feat(licenses): implement license management system with email notifications

- Added database schema for licenses, including types and statuses.
- Implemented license creation, validation, and activation functionalities.
- Integrated email templates for sending license keys and resend requests.
- Updated package dependencies and configuration for PostgreSQL integration.
- Introduced migration and truncation scripts for database management.
- Enhanced API endpoints for license operations with error handling and validation.
This commit is contained in:
Mauricio Siu
2025-03-19 00:36:35 -06:00
parent 9d047164ee
commit 4b6db35f16
19 changed files with 5071 additions and 82 deletions

9
apps/licenses/src/db.ts Normal file
View File

@@ -0,0 +1,9 @@
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";
import * as schema from "./schema";
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
export const db = drizzle(pool, { schema });

View File

@@ -1,39 +1,276 @@
import { serve } from "@hono/node-server";
import { Hono } from "hono";
import "dotenv/config";
import { cors } from "hono/cors";
import { z } from "zod";
import { zValidator } from "@hono/zod-validator";
import { logger } from "./logger.js";
import { deployJobSchema } from "./schema.js";
import { logger } from "./logger";
import Stripe from "stripe";
const app = new Hono();
import { render } from "@react-email/render";
import { createTransport } from "nodemailer";
import { LicenseEmail } from "../templates/emails/license-email";
import { ResendLicenseEmail } from "../templates/emails/resend-license-email";
import {
createLicense,
validateLicense,
activateLicense,
} from "./utils/license";
import { db } from "./db";
import { eq } from "drizzle-orm";
import { licenses } from "./schema";
import "dotenv/config";
app.post("/deploy", zValidator("json", deployJobSchema), (c) => {
const data = c.req.valid("json");
return c.json(
{
message: "Deployment Added",
},
200,
);
const app = new Hono();
app.use("/*", cors());
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: "2024-09-30.acacia",
});
// Stripe webhook
const transporter = createTransport({
host: process.env.SMTP_HOST,
port: Number(process.env.SMTP_PORT),
secure: true,
auth: {
user: process.env.SMTP_USER,
pass: process.env.SMTP_PASS,
},
});
const validateSchema = z.object({
licenseKey: z.string(),
serverIp: z.string(),
});
const resendSchema = z.object({
licenseKey: z.string(),
});
// Endpoint para validar una licencia
app.post("/validate", zValidator("json", validateSchema), async (c) => {
const { licenseKey, serverIp } = c.req.valid("json");
try {
const result = await validateLicense(licenseKey, serverIp);
return c.json(result);
} catch (error) {
logger.error("Error validating license:", error);
return c.json({ isValid: false, error: "Error validating license" }, 500);
}
});
// Endpoint para activar una licencia
app.post("/activate", zValidator("json", validateSchema), async (c) => {
const { licenseKey, serverIp } = c.req.valid("json");
try {
const license = await activateLicense(licenseKey, serverIp);
return c.json({ success: true, license });
} catch (error) {
logger.error("Error activating license:", error);
if (error instanceof Error) {
return c.json({ success: false, error: error.message }, 400);
}
return c.json({ success: false, error: "Unknown error occurred" }, 400);
}
});
// Endpoint para reenviar una licencia por email
app.post("/resend-license", zValidator("json", resendSchema), async (c) => {
const { licenseKey } = c.req.valid("json");
try {
const license = await db.query.licenses.findFirst({
where: eq(licenses.licenseKey, licenseKey),
});
if (!license) {
return c.json({ success: false, error: "License not found" }, 404);
}
// Generar el email
const emailHtml = await render(
ResendLicenseEmail({
customerName: license.customerId,
licenseKey: license.licenseKey,
productName: `Dokploy Self Hosted ${license.type}`,
expirationDate: new Date(license.expiresAt),
requestDate: new Date(),
}),
);
// Enviar el email
await transporter.sendMail({
from: process.env.SMTP_FROM,
to: license.email,
subject: "Your Dokploy License Key",
html: emailHtml,
});
return c.json({ success: true });
} catch (error) {
logger.error("Error resending license:", error);
return c.json({ success: false, error: "Error resending license" }, 500);
}
});
// Webhook de Stripe
app.post("/stripe/webhook", async (c) => {
const sig = c.req.header("stripe-signature");
const body = await c.req.json();
const event = stripe.webhooks.constructEvent(
body,
c.req.header("stripe-signature"),
process.env.STRIPE_WEBHOOK_SECRET,
);
let event: Stripe.Event;
return c.json({ status: "ok" });
try {
event = stripe.webhooks.constructEvent(
JSON.stringify(body),
sig!,
process.env.STRIPE_WEBHOOK_SECRET!,
);
} catch (err) {
logger.error("Webhook signature verification failed:", err);
return c.json({ error: "Webhook signature verification failed" }, 400);
}
try {
switch (event.type) {
case "checkout.session.completed": {
const session = event.data.object as Stripe.Checkout.Session;
// Obtener el customer
const customerResponse = await stripe.customers.retrieve(
session.customer as string,
);
if (customerResponse.deleted) {
throw new Error("Customer was deleted");
}
// Obtener el precio y determinar el tipo de licencia y facturación
const lineItems = await stripe.checkout.sessions.listLineItems(
session.id,
);
const priceId = lineItems.data[0].price?.id;
const { type, billingType } = getLicenseTypeFromPriceId(priceId!);
// Crear la licencia
const license = await createLicense({
customerId: customerResponse.id,
productId: session.id,
type,
billingType,
email: session.customer_details?.email!,
});
// Enviar el email con la licencia
const features = getLicenseFeatures(type);
const emailHtml = await render(
LicenseEmail({
customerName: customerResponse.name || "Customer",
licenseKey: license.licenseKey,
productName: `Dokploy Self Hosted ${type}`,
expirationDate: new Date(license.expiresAt),
features: features,
}),
);
await transporter.sendMail({
from: process.env.SMTP_FROM,
to: license.email,
subject: "Your Dokploy License Key",
html: emailHtml,
});
break;
}
// Puedes agregar más casos según necesites
}
return c.json({ received: true });
} catch (error) {
logger.error("Error processing webhook:", error);
if (error instanceof Error) {
return c.json({ error: error.message }, 500);
}
return c.json({ error: "Unknown error occurred" }, 500);
}
});
app.get("/health", async (c) => {
return c.json({ status: "ok" });
});
// Función auxiliar para obtener las características según el tipo de licencia
function getLicenseFeatures(type: string): string[] {
const baseFeatures = [
"Unlimited deployments",
"Basic monitoring",
"Email support",
];
const port = Number.parseInt(process.env.PORT || "3000");
logger.info("Starting Deployments Server ✅", port);
serve({ fetch: app.fetch, port });
const premiumFeatures = [
...baseFeatures,
"Priority support",
"Advanced monitoring",
"Custom domains",
"Team collaboration",
];
const businessFeatures = [
...premiumFeatures,
"24/7 support",
"Custom integrations",
"SLA guarantees",
"Dedicated account manager",
];
switch (type) {
case "basic":
return baseFeatures;
case "premium":
return premiumFeatures;
case "business":
return businessFeatures;
default:
return baseFeatures;
}
}
// Función auxiliar para determinar el tipo de licencia según el price ID
function getLicenseTypeFromPriceId(priceId: string): {
type: "basic" | "premium" | "business";
billingType: "monthly" | "annual";
} {
const priceMap = {
[process.env.SELF_HOSTED_BASIC_PRICE_MONTHLY_ID!]: {
type: "basic",
billingType: "monthly",
},
[process.env.SELF_HOSTED_BASIC_PRICE_ANNUAL_ID!]: {
type: "basic",
billingType: "annual",
},
[process.env.SELF_HOSTED_PREMIUM_PRICE_MONTHLY_ID!]: {
type: "premium",
billingType: "monthly",
},
[process.env.SELF_HOSTED_PREMIUM_PRICE_ANNUAL_ID!]: {
type: "premium",
billingType: "annual",
},
[process.env.SELF_HOSTED_BUSINESS_PRICE_MONTHLY_ID!]: {
type: "business",
billingType: "monthly",
},
[process.env.SELF_HOSTED_BUSINESS_PRICE_ANNUAL_ID!]: {
type: "business",
billingType: "annual",
},
} as const;
return priceMap[priceId] || { type: "basic", billingType: "monthly" };
}
const port = process.env.PORT || 4000;
console.log(`Server is running on port ${port}`);
serve({
fetch: app.fetch,
port: Number(port),
});

View File

@@ -0,0 +1,22 @@
import { drizzle } from "drizzle-orm/postgres-js";
import { migrate } from "drizzle-orm/postgres-js/migrator";
import postgres from "postgres";
import "dotenv/config";
import * as schema from "./schema";
const connectionString = process.env.DATABASE_URL!;
const sql = postgres(connectionString, { max: 1 });
const db = drizzle(sql, { schema });
await migrate(db, { migrationsFolder: "drizzle" })
.then(() => {
console.log("Migration complete");
sql.end();
})
.catch((error) => {
console.error("Migration failed", error);
process.exit(1);
})
.finally(() => {
sql.end();
});

View File

@@ -1,34 +1,37 @@
import { z } from "zod";
import { sql } from "drizzle-orm";
import { pgEnum, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core";
export const deployJobSchema = z.discriminatedUnion("applicationType", [
z.object({
applicationId: z.string(),
titleLog: z.string(),
descriptionLog: z.string(),
server: z.boolean().optional(),
type: z.enum(["deploy", "redeploy"]),
applicationType: z.literal("application"),
serverId: z.string().min(1),
}),
z.object({
composeId: z.string(),
titleLog: z.string(),
descriptionLog: z.string(),
server: z.boolean().optional(),
type: z.enum(["deploy", "redeploy"]),
applicationType: z.literal("compose"),
serverId: z.string().min(1),
}),
z.object({
applicationId: z.string(),
previewDeploymentId: z.string(),
titleLog: z.string(),
descriptionLog: z.string(),
server: z.boolean().optional(),
type: z.enum(["deploy"]),
applicationType: z.literal("application-preview"),
serverId: z.string().min(1),
}),
export const licenseStatusEnum = pgEnum("license_status", [
"active",
"expired",
"cancelled",
]);
export type DeployJob = z.infer<typeof deployJobSchema>;
export const licenseTypeEnum = pgEnum("license_type", [
"basic",
"premium",
"business",
]);
export const billingTypeEnum = pgEnum("billing_type", ["monthly", "annual"]);
export const licenses = pgTable("licenses", {
id: uuid("id").defaultRandom().primaryKey(),
customerId: text("customer_id").notNull(),
productId: text("product_id").notNull(),
licenseKey: text("license_key").notNull().unique(),
status: licenseStatusEnum("status").notNull().default("active"),
type: licenseTypeEnum("type").notNull(),
billingType: billingTypeEnum("billing_type").notNull(),
serverIp: text("server_ip"),
activatedAt: timestamp("activated_at"),
lastVerifiedAt: timestamp("last_verified_at"),
expiresAt: timestamp("expires_at").notNull(),
createdAt: timestamp("created_at").default(sql`CURRENT_TIMESTAMP`),
updatedAt: timestamp("updated_at").default(sql`CURRENT_TIMESTAMP`),
metadata: text("metadata"),
email: text("email").notNull(),
});
export type License = typeof licenses.$inferSelect;
export type NewLicense = typeof licenses.$inferInsert;

View File

@@ -0,0 +1,24 @@
import { sql } from "drizzle-orm";
// Credits to Louistiti from Drizzle Discord: https://discord.com/channels/1043890932593987624/1130802621750448160/1143083373535973406
import { drizzle } from "drizzle-orm/postgres-js";
import "dotenv/config";
import postgres from "postgres";
const connectionString = process.env.DATABASE_URL!;
const pg = postgres(connectionString, { max: 1 });
const db = drizzle(pg);
const clearDb = async (): Promise<void> => {
try {
const tablesQuery = sql<string>`DROP SCHEMA public CASCADE; CREATE SCHEMA public; DROP schema drizzle CASCADE;`;
const tables = await db.execute(tablesQuery);
console.log(tables);
await pg.end();
} catch (error) {
console.error("Error cleaning database", error);
} finally {
}
};
clearDb();

View File

@@ -0,0 +1,119 @@
import { randomBytes } from "node:crypto";
import { db } from "../db";
import { licenses } from "../schema";
import { eq } from "drizzle-orm";
export const generateLicenseKey = () => {
return randomBytes(32).toString("hex");
};
export const createLicense = async ({
customerId,
productId,
type,
billingType,
email,
}: {
customerId: string;
productId: string;
type: "basic" | "premium" | "business";
billingType: "monthly" | "annual";
email: string;
}) => {
const licenseKey = generateLicenseKey();
const expiresAt = new Date();
expiresAt.setMonth(
expiresAt.getMonth() + (billingType === "annual" ? 12 : 1),
);
const license = await db
.insert(licenses)
.values({
customerId,
productId,
licenseKey,
type,
billingType,
expiresAt,
email,
})
.returning();
return license[0];
};
export const validateLicense = async (
licenseKey: string,
serverIp?: string,
) => {
const license = await db.query.licenses.findFirst({
where: eq(licenses.licenseKey, licenseKey),
});
if (!license) {
return { isValid: false, error: "License not found" };
}
if (license.status !== "active") {
return { isValid: false, error: "License is not active" };
}
if (new Date() > license.expiresAt) {
await db
.update(licenses)
.set({ status: "expired" })
.where(eq(licenses.id, license.id));
return { isValid: false, error: "License has expired" };
}
if (license.serverIp && serverIp && license.serverIp !== serverIp) {
return { isValid: false, error: "Invalid server IP" };
}
// Update last verified timestamp
await db
.update(licenses)
.set({ lastVerifiedAt: new Date() })
.where(eq(licenses.id, license.id));
return { isValid: true, license };
};
export const activateLicense = async (licenseKey: string, serverIp: string) => {
const license = await db.query.licenses.findFirst({
where: eq(licenses.licenseKey, licenseKey),
});
if (!license) {
throw new Error("License not found");
}
if (license.status !== "active") {
throw new Error("License is not active");
}
if (new Date() > license.expiresAt) {
await db
.update(licenses)
.set({ status: "expired" })
.where(eq(licenses.id, license.id));
throw new Error("License has expired");
}
if (license.serverIp && license.serverIp !== serverIp) {
throw new Error("License is already activated on a different server");
}
// Activate the license with the server IP
const updatedLicense = await db
.update(licenses)
.set({
serverIp,
activatedAt: new Date(),
lastVerifiedAt: new Date(),
})
.where(eq(licenses.id, license.id))
.returning();
return updatedLicense[0];
};