Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Cap API keys per space and migrate writes to server actions (RAL-1268) (#2643)

Luke Vella767dcbc7ad5a
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.json
index 859a5f22b..5b1d21fae 100644
--- a/apps/web/public/locales/en/app.json
+++ b/apps/web/public/locales/en/app.json
@@ -46,6 +46,7 @@
"annualSavings": "Save {amount} with yearly billing",
"apiKeyCreated": "API key created",
"apiKeyCreatedDescription": "Copy your API key now. You won't be able to see it again.",
+ "apiKeyLimitReached": "You've reached the maximum number of API keys. Revoke one before creating another.",
"apiKeyNamePlaceholder": "My App",
"apiKeys": "API Keys",
"apiKeysDescription": "Manage API keys for programmatic access to your space",
@@ -147,7 +148,6 @@
"createEventTypeDescription": "Set up a reusable event type that people can book with you.",
"createEventTypeError": "Failed to create event type",
"createEventTypeTitle": "Create Event Type",
- "createFailed": "Failed to create",
"createNewPoll": "Create new poll",
"createPoll": "Create Poll",
"createPollPollCreated": "Poll created",
@@ -562,8 +562,6 @@
"revoke": "Revoke",
"revokeConfirmation": "Are you sure you want to revoke {name}? This will immediately disable the key.",
"revoked": "Revoked",
- "revokeFailed": "Failed to revoke",
- "revoking": "Revoking...",
"role": "Role",
"roleChangedError": "Failed to change role",
"roleChangedSuccess": "Role changed successfully",
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.tsx
index 684b68d9f..039f2bf5a 100644
--- 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.tsx
@@ -9,20 +9,19 @@ import {
EmptyStateIcon,
EmptyStateTitle,
} from "@/components/empty-state";
-import { Spinner } from "@/components/spinner";
import { StackedList, StackedListItem } from "@/components/stacked-list";
+import type { getSpaceApiKeys } from "@/features/api-keys/data";
import { Trans } from "@/i18n/client";
import { useDateTime } from "@/lib/datetime/client";
-import { trpc } from "@/trpc/client";
import { RevokeApiKeyButton } from "./revoke-api-key-button";
-export function ApiKeysList() {
- const { data: apiKeys } = trpc.apiKeys.list.useQuery();
- const { toRelativeTime } = useDateTime();
+type ApiKey = Extract<
+ Awaited<ReturnType<typeof getSpaceApiKeys>>,
+ { ok: true }
+>["apiKeys"][number];
- if (apiKeys === undefined) {
- return <Spinner />;
- }
+export function ApiKeysList({ apiKeys }: { apiKeys: ApiKey[] }) {
+ const { toRelativeTime } = useDateTime();
if (apiKeys.length === 0) {
return (
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.tsx
index 19d2d7495..d2f6a4e5e 100644
--- 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.tsx
@@ -27,25 +27,21 @@ import { AlertTriangleIcon, CheckIcon, CopyIcon, PlusIcon } from "lucide-react";
import React from "react";
import { useForm } from "react-hook-form";
import { useCopyToClipboard } from "react-use";
-import * as z from "zod";
+import { createApiKeyAction } from "@/features/api-keys/actions";
+import { createApiKeySchema } from "@/features/api-keys/schema";
import { Trans, useTranslation } from "@/i18n/client";
-import { trpc } from "@/trpc/client";
-
-const formSchema = z.object({
- name: z.string().min(1).max(100),
-});
+import { useSafeAction } from "@/lib/safe-action/client";
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 createApiKey = useSafeAction(createApiKeyAction);
const [, copy] = useCopyToClipboard();
const [didCopy, setDidCopy] = React.useState(false);
const form = useForm({
- resolver: zodResolver(formSchema),
+ resolver: zodResolver(createApiKeySchema),
defaultValues: {
name: "",
},
@@ -149,15 +145,17 @@ export function CreateApiKeyButton() {
<Form {...form}>
<form
onSubmit={form.handleSubmit(async (data) => {
- try {
- const result = await createApiKey.mutateAsync(data);
- setCreatedApiKey(result.apiKey);
- await utils.apiKeys.list.invalidate();
+ const result = await createApiKey.executeAsync(data);
+ if (result?.data?.ok) {
+ setCreatedApiKey(result.data.apiKey);
form.reset();
- } catch {
+ } else if (
+ result?.data?.reason === "max_api_keys_exceeded"
+ ) {
toast.error(
- t("createFailed", {
- defaultValue: "Failed to create",
+ t("apiKeyLimitReached", {
+ defaultValue:
+ "You've reached the maximum number of API keys. Revoke one before creating another.",
}),
);
}
@@ -190,8 +188,8 @@ export function CreateApiKeyButton() {
<Button
variant="primary"
type="submit"
- disabled={createApiKey.isPending}
- loading={createApiKey.isPending}
+ disabled={createApiKey.isExecuting}
+ loading={createApiKey.isExecuting}
>
<Trans i18nKey="create" defaults="Create" />
</Button>
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.tsx
index 45c23f345..ec4910539 100644
--- 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.tsx
@@ -20,8 +20,9 @@ import {
import { Icon } from "@rallly/ui/icon";
import { toast } from "@rallly/ui/sonner";
import { BanIcon, MoreVerticalIcon } from "lucide-react";
+import { revokeApiKeyAction } from "@/features/api-keys/actions";
import { Trans, useTranslation } from "@/i18n/client";
-import { trpc } from "@/trpc/client";
+import { useSafeAction } from "@/lib/safe-action/client";
export function RevokeApiKeyButton({
apiKeyId,
@@ -32,8 +33,14 @@ export function RevokeApiKeyButton({
}) {
const { t } = useTranslation();
const revokeDialog = useDialog();
- const revokeApiKey = trpc.apiKeys.revoke.useMutation();
- const utils = trpc.useUtils();
+ const revokeApiKey = useSafeAction(revokeApiKeyAction, {
+ onSuccess: () => {
+ toast.success(t("revoked", { defaultValue: "Revoked" }));
+ },
+ onSettled: () => {
+ revokeDialog.dismiss();
+ },
+ });
return (
<>
@@ -83,28 +90,9 @@ export function RevokeApiKeyButton({
<DialogFooter>
<Button
variant="destructive"
+ loading={revokeApiKey.isExecuting}
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();
+ revokeApiKey.execute({ id: apiKeyId });
}}
>
<Trans i18nKey="revoke" defaults="Revoke" />
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.tsx
index 39dc282b7..0c21f41da 100644
--- a/apps/web/src/app/[locale]/(space)/settings/api-keys/page.tsx
+++ b/apps/web/src/app/[locale]/(space)/settings/api-keys/page.tsx
@@ -1,6 +1,5 @@
-import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
import type { Metadata } from "next";
-import { notFound } from "next/navigation";
+import { notFound, redirect } from "next/navigation";
import {
PageSection,
PageSectionContent,
@@ -13,48 +12,56 @@ import {
SettingsPageHeader,
SettingsPageTitle,
} from "@/components/settings-layout";
+import { getSpaceApiKeys } from "@/features/api-keys/data";
import { Trans } from "@/i18n/client";
import { getTranslation } from "@/i18n/server";
-import { createPrivateSSRHelper } from "@/trpc/server/create-ssr-helper";
+import { getPathname } from "@/lib/pathname";
+import { buildSafeRedirectUrl } from "@/lib/utils/redirect";
import { ApiKeysList } from "./components/api-keys-list";
import { CreateApiKeyButton } from "./components/create-api-key-button";
export default async function ApiKeysSettingsPage() {
- const helpers = await createPrivateSSRHelper();
- try {
- await helpers.apiKeys.list.prefetch();
- } catch {
+ const result = await getSpaceApiKeys();
+
+ if (!result.ok) {
+ if (result.reason === "unauthorized") {
+ redirect(
+ buildSafeRedirectUrl({
+ destination: "/login",
+ returnUrl: await getPathname(),
+ }),
+ );
+ }
+
notFound();
}
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>
+ <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 apiKeys={result.apiKeys} />
+ </PageSectionContent>
+ </PageSection>
+ </PageSectionGroup>
+ </SettingsPageContent>
+ </SettingsPage>
);
}
diff --git a/apps/web/src/features/api-keys/ability.ts b/apps/web/src/features/api-keys/ability.ts
new file mode 100644
index 000000000..6f98ba285
--- /dev/null
+++ b/apps/web/src/features/api-keys/ability.ts
@@ -0,0 +1,22 @@
+import type { PureAbility } from "@casl/ability";
+import { AbilityBuilder } from "@casl/ability";
+import type { PrismaQuery, Subjects } from "@casl/prisma";
+import { createPrismaAbility } from "@casl/prisma";
+
+type Action = "revoke";
+type Subject = Subjects<{
+ ApiKey: {
+ spaceId: string;
+ };
+}>;
+
+export type ApiKeyAbility = PureAbility<[Action, Subject], PrismaQuery>;
+
+export function defineAbilityForApiKeys(context: { spaceId: string }) {
+ const { can, build } = new AbilityBuilder<ApiKeyAbility>(createPrismaAbility);
+
+ // A key can only be revoked from within the space that owns it.
+ can("revoke", "ApiKey", { spaceId: context.spaceId });
+
+ return build();
+}
diff --git a/apps/web/src/features/api-keys/actions.ts b/apps/web/src/features/api-keys/actions.ts
new file mode 100644
index 000000000..496e5b993
--- /dev/null
+++ b/apps/web/src/features/api-keys/actions.ts
@@ -0,0 +1,80 @@
+"use server";
+
+import { getApiKeyAccessContext } from "@/features/api-keys/data";
+import { createApiKey, revokeApiKey } from "@/features/api-keys/mutations";
+import {
+ createApiKeySchema,
+ revokeApiKeySchema,
+} from "@/features/api-keys/schema";
+import { AppError } from "@/lib/errors/app-error";
+import { posthog } from "@/lib/posthog";
+import { authActionClient } from "@/lib/safe-action/server";
+
+// The UI never offers these actions to users without API access, so a
+// failed gate is unexpected here — throw for the global error handler.
+async function requireApiAccess() {
+ const context = await getApiKeyAccessContext();
+
+ if (!context.ok) {
+ switch (context.reason) {
+ case "unauthorized":
+ throw new AppError({
+ code: "UNAUTHORIZED",
+ message: "You are not authenticated.",
+ });
+ case "no_active_space":
+ throw new AppError({
+ code: "NOT_FOUND",
+ message: "Space not found",
+ });
+ case "api_access_not_enabled":
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "API access is not enabled for this user or space",
+ });
+ }
+ }
+
+ return context;
+}
+
+export const createApiKeyAction = authActionClient
+ .metadata({ actionName: "create_api_key" })
+ .inputSchema(createApiKeySchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { space } = await requireApiAccess();
+
+ const result = await createApiKey({
+ spaceId: space.id,
+ name: parsedInput.name,
+ });
+
+ if (result.ok) {
+ posthog()?.capture({
+ distinctId: ctx.user.id,
+ event: "developer:api_key_create",
+ groups: {
+ space: space.id,
+ },
+ });
+ }
+
+ return result;
+ });
+
+export const revokeApiKeyAction = authActionClient
+ .metadata({ actionName: "revoke_api_key" })
+ .inputSchema(revokeApiKeySchema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { space } = await requireApiAccess();
+
+ await revokeApiKey({ spaceId: space.id, id: parsedInput.id });
+
+ posthog()?.capture({
+ distinctId: ctx.user.id,
+ event: "developer:api_key_revoke",
+ groups: {
+ space: space.id,
+ },
+ });
+ });
diff --git a/apps/web/src/features/api-keys/data.ts b/apps/web/src/features/api-keys/data.ts
index 75cd674d4..b5c34f953 100644
--- a/apps/web/src/features/api-keys/data.ts
+++ b/apps/web/src/features/api-keys/data.ts
@@ -1,16 +1,74 @@
import "server-only";
+import { prisma } from "@rallly/database";
+import { cache } from "react";
+import { getActiveSpaceForUser } from "@/features/space/data";
import type { SpaceTier } from "@/features/space/schema";
+import { getCurrentUser } from "@/features/user/data";
import { isSelfHosted } from "@/lib/constants";
import { posthog } from "@/lib/posthog";
+/**
+ * Resolve the current user's space and verify API access. Auth is enforced
+ * here in the DAL so no call site can fetch API keys without the gate.
+ * Failures are returned as values; stale sessions still throw
+ * InvalidSessionError from getCurrentUser for the boundary to handle.
+ */
+export const getApiKeyAccessContext = cache(async () => {
+ const user = await getCurrentUser();
+
+ if (!user) {
+ return { ok: false, reason: "unauthorized" } as const;
+ }
+
+ const space = await getActiveSpaceForUser(user.id);
+
+ if (!space) {
+ return { ok: false, reason: "no_active_space" } as const;
+ }
+
+ if (!(await isApiAccessEnabled(user, space))) {
+ return { ok: false, reason: "api_access_not_enabled" } as const;
+ }
+
+ return { ok: true, user, space } as const;
+});
+
+export const getSpaceApiKeys = cache(async () => {
+ const context = await getApiKeyAccessContext();
+
+ if (!context.ok) {
+ return context;
+ }
+
+ const apiKeys = await prisma.spaceApiKey.findMany({
+ where: {
+ spaceId: context.space.id,
+ },
+ select: {
+ id: true,
+ name: true,
+ prefix: true,
+ revokedAt: true,
+ lastUsedAt: true,
+ expiresAt: true,
+ createdAt: true,
+ },
+ orderBy: {
+ createdAt: "desc",
+ },
+ });
+
+ return { ok: true, apiKeys } as const;
+});
+
/**
* Determines if a user has access to API features (API keys, developer tools)
* @param user - The user to check access for
* @param space - The space to check access for
* @returns True if the user can access API features
*/
-export async function isApiAccessEnabled(
+async function isApiAccessEnabled(
user: {
id: string;
},
diff --git a/apps/web/src/features/api-keys/mutations.ts b/apps/web/src/features/api-keys/mutations.ts
new file mode 100644
index 000000000..c8e9d9efc
--- /dev/null
+++ b/apps/web/src/features/api-keys/mutations.ts
@@ -0,0 +1,97 @@
+import "server-only";
+
+import { subject } from "@casl/ability";
+import { prisma } from "@rallly/database";
+import { defineAbilityForApiKeys } from "@/features/api-keys/ability";
+import { generateApiKey } from "@/features/api-keys/utils";
+import { AppError } from "@/lib/errors/app-error";
+import { MAX_ACTIVE_API_KEYS_PER_SPACE } from "./schema";
+
+async function countActiveApiKeys(spaceId: string) {
+ return prisma.spaceApiKey.count({
+ where: {
+ spaceId,
+ revokedAt: null,
+ OR: [{ expiresAt: null }, { expiresAt: { gt: new Date() } }],
+ },
+ });
+}
+
+export async function createApiKey({
+ spaceId,
+ name,
+}: {
+ spaceId: string;
+ name: string;
+}) {
+ const activeCount = await countActiveApiKeys(spaceId);
+
+ // Expected outcome the caller handles specifically, so it's part of the
+ // return value; thrown errors are reserved for the global error handler.
+ if (activeCount >= MAX_ACTIVE_API_KEYS_PER_SPACE) {
+ return { ok: false, reason: "max_api_keys_exceeded" } as const;
+ }
+
+ const { apiKey, prefix, hashedKey } = await generateApiKey();
+
+ await prisma.spaceApiKey.create({
+ data: {
+ spaceId,
+ name,
+ prefix,
+ hashedKey,
+ },
+ });
+
+ return { ok: true, apiKey } as const;
+}
+
+export async function revokeApiKey({
+ spaceId,
+ id,
+}: {
+ spaceId: string;
+ id: string;
+}) {
+ const apiKey = await prisma.spaceApiKey.findUnique({
+ where: { id },
+ select: { spaceId: true, revokedAt: true },
+ });
+
+ if (!apiKey) {
+ throw new AppError({
+ code: "NOT_FOUND",
+ message: "API key not found",
+ });
+ }
+
+ const ability = defineAbilityForApiKeys({ spaceId });
+
+ if (ability.cannot("revoke", subject("ApiKey", apiKey))) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "You do not have permission to revoke this API key",
+ });
+ }
+
+ if (apiKey.revokedAt) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "API key is already revoked",
+ });
+ }
+
+ // Guard on revokedAt so a concurrent revoke can't have both requests report
+ // success (and emit duplicate lifecycle events). The loser updates 0 rows.
+ const { count } = await prisma.spaceApiKey.updateMany({
+ where: { id, revokedAt: null },
+ data: { revokedAt: new Date() },
+ });
+
+ if (count === 0) {
+ throw new AppError({
+ code: "FORBIDDEN",
+ message: "API key is already revoked",
+ });
+ }
+}
diff --git a/apps/web/src/features/api-keys/schema.ts b/apps/web/src/features/api-keys/schema.ts
new file mode 100644
index 000000000..6517c63b4
--- /dev/null
+++ b/apps/web/src/features/api-keys/schema.ts
@@ -0,0 +1,13 @@
+import * as z from "zod";
+
+// Cap on active (not revoked, not expired) keys per space. With per-space rate
+// limiting this is not a security control, just clutter prevention.
+export const MAX_ACTIVE_API_KEYS_PER_SPACE = 10;
+
+export const createApiKeySchema = z.object({
+ name: z.string().min(1).max(100),
+});
+
+export const revokeApiKeySchema = z.object({
+ id: z.string(),
+});
diff --git a/apps/web/src/features/api-keys/utils.test.ts b/apps/web/src/features/api-keys/utils.test.ts
index 132d42561..efb4c7fb1 100644
--- a/apps/web/src/features/api-keys/utils.test.ts
+++ b/apps/web/src/features/api-keys/utils.test.ts
@@ -1,8 +1,8 @@
import crypto from "node:crypto";
import { describe, expect, it } from "vitest";
import {
- createApiKey,
extractApiKeyPrefix,
+ generateApiKey,
hashApiKey,
isLegacyApiKeyHash,
randomToken,
@@ -38,32 +38,32 @@ describe("randomToken", () => {
});
});
-describe("createApiKey", () => {
+describe("generateApiKey", () => {
it("should generate an API key with correct format", async () => {
- const result = await createApiKey();
+ const result = await generateApiKey();
expect(result.apiKey).toMatch(/^sk_[A-Za-z0-9_-]+_[A-Za-z0-9_-]+$/);
});
it("should generate unique API keys on each call", async () => {
- const result1 = await createApiKey();
- const result2 = await createApiKey();
+ const result1 = await generateApiKey();
+ const result2 = await generateApiKey();
expect(result1.apiKey).not.toBe(result2.apiKey);
expect(result1.prefix).not.toBe(result2.prefix);
});
it("should generate a valid prefix", async () => {
- const result = await createApiKey();
+ const result = await generateApiKey();
expect(result.prefix).toBeTruthy();
expect(result.prefix.length).toBeGreaterThan(0);
});
it("should generate a hashed key in sha256 format", async () => {
- const result = await createApiKey();
+ const result = await generateApiKey();
expect(result.hashedKey).toMatch(/^sha256\$[A-Za-z0-9_-]+\$[a-f0-9]{64}$/);
});
it("should verify the generated API key against its hash", async () => {
- const result = await createApiKey();
+ const result = await generateApiKey();
const isValid = await verifyApiKey(result.apiKey, result.hashedKey);
expect(isValid).toBe(true);
});
@@ -111,7 +111,7 @@ describe("extractApiKeyPrefix", () => {
it("should extract the stored prefix from generated keys", async () => {
for (let i = 0; i < 50; i++) {
- const result = await createApiKey();
+ const result = await generateApiKey();
expect(extractApiKeyPrefix(result.apiKey)).toBe(result.prefix);
}
});
@@ -119,20 +119,20 @@ describe("extractApiKeyPrefix", () => {
describe("verifyApiKey", () => {
it("should verify correct API key", async () => {
- const result = await createApiKey();
+ const result = await generateApiKey();
const isValid = await verifyApiKey(result.apiKey, result.hashedKey);
expect(isValid).toBe(true);
});
it("should reject incorrect API key", async () => {
- const result = await createApiKey();
+ const result = await generateApiKey();
const wrongKey = "sk_wrong_prefix_wrong_secret";
const isValid = await verifyApiKey(wrongKey, result.hashedKey);
expect(isValid).toBe(false);
});
it("should reject API key with tampered salt", async () => {
- const result = await createApiKey();
+ const result = await generateApiKey();
const parts = result.hashedKey.split("$");
parts[1] = "wrongsalt";
const tamperedHash = parts.join("$");
@@ -141,7 +141,7 @@ describe("verifyApiKey", () => {
});
it("should reject API key with tampered hash", async () => {
- const result = await createApiKey();
+ const result = await generateApiKey();
const parts = result.hashedKey.split("$");
parts[2] = "0".repeat(64);
const tamperedHash = parts.join("$");
@@ -150,7 +150,7 @@ describe("verifyApiKey", () => {
});
it("should reject malformed hash format", async () => {
- const result = await createApiKey();
+ const result = await generateApiKey();
const isValid = await verifyApiKey(result.apiKey, "sha256$saltonly");
expect(isValid).toBe(false);
});
@@ -204,7 +204,7 @@ describe("verifyApiKey", () => {
});
it("should handle hashes with whitespace", async () => {
- const result = await createApiKey();
+ const result = await generateApiKey();
const hashWithSpace = ` ${result.hashedKey} `;
const isValid = await verifyApiKey(result.apiKey, hashWithSpace);
expect(isValid).toBe(true);
@@ -221,7 +221,7 @@ describe("verifyApiKey", () => {
});
it("should use constant-time comparison", async () => {
- const result = await createApiKey();
+ const result = await generateApiKey();
// Both should complete without throwing
await expect(
diff --git a/apps/web/src/features/api-keys/utils.ts b/apps/web/src/features/api-keys/utils.ts
index 02f910c47..b5e1522a8 100644
--- a/apps/web/src/features/api-keys/utils.ts
+++ b/apps/web/src/features/api-keys/utils.ts
@@ -34,10 +34,10 @@ const API_KEY_SCHEME = "sk_";
const API_KEY_PREFIX_LENGTH = 8;
/**
- * Create an API key with the format: sk_{prefix}_{secret}
+ * Generate API key material with the format: sk_{prefix}_{secret}
* @returns Object containing the full API key and components for storage
*/
-export const createApiKey = async (): Promise<{
+export const generateApiKey = async (): Promise<{
apiKey: string;
prefix: string;
hashedKey: string;
diff --git a/apps/web/src/features/space/data.ts b/apps/web/src/features/space/data.ts
index fd9a01c60..a837bf21f 100644
--- a/apps/web/src/features/space/data.ts
+++ b/apps/web/src/features/space/data.ts
@@ -5,6 +5,7 @@ import type {
SpaceTier as DBSpaceTier,
} from "@rallly/database";
import { prisma } from "@rallly/database";
+import { cache } from "react";
import type { MemberDTO } from "@/features/space/member/types";
import type { SpaceDTO } from "@/features/space/types";
@@ -111,7 +112,7 @@ export function getSpaceBranding(spaceId: string) {
});
}
-export const getActiveSpaceForUser = async (userId: string) => {
+export const getActiveSpaceForUser = cache(async (userId: string) => {
const spaceMember = await prisma.spaceMember.findFirst({
where: {
userId,
@@ -132,4 +133,4 @@ export const getActiveSpaceForUser = async (userId: string) => {
...spaceMember.space,
role: spaceMember.role,
});
-};
+});
diff --git a/apps/web/src/trpc/routers/api-keys.ts b/apps/web/src/trpc/routers/api-keys.ts
deleted file mode 100644
index 9f6e1e1ae..000000000
--- a/apps/web/src/trpc/routers/api-keys.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import { prisma } from "@rallly/database";
-import { TRPCError } from "@trpc/server";
-import * as z from "zod";
-import { isApiAccessEnabled } from "@/features/api-keys/data";
-import { createApiKey } from "@/features/api-keys/utils";
-import { router, spaceOwnerProcedure } from "../trpc";
-
-const apiAccessProcedure = spaceOwnerProcedure.use(async ({ ctx, next }) => {
- const hasAccess = await isApiAccessEnabled(ctx.user, ctx.space);
-
- if (!hasAccess) {
- throw new TRPCError({
- code: "FORBIDDEN",
- message: "API access is not enabled for this user or space",
- });
- }
-
- return next();
-});
-
-export const apiKeys = router({
- list: apiAccessProcedure.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: apiAccessProcedure
- .input(
- z.object({
- name: z.string().min(1).max(100),
- }),
- )
- .mutation(async ({ input, ctx }) => {
- const { apiKey, prefix, hashedKey } = await createApiKey();
-
- await prisma.spaceApiKey.create({
- data: {
- spaceId: ctx.space.id,
- name: input.name,
- prefix,
- hashedKey,
- },
- });
-
- return { apiKey };
- }),
- revoke: apiAccessProcedure
- .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.ts
index cffc0f31a..79d07712c 100644
--- a/apps/web/src/trpc/routers/index.ts
+++ b/apps/web/src/trpc/routers/index.ts
@@ -1,7 +1,6 @@
import "@/lib/dayjs";
import { mergeRouters, router } from "../trpc";
-import { apiKeys } from "./api-keys";
import { auth } from "./auth";
import { billing } from "./billing";
import { calendars } from "./calendars";
@@ -15,7 +14,6 @@ import { user } from "./user";
export const appRouter = mergeRouters(
router({
- apiKeys,
auth,
billing,
dashboard,