Files
Epicure/apps/web/lib/api-auth.ts
T
Arnaud eed57cd10b fix: API keys always showed "never used" — middleware blocked them entirely
proxy.ts required a session cookie for every non-public /api/v1/* request,
rejecting with 401 before the request ever reached requireSessionOrApiKey
(lib/api-auth.ts) — the only place that actually verifies a Bearer API key
and updates lastUsedAt. Pure API-key clients never send a session cookie,
so every single API-key request was blocked at the middleware layer; the
lastUsedAt update code was correct but unreachable.

Now lets requests with an `Authorization: Bearer ek_...` header through to
the route, which still does the real verification (and 401s itself on an
invalid/unknown key) — middleware just stops pre-emptively rejecting valid
ones. Also added error logging to the fire-and-forget lastUsedAt update,
previously silent on failure.

Verified locally: hashed a raw key, confirmed it matched the stored hash
(so the lookup itself was never the problem), reproduced the 401 against
the unpatched middleware, then confirmed both the 200 response and
lastUsedAt populating correctly after the fix — visible in the real
Settings → API Keys UI.
2026-07-12 19:34:25 +02:00

132 lines
3.9 KiB
TypeScript

import crypto from "node:crypto";
import { headers } from "next/headers";
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth/server";
import { db, apiKeys, users, eq } from "@epicure/db";
import { applyRateLimit } from "@/lib/rate-limit";
export async function requireSession() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) {
return { session: null, response: NextResponse.json({ error: "Unauthorized" }, { status: 401 }) };
}
return { session, response: null };
}
export async function requireAdmin() {
const { session, response } = await requireSession();
if (response) return { session: null, response };
// Don't trust session.user.role — it comes from a 5-minute cookieCache
// (see lib/auth/server.ts), so a just-demoted admin would keep access for
// up to 5 minutes. Query the current role directly.
const [dbUser] = await db
.select({ role: users.role })
.from(users)
.where(eq(users.id, session!.user.id))
.limit(1);
if (dbUser?.role !== "admin") {
return { session: null, response: NextResponse.json({ error: "Forbidden" }, { status: 403 }) };
}
return { session, response: null };
}
type SessionLike = {
user: {
id: string;
email: string;
name: string;
tier: string;
role?: string;
image?: string | null;
};
};
type RateLimitOpts = { limit: number; windowSeconds: number };
export async function requireSessionOrApiKey(
req: NextRequest,
opts?: { rateLimit?: RateLimitOpts }
): Promise<{ session: SessionLike; response: null } | { session: null; response: NextResponse }> {
// 1. Try Bearer API key
const authHeader = req.headers.get("authorization");
if (authHeader?.startsWith("Bearer ")) {
const rawKey = authHeader.slice(7).trim();
if (rawKey.startsWith("ek_")) {
const keyHash = crypto.createHash("sha256").update(rawKey).digest("hex");
const [keyRow] = await db
.select({ id: apiKeys.id, userId: apiKeys.userId })
.from(apiKeys)
.where(eq(apiKeys.keyHash, keyHash))
.limit(1);
if (keyRow) {
// Update lastUsedAt asynchronously — don't block response
void db
.update(apiKeys)
.set({ lastUsedAt: new Date() })
.where(eq(apiKeys.id, keyRow.id))
.catch((err) => console.error("[api-auth] failed to update apiKeys.lastUsedAt", err));
const [user] = await db
.select({
id: users.id,
email: users.email,
name: users.name,
tier: users.tier,
role: users.role,
})
.from(users)
.where(eq(users.id, keyRow.userId))
.limit(1);
if (user) {
// Rate limit per API key (not per user — a user's other keys shouldn't
// share this bucket).
if (opts?.rateLimit) {
const { limit, windowSeconds } = opts.rateLimit;
const rateLimitResponse = await applyRateLimit(
`rl:api:key:${keyRow.id}`,
limit,
windowSeconds
);
if (rateLimitResponse) {
return { session: null, response: rateLimitResponse };
}
}
return {
session: { user: { ...user, image: null } },
response: null,
};
}
}
return {
session: null,
response: NextResponse.json({ error: "Unauthorized" }, { status: 401 }),
};
}
}
// 2. Fall back to session cookie
const result = await requireSession();
if (result.response) return result;
if (opts?.rateLimit) {
const { limit, windowSeconds } = opts.rateLimit;
const rateLimitResponse = await applyRateLimit(
`rl:api:session:${result.session!.user.id}`,
limit,
windowSeconds
);
if (rateLimitResponse) {
return { session: null, response: rateLimitResponse };
}
}
return result;
}