Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
⚡️ Replace scrypt with SHA-256 for API key hashing (#2534)
Luke Vella0ca102d605ca
diff --git a/apps/web/src/app/api/private/[...route]/route.test.ts b/apps/web/src/app/api/private/[...route]/route.test.tsindex 0c4b0ec83..2b6e74452 100644--- a/apps/web/src/app/api/private/[...route]/route.test.ts+++ b/apps/web/src/app/api/private/[...route]/route.test.ts@@ -56,10 +56,13 @@ vi.mock("@/lib/kv", () => ({}));import { prisma } from "@rallly/database";+import { after } from "next/server";+import { hashApiKey, verifyApiKey } from "@/features/api-keys/api-key";import { app } from "./route";-// Pre-generated test API key fixture (eliminates non-deterministic scrypt timing issues)-// Generated once using createApiKey() and saved here for consistent test behavior+// Pre-generated test API key fixture. The stored hash deliberately uses the+// deprecated scrypt format so every test in this file exercises the legacy+// verification path that existing production keys depend on.const testApiKey = "sk_eXzkd84Y_bN24KFwZ_UyiQ0b6zckpNfL2pSdng3r3";const mockApiKey = {id: "api-key-id",@@ -181,6 +184,71 @@ describe("Private API - /polls", () => {});});+ describe("Hash migration (scrypt -> sha256)", () => {+ // The lastUsedAt/re-hash update runs in an after() callback; invoke the+ // captured callbacks to simulate the post-response phase+ const flushAfterCallbacks = async () => {+ for (const [callback] of vi.mocked(after).mock.calls) {+ await (callback as () => Promise<unknown>)();+ }+ };++ it("should authenticate a legacy scrypt-hashed key and re-hash it to sha256", 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"],+ }),+ });++ expect(res.status).toBe(200);+ await flushAfterCallbacks();++ expect(prisma.spaceApiKey.update).toHaveBeenCalledWith({+ where: { id: mockApiKey.id },+ data: expect.objectContaining({+ hashedKey: expect.stringMatching(/^sha256\$/),+ }),+ });++ // The re-hashed value must still verify the original key+ const updateCall = vi.mocked(prisma.spaceApiKey.update).mock.calls[0];+ const newHash = updateCall?.[0]?.data?.hashedKey as string;+ expect(await verifyApiKey(testApiKey, newHash)).toBe(true);+ });++ it("should authenticate a sha256-hashed key without re-hashing", async () => {+ vi.mocked(prisma.spaceApiKey.findMany).mockResolvedValue([+ { ...mockApiKey, hashedKey: hashApiKey(testApiKey) },+ ]);++ 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(200);+ await flushAfterCallbacks();++ expect(prisma.spaceApiKey.update).toHaveBeenCalledWith({+ where: { id: mockApiKey.id },+ data: { lastUsedAt: expect.any(Date) },+ });+ });+ });+describe("Create poll with dates", () => {it("should create a poll with date options", async () => {const res = await app.request("/api/private/polls", {diff --git a/apps/web/src/app/api/private/utils/api-key.ts b/apps/web/src/app/api/private/utils/api-key.tsindex 94339af99..d14ddd1e9 100644--- a/apps/web/src/app/api/private/utils/api-key.ts+++ b/apps/web/src/app/api/private/utils/api-key.ts@@ -2,7 +2,12 @@ import crypto from "node:crypto";import { prisma } from "@rallly/database";import { bearerAuth } from "hono/bearer-auth";import { after } from "next/server";-import { extractApiKeyPrefix, verifyApiKey } from "@/features/api-keys/api-key";+import {+ extractApiKeyPrefix,+ hashApiKey,+ isLegacyApiKeyHash,+ verifyApiKey,+} from "@/features/api-keys/api-key";export const spaceApiKeyAuth = bearerAuth({verifyToken: async (rawKey, c) => {@@ -38,6 +43,7 @@ export const spaceApiKeyAuth = bearerAuth({let apiKeyId: string | null = null;let spaceId: string | null = null;let spaceOwnerId: string | null = null;+ let needsRehash = false;for (const candidate of candidateKeys) {// Timing-safe prefix comparisonconst candidateBuffer = Buffer.from(candidate.prefix);@@ -51,6 +57,7 @@ export const spaceApiKeyAuth = bearerAuth({apiKeyId = candidate.id;spaceId = candidate.spaceId;spaceOwnerId = candidate.space.ownerId;+ needsRehash = isLegacyApiKeyHash(candidate.hashedKey);}}}@@ -65,10 +72,17 @@ export const spaceApiKeyAuth = bearerAuth({apiKeyId,});+ // Lazily migrate deprecated scrypt hashes to sha256 — we only hold the+ // raw key during verification, so this is the one place we can re-hash.+ const rehashedKey = needsRehash ? hashApiKey(rawKey) : null;+after(() =>prisma.spaceApiKey.update({where: { id: apiKeyId },- data: { lastUsedAt: new Date() },+ data: {+ lastUsedAt: new Date(),+ ...(rehashedKey ? { hashedKey: rehashedKey } : {}),+ },}),);diff --git a/apps/web/src/features/api-keys/api-key.test.ts b/apps/web/src/features/api-keys/api-key.test.tsindex c5e89fa1a..36455df50 100644--- a/apps/web/src/features/api-keys/api-key.test.ts+++ b/apps/web/src/features/api-keys/api-key.test.ts@@ -1,11 +1,23 @@+import crypto from "node:crypto";import { describe, expect, it } from "vitest";import {createApiKey,extractApiKeyPrefix,+ hashApiKey,+ isLegacyApiKeyHash,randomToken,verifyApiKey,} from "./api-key";+// Helper to create a hash in the deprecated scrypt format, as stored by the+// previous implementation (scrypt$N$r$p$salt$hash)+const createLegacyScryptHash = (apiKey: string, salt: string): string => {+ const hash = crypto+ .scryptSync(apiKey, salt, 64, { N: 16384, r: 8, p: 1 })+ .toString("hex");+ return `scrypt$16384$8$1$${salt}$${hash}`;+};+describe("randomToken", () => {it("should generate tokens of correct length", () => {const token = randomToken(16);@@ -45,11 +57,9 @@ describe("createApiKey", () => {expect(result.prefix.length).toBeGreaterThan(0);});- it("should generate a hashed key in scrypt format", async () => {+ it("should generate a hashed key in sha256 format", async () => {const result = await createApiKey();- expect(result.hashedKey).toMatch(- /^scrypt\$\d+\$\d+\$\d+\$[A-Za-z0-9_-]+\$[a-f0-9]+$/,- );+ expect(result.hashedKey).toMatch(/^sha256\$[A-Za-z0-9_-]+\$[a-f0-9]{64}$/);});it("should verify the generated API key against its hash", async () => {@@ -59,6 +69,30 @@ describe("createApiKey", () => {});});+describe("hashApiKey", () => {+ it("should produce a sha256 format hash that verifies", async () => {+ const hashed = hashApiKey("sk_test_somekey");+ expect(hashed).toMatch(/^sha256\$[A-Za-z0-9_-]+\$[a-f0-9]{64}$/);+ expect(await verifyApiKey("sk_test_somekey", hashed)).toBe(true);+ });++ it("should salt hashes so the same key hashes differently", () => {+ const key = "sk_test_somekey";+ expect(hashApiKey(key)).not.toBe(hashApiKey(key));+ });+});++describe("isLegacyApiKeyHash", () => {+ it("should identify scrypt hashes as legacy", () => {+ const hash = createLegacyScryptHash("sk_test_key", "somesalt");+ expect(isLegacyApiKeyHash(hash)).toBe(true);+ });++ it("should not identify sha256 hashes as legacy", () => {+ expect(isLegacyApiKeyHash(hashApiKey("sk_test_key"))).toBe(false);+ });+});+describe("extractApiKeyPrefix", () => {it("should extract prefix from valid API key", () => {const apiKey = "sk_abc123_def456";@@ -93,7 +127,7 @@ describe("verifyApiKey", () => {it("should reject API key with tampered salt", async () => {const result = await createApiKey();const parts = result.hashedKey.split("$");- parts[4] = "wrongsalt";+ parts[1] = "wrongsalt";const tamperedHash = parts.join("$");const isValid = await verifyApiKey(result.apiKey, tamperedHash);expect(isValid).toBe(false);@@ -102,7 +136,7 @@ describe("verifyApiKey", () => {it("should reject API key with tampered hash", async () => {const result = await createApiKey();const parts = result.hashedKey.split("$");- parts[5] = "0".repeat(128);+ parts[2] = "0".repeat(64);const tamperedHash = parts.join("$");const isValid = await verifyApiKey(result.apiKey, tamperedHash);expect(isValid).toBe(false);@@ -110,34 +144,29 @@ describe("verifyApiKey", () => {it("should reject malformed hash format", async () => {const result = await createApiKey();- const isValid = await verifyApiKey(result.apiKey, "scrypt$16384$8$1$salt");+ const isValid = await verifyApiKey(result.apiKey, "sha256$saltonly");+ expect(isValid).toBe(false);+ });++ it("should reject non-hex hash payload", async () => {+ const isValid = await verifyApiKey("test-key", "sha256$salt$notahex");expect(isValid).toBe(false);});// ------------------------------------------------------------------- // DEPRECATED: Legacy SHA-256 format tests- // TODO: Remove this block once all existing API keys have been regenerated+ // DEPRECATED: scrypt format tests — existing keys created before the+ // sha256 migration must keep verifying until they are lazily re-hashed// ------------------------------------------------------------------- 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}`;- };-+ describe("legacy scrypt format (deprecated)", () => {it("should verify correct legacy API key", async () => {const apiKey = "sk_test_legacykey";- const storedHash = createLegacySha256Hash(apiKey, "testsalt123");+ const storedHash = createLegacyScryptHash(apiKey, "testsalt123");const isValid = await verifyApiKey(apiKey, storedHash);expect(isValid).toBe(true);});it("should reject incorrect legacy API key", async () => {- const storedHash = createLegacySha256Hash(+ const storedHash = createLegacyScryptHash("sk_test_legacykey","testsalt123",);@@ -145,8 +174,24 @@ describe("verifyApiKey", () => {expect(isValid).toBe(false);});- it("should reject malformed legacy hash", async () => {- const isValid = await verifyApiKey("test-key", "sha256$salt$notahex");+ it("should reject legacy hash with tampered salt", async () => {+ const apiKey = "sk_test_legacykey";+ const parts = createLegacyScryptHash(apiKey, "testsalt123").split("$");+ parts[4] = "wrongsalt";+ const isValid = await verifyApiKey(apiKey, parts.join("$"));+ expect(isValid).toBe(false);+ });++ it("should reject legacy hash with missing parts", async () => {+ const isValid = await verifyApiKey("test-key", "scrypt$16384$8$1$salt");+ expect(isValid).toBe(false);+ });++ it("should reject legacy hash with invalid cost parameters", async () => {+ const isValid = await verifyApiKey(+ "test-key",+ "scrypt$12345$8$1$salt$deadbeef",+ );expect(isValid).toBe(false);});});@@ -164,7 +209,7 @@ describe("verifyApiKey", () => {});it("should reject hash with only prefix", async () => {- const isValid = await verifyApiKey("test-key", "scrypt$");+ const isValid = await verifyApiKey("test-key", "sha256$");expect(isValid).toBe(false);});diff --git a/apps/web/src/features/api-keys/api-key.ts b/apps/web/src/features/api-keys/api-key.tsindex b5d9e7645..13365cb67 100644--- a/apps/web/src/features/api-keys/api-key.ts+++ b/apps/web/src/features/api-keys/api-key.ts@@ -3,26 +3,6 @@ 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* @param bytes Number of random bytes to generate@@ -31,22 +11,22 @@ const SCRYPT_KEY_LENGTH = 64; // output length in bytesexport const randomToken = (bytes: number): string =>crypto.randomBytes(bytes).toString("base64url");+const sha256Hex = (value: string): string =>+ crypto.createHash("sha256").update(value).digest("hex");+/**- * Hash an API key using scrypt+ * Hash an API key for storage.+ *+ * API keys carry a 24-byte random secret (192 bits of entropy), so a fast+ * hash is sufficient — brute force is infeasible regardless of hash speed.+ * A slow KDF here would only add ~100ms of CPU to every API request.* @param rawKey Raw API key to hash- * @param salt Salt for hashing- * @returns Hex-encoded scrypt hash+ * @returns Stored hash in the format sha256$salt$hash*/-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");+export const hashApiKey = (rawKey: string): string => {+ const salt = randomToken(16);+ const hash = sha256Hex(`${salt}:${rawKey}`);+ return `sha256$${salt}$${hash}`;};/**@@ -62,14 +42,10 @@ export const createApiKey = async (): Promise<{const secret = randomToken(24);const apiKey = `sk_${prefix}_${secret}`;- const salt = randomToken(16);- const hash = await scryptHash(apiKey, salt);- const hashedKey = `scrypt$${SCRYPT_COST}$${SCRYPT_BLOCK_SIZE}$${SCRYPT_PARALLELIZATION}$${salt}$${hash}`;-return {apiKey,prefix,- hashedKey,+ hashedKey: hashApiKey(apiKey),};};@@ -88,9 +64,17 @@ export const extractApiKeyPrefix = (rawKey: string): string => {};/**- * Verify a raw API key against a stored scrypt hash+ * Check whether a stored hash uses the deprecated scrypt format and should+ * be re-hashed to sha256 on the next successful verification.+ */+export const isLegacyApiKeyHash = (storedHash: string): boolean =>+ storedHash.trim().startsWith("scrypt$");++/**+ * Verify a raw API key against a stored hash* @param rawKey Raw API key to verify- * @param storedHash Stored hash from database (format: scrypt$N$r$p$salt$hash)+ * @param storedHash Stored hash from database (sha256$salt$hash, or the+ * deprecated scrypt$N$r$p$salt$hash format)* @returns True if the key matches the hash*/export const verifyApiKey = async (@@ -99,78 +83,101 @@ export const verifyApiKey = async (): Promise<boolean> => {const trimmed = storedHash.trim();- // 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 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))- );+ if (trimmed.startsWith("sha256$")) {+ return verifySha256(rawKey, trimmed);}// ------------------------------------------------------------------- // DEPRECATED: Legacy SHA-256 format support (read-only)- // TODO: Remove this block once all existing API keys have been regenerated+ // DEPRECATED: scrypt format support (read-only)+ // Keys are lazily re-hashed to sha256 on successful verification; this+ // path only serves keys that haven't been used since the migration.// ------------------------------------------------------------------- if (trimmed.startsWith("sha256$")) {- return verifyLegacySha256(rawKey, trimmed);+ if (trimmed.startsWith("scrypt$")) {+ return verifyLegacyScrypt(rawKey, 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("$");+const verifySha256 = (rawKey: string, storedHash: string): boolean => {+ const parts = storedHash.split("$");+ if (parts.length !== 3) {+ return false;+ }+ const [, salt, hash] = parts;if (!salt || !hash || !isHexSha256(hash)) {return false;}const computed = sha256Hex(`${salt}:${rawKey}`);return crypto.timingSafeEqual(Buffer.from(computed), Buffer.from(hash));};++// ------------------------------------------------------------------+// DEPRECATED: scrypt verification (read-only)+// ------------------------------------------------------------------++const SCRYPT_KEY_LENGTH = 64;++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);+ });+ });+};++const verifyLegacyScrypt = async (+ rawKey: string,+ storedHash: string,+): Promise<boolean> => {+ const parts = storedHash.split("$");+ if (parts.length !== 6) {+ return false;+ }++ const [, nStr, rStr, pStr, salt, hash] = parts;+ if (!nStr || !rStr || !pStr || !salt || !hash) {+ return false;+ }++ 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))+ );+};