Files
calendar/packages/trpc/server/routers/viewer/admin/createSelfHostedLicenseKey.handler.ts
T
2a41cd0770 feat: license creation admin PR (#15024)
* WIP: UI created to see if it matches RFC idea

* Remove schema as we validate on the backend with old+new key schemas

* Add comment about proxy URL request when on older versions

* feat: create custom axios instance to use signature middleware

* fix: update form to respect new schema

* Add cal signature token to trubo env

* use backend mutation for creating license keys

* add loading state to creation button

* update form to have a success state

* fix type error for console.warning :')

* use api version v1

* restore checkLicense from main

* Add env vars to example

* nit: rename page export

* use US spelling

---------

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2024-06-06 18:34:32 +00:00

78 lines
2.0 KiB
TypeScript

import * as crypto from "crypto";
import { z } from "zod";
import type { TrpcSessionUser } from "../../../trpc";
import type { TCreateSelfHostedLicenseSchema } from "./createSelfHostedLicenseKey.schema";
type GetOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TCreateSelfHostedLicenseSchema;
};
const generateNonce = (): string => {
return crypto.randomBytes(16).toString("hex");
};
// Utility function to create a signature
const createSignature = (body: Record<string, unknown>, nonce: string, secretKey: string): string => {
return crypto
.createHmac("sha256", secretKey)
.update(JSON.stringify(body) + nonce)
.digest("hex");
};
// Fetch wrapper function
const fetchWithSignature = async (
url: string,
body: Record<string, unknown>,
secretKey: string,
options: RequestInit = {}
): Promise<Response> => {
const nonce = generateNonce();
const signature = createSignature(body, nonce, secretKey);
const headers = {
...options.headers,
"Content-Type": "application/json",
nonce: nonce,
signature: signature,
};
return await fetch(url, {
...options,
method: "POST",
headers: headers,
body: JSON.stringify(body),
});
};
const createSelfHostedInstance = async ({ input, ctx }: GetOptions) => {
const privateApiUrl = process.env.CALCOM_PRIVATE_API_ROUTE;
const signatureToken = process.env.CAL_SIGNATURE_TOKEN;
if (!privateApiUrl || !signatureToken) {
throw new Error("Private Api route does not exist in .env");
}
// Ensure admin
if (ctx.user.role !== "ADMIN") {
console.warn(`${ctx.user.username} just tried to create a license key without permission`);
throw new Error("You do not have permission to do this.");
}
const request = await fetchWithSignature(`${privateApiUrl}/v1/license`, input, signatureToken, {
method: "POST",
});
const data = await request.json();
const schema = z.object({
stripeCheckoutUrl: z.string(),
});
return schema.parse(data);
};
export default createSelfHostedInstance;