Skip to content

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

🚧 Rest API (#2085)

Luke Vella8872c12ef802
diff --git a/apps/web/package.json b/apps/web/package.json
index 84f0d82c2..4ce75964c 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -25,6 +25,8 @@
"@casl/prisma": "^1.5.1",
"@casl/react": "^5.0.0",
"@hono-rate-limiter/redis": "^0.1.4",
+ "@hono/standard-validator": "^0.2.1",
+ "@hono/zod-openapi": "^1.2.0",
"@hono/zod-validator": "^0.7.2",
"@hookform/resolvers": "^5.2.2",
"@next/env": "^15.4.8",
@@ -41,6 +43,7 @@
"@rallly/tailwind-config": "workspace:*",
"@rallly/ui": "workspace:*",
"@rallly/utils": "workspace:*",
+ "@scalar/hono-api-reference": "^0.9.30",
"@sentry/nextjs": "^9.14.0",
"@svgr/webpack": "^8.1.0",
"@t3-oss/env-nextjs": "^0.13.8",
@@ -67,6 +70,7 @@
"es-toolkit": "^1.39.9",
"googleapis": "^169.0.0",
"hono": "^4.11.1",
+ "hono-openapi": "^1.1.2",
"hono-rate-limiter": "^0.2.1",
"i18next": "^24.2.2",
"i18next-icu": "^2.3.0",
diff --git a/apps/web/src/app/api/private/[...route]/route.test.ts b/apps/web/src/app/api/private/[...route]/route.test.ts
new file mode 100644
index 000000000..ff127b383
--- /dev/null
+++ b/apps/web/src/app/api/private/[...route]/route.test.ts
@@ -0,0 +1,502 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@rallly/database", () => ({
+ prisma: {
+ apiKey: {
+ findUnique: vi.fn(),
+ update: vi.fn(),
+ },
+ user: {
+ findUnique: vi.fn(),
+ },
+ spaceMember: {
+ findFirst: vi.fn(),
+ },
+ poll: {
+ create: vi.fn(),
+ },
+ },
+}));
+
+vi.mock("@rallly/utils/absolute-url", () => ({
+ absoluteUrl: (path: string) => `https://example.com${path}`,
+ shortUrl: (path: string) => `https://example.com${path}`,
+}));
+
+vi.mock("@rallly/utils/nanoid", () => ({
+ nanoid: () => "test-poll-id",
+}));
+
+vi.mock("@vercel/functions", () => ({
+ waitUntil: vi.fn(),
+}));
+
+vi.mock("@/lib/kv", () => ({
+ isKvEnabled: false,
+ kv: null,
+}));
+
+import crypto from "node:crypto";
+import { prisma } from "@rallly/database";
+import { app } from "./route";
+
+const createMockApiKey = (rawKey: string) => {
+ const hashedKey = crypto.createHash("sha256").update(rawKey).digest("hex");
+ return {
+ id: "api-key-id",
+ name: "Test API Key",
+ prefix: "abc123",
+ userId: "test-user-id",
+ hashedKey,
+ lastUsedAt: null,
+ expiresAt: null,
+ revokedAt: null,
+ createdAt: new Date("2025-01-01"),
+ updatedAt: new Date("2025-01-01"),
+ };
+};
+
+describe("Private API - /polls", () => {
+ const testApiKey = "rallly_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.user.findUnique).mockResolvedValue({
+ timeZone: "Europe/London",
+ } as never);
+ vi.mocked(prisma.spaceMember.findFirst).mockResolvedValue(null);
+ vi.mocked(prisma.poll.create).mockResolvedValue({
+ id: "test-poll-id",
+ } as never);
+ });
+
+ describe("Authentication", () => {
+ it("should return 401 without authorization header", async () => {
+ const res = await app.request("/api/private/polls", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ title: "Test Poll",
+ dates: ["2025-01-15"],
+ }),
+ });
+
+ expect(res.status).toBe(401);
+ });
+
+ it("should return 401 with invalid API key", async () => {
+ vi.mocked(prisma.apiKey.findUnique).mockResolvedValue(null);
+
+ const res = await app.request("/api/private/polls", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: "Bearer invalid_key",
+ },
+ body: JSON.stringify({
+ title: "Test Poll",
+ dates: ["2025-01-15"],
+ }),
+ });
+
+ expect(res.status).toBe(401);
+ });
+
+ it("should return 401 with revoked API key", async () => {
+ vi.mocked(prisma.apiKey.findUnique).mockResolvedValue({
+ ...mockApiKey,
+ revokedAt: new Date(),
+ });
+
+ 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"],
+ }),
+ });
+
+ expect(res.status).toBe(401);
+ });
+
+ it("should return 401 with expired API key", async () => {
+ vi.mocked(prisma.apiKey.findUnique).mockResolvedValue({
+ ...mockApiKey,
+ expiresAt: new Date("2020-01-01"),
+ });
+
+ 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"],
+ }),
+ });
+
+ expect(res.status).toBe(401);
+ });
+ });
+
+ describe("Create poll with dates", () => {
+ it("should create a poll with 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: "Team offsite",
+ dates: ["2025-01-15", "2025-01-16", "2025-01-17"],
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+ expect(json.data.id).toBe("test-poll-id");
+ expect(json.data.adminUrl).toBe("https://example.com/poll/test-poll-id");
+ expect(json.data.inviteUrl).toBe(
+ "https://example.com/invite/test-poll-id",
+ );
+
+ expect(prisma.poll.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({
+ title: "Team offsite",
+ 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,
+ },
+ {
+ startTime: new Date("2025-01-17T00:00:00.000Z"),
+ duration: 0,
+ },
+ ],
+ },
+ },
+ }),
+ }),
+ );
+ });
+
+ 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",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ body: JSON.stringify({
+ title: "Team offsite",
+ location: "Conference Room A",
+ dates: ["2025-01-15"],
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ expect(prisma.poll.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({
+ title: "Team offsite",
+ location: "Conference Room A",
+ }),
+ }),
+ );
+ });
+
+ it("should return error when too many date options", async () => {
+ const dates = Array.from({ length: 101 }, (_, i) => {
+ const date = new Date(2025, 0, 1 + i);
+ return date.toISOString().split("T")[0];
+ });
+
+ 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,
+ }),
+ });
+
+ expect(res.status).toBe(400);
+ const json = await res.json();
+ expect(json.error.code).toBe("TOO_MANY_OPTIONS");
+ });
+ });
+
+ describe("Create poll with slots", () => {
+ it("should create a poll with time slot options", async () => {
+ const res = await app.request("/api/private/polls", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ body: JSON.stringify({
+ title: "Team sync",
+ slots: {
+ duration: 30,
+ timezone: "Europe/London",
+ times: ["2025-01-15T09:00:00Z", "2025-01-15T10:00:00Z"],
+ },
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+ expect(json.data.id).toBe("test-poll-id");
+
+ expect(prisma.poll.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({
+ title: "Team sync",
+ timeZone: "Europe/London",
+ }),
+ }),
+ );
+ });
+
+ it("should use user timezone when not provided in request", async () => {
+ const res = await app.request("/api/private/polls", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ body: JSON.stringify({
+ title: "Team sync",
+ slots: {
+ duration: 30,
+ times: ["2025-01-15T09:00:00Z"],
+ },
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ expect(prisma.poll.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ data: expect.objectContaining({
+ timeZone: "Europe/London",
+ }),
+ }),
+ );
+ });
+
+ it("should return error when timezone is missing and user has no timezone", async () => {
+ vi.mocked(prisma.user.findUnique).mockResolvedValue({
+ timeZone: null,
+ } as never);
+
+ const res = await app.request("/api/private/polls", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ body: JSON.stringify({
+ title: "Team sync",
+ slots: {
+ duration: 30,
+ times: ["2025-01-15T09:00:00Z"],
+ },
+ }),
+ });
+
+ expect(res.status).toBe(400);
+ const json = await res.json();
+ expect(json.error.code).toBe("TIMEZONE_REQUIRED");
+ });
+
+ it("should return error for invalid timezone", async () => {
+ const res = await app.request("/api/private/polls", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ body: JSON.stringify({
+ title: "Team sync",
+ slots: {
+ duration: 30,
+ timezone: "Invalid/Timezone",
+ times: ["2025-01-15T09:00:00Z"],
+ },
+ }),
+ });
+
+ expect(res.status).toBe(400);
+ });
+
+ it("should create poll with slot generator", async () => {
+ const res = await app.request("/api/private/polls", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ body: JSON.stringify({
+ title: "Weekly standup",
+ slots: {
+ duration: 30,
+ timezone: "Europe/London",
+ times: {
+ startDate: "2025-01-20",
+ endDate: "2025-01-22",
+ days: ["mon", "tue", "wed"],
+ startTime: "09:00",
+ endTime: "10:00",
+ },
+ },
+ }),
+ });
+
+ expect(res.status).toBe(200);
+ expect(prisma.poll.create).toHaveBeenCalled();
+ });
+ });
+
+ describe("Validation", () => {
+ it("should return error when neither dates nor slots 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",
+ }),
+ });
+
+ expect(res.status).toBe(400);
+ });
+
+ it("should return error when both dates and slots 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"],
+ slots: {
+ duration: 30,
+ timezone: "Europe/London",
+ times: ["2025-01-15T09:00:00Z"],
+ },
+ }),
+ });
+
+ expect(res.status).toBe(400);
+ });
+
+ it("should return error when title is missing", async () => {
+ const res = await app.request("/api/private/polls", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${testApiKey}`,
+ },
+ body: JSON.stringify({
+ dates: ["2025-01-15"],
+ }),
+ });
+
+ expect(res.status).toBe(400);
+ });
+
+ it("should return error when dates array is empty", 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: [],
+ }),
+ });
+
+ expect(res.status).toBe(400);
+ });
+ });
+
+ describe("OpenAPI endpoints", () => {
+ it("should return OpenAPI spec", async () => {
+ const res = await app.request("/api/private/openapi");
+
+ expect(res.status).toBe(200);
+ const json = await res.json();
+ expect(json.info.title).toBe("Rallly Private API");
+ });
+
+ it("should return docs page", async () => {
+ const res = await app.request("/api/private/docs");
+
+ expect(res.status).toBe(200);
+ expect(res.headers.get("content-type")).toContain("text/html");
+ });
+ });
+});
diff --git a/apps/web/src/app/api/private/[...route]/route.ts b/apps/web/src/app/api/private/[...route]/route.ts
new file mode 100644
index 000000000..55d735aac
--- /dev/null
+++ b/apps/web/src/app/api/private/[...route]/route.ts
@@ -0,0 +1,247 @@
+import { RedisStore } from "@hono-rate-limiter/redis";
+import { prisma } from "@rallly/database";
+import { Scalar } from "@scalar/hono-api-reference";
+import { Hono } from "hono";
+import { handle } from "hono/vercel";
+import {
+ describeRoute,
+ openAPIRouteHandler,
+ resolver,
+ validator,
+} from "hono-openapi";
+import { rateLimiter } from "hono-rate-limiter";
+import { isKvEnabled, kv } from "@/lib/kv";
+import { isSupportedTimeZone } from "@/utils/supported-time-zones";
+import {
+ createPollInputSchema,
+ createPollSuccessResponseSchema,
+ errorResponseSchema,
+} from "../schemas";
+import { apiKeyAuth } from "../utils/api-key";
+import { apiError, createPoll } from "../utils/poll";
+import type { SlotGeneratorInput } from "../utils/time-slots";
+import {
+ dedupeTimeSlots,
+ generateTimeSlots,
+ parseStartTime,
+} from "../utils/time-slots";
+
+type Env = {
+ Variables: {
+ apiAuth: {
+ userId: string;
+ apiKeyId: string;
+ };
+ };
+};
+
+const app = new Hono<Env>().basePath("/api/private");
+
+const MAX_OPTIONS = 100;
+
+app.get(
+ "/openapi",
+ openAPIRouteHandler(app, {
+ documentation: {
+ info: {
+ title: "Rallly Private API",
+ version: "0.0.1",
+ },
+ servers: [{ url: "/api/private" }],
+ components: {
+ securitySchemes: {
+ bearerAuth: {
+ type: "http",
+ scheme: "bearer",
+ },
+ },
+ },
+ },
+ }),
+);
+
+app.get(
+ "/docs",
+ Scalar({
+ url: "/api/private/openapi",
+ pageTitle: "Rallly Private API Documentation",
+ theme: "purple",
+ }),
+);
+
+app.post(
+ "/polls",
+ apiKeyAuth,
+ rateLimiter<Env>({
+ windowMs: 60 * 1000,
+ limit: 60,
+ keyGenerator: (c) => {
+ const { apiKeyId } = c.get("apiAuth");
+ return `private-api:polls-create:${apiKeyId}`;
+ },
+ store: isKvEnabled ? new RedisStore({ client: kv }) : undefined,
+ }),
+ describeRoute({
+ tags: ["Polls"],
+ summary: "Create a poll",
+ description:
+ "Creates a new poll with the specified options or slot generators.",
+ security: [{ bearerAuth: [] }],
+ responses: {
+ 200: {
+ description: "Successful response",
+ content: {
+ "application/json": {
+ schema: resolver(createPollSuccessResponseSchema),
+ },
+ },
+ },
+ 400: {
+ description: "Invalid input or no valid options generated",
+ content: {
+ "application/json": {
+ schema: resolver(errorResponseSchema),
+ },
+ },
+ },
+ },
+ }),
+ validator("json", createPollInputSchema),
+ async (c) => {
+ const input = c.req.valid("json");
+ const { userId } = c.get("apiAuth");
+
+ const user = await prisma.user.findUnique({
+ where: { id: userId },
+ select: { timeZone: true },
+ });
+
+ // 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) {
+ return c.json(
+ apiError(
+ "TOO_MANY_OPTIONS",
+ `Too many options (${options.length}). Maximum allowed is ${MAX_OPTIONS}.`,
+ ),
+ 400,
+ );
+ }
+
+ const poll = await createPoll({
+ userId,
+ title: input.title,
+ description: input.description,
+ location: input.location,
+ options,
+ });
+
+ return c.json({
+ data: {
+ id: poll.id,
+ adminUrl: poll.adminUrl,
+ inviteUrl: poll.inviteUrl,
+ },
+ });
+ }
+
+ // Process slots (time-based options)
+ if (!input.slots) {
+ return c.json(
+ apiError("INVALID_INPUT", "Either 'dates' or 'slots' must be provided"),
+ 400,
+ );
+ }
+
+ const slots = input.slots;
+ const timeZone = slots.timezone ?? user?.timeZone;
+
+ if (!timeZone) {
+ return c.json(
+ apiError(
+ "TIMEZONE_REQUIRED",
+ "Timezone is required. Either provide a timezone in slots or set one in your profile.",
+ ),
+ 400,
+ );
+ }
+
+ if (!isSupportedTimeZone(timeZone)) {
+ return c.json(
+ apiError(
+ "INVALID_TIMEZONE",
+ `Invalid timezone: ${timeZone}. Please provide a valid IANA timezone.`,
+ ),
+ 400,
+ );
+ }
+
+ const duration = slots.duration;
+ const times = Array.isArray(slots.times) ? slots.times : [slots.times];
+
+ const timeSlots = times.flatMap((time) => {
+ if (typeof time === "string") {
+ return parseStartTime(time, timeZone, duration);
+ }
+ const slotGenerator: SlotGeneratorInput = {
+ startDate: time.startDate,
+ endDate: time.endDate,
+ daysOfWeek: time.days,
+ fromTime: time.startTime,
+ toTime: time.endTime,
+ interval: time.interval,
+ };
+ return generateTimeSlots(slotGenerator, timeZone, duration);
+ });
+
+ const options = dedupeTimeSlots(timeSlots);
+
+ if (!options.length) {
+ return c.json(
+ apiError(
+ "NO_OPTIONS_GENERATED",
+ "No valid options were generated. Check that your slot generators produce valid time slots.",
+ ),
+ 400,
+ );
+ }
+
+ if (options.length > MAX_OPTIONS) {
+ return c.json(
+ apiError(
+ "TOO_MANY_OPTIONS",
+ `Too many options generated (${options.length}). Maximum allowed is ${MAX_OPTIONS}.`,
+ ),
+ 400,
+ );
+ }
+
+ const poll = await createPoll({
+ userId,
+ title: input.title,
+ description: input.description,
+ location: input.location,
+ timeZone,
+ options,
+ });
+
+ return c.json({
+ data: {
+ id: poll.id,
+ adminUrl: poll.adminUrl,
+ inviteUrl: poll.inviteUrl,
+ },
+ });
+ },
+);
+
+export { app };
+
+export const GET = handle(app);
+export const POST = handle(app);
diff --git a/apps/web/src/app/api/private/schemas.ts b/apps/web/src/app/api/private/schemas.ts
new file mode 100644
index 000000000..c824c90a7
--- /dev/null
+++ b/apps/web/src/app/api/private/schemas.ts
@@ -0,0 +1,120 @@
+import { z } from "@hono/zod-openapi";
+import { isSupportedTimeZone } from "@/utils/supported-time-zones";
+
+export const dateSchema = z.iso.date().openapi({
+ description: "Date in YYYY-MM-DD format",
+ example: "2025-12-23",
+});
+
+export const timeSchema = z.iso.time().openapi({
+ description: "Time in HH:mm (24-hour) format",
+ example: "09:30",
+});
+
+export const slotGeneratorSchema = z
+ .object({
+ startDate: dateSchema,
+ endDate: dateSchema,
+ days: z.array(z.enum(["mon", "tue", "wed", "thu", "fri", "sat", "sun"])),
+ startTime: timeSchema,
+ endTime: timeSchema,
+ interval: z.number().int().min(15).max(1440).optional().openapi({
+ description: "Interval in minutes between slots. Defaults to duration.",
+ example: 30,
+ }),
+ })
+ .openapi("SlotGenerator");
+
+const timeOptionSchema = z.union([
+ z.iso.datetime().openapi({
+ description: "ISO datetime start time",
+ example: "2025-01-15T09:00:00Z",
+ }),
+ slotGeneratorSchema,
+]);
+
+const slotsInputSchema = z
+ .object({
+ duration: z.number().int().min(15).max(1440).openapi({
+ description: "Duration in minutes for each time slot",
+ example: 30,
+ }),
+ timezone: z
+ .string()
+ .refine(isSupportedTimeZone, {
+ message: "Timezone must be a valid IANA timezone",
+ })
+ .optional()
+ .openapi({
+ description:
+ "IANA timezone. Defaults to user's timezone if not provided.",
+ example: "Europe/London",
+ }),
+ times: z
+ .union([slotGeneratorSchema, z.array(timeOptionSchema).min(1)])
+ .openapi({
+ description:
+ "Times to include. Can be a slot generator or an array of ISO datetime strings and/or slot generators.",
+ }),
+ })
+ .openapi("SlotsInput");
+
+const datesInputSchema = z
+ .array(z.iso.date())
+ .min(1)
+ .openapi({
+ description: "Array of ISO dates for all-day options",
+ example: ["2025-01-15", "2025-01-16", "2025-01-17"],
+ });
+
+export const createPollInputSchema = z
+ .object({
+ title: z.string().trim().min(1).openapi({ example: "Team sync" }),
+ description: z
+ .string()
+ .trim()
+ .max(1000)
+ .optional()
+ .openapi({ example: "Pick a time that works for everyone" }),
+ location: z
+ .string()
+ .trim()
+ .max(255)
+ .optional()
+ .openapi({ example: "Zoom" }),
+ dates: datesInputSchema.optional(),
+ slots: slotsInputSchema.optional(),
+ })
+ .refine((data) => data.dates || data.slots, {
+ message: "Either 'dates' or 'slots' must be provided",
+ })
+ .refine((data) => !(data.dates && data.slots), {
+ message: "Cannot provide both 'dates' and 'slots'",
+ })
+ .openapi("CreatePollInput");
+
+export const createPollSuccessResponseSchema = z
+ .object({
+ data: z.object({
+ id: z.string().openapi({ example: "p_123abc" }),
+ adminUrl: z
+ .string()
+ .openapi({ example: "https://example.com/poll/p_123abc" }),
+ inviteUrl: z
+ .string()
+ .openapi({ example: "https://example.com/invite/p_123abc" }),
+ }),
+ })
+ .openapi("CreatePollResponse");
+
+export const errorResponseSchema = z
+ .object({
+ error: z.object({
+ code: z.string().openapi({ example: "TIMEZONE_REQUIRED" }),
+ message: z.string().openapi({
+ example:
+ "Timezone is required. Either provide a timezone in the request or set one in your profile.",
+ }),
+ }),
+ })
+ .openapi("ErrorResponse");
diff --git a/apps/web/src/app/api/private/utils/api-key.ts b/apps/web/src/app/api/private/utils/api-key.ts
new file mode 100644
index 000000000..1cced7fc6
--- /dev/null
+++ b/apps/web/src/app/api/private/utils/api-key.ts
@@ -0,0 +1,85 @@
+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));
+};
+
+export const apiKeyAuth = bearerAuth({
+ verifyToken: async (rawKey, c) => {
+ const prefix = extractApiKeyPrefix(rawKey);
+
+ const apiKey = await prisma.apiKey.findUnique({
+ where: { prefix },
+ select: {
+ id: true,
+ userId: true,
+ hashedKey: true,
+ expiresAt: true,
+ revokedAt: true,
+ },
+ });
+
+ if (!apiKey) {
+ return false;
+ }
+
+ if (apiKey.revokedAt) {
+ return false;
+ }
+
+ if (apiKey.expiresAt && apiKey.expiresAt <= new Date()) {
+ return false;
+ }
+
+ if (!verifyApiKey(rawKey, apiKey.hashedKey)) {
+ return false;
+ }
+
+ c.set("apiAuth", {
+ userId: apiKey.userId,
+ apiKeyId: apiKey.id,
+ });
+
+ waitUntil(
+ prisma.apiKey.update({
+ where: { id: apiKey.id },
+ data: { lastUsedAt: new Date() },
+ }),
+ );
+
+ return true;
+ },
+});
diff --git a/apps/web/src/app/api/private/utils/poll.ts b/apps/web/src/app/api/private/utils/poll.ts
new file mode 100644
index 000000000..f92519295
--- /dev/null
+++ b/apps/web/src/app/api/private/utils/poll.ts
@@ -0,0 +1,59 @@
+import { prisma } from "@rallly/database";
+import { absoluteUrl, shortUrl } from "@rallly/utils/absolute-url";
+import { nanoid } from "@rallly/utils/nanoid";
+
+export type PollOption = {
+ startTime: Date;
+ duration: number;
+};
+
+export type CreatePollParams = {
+ userId: string;
+ title: string;
+ description?: string;
+ location?: string;
+ timeZone?: string;
+ options: PollOption[];
+};
+
+export const createPoll = async ({
+ userId,
+ title,
+ description,
+ location,
+ timeZone,
+ options,
+}: CreatePollParams) => {
+ const spaceMember = await prisma.spaceMember.findFirst({
+ where: { userId },
+ orderBy: { lastSelectedAt: "desc" },
+ select: { spaceId: true },
+ });
+
+ const poll = await prisma.poll.create({
+ data: {
+ id: nanoid(),
+ title,
+ description,
+ location,
+ timeZone,
+ adminUrlId: nanoid(),
+ participantUrlId: nanoid(),
+ userId,
+ watchers: { create: { userId } },
+ options: { createMany: { data: options } },
+ spaceId: spaceMember?.spaceId,
+ },
+ select: { id: true, title: true, location: true, description: true },
+ });
+
+ return {
+ id: poll.id,
+ adminUrl: absoluteUrl(`/poll/${poll.id}`),
+ inviteUrl: shortUrl(`/invite/${poll.id}`),
+ };
+};
+
+export const apiError = (code: string, message: string) => ({
+ error: { code, message },
+});
diff --git a/apps/web/src/app/api/private/utils/time-slots.test.ts b/apps/web/src/app/api/private/utils/time-slots.test.ts
new file mode 100644
index 000000000..254c0e4f3
--- /dev/null
+++ b/apps/web/src/app/api/private/utils/time-slots.test.ts
@@ -0,0 +1,225 @@
+import { describe, expect, it } from "vitest";
+import {
+ dedupeTimeSlots,
+ generateTimeSlots,
+ parseStartTime,
+} from "./time-slots";
+
+describe("time-slots utilities", () => {
+ describe("parseStartTime", () => {
+ it("should parse ISO datetime with timezone offset", () => {
+ const result = parseStartTime(
+ "2025-01-15T09:00:00Z",
+ "Europe/London",
+ 30,
+ );
+
+ expect(result.startTime).toEqual(new Date("2025-01-15T09:00:00Z"));
+ expect(result.duration).toBe(30);
+ });
+
+ it("should parse datetime without offset using provided timezone", () => {
+ const result = parseStartTime(
+ "2025-01-15T09:00:00",
+ "America/New_York",
+ 60,
+ );
+
+ expect(result.startTime).toEqual(new Date("2025-01-15T14:00:00Z"));
+ expect(result.duration).toBe(60);
+ });
+
+ it("should handle positive timezone offset", () => {
+ const result = parseStartTime(
+ "2025-01-15T09:00:00+05:30",
+ "Europe/London",
+ 30,
+ );
+
+ expect(result.startTime).toEqual(new Date("2025-01-15T03:30:00Z"));
+ });
+
+ it("should handle negative timezone offset", () => {
+ const result = parseStartTime(
+ "2025-01-15T09:00:00-08:00",
+ "Europe/London",
+ 30,
+ );
+
+ expect(result.startTime).toEqual(new Date("2025-01-15T17:00:00Z"));
+ });
+ });
+
+ describe("dedupeTimeSlots", () => {
+ it("should remove duplicate time slots", () => {
+ const slots = [
+ { startTime: new Date("2025-01-15T09:00:00Z"), duration: 30 },
+ { startTime: new Date("2025-01-15T09:00:00Z"), duration: 30 },
+ { startTime: new Date("2025-01-15T10:00:00Z"), duration: 30 },
+ ];
+
+ const result = dedupeTimeSlots(slots);
+
+ expect(result).toHaveLength(2);
+ expect(result[0].startTime).toEqual(new Date("2025-01-15T09:00:00Z"));
+ expect(result[1].startTime).toEqual(new Date("2025-01-15T10:00:00Z"));
+ });
+
+ it("should keep slots with same time but different duration", () => {
+ const slots = [
+ { startTime: new Date("2025-01-15T09:00:00Z"), duration: 30 },
+ { startTime: new Date("2025-01-15T09:00:00Z"), duration: 60 },
+ ];
+
+ const result = dedupeTimeSlots(slots);
+
+ expect(result).toHaveLength(2);
+ });
+
+ it("should return empty array for empty input", () => {
+ const result = dedupeTimeSlots([]);
+ expect(result).toEqual([]);
+ });
+ });
+
+ describe("generateTimeSlots", () => {
+ it("should generate slots for a single day", () => {
+ const result = generateTimeSlots(
+ {
+ startDate: "2025-01-15",
+ endDate: "2025-01-15",
+ daysOfWeek: ["wed"],
+ fromTime: "09:00",
+ toTime: "12:00",
+ },
+ "UTC",
+ 60,
+ );
+
+ expect(result).toHaveLength(3);
+ expect(result[0].startTime).toEqual(new Date("2025-01-15T09:00:00Z"));
+ expect(result[1].startTime).toEqual(new Date("2025-01-15T10:00:00Z"));
+ expect(result[2].startTime).toEqual(new Date("2025-01-15T11:00:00Z"));
+ expect(result[0].duration).toBe(60);
+ });
+
+ it("should generate slots across multiple days", () => {
+ const result = generateTimeSlots(
+ {
+ startDate: "2025-01-13",
+ endDate: "2025-01-17",
+ daysOfWeek: ["mon", "wed", "fri"],
+ fromTime: "09:00",
+ toTime: "10:00",
+ },
+ "UTC",
+ 30,
+ );
+
+ expect(result).toHaveLength(6);
+ });
+
+ it("should respect custom interval", () => {
+ const result = generateTimeSlots(
+ {
+ startDate: "2025-01-15",
+ endDate: "2025-01-15",
+ daysOfWeek: ["wed"],
+ fromTime: "09:00",
+ toTime: "11:00",
+ interval: 30,
+ },
+ "UTC",
+ 30,
+ );
+
+ expect(result).toHaveLength(4);
+ expect(result[0].startTime).toEqual(new Date("2025-01-15T09:00:00Z"));
+ expect(result[1].startTime).toEqual(new Date("2025-01-15T09:30:00Z"));
+ expect(result[2].startTime).toEqual(new Date("2025-01-15T10:00:00Z"));
+ expect(result[3].startTime).toEqual(new Date("2025-01-15T10:30:00Z"));
+ });
+
+ it("should return empty array when no matching days in range", () => {
+ const result = generateTimeSlots(
+ {
+ startDate: "2025-01-15",
+ endDate: "2025-01-15",
+ daysOfWeek: ["mon"],
+ fromTime: "09:00",
+ toTime: "10:00",
+ },
+ "UTC",
+ 30,
+ );
+
+ expect(result).toEqual([]);
+ });
+
+ it("should return empty array when end time is before start time", () => {
+ const result = generateTimeSlots(
+ {
+ startDate: "2025-01-15",
+ endDate: "2025-01-15",
+ daysOfWeek: ["wed"],
+ fromTime: "12:00",
+ toTime: "09:00",
+ },
+ "UTC",
+ 30,
+ );
+
+ expect(result).toEqual([]);
+ });
+
+ it("should handle timezone correctly", () => {
+ const result = generateTimeSlots(
+ {
+ startDate: "2025-01-15",
+ endDate: "2025-01-15",
+ daysOfWeek: ["wed"],
+ fromTime: "09:00",
+ toTime: "10:00",
+ },
+ "America/New_York",
+ 30,
+ );
+
+ expect(result[0].startTime).toEqual(new Date("2025-01-15T14:00:00Z"));
+ expect(result[1].startTime).toEqual(new Date("2025-01-15T14:30:00Z"));
+ });
+
+ it("should not generate slot if duration exceeds window", () => {
+ const result = generateTimeSlots(
+ {
+ startDate: "2025-01-15",
+ endDate: "2025-01-15",
+ daysOfWeek: ["wed"],
+ fromTime: "09:00",
+ toTime: "09:30",
+ },
+ "UTC",
+ 60,
+ );
+
+ expect(result).toEqual([]);
+ });
+
+ it("should deduplicate generated slots", () => {
+ const result = generateTimeSlots(
+ {
+ startDate: "2025-01-15",
+ endDate: "2025-01-15",
+ daysOfWeek: ["wed"],
+ fromTime: "09:00",
+ toTime: "10:00",
+ },
+ "UTC",
+ 30,
+ );
+
+ const uniqueTimes = new Set(result.map((s) => s.startTime.toISOString()));
+ expect(result.length).toBe(uniqueTimes.size);
+ });
+ });
+});
diff --git a/apps/web/src/app/api/private/utils/time-slots.ts b/apps/web/src/app/api/private/utils/time-slots.ts
new file mode 100644
index 000000000..d36628511
--- /dev/null
+++ b/apps/web/src/app/api/private/utils/time-slots.ts
@@ -0,0 +1,131 @@
+import dayjs from "dayjs";
+import isSameOrBefore from "dayjs/plugin/isSameOrBefore";
+import timezone from "dayjs/plugin/timezone";
+import utc from "dayjs/plugin/utc";
+
+dayjs.extend(utc);
+dayjs.extend(timezone);
+dayjs.extend(isSameOrBefore);
+
+export type SlotGeneratorInput = {
+ startDate: string;
+ endDate: string;
+ daysOfWeek: Array<"mon" | "tue" | "wed" | "thu" | "fri" | "sat" | "sun">;
+ fromTime: string;
+ toTime: string;
+ interval?: number;
+};
+
+export type TimeSlot = {
+ startTime: Date;
+ duration: number;
+};
+
+export const dedupeTimeSlots = (slots: Array<TimeSlot>) => {
+ const unique = new Map<string, TimeSlot>();
+ for (const slot of slots) {
+ unique.set(`${slot.startTime.getTime()}:${slot.duration}`, slot);
+ }
+ return Array.from(unique.values());
+};
+
+const hasTzOffset = (value: string) =>
+ /[zZ]$|[+-]\d{2}:\d{2}$|[+-]\d{4}$/.test(value);
+
+const parseDateTimeInTimeZone = (value: string, timeZone: string) =>
+ hasTzOffset(value) ? dayjs(value) : dayjs(value).tz(timeZone, true);
+
+const parseLocalDateTimeInTimeZone = (
+ date: string,
+ time: string,
+ timeZone: string,
+) => dayjs(`${date}T${time}`).tz(timeZone, true);
+
+export const parseStartTime = (
+ startTime: string,
+ timeZone: string,
+ duration: number,
+): TimeSlot => ({
+ startTime: parseDateTimeInTimeZone(startTime, timeZone).toDate(),
+ duration,
+});
+
+export const generateTimeSlots = (
+ generator: SlotGeneratorInput,
+ timeZone: string,
+ durationMinutes: number,
+): Array<TimeSlot> => {
+ const dayMap: Record<SlotGeneratorInput["daysOfWeek"][number], number> = {
+ sun: 0,
+ mon: 1,
+ tue: 2,
+ wed: 3,
+ thu: 4,
+ fri: 5,
+ sat: 6,
+ };
+
+ const allowed = new Set(generator.daysOfWeek.map((d) => dayMap[d]));
+
+ const startDay = dayjs(generator.startDate).tz(timeZone, true).startOf("day");
+ const endDay = dayjs(generator.endDate).tz(timeZone, true).startOf("day");
+
+ const from = parseLocalDateTimeInTimeZone(
+ generator.startDate,
+ generator.fromTime,
+ timeZone,
+ );
+ const to = parseLocalDateTimeInTimeZone(
+ generator.startDate,
+ generator.toTime,
+ timeZone,
+ );
+ if (!to.isAfter(from)) {
+ return [];
+ }
+
+ const results: Array<TimeSlot> = [];
+
+ for (
+ let cursor = startDay;
+ cursor.isSameOrBefore(endDay, "day");
+ cursor = cursor.add(1, "day")
+ ) {
+ if (!allowed.has(cursor.day())) {
+ continue;
+ }
+
+ const date = cursor.format("YYYY-MM-DD");
+ const windowStart = parseLocalDateTimeInTimeZone(
+ date,
+ generator.fromTime,
+ timeZone,
+ );
+ const windowEnd = parseLocalDateTimeInTimeZone(
+ date,
+ generator.toTime,
+ timeZone,
+ );
+ if (!windowEnd.isAfter(windowStart)) {
+ continue;
+ }
+
+ const duration = durationMinutes;
+ const interval = generator.interval ?? durationMinutes;
+ const totalMinutes = windowEnd.diff(windowStart, "minute");
+
+ for (
+ let offset = 0;
+ offset + duration <= totalMinutes;
+ offset += interval
+ ) {
+ const t = windowStart.add(offset, "minute");
+ results.push({
+ startTime: t.toDate(),
+ duration,
+ });
+ }
+ }
+
+ return dedupeTimeSlots(results);
+};
diff --git a/apps/web/src/components/forms/poll-details-form.tsx b/apps/web/src/components/forms/poll-details-form.tsx
index 0aa847b85..5391abbdc 100644
--- a/apps/web/src/components/forms/poll-details-form.tsx
+++ b/apps/web/src/components/forms/poll-details-form.tsx
@@ -20,10 +20,7 @@ export const PollDetailsForm = () => {
const form = useFormContext<NewEventData>();
const { requiredString } = useFormValidation();
- const {
- register,
- formState: { errors },
- } = form;
+ const { register } = form;
return (
<div className="grid gap-4 py-1">
diff --git a/apps/web/src/utils/supported-time-zones.ts b/apps/web/src/utils/supported-time-zones.ts
index 31f0e4eb9..842b7c5c9 100644
--- a/apps/web/src/utils/supported-time-zones.ts
+++ b/apps/web/src/utils/supported-time-zones.ts
@@ -428,3 +428,9 @@ export const supportedTimeZones = [
"Pacific/Wake",
"Pacific/Wallis",
] as const;
+
+export function isSupportedTimeZone(timeZone: string) {
+ return supportedTimeZones.includes(
+ timeZone as (typeof supportedTimeZones)[number],
+ );
+}
diff --git a/packages/database/package.json b/packages/database/package.json
index 49718aa1b..83de13f3b 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -8,6 +8,7 @@
"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/migrations/20251222101400_add_api_keys/migration.sql b/packages/database/prisma/migrations/20251222101400_add_api_keys/migration.sql
new file mode 100644
index 000000000..7d5cc95da
--- /dev/null
+++ b/packages/database/prisma/migrations/20251222101400_add_api_keys/migration.sql
@@ -0,0 +1,33 @@
+-- CreateTable
+CREATE TABLE "api_keys" (
+ "id" TEXT NOT NULL,
+ "user_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 "api_keys_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "api_keys_prefix_key" ON "api_keys"("prefix");
+
+-- CreateIndex
+CREATE INDEX "api_key_user_idx" ON "api_keys"("user_id");
+
+-- CreateIndex
+CREATE INDEX "api_key_expires_idx" ON "api_keys"("expires_at");
+
+-- CreateIndex
+CREATE INDEX "api_key_revoked_idx" ON "api_keys"("revoked_at");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "api_keys_user_id_name_key" ON "api_keys"("user_id", "name");
+
+-- AddForeignKey
+ALTER TABLE "api_keys" ADD CONSTRAINT "api_keys_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/packages/database/prisma/models/user.prisma b/packages/database/prisma/models/user.prisma
index 2c0310b0b..1c59a1b11 100644
--- a/packages/database/prisma/models/user.prisma
+++ b/packages/database/prisma/models/user.prisma
@@ -65,6 +65,7 @@ model User {
participants Participant[]
paymentMethods PaymentMethod[]
spaceMemberInvites SpaceMemberInvite[]
+ apiKeys ApiKey[]
subscriptions Subscription[] @relation("UserToSubscription")
spaces Space[] @relation("UserSpaces")
@@ -87,6 +88,29 @@ model User {
@@map("users")
}
+model ApiKey {
+ id String @id @default(cuid())
+ userId String @map("user_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")
+
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+
+ @@unique([userId, name], name: "user_api_key_name_unique")
+ @@index([userId], name: "api_key_user_idx")
+ @@index([expiresAt], name: "api_key_expires_idx")
+ @@index([revokedAt], name: "api_key_revoked_idx")
+ @@map("api_keys")
+}
+
model VerificationToken {
identifier String @db.Citext
token String @unique
diff --git a/packages/database/prisma/scripts/create-api-key.ts b/packages/database/prisma/scripts/create-api-key.ts
new file mode 100644
index 000000000..b101043be
--- /dev/null
+++ b/packages/database/prisma/scripts/create-api-key.ts
@@ -0,0 +1,104 @@
+import { PrismaClient } from "@prisma/client";
+import crypto from "node:crypto";
+
+const prisma = new PrismaClient();
+
+type Args = {
+ userId?: string;
+ userEmail?: 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 === "user-id") {
+ return { ...acc, userId: normalizedValue };
+ }
+ if (normalizedKey === "user-email") {
+ return { ...acc, userEmail: 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.userId && !args.userEmail) {
+ throw new Error("Missing required arg: --user-id or --user-email");
+ }
+
+ const user = args.userId
+ ? await prisma.user.findUnique({ where: { id: args.userId }, select: { id: true } })
+ : await prisma.user.findUnique({
+ where: { email: args.userEmail },
+ select: { id: true },
+ });
+
+ if (!user) {
+ throw new Error("User not found");
+ }
+
+ const prefix = randomToken(6);
+ const secret = randomToken(24);
+ const apiKey = `rly_${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.apiKey.create({
+ data: {
+ userId: user.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/pnpm-lock.yaml b/pnpm-lock.yaml
index 20b9808bc..e71df721a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -31,7 +31,7 @@ importers:
version: 5.8.3
vitest:
specifier: ^4.0.16
apps/docs:
dependencies:
@@ -80,7 +80,7 @@ importers:
version: 8.1.0([email protected])
'@vercel/analytics':
specifier: ^1.5.0
dayjs:
specifier: ^1.11.13
version: 1.11.13
@@ -119,7 +119,7 @@ importers:
next-seo:
specifier: ^6.1.0
react:
specifier: ^19.1.4
version: 19.2.1
@@ -193,6 +193,12 @@ importers:
'@hono-rate-limiter/redis':
specifier: ^0.1.4
+ '@hono/standard-validator':
+ specifier: ^0.2.1
+ version: 0.2.1(@standard-schema/[email protected])([email protected])
+ '@hono/zod-openapi':
+ specifier: ^1.2.0
'@hono/zod-validator':
specifier: ^0.7.2
@@ -241,6 +247,9 @@ importers:
'@rallly/utils':
specifier: workspace:*
version: link:../../packages/utils
+ '@scalar/hono-api-reference':
+ specifier: ^0.9.30
+ version: 0.9.30([email protected])
'@sentry/nextjs':
specifier: ^9.14.0
version: 9.14.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected](@babel/[email protected])(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])
@@ -294,7 +303,7 @@ importers:
version: 3.7.0
better-auth:
specifier: ^1.4.7
calendar-link:
specifier: ^2.6.0
version: 2.8.0
@@ -319,6 +328,9 @@ importers:
hono:
specifier: ^4.11.1
version: 4.11.1
+ hono-openapi:
+ specifier: ^1.1.2
hono-rate-limiter:
specifier: ^0.2.1
version: 0.2.3([email protected])
@@ -475,7 +487,7 @@ importers:
version: 4.4.5
'@vitejs/plugin-react':
specifier: ^5.0.0
cheerio:
specifier: ^1.0.0-rc.12
version: 1.0.0
@@ -493,7 +505,7 @@ importers:
version: 26.1.0
vitest:
specifier: ^4.0.16
packages/billing:
dependencies:
@@ -796,7 +808,7 @@ importers:
version: 20.19.27
vitest:
specifier: ^4.0.16
packages:
@@ -852,6 +864,11 @@ packages:
'@asamuzakjp/[email protected]':
resolution: {integrity: sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==}
+ '@asteasolutions/[email protected]':
+ resolution: {integrity: sha512-u05zNUirlukJAf9oEHmxSF31L1XQhz9XdpVILt7+xhrz65oQqBpiOWFkGvRWL0IpjOUJ878idKoNmYPxrFnkeg==}
+ peerDependencies:
+ zod: ^4.0.0
+
'@asyncapi/[email protected]':
resolution: {integrity: sha512-Sxn74oHiZSU6+cVeZy62iPZMFMvKp4jupMFHelSICCMw1qELmUHPvuZSr+ZHDmNGgHcEpzJM5HN02kR7T4g+PQ==}
@@ -2118,12 +2135,31 @@ packages:
peerDependencies:
hono-rate-limiter: ^0.2.1
+ resolution: {integrity: sha512-uF1W7/iSWi0r5Mugj5ZzdlCVp/KeGatS6JYt+Eht9xKO0IDtdZbdaLApgjrzHINQQa+Wnxw2pcX6EfO+vgB+Wg==}
+ peerDependencies:
+ '@standard-schema/spec': 1.0.0
+ hono: '>=3.9.0'
+
+ resolution: {integrity: sha512-KDfHqv/Wy4elVseZXgokbHxeWuqBL+AZfqsOMpEihBMUsk/fJ+bLIi3Sf70JFVpt1Ihui8RasYrInozt7ZBDIA==}
+ engines: {node: '>=16.0.0'}
+ peerDependencies:
+ hono: '>=4.3.6'
+ zod: ^4.0.0
+
resolution: {integrity: sha512-ub5eL/NeZ4eLZawu78JpW/J+dugDAYhwqUIdp9KYScI6PZECij4Hx4UsrthlEUutqDDhPwRI0MscUfNkvn/mqQ==}
peerDependencies:
hono: '>=3.9.0'
zod: ^3.25.0 || ^4.0.0
+ resolution: {integrity: sha512-Io1B6d011Gj1KknV4rXYz4le5+5EubcWEU/speUjuw9XMMIaP3n78yXLhjd2A3PXaXaUwEAluOiAyLqhBEJgsw==}
+ peerDependencies:
+ hono: '>=3.9.0'
+ zod: ^3.25.0 || ^4.0.0
+
'@hookform/[email protected]':
resolution: {integrity: sha512-A/IxlMLShx3KjV/HeTcTfaMxdwy690+L/ZADoeaTltLx+CVuzkeVIPuybK3jrRfw7YZnmdKsVVHAlEPIAEUNlA==}
peerDependencies:
@@ -3913,6 +3949,24 @@ packages:
cpu: [x64]
os: [win32]
+ '@scalar/[email protected]':
+ resolution: {integrity: sha512-Ka+g5P3Fe4f9lsJcBxfI+XAgwMYeZRgzIBWw1/HBrDoRmH3rV/N//410MBKEYXUw7pWpS+dZPJANZRvU5jtxhw==}
+ engines: {node: '>=20'}
+
+ '@scalar/[email protected]':
+ resolution: {integrity: sha512-G7oGybO2QXM+MIxa4OZLXaYsS9mxKygFgOcY4UOXO6xpVoY5+8rahdak9cPk7HNj8RZSt4m/BveoT8g5BtnXxg==}
+ engines: {node: '>=20'}
+
+ '@scalar/[email protected]':
+ resolution: {integrity: sha512-a9cPluqfi1bgX2p7PJl/2O4jgPcoAl/ecSAe74TbPYIi27A0O0bkUBscO7WNRJhWJ1GVVxX8NvJTNlDxUNBlpg==}
+ engines: {node: '>=20'}
+ peerDependencies:
+ hono: ^4.10.3
+
+ '@scalar/[email protected]':
+ resolution: {integrity: sha512-5FNQH/zx3tnERzxfpErscPHfRxLCuhncmhFYiaSz196Xi2iG1YI08BtxTV2slfT6of52epJ/MrKerarplKf9eg==}
+ engines: {node: '>=20'}
+
'@selderee/[email protected]':
resolution: {integrity: sha512-P33hHGdldxGabLFjPPpaTxVolMrzrcegejx+0GxjrIb9Zv48D8yAIA/QTDR2dFl7Uz7urX8aX6+5bCZslr+gWQ==}
@@ -4293,6 +4347,67 @@ packages:
'@socket.io/[email protected]':
resolution: {integrity: sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==}
+ '@standard-community/[email protected]':
+ resolution: {integrity: sha512-4+ZPorwDRt47i+O7RjyuaxHRK/37QY/LmgxlGrRrSTLYoFatEOzvqIc85GTlM18SFZ5E91C+v0o/M37wZPpUHA==}
+ peerDependencies:
+ '@standard-schema/spec': ^1.0.0
+ '@types/json-schema': ^7.0.15
+ '@valibot/to-json-schema': ^1.3.0
+ arktype: ^2.1.20
+ effect: ^3.16.8
+ quansync: ^0.2.11
+ sury: ^10.0.0
+ typebox: ^1.0.17
+ valibot: ^1.1.0
+ zod: ^3.25.0 || ^4.0.0
+ zod-to-json-schema: ^3.24.5
+ peerDependenciesMeta:
+ '@valibot/to-json-schema':
+ optional: true
+ arktype:
+ optional: true
+ effect:
+ optional: true
+ sury:
+ optional: true
+ typebox:
+ optional: true
+ valibot:
+ optional: true
+ zod:
+ optional: true
+ zod-to-json-schema:
+ optional: true
+
+ '@standard-community/[email protected]':
+ resolution: {integrity: sha512-htj+yldvN1XncyZi4rehbf9kLbu8os2Ke/rfqoZHCMHuw34kiF3LP/yQPdA0tQ940y8nDq3Iou8R3wG+AGGyvg==}
+ peerDependencies:
+ '@standard-community/standard-json': ^0.3.5
+ '@standard-schema/spec': ^1.0.0
+ arktype: ^2.1.20
+ effect: ^3.17.14
+ openapi-types: ^12.1.3
+ sury: ^10.0.0
+ typebox: ^1.0.0
+ valibot: ^1.1.0
+ zod: ^3.25.0 || ^4.0.0
+ zod-openapi: ^4
+ peerDependenciesMeta:
+ arktype:
+ optional: true
+ effect:
+ optional: true
+ sury:
+ optional: true
+ typebox:
+ optional: true
+ valibot:
+ optional: true
+ zod:
+ optional: true
+ zod-openapi:
+ optional: true
+
'@standard-schema/[email protected]':
resolution: {integrity: sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==}
@@ -6785,6 +6900,21 @@ packages:
resolution: {integrity: sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==}
+ resolution: {integrity: sha512-toUcO60MftRBxqcVyxsHNYs2m4vf4xkQaiARAucQx3TiBPDtMNNkoh+C4I1vAretQZiGyaLOZNWn1YxfSyUA5g==}
+ peerDependencies:
+ '@hono/standard-validator': ^0.2.0
+ '@standard-community/standard-json': ^0.3.5
+ '@standard-community/standard-openapi': ^0.2.9
+ '@types/json-schema': ^7.0.15
+ hono: ^4.8.3
+ openapi-types: ^12.1.3
+ peerDependenciesMeta:
+ '@hono/standard-validator':
+ optional: true
+ hono:
+ optional: true
+
resolution: {integrity: sha512-/pQIJWMd8saoySMoM3rhHNiC3XtZuZDkxBvtnPmRKrpNBZIG38k0cs+nVmBW5pc8HAmkS+I/14rbHfRObekWmw==}
peerDependencies:
@@ -8166,6 +8296,9 @@ packages:
resolution: {integrity: sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==}
+ resolution: {integrity: sha512-jaL+HgTq2Gj5jRcfdutgRGLosCy/hT8sQf6VOy+P+g36cZOjI1iukdPnijC+4CmeRzg/jEllJUboEic2FhxhtQ==}
+
resolution: {integrity: sha512-ur5UIdyw5Y7yEj9wLzhqXiy6GZ3Mwx0yGI+5sMn2r0N0v3cKJvUmFH5yPP+WXh9e0xfyzyJX95D8l088DNFj7A==}
hasBin: true
@@ -8532,6 +8665,9 @@ packages:
resolution: {integrity: sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==}
engines: {node: '>=0.6'}
+ resolution: {integrity: sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA==}
+
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
@@ -9594,6 +9730,10 @@ packages:
resolution: {integrity: sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==}
engines: {node: '>=16'}
+ resolution: {integrity: sha512-GeJop7+u7BYlQ6yQCAY1nBQiRSHR+6OdCEtd8Bwp9a3NK3+fWAVjOaPKJDteB9f6cIJ0wt4IfnScjLG450EpXA==}
+ engines: {node: '>=20'}
+
resolution: {integrity: sha512-VCn+LMHbd4t6sF3wfU/+HKT63C9OoyrSIf4b+vtWHpt2U7/4InZG467YDNMFMR70DdHjAdpPWmw2lzRdg0Xqqg==}
engines: {node: '>=20'}
@@ -10090,6 +10230,11 @@ packages:
engines: {node: '>= 14'}
hasBin: true
+ resolution: {integrity: sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A==}
+ engines: {node: '>= 14.6'}
+ hasBin: true
+
resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}
engines: {node: '>=12'}
@@ -10206,6 +10351,11 @@ snapshots:
'@csstools/css-tokenizer': 3.0.4
lru-cache: 10.4.3
+ dependencies:
+ openapi3-ts: 4.5.0
+ zod: 4.2.1
+
'@asyncapi/[email protected]':
dependencies:
'@asyncapi/specs': 6.8.1
@@ -11850,11 +12000,29 @@ snapshots:
dependencies:
hono-rate-limiter: 0.2.3([email protected])
+ dependencies:
+ '@standard-schema/spec': 1.0.0
+ hono: 4.11.1
+
+ dependencies:
+ '@asteasolutions/zod-to-openapi': 8.2.0([email protected])
+ '@hono/zod-validator': 0.7.6([email protected])([email protected])
+ hono: 4.11.1
+ openapi3-ts: 4.5.0
+ zod: 4.2.1
+
dependencies:
hono: 4.11.1
zod: 4.2.1
+ dependencies:
+ hono: 4.11.1
+ zod: 4.2.1
+
dependencies:
'@standard-schema/utils': 0.3.0
@@ -13969,6 +14137,24 @@ snapshots:
'@rollup/[email protected]':
optional: true
+ '@scalar/[email protected]':
+ dependencies:
+ '@scalar/types': 0.5.4
+
+ '@scalar/[email protected]': {}
+
+ dependencies:
+ '@scalar/core': 0.3.28
+ hono: 4.11.1
+
+ '@scalar/[email protected]':
+ dependencies:
+ '@scalar/helpers': 0.2.4
+ nanoid: 5.1.5
+ type-fest: 5.0.0
+ zod: 4.2.1
+
'@selderee/[email protected]':
dependencies:
domhandler: 5.0.3
@@ -14559,6 +14745,24 @@ snapshots:
'@socket.io/[email protected]': {}
+ dependencies:
+ '@standard-schema/spec': 1.0.0
+ '@types/json-schema': 7.0.15
+ quansync: 0.2.11
+ optionalDependencies:
+ arktype: 2.1.29
+ zod: 4.2.1
+
+ dependencies:
+ '@standard-community/standard-json': 0.3.5(@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])
+ '@standard-schema/spec': 1.0.0
+ openapi-types: 12.1.3
+ optionalDependencies:
+ arktype: 2.1.29
+ zod: 4.2.1
+
'@standard-schema/[email protected]': {}
'@standard-schema/[email protected]': {}
@@ -15276,7 +15480,7 @@ snapshots:
dependencies:
crypto-js: 4.2.0
optionalDependencies:
react: 19.2.1
@@ -15289,7 +15493,7 @@ snapshots:
dependencies:
'@upstash/redis': 1.34.8
dependencies:
'@babel/core': 7.28.3
'@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/[email protected])
@@ -15297,7 +15501,7 @@ snapshots:
'@rolldown/pluginutils': 1.0.0-beta.30
'@types/babel__core': 7.20.5
react-refresh: 0.17.0
transitivePeerDependencies:
- supports-color
@@ -15310,13 +15514,13 @@ snapshots:
chai: 6.2.1
tinyrainbow: 3.0.3
dependencies:
'@vitest/spy': 4.0.16
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
'@vitest/[email protected]':
dependencies:
@@ -15722,7 +15926,7 @@ snapshots:
dependencies:
@@ -15742,7 +15946,7 @@ snapshots:
prisma: 6.8.2([email protected])
react: 19.2.1
react-dom: 19.2.1([email protected])
dependencies:
@@ -17449,6 +17653,16 @@ snapshots:
dependencies:
react-is: 16.13.1
+ dependencies:
+ '@standard-community/standard-json': 0.3.5(@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])
+ '@standard-community/standard-openapi': 0.2.9(@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]))(@standard-schema/[email protected])([email protected])([email protected])([email protected])
+ '@types/json-schema': 7.0.15
+ openapi-types: 12.1.3
+ optionalDependencies:
+ '@hono/standard-validator': 0.2.1(@standard-schema/[email protected])([email protected])
+ hono: 4.11.1
+
dependencies:
hono: 4.11.1
@@ -18964,7 +19178,7 @@ snapshots:
react: 19.2.1
react-dom: 19.2.1([email protected])
dependencies:
react: 19.2.1
@@ -19139,6 +19353,10 @@ snapshots:
+ dependencies:
+ yaml: 2.8.2
+
@@ -19528,6 +19746,8 @@ snapshots:
dependencies:
side-channel: 1.1.0
+
@@ -20962,6 +21182,10 @@ snapshots:
+ dependencies:
+ tagged-tag: 1.0.0
+
dependencies:
tagged-tag: 1.0.0
@@ -21249,7 +21473,7 @@ snapshots:
replace-ext: 2.0.0
teex: 1.0.1
dependencies:
esbuild: 0.27.2
fdir: 6.5.0([email protected])
@@ -21264,12 +21488,12 @@ snapshots:
lightningcss: 1.30.2
terser: 5.39.0
tsx: 4.19.3
- yaml: 2.7.1
+ yaml: 2.8.2
dependencies:
'@vitest/expect': 4.0.16
'@vitest/pretty-format': 4.0.16
'@vitest/runner': 4.0.16
'@vitest/snapshot': 4.0.16
@@ -21286,7 +21510,7 @@ snapshots:
tinyexec: 1.0.2
tinyglobby: 0.2.15
tinyrainbow: 3.0.3
why-is-node-running: 2.3.0
optionalDependencies:
'@opentelemetry/api': 1.9.0
@@ -21517,6 +21741,8 @@ snapshots:
+