Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Allow user to refresh instance license (#2100)
Luke Vellacf0a23c74032
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex f7a560ed1..95000446c 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -316,7 +316,6 @@"licenseType": "License Type","removeLicense": "Remove License","removeLicenseDescription": "Are you sure you want to remove this license?",- "licenseKeyErrorRateLimitExceeded": "Rate limit exceeded","licenseKeyErrorInvalidLicenseKey": "Invalid license key","licenseKeyGenericError": "An error occurred while validating the license key","activate": "Activate",@@ -561,5 +560,8 @@"saving": "Saving...","saved": "Saved","instanceSettingsDescription": "Configure your instance settings",- "usersDescription": "Manage users on this instance"+ "usersDescription": "Manage users on this instance",+ "whiteLabelAddon": "White Label Add-on",+ "whiteLabelAddonDescription": "This add-on allows you to brand Rallly with your own logo and colors.",+ "refreshLicense": "Refresh License"}diff --git a/apps/web/src/app/[locale]/control-panel/license/page.tsx b/apps/web/src/app/[locale]/control-panel/license/page.tsxindex a382ac9c7..722ee3833 100644--- a/apps/web/src/app/[locale]/control-panel/license/page.tsx+++ b/apps/web/src/app/[locale]/control-panel/license/page.tsx@@ -1,4 +1,6 @@+import { Badge } from "@rallly/ui/badge";import { Button } from "@rallly/ui/button";+import { Card, CardContent, CardHeader, CardTitle } from "@rallly/ui/card";import {Dialog,DialogContent,@@ -8,7 +10,12 @@ import {} from "@rallly/ui/dialog";import { Icon } from "@rallly/ui/icon";import dayjs from "dayjs";-import { KeySquareIcon, PlusIcon, ShoppingBagIcon } from "lucide-react";+import {+ KeySquareIcon,+ PaletteIcon,+ PlusIcon,+ ShoppingBagIcon,+} from "lucide-react";import type { Metadata } from "next";import { PageSection } from "@/app/components/page-layout";import {@@ -33,6 +40,7 @@ import {} from "@/components/empty-state";import { Trans } from "@/components/trans";import { LicenseKeyForm } from "@/features/licensing/components/license-key-form";+import { RefreshLicenseButton } from "@/features/licensing/components/refresh-license-button";import { RemoveLicenseButton } from "@/features/licensing/components/remove-license-button";import { loadInstanceLicense } from "@/features/licensing/data";import { getTranslation } from "@/i18n/server";@@ -44,6 +52,7 @@ async function loadData() {export default async function LicensePage() {const { license } = await loadData();+return (<SettingsPage><SettingsPageHeader>@@ -59,56 +68,97 @@ export default async function LicensePage() {</SettingsPageHeader><SettingsPageContent>{license ? (- <PageSection variant="card">- <DescriptionList>- <DescriptionListTitle>- <Trans i18nKey="licenseType" defaults="License Type" />- </DescriptionListTitle>- <DescriptionListValue>- <span className="text-primary capitalize">{license.type}</span>- {license.seats ? (- <span className="ml-2 text-muted-foreground">- (+ <>+ <PageSection variant="card">+ <div className="flex justify-between">+ <DescriptionList>+ <DescriptionListTitle>+ <Trans i18nKey="licenseType" defaults="License Type" />+ </DescriptionListTitle>+ <DescriptionListValue>+ <span className="text-primary capitalize">+ {license.type}+ </span>+ {license.seats ? (+ <span className="ml-2 text-muted-foreground">+ (+ <Trans+ i18nKey="seatCount"+ defaults="{count, plural, one {# seat} other {# seats}}"+ values={{ count: license.seats }}+ />+ )+ </span>+ ) : null}+ </DescriptionListValue>+ <DescriptionListTitle>+ <Trans i18nKey="licenseKey" defaults="License Key" />+ </DescriptionListTitle>+ <DescriptionListValue>+ <span className="select-all font-mono text-sm">+ {license.licenseKey}+ </span>+ </DescriptionListValue>+ <DescriptionListTitle>+ <Trans i18nKey="licenseeName" defaults="Licensee Name" />+ </DescriptionListTitle>+ <DescriptionListValue>+ {license.licenseeName ?? "-"}+ </DescriptionListValue>+ <DescriptionListTitle>+ <Trans i18nKey="licenseeEmail" defaults="Licensee Email" />+ </DescriptionListTitle>+ <DescriptionListValue>+ {license.licenseeEmail ?? "-"}+ </DescriptionListValue>+ <DescriptionListTitle>+ <Trans i18nKey="purchaseDate" defaults="Purchase Date" />+ </DescriptionListTitle>+ <DescriptionListValue>+ {dayjs(license.issuedAt).format("YYYY-MM-DD")}+ </DescriptionListValue>+ </DescriptionList>+ <div className="flex gap-2">+ <RefreshLicenseButton />+ <RemoveLicenseButton />+ </div>+ </div>+ </PageSection>+ <div className="grid gap-4 lg:grid-cols-2">+ <Card>+ <CardHeader className="flex items-center justify-between gap-4">+ <div className="flex items-center gap-2">+ <PaletteIcon className="size-4" />+ <CardTitle>+ <Trans+ i18nKey="whiteLabelAddon"+ defaults="White Label Add-on"+ />+ </CardTitle>+ </div>+ <div>+ {license.whiteLabelAddon ? (+ <Badge variant="green">+ <Trans i18nKey="enabled" defaults="Enabled" />+ </Badge>+ ) : (+ <Badge>+ <Trans i18nKey="disabled" defaults="Disabled" />+ </Badge>+ )}+ </div>+ </CardHeader>+ <CardContent>+ <p className="text-muted-foreground text-sm leading-relaxed"><Trans- i18nKey="seatCount"- defaults="{count, plural, one {# seat} other {# seats}}"- values={{ count: license.seats }}+ i18nKey="whiteLabelAddonDescription"+ defaults="This add-on allows you to brand Rallly with your own logo and colors."/>- )- </span>- ) : null}- </DescriptionListValue>- <DescriptionListTitle>- <Trans i18nKey="licenseKey" defaults="License Key" />- </DescriptionListTitle>- <DescriptionListValue>- <span className="select-all font-mono text-sm">- {license.licenseKey}- </span>- </DescriptionListValue>- <DescriptionListTitle>- <Trans i18nKey="licenseeName" defaults="Licensee Name" />- </DescriptionListTitle>- <DescriptionListValue>- {license.licenseeName ?? "-"}- </DescriptionListValue>- <DescriptionListTitle>- <Trans i18nKey="licenseeEmail" defaults="Licensee Email" />- </DescriptionListTitle>- <DescriptionListValue>- {license.licenseeEmail ?? "-"}- </DescriptionListValue>- <DescriptionListTitle>- <Trans i18nKey="purchaseDate" defaults="Purchase Date" />- </DescriptionListTitle>- <DescriptionListValue>- {dayjs(license.issuedAt).format("YYYY-MM-DD")}- </DescriptionListValue>- </DescriptionList>- <div>- <RemoveLicenseButton />+ </p>+ </CardContent>+ </Card></div>- </PageSection>+ </>) : (<EmptyState className="h-full"><EmptyStateIcon>diff --git a/apps/web/src/app/[locale]/control-panel/page.tsx b/apps/web/src/app/[locale]/control-panel/page.tsxindex 0ee1702be..6d522065f 100644--- a/apps/web/src/app/[locale]/control-panel/page.tsx+++ b/apps/web/src/app/[locale]/control-panel/page.tsx@@ -55,7 +55,7 @@ export default async function AdminPage() {<Link href="/control-panel/users"><div className="flex justify-between"><div>- <PageIcon color="darkGray">+ <PageIcon><UsersIcon /></PageIcon><TileTitle>@@ -91,7 +91,7 @@ export default async function AdminPage() {<Tile asChild><Link href="/control-panel/license"><div className="flex justify-between">- <PageIcon color="darkGray">+ <PageIcon><KeySquareIcon /></PageIcon>{tier ? (@@ -113,7 +113,7 @@ export default async function AdminPage() {<Tile asChild><Link href="/control-panel/settings"><div className="flex justify-between">- <PageIcon color="darkGray">+ <PageIcon><SettingsIcon /></PageIcon></div>diff --git a/apps/web/src/components/description-list.tsx b/apps/web/src/components/description-list.tsxindex 1f7360629..de471fca4 100644--- a/apps/web/src/components/description-list.tsx+++ b/apps/web/src/components/description-list.tsx@@ -7,7 +7,7 @@ function DescriptionListTitle({ children }: { children: React.ReactNode }) {}function DescriptionListValue({ children }: { children: React.ReactNode }) {- return <dd className="mb-4 font-mono text-sm">{children}</dd>;+ return <dd className="mb-4 font-mono text-sm last:mb-0">{children}</dd>;}export { DescriptionList, DescriptionListTitle, DescriptionListValue };diff --git a/apps/web/src/features/licensing/actions.ts b/apps/web/src/features/licensing/actions.tsindex ca0868538..0a5bd7ed3 100644--- a/apps/web/src/features/licensing/actions.ts+++ b/apps/web/src/features/licensing/actions.ts@@ -1,7 +1,12 @@"use server";import { prisma } from "@rallly/database";+import { revalidateTag } from "next/cache";+import { INSTANCE_LICENSE_TAG } from "@/features/licensing/constants";+import { validateLicenseKeyInputSchema } from "@/features/licensing/schema";+import { AppError } from "@/lib/errors";import { adminActionClient } from "@/lib/safe-action/server";+import { licenseManager } from "./server";export const removeInstanceLicenseAction = adminActionClient.metadata({@@ -10,6 +15,7 @@ export const removeInstanceLicenseAction = adminActionClient.action(async () => {try {await prisma.instanceLicense.deleteMany();+ revalidateTag(INSTANCE_LICENSE_TAG);} catch (_error) {return {success: false,@@ -22,3 +28,97 @@ export const removeInstanceLicenseAction = adminActionClientmessage: "License deleted successfully",};});++export const refreshInstanceLicenseAction = adminActionClient+ .metadata({+ actionName: "refresh_instance_license",+ })+ .action(async () => {+ try {+ const instanceLicense = await prisma.instanceLicense.findFirst({+ orderBy: {+ id: "asc",+ },+ });++ if (!instanceLicense) {+ return {+ success: false,+ message: "No license found to refresh",+ };+ }++ const { data } = await licenseManager.validateLicenseKey({+ key: instanceLicense.licenseKey,+ });++ if (!data) {+ throw new AppError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Failed to validate license",+ });+ }++ await prisma.instanceLicense.update({+ where: {+ licenseKey: instanceLicense.licenseKey,+ },+ data: {+ licenseeName: data.licenseeName,+ licenseeEmail: data.licenseeEmail,+ issuedAt: data.issuedAt,+ expiresAt: data.expiresAt,+ seats: data.seats,+ type: data.type,+ whiteLabelAddon: data.whiteLabelAddon,+ },+ });++ revalidateTag(INSTANCE_LICENSE_TAG);++ return {+ success: true,+ message: "License refreshed successfully",+ };+ } catch (_error) {+ console.error(_error);+ throw new AppError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Failed to validate license",+ });+ }+ });++export const validateLicenseKeyAction = adminActionClient+ .metadata({+ actionName: "validate_license_key",+ })+ .inputSchema(validateLicenseKeyInputSchema)+ .action(async ({ parsedInput }) => {+ const { data } = await licenseManager.validateLicenseKey(parsedInput);+ if (!data) {+ throw new AppError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Failed to validate license",+ });+ }++ await prisma.instanceLicense.create({+ data: {+ licenseKey: data.key,+ licenseeName: data.licenseeName,+ licenseeEmail: data.licenseeEmail,+ issuedAt: data.issuedAt,+ expiresAt: data.expiresAt,+ seats: data.seats,+ type: data.type,+ whiteLabelAddon: data.whiteLabelAddon,+ },+ });++ revalidateTag(INSTANCE_LICENSE_TAG);++ return {+ valid: true,+ };+ });diff --git a/apps/web/src/features/licensing/actions/validate-license.ts b/apps/web/src/features/licensing/actions/validate-license.tsdeleted file mode 100644index deeb50b10..000000000--- a/apps/web/src/features/licensing/actions/validate-license.ts+++ /dev/null@@ -1,44 +0,0 @@-"use server";--import { prisma } from "@rallly/database";-import { rateLimit } from "@/lib/rate-limit";-import { licenseManager } from "../server";--export async function validateLicenseKey(key: string) {- const { success } = await rateLimit("validate_license_key", 10, "1 m");-- if (!success) {- return {- valid: false,- error: "Rate limit exceeded" as const,- };- }-- const { data } = await licenseManager.validateLicenseKey({- key,- });-- if (!data) {- return {- valid: false,- error: "Invalid license key" as const,- };- }-- await prisma.instanceLicense.create({- data: {- licenseKey: data.key,- licenseeName: data.licenseeName,- licenseeEmail: data.licenseeEmail,- issuedAt: data.issuedAt,- expiresAt: data.expiresAt,- seats: data.seats,- type: data.type,- },- });-- return {- valid: true,- error: null,- };-}diff --git a/apps/web/src/features/licensing/components/license-key-form.tsx b/apps/web/src/features/licensing/components/license-key-form.tsxindex 76b2647f3..8fb1b79cf 100644--- a/apps/web/src/features/licensing/components/license-key-form.tsx+++ b/apps/web/src/features/licensing/components/license-key-form.tsx@@ -15,8 +15,9 @@ import { useRouter } from "next/navigation";import { useForm } from "react-hook-form";import { z } from "zod";import { Trans } from "@/components/trans";+import { validateLicenseKeyAction } from "@/features/licensing/actions";import { useTranslation } from "@/i18n/client";-import { validateLicenseKey } from "../actions/validate-license";+import { useSafeAction } from "@/lib/safe-action/client";import { checkLicenseKey } from "../helpers/check-license-key";const formSchema = z.object({@@ -37,36 +38,20 @@ export function LicenseKeyForm() {resolver: zodResolver(formSchema),});+ const validateLicenseKey = useSafeAction(validateLicenseKeyAction);+const onSubmit = async (data: LicenseKeyFormValues) => {try {- const { error } = await validateLicenseKey(data.licenseKey);+ const result = await validateLicenseKey.executeAsync({+ key: data.licenseKey,+ });- if (error) {- switch (error) {- case "Rate limit exceeded":- form.setError("licenseKey", {- message: t("licenseKeyErrorRateLimitExceeded", {- defaultValue: "Rate limit exceeded",- }),- });- break;- case "Invalid license key":- form.setError("licenseKey", {- message: t("licenseKeyErrorInvalidLicenseKey", {- defaultValue: "Invalid license key",- }),- });- break;- default:- form.setError("licenseKey", {- message: t("licenseKeyGenericError", {- defaultValue:- "An error occurred while validating the license key",- }),- });- break;- }- return;+ if (!result.data) {+ form.setError("licenseKey", {+ message: t("licenseKeyErrorInvalidLicenseKey", {+ defaultValue: "Invalid license key",+ }),+ });}} catch (_error) {form.setError("licenseKey", {diff --git a/apps/web/src/features/licensing/components/license-limit-warning.tsx b/apps/web/src/features/licensing/components/license-limit-warning.tsxindex a82a65628..5281c95df 100644--- a/apps/web/src/features/licensing/components/license-limit-warning.tsx+++ b/apps/web/src/features/licensing/components/license-limit-warning.tsx@@ -1,22 +1,11 @@import Link from "next/link";import { Trans } from "@/components/trans";-import { loadInstanceLicense } from "@/features/licensing/data";-import { getUserCount } from "@/features/user/queries";-import { isSelfHosted } from "@/utils/constants";+import { didExceedLicenseLimit } from "@/features/licensing/data";export async function LicenseLimitWarning() {- if (!isSelfHosted) {- return null;- }-- const [license, userCount] = await Promise.all([- loadInstanceLicense(),- getUserCount(),- ]);-- const userLimit = license?.seats ?? 1;+ const exceeded = await didExceedLicenseLimit();- if (license?.type === "ENTERPRISE" || userCount <= userLimit) {+ if (!exceeded) {return null;}diff --git a/apps/web/src/features/licensing/components/refresh-license-button.tsx b/apps/web/src/features/licensing/components/refresh-license-button.tsxnew file mode 100644index 000000000..a9dd1f17c--- /dev/null+++ b/apps/web/src/features/licensing/components/refresh-license-button.tsx@@ -0,0 +1,35 @@+"use client";++import { Button } from "@rallly/ui/button";+import { Icon } from "@rallly/ui/icon";+import { Tooltip, TooltipContent, TooltipTrigger } from "@rallly/ui/tooltip";+import { RefreshCwIcon } from "lucide-react";+import { Trans } from "@/components/trans";+import { useSafeAction } from "@/lib/safe-action/client";+import { refreshInstanceLicenseAction } from "../actions";++export function RefreshLicenseButton() {+ const refreshInstanceLicense = useSafeAction(refreshInstanceLicenseAction);++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ loading={refreshInstanceLicense.isExecuting}+ onClick={async () => await refreshInstanceLicense.executeAsync()}+ >+ <Icon>+ <RefreshCwIcon />+ </Icon>+ <span className="sr-only">+ <Trans i18nKey="refreshLicense" defaults="Refresh License" />+ </span>+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <Trans i18nKey="refreshLicense" defaults="Refresh License" />+ </TooltipContent>+ </Tooltip>+ );+}diff --git a/apps/web/src/features/licensing/components/remove-license-button.tsx b/apps/web/src/features/licensing/components/remove-license-button.tsxindex 1fece22eb..4f23ee3ec 100644--- a/apps/web/src/features/licensing/components/remove-license-button.tsx+++ b/apps/web/src/features/licensing/components/remove-license-button.tsx@@ -13,6 +13,7 @@ import {useDialog,} from "@rallly/ui/dialog";import { Icon } from "@rallly/ui/icon";+import { Tooltip, TooltipContent, TooltipTrigger } from "@rallly/ui/tooltip";import { XIcon } from "lucide-react";import { useTransition } from "react";import { Trans } from "@/components/trans";@@ -25,14 +26,23 @@ export function RemoveLicenseButton() {const removeInstanceLicense = useSafeAction(removeInstanceLicenseAction);return (<Dialog {...dialog.dialogProps}>- <DialogTrigger asChild>- <Button onClick={() => dialog.trigger()}>- <Icon>- <XIcon />- </Icon>+ <Tooltip>+ <TooltipTrigger asChild>+ <DialogTrigger asChild>+ <Button variant="ghost" onClick={() => dialog.trigger()}>+ <Icon>+ <XIcon />+ </Icon>+ <span className="sr-only">+ <Trans i18nKey="removeLicense" defaults="Remove License" />+ </span>+ </Button>+ </DialogTrigger>+ </TooltipTrigger>+ <TooltipContent><Trans i18nKey="removeLicense" defaults="Remove License" />- </Button>- </DialogTrigger>+ </TooltipContent>+ </Tooltip><DialogContent size="sm"><DialogHeader><DialogTitle>diff --git a/apps/web/src/features/licensing/constants.ts b/apps/web/src/features/licensing/constants.tsnew file mode 100644index 000000000..f8fa70cd6--- /dev/null+++ b/apps/web/src/features/licensing/constants.ts@@ -0,0 +1 @@+export const INSTANCE_LICENSE_TAG = "instance-license";diff --git a/apps/web/src/features/licensing/data.ts b/apps/web/src/features/licensing/data.tsindex 9d2cabce6..6b9351f37 100644--- a/apps/web/src/features/licensing/data.ts+++ b/apps/web/src/features/licensing/data.ts@@ -1,5 +1,9 @@import { prisma } from "@rallly/database";+import { unstable_cache } from "next/cache";import { cache } from "react";+import { INSTANCE_LICENSE_TAG } from "@/features/licensing/constants";+import { getUserCount } from "@/features/user/queries";+import { isSelfHosted } from "@/utils/constants";export function getInstanceLicense() {return prisma.instanceLicense.findFirst({@@ -9,8 +13,16 @@ export function getInstanceLicense() {});}+export const cached_getInstanceLicense = unstable_cache(+ getInstanceLicense,+ [],+ {+ tags: [INSTANCE_LICENSE_TAG],+ },+);+export const loadInstanceLicense = cache(async () => {- const license = await getInstanceLicense();+ const license = await cached_getInstanceLicense();if (!license) {return null;@@ -23,9 +35,24 @@ export const loadInstanceLicense = cache(async () => {issuedAt: license.issuedAt,expiresAt: license.expiresAt,seats:- (license.seats ?? license.type === "ENTERPRISE")- ? Number.POSITIVE_INFINITY- : 1,+ license.seats ??+ (license.type === "ENTERPRISE" ? Number.POSITIVE_INFINITY : 1),type: license.type,+ whiteLabelAddon: license.whiteLabelAddon,};});++export const didExceedLicenseLimit = async () => {+ if (!isSelfHosted) {+ return false;+ }++ const license = await loadInstanceLicense();+ const userCount = await getUserCount();++ if (!license) {+ return userCount > 1;+ }++ return license.seats < userCount;+};diff --git a/apps/web/src/features/licensing/lib/licensing-manager.ts b/apps/web/src/features/licensing/lib/licensing-manager.tsindex 8ae0adb00..4cd011e3e 100644--- a/apps/web/src/features/licensing/lib/licensing-manager.ts+++ b/apps/web/src/features/licensing/lib/licensing-manager.ts@@ -1,3 +1,4 @@+import { AppError } from "@/lib/errors";import type {CreateLicenseInput,ValidateLicenseInputKeySchema,@@ -49,6 +50,17 @@ export class LicenseManager {body: JSON.stringify(input),});- return validateLicenseKeyResponseSchema.parse(await res.json());+ const data = await res.json();++ if (!res.ok) {+ console.error(data);+ throw new AppError({+ code: "INTERNAL_SERVER_ERROR",+ cause: data,+ message: "Failed to validate license",+ });+ }++ return validateLicenseKeyResponseSchema.parse(data);}}diff --git a/apps/web/src/features/space/utils.ts b/apps/web/src/features/space/utils.tsindex ec85d5127..8d4c81e01 100644--- a/apps/web/src/features/space/utils.ts+++ b/apps/web/src/features/space/utils.ts@@ -1,6 +1,6 @@import type { SpaceMemberRole as PrismaSpaceMemberRole } from "@prisma/client";import { getSpaceSubscription } from "@/features/billing/data";-import { getInstanceLicense } from "@/features/licensing/data";+import { cached_getInstanceLicense } from "@/features/licensing/data";import type { LicenseType } from "@/features/licensing/schema";import type { MemberRole } from "@/features/space/schema";import { AppError } from "@/lib/errors";@@ -60,7 +60,7 @@ export async function getTotalSeatsForSpace(spaceId: string): Promise<number> {try {if (isSelfHosted) {// For self-hosted instances, get seat limit from instance license- const license = await getInstanceLicense();+ const license = await cached_getInstanceLicense();if (!license) {// No license found, return default limitdiff --git a/packages/ui/src/badge.tsx b/packages/ui/src/badge.tsxindex f8a2bc292..bb4533f1a 100644--- a/packages/ui/src/badge.tsx+++ b/packages/ui/src/badge.tsx@@ -13,7 +13,8 @@ const badgeVariants = cva(default: "bg-muted",destructive: "bg-destructive text-destructive-foreground",outline: "text-foreground",- green: "bg-green-600 text-white",+ green:+ "bg-green-100 text-green-600 dark:bg-green-950 dark:text-green-300",secondary: "bg-primary/10 text-primary",},size: {