import { NextResponse } from "next/server" import { createSupabaseServerClient } from "@/lib/supabase/server" import { createSupabaseAdminClient } from "@/lib/supabase/admin" import { generateApiKey } from "@/lib/api-key" import { TIER_LIMITS, type SubscriptionTier } from "@asa-news/shared" import { rateLimit } from "@/lib/rate-limit" const MAXIMUM_ACTIVE_KEYS = 5 export async function GET() { const supabaseClient = await createSupabaseServerClient() const { data: { user }, } = await supabaseClient.auth.getUser() if (!user) { return NextResponse.json({ error: "not authenticated" }, { status: 401 }) } const adminClient = createSupabaseAdminClient() const { data: keys, error } = await adminClient .from("api_keys") .select("id, key_prefix, label, created_at, last_used_at, revoked_at") .eq("user_id", user.id) .order("created_at", { ascending: false }) if (error) { return NextResponse.json( { error: "failed to load api keys" }, { status: 500 } ) } const activeKeys = keys.filter((key) => key.revoked_at === null) return NextResponse.json({ keys: activeKeys.map((key) => ({ keyIdentifier: key.id, keyPrefix: key.key_prefix, label: key.label, createdAt: key.created_at, lastUsedAt: key.last_used_at, })), }) } export async function POST(request: Request) { const supabaseClient = await createSupabaseServerClient() const { data: { user }, } = await supabaseClient.auth.getUser() if (!user) { return NextResponse.json({ error: "not authenticated" }, { status: 401 }) } const rateLimitResult = rateLimit(`api-keys:${user.id}`, 10, 60_000) if (!rateLimitResult.success) { return NextResponse.json({ error: "too many requests" }, { status: 429 }) } const adminClient = createSupabaseAdminClient() const { data: userProfile } = await adminClient .from("user_profiles") .select("tier") .eq("id", user.id) .single() if ( !userProfile || !TIER_LIMITS[userProfile.tier as SubscriptionTier]?.allowsApiAccess ) { return NextResponse.json( { error: "api access requires the developer plan" }, { status: 403 } ) } const { count: activeKeyCount } = await adminClient .from("api_keys") .select("id", { count: "exact", head: true }) .eq("user_id", user.id) .is("revoked_at", null) if ((activeKeyCount ?? 0) >= MAXIMUM_ACTIVE_KEYS) { return NextResponse.json( { error: `maximum of ${MAXIMUM_ACTIVE_KEYS} active keys allowed` }, { status: 400 } ) } const body = await request.json().catch(() => ({})) const label = typeof body.label === "string" ? body.label.trim() || null : null const { fullKey, keyHash, keyPrefix } = generateApiKey() const { data: insertedKey, error: insertError } = await adminClient .from("api_keys") .insert({ user_id: user.id, key_hash: keyHash, key_prefix: keyPrefix, label, }) .select("id") .single() if (insertError) { return NextResponse.json( { error: "failed to create api key" }, { status: 500 } ) } return NextResponse.json({ fullKey, keyPrefix, keyIdentifier: insertedKey.id, }) }