const mysql = require('mysql2/promise'); require('dotenv').config(); // Configuration for the "Vendor/Central" License Database const remoteConfig = { host: process.env.LICENSE_DB_HOST, user: process.env.LICENSE_DB_USER, password: process.env.LICENSE_DB_PASSWORD, database: process.env.LICENSE_DB_NAME, port: process.env.LICENSE_DB_PORT || 3306, connectTimeout: 5000 // 5 seconds timeout }; function isRemoteConfigured() { return !!(process.env.LICENSE_DB_HOST && process.env.LICENSE_DB_USER && process.env.LICENSE_DB_NAME); } /** * Connects to the Remote DB, checks if the key exists, and disconnects. * @param {string} key * @returns {Promise} valid */ async function checkRemoteKey(key) { if (!isRemoteConfigured()) { console.warn('⚠️ Remote License DB not configured. Skipping remote check.'); return true; // Use local check only if remote is not configured } let conn; try { conn = await mysql.createConnection(remoteConfig); const [rows] = await conn.execute('SELECT 1 FROM issued_licenses WHERE license_key = ? LIMIT 1', [key]); return rows.length > 0; } catch (err) { console.error('❌ Remote License Check Failed:', err.message); return false; // Fail safe: if we can't verify remotely, assume invalid (or valid? User wanted "management", so fail is safer) } finally { if (conn) await conn.end(); } } /** * Connects to Remote DB, inserts the generated key, and disconnects. * @param {object} licenseData { key, module, type } * @returns {Promise} */ async function registerRemoteKey({ key, module, type }) { if (!isRemoteConfigured()) { console.log('ℹ️ Remote License DB not configured. Key generated locally only.'); return; } let conn; try { conn = await mysql.createConnection(remoteConfig); const sql = ` INSERT INTO issued_licenses (license_key, module_code, license_type, created_at) VALUES (?, ?, ?, NOW()) `; await conn.execute(sql, [key, module, type]); console.log('✅ License Key registered to Central DB.'); } catch (err) { console.error('❌ Failed to register key to Central DB:', err.message); console.warn('⚠️ The key was generated but may not be activatable if the server enforces remote check.'); } finally { if (conn) await conn.end(); } } module.exports = { checkRemoteKey, registerRemoteKey };