From 59a3d40e1c2027b9ee67c3264ca8be3caa18631e Mon Sep 17 00:00:00 2001 From: Mathias Wagner Date: Tue, 23 Jul 2024 00:04:07 +0200 Subject: [PATCH] Create validation.ts#signOfflineKey --- src/controller/validation.ts | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/controller/validation.ts b/src/controller/validation.ts index 0124042..c587039 100644 --- a/src/controller/validation.ts +++ b/src/controller/validation.ts @@ -3,6 +3,7 @@ import { License } from "@models/License"; import { mapLicense } from "@controller/license"; import { Group } from "@models/Group"; import { Permission } from "@models/Permission"; +import {createSign} from "node:crypto"; enum ResponseStatus { VALID = "VALID", @@ -39,4 +40,29 @@ export const validateLicense = async (validationKey: string, licenseKey: string) await License.updateOne({ _id: license.id }, { currentUses: license.currentUses + 1 }); return { status: ResponseStatus.VALID, license: licenseData }; +} + +export const signOfflineKey = async (validationKey: string, licenseKey: string) => { + const license = await validateLicense(validationKey, licenseKey); + + if (license.status !== ResponseStatus.VALID) return { status: license.status, message: license.message, file: null}; + + const project = await Project.findOne({ validationKey }); + if (project === null) return { status: ResponseStatus.INVALID_KEY, message: "The provided validation key is invalid", file: null }; + + const signer = createSign("RSA-SHA256"); + + const renewalDate = new Date(); + renewalDate.setDate(renewalDate.getDate() + 7); // TODO: Let the user choose the renewal date + + signer.update(JSON.stringify({...license.license, renewalDate})); + + const signature = signer.sign(project.privateKey, "hex"); + + let content = JSON.stringify({signature, data: {...license.license, renewalDate}}); + content = Buffer.from(content).toString('base64').replace(/(.{64})/g, "$1\n"); + + const file = `-----BEGIN LICENSE KEY-----\n${content}\n-----END LICENSE KEY-----`; + + return { status: ResponseStatus.VALID, file }; } \ No newline at end of file