⚡ 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
Merge remote-tracking branch 'origin/main' into fix/api-key-rate-limit-429
Andrejacf30893cd74
diff --cc apps/api/src/index.tsindex fd8ca679e,554f4df60..df5b05f70--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@@ -239,39 -250,8 +260,43 @@@ export function createApp()// JSON with repeated keys compresses extremely well.app.use(compress());- const api = new OpenAPIHono<ApiVariables>();+ const api = new OpenAPIHono<ApiVariables>({ defaultHook: validationHook });+ api.use("*", applyApiKeyHeaders);++ const apiKeyRateLimited = api.openAPIRegistry.registerComponent(+ "responses",+ "ApiKeyRateLimited",+ {+ description:+ "The API key exceeded its rate limit or usage quota. Wait the number of seconds in Retry-After before retrying. The X-RateLimit headers are sent only when the rate limit was hit.",+ headers: {+ "Retry-After": {+ description:+ "Seconds to wait before retrying. Omitted when an exhausted usage quota never refills.",+ schema: { type: "integer" },+ },+ "X-RateLimit-Limit": {+ description: "Requests the API key may make per window.",+ schema: { type: "integer" },+ },+ "X-RateLimit-Remaining": {+ description: "Requests left in the current window.",+ schema: { type: "integer" },+ },+ "X-RateLimit-Reset": {+ description: "Unix time in seconds when the current window resets.",+ schema: { type: "integer" },+ },+ },- content: { "text/plain": { schema: { type: "string" } } },++ content: {++ "application/json": {++ schema: { $ref: "#/components/schemas/ApiError" },++ },++ },+ },+ );+api.get("/health", (c) => {return c.json({ status: "ok" });});@@@ -490,9 -449,8 +500,9 @@@content: { "*/*": { schema: { type: "string", format: "binary" } } },},304: { description: "Not modified" },- 403: { description: "No access to this asset" },- 404: { description: "Asset not found" },+ 403: errorResponse("No access to this asset"),+ 404: errorResponse("Asset not found"),+ 429: apiKeyRateLimited.ref,},}),async (c) => {@@@ -666,8 -625,12 +677,13 @@@}operation.responses["401"] ??= {description: "Missing or invalid credentials",+ content: {+ "application/json": {+ schema: { $ref: "#/components/schemas/ApiError" },+ },+ },};+ operation.responses["429"] ??= apiKeyRateLimited.ref;}}@@@ -737,28 -699,24 +753,32 @@@// Preserve Better Auth bearer session tokens on auth routes.if (session?.session && session.user) {- return auth.handler(new Request(c.req.raw, { headers }));+ return withJsonNotFound(+ await auth.handler(new Request(c.req.raw, { headers })),+ );}- if (!(await verifyApiKey(bearerToken, { consume: false }))) {- throw new HTTPException(401, { message: "Unauthorized" });- }+ const apiKeyResult = await verifyApiKey(bearerToken, { consume: false });+ if (apiKeyResult?.status !== "valid") throw apiKeyRejection(apiKeyResult);// Better Auth API key plugin validates from x-api-key by default.headers.set("x-api-key", bearerToken);- const response = await auth.handler(new Request(c.req.raw, { headers }));- return withJsonNotFound(++ const response = await withJsonNotFound(+ await auth.handler(new Request(c.req.raw, { headers })),+ );+ c.set(+ "apiKeyHeaders",+ await apiKeyResponseHeaders(+ await readApiKeyCheck(bearerToken),+ response,+ new Date(),+ ),+ );+ return response;}- return auth.handler(c.req.raw);+ return withJsonNotFound(await auth.handler(c.req.raw));});api.route("/", mcpRoutes);diff --cc apps/api/src/utils/api-key-rejection.test.tsindex c45e47ebd,000000000..32f7c949emode 100644,000000..100644--- a/apps/api/src/utils/api-key-rejection.test.ts+++ b/apps/api/src/utils/api-key-rejection.test.ts@@@ -1,59 -1,0 +1,58 @@@+import { describe, expect, it } from "vite-plus/test";- import { betterAuthLimitRejection } from "./api-key-rejection";++import { httpExceptionResponse } from "../errors/http-exception-response";++import { apiKeyRejection } from "./api-key-rejection";++const now = new Date("2026-01-01T00:00:00.000Z");- const rateLimitedBody = {- code: "RATE_LIMITED",- details: { tryAgainIn: 4_500 },- };+- function headersOf(error: ReturnType<typeof betterAuthLimitRejection>) {- return Object.fromEntries(error.getResponse().headers);- }++describe("apiKeyRejection", () => {++ it("answers 401 for an unknown key", async () => {++ const response = await httpExceptionResponse(apiKeyRejection(null, now));+- describe("betterAuthLimitRejection", () => {- it("answers with the key's own retry headers when the key is denied", () => {++ expect(response.status).toBe(401);++ expect(await response.json()).toEqual({++ message: "Unauthorized",++ code: "UNAUTHORIZED",++ });++ });++++ it("answers a rate limited key with JSON and the key's retry headers", async () => {+ const resetAt = new Date(now.getTime() + 30_000);- const error = betterAuthLimitRejection(- rateLimitedBody,- { status: "rate_limited", limit: 10, resetAt },- now,++ const response = await httpExceptionResponse(++ apiKeyRejection({ status: "rate_limited", limit: 10, resetAt }, now),+ );+- expect(error.status).toBe(429);- expect(headersOf(error)).toMatchObject({++ expect(response.status).toBe(429);++ expect(Object.fromEntries(response.headers)).toMatchObject({++ "content-type": expect.stringContaining("application/json"),+ "retry-after": "30",+ "x-ratelimit-limit": "10",+ "x-ratelimit-remaining": "0",+ "x-ratelimit-reset": String(Math.ceil(resetAt.getTime() / 1000)),+ });++ expect(await response.json()).toEqual({++ message: "Rate limit exceeded",++ code: "RATE_LIMITED",++ });+ });++ it("uses the refill time for an exhausted quota", async () => {- const error = betterAuthLimitRejection(- { code: "USAGE_EXCEEDED" },- {- status: "usage_exceeded",- retryAt: new Date(now.getTime() + 120_000),- rateLimit: null,- },- now,++ const response = await httpExceptionResponse(++ apiKeyRejection(++ {++ status: "usage_exceeded",++ retryAt: new Date(now.getTime() + 120_000),++ rateLimit: null,++ },++ now,++ ),+ );+- expect(headersOf(error)).toMatchObject({ "retry-after": "120" });- expect(await error.getResponse().text()).toBe(- "API key usage limit exceeded",- );- });-- it("falls back to Better Auth's wait when the key cannot be checked", () => {- for (const check of [null, { status: "valid" as const, rateLimit: null }]) {- const error = betterAuthLimitRejection(rateLimitedBody, check, now);- expect(error.status).toBe(429);- expect(headersOf(error)).toEqual({- "content-type": "text/plain;charset=UTF-8",- "retry-after": "5",- });- }++ expect(response.status).toBe(429);++ expect(response.headers.get("retry-after")).toBe("120");++ expect(response.headers.get("x-ratelimit-limit")).toBeNull();++ expect(await response.json()).toEqual({++ message: "API key usage limit exceeded",++ code: "RATE_LIMITED",++ });+ });+});diff --cc apps/api/src/utils/api-key-rejection.tsindex 7a05ce530,000000000..df96b0cdcmode 100644,000000..100644--- a/apps/api/src/utils/api-key-rejection.ts+++ b/apps/api/src/utils/api-key-rejection.ts@@@ -1,43 -1,0 +1,17 @@@+import { HTTPException } from "hono/http-exception";- import {- type ApiKeyCheck,- type ApiKeyDenial,- apiKeyDenialHeaders,- retryAfterFromBody,- } from "./rate-limit-headers";-- function tooManyRequests(message: string, headers: Record<string, string>) {- return new HTTPException(429, {- message,- res: new Response(message, { status: 429, headers }),- });- }++import { type ApiKeyDenial, apiKeyDenialHeaders } from "./rate-limit-headers";++export function apiKeyRejection(denial: ApiKeyDenial | null, now = new Date()) {+ if (!denial) return new HTTPException(401, { message: "Unauthorized" });- return tooManyRequests(++ const message =+ denial.status === "rate_limited"+ ? "Rate limit exceeded"- : "API key usage limit exceeded",- apiKeyDenialHeaders(denial, now),- );- }-- export function betterAuthLimitRejection(- body: unknown,- check: ApiKeyCheck | null,- now = new Date(),- ) {- if (check && check.status !== "valid") return apiKeyRejection(check, now);- const { code } = (body ?? {}) as { code?: unknown };- if (code === "USAGE_EXCEEDED")- return apiKeyRejection(- { status: "usage_exceeded", retryAt: null, rateLimit: null },- now,- );- const retryAfter = retryAfterFromBody(body, now);- return tooManyRequests(- "Rate limit exceeded",- retryAfter ? { "Retry-After": retryAfter } : {},- );++ : "API key usage limit exceeded";++ return new HTTPException(429, {++ message,++ res: new Response(message, {++ status: 429,++ headers: apiKeyDenialHeaders(denial, now),++ }),++ });+}diff --cc apps/api/src/utils/authenticate-api-request.tsindex 54a0ad23f,d20715181..4c0310adf--- a/apps/api/src/utils/authenticate-api-request.ts+++ b/apps/api/src/utils/authenticate-api-request.ts@@@ -2,10 -2,8 +2,10 @@@ import * as Sentry from "@sentry/node"import { APIError } from "better-auth/api";import type { Context } from "hono";import { HTTPException } from "hono/http-exception";- import { auth } from "../auth";- import { apiKeyRejection, betterAuthLimitRejection } from "./api-key-rejection";++import { apiKeyRejection } from "./api-key-rejection";+ import { getUserSession } from "./get-user-session";+import { type ApiKeyRateLimit, rateLimitHeaders } from "./rate-limit-headers";- import { readApiKeyCheck, verifyApiKey } from "./verify-api-key";+ import { verifyApiKey } from "./verify-api-key";// User is tagged on Sentry's isolation scope; the per-request isolation// scope is forked by Sentry.withIsolationScope in the api.use("*", ...)diff --cc apps/docs/api-reference/authentication.mdxindex e4851772e,422a8e938..b6873f529--- a/apps/docs/api-reference/authentication.mdx+++ b/apps/docs/api-reference/authentication.mdx@@@ -38,26 -38,6 +38,26 @@@ const board = await response.json()Return to **API Keys** to remove a credential you no longer use. To rotate one, create a replacement, update the service that uses it, check a request succeeds, then revoke the old key.+## Rate limits++Each API key can make 100 requests per 60 seconds by default. Requests made with a browser session or a device access token do not count against it.++The window follows the key's most recent successful request. Every successful request starts the 60 seconds again, and the count resets only after a full window passes without a successful request. A steady stream of requests, even one per second, keeps the window open, so the key is limited after 100 requests until it has been idle for 60 seconds.++Successful requests made with an API key include these headers:++| Header | Meaning |+| --- | --- |+| `X-RateLimit-Limit` | Requests the key can make per window. |+| `X-RateLimit-Remaining` | Requests left in the current window. |+| `X-RateLimit-Reset` | Unix time in seconds when the window resets if the key makes no further requests. |+- When a key goes over its limit, Kaneo answers `429 Too Many Requests` with the same headers, `X-RateLimit-Remaining: 0`, and a `Retry-After` header with the number of seconds to wait. Wait at least that long before you retry, and pace bulk jobs rather than retrying in a loop. A `429` does not mean the key is invalid. An unknown, disabled, or expired key still gets `401 Unauthorized`.++When a key goes over its limit, Kaneo answers `429 Too Many Requests` with the error code `RATE_LIMITED`, the same headers, `X-RateLimit-Remaining: 0`, and a `Retry-After` header with the number of seconds to wait. Wait at least that long before you retry, and pace bulk jobs rather than retrying in a loop. A `429` does not mean the key is invalid. An unknown, disabled, or expired key still gets `401` with `UNAUTHORIZED`.+- A key with a usage quota also gets `429` once the quota runs out, with the message `API key usage limit exceeded`. `Retry-After` is included when the quota refills at a known time.++A key with a usage quota also gets `429` with `RATE_LIMITED` once the quota runs out, with the message `API key usage limit exceeded`. `Retry-After` is included when the quota refills at a known time.++Auth endpoints under `/api/auth` can also have their own per-IP limits, for example on sign-up and invitations. Those `429` responses include `Retry-After` but no `X-RateLimit` headers, because the request did not count against the key.+## Device authorizationBy default, self-hosted Kaneo allows the built-in device clients `kaneo-cli` and `kaneo-mcp`.diff --cc apps/docs/openapi.jsonindex 550dd2cb6,37e0e8212..13e3f5b1d--- a/apps/docs/openapi.json+++ b/apps/docs/openapi.json@@@ -17,44 -17,6 +17,44 @@@}],"components": {+ "responses": {+ "ApiKeyRateLimited": {+ "description": "The API key exceeded its rate limit or usage quota. Wait the number of seconds in Retry-After before retrying. The X-RateLimit headers are sent only when the rate limit was hit.",+ "headers": {+ "Retry-After": {+ "description": "Seconds to wait before retrying. Omitted when an exhausted usage quota never refills.",+ "schema": {+ "type": "integer"+ }+ },+ "X-RateLimit-Limit": {+ "description": "Requests the API key may make per window.",+ "schema": {+ "type": "integer"+ }+ },+ "X-RateLimit-Remaining": {+ "description": "Requests left in the current window.",+ "schema": {+ "type": "integer"+ }+ },+ "X-RateLimit-Reset": {+ "description": "Unix time in seconds when the current window resets.",+ "schema": {+ "type": "integer"+ }+ }+ },+ "content": {- "text/plain": {++ "application/json": {+ "schema": {- "type": "string"++ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ }+ },"securitySchemes": {"bearerAuth": {"type": "http",@@@ -5288,13 -5265,24 +5306,27 @@@"description": "Not modified"},"403": {- "description": "No access to this asset"+ "description": "No access to this asset",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }},"404": {- "description": "Asset not found"+ "description": "Asset not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -5411,10 -5406,14 +5450,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -5491,10 -5490,14 +5537,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -5531,10 -5534,14 +5584,17 @@@"description": "Success"},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -5571,10 -5578,14 +5631,17 @@@"description": "Success"},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -5647,10 -5658,14 +5714,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -5705,10 -5720,14 +5779,17 @@@"description": "Success"},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -5785,10 -5804,14 +5866,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -5832,10 -5855,14 +5920,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -5900,10 -5927,14 +5995,17 @@@"description": "Success"},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -5948,10 -5979,14 +6050,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -5969,10 -6004,14 +6078,17 @@@"description": "Success"},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -5995,10 -6034,14 +6111,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -6094,10 -6137,14 +6217,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -6115,10 -6162,14 +6245,17 @@@"description": "Success"},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -6179,10 -6230,14 +6316,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -6330,11 -6385,15 +6474,18 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }},+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"+ },"502": {"description": "Invitation saved, but email delivery failed","content": {@@@ -6395,10 -6454,14 +6546,17 @@@"description": "Success"},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -6424,10 -6487,14 +6582,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -6518,10 -6585,14 +6683,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -6539,10 -6610,14 +6711,17 @@@"description": "Success"},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -6560,10 -6635,14 +6739,17 @@@"description": "Success"},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -6615,10 -6694,14 +6801,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -6675,10 -6758,14 +6868,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -6754,10 -6841,14 +6954,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -6783,10 -6874,14 +6990,17 @@@}},"401": {- "description": "Missing or invalid credentials"- },- "429": {- "$ref": "#/components/responses/ApiKeyRateLimited"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }++ },++ "429": {++ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -6843,10 -6938,14 +7057,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -6922,10 -7021,14 +7143,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -6985,10 -7088,14 +7213,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -7053,10 -7160,14 +7288,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -7102,10 -7213,14 +7344,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -7147,10 -7262,14 +7396,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -7223,10 -7342,14 +7479,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -7317,10 -7440,14 +7580,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -7405,10 -7532,14 +7675,17 @@@"description": "Success"},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -7502,10 -7633,14 +7779,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -7903,10 -8032,14 +8187,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -13791,10 -14151,14 +14510,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}},@@@ -13883,10 -14247,14 +14609,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -13972,10 -14344,14 +14712,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -14013,10 -14389,14 +14760,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -14041,10 -14421,14 +14795,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}},@@@ -14161,10 -14545,14 +14922,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -15265,10 -15685,14 +16089,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -19481,10 -20073,14 +20627,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -19519,10 -20115,14 +20672,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}@@@ -20545,10 -21194,14 +21796,17 @@@}},"401": {- "description": "Missing or invalid credentials"+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"}}}diff --cc tests/api-integration/api-key-mixed-credentials.test.tsindex 000000000,b689f96a8..d384abaa6mode 000000,100644..100644--- a/tests/api-integration/api-key-mixed-credentials.test.ts+++ b/tests/api-integration/api-key-mixed-credentials.test.ts@@@ -1,0 -1,157 +1,161 @@@+ import { createHash, randomUUID } from "node:crypto";+ import { eq } from "drizzle-orm";+ import { beforeEach, describe, expect, it, vi } from "vite-plus/test";+ import { auth } from "../../apps/api/src/auth";+ import db, { schema } from "../../apps/api/src/database";+ import { createApp } from "../../apps/api/src/index";+ import {+ createAuthorizationRequest,+ registerClient,+ } from "../../apps/api/src/mcp/oauth";+ import { resetTestDatabase } from "./helpers/database";++import { readErrorBody } from "./helpers/error-body";+ import {+ createProjectFixture,+ createWorkspaceMember,+ } from "./helpers/fixtures";++ vi.mock("../../apps/api/src/storage/s3", async (importOriginal) => ({+ ...(await importOriginal<object>()),+ getPrivateObject: async () => ({+ body: new Uint8Array([1, 2, 3]),+ contentType: "image/png",+ contentLength: 3,+ }),+ }));++ const invalidBearer = { Authorization: "Bearer not-a-real-token" };++ async function createKey(+ userId: string,+ permissions?: Record<string, string[]>,+ ) {+ const { key } = await auth.api.createApiKey({+ body: { userId, name: "Mixed credentials test", permissions },+ });+ return key;+ }++ describe("API integration: API key sent with an invalid bearer token", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ });++ it("does not turn an administrator API key into a session", async () => {+ const { user } = await createWorkspaceMember();+ await db+ .update(schema.userTable)+ .set({ role: "admin" })+ .where(eq(schema.userTable.id, user.id));+ const key = await createKey(user.id);+ const { app } = createApp();++ const keyOnly = await app.request("/api/admin/users", {+ headers: { "x-api-key": key },+ });+ expect(keyOnly.status).toBe(403);++ const mixed = await app.request("/api/admin/users", {+ headers: { "x-api-key": key, ...invalidBearer },+ });+ expect(mixed.status).toBe(401);+ });++ it("keeps the API key scope", async () => {+ const { user, workspace } = await createWorkspaceMember({ role: "owner" });+ const key = await createKey(user.id, { project: ["read"] });+ const { app } = createApp();+ const createProject = (headers: Record<string, string>) =>+ app.request("/api/project", {+ method: "POST",+ headers: { "content-type": "application/json", ...headers },+ body: JSON.stringify({+ name: "Scoped",+ workspaceId: workspace.id,+ icon: "Layout",+ slug: "SCP",+ }),+ });++ const keyOnly = await createProject({ "x-api-key": key });+ expect(keyOnly.status).toBe(403);- expect(await keyOnly.text()).toBe("Insufficient API key scope");++ expect(await readErrorBody(keyOnly)).toMatchObject({++ message: "Insufficient API key scope",++ code: "API_KEY_SCOPE",++ });++ const mixed = await createProject({ "x-api-key": key, ...invalidBearer });+ expect(mixed.status).toBe(401);+ expect(+ await db+ .select()+ .from(schema.projectTable)+ .where(eq(schema.projectTable.workspaceId, workspace.id)),+ ).toHaveLength(0);+ });++ it("rejects private asset downloads", async () => {+ const { user, workspace } = await createWorkspaceMember();+ const { project } = await createProjectFixture({+ workspaceId: workspace.id,+ });+ const [asset] = await db+ .insert(schema.assetTable)+ .values({+ workspaceId: workspace.id,+ projectId: project.id,+ objectKey: randomUUID(),+ filename: "image.png",+ mimeType: "image/png",+ size: 3,+ surface: "comment",+ createdBy: user.id,+ })+ .returning();+ const key = await createKey(user.id);+ const { app } = createApp();++ const keyOnly = await app.request(`/api/asset/${asset.id}`, {+ headers: { "x-api-key": key },+ });+ expect(keyOnly.status).toBe(200);++ const mixed = await app.request(`/api/asset/${asset.id}`, {+ headers: { "x-api-key": key, ...invalidBearer },+ });+ expect(mixed.status).toBe(401);+ });+ });++ describe("API integration: MCP consent with an API key", () => {+ beforeEach(async () => {+ await resetTestDatabase();+ });++ it("requires a user session to approve an authorization request", async () => {+ const { user } = await createWorkspaceMember();+ const key = await createKey(user.id, { project: ["read"] });+ const redirectUri = "https://client.example/callback";+ const client = await registerClient({ redirectUris: [redirectUri] });+ const id = await createAuthorizationRequest({+ clientId: client.clientId,+ codeChallenge: createHash("sha256")+ .update("test-verifier")+ .digest("base64url"),+ redirectUri,+ });+ const { app } = createApp();++ const response = await app.request(`/api/mcp/authorize/request/${id}`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ origin: "http://localhost:5173",+ "x-api-key": key,+ },+ body: JSON.stringify({ approved: true }),+ });++ expect(response.status).toBe(401);+ });+ });diff --cc tests/api-integration/api-key-rate-limit.test.tsindex c1ae31c3c,000000000..dc2452ba3mode 100644,000000..100644--- a/tests/api-integration/api-key-rate-limit.test.ts+++ b/tests/api-integration/api-key-rate-limit.test.ts@@@ -1,444 -1,0 +1,417 @@@+import { createHash, randomUUID } from "node:crypto";+import { eq } from "drizzle-orm";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { auth } from "../../apps/api/src/auth";+import db, { getDatabase, schema } from "../../apps/api/src/database";+import { createApp } from "../../apps/api/src/index";+import { signUpWithSession } from "./helpers/auth-session";+import { resetTestDatabase } from "./helpers/database";++import { readErrorBody } from "./helpers/error-body";+import { createWorkspaceMember } from "./helpers/fixtures";++const LIMIT = 3;+const WINDOW = 60_000;++beforeEach(resetTestDatabase);++async function seedKey(+ overrides: Partial<typeof schema.apikeyTable.$inferInsert> = {},+) {+ const { user, workspace } = await createWorkspaceMember();+ const key = `rate-limit-test-${user.id}`.padEnd(64, "x");+ const [row] = await db+ .insert(schema.apikeyTable)+ .values({+ referenceId: user.id,+ userId: user.id,+ key: createHash("sha256").update(key).digest("base64url"),+ createdAt: new Date(),+ updatedAt: new Date(),+ rateLimitEnabled: true,+ rateLimitMax: LIMIT,+ rateLimitTimeWindow: WINDOW,+ ...overrides,+ })+ .returning();+ return { key, row, workspace };+}++async function fillWindow(id: string, lastRequest: Date) {+ await db+ .update(schema.apikeyTable)+ .set({ requestCount: LIMIT, lastRequest })+ .where(eq(schema.apikeyTable.id, id));+}++async function savedKey(id: string) {+ const [row] = await db+ .select()+ .from(schema.apikeyTable)+ .where(eq(schema.apikeyTable.id, id));+ return row;+}++function limitHeaders(response: Response) {+ return {+ limit: response.headers.get("x-ratelimit-limit"),+ remaining: response.headers.get("x-ratelimit-remaining"),+ reset: response.headers.get("x-ratelimit-reset"),+ retryAfter: response.headers.get("retry-after"),+ };+}+++const rateLimited = { message: "Rate limit exceeded", code: "RATE_LIMITED" };++const usageExceeded = {++ message: "API key usage limit exceeded",++ code: "RATE_LIMITED",++};+++function epochSeconds(date: Date) {+ return String(Math.ceil(date.getTime() / 1000));+}++describe("API key rate limits", () => {+ it("reports the window on every successful key request", async () => {+ const { key } = await seedKey();+ const { app } = createApp();++ const before = Date.now();+ const first = await app.request("/api/user/me", {+ headers: { "x-api-key": key },+ });+ const after = Date.now();++ expect(first.status).toBe(200);+ expect(first.headers.get("cache-control")).toBe("private");+ const headers = limitHeaders(first);+ expect(headers).toMatchObject({+ limit: String(LIMIT),+ remaining: String(LIMIT - 1),+ retryAfter: null,+ });+ expect(Number(headers.reset)).toBeGreaterThanOrEqual(+ Math.ceil((before + WINDOW) / 1000),+ );+ expect(Number(headers.reset)).toBeLessThanOrEqual(+ Math.ceil((after + WINDOW) / 1000),+ );++ const second = await app.request("/api/user/me", {+ headers: { Authorization: `Bearer ${key}` },+ });+ expect(second.status).toBe(200);+ expect(limitHeaders(second).remaining).toBe(String(LIMIT - 2));+ });++ it.each([+ ["x-api-key", (key: string) => ({ "x-api-key": key })],+ ["a Bearer key", (key: string) => ({ Authorization: `Bearer ${key}` })],+ ])("answers 429 with retry headers via %s", async (_, headersFor) => {+ const { key, row } = await seedKey();+ const lastRequest = new Date(Date.now() - 45_000);+ await fillWindow(row.id, lastRequest);+ const { app } = createApp();++ const response = await app.request("/api/user/me", {+ headers: headersFor(key),+ });++ expect(response.status).toBe(429);- expect(await response.text()).toContain("Rate limit exceeded");++ expect(await readErrorBody(response)).toEqual(rateLimited);+ const headers = limitHeaders(response);+ expect(headers).toMatchObject({+ limit: String(LIMIT),+ remaining: "0",+ reset: epochSeconds(new Date(lastRequest.getTime() + WINDOW)),+ });+ expect(Number(headers.retryAfter)).toBeGreaterThanOrEqual(14);+ expect(Number(headers.retryAfter)).toBeLessThanOrEqual(15);++ const saved = await savedKey(row.id);+ expect(saved.requestCount).toBe(LIMIT);+ expect(saved.lastRequest?.getTime()).toBe(lastRequest.getTime());+ });++ it("answers 429 on Better Auth routes", async () => {+ const { key, row } = await seedKey();+ const { app } = createApp();++ const allowed = await app.request("/api/auth/get-session", {+ headers: { "x-api-key": key },+ });+ expect(allowed.status).toBe(200);+ expect(await allowed.json()).toMatchObject({+ user: { id: row.referenceId },+ });+ expect(limitHeaders(allowed)).toMatchObject({+ limit: String(LIMIT),+ remaining: String(LIMIT - 1),+ });++ await fillWindow(row.id, new Date());++ const limited = await app.request("/api/auth/get-session", {+ headers: { "x-api-key": key },+ });+ expect(limited.status).toBe(429);- expect(await limited.text()).toContain("Rate limit exceeded");++ expect(await readErrorBody(limited)).toEqual(rateLimited);+ expect(limitHeaders(limited)).toMatchObject({+ limit: String(LIMIT),+ remaining: "0",+ });+ expect(Number(limitHeaders(limited).retryAfter)).toBeGreaterThanOrEqual(59);++ const bearer = await app.request("/api/auth/organization/list", {+ headers: { Authorization: `Bearer ${key}` },+ });+ expect(bearer.status).toBe(429);- expect(await bearer.text()).toContain("Rate limit exceeded");++ expect(await readErrorBody(bearer)).toEqual(rateLimited);+ expect(limitHeaders(bearer).remaining).toBe("0");+ expect(limitHeaders(bearer).retryAfter).not.toBeNull();+ });+- it("answers 429 when Better Auth rejects a rate limited key", async () => {- const { key, row } = await seedKey();- await fillWindow(row.id, new Date());- const { app } = createApp();-- const response = await app.request("/api/user/me", {- headers: { Authorization: "Bearer not-a-real-key", "x-api-key": key },- });-- expect(response.status).toBe(429);- expect(await response.text()).toContain("Rate limit exceeded");- const headers = limitHeaders(response);- expect(headers).toMatchObject({- limit: String(LIMIT),- remaining: "0",- reset: expect.stringMatching(/^\d+$/),- });- expect(Number(headers.retryAfter)).toBeGreaterThanOrEqual(59);- });-- it("answers 429 with the refill time when Better Auth rejects an exhausted key", async () => {- const { key } = await seedKey({- remaining: 0,- refillAmount: 5,- refillInterval: 3_600_000,- lastRefillAt: new Date(Date.now() - 600_000),- });- const { app } = createApp();-- const response = await app.request("/api/user/me", {- headers: { Authorization: "Bearer not-a-real-key", "x-api-key": key },- });-- expect(response.status).toBe(429);- expect(await response.text()).toContain("API key usage limit exceeded");- const retryAfter = Number(limitHeaders(response).retryAfter);- expect(retryAfter).toBeGreaterThanOrEqual(2_999);- expect(retryAfter).toBeLessThanOrEqual(3_000);- });-+ it.each([+ [+ "x-api-key",+ "/api/auth/get-session",+ (key: string) => ({ "x-api-key": key }),+ ],+ [+ "a Bearer key",+ "/api/auth/organization/list",+ (key: string) => ({ Authorization: `Bearer ${key}` }),+ ],+ ])(+ "reports the window on an auth request that spends the last quota unit via %s",+ async (_, path, headersFor) => {+ const { key, row } = await seedKey({ remaining: 1 });+ const { app } = createApp();++ const response = await app.request(path, { headers: headersFor(key) });++ expect(response.status).toBe(200);+ expect(limitHeaders(response)).toMatchObject({+ limit: String(LIMIT),+ remaining: String(LIMIT - 1),+ retryAfter: null,+ });+ expect((await savedKey(row.id)).remaining).toBe(0);+ },+ );++ it.each([+ [+ "x-api-key",+ "/api/auth/get-session",+ (key: string) => ({ "x-api-key": key }),+ ],+ [+ "a Bearer key",+ "/api/auth/organization/list",+ (key: string) => ({ Authorization: `Bearer ${key}` }),+ ],+ ])(+ "adds retry headers when the window fills before Better Auth checks a key via %s",+ async (_, path, headersFor) => {+ const { key, row } = await seedKey();+ const handler = auth.handler;+ vi.spyOn(auth, "handler").mockImplementationOnce(async (request) => {+ await fillWindow(row.id, new Date());+ return handler(request);+ });+ const { app } = createApp();++ const response = await app.request(path, { headers: headersFor(key) });++ expect(response.status).toBe(429);+ const headers = limitHeaders(response);+ expect(headers).toMatchObject({ limit: String(LIMIT), remaining: "0" });+ expect(Number(headers.retryAfter)).toBeGreaterThanOrEqual(59);+ expect(Number(headers.retryAfter)).toBeLessThanOrEqual(60);+ },+ );++ it.each([+ [+ "x-api-key",+ "/api/auth/get-session",+ (key: string) => ({ "x-api-key": key }),+ ],+ [+ "a Bearer key",+ "/api/auth/organization/list",+ (key: string) => ({ Authorization: `Bearer ${key}` }),+ ],+ ])(+ "answers Better Auth's own 429 with its Retry-After and no key window via %s",+ async (_, path, headersFor) => {+ const { key, row } = await seedKey();+ vi.spyOn(auth, "handler").mockResolvedValueOnce(+ new Response(+ JSON.stringify({+ message: "Too many requests. Please try again later.",+ }),+ { status: 429, headers: { "X-Retry-After": "42" } },+ ),+ );+ const { app } = createApp();++ const response = await app.request(path, { headers: headersFor(key) });++ expect(response.status).toBe(429);+ expect(limitHeaders(response)).toEqual({+ limit: null,+ remaining: null,+ reset: null,+ retryAfter: "42",+ });+ expect(response.headers.get("cache-control")).toBe("private");+ expect((await savedKey(row.id)).requestCount).toBe(0);+ },+ );++ it("still answers when the rate limit headers cannot be read", async () => {+ const { key, row } = await seedKey();+ const handler = auth.handler;+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});+ vi.spyOn(auth, "handler").mockImplementationOnce(async (request) => {+ const response = await handler(request);+ vi.spyOn(getDatabase(), "select").mockImplementationOnce(() => {+ throw new Error("database unavailable");+ });+ return response;+ });+ const { app } = createApp();++ const response = await app.request("/api/auth/get-session", {+ headers: { "x-api-key": key },+ });++ expect(response.status).toBe(200);+ expect(await response.json()).toMatchObject({+ user: { id: row.referenceId },+ });+ expect(limitHeaders(response).limit).toBeNull();+ expect(errors).toHaveBeenCalledWith(+ "Failed to read API key usage:",+ expect.any(Error),+ );+ });++ it("lets the key through again after a full window", async () => {+ const { key, row } = await seedKey();+ await fillWindow(row.id, new Date(Date.now() - WINDOW - 1_000));+ const { app } = createApp();++ const response = await app.request("/api/user/me", {+ headers: { "x-api-key": key },+ });++ expect(response.status).toBe(200);+ expect(limitHeaders(response).remaining).toBe(String(LIMIT - 1));+ });++ it.each([+ ["x-api-key", { "x-api-key": "not-a-real-key" }],+ ["Bearer", { Authorization: "Bearer not-a-real-key" }],+ ])("keeps answering 401 for an unknown key in %s", async (_, headers) => {+ const { app } = createApp();++ const response = await app.request("/api/user/me", { headers });++ expect(response.status).toBe(401);- expect(await response.text()).toBe("Unauthorized");++ expect(await readErrorBody(response)).toEqual({++ message: "Unauthorized",++ code: "UNAUTHORIZED",++ });+ expect(limitHeaders(response)).toMatchObject({+ limit: null,+ retryAfter: null,+ });+ });++ it("sends no rate limit headers on session requests", async () => {+ const { app } = createApp();+ const { cookies } = await signUpWithSession(app, {+ email: `${randomUUID()}@example.com`,+ name: "Session User",+ });++ const response = await app.request("/api/user/me", {+ headers: { cookie: cookies },+ });++ expect(response.status).toBe(200);+ expect(limitHeaders(response)).toEqual({+ limit: null,+ remaining: null,+ reset: null,+ retryAfter: null,+ });+ });++ it("keeps the headers when the route itself fails", async () => {+ const { key, workspace } = await seedKey();+ const { app } = createApp();++ const missing = await app.request(+ `/api/workspace/${workspace.id}/members?projectId=${randomUUID()}`,+ { headers: { "x-api-key": key } },+ );+ expect(missing.status).toBe(404);- expect(await missing.text()).toContain("Project not found");++ expect(await readErrorBody(missing)).toEqual({++ message: "Project not found",++ code: "NOT_FOUND",++ });+ expect(limitHeaders(missing)).toMatchObject({+ limit: String(LIMIT),+ remaining: String(LIMIT - 1),+ });+ expect(missing.headers.get("cache-control")).toBe("private");++ const unknownRoute = await app.request("/api/no-such-route", {+ headers: { "x-api-key": key },+ });+ expect(unknownRoute.status).toBe(404);+ expect(limitHeaders(unknownRoute).remaining).toBe(String(LIMIT - 2));+ expect(unknownRoute.headers.get("cache-control")).toBe("private");+ });++ it("answers 429 when the usage quota is exhausted", async () => {+ const lastRefillAt = new Date(Date.now() - 600_000);+ const { key, row } = await seedKey({+ remaining: 0,+ refillAmount: 5,+ refillInterval: 3_600_000,+ lastRefillAt,+ });+ const { app } = createApp();++ const response = await app.request("/api/user/me", {+ headers: { "x-api-key": key },+ });++ expect(response.status).toBe(429);- expect(await response.text()).toContain("API key usage limit exceeded");++ expect(await readErrorBody(response)).toEqual(usageExceeded);+ const retryAfter = Number(limitHeaders(response).retryAfter);+ expect(retryAfter).toBeGreaterThanOrEqual(2_999);+ expect(retryAfter).toBeLessThanOrEqual(3_000);+ expect(limitHeaders(response).limit).toBeNull();+ expect((await savedKey(row.id)).remaining).toBe(0);+ });++ it("answers 429 without Retry-After when the quota never refills", async () => {+ const { key } = await seedKey({ remaining: 0 });+ const { app } = createApp();++ for (const headers of [+ { "x-api-key": key },+ { Authorization: `Bearer ${key}` },+ ]) {+ const response = await app.request("/api/user/me", { headers });+ expect(response.status).toBe(429);- expect(await response.text()).toContain("API key usage limit exceeded");++ expect(await readErrorBody(response)).toEqual(usageExceeded);+ expect(limitHeaders(response).retryAfter).toBeNull();+ }+ });+});diff --cc tests/api-integration/openapi.test.tsindex d656dc3a3,f06d00df0..f385c465f--- a/tests/api-integration/openapi.test.ts+++ b/tests/api-integration/openapi.test.ts@@@ -13,7 -13,6 +13,10 @@@ type Spec =paths: Record<string, Record<string, Operation>>;security?: Array<Record<string, unknown>>;components: {- responses: Record<string, { headers?: Record<string, unknown> }>;++ responses: Record<++ string,++ { headers?: Record<string, unknown>; content?: Record<string, unknown> }++ >;schemas: Record<string, unknown>;securitySchemes: Record<string, { type: string; scheme?: string }>;};@@@ -114,6 -113,32 +117,36 @@@ describe("Kaneo API OpenAPI spec", () =);});+ it("documents Kaneo errors as ApiError JSON", () => {+ expect(spec.components.schemas.ApiError).toMatchObject({+ type: "object",+ required: ["message", "code"],+ });+ const plainText: string[] = [];+ for (const [method, path, operation] of operations(spec)) {+ if (path.startsWith("/mcp/")) continue;+ for (const [status, response] of Object.entries(operation.responses)) {+ if (!/^[45]/.test(status)) continue;- const content = (response as { content?: Record<string, unknown> })- .content;++ const ref = (response as { $ref?: string }).$ref;++ const content = (++ ref++ ? spec.components.responses[ref.split("/").pop() ?? ""]++ : (response as { content?: Record<string, unknown> })++ )?.content;+ if (!content?.["application/json"])+ plainText.push(`${method.toUpperCase()} ${path} ${status}`);+ }+ }+ expect(plainText).toEqual([]);+ expect(spec.paths["/task/{id}"]?.get?.responses["401"]).toMatchObject({+ content: {+ "application/json": {+ schema: { $ref: "#/components/schemas/ApiError" },+ },+ },+ });+ });+it("documents a 401 on every operation that requires auth", () => {const missing: string[] = [];for (const [method, path, operation] of operations(spec)) {@@@ -125,52 -150,4 +158,57 @@@}expect(missing).toEqual([]);});++ it("documents the API key rate limit on every operation that requires auth", () => {+ expect(+ Object.keys(+ spec.components.responses.ApiKeyRateLimited?.headers ?? {},+ ).sort(),+ ).toEqual([+ "Retry-After",+ "X-RateLimit-Limit",+ "X-RateLimit-Remaining",+ "X-RateLimit-Reset",+ ]);++ expect(spec.components.responses.ApiKeyRateLimited?.content).toEqual({++ "application/json": {++ schema: { $ref: "#/components/schemas/ApiError" },++ },++ });+ const missing: string[] = [];+ for (const [method, path, operation] of operations(spec)) {+ const isPublic =+ Array.isArray(operation.security) && operation.security.length === 0;+ if (isPublic) continue;+ if (!operation.responses["429"])+ missing.push(`${method.toUpperCase()} ${path}`);+ }+ expect(missing).toEqual([]);+ expect(spec.paths["/project"]?.get?.responses["429"]).toEqual({+ $ref: "#/components/responses/ApiKeyRateLimited",+ });+ });++ it("documents the API key rate limit on public routes that read an API key", () => {+ const byId = new Map(+ operations(spec).map(([, , operation]) => [+ operation.operationId,+ operation,+ ]),+ );+ for (const id of ["getSession", "getAsset", "getDeviceAuthorizationPage"]) {+ expect(byId.get(id)?.responses["429"], id).toEqual({+ $ref: "#/components/responses/ApiKeyRateLimited",+ });+ }+ for (const id of [+ "getInstanceStatus",+ "getPublicProject",+ "getUserAvatar",+ "getCalendarFeed",+ "getConfig",+ ]) {+ expect(byId.get(id)?.responses["429"], id).toBeUndefined();+ }+ });});