⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(auth): consume API key quota once per websocket handshake
Tin06491c00cb9e
diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 581850554..f5faa9378 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -797,15 +797,6 @@ export function createApp() {"/ws/user",upgradeWebSocket(async (c) => {assertWebSocketOrigin(c.req.raw.headers);- try {- await authenticateApiRequest(c);- } catch (error) {- if (error instanceof HTTPException) {- throw error;- }- console.error("API authentication failed:", error);- throw new HTTPException(500, { message: "Internal Server Error" });- }const userId = c.get("userId");let conn: ReturnType<typeof addUserConnection> | null = null;@@ -832,16 +823,6 @@ export function createApp() {assertWebSocketOrigin(c.req.raw.headers);const projectId = c.req.param("projectId");- try {- await authenticateApiRequest(c);- } catch (error) {- if (error instanceof HTTPException) {- throw error;- }- console.error("API authentication failed:", error);- throw new HTTPException(500, { message: "Internal Server Error" });- }-const userId = c.get("userId");let workspaceId: string | undefined;diff --git a/tests/api-integration/api-key-accounting.test.ts b/tests/api-integration/api-key-accounting.test.tsindex 6fc29297f..38cc95b57 100644--- a/tests/api-integration/api-key-accounting.test.ts+++ b/tests/api-integration/api-key-accounting.test.ts@@ -1,6 +1,7 @@import { createHash } from "node:crypto";import { eq } from "drizzle-orm";import { beforeEach, describe, expect, it } from "vite-plus/test";+import { auth } from "../../apps/api/src/auth";import db, { schema } from "../../apps/api/src/database";import { verifyApiKey } from "../../apps/api/src/utils/verify-api-key";import { resetTestDatabase } from "./helpers/database";@@ -84,3 +85,18 @@ it("charges an auth request once when the identity guard precedes Better Auth",.where(eq(schema.apikeyTable.id, row.id));expect(saved.remaining).toBe(0);});++it("creates normal API keys with the configured 100-per-minute limit", async () => {+ const { user } = await createWorkspaceMember();+ const created = await auth.api.createApiKey({+ body: { userId: user.id, name: "default limits" },+ });+ const [saved] = await db+ .select()+ .from(schema.apikeyTable)+ .where(eq(schema.apikeyTable.id, created.id));+ expect(saved.rateLimitMax).toBe(100);+ expect(saved.rateLimitTimeWindow).toBe(60_000);+ for (let i = 0; i < 11; i++)+ expect(await verifyApiKey(created.key)).not.toBeNull();+});diff --git a/tests/api-integration/websocket-security.test.ts b/tests/api-integration/websocket-security.test.tsindex 251116595..a0b4e70f7 100644--- a/tests/api-integration/websocket-security.test.ts+++ b/tests/api-integration/websocket-security.test.ts@@ -1,3 +1,6 @@+import { createHash } from "node:crypto";+import { eq } from "drizzle-orm";+import db, { schema } from "../../apps/api/src/database";import { once } from "node:events";import type { IncomingMessage } from "node:http";import { createRequire } from "node:module";@@ -105,6 +108,31 @@ afterEach(async () => {describe.each(["project", "user"])("%s WebSocket", (endpoint) => {const path = () => (endpoint === "user" ? "user" : projectId);+ it("consumes a single quota and rate-limit unit per API-key handshake", async () => {+ const key = `ws-key-${userId}`;+ const [row] = await db+ .insert(schema.apikeyTable)+ .values({+ referenceId: userId,+ userId,+ key: createHash("sha256").update(key).digest("base64url"),+ remaining: 1,+ rateLimitEnabled: true,+ rateLimitMax: 1,+ rateLimitTimeWindow: 60_000,+ createdAt: new Date(),+ updatedAt: new Date(),+ })+ .returning();+ expect((await connect(path(), { "x-api-key": key })).status).toBe(101);+ const [saved] = await db+ .select()+ .from(schema.apikeyTable)+ .where(eq(schema.apikeyTable.id, row.id));+ expect(saved.remaining).toBe(0);+ expect(saved.requestCount).toBe(1);+ expect((await connect(path(), { "x-api-key": key })).status).toBe(401);+ });it("rejects missing, null, hostile and lookalike browser origins", async () => {for (const origin of [undefined,