smart_ims/server/utils/remoteLicense.js
2026-01-22 23:42:55 +09:00

71 lines
2.5 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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<boolean>} 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<void>}
*/
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 };