Skip to content

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

🚀 Add support for space level api keys (#2113)

Luke Vella8a902b543471
diff --git a/apps/web/src/app/api/private/[...route]/route.test.ts b/apps/web/src/app/api/private/[...route]/route.test.ts
index 14e3f31f9..3fec06940 100644
--- a/apps/web/src/app/api/private/[...route]/route.test.ts
+++ b/apps/web/src/app/api/private/[...route]/route.test.ts
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@rallly/database", () => ({
prisma: {
- apiKey: {
+ spaceApiKey: {
findUnique: vi.fn(),
update: vi.fn(),
},
@@ -46,26 +46,30 @@ const createMockApiKey = (rawKey: string) => {
id: "api-key-id",
name: "Test API Key",
prefix: "abc123",
- userId: "test-user-id",
+ spaceId: "test-space-id",
hashedKey,
lastUsedAt: null,
expiresAt: null,
revokedAt: null,
createdAt: new Date("2025-01-01"),
updatedAt: new Date("2025-01-01"),
+ space: {
+ ownerId: "test-user-id",
+ },
};
};
describe("Private API - /polls", () => {
- const testApiKey = "rallly_abc123_secretkey";
+ const testApiKey = "sk_abc123_secretkey";
const mockApiKey = createMockApiKey(testApiKey);
beforeEach(() => {
vi.clearAllMocks();
- vi.mocked(prisma.apiKey.findUnique).mockResolvedValue(mockApiKey);
- vi.mocked(prisma.apiKey.update).mockResolvedValue({} as never);
+ vi.mocked(prisma.spaceApiKey.findUnique).mockResolvedValue(mockApiKey);
+ vi.mocked(prisma.spaceApiKey.update).mockResolvedValue({} as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
+ id: "test-user-id",
timeZone: "Europe/London",
} as never);
vi.mocked(prisma.spaceMember.findFirst).mockResolvedValue(null);
@@ -89,7 +93,7 @@ describe("Private API - /polls", () => {
});
it("should return 401 with invalid API key", async () => {
- vi.mocked(prisma.apiKey.findUnique).mockResolvedValue(null);
+ vi.mocked(prisma.spaceApiKey.findUnique).mockResolvedValue(null);
const res = await app.request("/api/private/polls", {
method: "POST",
@@ -107,7 +111,7 @@ describe("Private API - /polls", () => {
});
it("should return 401 with revoked API key", async () => {
- vi.mocked(prisma.apiKey.findUnique).mockResolvedValue({
+ vi.mocked(prisma.spaceApiKey.findUnique).mockResolvedValue({
...mockApiKey,
revokedAt: new Date(),
});
@@ -128,7 +132,7 @@ describe("Private API - /polls", () => {
});
it("should return 401 with expired API key", async () => {
- vi.mocked(prisma.apiKey.findUnique).mockResolvedValue({
+ vi.mocked(prisma.spaceApiKey.findUnique).mockResolvedValue({
...mockApiKey,
expiresAt: new Date("2020-01-01"),
});
@@ -198,42 +202,6 @@ describe("Private API - /polls", () => {
);
});
- it("should deduplicate date options", async () => {
- const res = await app.request("/api/private/polls", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${testApiKey}`,
- },
- body: JSON.stringify({
- title: "Test Poll",
- dates: ["2025-01-15", "2025-01-15", "2025-01-16"],
- }),
- });
-
- expect(res.status).toBe(200);
- expect(prisma.poll.create).toHaveBeenCalledWith(
- expect.objectContaining({
- data: expect.objectContaining({
- options: {
- createMany: {
- data: [
- {
- startTime: new Date("2025-01-15T00:00:00.000Z"),
- duration: 0,
- },
- {
- startTime: new Date("2025-01-16T00:00:00.000Z"),
- duration: 0,
- },
- ],
- },
- },
- }),
- }),
- );
- });
-
it("should save location when provided", async () => {
const res = await app.request("/api/private/polls", {
method: "POST",
@@ -281,6 +249,25 @@ describe("Private API - /polls", () => {
const json = await res.json();
expect(json.error.code).toBe("TOO_MANY_OPTIONS");
});
+
+ it("should return error when duplicate dates are provided", async () => {
+ const res = await app.request("/api/private/polls", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ body: JSON.stringify({
+ title: "Test Poll",
+ dates: ["2025-01-15", "2025-01-16", "2025-01-15", "2025-01-17"],
+ }),
+ });
+
+ expect(res.status).toBe(400);
+ const json = await res.json();
+ expect(json.error.code).toBe("DUPLICATE_DATES");
+ expect(json.error.message).toContain("Duplicate dates found");
+ });
});
describe("Create poll with slots", () => {
diff --git a/apps/web/src/app/api/private/[...route]/route.ts b/apps/web/src/app/api/private/[...route]/route.ts
index 31ac93dc9..9fd019172 100644
--- a/apps/web/src/app/api/private/[...route]/route.ts
+++ b/apps/web/src/app/api/private/[...route]/route.ts
@@ -17,7 +17,7 @@ import {
createPollSuccessResponseSchema,
errorResponseSchema,
} from "../schemas";
-import { apiKeyAuth } from "../utils/api-key";
+import { spaceApiKeyAuth } from "../utils/api-key";
import { apiError, createPoll } from "../utils/poll";
import type { SlotGeneratorInput } from "../utils/time-slots";
import {
@@ -29,7 +29,8 @@ import {
type Env = {
Variables: {
apiAuth: {
- userId: string;
+ spaceId: string;
+ spaceOwnerId: string;
apiKeyId: string;
};
};
@@ -71,7 +72,7 @@ app.get(
app.post(
"/polls",
- apiKeyAuth,
+ spaceApiKeyAuth,
rateLimiter<Env>({
windowMs: 60 * 1000,
limit: 60,
@@ -109,33 +110,48 @@ app.post(
validator("json", createPollInputSchema),
async (c) => {
const input = c.req.valid("json");
- const { userId } = c.get("apiAuth");
+ const { spaceId, spaceOwnerId } = c.get("apiAuth");
const user = await prisma.user.findUnique({
- where: { id: userId },
- select: { timeZone: true },
+ where: { id: spaceOwnerId },
+ select: { id: true, timeZone: true },
});
+ if (!user) {
+ return c.json(apiError("UNAUTHORIZED", "User not found"), 401);
+ }
+
// Process dates (all-day options)
if (input.dates) {
- const uniqueDates = [...new Set(input.dates)];
- const options = uniqueDates.map((date) => ({
- startTime: new Date(`${date}T00:00:00.000Z`),
- duration: 0,
- }));
-
- if (options.length > MAX_OPTIONS) {
+ if (input.dates.length > MAX_OPTIONS) {
return c.json(
apiError(
"TOO_MANY_OPTIONS",
- `Too many options (${options.length}). Maximum allowed is ${MAX_OPTIONS}.`,
+ `Too many options (${input.dates.length}). Maximum allowed is ${MAX_OPTIONS}.`,
),
400,
);
}
+ const uniqueDates = [...new Set(input.dates)];
+ if (uniqueDates.length < input.dates.length) {
+ const duplicateCount = input.dates.length - uniqueDates.length;
+ return c.json(
+ apiError(
+ "DUPLICATE_DATES",
+ `Duplicate dates found. Please remove ${duplicateCount} duplicate date${duplicateCount > 1 ? "s" : ""}.`,
+ ),
+ 400,
+ );
+ }
+
+ const options = uniqueDates.map((date) => ({
+ startTime: new Date(`${date}T00:00:00.000Z`),
+ duration: 0,
+ }));
+
const poll = await createPoll({
- userId,
+ userId: user.id,
title: input.title,
description: input.description,
location: input.location,
@@ -144,6 +160,8 @@ app.post(
hideScores: input.hideScores,
disableComments: input.disableComments,
options,
+ spaceId,
+ spaceOwnerId,
});
return c.json({
@@ -227,7 +245,7 @@ app.post(
}
const poll = await createPoll({
- userId,
+ userId: spaceOwnerId,
title: input.title,
description: input.description,
location: input.location,
@@ -237,6 +255,8 @@ app.post(
hideScores: input.hideScores,
disableComments: input.disableComments,
options,
+ spaceId,
+ spaceOwnerId,
});
return c.json({
diff --git a/apps/web/src/app/api/private/utils/api-key.ts b/apps/web/src/app/api/private/utils/api-key.ts
index 1cced7fc6..b3c8c3cd5 100644
--- a/apps/web/src/app/api/private/utils/api-key.ts
+++ b/apps/web/src/app/api/private/utils/api-key.ts
@@ -37,18 +37,23 @@ const verifyApiKey = (rawKey: string, stored: string) => {
return crypto.timingSafeEqual(Buffer.from(computed), Buffer.from(trimmed));
};
-export const apiKeyAuth = bearerAuth({
+export const spaceApiKeyAuth = bearerAuth({
verifyToken: async (rawKey, c) => {
const prefix = extractApiKeyPrefix(rawKey);
- const apiKey = await prisma.apiKey.findUnique({
+ const apiKey = await prisma.spaceApiKey.findUnique({
where: { prefix },
select: {
id: true,
- userId: true,
+ spaceId: true,
hashedKey: true,
expiresAt: true,
revokedAt: true,
+ space: {
+ select: {
+ ownerId: true,
+ },
+ },
},
});
@@ -69,12 +74,13 @@ export const apiKeyAuth = bearerAuth({
}
c.set("apiAuth", {
- userId: apiKey.userId,
+ spaceId: apiKey.spaceId,
+ spaceOwnerId: apiKey.space.ownerId,
apiKeyId: apiKey.id,
});
waitUntil(
- prisma.apiKey.update({
+ prisma.spaceApiKey.update({
where: { id: apiKey.id },
data: { lastUsedAt: new Date() },
}),
diff --git a/apps/web/src/app/api/private/utils/poll.ts b/apps/web/src/app/api/private/utils/poll.ts
index 490f0324e..7a174647a 100644
--- a/apps/web/src/app/api/private/utils/poll.ts
+++ b/apps/web/src/app/api/private/utils/poll.ts
@@ -18,6 +18,8 @@ export type CreatePollParams = {
hideScores?: boolean;
disableComments?: boolean;
options: PollOption[];
+ spaceId?: string;
+ spaceOwnerId?: string;
};
export const createPoll = async ({
@@ -31,12 +33,21 @@ export const createPoll = async ({
hideScores,
disableComments,
options,
+ spaceId,
+ spaceOwnerId,
}: CreatePollParams) => {
- const spaceMember = await prisma.spaceMember.findFirst({
- where: { userId },
- orderBy: { lastSelectedAt: "desc" },
- select: { spaceId: true },
- });
+ // If spaceId and spaceOwnerId are provided, use them directly
+ // Otherwise, fall back to looking up the user's most recent space
+ const finalUserId = spaceOwnerId ?? userId;
+ const finalSpaceId =
+ spaceId ??
+ (
+ await prisma.spaceMember.findFirst({
+ where: { userId },
+ orderBy: { lastSelectedAt: "desc" },
+ select: { spaceId: true },
+ })
+ )?.spaceId;
const poll = await prisma.poll.create({
data: {
@@ -51,10 +62,10 @@ export const createPoll = async ({
disableComments,
adminUrlId: nanoid(),
participantUrlId: nanoid(),
- userId,
- watchers: { create: { userId } },
+ userId: finalUserId,
+ watchers: { create: { userId: finalUserId } },
options: { createMany: { data: options } },
- spaceId: spaceMember?.spaceId,
+ spaceId: finalSpaceId,
},
select: { id: true },
});
diff --git a/packages/database/prisma/migrations/20260107154216_add_space_api_keys/migration.sql b/packages/database/prisma/migrations/20260107154216_add_space_api_keys/migration.sql
new file mode 100644
index 000000000..85d734318
--- /dev/null
+++ b/packages/database/prisma/migrations/20260107154216_add_space_api_keys/migration.sql
@@ -0,0 +1,30 @@
+-- CreateTable
+CREATE TABLE "space_api_keys" (
+ "id" TEXT NOT NULL,
+ "space_id" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "prefix" TEXT NOT NULL,
+ "hashed_key" TEXT NOT NULL,
+ "last_used_at" TIMESTAMP(3),
+ "expires_at" TIMESTAMP(3),
+ "revoked_at" TIMESTAMP(3),
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "space_api_keys_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "space_api_keys_prefix_key" ON "space_api_keys"("prefix");
+
+-- CreateIndex
+CREATE INDEX "space_api_key_space_idx" ON "space_api_keys"("space_id");
+
+-- CreateIndex
+CREATE INDEX "space_api_key_expires_idx" ON "space_api_keys"("expires_at");
+
+-- CreateIndex
+CREATE INDEX "space_api_key_revoked_idx" ON "space_api_keys"("revoked_at");
+
+-- AddForeignKey
+ALTER TABLE "space_api_keys" ADD CONSTRAINT "space_api_keys_space_id_fkey" FOREIGN KEY ("space_id") REFERENCES "spaces"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/packages/database/prisma/models/space.prisma b/packages/database/prisma/models/space.prisma
index ffd80f52c..4659c48ec 100644
--- a/packages/database/prisma/models/space.prisma
+++ b/packages/database/prisma/models/space.prisma
@@ -16,6 +16,8 @@ model Space {
memberInvites SpaceMemberInvite[]
+ apiKeys SpaceApiKey[]
+
@@index([ownerId], type: Hash)
@@map("spaces")
}
@@ -66,3 +68,25 @@ model SpaceMemberInvite {
@@index([spaceId], type: Hash, map: "space_member_invites_space_id_idx")
@@map("space_member_invites")
}
+
+model SpaceApiKey {
+ id String @id @default(cuid())
+ spaceId String @map("space_id")
+ name String
+ prefix String @unique
+ hashedKey String @map("hashed_key") @db.Text
+
+ lastUsedAt DateTime? @map("last_used_at")
+ expiresAt DateTime? @map("expires_at")
+ revokedAt DateTime? @map("revoked_at")
+
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @updatedAt @map("updated_at")
+
+ space Space @relation(fields: [spaceId], references: [id], onDelete: Cascade)
+
+ @@index([spaceId], name: "space_api_key_space_idx")
+ @@index([expiresAt], name: "space_api_key_expires_idx")
+ @@index([revokedAt], name: "space_api_key_revoked_idx")
+ @@map("space_api_keys")
+}
diff --git a/packages/database/prisma/scripts/create-space-api-key.ts b/packages/database/prisma/scripts/create-space-api-key.ts
new file mode 100644
index 000000000..e300e05f0
--- /dev/null
+++ b/packages/database/prisma/scripts/create-space-api-key.ts
@@ -0,0 +1,103 @@
+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();
+ });
+