feat: read-only API key scoping
New keys can be created as "Full access" (default, unchanged) or "Read-only" — read-only keys can only make GET/HEAD/OPTIONS requests, enforced once in requireSessionOrApiKey (lib/api-auth.ts) rather than in every route, since a route has no way to know a request came from a scoped key without that check. Existing keys default to full access — no behavior change for anyone who doesn't opt in. Also included in this migration: the chat_messages table for the next commit (chat history persistence) — generated together since both touched packages/db/src/schema/users.ts in the same pass. Verified locally: created both a read-only and a full-access key, confirmed GET succeeds and POST 403s on the read-only key, confirmed POST still works on the full-access key, and checked the scope badges render correctly in the real Settings → API Keys UI.
This commit is contained in:
@@ -6,6 +6,7 @@ import { requireSession } from "@/lib/api-auth";
|
||||
|
||||
const CreateApiKeyBody = z.object({
|
||||
name: z.string().min(1).max(100),
|
||||
scope: z.enum(["full", "read"]).default("full"),
|
||||
});
|
||||
|
||||
export async function GET() {
|
||||
@@ -16,6 +17,7 @@ export async function GET() {
|
||||
.select({
|
||||
id: apiKeys.id,
|
||||
name: apiKeys.name,
|
||||
scope: apiKeys.scope,
|
||||
lastUsedAt: apiKeys.lastUsedAt,
|
||||
createdAt: apiKeys.createdAt,
|
||||
})
|
||||
@@ -56,11 +58,12 @@ export async function POST(req: NextRequest) {
|
||||
userId: session!.user.id,
|
||||
name: parsed.data.name,
|
||||
keyHash,
|
||||
scope: parsed.data.scope,
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
{ id, name: parsed.data.name, key: rawKey, createdAt: now.toISOString() },
|
||||
{ id, name: parsed.data.name, scope: parsed.data.scope, key: rawKey, createdAt: now.toISOString() },
|
||||
{ status: 201 }
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user