// 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 };