Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
🔒️ Use scrypt to has space-level api keys (#2150)
Luke Vellad060f67cd320
diff --git a/apps/web/src/app/api/private/[...route]/route.test.ts b/apps/web/src/app/api/private/[...route]/route.test.tsindex ac12c02fd..d55fb306e 100644--- a/apps/web/src/app/api/private/[...route]/route.test.ts+++ b/apps/web/src/app/api/private/[...route]/route.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";// Mock server-only before any imports that might need itvi.mock("server-only", () => ({}));@@ -57,19 +57,32 @@ vi.mock("@/lib/kv", () => ({}));import { prisma } from "@rallly/database";-import { hashApiKey, randomToken } from "@/features/developer/utils";+import { createApiKey } from "@/features/developer/utils";import { app } from "./route";-const createMockApiKey = (rawKey: string) => {- // Use the new salted hash format- const salt = randomToken(12);- const hash = hashApiKey(rawKey, salt);- const hashedKey = `sha256$${salt}$${hash}`;+// Pre-generated test API key and hash (created once, reused across all tests)+let testApiKey: string;+let mockApiKey: {+ id: string;+ name: string;+ prefix: string;+ spaceId: string;+ hashedKey: string;+ lastUsedAt: null;+ expiresAt: null;+ revokedAt: null;+ createdAt: Date;+ updatedAt: Date;+ space: { ownerId: string };+};- return {+beforeAll(async () => {+ const { apiKey, prefix, hashedKey } = await createApiKey();+ testApiKey = apiKey;+ mockApiKey = {id: "api-key-id",name: "Test API Key",- prefix: "abc123",+ prefix,spaceId: "test-space-id",hashedKey,lastUsedAt: null,@@ -81,12 +94,9 @@ const createMockApiKey = (rawKey: string) => {ownerId: "test-user-id",},};-};+});describe("Private API - /polls", () => {- const testApiKey = "sk_abc123_secretkey";- const mockApiKey = createMockApiKey(testApiKey);-beforeEach(() => {vi.clearAllMocks();diff --git a/apps/web/src/app/api/private/utils/api-key.ts b/apps/web/src/app/api/private/utils/api-key.tsindex fab03f8ff..23bfb5fbb 100644--- a/apps/web/src/app/api/private/utils/api-key.ts+++ b/apps/web/src/app/api/private/utils/api-key.ts@@ -35,8 +35,9 @@ export const spaceApiKeyAuth = bearerAuth({},});- // Constant-time search through candidates- let validKey = null;+ let apiKeyId: string | null = null;+ let spaceId: string | null = null;+ let spaceOwnerId: string | null = null;for (const candidate of candidateKeys) {// Timing-safe prefix comparisonconst candidateBuffer = Buffer.from(candidate.prefix);@@ -45,26 +46,28 @@ export const spaceApiKeyAuth = bearerAuth({crypto.timingSafeEqual(prefixBuffer, candidateBuffer)) {// Verify the full key hash- if (verifyApiKey(rawKey, candidate.hashedKey)) {- validKey = candidate;- // Continue iterating to maintain constant time+ const isValid = await verifyApiKey(rawKey, candidate.hashedKey);+ if (isValid) {+ apiKeyId = candidate.id;+ spaceId = candidate.spaceId;+ spaceOwnerId = candidate.space.ownerId;}}}- if (!validKey) {+ if (!apiKeyId || !spaceId || !spaceOwnerId) {return false;}c.set("apiAuth", {- spaceId: validKey.spaceId,- spaceOwnerId: validKey.space.ownerId,- apiKeyId: validKey.id,+ spaceId,+ spaceOwnerId,+ apiKeyId,});waitUntil(prisma.spaceApiKey.update({- where: { id: validKey.id },+ where: { id: apiKeyId },data: { lastUsedAt: new Date() },}),);diff --git a/apps/web/src/features/developer/utils.test.ts b/apps/web/src/features/developer/utils.test.tsindex 5553769ae..f0fd6292c 100644--- a/apps/web/src/features/developer/utils.test.ts+++ b/apps/web/src/features/developer/utils.test.ts@@ -2,10 +2,7 @@ import { describe, expect, it } from "vitest";import {createApiKey,extractApiKeyPrefix,- hashApiKey,- isHexSha256,randomToken,- sha256Hex,verifyApiKey,} from "./utils";@@ -29,75 +26,36 @@ describe("randomToken", () => {});});-describe("sha256Hex", () => {- it("should generate consistent hashes for same input", () => {- const input = "test-string";- const hash1 = sha256Hex(input);- const hash2 = sha256Hex(input);- expect(hash1).toBe(hash2);- });-- it("should generate different hashes for different inputs", () => {- const hash1 = sha256Hex("input1");- const hash2 = sha256Hex("input2");- expect(hash1).not.toBe(hash2);- });-- it("should generate 64-character hex strings", () => {- const hash = sha256Hex("test");- expect(hash).toMatch(/^[a-f0-9]{64}$/);- });-});--describe("isHexSha256", () => {- it("should return true for valid SHA-256 hex strings", () => {- const validHash =- "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08";- expect(isHexSha256(validHash)).toBe(true);- });-- it("should return false for strings that are too short", () => {- expect(isHexSha256("abc123")).toBe(false);- });-- it("should return false for strings with non-hex characters", () => {- const invalidHash =- "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00aGZ";- expect(isHexSha256(invalidHash)).toBe(false);- });-- it("should return false for empty strings", () => {- expect(isHexSha256("")).toBe(false);- });-});-describe("createApiKey", () => {- it("should generate an API key with correct format", () => {- const result = createApiKey();+ it("should generate an API key with correct format", async () => {+ const result = await createApiKey();expect(result.apiKey).toMatch(/^sk_[A-Za-z0-9_-]+_[A-Za-z0-9_-]+$/);});- it("should generate unique API keys on each call", () => {- const result1 = createApiKey();- const result2 = createApiKey();+ it("should generate unique API keys on each call", async () => {+ const result1 = await createApiKey();+ const result2 = await createApiKey();expect(result1.apiKey).not.toBe(result2.apiKey);expect(result1.prefix).not.toBe(result2.prefix);});- it("should generate a valid prefix", () => {- const result = createApiKey();+ it("should generate a valid prefix", async () => {+ const result = await createApiKey();expect(result.prefix).toBeTruthy();expect(result.prefix.length).toBeGreaterThan(0);});- it("should generate a hashed key in correct format", () => {- const result = createApiKey();- expect(result.hashedKey).toMatch(/^sha256\$[A-Za-z0-9_-]+\$[a-f0-9]{64}$/);+ it("should generate a hashed key in scrypt format", async () => {+ const result = await createApiKey();+ expect(result.hashedKey).toMatch(+ /^scrypt\$\d+\$\d+\$\d+\$[A-Za-z0-9_-]+\$[a-f0-9]+$/,+ );});- it("should verify the generated API key against its hash", () => {- const result = createApiKey();- expect(verifyApiKey(result.apiKey, result.hashedKey)).toBe(true);+ it("should verify the generated API key against its hash", async () => {+ const result = await createApiKey();+ const isValid = await verifyApiKey(result.apiKey, result.hashedKey);+ expect(isValid).toBe(true);});});@@ -118,120 +76,107 @@ describe("extractApiKeyPrefix", () => {});});-describe("hashApiKey", () => {- it("should generate consistent hashes without salt", () => {- const key = "test-api-key";- const hash1 = hashApiKey(key);- const hash2 = hashApiKey(key);- expect(hash1).toBe(hash2);- });-- it("should generate consistent hashes with salt", () => {- const key = "test-api-key";- const salt = "test-salt";- const hash1 = hashApiKey(key, salt);- const hash2 = hashApiKey(key, salt);- expect(hash1).toBe(hash2);- });-- it("should generate different hashes for different salts", () => {- const key = "test-api-key";- const hash1 = hashApiKey(key, "salt1");- const hash2 = hashApiKey(key, "salt2");- expect(hash1).not.toBe(hash2);- });-- it("should generate different hashes with and without salt", () => {- const key = "test-api-key";- const hash1 = hashApiKey(key);- const hash2 = hashApiKey(key, "salt");- expect(hash1).not.toBe(hash2);- });-});-describe("verifyApiKey", () => {- describe("salted format (sha256$salt$hash)", () => {- it("should verify correct API key", () => {- const result = createApiKey();- expect(verifyApiKey(result.apiKey, result.hashedKey)).toBe(true);- });-- it("should reject incorrect API key", () => {- const result = createApiKey();- const wrongKey = "sk_wrong_prefix_wrong_secret";- expect(verifyApiKey(wrongKey, result.hashedKey)).toBe(false);+ it("should verify correct API key", async () => {+ const result = await createApiKey();+ const isValid = await verifyApiKey(result.apiKey, result.hashedKey);+ expect(isValid).toBe(true);+ });++ it("should reject incorrect API key", async () => {+ const result = await createApiKey();+ 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 parts = result.hashedKey.split("$");+ parts[4] = "wrongsalt";+ const tamperedHash = parts.join("$");+ const isValid = await verifyApiKey(result.apiKey, tamperedHash);+ expect(isValid).toBe(false);+ });++ it("should reject API key with tampered hash", async () => {+ const result = await createApiKey();+ const parts = result.hashedKey.split("$");+ parts[5] = "0".repeat(128);+ const tamperedHash = parts.join("$");+ const isValid = await verifyApiKey(result.apiKey, tamperedHash);+ expect(isValid).toBe(false);+ });++ it("should reject malformed hash format", async () => {+ const result = await createApiKey();+ const isValid = await verifyApiKey(result.apiKey, "scrypt$16384$8$1$salt");+ expect(isValid).toBe(false);+ });++ // ------------------------------------------------------------------+ // DEPRECATED: Legacy SHA-256 format tests+ // TODO: Remove this block once all existing API keys have been regenerated+ // ------------------------------------------------------------------+ describe("legacy sha256 format (deprecated)", () => {+ // Helper to create a legacy hash for testing+ const createLegacySha256Hash = (apiKey: string, salt: string): string => {+ const crypto = require("node:crypto");+ const hash = crypto+ .createHash("sha256")+ .update(`${salt}:${apiKey}`)+ .digest("hex");+ return `sha256$${salt}$${hash}`;+ };++ it("should verify correct legacy API key", async () => {+ const apiKey = "sk_test_legacykey";+ const storedHash = createLegacySha256Hash(apiKey, "testsalt123");+ const isValid = await verifyApiKey(apiKey, storedHash);+ expect(isValid).toBe(true);});- it("should reject API key with tampered salt", () => {- const result = createApiKey();- const [, , hash] = result.hashedKey.split("$");- const tamperedHash = `sha256$wrongsalt$${hash}`;- expect(verifyApiKey(result.apiKey, tamperedHash)).toBe(false);+ it("should reject incorrect legacy API key", async () => {+ const storedHash = createLegacySha256Hash(+ "sk_test_legacykey",+ "testsalt123",+ );+ const isValid = await verifyApiKey("wrong-key", storedHash);+ expect(isValid).toBe(false);});- it("should reject API key with tampered hash", () => {- const result = createApiKey();- const [, salt] = result.hashedKey.split("$");- const tamperedHash = `sha256$${salt}$${"0".repeat(64)}`;- expect(verifyApiKey(result.apiKey, tamperedHash)).toBe(false);- });-- it("should reject malformed hash format", () => {- const result = createApiKey();- expect(verifyApiKey(result.apiKey, "sha256$invalidsalt")).toBe(false);- });-- it("should reject hash with non-hex characters", () => {- const result = createApiKey();- expect(verifyApiKey(result.apiKey, "sha256$salt$notahex")).toBe(false);+ it("should reject malformed legacy hash", async () => {+ const isValid = await verifyApiKey("test-key", "sha256$salt$notahex");+ expect(isValid).toBe(false);});});- describe("legacy format (plain hex)", () => {- it("should verify correct legacy API key", () => {- const apiKey = "test-legacy-key";- const hash = sha256Hex(apiKey);- expect(verifyApiKey(apiKey, hash)).toBe(true);- });-- it("should reject incorrect legacy API key", () => {- const apiKey = "test-legacy-key";- const hash = sha256Hex(apiKey);- expect(verifyApiKey("wrong-key", hash)).toBe(false);- });-- it("should reject malformed legacy hash", () => {- expect(verifyApiKey("test-key", "not-a-valid-hash")).toBe(false);- });+ it("should handle hashes with whitespace", async () => {+ const result = await createApiKey();+ const hashWithSpace = ` ${result.hashedKey} `;+ const isValid = await verifyApiKey(result.apiKey, hashWithSpace);+ expect(isValid).toBe(true);});- describe("edge cases", () => {- it("should handle hashes with whitespace", () => {- const result = createApiKey();- const hashWithSpace = ` ${result.hashedKey} `;- expect(verifyApiKey(result.apiKey, hashWithSpace)).toBe(true);- });-- it("should reject empty hash", () => {- expect(verifyApiKey("test-key", "")).toBe(false);- });+ it("should reject empty hash", async () => {+ const isValid = await verifyApiKey("test-key", "");+ expect(isValid).toBe(false);+ });- it("should reject hash with only prefix", () => {- expect(verifyApiKey("test-key", "sha256$")).toBe(false);- });+ it("should reject hash with only prefix", async () => {+ const isValid = await verifyApiKey("test-key", "scrypt$");+ expect(isValid).toBe(false);});- describe("timing attack resistance", () => {- it("should use constant-time comparison", () => {- // This test verifies that the function uses timingSafeEqual- // by checking that both valid and invalid keys execute the comparison- const result = createApiKey();+ it("should use constant-time comparison", async () => {+ const result = await createApiKey();- // Both should complete without throwing- expect(() => verifyApiKey(result.apiKey, result.hashedKey)).not.toThrow();- expect(() =>- verifyApiKey("sk_wrong_key", result.hashedKey),- ).not.toThrow();- });+ // Both should complete without throwing+ await expect(+ verifyApiKey(result.apiKey, result.hashedKey),+ ).resolves.toBeDefined();+ await expect(+ verifyApiKey("sk_wrong_key", result.hashedKey),+ ).resolves.toBeDefined();});});diff --git a/apps/web/src/features/developer/utils.ts b/apps/web/src/features/developer/utils.tsindex 91a5efb87..b5d9e7645 100644--- a/apps/web/src/features/developer/utils.ts+++ b/apps/web/src/features/developer/utils.ts@@ -1,4 +1,27 @@import crypto from "node:crypto";+import { createLogger } from "@rallly/logger";++const logger = createLogger("api-key");++const scryptAsync = (+ password: string,+ salt: string,+ keylen: number,+ options: crypto.ScryptOptions,+): Promise<Buffer> => {+ return new Promise((resolve, reject) => {+ crypto.scrypt(password, salt, keylen, options, (err, derivedKey) => {+ if (err) reject(err);+ else resolve(derivedKey);+ });+ });+};++// scrypt parameters - these provide strong security while keeping verification under 100ms+const SCRYPT_COST = 16384; // N: CPU/memory cost (2^14)+const SCRYPT_BLOCK_SIZE = 8; // r: block size+const SCRYPT_PARALLELIZATION = 1; // p: parallelization+const SCRYPT_KEY_LENGTH = 64; // output length in bytes/*** Generate a cryptographically random token@@ -9,28 +32,39 @@ export const randomToken = (bytes: number): string =>crypto.randomBytes(bytes).toString("base64url");/**- * Hash a value using SHA-256- * @param value String to hash- * @returns Hex-encoded SHA-256 hash+ * Hash an API key using scrypt+ * @param rawKey Raw API key to hash+ * @param salt Salt for hashing+ * @returns Hex-encoded scrypt hash*/-export const sha256Hex = (value: string): string =>- crypto.createHash("sha256").update(value).digest("hex");+export const scryptHash = async (+ rawKey: string,+ salt: string,+): Promise<string> => {+ const derivedKey = (await scryptAsync(rawKey, salt, SCRYPT_KEY_LENGTH, {+ N: SCRYPT_COST,+ r: SCRYPT_BLOCK_SIZE,+ p: SCRYPT_PARALLELIZATION,+ })) as Buffer;+ return derivedKey.toString("hex");+};/*** Create an API key with the format: sk_{prefix}_{secret}* @returns Object containing the full API key and components for storage*/-export const createApiKey = (): {+export const createApiKey = async (): Promise<{apiKey: string;prefix: string;hashedKey: string;-} => {+}> => {const prefix = randomToken(6);const secret = randomToken(24);const apiKey = `sk_${prefix}_${secret}`;- const salt = randomToken(12);- const hashedKey = `sha256$${salt}$${sha256Hex(`${salt}:${apiKey}`)}`;+ const salt = randomToken(16);+ const hash = await scryptHash(apiKey, salt);+ const hashedKey = `scrypt$${SCRYPT_COST}$${SCRYPT_BLOCK_SIZE}$${SCRYPT_PARALLELIZATION}$${salt}$${hash}`;return {apiKey,@@ -54,49 +88,89 @@ export const extractApiKeyPrefix = (rawKey: string): string => {};/**- * Check if a string is a valid hex SHA-256 hash- * @param value String to validate- * @returns True if valid hex SHA-256 (64 characters)- */-export const isHexSha256 = (value: string): boolean =>- /^[a-f0-9]{64}$/i.test(value);--/**- * Hash an API key with optional salt (for verification)- * @param rawKey Raw API key- * @param salt Optional salt for hashing- * @returns Hex-encoded SHA-256 hash- */-export const hashApiKey = (rawKey: string, salt?: string): string => {- const input = salt ? `${salt}:${rawKey}` : rawKey;- return sha256Hex(input);-};--/**- * Verify a raw API key against a stored hash- * Supports both legacy (unsalted) and current (salted) hash formats+ * Verify a raw API key against a stored scrypt hash* @param rawKey Raw API key to verify- * @param storedHash Stored hash from database (format: "sha256$salt$hash" or plain hex)+ * @param storedHash Stored hash from database (format: scrypt$N$r$p$salt$hash)* @returns True if the key matches the hash*/-export const verifyApiKey = (rawKey: string, storedHash: string): boolean => {+export const verifyApiKey = async (+ rawKey: string,+ storedHash: string,+): Promise<boolean> => {const trimmed = storedHash.trim();- // Current format: sha256$salt$hash- if (trimmed.startsWith("sha256$")) {- const [, salt, hash] = trimmed.split("$");- if (!salt || !hash || !isHexSha256(hash)) {+ // Current format: scrypt$N$r$p$salt$hash+ if (trimmed.startsWith("scrypt$")) {+ const parts = trimmed.split("$");+ if (parts.length !== 6) {+ return false;+ }++ const [, nStr, rStr, pStr, salt, hash] = parts;+ if (!nStr || !rStr || !pStr || !salt || !hash) {return false;}- const computed = hashApiKey(rawKey, salt);- return crypto.timingSafeEqual(Buffer.from(computed), Buffer.from(hash));++ const N = Number.parseInt(nStr, 10);+ const r = Number.parseInt(rStr, 10);+ const p = Number.parseInt(pStr, 10);+ if (+ !Number.isSafeInteger(N) ||+ !Number.isSafeInteger(r) ||+ !Number.isSafeInteger(p) ||+ N <= 1 ||+ r <= 0 ||+ p <= 0 ||+ (N & (N - 1)) !== 0+ ) {+ return false;+ }++ let derivedKey: Buffer;+ try {+ derivedKey = await scryptAsync(rawKey, salt, SCRYPT_KEY_LENGTH, {+ N,+ r,+ p,+ });+ } catch (error) {+ logger.error({ error }, "scrypt verification failed");+ return false;+ }+ const computed = derivedKey.toString("hex");++ return (+ computed.length === hash.length &&+ crypto.timingSafeEqual(Buffer.from(computed), Buffer.from(hash))+ );}- // Legacy format: plain hex hash (unsalted)- if (!isHexSha256(trimmed)) {- return false;+ // ------------------------------------------------------------------+ // DEPRECATED: Legacy SHA-256 format support (read-only)+ // TODO: Remove this block once all existing API keys have been regenerated+ // ------------------------------------------------------------------+ if (trimmed.startsWith("sha256$")) {+ return verifyLegacySha256(rawKey, trimmed);}- const computed = hashApiKey(rawKey);- return crypto.timingSafeEqual(Buffer.from(computed), Buffer.from(trimmed));+ return false;+};++// ------------------------------------------------------------------+// DEPRECATED: Legacy SHA-256 verification (read-only)+// TODO: Remove these functions once all existing API keys have been regenerated+// ------------------------------------------------------------------++const isHexSha256 = (value: string): boolean => /^[a-f0-9]{64}$/i.test(value);++const sha256Hex = (value: string): string =>+ crypto.createHash("sha256").update(value).digest("hex");++const verifyLegacySha256 = (rawKey: string, storedHash: string): boolean => {+ const [, salt, hash] = storedHash.split("$");+ if (!salt || !hash || !isHexSha256(hash)) {+ return false;+ }+ const computed = sha256Hex(`${salt}:${rawKey}`);+ return crypto.timingSafeEqual(Buffer.from(computed), Buffer.from(hash));};diff --git a/apps/web/src/trpc/routers/api-keys.ts b/apps/web/src/trpc/routers/api-keys.tsindex a3fdf5c39..0c3c6e6d7 100644--- a/apps/web/src/trpc/routers/api-keys.ts+++ b/apps/web/src/trpc/routers/api-keys.ts@@ -33,7 +33,7 @@ export const apiKeys = router({}),).mutation(async ({ input, ctx }) => {- const { apiKey, prefix, hashedKey } = createApiKey();+ const { apiKey, prefix, hashedKey } = await createApiKey();await prisma.spaceApiKey.create({data: {