Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
🚧 Add API Keys page (#2118)
Luke Vella89342c039e41
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 322059e21..05e5f9711 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -579,5 +579,30 @@"logoDark": "Logo (Dark Mode)","attribution": "Attribution","attributionDescription": "Control the visibility of the attribution text",- "hideAttribution": "Hide Attribution"+ "hideAttribution": "Hide Attribution",+ "apiKeys": "API Keys",+ "apiKeysDescription": "Manage API keys for programmatic access to your space",+ "apiKeysSettings": "API Keys Settings",+ "apiKeysSettingsDescription": "Create and manage API keys for programmatic access to your space.",+ "noApiKeys": "No API keys found",+ "noApiKeysDescription": "Create an API key to access your space programmatically",+ "lastUsedAt": "Last used {date}",+ "neverUsed": "Never used",+ "createApiKey": "Create API key",+ "apiKeyCreated": "API key created",+ "apiKeyCreatedDescription": "Copy your API key now. You won't be able to see it again.",+ "apiKeySecurityWarning": "Store this key securely. It won't be shown again.",+ "yourApiKey": "Your API key",+ "done": "Done",+ "createApiKeyDescription": "Create a new API key for programmatic access to your space",+ "apiKeyNamePlaceholder": "My App",+ "developer": "Developer",+ "active": "Active",+ "revoked": "Revoked",+ "revoke": "Revoke",+ "copiedToClipboard": "Copied to clipboard",+ "createFailed": "Failed to create",+ "revokeConfirmation": "Are you sure you want to revoke {name}? This will immediately disable the key.",+ "revoking": "Revoking...",+ "revokeFailed": "Failed to revoke"}diff --git a/apps/web/src/app/[locale]/(space)/settings/api-keys/components/api-keys-list.tsx b/apps/web/src/app/[locale]/(space)/settings/api-keys/components/api-keys-list.tsxnew file mode 100644index 000000000..52ddd64b1--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/api-keys/components/api-keys-list.tsx@@ -0,0 +1,94 @@+"use client";++import { Badge } from "@rallly/ui/badge";+import { Icon } from "@rallly/ui/icon";+import dayjs from "dayjs";+import { KeyIcon } from "lucide-react";+import {+ EmptyState,+ EmptyStateDescription,+ EmptyStateIcon,+ EmptyStateTitle,+} from "@/components/empty-state";+import { Spinner } from "@/components/spinner";+import { StackedList, StackedListItem } from "@/components/stacked-list";+import { Trans } from "@/components/trans";+import { trpc } from "@/trpc/client";+import { RevokeApiKeyButton } from "./revoke-api-key-button";++export function ApiKeysList() {+ const { data: apiKeys } = trpc.apiKeys.list.useQuery();++ if (apiKeys === undefined) {+ return <Spinner />;+ }++ if (apiKeys.length === 0) {+ return (+ <EmptyState>+ <EmptyStateIcon>+ <KeyIcon />+ </EmptyStateIcon>+ <EmptyStateTitle>+ <Trans i18nKey="noApiKeys" defaults="No API keys found" />+ </EmptyStateTitle>+ <EmptyStateDescription>+ <Trans+ i18nKey="noApiKeysDescription"+ defaults="Create an API key to access your space programmatically"+ />+ </EmptyStateDescription>+ </EmptyState>+ );+ }++ return (+ <StackedList>+ {apiKeys.map((apiKey) => (+ <StackedListItem key={apiKey.id}>+ <div className="flex flex-1 items-center gap-4">+ <div className="flex size-10 items-center justify-center rounded-lg border bg-card-accent">+ <Icon>+ <KeyIcon />+ </Icon>+ </div>+ <div>+ <div className="flex items-center gap-2">+ <div className="font-semibold text-sm">{apiKey.name}</div>+ {!apiKey.revokedAt ? (+ <Badge variant="green">+ <Trans i18nKey="active" defaults="Active" />+ </Badge>+ ) : (+ <Badge variant="destructive">+ <Trans i18nKey="revoked" defaults="Revoked" />+ </Badge>+ )}+ </div>+ <div className="text-muted-foreground text-sm">+ {`sk_${apiKey.prefix}`}+ ••••+ </div>+ </div>+ </div>+ <div className="text-muted-foreground text-sm">+ {apiKey.lastUsedAt ? (+ <Trans+ i18nKey="lastUsedAt"+ defaults="Last used {date}"+ values={{+ date: dayjs(apiKey.lastUsedAt).fromNow(),+ }}+ />+ ) : (+ <Trans i18nKey="neverUsed" defaults="Never used" />+ )}+ </div>+ {!apiKey.revokedAt ? (+ <RevokeApiKeyButton apiKeyId={apiKey.id} apiKeyName={apiKey.name} />+ ) : null}+ </StackedListItem>+ ))}+ </StackedList>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/settings/api-keys/components/create-api-key-button.tsx b/apps/web/src/app/[locale]/(space)/settings/api-keys/components/create-api-key-button.tsxnew file mode 100644index 000000000..55de93515--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/api-keys/components/create-api-key-button.tsx@@ -0,0 +1,211 @@+"use client";++import { zodResolver } from "@hookform/resolvers/zod";+import { Alert, AlertDescription } from "@rallly/ui/alert";+import { Button } from "@rallly/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ useDialog,+} from "@rallly/ui/dialog";+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@rallly/ui/form";+import { Icon } from "@rallly/ui/icon";+import { Input } from "@rallly/ui/input";+import { toast } from "@rallly/ui/sonner";+import { AlertTriangleIcon, CheckIcon, CopyIcon, PlusIcon } from "lucide-react";+import React from "react";+import { useForm } from "react-hook-form";+import { useCopyToClipboard } from "react-use";+import { z } from "zod";+import { Trans } from "@/components/trans";+import { useTranslation } from "@/i18n/client";+import { trpc } from "@/trpc/client";++const formSchema = z.object({+ name: z.string().min(1).max(100),+});++type FormData = z.infer<typeof formSchema>;++export function CreateApiKeyButton() {+ const { t } = useTranslation();+ const dialog = useDialog();+ const [createdApiKey, setCreatedApiKey] = React.useState<string | null>(null);+ const createApiKey = trpc.apiKeys.create.useMutation();+ const utils = trpc.useUtils();+ const [, copy] = useCopyToClipboard();+ const [didCopy, setDidCopy] = React.useState(false);++ const form = useForm<FormData>({+ resolver: zodResolver(formSchema),+ defaultValues: {+ name: "",+ },+ });++ const handleClose = () => {+ dialog.dismiss();+ setCreatedApiKey(null);+ form.reset();+ };++ const handleCopy = () => {+ if (createdApiKey) {+ copy(createdApiKey);+ setDidCopy(true);+ setTimeout(() => setDidCopy(false), 2000);+ toast.success(+ t("copiedToClipboard", {+ defaultValue: "Copied to clipboard",+ }),+ );+ }+ };++ const onSubmit = async (data: FormData) => {+ try {+ const result = await createApiKey.mutateAsync(data);+ setCreatedApiKey(result.apiKey);+ await utils.apiKeys.list.invalidate();+ form.reset();+ } catch {+ toast.error(+ t("createFailed", {+ defaultValue: "Failed to create",+ }),+ );+ }+ };++ return (+ <>+ <Button onClick={() => dialog.trigger()}>+ <Icon>+ <PlusIcon />+ </Icon>+ <Trans i18nKey="createApiKey" defaults="Create API key" />+ </Button>+ <Dialog {...dialog.dialogProps} onOpenChange={handleClose}>+ <DialogContent>+ {createdApiKey ? (+ <>+ <DialogHeader>+ <DialogTitle>+ <Trans i18nKey="apiKeyCreated" defaults="API key created" />+ </DialogTitle>+ <DialogDescription>+ <Trans+ i18nKey="apiKeyCreatedDescription"+ defaults="Copy your API key now. You won't be able to see it again."+ />+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-4">+ <Alert variant="warning">+ <AlertTriangleIcon />+ <AlertDescription>+ <Trans+ i18nKey="apiKeySecurityWarning"+ defaults="Store this key securely. It won't be shown again."+ />+ </AlertDescription>+ </Alert>+ <div className="space-y-2">+ <label+ htmlFor="created-api-key"+ className="font-medium text-sm"+ >+ <Trans i18nKey="yourApiKey" defaults="Your API key" />+ </label>+ <div className="flex gap-2">+ <Input+ id="created-api-key"+ value={createdApiKey}+ readOnly+ className="font-mono text-sm"+ />+ <Button+ variant="ghost"+ size="icon"+ onClick={handleCopy}+ type="button"+ >+ <Icon>{didCopy ? <CheckIcon /> : <CopyIcon />}</Icon>+ </Button>+ </div>+ </div>+ </div>+ <DialogFooter>+ <Button onClick={handleClose}>+ <Trans i18nKey="done" defaults="Done" />+ </Button>+ </DialogFooter>+ </>+ ) : (+ <>+ <DialogHeader>+ <DialogTitle>+ <Trans i18nKey="createApiKey" defaults="Create API key" />+ </DialogTitle>+ <DialogDescription>+ <Trans+ i18nKey="createApiKeyDescription"+ defaults="Create a new API key for programmatic access to your space"+ />+ </DialogDescription>+ </DialogHeader>+ <Form {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)}>+ <div className="space-y-4">+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ <Trans i18nKey="name" defaults="Name" />+ </FormLabel>+ <FormControl>+ <Input+ {...field}+ placeholder={t("apiKeyNamePlaceholder", {+ defaultValue: "My App",+ })}+ autoFocus+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ <DialogFooter className="mt-6">+ <Button+ variant="primary"+ type="submit"+ disabled={createApiKey.isPending}+ loading={createApiKey.isPending}+ >+ <Trans i18nKey="create" defaults="Create" />+ </Button>+ </DialogFooter>+ </form>+ </Form>+ </>+ )}+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/settings/api-keys/components/revoke-api-key-button.tsx b/apps/web/src/app/[locale]/(space)/settings/api-keys/components/revoke-api-key-button.tsxnew file mode 100644index 000000000..1f91ab6c9--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/api-keys/components/revoke-api-key-button.tsx@@ -0,0 +1,117 @@+"use client";++import { Button } from "@rallly/ui/button";+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ useDialog,+} from "@rallly/ui/dialog";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@rallly/ui/dropdown-menu";+import { Icon } from "@rallly/ui/icon";+import { toast } from "@rallly/ui/sonner";+import { BanIcon, MoreHorizontalIcon } from "lucide-react";+import { Trans } from "@/components/trans";+import { useTranslation } from "@/i18n/client";+import { trpc } from "@/trpc/client";++export function RevokeApiKeyButton({+ apiKeyId,+ apiKeyName,+}: {+ apiKeyId: string;+ apiKeyName: string;+}) {+ const { t } = useTranslation();+ const revokeDialog = useDialog();+ const revokeApiKey = trpc.apiKeys.revoke.useMutation();+ const utils = trpc.useUtils();++ return (+ <>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button variant="ghost" size="icon">+ <Icon>+ <MoreHorizontalIcon />+ </Icon>+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ onClick={() => {+ revokeDialog.trigger();+ }}+ className="text-destructive"+ >+ <BanIcon className="size-4" />+ <Trans i18nKey="revoke" defaults="Revoke" />+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <Dialog {...revokeDialog.dialogProps}>+ <DialogContent size="sm">+ <DialogHeader>+ <DialogTitle>+ <Trans i18nKey="revoke" defaults="Revoke" />+ </DialogTitle>+ <DialogDescription>+ <Trans+ i18nKey="revokeConfirmation"+ defaults="Are you sure you want to revoke {name}? This will immediately disable the key."+ values={{ name: apiKeyName }}+ components={{+ b: <b className="whitespace-nowrap font-bold" />,+ }}+ />+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button+ variant="destructive"+ onClick={() => {+ toast.promise(+ revokeApiKey+ .mutateAsync({+ id: apiKeyId,+ })+ .then(() => {+ utils.apiKeys.list.invalidate();+ }),+ {+ loading: t("revoking", {+ defaultValue: "Revoking...",+ }),+ success: t("revoked", {+ defaultValue: "Revoked",+ }),+ error: t("revokeFailed", {+ defaultValue: "Failed to revoke",+ }),+ },+ );+ revokeDialog.dismiss();+ }}+ >+ <Trans i18nKey="revoke" defaults="Revoke" />+ </Button>+ <DialogClose asChild>+ <Button>+ <Trans i18nKey="cancel" defaults="Cancel" />+ </Button>+ </DialogClose>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/settings/api-keys/page.tsx b/apps/web/src/app/[locale]/(space)/settings/api-keys/page.tsxnew file mode 100644index 000000000..5f2b6b671--- /dev/null+++ b/apps/web/src/app/[locale]/(space)/settings/api-keys/page.tsx@@ -0,0 +1,75 @@+import { dehydrate, HydrationBoundary } from "@tanstack/react-query";+import type { Metadata } from "next";+import { notFound } from "next/navigation";+import {+ PageSection,+ PageSectionContent,+ PageSectionGroup,+} from "@/app/components/page-layout";+import {+ SettingsPage,+ SettingsPageContent,+ SettingsPageDescription,+ SettingsPageHeader,+ SettingsPageTitle,+} from "@/app/components/settings-layout";+import { requireSpace, requireUser } from "@/auth/data";+import { Trans } from "@/components/trans";+import { getTranslation } from "@/i18n/server";+import { createSSRHelper } from "@/trpc/server/create-ssr-helper";+import { ApiKeysList } from "./components/api-keys-list";+import { CreateApiKeyButton } from "./components/create-api-key-button";++export default async function ApiKeysSettingsPage() {+ const [space, user] = await Promise.all([requireSpace(), requireUser()]);++ if (space.ownerId !== user.id) {+ return notFound();+ }++ const helpers = await createSSRHelper();+ await helpers.apiKeys.list.prefetch();++ return (+ <HydrationBoundary state={dehydrate(helpers.queryClient)}>+ <SettingsPage>+ <SettingsPageHeader className="flex-row items-center justify-between">+ <div>+ <SettingsPageTitle>+ <Trans i18nKey="apiKeys" defaults="API Keys" />+ </SettingsPageTitle>+ <SettingsPageDescription>+ <Trans+ i18nKey="apiKeysDescription"+ defaults="Manage API keys for programmatic access to your space"+ />+ </SettingsPageDescription>+ </div>+ <CreateApiKeyButton />+ </SettingsPageHeader>+ <SettingsPageContent>+ <PageSectionGroup>+ <PageSection>+ <PageSectionContent>+ <ApiKeysList />+ </PageSectionContent>+ </PageSection>+ </PageSectionGroup>+ </SettingsPageContent>+ </SettingsPage>+ </HydrationBoundary>+ );+}++export async function generateMetadata(): Promise<Metadata> {+ const { t } = await getTranslation();+ return {+ title: t("apiKeysSettings", {+ defaultValue: "API Keys Settings",+ }),+ description: t("apiKeysSettingsDescription", {+ defaultValue:+ "Create and manage API keys for programmatic access to your space.",+ }),+ };+}diff --git a/apps/web/src/app/[locale]/(space)/settings/components/sidebar.tsx b/apps/web/src/app/[locale]/(space)/settings/components/sidebar.tsxindex f0b8b8135..697572839 100644--- a/apps/web/src/app/[locale]/(space)/settings/components/sidebar.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/components/sidebar.tsx@@ -1,7 +1,11 @@"use client";+import { useFeatureFlagEnabled } from "@rallly/posthog/client";import { Icon } from "@rallly/ui/icon";import {+ SidebarGroup,+ SidebarGroupContent,+ SidebarGroupLabel,SidebarMenu,SidebarMenuButton,SidebarMenuItem,@@ -10,6 +14,7 @@ import {BoltIcon,CalendarIcon,CreditCardIcon,+ KeyIcon,LockIcon,PanelsTopLeftIcon,Settings2Icon,@@ -18,6 +23,7 @@ import {} from "lucide-react";import Link from "next/link";import { usePathname } from "next/navigation";+import { Trans } from "@/components/trans";import { useTranslation } from "@/i18n/client";import { useFeatureFlag } from "@/lib/feature-flags/client";@@ -122,3 +128,47 @@ export function SpaceSidebarMenu() {</SidebarMenu>);}++export function DeveloperSidebarMenu() {+ const { t } = useTranslation();+ const pathname = usePathname();+ const isDeveloperToolsEnabled = useFeatureFlagEnabled("developer-tools");++ if (!isDeveloperToolsEnabled) {+ return null;+ }++ const menuItems = [+ {+ id: "apiKeys",+ label: t("apiKeys", { defaultValue: "API Keys" }),+ icon: <KeyIcon />,+ href: "/settings/api-keys",+ },+ ];++ return (+ <SidebarGroup>+ <SidebarGroupLabel>+ <Trans i18nKey="developer" defaults="Developer" />+ </SidebarGroupLabel>+ <SidebarGroupContent>+ <SidebarMenu>+ {menuItems.map((item) => (+ <SidebarMenuItem key={item.id}>+ <SidebarMenuButton+ asChild+ isActive={pathname.startsWith(item.href)}+ >+ <Link href={item.href} className="flex items-center gap-x-2">+ <Icon>{item.icon}</Icon>+ {item.label}+ </Link>+ </SidebarMenuButton>+ </SidebarMenuItem>+ ))}+ </SidebarMenu>+ </SidebarGroupContent>+ </SidebarGroup>+ );+}diff --git a/apps/web/src/app/[locale]/(space)/settings/layout.tsx b/apps/web/src/app/[locale]/(space)/settings/layout.tsxindex 663a81d11..21640f782 100644--- a/apps/web/src/app/[locale]/(space)/settings/layout.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/layout.tsx@@ -18,18 +18,23 @@ import {import { ArrowLeftIcon, SettingsIcon } from "lucide-react";import Link from "next/link";import type React from "react";-import { requireUser } from "@/auth/data";+import { requireSpace, requireUser } from "@/auth/data";import { NavUser } from "@/components/nav-user";import { Trans } from "@/components/trans";import { BillingProvider } from "@/features/billing/client";-import { AccountSidebarMenu, SpaceSidebarMenu } from "./components/sidebar";+import {+ AccountSidebarMenu,+ DeveloperSidebarMenu,+ SpaceSidebarMenu,+} from "./components/sidebar";export default async function Layout({children,}: {children?: React.ReactNode;}) {- const user = await requireUser();+ const [user, space] = await Promise.all([requireUser(), requireSpace()]);+ const isSpaceOwner = space.ownerId === user.id;return (<BillingProvider>@@ -73,6 +78,7 @@ export default async function Layout({<SpaceSidebarMenu /></SidebarGroupContent></SidebarGroup>+ {isSpaceOwner ? <DeveloperSidebarMenu /> : null}</SidebarContent><SidebarFooter><NavUserdiff --git a/apps/web/src/app/api/private/[...route]/route.test.ts b/apps/web/src/app/api/private/[...route]/route.test.tsindex 49a4422f9..39cad681c 100644--- a/apps/web/src/app/api/private/[...route]/route.test.ts+++ b/apps/web/src/app/api/private/[...route]/route.test.ts@@ -4,6 +4,7 @@ vi.mock("@rallly/database", () => ({prisma: {spaceApiKey: {findUnique: vi.fn(),+ findMany: vi.fn(),update: vi.fn(),},user: {@@ -36,12 +37,16 @@ vi.mock("@/lib/kv", () => ({kv: null,}));-import crypto from "node:crypto";import { prisma } from "@rallly/database";+import { hashApiKey, randomToken } from "@/features/developer/utils";import { app } from "./route";const createMockApiKey = (rawKey: string) => {- const hashedKey = crypto.createHash("sha256").update(rawKey).digest("hex");+ // Use the new salted hash format+ const salt = randomToken(12);+ const hash = hashApiKey(rawKey, salt);+ const hashedKey = `sha256$${salt}$${hash}`;+return {id: "api-key-id",name: "Test API Key",@@ -66,6 +71,8 @@ describe("Private API - /polls", () => {beforeEach(() => {vi.clearAllMocks();+ // Mock findMany for the timing-safe lookup+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([mockApiKey]);vi.mocked(prisma.spaceApiKey.findUnique).mockResolvedValue(mockApiKey);vi.mocked(prisma.spaceApiKey.update).mockResolvedValue({} as never);vi.mocked(prisma.user.findUnique).mockResolvedValue({@@ -92,7 +99,7 @@ describe("Private API - /polls", () => {});it("should return 401 with invalid API key", async () => {- vi.mocked(prisma.spaceApiKey.findUnique).mockResolvedValue(null);+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([]);const res = await app.request("/api/private/polls", {method: "POST",@@ -110,10 +117,8 @@ describe("Private API - /polls", () => {});it("should return 401 with revoked API key", async () => {- vi.mocked(prisma.spaceApiKey.findUnique).mockResolvedValue({- ...mockApiKey,- revokedAt: new Date(),- });+ // Revoked keys are filtered out by the database query+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([]);const res = await app.request("/api/private/polls", {method: "POST",@@ -131,10 +136,8 @@ describe("Private API - /polls", () => {});it("should return 401 with expired API key", async () => {- vi.mocked(prisma.spaceApiKey.findUnique).mockResolvedValue({- ...mockApiKey,- expiresAt: new Date("2020-01-01"),- });+ // Expired keys are filtered out by the database query+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([]);const res = await app.request("/api/private/polls", {method: "POST",diff --git a/apps/web/src/app/api/private/utils/api-key.ts b/apps/web/src/app/api/private/utils/api-key.tsindex b3c8c3cd5..fab03f8ff 100644--- a/apps/web/src/app/api/private/utils/api-key.ts+++ b/apps/web/src/app/api/private/utils/api-key.ts@@ -2,49 +2,27 @@ import crypto from "node:crypto";import { prisma } from "@rallly/database";import { waitUntil } from "@vercel/functions";import { bearerAuth } from "hono/bearer-auth";--const extractApiKeyPrefix = (rawKey: string) => {- const parts = rawKey.split("_").filter(Boolean);- if (parts.length >= 3 && parts[1]) {- return parts[1];- }- return rawKey.slice(0, 12);-};--const isHexSha256 = (value: string) => /^[a-f0-9]{64}$/i.test(value);--const hashApiKey = (rawKey: string, salt?: string) => {- const input = salt ? `${salt}:${rawKey}` : rawKey;- return crypto.createHash("sha256").update(input).digest("hex");-};--const verifyApiKey = (rawKey: string, stored: string) => {- const trimmed = stored.trim();- if (trimmed.startsWith("sha256$")) {- const [, salt, hash] = trimmed.split("$");- if (!salt || !hash || !isHexSha256(hash)) {- return false;- }- const computed = hashApiKey(rawKey, salt);- return crypto.timingSafeEqual(Buffer.from(computed), Buffer.from(hash));- }-- if (!isHexSha256(trimmed)) {- return false;- }-- const computed = hashApiKey(rawKey);- return crypto.timingSafeEqual(Buffer.from(computed), Buffer.from(trimmed));-};+import { extractApiKeyPrefix, verifyApiKey } from "@/features/developer/utils";export const spaceApiKeyAuth = bearerAuth({verifyToken: async (rawKey, c) => {const prefix = extractApiKeyPrefix(rawKey);+ const prefixBuffer = Buffer.from(prefix);- const apiKey = await prisma.spaceApiKey.findUnique({- where: { prefix },+ // Query candidate keys to avoid timing attack via database lookup+ // We use a partial prefix match to narrow the search space+ const now = new Date();+ const candidateKeys = await prisma.spaceApiKey.findMany({+ where: {+ prefix: {+ startsWith: prefix.slice(0, Math.min(4, prefix.length)),+ },+ revokedAt: null,+ OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],+ },select: {id: true,+ prefix: true,spaceId: true,hashedKey: true,expiresAt: true,@@ -57,31 +35,36 @@ export const spaceApiKeyAuth = bearerAuth({},});- if (!apiKey) {- return false;- }-- if (apiKey.revokedAt) {- return false;- }-- if (apiKey.expiresAt && apiKey.expiresAt <= new Date()) {- return false;+ // Constant-time search through candidates+ let validKey = null;+ for (const candidate of candidateKeys) {+ // Timing-safe prefix comparison+ const candidateBuffer = Buffer.from(candidate.prefix);+ if (+ prefixBuffer.length === candidateBuffer.length &&+ crypto.timingSafeEqual(prefixBuffer, candidateBuffer)+ ) {+ // Verify the full key hash+ if (verifyApiKey(rawKey, candidate.hashedKey)) {+ validKey = candidate;+ // Continue iterating to maintain constant time+ }+ }}- if (!verifyApiKey(rawKey, apiKey.hashedKey)) {+ if (!validKey) {return false;}c.set("apiAuth", {- spaceId: apiKey.spaceId,- spaceOwnerId: apiKey.space.ownerId,- apiKeyId: apiKey.id,+ spaceId: validKey.spaceId,+ spaceOwnerId: validKey.space.ownerId,+ apiKeyId: validKey.id,});waitUntil(prisma.spaceApiKey.update({- where: { id: apiKey.id },+ where: { id: validKey.id },data: { lastUsedAt: new Date() },}),);diff --git a/apps/web/src/components/empty-state.tsx b/apps/web/src/components/empty-state.tsxindex 0c644bdd2..c0f6d639a 100644--- a/apps/web/src/components/empty-state.tsx+++ b/apps/web/src/components/empty-state.tsx@@ -22,7 +22,7 @@ export function EmptyState({export function EmptyStateIcon({ children }: { children: React.ReactNode }) {return (- <div className="mb-4 inline-flex rounded-full border bg-linear-to-b from-gray-50 to-white p-4 dark:border-gray-700 dark:from-gray-900 dark:to-gray-800">+ <div className="mb-4 inline-flex rounded-full border p-4"><Icon size="xl" className="opacity-50">{children}</Icon>diff --git a/apps/web/src/features/developer/utils.test.ts b/apps/web/src/features/developer/utils.test.tsnew file mode 100644index 000000000..5553769ae--- /dev/null+++ b/apps/web/src/features/developer/utils.test.ts@@ -0,0 +1,237 @@+import { describe, expect, it } from "vitest";+import {+ createApiKey,+ extractApiKeyPrefix,+ hashApiKey,+ isHexSha256,+ randomToken,+ sha256Hex,+ verifyApiKey,+} from "./utils";++describe("randomToken", () => {+ it("should generate tokens of correct length", () => {+ const token = randomToken(16);+ expect(token).toBeTruthy();+ expect(token.length).toBeGreaterThan(0);+ });++ it("should generate different tokens on each call", () => {+ const token1 = randomToken(16);+ const token2 = randomToken(16);+ expect(token1).not.toBe(token2);+ });++ it("should generate base64url encoded strings", () => {+ const token = randomToken(16);+ // Base64URL uses A-Z, a-z, 0-9, -, _+ expect(token).toMatch(/^[A-Za-z0-9_-]+$/);+ });+});++describe("sha256Hex", () => {+ it("should generate consistent hashes for same input", () => {+ const input = "test-string";+ const hash1 = sha256Hex(input);+ const hash2 = sha256Hex(input);+ expect(hash1).toBe(hash2);+ });++ it("should generate different hashes for different inputs", () => {+ const hash1 = sha256Hex("input1");+ const hash2 = sha256Hex("input2");+ expect(hash1).not.toBe(hash2);+ });++ it("should generate 64-character hex strings", () => {+ const hash = sha256Hex("test");+ expect(hash).toMatch(/^[a-f0-9]{64}$/);+ });+});++describe("isHexSha256", () => {+ it("should return true for valid SHA-256 hex strings", () => {+ const validHash =+ "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08";+ expect(isHexSha256(validHash)).toBe(true);+ });++ it("should return false for strings that are too short", () => {+ expect(isHexSha256("abc123")).toBe(false);+ });++ it("should return false for strings with non-hex characters", () => {+ const invalidHash =+ "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00aGZ";+ expect(isHexSha256(invalidHash)).toBe(false);+ });++ it("should return false for empty strings", () => {+ expect(isHexSha256("")).toBe(false);+ });+});++describe("createApiKey", () => {+ it("should generate an API key with correct format", () => {+ const result = createApiKey();+ expect(result.apiKey).toMatch(/^sk_[A-Za-z0-9_-]+_[A-Za-z0-9_-]+$/);+ });++ it("should generate unique API keys on each call", () => {+ const result1 = createApiKey();+ const result2 = createApiKey();+ expect(result1.apiKey).not.toBe(result2.apiKey);+ expect(result1.prefix).not.toBe(result2.prefix);+ });++ it("should generate a valid prefix", () => {+ const result = createApiKey();+ expect(result.prefix).toBeTruthy();+ expect(result.prefix.length).toBeGreaterThan(0);+ });++ it("should generate a hashed key in correct format", () => {+ const result = createApiKey();+ expect(result.hashedKey).toMatch(/^sha256\$[A-Za-z0-9_-]+\$[a-f0-9]{64}$/);+ });++ it("should verify the generated API key against its hash", () => {+ const result = createApiKey();+ expect(verifyApiKey(result.apiKey, result.hashedKey)).toBe(true);+ });+});++describe("extractApiKeyPrefix", () => {+ it("should extract prefix from valid API key", () => {+ const apiKey = "sk_abc123_def456";+ expect(extractApiKeyPrefix(apiKey)).toBe("abc123");+ });++ it("should handle malformed keys with fallback", () => {+ const malformed = "invalidkey";+ expect(extractApiKeyPrefix(malformed)).toBe(malformed.slice(0, 12));+ });++ it("should handle keys with extra underscores", () => {+ const apiKey = "sk_prefix_secret_extra";+ expect(extractApiKeyPrefix(apiKey)).toBe("prefix");+ });+});++describe("hashApiKey", () => {+ it("should generate consistent hashes without salt", () => {+ const key = "test-api-key";+ const hash1 = hashApiKey(key);+ const hash2 = hashApiKey(key);+ expect(hash1).toBe(hash2);+ });++ it("should generate consistent hashes with salt", () => {+ const key = "test-api-key";+ const salt = "test-salt";+ const hash1 = hashApiKey(key, salt);+ const hash2 = hashApiKey(key, salt);+ expect(hash1).toBe(hash2);+ });++ it("should generate different hashes for different salts", () => {+ const key = "test-api-key";+ const hash1 = hashApiKey(key, "salt1");+ const hash2 = hashApiKey(key, "salt2");+ expect(hash1).not.toBe(hash2);+ });++ it("should generate different hashes with and without salt", () => {+ const key = "test-api-key";+ const hash1 = hashApiKey(key);+ const hash2 = hashApiKey(key, "salt");+ expect(hash1).not.toBe(hash2);+ });+});++describe("verifyApiKey", () => {+ describe("salted format (sha256$salt$hash)", () => {+ it("should verify correct API key", () => {+ const result = createApiKey();+ expect(verifyApiKey(result.apiKey, result.hashedKey)).toBe(true);+ });++ it("should reject incorrect API key", () => {+ const result = createApiKey();+ const wrongKey = "sk_wrong_prefix_wrong_secret";+ expect(verifyApiKey(wrongKey, result.hashedKey)).toBe(false);+ });++ it("should reject API key with tampered salt", () => {+ const result = createApiKey();+ const [, , hash] = result.hashedKey.split("$");+ const tamperedHash = `sha256$wrongsalt$${hash}`;+ expect(verifyApiKey(result.apiKey, tamperedHash)).toBe(false);+ });++ it("should reject API key with tampered hash", () => {+ const result = createApiKey();+ const [, salt] = result.hashedKey.split("$");+ const tamperedHash = `sha256$${salt}$${"0".repeat(64)}`;+ expect(verifyApiKey(result.apiKey, tamperedHash)).toBe(false);+ });++ it("should reject malformed hash format", () => {+ const result = createApiKey();+ expect(verifyApiKey(result.apiKey, "sha256$invalidsalt")).toBe(false);+ });++ it("should reject hash with non-hex characters", () => {+ const result = createApiKey();+ expect(verifyApiKey(result.apiKey, "sha256$salt$notahex")).toBe(false);+ });+ });++ describe("legacy format (plain hex)", () => {+ it("should verify correct legacy API key", () => {+ const apiKey = "test-legacy-key";+ const hash = sha256Hex(apiKey);+ expect(verifyApiKey(apiKey, hash)).toBe(true);+ });++ it("should reject incorrect legacy API key", () => {+ const apiKey = "test-legacy-key";+ const hash = sha256Hex(apiKey);+ expect(verifyApiKey("wrong-key", hash)).toBe(false);+ });++ it("should reject malformed legacy hash", () => {+ expect(verifyApiKey("test-key", "not-a-valid-hash")).toBe(false);+ });+ });++ describe("edge cases", () => {+ it("should handle hashes with whitespace", () => {+ const result = createApiKey();+ const hashWithSpace = ` ${result.hashedKey} `;+ expect(verifyApiKey(result.apiKey, hashWithSpace)).toBe(true);+ });++ it("should reject empty hash", () => {+ expect(verifyApiKey("test-key", "")).toBe(false);+ });++ it("should reject hash with only prefix", () => {+ expect(verifyApiKey("test-key", "sha256$")).toBe(false);+ });+ });++ describe("timing attack resistance", () => {+ it("should use constant-time comparison", () => {+ // This test verifies that the function uses timingSafeEqual+ // by checking that both valid and invalid keys execute the comparison+ const result = createApiKey();++ // Both should complete without throwing+ expect(() => verifyApiKey(result.apiKey, result.hashedKey)).not.toThrow();+ expect(() =>+ verifyApiKey("sk_wrong_key", result.hashedKey),+ ).not.toThrow();+ });+ });+});diff --git a/apps/web/src/features/developer/utils.ts b/apps/web/src/features/developer/utils.tsnew file mode 100644index 000000000..91a5efb87--- /dev/null+++ b/apps/web/src/features/developer/utils.ts@@ -0,0 +1,102 @@+import crypto from "node:crypto";++/**+ * Generate a cryptographically random token+ * @param bytes Number of random bytes to generate+ * @returns Base64URL encoded random string+ */+export const randomToken = (bytes: number): string =>+ crypto.randomBytes(bytes).toString("base64url");++/**+ * Hash a value using SHA-256+ * @param value String to hash+ * @returns Hex-encoded SHA-256 hash+ */+export const sha256Hex = (value: string): string =>+ crypto.createHash("sha256").update(value).digest("hex");++/**+ * Create an API key with the format: sk_{prefix}_{secret}+ * @returns Object containing the full API key and components for storage+ */+export const createApiKey = (): {+ apiKey: string;+ prefix: string;+ hashedKey: string;+} => {+ const prefix = randomToken(6);+ const secret = randomToken(24);+ const apiKey = `sk_${prefix}_${secret}`;++ const salt = randomToken(12);+ const hashedKey = `sha256$${salt}$${sha256Hex(`${salt}:${apiKey}`)}`;++ return {+ apiKey,+ prefix,+ hashedKey,+ };+};++/**+ * Extract the prefix from a raw API key+ * @param rawKey Raw API key in format sk_{prefix}_{secret}+ * @returns The prefix portion+ */+export const extractApiKeyPrefix = (rawKey: string): string => {+ const parts = rawKey.split("_").filter(Boolean);+ if (parts.length >= 3 && parts[1]) {+ return parts[1];+ }+ // Fallback for malformed keys+ return rawKey.slice(0, 12);+};++/**+ * Check if a string is a valid hex SHA-256 hash+ * @param value String to validate+ * @returns True if valid hex SHA-256 (64 characters)+ */+export const isHexSha256 = (value: string): boolean =>+ /^[a-f0-9]{64}$/i.test(value);++/**+ * Hash an API key with optional salt (for verification)+ * @param rawKey Raw API key+ * @param salt Optional salt for hashing+ * @returns Hex-encoded SHA-256 hash+ */+export const hashApiKey = (rawKey: string, salt?: string): string => {+ const input = salt ? `${salt}:${rawKey}` : rawKey;+ return sha256Hex(input);+};++/**+ * Verify a raw API key against a stored hash+ * Supports both legacy (unsalted) and current (salted) hash formats+ * @param rawKey Raw API key to verify+ * @param storedHash Stored hash from database (format: "sha256$salt$hash" or plain hex)+ * @returns True if the key matches the hash+ */+export const verifyApiKey = (rawKey: string, storedHash: string): boolean => {+ const trimmed = storedHash.trim();++ // Current format: sha256$salt$hash+ if (trimmed.startsWith("sha256$")) {+ const [, salt, hash] = trimmed.split("$");+ if (!salt || !hash || !isHexSha256(hash)) {+ return false;+ }+ const computed = hashApiKey(rawKey, salt);+ return crypto.timingSafeEqual(Buffer.from(computed), Buffer.from(hash));+ }++ // Legacy format: plain hex hash (unsalted)+ if (!isHexSha256(trimmed)) {+ return false;+ }++ const computed = hashApiKey(rawKey);+ return crypto.timingSafeEqual(Buffer.from(computed), Buffer.from(trimmed));+};diff --git a/apps/web/src/trpc/routers/api-keys.ts b/apps/web/src/trpc/routers/api-keys.tsnew file mode 100644index 000000000..6018420f2--- /dev/null+++ b/apps/web/src/trpc/routers/api-keys.ts@@ -0,0 +1,87 @@+import { prisma } from "@rallly/database";+import { TRPCError } from "@trpc/server";+import { z } from "zod";+import { createApiKey } from "@/features/developer/utils";+import { router, spaceOwnerProcedure } from "../trpc";++export const apiKeys = router({+ list: spaceOwnerProcedure.query(async ({ ctx }) => {+ const keys = await prisma.spaceApiKey.findMany({+ where: {+ spaceId: ctx.space.id,+ },+ select: {+ id: true,+ name: true,+ prefix: true,+ revokedAt: true,+ lastUsedAt: true,+ expiresAt: true,+ createdAt: true,+ },+ orderBy: {+ createdAt: "desc",+ },+ });++ return keys;+ }),+ create: spaceOwnerProcedure+ .input(+ z.object({+ name: z.string().min(1).max(100),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const { apiKey, prefix, hashedKey } = createApiKey();++ await prisma.spaceApiKey.create({+ data: {+ spaceId: ctx.space.id,+ name: input.name,+ prefix,+ hashedKey,+ },+ });++ return { apiKey };+ }),+ revoke: spaceOwnerProcedure+ .input(+ z.object({+ id: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const apiKey = await prisma.spaceApiKey.findUnique({+ where: { id: input.id },+ select: { spaceId: true, revokedAt: true },+ });++ if (!apiKey) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "API key not found",+ });+ }++ if (apiKey.spaceId !== ctx.space.id) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "You do not have permission to revoke this API key",+ });+ }++ if (apiKey.revokedAt) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "API key is already revoked",+ });+ }++ await prisma.spaceApiKey.update({+ where: { id: input.id },+ data: { revokedAt: new Date() },+ });+ }),+});diff --git a/apps/web/src/trpc/routers/index.ts b/apps/web/src/trpc/routers/index.tsindex a7c0172db..8dd994bc6 100644--- a/apps/web/src/trpc/routers/index.ts+++ b/apps/web/src/trpc/routers/index.ts@@ -4,6 +4,7 @@ import toArray from "dayjs/plugin/toArray";import utc from "dayjs/plugin/utc";import { mergeRouters, router } from "../trpc";+import { apiKeys } from "./api-keys";import { auth } from "./auth";import { calendars } from "./calendars";import { events } from "./events";@@ -16,6 +17,7 @@ dayjs.extend(utc);export const appRouter = mergeRouters(router({+ apiKeys,auth,events,polls,diff --git a/apps/web/src/trpc/trpc.ts b/apps/web/src/trpc/trpc.tsindex 01c2c53cc..e3b1ffc3c 100644--- a/apps/web/src/trpc/trpc.ts+++ b/apps/web/src/trpc/trpc.ts@@ -133,6 +133,31 @@ export const proProcedure = privateProcedure.use(async ({ next }) => {return next();});+export const spaceOwnerProcedure = privateProcedure.use(async ({ next }) => {+ const data = await getCurrentUserSpace();++ if (!data) {+ throw new TRPCError({+ code: "UNAUTHORIZED",+ message: "User must be logged in with a space selected",+ });+ }++ if (data.space.ownerId !== data.user.id) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: "Only the space owner can perform this action",+ });+ }++ return next({+ ctx: {+ space: data.space,+ user: data.user,+ },+ });+});+export const createRateLimitMiddleware = (name: string,requests: number,diff --git a/packages/database/package.json b/packages/database/package.jsonindex 83de13f3b..49718aa1b 100644--- a/packages/database/package.json+++ b/packages/database/package.json@@ -8,7 +8,6 @@"db:deploy": "prisma migrate deploy","db:migrate": "prisma migrate dev","db:seed": "tsx prisma/seed.ts",- "db:create-api-key": "tsx prisma/scripts/create-api-key.ts","type-check": "tsc --pretty --noEmit"},"exports": "./index.ts",diff --git a/packages/database/prisma/scripts/create-space-api-key.ts b/packages/database/prisma/scripts/create-space-api-key.tsdeleted file mode 100644index e300e05f0..000000000--- a/packages/database/prisma/scripts/create-space-api-key.ts+++ /dev/null@@ -1,103 +0,0 @@-import { PrismaClient } from "@prisma/client";-import crypto from "node:crypto";--const prisma = new PrismaClient();--type Args = {- spaceId?: string;- spaceName?: string;- name?: string;- expiresAt?: string;-};--const parseArgs = (argv: string[]) => {- return argv.reduce<Args>((acc, arg) => {- const [key, value] = arg.split("=");- if (!key?.startsWith("--")) {- return acc;- }- const normalizedKey = key.slice(2);- const normalizedValue = value?.trim() || undefined;- if (!normalizedValue) {- return acc;- }- if (normalizedKey === "space-id") {- return { ...acc, spaceId: normalizedValue };- }- if (normalizedKey === "space-name") {- return { ...acc, spaceName: normalizedValue };- }- if (normalizedKey === "name") {- return { ...acc, name: normalizedValue };- }- if (normalizedKey === "expires-at") {- return { ...acc, expiresAt: normalizedValue };- }- return acc;- }, {});-};--const randomToken = (bytes: number) => crypto.randomBytes(bytes).toString("base64url");--const sha256Hex = (value: string) =>- crypto.createHash("sha256").update(value).digest("hex");--async function main() {- const args = parseArgs(process.argv.slice(2));-- if (!args.name) {- throw new Error("Missing required arg: --name");- }-- if (!args.spaceId && !args.spaceName) {- throw new Error("Missing required arg: --space-id or --space-name");- }-- const space = args.spaceId- ? await prisma.space.findUnique({ where: { id: args.spaceId }, select: { id: true } })- : await prisma.space.findFirst({- where: { name: args.spaceName },- select: { id: true },- });-- if (!space) {- throw new Error("Space not found");- }-- const prefix = randomToken(6);- const secret = randomToken(24);- const apiKey = `sk_${prefix}_${secret}`;-- const salt = randomToken(12);- const hashedKey = `sha256$${salt}$${sha256Hex(`${salt}:${apiKey}`)}`;-- const expiresAt = args.expiresAt ? new Date(args.expiresAt) : undefined;- if (expiresAt && Number.isNaN(expiresAt.getTime())) {- throw new Error("Invalid --expires-at value (expected ISO date string)");- }-- await prisma.spaceApiKey.create({- data: {- spaceId: space.id,- name: args.name,- prefix,- hashedKey,- expiresAt,- },- select: {- id: true,- },- });-- process.stdout.write(`${apiKey}\n`);-}--main()- .catch((error) => {- process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);- process.exitCode = 1;- })- .finally(async () => {- await prisma.$disconnect();- });-diff --git a/packages/posthog/src/client.tsx b/packages/posthog/src/client.tsxindex 862a24767..af534971e 100644--- a/packages/posthog/src/client.tsx+++ b/packages/posthog/src/client.tsx@@ -2,7 +2,7 @@import posthog from "posthog-js";import type React from "react";-export { usePostHog } from "posthog-js/react";+export { useFeatureFlagEnabled, usePostHog } from "posthog-js/react";import { PostHogProvider as BasePostHogProvider } from "posthog-js/react";diff --git a/packages/ui/src/alert.tsx b/packages/ui/src/alert.tsxindex 14d6ea443..1905788f3 100644--- a/packages/ui/src/alert.tsx+++ b/packages/ui/src/alert.tsx@@ -11,14 +11,14 @@ const alertVariants = cva(variant: {primary:"bg-primary *:data-[slot=alert-description]:text-primary-foreground/90 [&>svg]:text-primary-foreground",- info: "bg-blue-50 text-blue-500 *:data-[slot=alert-description]:text-blue-700/90 dark:bg-blue-950 dark:text-blue-100 dark:*:data-[slot=alert-description]:text-blue-100/90 [&>svg]:text-blue-700/90 dark:[&>svg]:text-blue-100/90",+ info: "bg-blue-50 text-blue-700 *:data-[slot=alert-description]:text-blue-700/90 dark:bg-blue-950 dark:text-blue-100 dark:*:data-[slot=alert-description]:text-blue-100/90 [&>svg]:text-blue-700/90 dark:[&>svg]:text-blue-100/90",warning:- "bg-yellow-50 text-yellow-500 *:data-[slot=alert-description]:text-yellow-500/90 dark:bg-yellow-950 dark:text-yellow-100 dark:*:data-[slot=alert-description]:text-yellow-100/90 [&>svg]:text-yellow-700/90 dark:[&>svg]:text-yellow-100/90",+ "bg-yellow-50 text-yellow-700 *:data-[slot=alert-description]:text-yellow-700/90 dark:bg-yellow-950 dark:text-yellow-100 dark:*:data-[slot=alert-description]:text-yellow-100/90 [&>svg]:text-yellow-700/90 dark:[&>svg]:text-yellow-100/90",success:- "bg-green-50 text-green-500 *:data-[slot=alert-description]:text-green-500/90 dark:bg-green-950 dark:text-green-100 dark:*:data-[slot=alert-description]:text-green-100/90 [&>svg]:text-green-700/90 dark:[&>svg]:text-green-100/90",+ "bg-green-50 text-green-700 *:data-[slot=alert-description]:text-green-700/90 dark:bg-green-950 dark:text-green-100 dark:*:data-[slot=alert-description]:text-green-100/90 [&>svg]:text-green-700/90 dark:[&>svg]:text-green-100/90",note: "bg-muted text-muted-foreground *:data-[slot=alert-description]:text-muted-foreground/75 [&>svg]:text-muted-foreground/90",error:- "bg-rose-50 text-rose-500 *:data-[slot=alert-description]:text-rose-500/90 dark:bg-rose-950 dark:text-rose-100 dark:*:data-[slot=alert-description]:text-rose-100/90 [&>svg]:text-rose-700/90 dark:[&>svg]:text-rose-100/90",+ "bg-rose-50 text-rose-700 *:data-[slot=alert-description]:text-rose-700/90 dark:bg-rose-950 dark:text-rose-100 dark:*:data-[slot=alert-description]:text-rose-100/90 [&>svg]:text-rose-700/90 dark:[&>svg]:text-rose-100/90",},},defaultVariants: {diff --git a/packages/ui/src/badge.tsx b/packages/ui/src/badge.tsxindex bb4533f1a..5c6001f22 100644--- a/packages/ui/src/badge.tsx+++ b/packages/ui/src/badge.tsx@@ -11,10 +11,11 @@ const badgeVariants = cva(variant: {primary: "bg-primary text-primary-foreground",default: "bg-muted",- destructive: "bg-destructive text-destructive-foreground",+ destructive:+ "bg-rose-600/10 text-rose-600 dark:bg-rose-500/10 dark:text-rose-500",outline: "text-foreground",green:- "bg-green-100 text-green-600 dark:bg-green-950 dark:text-green-300",+ "bg-green-600/10 text-green-600 dark:bg-green-500/10 dark:text-green-500",secondary: "bg-primary/10 text-primary",},size: {