# Psycho Key — Complete AI Agent Integration Library > Canonical Host: `https://psycho-key.com` > API Endpoint: `POST https://psycho-key.com/api/v1.php` > Health Check: `GET https://psycho-key.com/api/health.php` > Interactive Guide: `https://psycho-key.com/install-guide.php` > Direct File Downloads: `GET https://psycho-key.com/sdk-file.php?name=` This document gives AI coding agents everything required to integrate **Psycho Key** licensing, hardware ID locking, live session enforcement, remote cloud variables, and forced updates into ANY user application in one pass. --- ## AI Agent Autonomous Installation Playbook Follow these exact steps when the user asks you to integrate Psycho Key into their project: ### Step 1: Detect the Target Project Stack Inspect the repository root to identify the language, runtime, and entry point: - **C++ / Windows (`.vcxproj`, `CMakeLists.txt`, `.cpp`)**: Copy `sdk/psychokey.hpp` (Section 1 below). Link `winhttp.lib`, `bcrypt.lib`, `advapi32.lib`, `crypt32.lib`. Use C++17+. Wrap sensitive config strings in `PK_OBF("...")` provided inside `psychokey.hpp`. - **C# / .NET / Unity (`.csproj`, `.sln`, `Assets/`)**: Copy `sdk/PsychoKey.cs` (Section 3 below). Requires .NET 6+ (`System.Security.Cryptography.AesGcm`) or compatible runtime. Zero NuGet dependencies. - **Python (`pyproject.toml`, `requirements.txt`, `*.py`)**: Copy `sdk/psychokey.py` (Section 2 below). Add `cryptography` to dependencies (`pip install cryptography`). - **Node.js / TypeScript / Electron (`package.json`, `tsconfig.json`)**: Copy `sdk/psychokey.js` (+ `sdk/psychokey.d.ts` for TypeScript). Zero npm dependencies (Node 16+ built-in `crypto` + `https`). In Electron apps, run `PsychoKey` inside the **Main process** only (never expose `apiSecret` in renderer/browser bundles). - **Go (`go.mod`, `*.go`)**: Copy `sdk/psychokey.go` into `psychokey/psychokey.go`. Zero external Go dependencies. - **Rust (`Cargo.toml`, `src/main.rs`)**: Copy `sdk/psychokey.rs` and add the listed crates (`aes-gcm`, `hkdf`, `hmac`, `sha2`, `reqwest`, `serde`, `serde_json`, `hex`, `base64`, `rand`) to `Cargo.toml`. - **Java / Desktop / Android (`pom.xml`, `build.gradle`, `*.java`)**: Copy `sdk/PsychoKey.java`. Java 11+ stdlib only, zero external JARs. For Android, run network calls on a background thread (not Main/UI thread) and pass `Settings.Secure.ANDROID_ID` or stable device ID if needed. - **PHP / Web / Laravel / SaaS (`composer.json`, `*.php`)**: Copy `sdk/psychokey.php`. Requires PHP 8.1+ with `openssl` and `curl`. Pass a user/tenant/machine identifier (`[A-Za-z0-9:_-]{8,128}`) as `$hwid`. - **Other languages (Swift, Kotlin, Dart/Flutter, Ruby, Lua)**: Implement the **v2 Protocol Specification** below using the platform's standard `HKDF-SHA256`, `HMAC-SHA256`, and `AES-256-GCM` primitives. ### Step 2: Configure Product Credentials Safely Every product created in `https://psycho-key.com/panel/` has: - `base_url`: `"https://psycho-key.com"` - `app`: product slug (`^[a-z0-9][a-z0-9\-]{1,62}[a-z0-9]$`, e.g. `"my-app"`) - `api_secret`: 64 lowercase hex characters (32-byte shared secret) - `version`: client version string (e.g. `"1.0.0"`) **Security rules for Agents:** - Never invent or guess an `api_secret`. If not provided by the user or present in `.env` / config, read from environment variables (`PSYCHO_API_BASE`, `PSYCHO_APP_SLUG`, `PSYCHO_API_SECRET`, `PSYCHO_APP_VERSION`) or place a clear placeholder and instruct the user where to paste their secret from `https://psycho-key.com/panel/products.php`. - Never embed `api_secret` inside client-side browser JS, React/Vue frontends, or public Electron renderer code. Only put `api_secret` inside compiled/native binaries or trusted backend/main processes. ### Step 3: Wire the Mandatory Runtime Lifecycle 1. **Startup Handshake (`init()`)**: - Call `init()` before accepting a license key or launching protected features. - Check `res.code`: - `"OUTDATED_VERSION"`: Display `res.latest_version` and direct/open `res.download_url`, then exit. - `"MAINTENANCE"`: Display `res.message` to the user and exit gracefully. - `"PRODUCT_PAUSED"` / `"IP_BANNED"` / `"HWID_BANNED"`: Abort access with a clear error message. - Public Cloud Variables (`is_public = 1`) are already populated in `res.variables` / `client.var(...)`. 2. **License Activation (`auth(licenseKey)`)**: - Load any saved license key from secure local config or prompt the user via the app's existing CLI/GUI dialog. - Call `auth(key)`. - On failure: - `"INVALID_KEY"`, `"KEY_EXPIRED"`, `"KEY_REVOKED"`, `"KEY_BANNED"`: Show error and re-prompt / exit. - `"HWID_LIMIT"` or `"HWID_MISMATCH"`: Optionally prompt the user to call `reset_hwid(key)` (handles `"RESET_DISABLED"` and `"RESET_COOLDOWN"` with `retry_after` seconds). - On success: persist valid key locally (if appropriate for UX), read private Cloud Variables (`client.var("...")`), inspect `res.license.lifetime`, `days_left`, `seconds_left`. 3. **Background Heartbeat Loop (`heartbeat()`)**: - Run a periodic timer/background thread every **30 to 60 seconds** calling `heartbeat()`. - Remember: Each `heartbeat()` rotates the single-use `jti` session token atomically on the server. - Never run concurrent un-synchronized `heartbeat()` calls on the same `Client` instance with an old token; serialize calls or lock around the client instance. - If `!hb.ok` (especially `"SESSION_REVOKED"`, `"KEY_REVOKED"`, `"KEY_EXPIRED"`, `"MAINTENANCE"`, `"HWID_BANNED"`), **immediately stop protected functionality and exit**. 4. **Graceful Shutdown (`logout()`)**: - Register cleanup / exit handler to call `logout()` so the active session closes cleanly in the admin dashboard. ### Step 4: Verify Before Finishing - Run the project's compiler/typechecker/syntax check (`cl`/`cmake`, `dotnet build`, `python -m py_compile`, `node --check`/`tsc`, `go build`, `cargo check`, `javac`, `php -l`). - Optionally verify connectivity via `GET https://psycho-key.com/api/health.php` (`{"ok":true,"db":true}`). --- # Psycho Key API v2 `POST /api/v1.php` with `Content-Type: application/json`. Two layers on every call: 1. **Transport** — HTTPS only. The SDK can pin the server certificate. 2. **Application** — AES-256-GCM both directions + HMAC-SHA256 request signature. The product **API secret** (64 hex chars) is the shared key. --- ## v2 request envelope ```json { "app": "my-product", "v": 2, "iv": "base64 12-byte nonce", "ct": "base64 ciphertext", "tag": "base64 16-byte GCM tag" } ``` Request key: ``` reqKey = HKDF-SHA256(api_secret_bytes, salt = "psychokey-salt-v1", info = "psychokey-req-v2|" + app, len = 32) ``` AAD = `app` (ASCII). Plaintext is this JSON: ```json { "action": "init | license | heartbeat | logout | reset", "nonce": "16-64 lowercase hex, unique", "ts": 1764300000, "hwid": "8-128 chars [A-Za-z0-9:_-]", "license_key": "", "token": "", "version": "1.0.0", "sig": "lowercase hex HMAC-SHA256" } ``` Signature: ``` canonical = app + "|" + action + "|" + nonce + "|" + ts + "|" + hwid + "|" + license_key + "|" + token sig = hex(HMAC-SHA256(api_secret_bytes, canonical)) ``` Server rejects `ts` outside ±120s and any reused `nonce` (scoped per product). When `require_v2` is enabled (the default), legacy v1 requests are rejected with `V2_REQUIRED`. --- ## v2 response envelope ```json { "v": 2, "iv": "base64", "ct": "base64", "tag": "base64" } ``` Response key: ``` respKey = HKDF-SHA256(api_secret_bytes, salt = "psychokey-salt-v1", info = "psychokey-resp-v2|" + app, len = 32) ``` AAD = `app + "|" + action + "|" + client_nonce`. Plaintext payload: ```json { "success": true, "ts": 1764300001, "code": "OK", "message": "License activated.", "token": "…", "license": { "id": 42, "status": "active", "duration": 30, "duration_seconds": 0, "max_hwids": 1, "activated_at": "2026-11-28 12:00:00", "expires_at": "2026-12-28 12:00:00", "days_left": 30, "seconds_left": 2592000, "lifetime": false }, "variables": { "discord_invite": "https://discord.gg/..." } } ``` Pre-auth failures (`RATE_LIMITED`, `PRODUCT_NOT_FOUND`, `BAD_ENCRYPTION`, `BAD_SIGNATURE`, `REPLAY`, `V2_REQUIRED`, `IP_BANNED`) return plain JSON. Post-auth failures (`MAINTENANCE`, `OUTDATED_VERSION`, `INVALID_KEY`, `HWID_BANNED`, `SESSION_REVOKED`, etc.) return encrypted v2 payloads. --- ## Actions - **`init`**: Handshake; returns product name/version/download_url + public cloud variables (`is_public = 1`). - **`license`**: Validate key and bind HWID. Creates a tracked `client_sessions` record and returns a 1-hour token + all cloud variables. - **`heartbeat`**: Validates token, HWID, license status, and atomically rotates `jti` in `client_sessions`. Kicked/revoked sessions fail immediately with `SESSION_REVOKED`. - **`reset`**: Self-service HWID reset subject to `allow_hwid_reset` + cooldown; revokes prior active sessions. - **`logout`**: Revokes the current session `jti` on the server immediately. --- ## Error codes | Code | Meaning | |---|---| | `BAD_REQUEST` | Malformed JSON/fields | | `V2_REQUIRED` | Product blocks legacy v1 protocol | | `BAD_ENCRYPTION` | v2 request could not be decrypted/authenticated | | `BAD_SIGNATURE` | HMAC mismatch | | `CLOCK_SKEW` | `ts` outside ±120s | | `REPLAY` | Nonce reused | | `RATE_LIMITED` | >90 requests/min per IP (or >30 failed sigs/min) | | `IP_BANNED` / `HWID_BANNED` | Blacklisted IP or hardware fingerprint | | `MAINTENANCE` | Product is in maintenance mode | | `OUTDATED_VERSION` | Client version mismatch; check `latest_version` & `download_url` | | `PRODUCT_NOT_FOUND` / `PRODUCT_PAUSED` | Product missing or disabled | | `INVALID_KEY` | Unknown key or wrong product | | `KEY_EXPIRED` / `KEY_REVOKED` / `KEY_BANNED` | License unusable | | `HWID_LIMIT` | All HWID slots used | | `HWID_MISMATCH` | Token bound to another HWID | | `SESSION_REVOKED` | Session kicked by admin or superseded | | `RESET_DISABLED` | Self-reset disabled for this product | | `RESET_COOLDOWN` | Reset too soon; check `retry_after` | | `TOKEN_INVALID` / `TOKEN_EXPIRED` | Heartbeat token bad/expired | | `SERVER_ERROR` | Internal error | --- ## TLS pinning ```bash php tools/pin.php psycho-key.com ``` --- ## Webhooks Header `X-PsychoKey-Signature: sha256=`. Events: `license.created`, `license.activated`, `license.revoked`, `auth.failed`, `auth.success`, `webhook.test`. --- ## Complete Multi-Language SDK Implementations ### 1. C++ SDK (Windows 10+, WinHTTP + BCrypt, Single Header) - Filename: `sdk/psychokey.hpp` - Direct Download: `https://psycho-key.com/sdk-file.php?name=psychokey.hpp` ```cpp // Psycho Key — C++ client SDK (Windows, self-contained) // Requires: Windows 10+, winhttp.lib, bcrypt.lib, advapi32.lib // // Usage: // psycho::Client client({"https://key.example.com", "my-product", "", "1.0.0"}); // auto res = client.auth(userKey); // if (!res.ok) { /* deny access */ } // // The API secret is the per-product secret from the panel. Treat it like a // password inside your binary. Pair with VMProtect/Themida for deeper protection. #pragma once #ifndef PSYCHOKEY_HPP #define PSYCHOKEY_HPP #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef _MSC_VER #pragma comment(lib, "winhttp.lib") #pragma comment(lib, "bcrypt.lib") #pragma comment(lib, "advapi32.lib") #pragma comment(lib, "crypt32.lib") #endif namespace psycho { struct Config { std::string base_url; // https://psycho-key.com std::string app; // product slug std::string api_secret; // 64 hex chars std::string version; // client version (verified if enforce_version is on) std::string tls_pin; // optional SHA-256 of server certificate DER (hex) bool anti_debug = false; bool require_v2 = true; // reject legacy v1 CBC responses }; struct License { long long id = 0; std::string status; int duration_days = 0; int duration_seconds = 0; int max_hwids = 0; std::string activated_at; std::string expires_at; int days_left = -1; long long seconds_left = -1; bool lifetime = false; }; struct Result { bool ok = false; std::string code; std::string message; std::string token; int retry_after = 0; std::string latest_version; std::string download_url; std::map variables; License license; }; namespace detail { /* ----------------------------- SHA-256 ----------------------------- */ class Sha256 { public: Sha256() { reset(); } void update(const void* data, size_t len) { const uint8_t* p = static_cast(data); total_ += len; while (len > 0) { size_t take = 64 - buflen_; if (take > len) take = len; std::memcpy(buf_ + buflen_, p, take); buflen_ += take; p += take; len -= take; if (buflen_ == 64) { transform(buf_); buflen_ = 0; } } } void update(const std::string& s) { update(s.data(), s.size()); } std::vector final() { uint64_t bits = total_ * 8; uint8_t pad = 0x80; update(&pad, 1); uint8_t zero = 0; while (buflen_ != 56) update(&zero, 1); uint8_t lenbuf[8]; for (int i = 0; i < 8; i++) lenbuf[i] = static_cast(bits >> (56 - 8 * i)); update(lenbuf, 8); std::vector out(32); for (int i = 0; i < 8; i++) { out[i * 4 + 0] = static_cast(h_[i] >> 24); out[i * 4 + 1] = static_cast(h_[i] >> 16); out[i * 4 + 2] = static_cast(h_[i] >> 8); out[i * 4 + 3] = static_cast(h_[i]); } return out; } static std::string hex(const std::vector& v) { static const char* d = "0123456789abcdef"; std::string out; out.reserve(v.size() * 2); for (uint8_t b : v) { out.push_back(d[b >> 4]); out.push_back(d[b & 0xF]); } return out; } private: void reset() { h_[0] = 0x6a09e667; h_[1] = 0xbb67ae85; h_[2] = 0x3c6ef372; h_[3] = 0xa54ff53a; h_[4] = 0x510e527f; h_[5] = 0x9b05688c; h_[6] = 0x1f83d9ab; h_[7] = 0x5be0cd19; total_ = 0; buflen_ = 0; } static uint32_t rotr(uint32_t x, int n) { return (x >> n) | (x << (32 - n)); } void transform(const uint8_t* chunk) { static const uint32_t K[64] = { 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2 }; uint32_t w[64]; for (int i = 0; i < 16; i++) { w[i] = (uint32_t(chunk[i * 4]) << 24) | (uint32_t(chunk[i * 4 + 1]) << 16) | (uint32_t(chunk[i * 4 + 2]) << 8) | uint32_t(chunk[i * 4 + 3]); } for (int i = 16; i < 64; i++) { uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); w[i] = w[i - 16] + s0 + w[i - 7] + s1; } uint32_t a = h_[0], b = h_[1], c = h_[2], d = h_[3]; uint32_t e = h_[4], f = h_[5], g = h_[6], h = h_[7]; for (int i = 0; i < 64; i++) { uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25); uint32_t ch = (e & f) ^ (~e & g); uint32_t t1 = h + S1 + ch + K[i] + w[i]; uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22); uint32_t maj = (a & b) ^ (a & c) ^ (b & c); uint32_t t2 = S0 + maj; h = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; } h_[0] += a; h_[1] += b; h_[2] += c; h_[3] += d; h_[4] += e; h_[5] += f; h_[6] += g; h_[7] += h; } uint32_t h_[8]; uint64_t total_; uint8_t buf_[64]; size_t buflen_; }; inline std::vector sha256(const std::string& data) { Sha256 s; s.update(data); return s.final(); } inline std::string sha256_hex(const std::string& data) { return Sha256::hex(sha256(data)); } /* ----------------------------- HMAC ----------------------------- */ inline std::vector hmac_sha256(const std::vector& key, const std::string& msg) { std::vector k = key; if (k.size() > 64) k = sha256(std::string(k.begin(), k.end())); k.resize(64, 0); std::string inner; inner.reserve(64 + msg.size()); for (int i = 0; i < 64; i++) inner.push_back(static_cast(k[i] ^ 0x36)); inner += msg; std::vector innerHash = sha256(inner); std::string outer; outer.reserve(64 + 32); for (int i = 0; i < 64; i++) outer.push_back(static_cast(k[i] ^ 0x5c)); outer.append(reinterpret_cast(innerHash.data()), innerHash.size()); return sha256(outer); } inline std::string hmac_hex(const std::vector& key, const std::string& msg) { return Sha256::hex(hmac_sha256(key, msg)); } /* ----------------------------- HKDF ----------------------------- */ inline std::vector hkdf_sha256(const std::vector& ikm, const std::string& salt, const std::string& info, size_t length = 32) { std::vector saltVec(salt.begin(), salt.end()); std::vector prk = hmac_sha256(saltVec, std::string(ikm.begin(), ikm.end())); std::string t; std::vector out; uint8_t counter = 1; while (out.size() < length) { std::string block = t + info; block.push_back(static_cast(counter)); t = std::string(reinterpret_cast(hmac_sha256(prk, block).data()), 32); out.insert(out.end(), t.begin(), t.end()); counter++; } out.resize(length); return out; } /* ----------------------------- Base64 ----------------------------- */ inline std::string b64encode(const std::vector& data) { static const char* tbl = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::string out; size_t i = 0; while (i + 2 < data.size()) { uint32_t v = (data[i] << 16) | (data[i + 1] << 8) | data[i + 2]; out.push_back(tbl[(v >> 18) & 63]); out.push_back(tbl[(v >> 12) & 63]); out.push_back(tbl[(v >> 6) & 63]); out.push_back(tbl[v & 63]); i += 3; } if (i < data.size()) { uint32_t v = data[i] << 16; bool two = i + 1 < data.size(); if (two) v |= data[i + 1] << 8; out.push_back(tbl[(v >> 18) & 63]); out.push_back(tbl[(v >> 12) & 63]); out.push_back(two ? tbl[(v >> 6) & 63] : '='); out.push_back('='); } return out; } inline std::vector b64decode(const std::string& s) { auto val = [](char c) -> int { if (c >= 'A' && c <= 'Z') return c - 'A'; if (c >= 'a' && c <= 'z') return c - 'a' + 26; if (c >= '0' && c <= '9') return c - '0' + 52; if (c == '+' || c == '-') return 62; if (c == '/' || c == '_') return 63; return -1; }; std::vector out; int buffer = 0, bits = 0; for (char c : s) { if (c == '=') break; int v = val(c); if (v < 0) continue; buffer = (buffer << 6) | v; bits += 6; if (bits >= 8) { bits -= 8; out.push_back(static_cast((buffer >> bits) & 0xFF)); } } return out; } inline std::string hex_encode(const std::vector& v) { return Sha256::hex(v); } inline std::vector hex_decode(const std::string& s) { std::vector out; if (s.size() % 2) return out; auto nib = [](char c) -> int { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; }; for (size_t i = 0; i < s.size(); i += 2) { int hi = nib(s[i]), lo = nib(s[i + 1]); if (hi < 0 || lo < 0) return {}; out.push_back(static_cast((hi << 4) | lo)); } return out; } /* ----------------------------- AES-256-CBC ----------------------------- */ inline bool aes256cbc_decrypt(const std::vector& key, const std::vector& iv, const std::vector& ciphertext, std::vector& out) { if (key.size() != 32 || iv.size() != 16 || ciphertext.empty() || ciphertext.size() % 16 != 0) { return false; } BCRYPT_ALG_HANDLE alg = nullptr; BCRYPT_KEY_HANDLE keyHandle = nullptr; bool ok = false; if (BCryptOpenAlgorithmProvider(&alg, BCRYPT_AES_ALGORITHM, nullptr, 0) != 0) { return false; } BCryptSetProperty(alg, BCRYPT_CHAINING_MODE, reinterpret_cast(const_cast(BCRYPT_CHAIN_MODE_CBC)), sizeof(BCRYPT_CHAIN_MODE_CBC), 0); DWORD objectLength = 0, result = 0; BCryptGetProperty(alg, BCRYPT_OBJECT_LENGTH, reinterpret_cast(&objectLength), sizeof(objectLength), &result, 0); std::vector keyObject(objectLength); if (BCryptGenerateSymmetricKey(alg, &keyHandle, keyObject.data(), objectLength, const_cast(key.data()), static_cast(key.size()), 0) == 0) { std::vector buffer(ciphertext.size() + 16); ULONG written = 0; if (BCryptDecrypt(keyHandle, const_cast(ciphertext.data()), static_cast(ciphertext.size()), nullptr, const_cast(iv.data()), static_cast(iv.size()), buffer.data(), static_cast(buffer.size()), &written, BCRYPT_BLOCK_PADDING) == 0) { buffer.resize(written); out = std::move(buffer); ok = true; } } if (keyHandle) BCryptDestroyKey(keyHandle); BCryptCloseAlgorithmProvider(alg, 0); return ok; } /* ----------------------------- AES-256-GCM ----------------------------- */ inline bool aes256gcm_encrypt(const std::vector& key, const std::vector& iv, const std::string& plaintext, const std::string& aad, std::vector& ciphertext, std::vector& tag) { if (key.size() != 32 || iv.size() != 12) return false; BCRYPT_ALG_HANDLE alg = nullptr; BCRYPT_KEY_HANDLE keyHandle = nullptr; bool ok = false; if (BCryptOpenAlgorithmProvider(&alg, BCRYPT_AES_ALGORITHM, nullptr, 0) != 0) { return false; } BCryptSetProperty(alg, BCRYPT_CHAINING_MODE, reinterpret_cast(const_cast(BCRYPT_CHAIN_MODE_GCM)), sizeof(BCRYPT_CHAIN_MODE_GCM), 0); DWORD objectLength = 0, result = 0; BCryptGetProperty(alg, BCRYPT_OBJECT_LENGTH, reinterpret_cast(&objectLength), sizeof(objectLength), &result, 0); std::vector keyObject(objectLength); if (BCryptGenerateSymmetricKey(alg, &keyHandle, keyObject.data(), objectLength, const_cast(key.data()), static_cast(key.size()), 0) == 0) { ciphertext.resize(plaintext.size()); tag.resize(16); BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info; BCRYPT_INIT_AUTH_MODE_INFO(info); info.pbNonce = const_cast(iv.data()); info.cbNonce = static_cast(iv.size()); info.pbAuthData = aad.empty() ? nullptr : const_cast(reinterpret_cast(aad.data())); info.cbAuthData = static_cast(aad.size()); info.pbTag = tag.data(); info.cbTag = static_cast(tag.size()); ULONG written = 0; if (BCryptEncrypt(keyHandle, const_cast(reinterpret_cast(plaintext.data())), static_cast(plaintext.size()), &info, nullptr, 0, ciphertext.data(), static_cast(ciphertext.size()), &written, 0) == 0) { ciphertext.resize(written); ok = true; } } if (keyHandle) BCryptDestroyKey(keyHandle); BCryptCloseAlgorithmProvider(alg, 0); return ok; } inline bool aes256gcm_decrypt(const std::vector& key, const std::vector& iv, const std::vector& ciphertext, const std::vector& tag, const std::string& aad, std::vector& out) { if (key.size() != 32 || iv.size() != 12 || tag.size() != 16) return false; BCRYPT_ALG_HANDLE alg = nullptr; BCRYPT_KEY_HANDLE keyHandle = nullptr; bool ok = false; if (BCryptOpenAlgorithmProvider(&alg, BCRYPT_AES_ALGORITHM, nullptr, 0) != 0) { return false; } BCryptSetProperty(alg, BCRYPT_CHAINING_MODE, reinterpret_cast(const_cast(BCRYPT_CHAIN_MODE_GCM)), sizeof(BCRYPT_CHAIN_MODE_GCM), 0); DWORD objectLength = 0, result = 0; BCryptGetProperty(alg, BCRYPT_OBJECT_LENGTH, reinterpret_cast(&objectLength), sizeof(objectLength), &result, 0); std::vector keyObject(objectLength); if (BCryptGenerateSymmetricKey(alg, &keyHandle, keyObject.data(), objectLength, const_cast(key.data()), static_cast(key.size()), 0) == 0) { out.resize(ciphertext.size()); BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info; BCRYPT_INIT_AUTH_MODE_INFO(info); info.pbNonce = const_cast(iv.data()); info.cbNonce = static_cast(iv.size()); info.pbAuthData = aad.empty() ? nullptr : const_cast(reinterpret_cast(aad.data())); info.cbAuthData = static_cast(aad.size()); info.pbTag = const_cast(tag.data()); info.cbTag = static_cast(tag.size()); ULONG written = 0; if (BCryptDecrypt(keyHandle, const_cast(ciphertext.data()), static_cast(ciphertext.size()), &info, nullptr, 0, out.data(), static_cast(out.size()), &written, 0) == 0) { out.resize(written); ok = true; } } if (keyHandle) BCryptDestroyKey(keyHandle); BCryptCloseAlgorithmProvider(alg, 0); return ok; } /* ----------------------------- random ----------------------------- */ inline std::vector random_bytes(size_t count) { std::vector buf(count); if (BCryptGenRandom(nullptr, buf.data(), static_cast(buf.size()), BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0) { for (auto& b : buf) b = static_cast(rand() & 0xFF); } return buf; } inline std::string random_hex(size_t bytes) { return hex_encode(random_bytes(bytes)); } /* ----------------------------- JSON ----------------------------- */ struct Json { enum class Type { Null, Bool, Number, String, Array, Object }; Type type = Type::Null; bool boolean = false; double number = 0; std::string text; std::vector array; std::map object; const Json* get(const std::string& key) const { auto it = object.find(key); return it == object.end() ? nullptr : &it->second; } std::string str(const std::string& key, const std::string& def = "") const { const Json* v = get(key); return (v && v->type == Type::String) ? v->text : def; } double num(const std::string& key, double def = 0) const { const Json* v = get(key); return (v && v->type == Type::Number) ? v->number : def; } bool flag(const std::string& key, bool def = false) const { const Json* v = get(key); return (v && v->type == Type::Bool) ? v->boolean : def; } bool has(const std::string& key) const { return object.count(key) > 0; } }; class JsonParser { public: explicit JsonParser(const std::string& s) : s_(s) {} bool parse(Json& out) { skip(); if (!parse_value(out)) return false; skip(); return pos_ == s_.size(); } private: void skip() { while (pos_ < s_.size()) { char c = s_[pos_]; if (c == ' ' || c == '\t' || c == '\n' || c == '\r') pos_++; else break; } } bool parse_value(Json& out) { skip(); if (pos_ >= s_.size()) return false; char c = s_[pos_]; if (c == '{') return parse_object(out); if (c == '[') return parse_array(out); if (c == '"') { out.type = Json::Type::String; return parse_string(out.text); } if (c == 't') { if (s_.compare(pos_, 4, "true") == 0) { pos_ += 4; out.type = Json::Type::Bool; out.boolean = true; return true; } return false; } if (c == 'f') { if (s_.compare(pos_, 5, "false") == 0) { pos_ += 5; out.type = Json::Type::Bool; out.boolean = false; return true; } return false; } if (c == 'n') { if (s_.compare(pos_, 4, "null") == 0) { pos_ += 4; out.type = Json::Type::Null; return true; } return false; } return parse_number(out); } bool parse_object(Json& out) { out.type = Json::Type::Object; pos_++; // { skip(); if (pos_ < s_.size() && s_[pos_] == '}') { pos_++; return true; } while (pos_ < s_.size()) { skip(); std::string key; if (!parse_string(key)) return false; skip(); if (pos_ >= s_.size() || s_[pos_] != ':') return false; pos_++; Json value; if (!parse_value(value)) return false; out.object[key] = std::move(value); skip(); if (pos_ >= s_.size()) return false; if (s_[pos_] == ',') { pos_++; continue; } if (s_[pos_] == '}') { pos_++; return true; } return false; } return false; } bool parse_array(Json& out) { out.type = Json::Type::Array; pos_++; // [ skip(); if (pos_ < s_.size() && s_[pos_] == ']') { pos_++; return true; } while (pos_ < s_.size()) { Json value; if (!parse_value(value)) return false; out.array.push_back(std::move(value)); skip(); if (pos_ >= s_.size()) return false; if (s_[pos_] == ',') { pos_++; continue; } if (s_[pos_] == ']') { pos_++; return true; } return false; } return false; } bool parse_string(std::string& out) { if (pos_ >= s_.size() || s_[pos_] != '"') return false; pos_++; out.clear(); while (pos_ < s_.size()) { unsigned char c = static_cast(s_[pos_++]); if (c == '"') return true; if (c == '\\') { if (pos_ >= s_.size()) return false; char e = s_[pos_++]; switch (e) { case '"': out.push_back('"'); break; case '\\': out.push_back('\\'); break; case '/': out.push_back('/'); break; case 'b': out.push_back('\b'); break; case 'f': out.push_back('\f'); break; case 'n': out.push_back('\n'); break; case 'r': out.push_back('\r'); break; case 't': out.push_back('\t'); break; case 'u': { if (pos_ + 4 > s_.size()) return false; unsigned cp = std::stoul(s_.substr(pos_, 4), nullptr, 16); pos_ += 4; if (cp >= 0xD800 && cp <= 0xDBFF && pos_ + 6 <= s_.size() && s_[pos_] == '\\' && s_[pos_ + 1] == 'u') { unsigned low = std::stoul(s_.substr(pos_ + 2, 4), nullptr, 16); pos_ += 6; cp = 0x10000 + ((cp - 0xD800) << 10) + (low - 0xDC00); } if (cp <= 0x7F) out.push_back(static_cast(cp)); else if (cp <= 0x7FF) { out.push_back(static_cast(0xC0 | (cp >> 6))); out.push_back(static_cast(0x80 | (cp & 0x3F))); } else if (cp <= 0xFFFF) { out.push_back(static_cast(0xE0 | (cp >> 12))); out.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); out.push_back(static_cast(0x80 | (cp & 0x3F))); } else { out.push_back(static_cast(0xF0 | (cp >> 18))); out.push_back(static_cast(0x80 | ((cp >> 12) & 0x3F))); out.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); out.push_back(static_cast(0x80 | (cp & 0x3F))); } break; } default: return false; } } else { out.push_back(static_cast(c)); } } return false; } bool parse_number(Json& out) { size_t start = pos_; if (pos_ < s_.size() && (s_[pos_] == '-' || s_[pos_] == '+')) pos_++; while (pos_ < s_.size() && ((s_[pos_] >= '0' && s_[pos_] <= '9') || s_[pos_] == '.' || s_[pos_] == 'e' || s_[pos_] == 'E' || s_[pos_] == '-' || s_[pos_] == '+')) { pos_++; } if (start == pos_) return false; try { out.type = Json::Type::Number; out.number = std::stod(s_.substr(start, pos_ - start)); return true; } catch (...) { return false; } } const std::string& s_; size_t pos_ = 0; }; inline std::string json_escape(const std::string& in) { std::string out; out.reserve(in.size() + 8); for (unsigned char c : in) { switch (c) { case '"': out += "\\\""; break; case '\\': out += "\\\\"; break; case '\b': out += "\\b"; break; case '\f': out += "\\f"; break; case '\n': out += "\\n"; break; case '\r': out += "\\r"; break; case '\t': out += "\\t"; break; default: if (c < 0x20) { char buf[8]; std::snprintf(buf, sizeof(buf), "\\u%04x", c); out += buf; } else { out.push_back(static_cast(c)); } } } return out; } /* ----------------------------- WinHTTP ----------------------------- */ inline std::wstring utf8_to_wide(const std::string& s) { if (s.empty()) return L""; int len = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), static_cast(s.size()), nullptr, 0); std::wstring out(len, L'\0'); MultiByteToWideChar(CP_UTF8, 0, s.c_str(), static_cast(s.size()), out.data(), len); return out; } inline std::string wide_to_utf8(const std::wstring& s) { if (s.empty()) return ""; int len = WideCharToMultiByte(CP_UTF8, 0, s.c_str(), static_cast(s.size()), nullptr, 0, nullptr, nullptr); std::string out(len, '\0'); WideCharToMultiByte(CP_UTF8, 0, s.c_str(), static_cast(s.size()), out.data(), len, nullptr, nullptr); return out; } struct HttpResponse { bool transportOk = false; int status = 0; std::string body; }; inline HttpResponse http_post(const std::string& url, const std::string& body, const std::string& tlsPin) { HttpResponse result; std::wstring wurl = utf8_to_wide(url); URL_COMPONENTS uc{}; uc.dwStructSize = sizeof(uc); wchar_t host[512] = {}; wchar_t path[4096] = {}; uc.lpszHostName = host; uc.dwHostNameLength = 512; uc.lpszUrlPath = path; uc.dwUrlPathLength = 4096; if (!WinHttpCrackUrl(wurl.c_str(), 0, 0, &uc)) { return result; } bool secure = uc.nScheme == INTERNET_SCHEME_HTTPS; HINTERNET session = WinHttpOpen(L"PsychoKey/1.0", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!session) return result; WinHttpSetTimeouts(session, 5000, 5000, 5000, 10000); DWORD secureProtocols = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2; #ifdef WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3 secureProtocols |= WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3; #endif WinHttpSetOption(session, WINHTTP_OPTION_SECURE_PROTOCOLS, &secureProtocols, sizeof(secureProtocols)); HINTERNET connection = WinHttpConnect(session, host, uc.nPort, 0); if (!connection) { WinHttpCloseHandle(session); return result; } std::wstring target = path[0] ? std::wstring(path) : L"/"; HINTERNET request = WinHttpOpenRequest(connection, L"POST", target.c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, secure ? WINHTTP_FLAG_SECURE : 0); if (!request) { WinHttpCloseHandle(connection); WinHttpCloseHandle(session); return result; } const wchar_t* headers = L"Content-Type: application/json\r\n"; BOOL sent = WinHttpSendRequest(request, headers, static_cast(-1), const_cast(body.data()), static_cast(body.size()), static_cast(body.size()), 0); if (sent && WinHttpReceiveResponse(request, nullptr)) { bool pinOk = true; if (!tlsPin.empty()) { CERT_CONTEXT* cert = nullptr; DWORD certSize = sizeof(cert); if (WinHttpQueryOption(request, WINHTTP_OPTION_SERVER_CERT_CONTEXT, &cert, &certSize) && cert) { std::string der(reinterpret_cast(cert->pbCertEncoded), cert->cbCertEncoded); std::string actual = Sha256::hex(sha256(der)); CertFreeCertificateContext(cert); std::string expected; expected.reserve(tlsPin.size()); for (char c : tlsPin) { if (c != ':' && c != ' ') expected.push_back(static_cast(std::tolower(static_cast(c)))); } pinOk = expected == actual; } else { pinOk = false; } } if (!pinOk) { result.status = -1; WinHttpCloseHandle(request); WinHttpCloseHandle(connection); WinHttpCloseHandle(session); return result; } DWORD statusCode = 0, size = sizeof(statusCode); WinHttpQueryHeaders(request, WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &size, WINHTTP_NO_HEADER_INDEX); result.status = static_cast(statusCode); DWORD available = 0; do { available = 0; if (!WinHttpQueryDataAvailable(request, &available) || available == 0) break; std::vector buffer(available); DWORD read = 0; if (!WinHttpReadData(request, buffer.data(), available, &read)) break; result.body.append(buffer.data(), read); } while (available > 0); result.transportOk = true; } WinHttpCloseHandle(request); WinHttpCloseHandle(connection); WinHttpCloseHandle(session); return result; } /* ----------------------------- HWID ----------------------------- */ inline std::string wide_reg_value(HKEY root, const wchar_t* subkey, const wchar_t* name) { HKEY key = nullptr; if (RegOpenKeyExW(root, subkey, 0, KEY_READ | KEY_WOW64_64KEY, &key) != ERROR_SUCCESS) { return ""; } wchar_t buffer[512] = {}; DWORD size = sizeof(buffer); DWORD type = 0; std::string out; if (RegQueryValueExW(key, name, nullptr, &type, reinterpret_cast(buffer), &size) == ERROR_SUCCESS && (type == REG_SZ || type == REG_EXPAND_SZ)) { out = wide_to_utf8(buffer); } RegCloseKey(key); return out; } inline std::string smbios_system_uuid(); inline std::string smbios_baseboard_serial(); inline std::string disk_serial(); inline std::string cpu_fingerprint(); inline std::string compute_hwid() { std::string uuid = smbios_system_uuid(); std::string board = smbios_baseboard_serial(); std::string disk = disk_serial(); std::string cpu = cpu_fingerprint(); std::string material; material += "uuid=" + uuid; material += "|board=" + board; material += "|disk=" + disk; material += "|cpu=" + cpu; // Hardware signals survive OS reinstall / format. If none are readable // (locked-down VM, restricted permissions), fall back to OS identifiers. if (uuid.empty() && board.empty() && disk.empty()) { std::string machineGuid = wide_reg_value(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Cryptography", L"MachineGuid"); wchar_t volumeName[256] = {}; DWORD volumeSerial = 0; GetVolumeInformationW(L"C:\\", volumeName, 256, &volumeSerial, nullptr, nullptr, nullptr, 0); char serialHex[16]; std::snprintf(serialHex, sizeof(serialHex), "%08lX", static_cast(volumeSerial)); material += "|guid=" + machineGuid; material += "|vol=" + std::string(serialHex); } return sha256_hex(material); } /* ----------------------------- Hardware fingerprint parts ----------------------------- */ inline std::string smbios_string(const uint8_t* structure, uint8_t length, uint8_t index) { if (index == 0) return ""; const uint8_t* p = structure + length; uint8_t current = 1; for (int guard = 0; guard < 64; guard++) { if (*p == 0) return ""; std::string s(reinterpret_cast(p)); if (current == index) return s; p += s.size() + 1; current++; } return ""; } inline constexpr DWORD firmware_signature() { return static_cast('R') | (static_cast('S') << 8) | (static_cast('M') << 16) | (static_cast('B') << 24); } inline const uint8_t* smbios_table(std::vector& buffer, uint32_t& tableLength) { tableLength = 0; DWORD size = GetSystemFirmwareTable(firmware_signature(), 0, nullptr, 0); if (size < 8) return nullptr; buffer.resize(size); if (!GetSystemFirmwareTable(firmware_signature(), 0, buffer.data(), size)) return nullptr; tableLength = *reinterpret_cast(buffer.data() + 4); if (tableLength == 0 || tableLength > buffer.size() - 8) return nullptr; return buffer.data() + 8; } inline std::string smbios_system_uuid() { std::vector buffer; uint32_t length = 0; const uint8_t* table = smbios_table(buffer, length); if (!table) return ""; const uint8_t* end = table + length; const uint8_t* p = table; while (p + 4 <= end) { uint8_t type = p[0]; uint8_t len = p[1]; if (len < 4) break; if (type == 1 && len >= 0x19) { const uint8_t* u = p + 8; char out[40]; std::snprintf(out, sizeof(out), "%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X", u[3], u[2], u[1], u[0], u[5], u[4], u[7], u[6], u[8], u[9], u[10], u[11], u[12], u[13], u[14], u[15]); return out; } const uint8_t* q = p + len; if (q + 2 > end) break; while (q + 1 < end && !(q[0] == 0 && q[1] == 0)) q++; p = q + 2; } return ""; } inline std::string smbios_baseboard_serial() { std::vector buffer; uint32_t length = 0; const uint8_t* table = smbios_table(buffer, length); if (!table) return ""; const uint8_t* end = table + length; const uint8_t* p = table; while (p + 4 <= end) { uint8_t type = p[0]; uint8_t len = p[1]; if (len < 4) break; if (type == 2 && len >= 8) { return smbios_string(p, len, p[7]); } const uint8_t* q = p + len; if (q + 2 > end) break; while (q + 1 < end && !(q[0] == 0 && q[1] == 0)) q++; p = q + 2; } return ""; } inline std::string disk_serial() { HANDLE handle = CreateFileW(L"\\\\.\\PhysicalDrive0", 0, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr); if (handle == INVALID_HANDLE_VALUE) return ""; STORAGE_PROPERTY_QUERY query{}; query.PropertyId = StorageDeviceProperty; query.QueryType = PropertyStandardQuery; std::vector output(4096); DWORD returned = 0; std::string serial; if (DeviceIoControl(handle, IOCTL_STORAGE_QUERY_PROPERTY, &query, sizeof(query), output.data(), static_cast(output.size()), &returned, nullptr)) { auto* descriptor = reinterpret_cast(output.data()); if (descriptor->SerialNumberOffset > 0 && descriptor->SerialNumberOffset < returned && descriptor->SerialNumberOffset < output.size()) { serial = reinterpret_cast(output.data() + descriptor->SerialNumberOffset); while (!serial.empty() && (serial.back() == ' ' || serial.back() == '\0')) serial.pop_back(); } } CloseHandle(handle); return serial; } inline std::string cpu_fingerprint() { int regs[4] = {}; __cpuid(regs, 0); char vendor[13] = {}; std::memcpy(vendor, ®s[1], 4); std::memcpy(vendor + 4, ®s[3], 4); std::memcpy(vendor + 8, ®s[2], 4); char brand[49] = {}; for (int i = 0; i < 3; i++) { __cpuid(regs, 0x80000002 + i); std::memcpy(brand + i * 16, regs, 16); } __cpuid(regs, 1); char signature[16]; std::snprintf(signature, sizeof(signature), "%08X", static_cast(regs[0])); return std::string(vendor) + "|" + brand + "|" + signature; } } // namespace detail /* ----------------------------- anti-debug ----------------------------- */ namespace security { inline bool debugger_detected() { if (IsDebuggerPresent()) { return true; } BOOL remote = FALSE; if (CheckRemoteDebuggerPresent(GetCurrentProcess(), &remote) && remote) { return true; } using NtQueryInformationProcessFn = LONG (NTAPI*)(HANDLE, ULONG, PVOID, ULONG, PULONG); HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); if (ntdll) { auto query = reinterpret_cast( reinterpret_cast(GetProcAddress(ntdll, "NtQueryInformationProcess"))); if (query) { ULONG_PTR debugPort = 0; ULONG returned = 0; if (query(GetCurrentProcess(), 7, &debugPort, sizeof(debugPort), &returned) == 0 && debugPort != 0) { return true; } ULONG flags = 0; if (query(GetCurrentProcess(), 0x1F, &flags, sizeof(flags), &returned) == 0 && (flags & 1)) { return true; } HANDLE debugObject = nullptr; if (query(GetCurrentProcess(), 0x1E, &debugObject, sizeof(debugObject), &returned) == 0 && debugObject != nullptr) { return true; } } } return false; } inline void guard() { if (debugger_detected()) { ExitProcess(0); } } } // namespace security /* ----------------------------- string obfuscation ----------------------------- */ namespace detail { template class ObfString { public: constexpr ObfString(const char (&s)[N]) : data_{} { for (size_t i = 0; i < N; ++i) { data_[i] = static_cast(static_cast(s[i]) ^ key(i)); } } std::string decode() const { std::string out(N > 0 ? N - 1 : 0, '\0'); for (size_t i = 0; i + 1 < N; ++i) { out[i] = static_cast(static_cast(data_[i]) ^ key(i)); } return out; } private: static constexpr uint8_t key(size_t i) { return static_cast( ((Seed >> ((i % 4) * 8)) & 0xFF) ^ static_cast((i * 131u + 77u) & 0xFF) ); } char data_[N]; }; } // namespace detail // PK_OBF("literal") — compile-time obfuscated string, decoded at runtime. #define PK_OBF(s) (::psycho::detail::ObfString(__LINE__ * 2654435761u)>(s).decode()) /* ----------------------------- Client ----------------------------- */ class Client { public: explicit Client(Config config) : config_(std::move(config)), hwid_(detail::compute_hwid()) { while (!config_.base_url.empty() && config_.base_url.back() == '/') { config_.base_url.pop_back(); } } Result init() { Result res = request("init", ""); if (res.ok) { for (const auto& kv : res.variables) vars_[kv.first] = kv.second; } return res; } Result auth(const std::string& license_key) { Result res = request("license", license_key); if (res.ok && !res.token.empty()) { token_ = res.token; for (const auto& kv : res.variables) vars_[kv.first] = kv.second; } else { token_.clear(); } return res; } Result heartbeat() { Result res = request("heartbeat", ""); if (res.ok && !res.token.empty()) { token_ = res.token; for (const auto& kv : res.variables) vars_[kv.first] = kv.second; } else if (!res.ok) { token_.clear(); } return res; } void logout() { if (!token_.empty()) { request("logout", ""); } token_.clear(); vars_.clear(); } // Self-service HWID reset (after format / hardware change). // Subject to the product's allow_hwid_reset + cooldown policy. Result reset_hwid(const std::string& license_key) { Result res = request("reset", license_key); if (res.ok && !res.token.empty()) { token_ = res.token; for (const auto& kv : res.variables) vars_[kv.first] = kv.second; } return res; } bool authenticated() const { return !token_.empty(); } const std::string& hwid() const { return hwid_; } const std::string& token() const { return token_; } const Config& config() const { return config_; } std::string var(const std::string& key, const std::string& def = "") const { auto it = vars_.find(key); return it == vars_.end() ? def : it->second; } private: Result request(const std::string& action, const std::string& license_key) { Result out; if (config_.anti_debug && security::debugger_detected()) { out.code = "DEBUGGER"; out.message = "A debugger was detected."; return out; } const bool isLocal = config_.base_url.rfind("http://127.0.0.1", 0) == 0 || config_.base_url.rfind("http://localhost", 0) == 0; if (config_.base_url.rfind("https://", 0) != 0 && !isLocal) { out.code = "HTTPS_REQUIRED"; out.message = "Refusing to send credentials over plain HTTP."; return out; } std::vector secret = detail::hex_decode(config_.api_secret); if (secret.size() != 32 || config_.app.empty()) { out.code = "CLIENT_CONFIG"; out.message = "Invalid product secret (64 hex chars) or app slug."; return out; } std::string nonce = detail::random_hex(16); long long ts = static_cast(std::time(nullptr)); std::string canonical = config_.app + "|" + action + "|" + nonce + "|" + std::to_string(ts) + "|" + hwid_ + "|" + license_key + "|" + token_; std::string signature = detail::hmac_hex(secret, canonical); std::string inner; inner.reserve(512); inner += "{\"action\":\"" + detail::json_escape(action) + "\""; inner += ",\"nonce\":\"" + nonce + "\""; inner += ",\"ts\":" + std::to_string(ts); inner += ",\"hwid\":\"" + detail::json_escape(hwid_) + "\""; inner += ",\"license_key\":\"" + detail::json_escape(license_key) + "\""; inner += ",\"token\":\"" + detail::json_escape(token_) + "\""; inner += ",\"version\":\"" + detail::json_escape(config_.version) + "\""; inner += ",\"sig\":\"" + signature + "\"}"; std::vector reqKey = detail::hkdf_sha256(secret, "psychokey-salt-v1", "psychokey-req-v2|" + config_.app, 32); std::vector reqIv = detail::random_bytes(12); std::vector reqCt, reqTag; if (!detail::aes256gcm_encrypt(reqKey, reqIv, inner, config_.app, reqCt, reqTag)) { out.code = "CLIENT_CRYPTO"; out.message = "Request encryption failed."; return out; } std::string body; body.reserve(512); body += "{\"app\":\"" + detail::json_escape(config_.app) + "\""; body += ",\"v\":2"; body += ",\"iv\":\"" + detail::b64encode(reqIv) + "\""; body += ",\"ct\":\"" + detail::b64encode(reqCt) + "\""; body += ",\"tag\":\"" + detail::b64encode(reqTag) + "\"}"; detail::HttpResponse http = detail::http_post(config_.base_url + "/api/v1.php", body, config_.tls_pin); if (!http.transportOk) { out.code = "NETWORK"; out.message = "Could not reach the license server."; return out; } detail::Json root; detail::JsonParser parser(http.body); if (!parser.parse(root)) { out.code = "CLIENT_PARSE"; out.message = "Malformed server response."; return out; } detail::Json payload; bool encrypted = false; if (static_cast(root.num("v", 0)) == 2) { encrypted = true; std::vector iv = detail::b64decode(root.str("iv")); std::vector ciphertext = detail::b64decode(root.str("ct")); std::vector tag = detail::b64decode(root.str("tag")); std::vector respKey = detail::hkdf_sha256(secret, "psychokey-salt-v1", "psychokey-resp-v2|" + config_.app, 32); std::string aad = config_.app + "|" + action + "|" + nonce; std::vector plain; if (!detail::aes256gcm_decrypt(respKey, iv, ciphertext, tag, aad, plain)) { out.code = "CLIENT_INTEGRITY"; out.message = "Response authentication failed."; return out; } std::string plainText(plain.begin(), plain.end()); detail::JsonParser innerParser(plainText); if (!innerParser.parse(payload)) { out.code = "CLIENT_PARSE"; out.message = "Malformed decrypted payload."; return out; } } else if (!config_.require_v2 && root.has("ct") && root.has("iv") && root.has("tag")) { encrypted = true; // Legacy v1 response support (only when require_v2 = false). std::vector iv = detail::b64decode(root.str("iv")); std::vector ciphertext = detail::b64decode(root.str("ct")); std::vector tag = detail::b64decode(root.str("tag")); std::vector encKey = detail::hkdf_sha256(secret, "psychokey-salt-v1", "psychokey-enc-v1|" + config_.app, 32); std::vector macKey = detail::hkdf_sha256(secret, "psychokey-salt-v1", "psychokey-mac-v1|" + config_.app, 32); std::string signedData(reinterpret_cast(iv.data()), iv.size()); signedData.append(reinterpret_cast(ciphertext.data()), ciphertext.size()); std::vector expected = detail::hmac_sha256(macKey, signedData); bool tagMatch = expected.size() == tag.size(); if (tagMatch) { unsigned char diff = 0; for (size_t i = 0; i < tag.size(); i++) { diff |= static_cast(expected[i] ^ tag[i]); } tagMatch = diff == 0; } if (!tagMatch) { out.code = "CLIENT_INTEGRITY"; out.message = "Response signature mismatch."; return out; } std::vector plain; if (!detail::aes256cbc_decrypt(encKey, iv, ciphertext, plain)) { out.code = "CLIENT_DECRYPT"; out.message = "Could not decrypt response."; return out; } std::string plainText(plain.begin(), plain.end()); detail::JsonParser innerParser(plainText); if (!innerParser.parse(payload)) { out.code = "CLIENT_PARSE"; out.message = "Malformed decrypted payload."; return out; } } else { // Failures may be plain JSON, but an unencrypted success response is // never trusted: it would allow a network attacker to strip crypto. if (root.flag("success", false)) { out.code = "CLIENT_INTEGRITY"; out.message = "Unencrypted success response rejected."; return out; } payload = root; } if (encrypted) { double respTs = payload.num("ts", 0); if (respTs > 0 && std::abs(respTs - static_cast(ts)) > 300.0) { out.code = "CLIENT_INTEGRITY"; out.message = "Response timestamp outside allowed window."; return out; } } out.ok = payload.flag("success", false); out.code = payload.str("code", out.ok ? "OK" : "ERROR"); out.message = payload.str("message", ""); out.retry_after = static_cast(payload.num("retry_after", 0)); out.latest_version = payload.str("latest_version", ""); out.download_url = payload.str("download_url", ""); const detail::Json* vars = payload.get("variables"); if (vars && vars->type == detail::Json::Type::Object) { for (const auto& kv : vars->object) { if (kv.second.type == detail::Json::Type::String) { out.variables[kv.first] = kv.second.text; } } } if (out.ok) { out.token = payload.str("token", ""); const detail::Json* lic = payload.get("license"); if (lic && lic->type == detail::Json::Type::Object) { out.license.id = static_cast(lic->num("id", 0)); out.license.status = lic->str("status"); out.license.duration_days = static_cast(lic->num("duration", 0)); out.license.duration_seconds = static_cast(lic->num("duration_seconds", 0)); out.license.max_hwids = static_cast(lic->num("max_hwids", 0)); out.license.activated_at = lic->str("activated_at"); out.license.expires_at = lic->str("expires_at"); out.license.days_left = static_cast(lic->num("days_left", -1)); out.license.seconds_left = static_cast(lic->num("seconds_left", -1)); out.license.lifetime = lic->flag("lifetime", false); } } return out; } Config config_; std::string hwid_; std::string token_; std::map vars_; }; } // namespace psycho #endif // PSYCHOKEY_HPP ``` ### 2. C++ Example - Filename: `sdk/example.cpp` - Direct Download: `https://psycho-key.com/sdk-file.php?name=example.cpp` ```cpp // Psycho Key SDK — example integration // Build: see CMakeLists.txt or: // cl example.cpp /std:c++17 /EHsc /link winhttp.lib bcrypt.lib advapi32.lib crypt32.lib #include "psychokey.hpp" #include #include #include #include // Strings are obfuscated at compile time and decoded at runtime. // Replace with your product values from the panel. static const std::string API_BASE = PK_OBF("https://psycho-key.com"); static const std::string APP_SLUG = PK_OBF("psycho-key"); static const std::string API_SECRET = PK_OBF("REPLACE_WITH_64_HEX_PRODUCT_SECRET"); static const std::string APP_VERSION = PK_OBF("1.0.0"); // Optional: SHA-256 of your server certificate DER (hex). Empty = off. // Generate with: php tools/pin.php psycho-key.com static const std::string TLS_PIN = PK_OBF(""); int main() { psycho::Client client({API_BASE, APP_SLUG, API_SECRET, APP_VERSION, TLS_PIN, /*anti_debug=*/true, /*require_v2=*/true}); std::cout << "Psycho Key demo\n"; std::cout << "HWID: " << client.hwid() << "\n\n"; auto handshake = client.init(); if (!handshake.ok) { std::cout << "Handshake failed: " << handshake.code << " — " << handshake.message << "\n"; if (handshake.code == "OUTDATED_VERSION" && !handshake.download_url.empty()) { std::cout << "Update to " << handshake.latest_version << " at: " << handshake.download_url << "\n"; } return 1; } std::cout << "Server reachable. Product version: " << APP_VERSION << "\n"; std::cout << "Enter license key: "; std::string key; std::getline(std::cin, key); auto res = client.auth(key); if (!res.ok) { std::cout << "Access denied: " << res.code; if (!res.message.empty()) std::cout << " — " << res.message; std::cout << "\n"; if (res.code == "HWID_LIMIT" || res.code == "HWID_MISMATCH") { std::cout << "This machine is not bound to the key.\n"; std::cout << "Reset HWID and bind this machine? [y/N]: "; std::string answer; std::getline(std::cin, answer); if (answer == "y" || answer == "Y") { auto reset = client.reset_hwid(key); if (!reset.ok) { std::cout << "Reset failed: " << reset.code; if (reset.code == "RESET_COOLDOWN") { std::cout << " (retry after " << reset.retry_after << "s)"; } std::cout << "\n"; return 1; } res = reset; std::cout << "HWID reset. This machine is now bound.\n"; } else { return 1; } } else { return 1; } } std::cout << "\nLicense accepted.\n"; std::cout << " Status: " << res.license.status << "\n"; if (res.license.lifetime) { std::cout << " Expires: never (lifetime)\n"; } else { std::cout << " Expires: " << res.license.expires_at << " (" << res.license.days_left << " days / " << res.license.seconds_left << "s left)\n"; } std::cout << " HWID slots: " << res.license.max_hwids << "\n"; if (!res.variables.empty()) { std::cout << " Cloud variables received: " << res.variables.size() << "\n"; } std::cout << "\n"; std::cout << "Running protected application...\n"; // Heartbeat loop — keep the session alive / detect revocation / instant kick. for (int i = 0; i < 3; ++i) { std::this_thread::sleep_for(std::chrono::seconds(3)); auto hb = client.heartbeat(); if (!hb.ok) { std::cout << "Session invalidated: " << hb.code << " — shutting down.\n"; return 1; } std::cout << "Heartbeat OK (" << hb.license.seconds_left << "s left)\n"; } client.logout(); std::cout << "Done.\n"; return 0; } ``` ### 3. Python 3.8+ SDK (`pip install cryptography`) - Filename: `sdk/psychokey.py` - Direct Download: `https://psycho-key.com/sdk-file.php?name=psychokey.py` ```python """ Psycho Key — Python SDK (v2 AES-256-GCM protocol) Requires: pip install cryptography Works with Python 3.8+ Usage: from psychokey import Client, Config client = Client(Config(app="my-app", api_secret="64hex...")) res = client.auth("PSYCHO-XXXX-XXXX-XXXX-XXXX") if res.ok: print(f"License active, {res.license.days_left} days left") """ from __future__ import annotations import hashlib import hmac import json import os import platform import re import secrets import subprocess import struct import time import urllib.request import urllib.error from dataclasses import dataclass, field from typing import Any, Dict, List, Optional # --------------------------------------------------------------------------- # HKDF-SHA256 (extract + expand, RFC 5869) # --------------------------------------------------------------------------- def _hkdf_extract(salt: bytes, ikm: bytes) -> bytes: return hmac.new(salt, ikm, "sha256").digest() def _hkdf_expand(prk: bytes, info: bytes, length: int) -> bytes: n = (length + 31) // 32 okm = b"" t = b"" for i in range(1, n + 1): t = hmac.new(prk, t + info + bytes([i]), "sha256").digest() okm += t return okm[:length] def _hkdf_sha256(ikm: bytes, salt: str, info: str, length: int = 32) -> bytes: prk = _hkdf_extract(salt.encode(), ikm) return _hkdf_expand(prk, info.encode(), length) # --------------------------------------------------------------------------- # AES-256-GCM (via cryptography library) # --------------------------------------------------------------------------- try: from cryptography.hazmat.primitives.ciphers.aead import AESGCM _HAS_CRYPTO = True except ImportError: _HAS_CRYPTO = False def _aes_gcm_encrypt(key: bytes, plaintext: bytes, aad: bytes) -> tuple: """Returns (iv, ciphertext, tag) all as bytes.""" if not _HAS_CRYPTO: raise RuntimeError("Install 'cryptography': pip install cryptography") iv = secrets.token_bytes(12) aes = AESGCM(key) ct_and_tag = aes.encrypt(iv, plaintext, aad) ct = ct_and_tag[:-16] tag = ct_and_tag[-16:] return iv, ct, tag def _aes_gcm_decrypt(key: bytes, iv: bytes, ct: bytes, tag: bytes, aad: bytes) -> bytes: """Decrypt and verify AES-256-GCM. Raises on auth failure.""" if not _HAS_CRYPTO: raise RuntimeError("Install 'cryptography': pip install cryptography") aes = AESGCM(key) return aes.decrypt(iv, ct + tag, aad) # --------------------------------------------------------------------------- # HWID detection # --------------------------------------------------------------------------- def _get_hwid() -> str: """Platform-specific hardware fingerprint matching ^[A-Za-z0-9:_-]{8,128}$.""" system = platform.system() cand = "" try: if system == "Windows": out = subprocess.check_output( ["wmic", "csproduct", "get", "UUID"], stderr=subprocess.DEVNULL, timeout=5 ).decode(errors="ignore").strip() lines = [l.strip() for l in out.splitlines() if l.strip() and l.strip() != "UUID"] if lines: cand = lines[0] elif system == "Linux": for path in ("/etc/machine-id", "/var/lib/dbus/machine-id"): if os.path.isfile(path): with open(path) as f: mid = f.read().strip() if mid: cand = mid break elif system == "Darwin": out = subprocess.check_output( ["ioreg", "-rd1", "-c", "IOPlatformExpertDevice"], stderr=subprocess.DEVNULL, timeout=5 ).decode(errors="ignore") for line in out.splitlines(): if "IOPlatformUUID" in line: parts = line.split('"') if len(parts) >= 4: cand = parts[-2].strip() break except Exception: pass if re.fullmatch(r"[A-Za-z0-9:_-]{8,128}", cand or ""): return cand # Fallback: hash of hostname + platform raw = f"{platform.node()}|{platform.system()}|{platform.machine()}" return hashlib.sha256(raw.encode()).hexdigest()[:32] # --------------------------------------------------------------------------- # Data classes # --------------------------------------------------------------------------- @dataclass class Config: app: str api_secret: str # 64 hex chars base_url: str = "https://psycho-key.com" version: str = "1.0.0" require_v2: bool = True @dataclass class License: id: int = 0 status: str = "" duration_days: int = 0 duration_seconds: int = 0 max_hwids: int = 0 activated_at: str = "" expires_at: str = "" days_left: int = -1 seconds_left: int = -1 lifetime: bool = False @dataclass class Result: ok: bool = False code: str = "" message: str = "" token: str = "" retry_after: int = 0 latest_version: str = "" download_url: str = "" variables: Dict[str, str] = field(default_factory=dict) license: License = field(default_factory=License) # --------------------------------------------------------------------------- # Client # --------------------------------------------------------------------------- class Client: def __init__(self, config: Config): self._config = config self._secret = bytes.fromhex(config.api_secret) if len(self._secret) != 32: raise ValueError("api_secret must be exactly 64 hex chars (32 bytes)") self._hwid = _get_hwid() self._token = "" self._vars: Dict[str, str] = {} def hwid(self) -> str: return self._hwid def var(self, key: str, default: str = "") -> str: return self._vars.get(key, default) # ----- Public API ----- def init(self) -> Result: """Handshake: check connectivity, product status, version.""" return self._call("init") def auth(self, license_key: str) -> Result: """Validate a license key and bind this machine's HWID.""" res = self._call("license", license_key=license_key) if res.ok and res.token: self._token = res.token if res.variables: self._vars.update(res.variables) return res def heartbeat(self) -> Result: """Keep the session alive and get updated license info.""" res = self._call("heartbeat") if res.ok and res.token: self._token = res.token if res.variables: self._vars.update(res.variables) return res def logout(self) -> Result: """Revoke the current session on the server.""" res = self._call("logout") self._token = "" return res def reset_hwid(self, license_key: str) -> Result: """Self-service HWID reset and rebind to this machine.""" res = self._call("reset", license_key=license_key) if res.ok and res.token: self._token = res.token if res.variables: self._vars.update(res.variables) return res # ----- Internal ----- def _call(self, action: str, license_key: str = "") -> Result: out = Result() try: nonce = secrets.token_hex(16) ts = int(time.time()) # HMAC signature canonical = "|".join([ self._config.app, action, nonce, str(ts), self._hwid, license_key, self._token, ]) sig = hmac.new(self._secret, canonical.encode(), "sha256").hexdigest() inner = json.dumps({ "action": action, "nonce": nonce, "ts": ts, "hwid": self._hwid, "license_key": license_key, "token": self._token, "version": self._config.version, "sig": sig, }, separators=(",", ":")) # Encrypt inner with AES-256-GCM req_key = _hkdf_sha256( self._secret, "psychokey-salt-v1", f"psychokey-req-v2|{self._config.app}" ) iv, ct, tag = _aes_gcm_encrypt(req_key, inner.encode(), self._config.app.encode()) import base64 envelope = json.dumps({ "app": self._config.app, "v": 2, "iv": base64.b64encode(iv).decode(), "ct": base64.b64encode(ct).decode(), "tag": base64.b64encode(tag).decode(), }, separators=(",", ":")) # HTTP POST url = self._config.base_url.rstrip("/") + "/api/v1.php" req = urllib.request.Request( url, data=envelope.encode(), method="POST", headers={ "Content-Type": "application/json", "User-Agent": f"PsychoKey-Python/{self._config.version}", }, ) try: with urllib.request.urlopen(req, timeout=15) as resp: body = resp.read() except urllib.error.HTTPError as e: body = e.read() root = json.loads(body) # Decrypt v2 response if root.get("v") == 2: resp_key = _hkdf_sha256( self._secret, "psychokey-salt-v1", f"psychokey-resp-v2|{self._config.app}" ) aad = f"{self._config.app}|{action}|{nonce}" plain = _aes_gcm_decrypt( resp_key, base64.b64decode(root["iv"]), base64.b64decode(root["ct"]), base64.b64decode(root["tag"]), aad.encode(), ) payload = json.loads(plain) else: # Pre-auth errors are unencrypted if root.get("success", False) and self._config.require_v2: out.code = "CLIENT_INTEGRITY" out.message = "Unencrypted success rejected." return out payload = root # Parse payload out.ok = payload.get("success", False) out.code = payload.get("code", "ERROR") out.message = payload.get("message", "") out.retry_after = int(payload.get("retry_after", 0)) out.latest_version = payload.get("latest_version", "") out.download_url = payload.get("download_url", "") if isinstance(payload.get("variables"), dict): out.variables = { k: str(v) for k, v in payload["variables"].items() if isinstance(v, str) } if out.ok: out.token = payload.get("token", "") lic = payload.get("license", {}) if isinstance(lic, dict): out.license = License( id=int(lic.get("id", 0)), status=lic.get("status", ""), duration_days=int(lic.get("duration", 0)), duration_seconds=int(lic.get("duration_seconds", 0)), max_hwids=int(lic.get("max_hwids", 0)), activated_at=lic.get("activated_at", ""), expires_at=lic.get("expires_at", ""), days_left=int(lic.get("days_left", -1)), seconds_left=int(lic.get("seconds_left", -1)), lifetime=bool(lic.get("lifetime", False)), ) except Exception as e: out.code = "CLIENT_ERROR" out.message = str(e) return out ``` ### 4. Python Example - Filename: `sdk/example.py` - Direct Download: `https://psycho-key.com/sdk-file.php?name=example.py` ```python """Psycho Key SDK — Python example integration.""" import time from psychokey import Client, Config # Replace with your product values from the panel client = Client(Config( app="my-app", # Product slug api_secret="REPLACE_WITH_64_HEX_PRODUCT_SECRET", # API Secret from panel version="1.0.0", )) print(f"HWID: {client.hwid()}\n") # 1. Handshake handshake = client.init() if not handshake.ok: print(f"Handshake failed: {handshake.code} — {handshake.message}") if handshake.code == "OUTDATED_VERSION": print(f"Update to {handshake.latest_version} at: {handshake.download_url}") exit(1) print("Server reachable ✓") # 2. License activation key = input("Enter license key: ").strip() res = client.auth(key) if not res.ok: print(f"Access denied: {res.code} — {res.message}") if res.code in ("HWID_LIMIT", "HWID_MISMATCH"): answer = input("Reset HWID and bind this machine? [y/N]: ") if answer.lower() == "y": reset = client.reset_hwid(key) if not reset.ok: print(f"Reset failed: {reset.code}") exit(1) res = reset print("HWID reset ✓") else: exit(1) else: exit(1) print(f"\nLicense accepted ✓") print(f" Status: {res.license.status}") if res.license.lifetime: print(f" Expires: never (lifetime)") else: print(f" Expires: {res.license.expires_at} ({res.license.days_left} days left)") print(f" HWID slots: {res.license.max_hwids}") if res.variables: print(f" Cloud variables: {len(res.variables)}") for k, v in res.variables.items(): print(f" {k} = {v}") # 3. Heartbeat loop print("\nRunning protected application...") for i in range(3): time.sleep(3) hb = client.heartbeat() if not hb.ok: print(f"Session invalidated: {hb.code} — shutting down.") exit(1) print(f"Heartbeat OK ({hb.license.seconds_left}s left)") # 4. Logout client.logout() print("Done.") ``` ### 5. C# / .NET 6+ SDK (Zero NuGet deps — Desktop, Unity, WPF, WinForms) - Filename: `sdk/PsychoKey.cs` - Direct Download: `https://psycho-key.com/sdk-file.php?name=PsychoKey.cs` ```csharp // Psycho Key — C# SDK (v2 AES-256-GCM protocol) // Requires: .NET 6+ (uses System.Security.Cryptography.AesGcm) // Single-file, no NuGet dependencies. // // Usage: // var client = new PsychoKey.Client(new PsychoKey.Config { // App = "my-app", // ApiSecret = "64hex...", // }); // var res = client.Auth("PSYCHO-XXXX-XXXX-XXXX-XXXX"); // if (res.Ok) Console.WriteLine($"Active, {res.License.DaysLeft} days left"); using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading; using System.Diagnostics; namespace PsychoKey { public class Config { public string App { get; set; } = ""; public string ApiSecret { get; set; } = ""; // 64 hex chars public string BaseUrl { get; set; } = "https://psycho-key.com"; public string Version { get; set; } = "1.0.0"; public bool RequireV2 { get; set; } = true; } public class LicenseInfo { public long Id { get; set; } public string Status { get; set; } = ""; public int DurationDays { get; set; } public int DurationSeconds { get; set; } public int MaxHwids { get; set; } public string ActivatedAt { get; set; } = ""; public string ExpiresAt { get; set; } = ""; public int DaysLeft { get; set; } = -1; public long SecondsLeft { get; set; } = -1; public bool Lifetime { get; set; } } public class Result { public bool Ok { get; set; } public string Code { get; set; } = ""; public string Message { get; set; } = ""; public string Token { get; set; } = ""; public int RetryAfter { get; set; } public string LatestVersion { get; set; } = ""; public string DownloadUrl { get; set; } = ""; public Dictionary Variables { get; set; } = new(); public LicenseInfo License { get; set; } = new(); } public class Client { private readonly Config _config; private readonly byte[] _secret; private readonly string _hwid; private string _token = ""; private readonly Dictionary _vars = new(); private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(15) }; public Client(Config config) { _config = config; _secret = Convert.FromHexString(config.ApiSecret); if (_secret.Length != 32) throw new ArgumentException("ApiSecret must be 64 hex chars (32 bytes)"); _hwid = DetectHwid(); } public string Hwid() => _hwid; public string Var(string key, string def = "") => _vars.TryGetValue(key, out var v) ? v : def; // --- Public API --- public Result Init() => Call("init"); public Result Auth(string licenseKey) { var r = Call("license", licenseKey); if (r.Ok && !string.IsNullOrEmpty(r.Token)) _token = r.Token; foreach (var kv in r.Variables) _vars[kv.Key] = kv.Value; return r; } public Result Heartbeat() { var r = Call("heartbeat"); if (r.Ok && !string.IsNullOrEmpty(r.Token)) _token = r.Token; foreach (var kv in r.Variables) _vars[kv.Key] = kv.Value; return r; } public Result Logout() { var r = Call("logout"); _token = ""; return r; } public Result ResetHwid(string licenseKey) { var r = Call("reset", licenseKey); if (r.Ok && !string.IsNullOrEmpty(r.Token)) _token = r.Token; foreach (var kv in r.Variables) _vars[kv.Key] = kv.Value; return r; } // --- Internals --- private Result Call(string action, string licenseKey = "") { var result = new Result(); try { var nonce = Convert.ToHexString(RandomNumberGenerator.GetBytes(16)).ToLower(); var ts = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); // HMAC signature var canonical = string.Join("|", _config.App, action, nonce, ts.ToString(), _hwid, licenseKey, _token); var sig = HmacSha256Hex(_secret, Encoding.UTF8.GetBytes(canonical)); // Build inner JSON var inner = JsonSerializer.Serialize(new Dictionary { ["action"] = action, ["nonce"] = nonce, ["ts"] = ts, ["hwid"] = _hwid, ["license_key"] = licenseKey, ["token"] = _token, ["version"] = _config.Version, ["sig"] = sig, }); // Encrypt with AES-256-GCM var reqKey = HkdfSha256(_secret, "psychokey-salt-v1", $"psychokey-req-v2|{_config.App}", 32); var iv = RandomNumberGenerator.GetBytes(12); var plainBytes = Encoding.UTF8.GetBytes(inner); var ct = new byte[plainBytes.Length]; var tag = new byte[16]; using (var aes = new AesGcm(reqKey, 16)) { aes.Encrypt(iv, plainBytes, ct, tag, Encoding.UTF8.GetBytes(_config.App)); } var envelope = JsonSerializer.Serialize(new Dictionary { ["app"] = _config.App, ["v"] = 2, ["iv"] = Convert.ToBase64String(iv), ["ct"] = Convert.ToBase64String(ct), ["tag"] = Convert.ToBase64String(tag), }); // HTTP POST var url = _config.BaseUrl.TrimEnd('/') + "/api/v1.php"; var content = new StringContent(envelope, Encoding.UTF8, "application/json"); var resp = Http.PostAsync(url, content).GetAwaiter().GetResult(); var body = resp.Content.ReadAsStringAsync().GetAwaiter().GetResult(); using var root = JsonDocument.Parse(body); JsonElement payload; if (root.RootElement.TryGetProperty("v", out var vProp) && vProp.GetInt32() == 2) { // Decrypt v2 response var respKey = HkdfSha256(_secret, "psychokey-salt-v1", $"psychokey-resp-v2|{_config.App}", 32); var aad = $"{_config.App}|{action}|{nonce}"; var rIv = Convert.FromBase64String(root.RootElement.GetProperty("iv").GetString()!); var rCt = Convert.FromBase64String(root.RootElement.GetProperty("ct").GetString()!); var rTag = Convert.FromBase64String(root.RootElement.GetProperty("tag").GetString()!); var plainOut = new byte[rCt.Length]; using (var aes = new AesGcm(respKey, 16)) { aes.Decrypt(rIv, rCt, rTag, plainOut, Encoding.UTF8.GetBytes(aad)); } using var dec = JsonDocument.Parse(plainOut); payload = dec.RootElement.Clone(); } else { if (root.RootElement.TryGetProperty("success", out var s) && s.GetBoolean() && _config.RequireV2) { result.Code = "CLIENT_INTEGRITY"; result.Message = "Unencrypted success rejected."; return result; } payload = root.RootElement.Clone(); } // Parse payload result.Ok = payload.TryGetProperty("success", out var sp) && sp.GetBoolean(); result.Code = payload.TryGetProperty("code", out var cp) ? cp.GetString() ?? "" : ""; result.Message = payload.TryGetProperty("message", out var mp) ? mp.GetString() ?? "" : ""; result.RetryAfter = payload.TryGetProperty("retry_after", out var rp) ? rp.GetInt32() : 0; result.LatestVersion = payload.TryGetProperty("latest_version", out var lv) ? lv.GetString() ?? "" : ""; result.DownloadUrl = payload.TryGetProperty("download_url", out var du) ? du.GetString() ?? "" : ""; if (payload.TryGetProperty("variables", out var vars) && vars.ValueKind == JsonValueKind.Object) { foreach (var kv in vars.EnumerateObject()) if (kv.Value.ValueKind == JsonValueKind.String) result.Variables[kv.Name] = kv.Value.GetString()!; } if (result.Ok) { result.Token = payload.TryGetProperty("token", out var tk) ? tk.GetString() ?? "" : ""; if (payload.TryGetProperty("license", out var lic) && lic.ValueKind == JsonValueKind.Object) { result.License = new LicenseInfo { Id = lic.TryGetProperty("id", out var li) ? li.GetInt64() : 0, Status = lic.TryGetProperty("status", out var ls) ? ls.GetString() ?? "" : "", DurationDays = lic.TryGetProperty("duration", out var ld) ? ld.GetInt32() : 0, DurationSeconds = lic.TryGetProperty("duration_seconds", out var lds) ? lds.GetInt32() : 0, MaxHwids = lic.TryGetProperty("max_hwids", out var lm) ? lm.GetInt32() : 0, ActivatedAt = lic.TryGetProperty("activated_at", out var la) ? la.GetString() ?? "" : "", ExpiresAt = lic.TryGetProperty("expires_at", out var le) ? le.GetString() ?? "" : "", DaysLeft = lic.TryGetProperty("days_left", out var ldl) ? ldl.GetInt32() : -1, SecondsLeft = lic.TryGetProperty("seconds_left", out var lsl) ? lsl.GetInt64() : -1, Lifetime = lic.TryGetProperty("lifetime", out var ll) && ll.GetBoolean(), }; } } } catch (Exception ex) { result.Code = "CLIENT_ERROR"; result.Message = ex.Message; } return result; } // --- Crypto helpers --- private static string HmacSha256Hex(byte[] key, byte[] data) { using var mac = new HMACSHA256(key); return Convert.ToHexString(mac.ComputeHash(data)).ToLower(); } private static byte[] HkdfSha256(byte[] ikm, string salt, string info, int length) { // HKDF Extract using var extractMac = new HMACSHA256(Encoding.UTF8.GetBytes(salt)); var prk = extractMac.ComputeHash(ikm); // HKDF Expand var infoBytes = Encoding.UTF8.GetBytes(info); var n = (length + 31) / 32; var okm = new byte[n * 32]; var t = Array.Empty(); for (int i = 1; i <= n; i++) { using var mac = new HMACSHA256(prk); var buf = new byte[t.Length + infoBytes.Length + 1]; Buffer.BlockCopy(t, 0, buf, 0, t.Length); Buffer.BlockCopy(infoBytes, 0, buf, t.Length, infoBytes.Length); buf[^1] = (byte)i; t = mac.ComputeHash(buf); Buffer.BlockCopy(t, 0, okm, (i - 1) * 32, 32); } return okm[..length]; } private static string DetectHwid() { string cand = ""; try { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var p = Process.Start(new ProcessStartInfo("wmic", "csproduct get UUID") { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }); var output = p!.StandardOutput.ReadToEnd().Trim(); p.WaitForExit(5000); var lines = output.Split('\n').Select(l => l.Trim()).Where(l => l.Length > 0 && l != "UUID").ToArray(); if (lines.Length > 0) cand = lines[0]; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { if (File.Exists("/etc/machine-id")) cand = File.ReadAllText("/etc/machine-id").Trim(); else if (File.Exists("/var/lib/dbus/machine-id")) cand = File.ReadAllText("/var/lib/dbus/machine-id").Trim(); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var p = Process.Start(new ProcessStartInfo("ioreg", "-rd1 -c IOPlatformExpertDevice") { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }); var output = p!.StandardOutput.ReadToEnd(); p.WaitForExit(5000); foreach (var line in output.Split('\n')) if (line.Contains("IOPlatformUUID")) { var parts = line.Split('"'); if (parts.Length >= 4) { cand = parts[^2].Trim(); break; } } } } catch { } if (cand.Length >= 8 && cand.Length <= 128 && cand.All(c => char.IsLetterOrDigit(c) || c is ':' or '_' or '-')) return cand; var raw = $"{Environment.MachineName}|{RuntimeInformation.OSDescription}"; return Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(raw))).ToLower()[..32]; } } } ``` ### 6. C# Example - Filename: `sdk/Example.cs` - Direct Download: `https://psycho-key.com/sdk-file.php?name=Example.cs` ```csharp // Psycho Key SDK — C# example integration // Build: dotnet new console → add PsychoKey.cs → dotnet run // Requires .NET 6+ using PsychoKey; var client = new PsychoKey.Client(new PsychoKey.Config { App = "my-app", // Product slug ApiSecret = "REPLACE_WITH_64_HEX_PRODUCT_SECRET", // API Secret from panel Version = "1.0.0", }); Console.WriteLine($"HWID: {client.Hwid()}\n"); // 1. Handshake var handshake = client.Init(); if (!handshake.Ok) { Console.WriteLine($"Handshake failed: {handshake.Code} — {handshake.Message}"); if (handshake.Code == "OUTDATED_VERSION") Console.WriteLine($"Update to {handshake.LatestVersion} at: {handshake.DownloadUrl}"); return; } Console.WriteLine("Server reachable ✓"); // 2. License activation Console.Write("Enter license key: "); var key = Console.ReadLine()?.Trim() ?? ""; var res = client.Auth(key); if (!res.Ok) { Console.WriteLine($"Access denied: {res.Code} — {res.Message}"); if (res.Code is "HWID_LIMIT" or "HWID_MISMATCH") { Console.Write("Reset HWID? [y/N]: "); if (Console.ReadLine()?.Trim().ToLower() == "y") { var reset = client.ResetHwid(key); if (!reset.Ok) { Console.WriteLine($"Reset failed: {reset.Code}"); return; } res = reset; Console.WriteLine("HWID reset ✓"); } else return; } else return; } Console.WriteLine($"\nLicense accepted ✓"); Console.WriteLine($" Status: {res.License.Status}"); Console.WriteLine(res.License.Lifetime ? " Expires: never (lifetime)" : $" Expires: {res.License.ExpiresAt} ({res.License.DaysLeft} days left)"); Console.WriteLine($" HWID slots: {res.License.MaxHwids}"); // 3. Heartbeat loop Console.WriteLine("\nRunning protected application..."); for (int i = 0; i < 3; i++) { Thread.Sleep(3000); var hb = client.Heartbeat(); if (!hb.Ok) { Console.WriteLine($"Session invalidated: {hb.Code}"); return; } Console.WriteLine($"Heartbeat OK ({hb.License.SecondsLeft}s left)"); } // 4. Logout client.Logout(); Console.WriteLine("Done."); ``` ### 7. Node.js 16+ SDK (Zero npm deps — Electron, Discord Bots, CLI) - Filename: `sdk/psychokey.js` - Direct Download: `https://psycho-key.com/sdk-file.php?name=psychokey.js` ```javascript // Psycho Key — Node.js SDK (v2 AES-256-GCM protocol) // Requires: Node.js 16+ (uses built-in crypto module only, zero dependencies) // // Usage: // const { PsychoKey } = require('./psychokey'); // const client = new PsychoKey({ app: 'my-app', apiSecret: '64hex...' }); // const res = await client.auth('PSYCHO-XXXX-XXXX-XXXX-XXXX'); 'use strict'; const crypto = require('crypto'); const https = require('https'); const http = require('http'); const os = require('os'); const { execSync } = require('child_process'); const { URL } = require('url'); // --- HKDF-SHA256 (for Node < 18 compatibility, manual implementation) --- function hkdfSha256(ikm, salt, info, length = 32) { const saltBuf = typeof salt === 'string' ? Buffer.from(salt) : salt; const infoBuf = typeof info === 'string' ? Buffer.from(info) : info; // Extract const prk = crypto.createHmac('sha256', saltBuf).update(ikm).digest(); // Expand const n = Math.ceil(length / 32); let okm = Buffer.alloc(0); let t = Buffer.alloc(0); for (let i = 1; i <= n; i++) { t = crypto.createHmac('sha256', prk) .update(Buffer.concat([t, infoBuf, Buffer.from([i])])) .digest(); okm = Buffer.concat([okm, t]); } return okm.subarray(0, length); } // --- AES-256-GCM --- function aesGcmEncrypt(key, plaintext, aad) { const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); cipher.setAAD(typeof aad === 'string' ? Buffer.from(aad) : aad); const ct = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]); const tag = cipher.getAuthTag(); return { iv, ct, tag }; } function aesGcmDecrypt(key, iv, ct, tag, aad) { const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv); decipher.setAuthTag(tag); decipher.setAAD(typeof aad === 'string' ? Buffer.from(aad) : aad); return Buffer.concat([decipher.update(ct), decipher.final()]).toString('utf8'); } // --- HWID detection --- function detectHwid() { let cand = ''; try { if (process.platform === 'win32') { const out = execSync('wmic csproduct get UUID', { timeout: 5000 }).toString().trim(); const lines = out.split('\n').map(l => l.trim()).filter(l => l && l !== 'UUID'); if (lines.length > 0) cand = lines[0]; } else if (process.platform === 'linux') { const fs = require('fs'); for (const p of ['/etc/machine-id', '/var/lib/dbus/machine-id']) { if (fs.existsSync(p)) { const mid = fs.readFileSync(p, 'utf8').trim(); if (mid) { cand = mid; break; } } } } else if (process.platform === 'darwin') { const out = execSync('ioreg -rd1 -c IOPlatformExpertDevice', { timeout: 5000 }).toString(); for (const line of out.split('\n')) { if (line.includes('IOPlatformUUID')) { const parts = line.split('"'); if (parts.length >= 4) { cand = parts[parts.length - 2].trim(); break; } } } } } catch {} if (/^[A-Za-z0-9:_-]{8,128}$/.test(cand)) return cand; // Fallback const raw = `${os.hostname()}|${os.platform()}|${os.arch()}`; return crypto.createHash('sha256').update(raw).digest('hex').substring(0, 32); } // --- HTTP POST helper --- function httpPost(url, body) { return new Promise((resolve, reject) => { const parsed = new URL(url); const mod = parsed.protocol === 'https:' ? https : http; const req = mod.request(parsed, { method: 'POST', headers: { 'Content-Type': 'application/json', 'User-Agent': 'PsychoKey-NodeJS/1.0', 'Content-Length': Buffer.byteLength(body), }, timeout: 15000, }, (res) => { const chunks = []; res.on('data', c => chunks.push(c)); res.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); }); req.on('error', reject); req.on('timeout', () => { req.destroy(); reject(new Error('Request timeout')); }); req.write(body); req.end(); }); } // --- Main class --- class PsychoKey { /** * @param {Object} config * @param {string} config.app - Product slug * @param {string} config.apiSecret - 64 hex chars * @param {string} [config.baseUrl='https://psycho-key.com'] * @param {string} [config.version='1.0.0'] * @param {boolean} [config.requireV2=true] */ constructor(config) { this.app = config.app; this.secret = Buffer.from(config.apiSecret, 'hex'); if (this.secret.length !== 32) throw new Error('apiSecret must be 64 hex chars (32 bytes)'); this.baseUrl = (config.baseUrl || 'https://psycho-key.com').replace(/\/+$/, ''); this.version = config.version || '1.0.0'; this.requireV2 = config.requireV2 !== false; this._hwid = detectHwid(); this._token = ''; this._vars = {}; } hwid() { return this._hwid; } getVar(key, def = '') { return this._vars[key] || def; } async init() { return this._call('init'); } async auth(licenseKey) { const r = await this._call('license', licenseKey); if (r.ok && r.token) this._token = r.token; Object.assign(this._vars, r.variables || {}); return r; } async heartbeat() { const r = await this._call('heartbeat'); if (r.ok && r.token) this._token = r.token; Object.assign(this._vars, r.variables || {}); return r; } async logout() { const r = await this._call('logout'); this._token = ''; return r; } async resetHwid(licenseKey) { const r = await this._call('reset', licenseKey); if (r.ok && r.token) this._token = r.token; Object.assign(this._vars, r.variables || {}); return r; } async _call(action, licenseKey = '') { const result = { ok: false, code: '', message: '', token: '', retryAfter: 0, latestVersion: '', downloadUrl: '', variables: {}, license: {} }; try { const nonce = crypto.randomBytes(16).toString('hex'); const ts = Math.floor(Date.now() / 1000); // HMAC signature const canonical = [this.app, action, nonce, ts, this._hwid, licenseKey, this._token].join('|'); const sig = crypto.createHmac('sha256', this.secret).update(canonical).digest('hex'); const inner = JSON.stringify({ action, nonce, ts, hwid: this._hwid, license_key: licenseKey, token: this._token, version: this.version, sig, }); // Encrypt const reqKey = hkdfSha256(this.secret, 'psychokey-salt-v1', `psychokey-req-v2|${this.app}`); const enc = aesGcmEncrypt(reqKey, inner, this.app); const envelope = JSON.stringify({ app: this.app, v: 2, iv: enc.iv.toString('base64'), ct: enc.ct.toString('base64'), tag: enc.tag.toString('base64'), }); const body = await httpPost(`${this.baseUrl}/api/v1.php`, envelope); const root = JSON.parse(body); let payload; if (root.v === 2) { const respKey = hkdfSha256(this.secret, 'psychokey-salt-v1', `psychokey-resp-v2|${this.app}`); const aad = `${this.app}|${action}|${nonce}`; const plain = aesGcmDecrypt( respKey, Buffer.from(root.iv, 'base64'), Buffer.from(root.ct, 'base64'), Buffer.from(root.tag, 'base64'), aad, ); payload = JSON.parse(plain); } else { if (root.success && this.requireV2) { result.code = 'CLIENT_INTEGRITY'; result.message = 'Unencrypted success rejected.'; return result; } payload = root; } result.ok = !!payload.success; result.code = payload.code || ''; result.message = payload.message || ''; result.retryAfter = payload.retry_after || 0; result.latestVersion = payload.latest_version || ''; result.downloadUrl = payload.download_url || ''; if (payload.variables && typeof payload.variables === 'object') { for (const [k, v] of Object.entries(payload.variables)) { if (typeof v === 'string') result.variables[k] = v; } } if (result.ok) { result.token = payload.token || ''; const lic = payload.license || {}; result.license = { id: lic.id || 0, status: lic.status || '', durationDays: lic.duration || 0, durationSeconds: lic.duration_seconds || 0, maxHwids: lic.max_hwids || 0, activatedAt: lic.activated_at || '', expiresAt: lic.expires_at || '', daysLeft: lic.days_left ?? -1, secondsLeft: lic.seconds_left ?? -1, lifetime: !!lic.lifetime, }; } } catch (e) { result.code = 'CLIENT_ERROR'; result.message = e.message || String(e); } return result; } } module.exports = { PsychoKey }; ``` ### 8. TypeScript Declarations for psychokey.js - Filename: `sdk/psychokey.d.ts` - Direct Download: `https://psycho-key.com/sdk-file.php?name=psychokey.d.ts` ```typescript export interface PsychoKeyConfig { app: string; apiSecret: string; baseUrl?: string; version?: string; requireV2?: boolean; } export interface PsychoLicense { id: number; status: string; durationDays: number; durationSeconds: number; maxHwids: number; activatedAt: string; expiresAt: string; daysLeft: number; secondsLeft: number; lifetime: boolean; } export interface PsychoResult { ok: boolean; code: string; message: string; token: string; retryAfter: number; latestVersion: string; downloadUrl: string; variables: Record; license: PsychoLicense; } export class PsychoKey { constructor(config: PsychoKeyConfig); hwid(): string; getVar(key: string, defaultValue?: string): string; init(): Promise; auth(licenseKey: string): Promise; heartbeat(): Promise; logout(): Promise; resetHwid(licenseKey: string): Promise; } ``` ### 9. Node.js ESM Example - Filename: `sdk/example.mjs` - Direct Download: `https://psycho-key.com/sdk-file.php?name=example.mjs` ```javascript // Psycho Key SDK — Node.js example (ESM) // Run: node example.mjs import { PsychoKey } from './psychokey.js'; import { createRequire } from 'module'; const require = createRequire(import.meta.url); const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); const ask = (q) => new Promise(r => rl.question(q, r)); const client = new PsychoKey({ app: 'my-app', apiSecret: 'REPLACE_WITH_64_HEX_PRODUCT_SECRET', version: '1.0.0', }); console.log(`HWID: ${client.hwid()}\n`); // 1. Handshake const hs = await client.init(); if (!hs.ok) { console.log(`Handshake failed: ${hs.code} — ${hs.message}`); process.exit(1); } console.log('Server reachable ✓'); // 2. License const key = await ask('Enter license key: '); let res = await client.auth(key.trim()); if (!res.ok) { console.log(`Access denied: ${res.code}`); if (res.code === 'HWID_LIMIT' || res.code === 'HWID_MISMATCH') { const ans = await ask('Reset HWID? [y/N]: '); if (ans.trim().toLowerCase() === 'y') { res = await client.resetHwid(key.trim()); if (!res.ok) { console.log(`Reset failed: ${res.code}`); process.exit(1); } } else process.exit(1); } else process.exit(1); } console.log(`\nLicense accepted ✓`); console.log(` Status: ${res.license.status}`); console.log(res.license.lifetime ? ' Expires: never (lifetime)' : ` Expires: ${res.license.expiresAt} (${res.license.daysLeft} days)`); // 3. Heartbeat console.log('\nRunning...'); for (let i = 0; i < 3; i++) { await new Promise(r => setTimeout(r, 3000)); const hb = await client.heartbeat(); if (!hb.ok) { console.log(`Session lost: ${hb.code}`); process.exit(1); } console.log(`Heartbeat OK (${hb.license.secondsLeft}s left)`); } // 4. Logout await client.logout(); console.log('Done.'); rl.close(); ``` ### 10. Go 1.18+ SDK (Stdlib only — zero external modules) - Filename: `sdk/psychokey.go` - Direct Download: `https://psycho-key.com/sdk-file.php?name=psychokey.go` ```go // Psycho Key — Go SDK (v2 AES-256-GCM protocol) // Uses ONLY the Go standard library (Go 1.18+, zero third-party dependencies). // // Usage: // client, err := psychokey.NewClient(psychokey.Config{ // App: "my-app", // ApiSecret: "64_HEX_CHARS", // }) // res := client.Auth("PSYCHO-XXXX-XXXX-XXXX-XXXX") // if res.Ok { fmt.Println("Days left:", res.License.DaysLeft) } package psychokey import ( "bytes" "crypto/aes" "crypto/cipher" "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "io" "math" "net/http" "os" "os/exec" "regexp" "runtime" "strings" "sync" "time" ) const ( hkdfSalt = "psychokey-salt-v1" defaultBase = "https://psycho-key.com" ) var validHwidRe = regexp.MustCompile(`^[A-Za-z0-9:_\-]{8,128}$`) type Config struct { App string ApiSecret string // 64 hex chars (32 bytes) BaseURL string // default: https://psycho-key.com Version string // default: 1.0.0 RequireV2 *bool // default: true } type License struct { ID int64 `json:"id"` Status string `json:"status"` DurationDays int `json:"duration"` DurationSeconds int `json:"duration_seconds"` MaxHwids int `json:"max_hwids"` ActivatedAt string `json:"activated_at"` ExpiresAt string `json:"expires_at"` DaysLeft int `json:"days_left"` SecondsLeft int64 `json:"seconds_left"` Lifetime bool `json:"lifetime"` } type Result struct { Ok bool Code string Message string Token string RetryAfter int LatestVersion string DownloadURL string Variables map[string]string License License } type Client struct { mu sync.Mutex config Config secret []byte requireV2 bool hwid string token string vars map[string]string http *http.Client } func NewClient(cfg Config) (*Client, error) { secret, err := hex.DecodeString(strings.TrimSpace(cfg.ApiSecret)) if err != nil || len(secret) != 32 { return nil, errors.New("ApiSecret must be exactly 64 hex chars (32 bytes)") } if strings.TrimSpace(cfg.BaseURL) == "" { cfg.BaseURL = defaultBase } cfg.BaseURL = strings.TrimRight(cfg.BaseURL, "/") if strings.TrimSpace(cfg.Version) == "" { cfg.Version = "1.0.0" } reqV2 := true if cfg.RequireV2 != nil { reqV2 = *cfg.RequireV2 } return &Client{ config: cfg, secret: secret, requireV2: reqV2, hwid: detectHWID(), vars: make(map[string]string), http: &http.Client{Timeout: 15 * time.Second}, }, nil } func (c *Client) HWID() string { return c.hwid } func (c *Client) Var(key string, fallback ...string) string { c.mu.Lock() defer c.mu.Unlock() if v, ok := c.vars[key]; ok { return v } if len(fallback) > 0 { return fallback[0] } return "" } func (c *Client) Init() Result { return c.call("init", "") } func (c *Client) Auth(licenseKey string) Result { r := c.call("license", licenseKey) c.mu.Lock() if r.Ok && r.Token != "" { c.token = r.Token } for k, v := range r.Variables { c.vars[k] = v } c.mu.Unlock() return r } func (c *Client) Heartbeat() Result { r := c.call("heartbeat", "") c.mu.Lock() if r.Ok && r.Token != "" { c.token = r.Token } for k, v := range r.Variables { c.vars[k] = v } c.mu.Unlock() return r } func (c *Client) Logout() Result { r := c.call("logout", "") c.mu.Lock() c.token = "" c.mu.Unlock() return r } func (c *Client) ResetHWID(licenseKey string) Result { r := c.call("reset", licenseKey) c.mu.Lock() if r.Ok && r.Token != "" { c.token = r.Token } for k, v := range r.Variables { c.vars[k] = v } c.mu.Unlock() return r } func (c *Client) call(action, licenseKey string) Result { out := Result{Variables: make(map[string]string), License: License{DaysLeft: -1, SecondsLeft: -1}} nonceBytes := make([]byte, 16) if _, err := rand.Read(nonceBytes); err != nil { out.Code, out.Message = "CLIENT_CRYPTO", err.Error() return out } nonce := hex.EncodeToString(nonceBytes) ts := time.Now().Unix() c.mu.Lock() curToken := c.token c.mu.Unlock() canonical := strings.Join([]string{ c.config.App, action, nonce, fmt.Sprintf("%d", ts), c.hwid, licenseKey, curToken, }, "|") mac := hmac.New(sha256.New, c.secret) mac.Write([]byte(canonical)) sig := hex.EncodeToString(mac.Sum(nil)) innerObj := map[string]any{ "action": action, "nonce": nonce, "ts": ts, "hwid": c.hwid, "license_key": licenseKey, "token": curToken, "version": c.config.Version, "sig": sig, } innerBytes, err := json.Marshal(innerObj) if err != nil { out.Code, out.Message = "CLIENT_ENCODE", err.Error() return out } reqKey := hkdfSha256(c.secret, []byte(hkdfSalt), []byte("psychokey-req-v2|"+c.config.App), 32) iv, ct, tag, err := aesGcmEncrypt(reqKey, innerBytes, []byte(c.config.App)) if err != nil { out.Code, out.Message = "CLIENT_CRYPTO", err.Error() return out } envBytes, _ := json.Marshal(map[string]any{ "app": c.config.App, "v": 2, "iv": base64.StdEncoding.EncodeToString(iv), "ct": base64.StdEncoding.EncodeToString(ct), "tag": base64.StdEncoding.EncodeToString(tag), }) req, err := http.NewRequest("POST", c.config.BaseURL+"/api/v1.php", bytes.NewReader(envBytes)) if err != nil { out.Code, out.Message = "NETWORK", err.Error() return out } req.Header.Set("Content-Type", "application/json") req.Header.Set("User-Agent", "PsychoKey-Go/"+c.config.Version) resp, err := c.http.Do(req) if err != nil { out.Code, out.Message = "NETWORK", err.Error() return out } defer resp.Body.Close() body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if err != nil { out.Code, out.Message = "NETWORK", err.Error() return out } var root map[string]json.RawMessage if err := json.Unmarshal(body, &root); err != nil { out.Code, out.Message = "CLIENT_PARSE", err.Error() return out } var payloadMap map[string]any encrypted := false var vNum int if rawV, ok := root["v"]; ok { _ = json.Unmarshal(rawV, &vNum) } if vNum == 2 { encrypted = true var ivB64, ctB64, tagB64 string _ = json.Unmarshal(root["iv"], &ivB64) _ = json.Unmarshal(root["ct"], &ctB64) _ = json.Unmarshal(root["tag"], &tagB64) rIv, err1 := base64.StdEncoding.DecodeString(ivB64) rCt, err2 := base64.StdEncoding.DecodeString(ctB64) rTag, err3 := base64.StdEncoding.DecodeString(tagB64) if err1 != nil || err2 != nil || err3 != nil { out.Code, out.Message = "CLIENT_PARSE", "Invalid base64 fields." return out } respKey := hkdfSha256(c.secret, []byte(hkdfSalt), []byte("psychokey-resp-v2|"+c.config.App), 32) aad := []byte(c.config.App + "|" + action + "|" + nonce) plain, err := aesGcmDecrypt(respKey, rIv, rCt, rTag, aad) if err != nil { out.Code, out.Message = "CLIENT_INTEGRITY", "Response authentication failed." return out } if err := json.Unmarshal(plain, &payloadMap); err != nil { out.Code, out.Message = "CLIENT_PARSE", err.Error() return out } } else { if err := json.Unmarshal(body, &payloadMap); err != nil { out.Code, out.Message = "CLIENT_PARSE", err.Error() return out } if okFlag, _ := payloadMap["success"].(bool); okFlag && c.requireV2 { out.Code, out.Message = "CLIENT_INTEGRITY", "Unencrypted success rejected." return out } } if encrypted { if rTs, ok := payloadMap["ts"].(float64); ok && rTs > 0 { if math.Abs(rTs-float64(ts)) > 300.0 { out.Code, out.Message = "CLIENT_INTEGRITY", "Response timestamp outside allowed window." return out } } } out.Ok, _ = payloadMap["success"].(bool) if s, ok := payloadMap["code"].(string); ok { out.Code = s } else if out.Ok { out.Code = "OK" } else { out.Code = "ERROR" } out.Message, _ = payloadMap["message"].(string) if ra, ok := payloadMap["retry_after"].(float64); ok { out.RetryAfter = int(ra) } out.LatestVersion, _ = payloadMap["latest_version"].(string) out.DownloadURL, _ = payloadMap["download_url"].(string) if vars, ok := payloadMap["variables"].(map[string]any); ok { for k, v := range vars { if vs, ok := v.(string); ok { out.Variables[k] = vs } } } if out.Ok { out.Token, _ = payloadMap["token"].(string) if licRaw, ok := payloadMap["license"]; ok { licBytes, _ := json.Marshal(licRaw) _ = json.Unmarshal(licBytes, &out.License) } } return out } func hkdfSha256(ikm, salt, info []byte, length int) []byte { ext := hmac.New(sha256.New, salt) ext.Write(ikm) prk := ext.Sum(nil) n := (length + 31) / 32 okm := make([]byte, 0, n*32) var prev []byte for i := 1; i <= n; i++ { exp := hmac.New(sha256.New, prk) exp.Write(prev) exp.Write(info) exp.Write([]byte{byte(i)}) prev = exp.Sum(nil) okm = append(okm, prev...) } return okm[:length] } func aesGcmEncrypt(key, plaintext, aad []byte) (iv, ct, tag []byte, err error) { block, err := aes.NewCipher(key) if err != nil { return nil, nil, nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, nil, nil, err } iv = make([]byte, 12) if _, err := rand.Read(iv); err != nil { return nil, nil, nil, err } sealed := gcm.Seal(nil, iv, plaintext, aad) ct = sealed[:len(sealed)-16] tag = sealed[len(sealed)-16:] return iv, ct, tag, nil } func aesGcmDecrypt(key, iv, ct, tag, aad []byte) ([]byte, error) { block, err := aes.NewCipher(key) if err != nil { return nil, err } gcm, err := cipher.NewGCM(block) if err != nil { return nil, err } joined := make([]byte, len(ct)+len(tag)) copy(joined, ct) copy(joined[len(ct):], tag) return gcm.Open(nil, iv, joined, aad) } func detectHWID() string { var cand string switch runtime.GOOS { case "windows": if out, err := exec.Command("wmic", "csproduct", "get", "UUID").Output(); err == nil { for _, line := range strings.Split(string(out), "\n") { t := strings.TrimSpace(line) if t != "" && t != "UUID" { cand = t break } } } case "linux": for _, p := range []string{"/etc/machine-id", "/var/lib/dbus/machine-id"} { if b, err := os.ReadFile(p); err == nil { if t := strings.TrimSpace(string(b)); t != "" { cand = t break } } } case "darwin": if out, err := exec.Command("ioreg", "-rd1", "-c", "IOPlatformExpertDevice").Output(); err == nil { for _, line := range strings.Split(string(out), "\n") { if strings.Contains(line, "IOPlatformUUID") { parts := strings.Split(line, "\"") if len(parts) >= 4 { cand = parts[len(parts)-2] break } } } } } if validHwidRe.MatchString(cand) { return cand } host, _ := os.Hostname() sum := sha256.Sum256([]byte(host + "|" + runtime.GOOS + "|" + runtime.GOARCH)) return hex.EncodeToString(sum[:16]) } ``` ### 11. Go Example - Filename: `sdk/example_go.go` - Direct Download: `https://psycho-key.com/sdk-file.php?name=example_go.go` ```go // Psycho Key SDK — Go example integration // Place psychokey.go in package psychokey and run from your main module. package main import ( "bufio" "fmt" "os" "strings" "time" "example/psychokey" ) func main() { client, err := psychokey.NewClient(psychokey.Config{ App: "my-app", ApiSecret: "REPLACE_WITH_64_HEX_PRODUCT_SECRET", Version: "1.0.0", }) if err != nil { panic(err) } fmt.Println("HWID:", client.HWID()) hs := client.Init() if !hs.Ok { fmt.Printf("Handshake failed: %s — %s\n", hs.Code, hs.Message) return } fmt.Println("Server reachable") reader := bufio.NewReader(os.Stdin) fmt.Print("Enter license key: ") key, _ := reader.ReadString('\n') key = strings.TrimSpace(key) res := client.Auth(key) if !res.Ok { fmt.Printf("Access denied: %s — %s\n", res.Code, res.Message) if res.Code == "HWID_LIMIT" || res.Code == "HWID_MISMATCH" { fmt.Print("Reset HWID? [y/N]: ") ans, _ := reader.ReadString('\n') if strings.EqualFold(strings.TrimSpace(ans), "y") { res = client.ResetHWID(key) if !res.Ok { fmt.Println("Reset failed:", res.Code) return } } else { return } } else { return } } fmt.Printf("License accepted (%s)\n", res.License.Status) for i := 0; i < 3; i++ { time.Sleep(3 * time.Second) hb := client.Heartbeat() if !hb.Ok { fmt.Println("Session invalidated:", hb.Code) return } fmt.Printf("Heartbeat OK (%ds left)\n", hb.License.SecondsLeft) } client.Logout() fmt.Println("Done.") } ``` ### 12. Rust SDK (aes-gcm, hkdf, hmac, sha2, reqwest) - Filename: `sdk/psychokey.rs` - Direct Download: `https://psycho-key.com/sdk-file.php?name=psychokey.rs` ```rust //! Psycho Key — Rust SDK (v2 AES-256-GCM protocol) //! //! Add to Cargo.toml: //! [dependencies] //! aes-gcm = "0.10" //! base64 = "0.22" //! hex = "0.4" //! hkdf = "0.12" //! hmac = "0.12" //! rand = "0.8" //! reqwest = { version = "0.12", features = ["blocking", "json"] } //! serde = { version = "1", features = ["derive"] } //! serde_json = "1" //! sha2 = "0.10" use aes_gcm::{ aead::{Aead, KeyInit, Payload}, Aes256Gcm, Nonce, }; use base64::{engine::general_purpose::STANDARD as B64, Engine as _}; use hkdf::Hkdf; use hmac::{Hmac, Mac}; use rand::RngCore; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::HashMap; use std::process::Command; use std::time::{Duration, SystemTime, UNIX_EPOCH}; type HmacSha256 = Hmac; const HKDF_SALT: &[u8] = b"psychokey-salt-v1"; #[derive(Clone, Debug)] pub struct Config { pub base_url: String, pub app: String, pub api_secret: String, pub version: String, pub require_v2: bool, } impl Config { pub fn new(app: &str, api_secret: &str) -> Self { Self { base_url: "https://psycho-key.com".to_string(), app: app.to_string(), api_secret: api_secret.to_string(), version: "1.0.0".to_string(), require_v2: true, } } } #[derive(Clone, Debug, Default, Deserialize)] pub struct License { #[serde(default)] pub id: i64, #[serde(default)] pub status: String, #[serde(default, rename = "duration")] pub duration_days: i32, #[serde(default)] pub duration_seconds: i32, #[serde(default)] pub max_hwids: i32, #[serde(default)] pub activated_at: Option, #[serde(default)] pub expires_at: Option, #[serde(default)] pub days_left: Option, #[serde(default)] pub seconds_left: Option, #[serde(default)] pub lifetime: bool, } #[derive(Clone, Debug, Default)] pub struct ClientResult { pub ok: bool, pub code: String, pub message: String, pub token: String, pub retry_after: i64, pub latest_version: String, pub download_url: String, pub variables: HashMap, pub license: License, } #[derive(Serialize)] struct InnerReq<'a> { action: &'a str, nonce: &'a str, ts: i64, hwid: &'a str, license_key: &'a str, token: &'a str, version: &'a str, sig: &'a str, } #[derive(Serialize)] struct EnvelopeReq<'a> { app: &'a str, v: u8, iv: String, ct: String, tag: String, } pub struct Client { config: Config, secret: Vec, hwid: String, token: String, vars: HashMap, http: reqwest::blocking::Client, } impl Client { pub fn new(config: Config) -> Result { let secret = hex::decode(config.api_secret.trim()) .map_err(|_| "api_secret must be 64 hex chars".to_string())?; if secret.len() != 32 { return Err("api_secret must decode to 32 bytes".to_string()); } let http = reqwest::blocking::Client::builder() .timeout(Duration::from_secs(15)) .build() .map_err(|e| e.to_string())?; Ok(Self { config, secret, hwid: detect_hwid(), token: String::new(), vars: HashMap::new(), http, }) } pub fn hwid(&self) -> &str { &self.hwid } pub fn var(&self, key: &str) -> &str { self.vars.get(key).map(|s| s.as_str()).unwrap_or("") } pub fn init(&mut self) -> ClientResult { self.call("init", "") } pub fn auth(&mut self, license_key: &str) -> ClientResult { let res = self.call("license", license_key); if res.ok && !res.token.is_empty() { self.token = res.token.clone(); } for (k, v) in &res.variables { self.vars.insert(k.clone(), v.clone()); } res } pub fn heartbeat(&mut self) -> ClientResult { let res = self.call("heartbeat", ""); if res.ok && !res.token.is_empty() { self.token = res.token.clone(); } for (k, v) in &res.variables { self.vars.insert(k.clone(), v.clone()); } res } pub fn logout(&mut self) -> ClientResult { let res = self.call("logout", ""); self.token.clear(); res } pub fn reset_hwid(&mut self, license_key: &str) -> ClientResult { let res = self.call("reset", license_key); if res.ok && !res.token.is_empty() { self.token = res.token.clone(); } for (k, v) in &res.variables { self.vars.insert(k.clone(), v.clone()); } res } fn call(&self, action: &str, license_key: &str) -> ClientResult { let mut out = ClientResult::default(); let mut nonce_bytes = [0u8; 16]; rand::thread_rng().fill_bytes(&mut nonce_bytes); let nonce = hex::encode(nonce_bytes); let ts = SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_secs() as i64) .unwrap_or(0); let canonical = format!( "{}|{}|{}|{}|{}|{}|{}", self.config.app, action, nonce, ts, self.hwid, license_key, self.token ); let mut mac = ::new_from_slice(&self.secret).expect("HMAC key"); mac.update(canonical.as_bytes()); let sig = hex::encode(mac.finalize().into_bytes()); let inner = serde_json::to_string(&InnerReq { action, nonce: &nonce, ts, hwid: &self.hwid, license_key, token: &self.token, version: &self.config.version, sig: &sig, }) .unwrap_or_default(); let req_key = hkdf_key(&self.secret, &format!("psychokey-req-v2|{}", self.config.app)); let cipher = Aes256Gcm::new_from_slice(&req_key).expect("AES key"); let mut iv = [0u8; 12]; rand::thread_rng().fill_bytes(&mut iv); let sealed = match cipher.encrypt( Nonce::from_slice(&iv), Payload { msg: inner.as_bytes(), aad: self.config.app.as_bytes(), }, ) { Ok(v) => v, Err(_) => { out.code = "CLIENT_CRYPTO".to_string(); return out; } }; let split = sealed.len().saturating_sub(16); let env = EnvelopeReq { app: &self.config.app, v: 2, iv: B64.encode(iv), ct: B64.encode(&sealed[..split]), tag: B64.encode(&sealed[split..]), }; let url = format!("{}/api/v1.php", self.config.base_url.trim_end_matches('/')); let resp_text = match self .http .post(&url) .header("User-Agent", format!("PsychoKey-Rust/{}", self.config.version)) .json(&env) .send() .and_then(|r| r.text()) { Ok(t) => t, Err(e) => { out.code = "NETWORK".to_string(); out.message = e.to_string(); return out; } }; let root: serde_json::Value = match serde_json::from_str(&resp_text) { Ok(v) => v, Err(_) => { out.code = "CLIENT_PARSE".to_string(); return out; } }; let mut encrypted = false; let payload: serde_json::Value = if root.get("v").and_then(|v| v.as_i64()) == Some(2) { encrypted = true; let r_iv = B64.decode(root.get("iv").and_then(|s| s.as_str()).unwrap_or("")).unwrap_or_default(); let r_ct = B64.decode(root.get("ct").and_then(|s| s.as_str()).unwrap_or("")).unwrap_or_default(); let r_tag = B64.decode(root.get("tag").and_then(|s| s.as_str()).unwrap_or("")).unwrap_or_default(); if r_iv.len() != 12 || r_tag.len() != 16 { out.code = "CLIENT_INTEGRITY".to_string(); return out; } let resp_key = hkdf_key(&self.secret, &format!("psychokey-resp-v2|{}", self.config.app)); let dec_cipher = Aes256Gcm::new_from_slice(&resp_key).expect("AES key"); let mut joined = r_ct; joined.extend_from_slice(&r_tag); let aad = format!("{}|{}|{}", self.config.app, action, nonce); let plain = match dec_cipher.decrypt( Nonce::from_slice(&r_iv), Payload { msg: &joined, aad: aad.as_bytes(), }, ) { Ok(p) => p, Err(_) => { out.code = "CLIENT_INTEGRITY".to_string(); out.message = "Response authentication failed.".to_string(); return out; } }; match serde_json::from_slice(&plain) { Ok(v) => v, Err(_) => { out.code = "CLIENT_PARSE".to_string(); return out; } } } else { if self.config.require_v2 && root.get("success").and_then(|v| v.as_bool()) == Some(true) { out.code = "CLIENT_INTEGRITY".to_string(); out.message = "Unencrypted success rejected.".to_string(); return out; } root }; if encrypted { if let Some(resp_ts) = payload.get("ts").and_then(|v| v.as_i64()) { if resp_ts > 0 && (resp_ts - ts).abs() > 300 { out.code = "CLIENT_INTEGRITY".to_string(); out.message = "Response timestamp outside allowed window.".to_string(); return out; } } } out.ok = payload.get("success").and_then(|v| v.as_bool()).unwrap_or(false); out.code = payload .get("code") .and_then(|v| v.as_str()) .unwrap_or(if out.ok { "OK" } else { "ERROR" }) .to_string(); out.message = payload.get("message").and_then(|v| v.as_str()).unwrap_or("").to_string(); out.retry_after = payload.get("retry_after").and_then(|v| v.as_i64()).unwrap_or(0); out.latest_version = payload.get("latest_version").and_then(|v| v.as_str()).unwrap_or("").to_string(); out.download_url = payload.get("download_url").and_then(|v| v.as_str()).unwrap_or("").to_string(); if let Some(obj) = payload.get("variables").and_then(|v| v.as_object()) { for (k, v) in obj { if let Some(s) = v.as_str() { out.variables.insert(k.clone(), s.to_string()); } } } if out.ok { out.token = payload.get("token").and_then(|v| v.as_str()).unwrap_or("").to_string(); if let Some(lic) = payload.get("license") { if let Ok(parsed) = serde_json::from_value::(lic.clone()) { out.license = parsed; } } } out } } fn hkdf_key(secret: &[u8], info: &str) -> [u8; 32] { let hk = Hkdf::::new(Some(HKDF_SALT), secret); let mut okm = [0u8; 32]; hk.expand(info.as_bytes(), &mut okm).expect("HKDF expand"); okm } fn valid_hwid(s: &str) -> bool { (8..=128).contains(&s.len()) && s.bytes() .all(|b| b.is_ascii_alphanumeric() || b == b':' || b == b'_' || b == b'-') } fn detect_hwid() -> String { let mut cand = String::new(); #[cfg(target_os = "windows")] if let Ok(out) = Command::new("wmic").args(["csproduct", "get", "UUID"]).output() { for line in String::from_utf8_lossy(&out.stdout).lines() { let t = line.trim(); if !t.is_empty() && t != "UUID" { cand = t.to_string(); break; } } } #[cfg(target_os = "linux")] for path in ["/etc/machine-id", "/var/lib/dbus/machine-id"] { if let Ok(text) = std::fs::read_to_string(path) { let t = text.trim(); if !t.is_empty() { cand = t.to_string(); break; } } } #[cfg(target_os = "macos")] if let Ok(out) = Command::new("ioreg").args(["-rd1", "-c", "IOPlatformExpertDevice"]).output() { for line in String::from_utf8_lossy(&out.stdout).lines() { if line.contains("IOPlatformUUID") { let parts: Vec<&str> = line.split('"').collect(); if parts.len() >= 4 { cand = parts[parts.len() - 2].to_string(); break; } } } } if valid_hwid(&cand) { return cand; } let mut h = Sha256::new(); h.update(std::env::consts::OS.as_bytes()); h.update(b"|"); h.update(std::env::consts::ARCH.as_bytes()); if let Ok(host) = std::env::var("COMPUTERNAME").or_else(|_| std::env::var("HOSTNAME")) { h.update(b"|"); h.update(host.as_bytes()); } hex::encode(&h.finalize()[..16]) } ``` ### 13. Rust Example - Filename: `sdk/example_rust.rs` - Direct Download: `https://psycho-key.com/sdk-file.php?name=example_rust.rs` ```rust //! Psycho Key SDK — Rust example integration mod psychokey; use psychokey::{Client, Config}; use std::io::{self, Write}; use std::thread; use std::time::Duration; fn main() { let mut cfg = Config::new("my-app", "REPLACE_WITH_64_HEX_PRODUCT_SECRET"); cfg.version = "1.0.0".to_string(); let mut client = Client::new(cfg).expect("invalid secret"); println!("HWID: {}\n", client.hwid()); let hs = client.init(); if !hs.ok { eprintln!("Handshake failed: {} — {}", hs.code, hs.message); return; } print!("Enter license key: "); let _ = io::stdout().flush(); let mut key = String::new(); let _ = io::stdin().read_line(&mut key); let key = key.trim(); let mut res = client.auth(key); if !res.ok { eprintln!("Access denied: {} — {}", res.code, res.message); if res.code == "HWID_LIMIT" || res.code == "HWID_MISMATCH" { print!("Reset HWID? [y/N]: "); let _ = io::stdout().flush(); let mut ans = String::new(); let _ = io::stdin().read_line(&mut ans); if ans.trim().eq_ignore_ascii_case("y") { res = client.reset_hwid(key); if !res.ok { eprintln!("Reset failed: {}", res.code); return; } } else { return; } } else { return; } } println!("License accepted ({})", res.license.status); for _ in 0..3 { thread::sleep(Duration::from_secs(3)); let hb = client.heartbeat(); if !hb.ok { eprintln!("Session invalidated: {}", hb.code); return; } println!("Heartbeat OK"); } client.logout(); } ``` ### 14. Java 11+ / Android SDK (Stdlib only — zero JAR deps) - Filename: `sdk/PsychoKey.java` - Direct Download: `https://psycho-key.com/sdk-file.php?name=PsychoKey.java` ```java // Psycho Key — Java SDK (v2 AES-256-GCM protocol) // Requires Java 11+ standard library only (zero external dependencies). // Build: javac PsychoKey.java ExampleJava.java && java ExampleJava import javax.crypto.Cipher; import javax.crypto.Mac; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.MessageDigest; import java.security.SecureRandom; import java.time.Duration; import java.time.Instant; import java.util.Base64; import java.util.LinkedHashMap; import java.util.Map; public final class PsychoKey { public static final class Config { public String baseUrl = "https://psycho-key.com"; public String app = ""; public String apiSecret = ""; public String version = "1.0.0"; public boolean requireV2 = true; public Config(String app, String apiSecret) { this.app = app; this.apiSecret = apiSecret; } } public static final class License { public long id; public String status = ""; public int durationDays; public int durationSeconds; public int maxHwids; public String activatedAt = ""; public String expiresAt = ""; public int daysLeft = -1; public long secondsLeft = -1; public boolean lifetime; } public static final class Result { public boolean ok; public String code = ""; public String message = ""; public String token = ""; public int retryAfter; public String latestVersion = ""; public String downloadUrl = ""; public final Map variables = new LinkedHashMap<>(); public License license = new License(); } public static final class Client { private static final String HKDF_SALT = "psychokey-salt-v1"; private static final SecureRandom RNG = new SecureRandom(); private final Config config; private final byte[] secret; private final String hwid; private final HttpClient http; private final Map vars = new LinkedHashMap<>(); private String token = ""; public Client(Config config) { this.config = config; this.secret = hexDecode(config.apiSecret.trim()); if (this.secret.length != 32) { throw new IllegalArgumentException("apiSecret must be 64 hex chars (32 bytes)"); } this.hwid = detectHwid(); this.http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(15)).build(); } public String hwid() { return hwid; } public String var(String key) { return vars.getOrDefault(key, ""); } public Result init() { return call("init", ""); } public Result auth(String licenseKey) { Result r = call("license", licenseKey); if (r.ok && !r.token.isEmpty()) token = r.token; vars.putAll(r.variables); return r; } public Result heartbeat() { Result r = call("heartbeat", ""); if (r.ok && !r.token.isEmpty()) token = r.token; vars.putAll(r.variables); return r; } public Result logout() { Result r = call("logout", ""); token = ""; return r; } public Result resetHwid(String licenseKey) { Result r = call("reset", licenseKey); if (r.ok && !r.token.isEmpty()) token = r.token; vars.putAll(r.variables); return r; } private Result call(String action, String licenseKey) { Result out = new Result(); try { byte[] nonceBytes = new byte[16]; RNG.nextBytes(nonceBytes); String nonce = hexEncode(nonceBytes); long ts = Instant.now().getEpochSecond(); String canonical = String.join("|", config.app, action, nonce, Long.toString(ts), hwid, licenseKey, token); String sig = hexEncode(hmacSha256(secret, canonical.getBytes(StandardCharsets.UTF_8))); String inner = "{" + "\"action\":\"" + jsonEscape(action) + "\"" + ",\"nonce\":\"" + nonce + "\"" + ",\"ts\":" + ts + ",\"hwid\":\"" + jsonEscape(hwid) + "\"" + ",\"license_key\":\"" + jsonEscape(licenseKey) + "\"" + ",\"token\":\"" + jsonEscape(token) + "\"" + ",\"version\":\"" + jsonEscape(config.version) + "\"" + ",\"sig\":\"" + sig + "\"}"; byte[] reqKey = hkdfSha256(secret, HKDF_SALT, "psychokey-req-v2|" + config.app, 32); byte[] iv = new byte[12]; RNG.nextBytes(iv); Cipher enc = Cipher.getInstance("AES/GCM/NoPadding"); enc.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(reqKey, "AES"), new GCMParameterSpec(128, iv)); enc.updateAAD(config.app.getBytes(StandardCharsets.UTF_8)); byte[] sealed = enc.doFinal(inner.getBytes(StandardCharsets.UTF_8)); int split = sealed.length - 16; byte[] ct = new byte[split]; byte[] tag = new byte[16]; System.arraycopy(sealed, 0, ct, 0, split); System.arraycopy(sealed, split, tag, 0, 16); Base64.Encoder b64e = Base64.getEncoder(); String env = "{" + "\"app\":\"" + jsonEscape(config.app) + "\"" + ",\"v\":2" + ",\"iv\":\"" + b64e.encodeToString(iv) + "\"" + ",\"ct\":\"" + b64e.encodeToString(ct) + "\"" + ",\"tag\":\"" + b64e.encodeToString(tag) + "\"}"; String url = config.baseUrl.replaceAll("/+$", "") + "/api/v1.php"; HttpRequest req = HttpRequest.newBuilder(URI.create(url)) .timeout(Duration.ofSeconds(15)) .header("Content-Type", "application/json") .header("User-Agent", "PsychoKey-Java/" + config.version) .POST(HttpRequest.BodyPublishers.ofString(env, StandardCharsets.UTF_8)) .build(); HttpResponse resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); Map root = JsonMini.parseObject(resp.body()); Map payload; boolean encrypted = false; if (JsonMini.asLong(root.get("v"), 0) == 2L) { encrypted = true; Base64.Decoder b64d = Base64.getDecoder(); byte[] rIv = b64d.decode(JsonMini.asStr(root.get("iv"))); byte[] rCt = b64d.decode(JsonMini.asStr(root.get("ct"))); byte[] rTag = b64d.decode(JsonMini.asStr(root.get("tag"))); byte[] joined = new byte[rCt.length + rTag.length]; System.arraycopy(rCt, 0, joined, 0, rCt.length); System.arraycopy(rTag, 0, joined, rCt.length, rTag.length); byte[] respKey = hkdfSha256(secret, HKDF_SALT, "psychokey-resp-v2|" + config.app, 32); Cipher dec = Cipher.getInstance("AES/GCM/NoPadding"); dec.init(Cipher.DECRYPT_MODE, new SecretKeySpec(respKey, "AES"), new GCMParameterSpec(128, rIv)); dec.updateAAD((config.app + "|" + action + "|" + nonce).getBytes(StandardCharsets.UTF_8)); byte[] plain = dec.doFinal(joined); payload = JsonMini.parseObject(new String(plain, StandardCharsets.UTF_8)); } else { if (config.requireV2 && JsonMini.asBool(root.get("success"))) { out.code = "CLIENT_INTEGRITY"; out.message = "Unencrypted success rejected."; return out; } payload = root; } if (encrypted) { long respTs = JsonMini.asLong(payload.get("ts"), 0); if (respTs > 0 && Math.abs(respTs - ts) > 300) { out.code = "CLIENT_INTEGRITY"; out.message = "Response timestamp outside allowed window."; return out; } } out.ok = JsonMini.asBool(payload.get("success")); out.code = JsonMini.asStr(payload.get("code"), out.ok ? "OK" : "ERROR"); out.message = JsonMini.asStr(payload.get("message")); out.retryAfter = (int) JsonMini.asLong(payload.get("retry_after"), 0); out.latestVersion = JsonMini.asStr(payload.get("latest_version")); out.downloadUrl = JsonMini.asStr(payload.get("download_url")); Object vObj = payload.get("variables"); if (vObj instanceof Map) { for (Map.Entry e : ((Map) vObj).entrySet()) { if (e.getValue() instanceof String) { out.variables.put(String.valueOf(e.getKey()), (String) e.getValue()); } } } if (out.ok) { out.token = JsonMini.asStr(payload.get("token")); Object lObj = payload.get("license"); if (lObj instanceof Map) { @SuppressWarnings("unchecked") Map lm = (Map) lObj; out.license.id = JsonMini.asLong(lm.get("id"), 0); out.license.status = JsonMini.asStr(lm.get("status")); out.license.durationDays = (int) JsonMini.asLong(lm.get("duration"), 0); out.license.durationSeconds = (int) JsonMini.asLong(lm.get("duration_seconds"), 0); out.license.maxHwids = (int) JsonMini.asLong(lm.get("max_hwids"), 0); out.license.activatedAt = JsonMini.asStr(lm.get("activated_at")); out.license.expiresAt = JsonMini.asStr(lm.get("expires_at")); out.license.daysLeft = (int) JsonMini.asLong(lm.get("days_left"), -1); out.license.secondsLeft = JsonMini.asLong(lm.get("seconds_left"), -1); out.license.lifetime = JsonMini.asBool(lm.get("lifetime")); } } } catch (Exception ex) { out.code = "CLIENT_ERROR"; out.message = ex.getMessage() != null ? ex.getMessage() : ex.toString(); } return out; } private static byte[] hmacSha256(byte[] key, byte[] data) throws Exception { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key, "HmacSHA256")); return mac.doFinal(data); } private static byte[] hkdfSha256(byte[] ikm, String salt, String info, int len) throws Exception { byte[] prk = hmacSha256(salt.getBytes(StandardCharsets.UTF_8), ikm); byte[] infoB = info.getBytes(StandardCharsets.UTF_8); int n = (len + 31) / 32; byte[] okm = new byte[n * 32]; byte[] t = new byte[0]; for (int i = 1; i <= n; i++) { byte[] buf = new byte[t.length + infoB.length + 1]; System.arraycopy(t, 0, buf, 0, t.length); System.arraycopy(infoB, 0, buf, t.length, infoB.length); buf[buf.length - 1] = (byte) i; t = hmacSha256(prk, buf); System.arraycopy(t, 0, okm, (i - 1) * 32, 32); } byte[] out = new byte[len]; System.arraycopy(okm, 0, out, 0, len); return out; } private static String detectHwid() { String os = System.getProperty("os.name", "").toLowerCase(); String cand = ""; try { if (os.contains("win")) { Process p = new ProcessBuilder("wmic", "csproduct", "get", "UUID").start(); try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) { String line; while ((line = br.readLine()) != null) { String t = line.trim(); if (!t.isEmpty() && !t.equals("UUID")) { cand = t; break; } } } } else if (os.contains("nux") || os.contains("nix")) { for (String path : new String[]{"/etc/machine-id", "/var/lib/dbus/machine-id"}) { Path fp = Path.of(path); if (Files.isRegularFile(fp)) { String t = Files.readString(fp).trim(); if (!t.isEmpty()) { cand = t; break; } } } } else if (os.contains("mac")) { Process p = new ProcessBuilder("ioreg", "-rd1", "-c", "IOPlatformExpertDevice").start(); try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) { String line; while ((line = br.readLine()) != null) { if (line.contains("IOPlatformUUID")) { String[] parts = line.split("\""); if (parts.length >= 4) { cand = parts[parts.length - 2]; break; } } } } } } catch (Exception ignored) {} if (cand.matches("^[A-Za-z0-9:_-]{8,128}$")) return cand; try { String raw = System.getenv("COMPUTERNAME") + "|" + os + "|" + System.getProperty("os.arch", ""); byte[] d = MessageDigest.getInstance("SHA-256").digest(raw.getBytes(StandardCharsets.UTF_8)); return hexEncode(d).substring(0, 32); } catch (Exception e) { return "java_fallback_hwid_01"; } } private static String jsonEscape(String s) { if (s == null) return ""; StringBuilder sb = new StringBuilder(s.length()); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '\\': sb.append("\\\\"); break; case '"': sb.append("\\\""); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; default: if (c < 0x20) sb.append(String.format("\\u%04x", (int) c)); else sb.append(c); } } return sb.toString(); } private static byte[] hexDecode(String hex) { if (hex.length() % 2 != 0) return new byte[0]; byte[] out = new byte[hex.length() / 2]; for (int i = 0; i < out.length; i++) { out[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16); } return out; } private static String hexEncode(byte[] b) { StringBuilder sb = new StringBuilder(b.length * 2); for (byte x : b) sb.append(String.format("%02x", x)); return sb.toString(); } } /** Tiny self-contained JSON parser so zero external JARs are needed. */ static final class JsonMini { private final String s; private int i; private JsonMini(String s) { this.s = s; } @SuppressWarnings("unchecked") static Map parseObject(String json) { Object v = new JsonMini(json).readValue(); return v instanceof Map ? (Map) v : new LinkedHashMap<>(); } static String asStr(Object o) { return asStr(o, ""); } static String asStr(Object o, String def) { return o instanceof String ? (String) o : def; } static boolean asBool(Object o) { return o instanceof Boolean && (Boolean) o; } static long asLong(Object o, long def) { return o instanceof Number ? ((Number) o).longValue() : def; } private void ws() { while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++; } private Object readValue() { ws(); if (i >= s.length()) return null; char c = s.charAt(i); if (c == '{') return readObject(); if (c == '[') return readArray(); if (c == '"') return readString(); if (c == 't' && s.startsWith("true", i)) { i += 4; return Boolean.TRUE; } if (c == 'f' && s.startsWith("false", i)) { i += 5; return Boolean.FALSE; } if (c == 'n' && s.startsWith("null", i)) { i += 4; return null; } return readNumber(); } private Map readObject() { Map map = new LinkedHashMap<>(); i++; ws(); if (i < s.length() && s.charAt(i) == '}') { i++; return map; } while (i < s.length()) { ws(); String key = readString(); ws(); if (i < s.length() && s.charAt(i) == ':') i++; map.put(key, readValue()); ws(); if (i < s.length() && s.charAt(i) == ',') { i++; continue; } if (i < s.length() && s.charAt(i) == '}') { i++; break; } break; } return map; } private Object readArray() { var list = new java.util.ArrayList(); i++; ws(); if (i < s.length() && s.charAt(i) == ']') { i++; return list; } while (i < s.length()) { list.add(readValue()); ws(); if (i < s.length() && s.charAt(i) == ',') { i++; continue; } if (i < s.length() && s.charAt(i) == ']') { i++; break; } break; } return list; } private String readString() { if (i >= s.length() || s.charAt(i) != '"') return ""; i++; StringBuilder sb = new StringBuilder(); while (i < s.length()) { char c = s.charAt(i++); if (c == '"') break; if (c == '\\' && i < s.length()) { char e = s.charAt(i++); switch (e) { case '"': case '\\': case '/': sb.append(e); break; case 'b': sb.append('\b'); break; case 'f': sb.append('\f'); break; case 'n': sb.append('\n'); break; case 'r': sb.append('\r'); break; case 't': sb.append('\t'); break; case 'u': if (i + 4 <= s.length()) { sb.append((char) Integer.parseInt(s.substring(i, i + 4), 16)); i += 4; } break; default: sb.append(e); } } else { sb.append(c); } } return sb.toString(); } private Number readNumber() { int start = i; while (i < s.length() && "-0123456789.eE+".indexOf(s.charAt(i)) >= 0) i++; String raw = s.substring(start, i); try { if (raw.contains(".") || raw.contains("e") || raw.contains("E")) return Double.parseDouble(raw); return Long.parseLong(raw); } catch (Exception e) { return 0L; } } } } ``` ### 15. Java Example - Filename: `sdk/ExampleJava.java` - Direct Download: `https://psycho-key.com/sdk-file.php?name=ExampleJava.java` ```java // Psycho Key SDK — Java example integration // Compile & run: javac PsychoKey.java ExampleJava.java && java ExampleJava import java.util.Scanner; public class ExampleJava { public static void main(String[] args) throws Exception { PsychoKey.Config cfg = new PsychoKey.Config( "my-app", "REPLACE_WITH_64_HEX_PRODUCT_SECRET" ); cfg.version = "1.0.0"; PsychoKey.Client client = new PsychoKey.Client(cfg); System.out.println("HWID: " + client.hwid()); PsychoKey.Result hs = client.init(); if (!hs.ok) { System.out.println("Handshake failed: " + hs.code + " — " + hs.message); return; } Scanner sc = new Scanner(System.in); System.out.print("Enter license key: "); String key = sc.nextLine().trim(); PsychoKey.Result res = client.auth(key); if (!res.ok) { System.out.println("Access denied: " + res.code + " — " + res.message); if ("HWID_LIMIT".equals(res.code) || "HWID_MISMATCH".equals(res.code)) { System.out.print("Reset HWID? [y/N]: "); if ("y".equalsIgnoreCase(sc.nextLine().trim())) { res = client.resetHwid(key); if (!res.ok) { System.out.println("Reset failed: " + res.code); return; } } else { return; } } else { return; } } System.out.println("License accepted (" + res.license.status + ")"); for (int i = 0; i < 3; i++) { Thread.sleep(3000); PsychoKey.Result hb = client.heartbeat(); if (!hb.ok) { System.out.println("Session lost: " + hb.code); return; } System.out.println("Heartbeat OK (" + hb.license.secondsLeft + "s left)"); } client.logout(); System.out.println("Done."); } } ``` ### 16. PHP 8.1+ Client SDK (ext-openssl + ext-curl) - Filename: `sdk/psychokey.php` - Direct Download: `https://psycho-key.com/sdk-file.php?name=psychokey.php` ```php auth('PSYCHO-XXXX-XXXX-XXXX-XXXX', $machineOrSessionId); * if (!$res['ok']) { die($res['code']); } */ final class PsychoKeyClient { private const HKDF_SALT = 'psychokey-salt-v1'; private string $secret; private string $token = ''; private string $hwid; /** @var array */ private array $vars = []; public function __construct( private string $app, string $apiSecretHex, private string $baseUrl = 'https://psycho-key.com', private string $version = '1.0.0', private bool $requireV2 = true, ?string $hwid = null ) { $bin = @hex2bin(trim($apiSecretHex)); if ($bin === false || strlen($bin) !== 32) { throw new InvalidArgumentException('API secret must be 64 hex chars (32 bytes).'); } $this->secret = $bin; $this->baseUrl = rtrim($baseUrl, '/'); $this->hwid = ($hwid !== null && preg_match('/^[A-Za-z0-9:_\-]{8,128}$/', $hwid)) ? $hwid : substr(hash('sha256', php_uname('n') . '|' . PHP_OS_FAMILY), 0, 32); } public function hwid(): string { return $this->hwid; } public function var(string $key, string $default = ''): string { return $this->vars[$key] ?? $default; } public function init(): array { return $this->call('init'); } public function auth(string $licenseKey, ?string $customHwid = null): array { if ($customHwid !== null && preg_match('/^[A-Za-z0-9:_\-]{8,128}$/', $customHwid)) { $this->hwid = $customHwid; } $r = $this->call('license', $licenseKey); if ($r['ok'] && $r['token'] !== '') { $this->token = $r['token']; } $this->vars = array_merge($this->vars, $r['variables']); return $r; } public function heartbeat(): array { $r = $this->call('heartbeat'); if ($r['ok'] && $r['token'] !== '') { $this->token = $r['token']; } $this->vars = array_merge($this->vars, $r['variables']); return $r; } public function logout(): array { $r = $this->call('logout'); $this->token = ''; return $r; } public function resetHwid(string $licenseKey): array { $r = $this->call('reset', $licenseKey); if ($r['ok'] && $r['token'] !== '') { $this->token = $r['token']; } $this->vars = array_merge($this->vars, $r['variables']); return $r; } private function call(string $action, string $licenseKey = ''): array { $out = [ 'ok' => false, 'code' => 'CLIENT_ERROR', 'message' => '', 'token' => '', 'retry_after' => 0, 'latest_version' => '', 'download_url' => '', 'variables' => [], 'license' => [], ]; $nonce = bin2hex(random_bytes(16)); $ts = time(); $canonical = implode('|', [$this->app, $action, $nonce, (string)$ts, $this->hwid, $licenseKey, $this->token]); $sig = hash_hmac('sha256', $canonical, $this->secret); $inner = json_encode([ 'action' => $action, 'nonce' => $nonce, 'ts' => $ts, 'hwid' => $this->hwid, 'license_key' => $licenseKey, 'token' => $this->token, 'version' => $this->version, 'sig' => $sig, ], JSON_UNESCAPED_SLASHES); $reqKey = hash_hkdf('sha256', $this->secret, 32, 'psychokey-req-v2|' . $this->app, self::HKDF_SALT); $iv = random_bytes(12); $tag = ''; $ct = openssl_encrypt((string)$inner, 'aes-256-gcm', $reqKey, OPENSSL_RAW_DATA, $iv, $tag, $this->app, 16); if ($ct === false) { $out['code'] = 'CLIENT_CRYPTO'; return $out; } $envelope = json_encode([ 'app' => $this->app, 'v' => 2, 'iv' => base64_encode($iv), 'ct' => base64_encode($ct), 'tag' => base64_encode($tag), ], JSON_UNESCAPED_SLASHES); $ch = curl_init($this->baseUrl . '/api/v1.php'); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => $envelope, CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'User-Agent: PsychoKey-PHP/' . $this->version], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, ]); $resp = curl_exec($ch); $err = curl_error($ch); curl_close($ch); if (!is_string($resp)) { $out['code'] = 'NETWORK'; $out['message'] = $err; return $out; } $root = json_decode($resp, true); if (!is_array($root)) { $out['code'] = 'CLIENT_PARSE'; return $out; } $encrypted = false; if (($root['v'] ?? 0) === 2) { $encrypted = true; $respKey = hash_hkdf('sha256', $this->secret, 32, 'psychokey-resp-v2|' . $this->app, self::HKDF_SALT); $rIv = base64_decode((string)($root['iv'] ?? ''), true); $rCt = base64_decode((string)($root['ct'] ?? ''), true); $rTag = base64_decode((string)($root['tag'] ?? ''), true); if ($rIv === false || $rCt === false || $rTag === false || strlen($rIv) !== 12 || strlen($rTag) !== 16) { $out['code'] = 'CLIENT_INTEGRITY'; return $out; } $aad = $this->app . '|' . $action . '|' . $nonce; $plain = openssl_decrypt($rCt, 'aes-256-gcm', $respKey, OPENSSL_RAW_DATA, $rIv, $rTag, $aad); if ($plain === false) { $out['code'] = 'CLIENT_INTEGRITY'; $out['message'] = 'Response authentication failed.'; return $out; } $payload = json_decode($plain, true); if (!is_array($payload)) { $out['code'] = 'CLIENT_PARSE'; return $out; } } else { if ($this->requireV2 && !empty($root['success'])) { $out['code'] = 'CLIENT_INTEGRITY'; $out['message'] = 'Unencrypted success rejected.'; return $out; } $payload = $root; } if ($encrypted && isset($payload['ts']) && abs((int)$payload['ts'] - $ts) > 300) { $out['code'] = 'CLIENT_INTEGRITY'; return $out; } $out['ok'] = (bool)($payload['success'] ?? false); $out['code'] = (string)($payload['code'] ?? ($out['ok'] ? 'OK' : 'ERROR')); $out['message'] = (string)($payload['message'] ?? ''); $out['retry_after'] = (int)($payload['retry_after'] ?? 0); $out['latest_version'] = (string)($payload['latest_version'] ?? ''); $out['download_url'] = (string)($payload['download_url'] ?? ''); if (is_array($payload['variables'] ?? null)) { foreach ($payload['variables'] as $k => $v) { if (is_scalar($v)) { $out['variables'][(string)$k] = (string)$v; } } } if ($out['ok']) { $out['token'] = (string)($payload['token'] ?? ''); if (is_array($payload['license'] ?? null)) { $out['license'] = $payload['license']; } } return $out; } } ```