server.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. require('dotenv').config();
  2. const express = require('express');
  3. const mongoose = require('mongoose');
  4. const cors = require('cors');
  5. const crypto = require('crypto');
  6. const License = require('./models/License');
  7. const LicenseKey = require('./models/LicenseKey');
  8. const { formatChinaTime, getNowChinaTime, getNowChinaTimeString } = require('./utils/date');
  9. const app = express();
  10. // Middleware
  11. app.use(cors());
  12. app.use(express.json());
  13. // Encryption functions
  14. function getIV() {
  15. // 如果需要固定 IV(不推荐),可以从环境变量获取
  16. if (process.env.ENCRYPTION_IV) {
  17. return Buffer.from(process.env.ENCRYPTION_IV, 'hex');
  18. }
  19. // 否则生成随机 IV(更安全,但需要存储)
  20. return crypto.randomBytes(16);
  21. }
  22. function encryptLicenseKey(text) {
  23. const key = Buffer.from(process.env.ENCRYPTION_KEY, 'hex');
  24. const iv = getIV();
  25. const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
  26. let encrypted = cipher.update(text, 'utf8', 'hex');
  27. encrypted += cipher.final('hex');
  28. // 将 IV 附加到加密文本中,以便解密时使用
  29. return iv.toString('hex') + ':' + encrypted;
  30. }
  31. function decryptLicenseKey(encrypted) {
  32. const [ivHex, encryptedText] = encrypted.split(':');
  33. const key = Buffer.from(process.env.ENCRYPTION_KEY, 'hex');
  34. const iv = Buffer.from(ivHex, 'hex');
  35. const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
  36. let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
  37. decrypted += decipher.final('utf8');
  38. return decrypted;
  39. }
  40. function generateLicenseKey() {
  41. const randomBytes = crypto.randomBytes(16);
  42. const timestamp = Date.now().toString();
  43. const combined = randomBytes.toString('hex') + timestamp;
  44. const encrypted = encryptLicenseKey(combined);
  45. // 由于加密后的字符串现在包含 IV,我们需要使用完整的字符串
  46. return encrypted;
  47. }
  48. // 在现有的加密函数下添加新的响应加密函数
  49. function encryptResponse(data) {
  50. // 将对象转换为 JSON 字符串
  51. const jsonStr = JSON.stringify(data);
  52. const key = Buffer.from(process.env.ENCRYPTION_KEY, 'hex');
  53. const iv = getIV();
  54. const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
  55. let encrypted = cipher.update(jsonStr, 'utf8', 'hex');
  56. encrypted += cipher.final('hex');
  57. // 将 IV 附加到加密文本中
  58. return {
  59. encrypted_data: iv.toString('hex') + ':' + encrypted
  60. };
  61. }
  62. // Connect to MongoDB
  63. mongoose.connect(process.env.MONGODB_URI, {
  64. useNewUrlParser: true,
  65. useUnifiedTopology: true,
  66. serverSelectionTimeoutMS: 5000, // 超时时间
  67. socketTimeoutMS: 45000, // Socket 超时
  68. family: 4, // 强制使用 IPv4
  69. })
  70. .then(() => console.log('Connected to MongoDB'))
  71. .catch(err => {
  72. console.error('MongoDB connection error:', err);
  73. process.exit(1); // 如果连接失败,终止程序
  74. });
  75. // 添加连接错误处理
  76. mongoose.connection.on('error', err => {
  77. console.error('MongoDB connection error:', err);
  78. });
  79. mongoose.connection.on('disconnected', () => {
  80. console.log('MongoDB disconnected');
  81. });
  82. // 定义一个复杂的路径,可以放在环境变量中
  83. const GENERATE_PATH = process.env.GENERATE_PATH || 'xx-zz-yy-dd';
  84. // 在应用启动时输出生成路径(仅在控制台显示一次)
  85. console.log('License generation path:', GENERATE_PATH);
  86. // Generate license key endpoint
  87. app.post(`/${GENERATE_PATH}`, async (req, res) => {
  88. try {
  89. const licenseKey = generateLicenseKey();
  90. await LicenseKey.create({
  91. licenseKey: licenseKey,
  92. isUsed: false
  93. });
  94. // 加密响应数据
  95. const responseData = {
  96. success: true,
  97. license_key: licenseKey
  98. };
  99. return res.json(responseData);
  100. } catch (error) {
  101. console.error('生成许可证错误:', error);
  102. return res.status(500).json(encryptResponse({
  103. success: false,
  104. message: '服务器错误'
  105. }));
  106. }
  107. });
  108. // Activation endpoint
  109. app.post('/activate', async (req, res) => {
  110. try {
  111. const { license_key, machine_code, activation_date } = req.body;
  112. // Validate input
  113. if (!license_key || !machine_code) {
  114. return res.status(400).json({
  115. success: false,
  116. message: '许可证密钥和机器码是必需的'
  117. });
  118. }
  119. // Validate license key format
  120. try {
  121. decryptLicenseKey(license_key);
  122. } catch (error) {
  123. return res.status(400).json({
  124. success: false,
  125. message: '无效的许可证密钥'
  126. });
  127. }
  128. // 检查许可证是否存在于生成记录中
  129. const licenseKeyRecord = await LicenseKey.findOne({ licenseKey: license_key });
  130. if (!licenseKeyRecord) {
  131. return res.status(400).json({
  132. success: false,
  133. message: '无效的许可证密钥'
  134. });
  135. }
  136. // 检查许可证是否已被使用
  137. if (licenseKeyRecord.isUsed) {
  138. return res.status(400).json({
  139. success: false,
  140. message: '此许可证密钥已被使用,不能重复激活'
  141. });
  142. }
  143. // 检查许可证激活状态
  144. const existingLicense = await License.findOne({ licenseKey: license_key });
  145. if (existingLicense) {
  146. return res.status(400).json({
  147. success: false,
  148. message: '此许可证已被激活,不能重复使用'
  149. });
  150. }
  151. // 更新过期时间计算,使用中国时区
  152. const expiryDate = formatChinaTime(getNowChinaTime().add(1, 'month'), 'YYYY-MM-DD');
  153. await License.create([{
  154. licenseKey: license_key,
  155. machineCode: machine_code,
  156. activationDate: activation_date ? activation_date : getNowChinaTimeString(),
  157. expiryDate: expiryDate,
  158. isActive: true,
  159. maxUsageCount: process.env.MAX_USAGE_COUNT || 10,
  160. currentUsageCount: 1
  161. }]);
  162. // 更新许可证密钥状态为已使用
  163. licenseKeyRecord.isUsed = true;
  164. await licenseKeyRecord.save();
  165. const responseData = {
  166. success: true,
  167. message: '激活成功',
  168. expiry_date: expiryDate
  169. };
  170. return res.json(encryptResponse(responseData));
  171. } catch (error) {
  172. console.error('激活错误:', error);
  173. return res.status(500).json(encryptResponse({
  174. success: false,
  175. message: '服务器错误'
  176. }));
  177. }
  178. });
  179. // Verification endpoint
  180. app.post('/verify', async (req, res) => {
  181. try {
  182. const { license_key, machine_code } = req.body;
  183. // Validate input
  184. if (!license_key || !machine_code) {
  185. return res.status(400).json({
  186. success: false,
  187. message: '许可证密钥和机器码是必需的'
  188. });
  189. }
  190. // Validate license key format
  191. try {
  192. decryptLicenseKey(license_key);
  193. } catch (error) {
  194. return res.status(400).json({
  195. success: false,
  196. message: '无效的许可证密钥'
  197. });
  198. }
  199. // Find license
  200. const license = await License.findOne({ licenseKey: license_key });
  201. if (!license) {
  202. return res.status(404).json({
  203. success: false,
  204. message: '许可证不存在'
  205. });
  206. }
  207. // Check machine code
  208. if (license.machineCode !== machine_code) {
  209. return res.status(400).json({
  210. success: false,
  211. message: '硬件信息不匹配'
  212. });
  213. }
  214. // Check if license is active
  215. if (!license.isActive) {
  216. return res.status(400).json({
  217. success: false,
  218. message: '许可证已被禁用'
  219. });
  220. }
  221. // 使用中国时区检查过期时间
  222. if (getNowChinaTime().isAfter(license.expiryDate)) {
  223. return res.status(400).json({
  224. success: false,
  225. message: '许可证已过期'
  226. });
  227. }
  228. // 检查使用次数
  229. if (license.currentUsageCount >= license.maxUsageCount) {
  230. return res.status(400).json({
  231. success: false,
  232. message: '许可证使用次数已达到上限'
  233. });
  234. }
  235. // 更新使用次数
  236. license.currentUsageCount += 1;
  237. await license.save();
  238. const responseData = {
  239. success: true,
  240. message: '许可证有效',
  241. expiry_date: formatChinaTime(license.expiryDate, 'YYYY-MM-DD'),
  242. usage_count: {
  243. current: license.currentUsageCount,
  244. max: license.maxUsageCount
  245. }
  246. };
  247. return res.json(encryptResponse(responseData));
  248. } catch (error) {
  249. console.error('验证错误:', error);
  250. return res.status(500).json(encryptResponse({
  251. success: false,
  252. message: '服务器错误'
  253. }));
  254. }
  255. });
  256. const PORT = process.env.PORT || 3000;
  257. app.listen(PORT, () => {
  258. console.log(`Server is running on port ${PORT}`);
  259. });