Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(api): add the error code to Better Auth rate limit responses

Andrejd790f8e36978
diff --git a/apps/api/src/errors/rate-limit-response.test.ts b/apps/api/src/errors/rate-limit-response.test.ts
new file mode 100644
index 000000000..b18915730
--- /dev/null
+++ b/apps/api/src/errors/rate-limit-response.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from "vite-plus/test";
+import { withJsonRateLimit } from "./rate-limit-response";
+
+describe("withJsonRateLimit", () => {
+ it("adds the code to a message-only 429 and keeps its headers", async () => {
+ const response = await withJsonRateLimit(
+ new Response(
+ JSON.stringify({
+ message: "Too many requests. Please try again later.",
+ }),
+ { status: 429, headers: { "X-Retry-After": "42" } },
+ ),
+ );
+
+ expect(response.status).toBe(429);
+ expect(response.headers.get("x-retry-after")).toBe("42");
+ expect(response.headers.get("content-type")).toContain("application/json");
+ expect(await response.json()).toEqual({
+ message: "Too many requests. Please try again later.",
+ code: "RATE_LIMITED",
+ });
+ });
+
+ it("uses a plain text body as the message", async () => {
+ const response = await withJsonRateLimit(
+ new Response("Slow down", { status: 429 }),
+ );
+
+ expect(await response.json()).toEqual({
+ message: "Slow down",
+ code: "RATE_LIMITED",
+ });
+ });
+
+ it("falls back to a default message for an empty 429", async () => {
+ const response = await withJsonRateLimit(
+ new Response(null, { status: 429 }),
+ );
+
+ expect(await response.json()).toEqual({
+ message: "Too many requests",
+ code: "RATE_LIMITED",
+ });
+ });
+
+ it("keeps a 429 that already has the standard shape", async () => {
+ const original = Response.json(
+ { message: "Rate limit exceeded", code: "RATE_LIMITED" },
+ { status: 429 },
+ );
+
+ expect(await withJsonRateLimit(original)).toBe(original);
+ });
+
+ it("keeps other responses", async () => {
+ const original = new Response(null, { status: 204 });
+
+ expect(await withJsonRateLimit(original)).toBe(original);
+ });
+});
diff --git a/apps/api/src/errors/rate-limit-response.ts b/apps/api/src/errors/rate-limit-response.ts
new file mode 100644
index 000000000..4f3e7f879
--- /dev/null
+++ b/apps/api/src/errors/rate-limit-response.ts
@@ -0,0 +1,34 @@
+import { errorCodeForStatus } from "./error-code";
+
+const FALLBACK_MESSAGE = "Too many requests";
+
+type Body = { message?: unknown; code?: unknown };
+
+function parseBody(text: string): Body | null {
+ try {
+ const value: unknown = JSON.parse(text);
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Body)
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+export async function withJsonRateLimit(response: Response): Promise<Response> {
+ if (response.status !== 429) return response;
+ const text = await response.clone().text();
+ const body = parseBody(text);
+ if (typeof body?.message === "string" && typeof body.code === "string") {
+ return response;
+ }
+ const message =
+ typeof body?.message === "string" ? body.message : body ? "" : text.trim();
+ const headers = new Headers(response.headers);
+ headers.delete("content-type");
+ headers.delete("content-length");
+ return Response.json(
+ { message: message || FALLBACK_MESSAGE, code: errorCodeForStatus(429) },
+ { status: 429, headers },
+ );
+}
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index df5b05f70..db9bd4ffb 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -33,6 +33,7 @@ import {
notFoundResponse,
withJsonNotFound,
} from "./errors/not-found-response";
+import { withJsonRateLimit } from "./errors/rate-limit-response";
import {
validationHook,
validationHookWithMessage,
@@ -480,7 +481,7 @@ export function createApp() {
429: apiKeyRateLimited.ref,
},
}),
- async (c) => auth.handler(c.req.raw),
+ async (c) => withJsonRateLimit(await auth.handler(c.req.raw)),
);
api.openapi(
@@ -737,7 +738,7 @@ export function createApp() {
}
return c.redirect(deviceUrl.toString(), 302);
}
- return auth.handler(c.req.raw);
+ return withJsonRateLimit(await auth.handler(c.req.raw));
},
);
@@ -753,8 +754,10 @@ export function createApp() {
// Preserve Better Auth bearer session tokens on auth routes.
if (session?.session && session.user) {
- return withJsonNotFound(
- await auth.handler(new Request(c.req.raw, { headers })),
+ return withJsonRateLimit(
+ await withJsonNotFound(
+ await auth.handler(new Request(c.req.raw, { headers })),
+ ),
);
}
@@ -764,8 +767,10 @@ export function createApp() {
// Better Auth API key plugin validates from x-api-key by default.
headers.set("x-api-key", bearerToken);
- const response = await withJsonNotFound(
- await auth.handler(new Request(c.req.raw, { headers })),
+ const response = await withJsonRateLimit(
+ await withJsonNotFound(
+ await auth.handler(new Request(c.req.raw, { headers })),
+ ),
);
c.set(
"apiKeyHeaders",
@@ -778,7 +783,9 @@ export function createApp() {
return response;
}
- return withJsonNotFound(await auth.handler(c.req.raw));
+ return withJsonRateLimit(
+ await withJsonNotFound(await auth.handler(c.req.raw)),
+ );
});
api.route("/", mcpRoutes);
diff --git a/tests/api-integration/api-key-rate-limit.test.ts b/tests/api-integration/api-key-rate-limit.test.ts
index dc2452ba3..c5ce196d2 100644
--- a/tests/api-integration/api-key-rate-limit.test.ts
+++ b/tests/api-integration/api-key-rate-limit.test.ts
@@ -265,6 +265,10 @@ describe("API key rate limits", () => {
reset: null,
retryAfter: "42",
});
+ expect(await response.json()).toEqual({
+ message: "Too many requests. Please try again later.",
+ code: "RATE_LIMITED",
+ });
expect(response.headers.get("cache-control")).toBe("private");
expect((await savedKey(row.id)).requestCount).toBe(0);
},