import { NextResponse, type NextRequest } from 'next/server'; import { randomBytes } from 'node:crypto'; import { getSupabaseAdmin, getSupabaseAnon } from '@/lib/supabase/admin'; import { createSupabaseServerClient } from '@/lib/supabase/server'; import { validateSubdomain } from '@/lib/validation'; export const runtime = 'nodejs'; export const dynamic = 'force-dynamic'; type ClaimBody = { subdomain?: unknown }; async function resolveUserId(req: NextRequest): Promise { // 1. Authorization: Bearer (used by the E2E script) const auth = req.headers.get('authorization') ?? ''; const m = /^Bearer\s+(.+)$/i.exec(auth.trim()); if (m) { const anon = getSupabaseAnon(); const { data, error } = await anon.auth.getUser(m[1]); if (!error && data.user) return data.user.id; } // 2. Fallback to cookie session (browser). const supabase = createSupabaseServerClient(); const { data: { user }, } = await supabase.auth.getUser(); return user?.id ?? null; } export async function POST(req: NextRequest) { const userId = await resolveUserId(req); if (!userId) { return NextResponse.json({ error: 'unauthorized' }, { status: 401 }); } let body: ClaimBody; try { body = (await req.json()) as ClaimBody; } catch { return NextResponse.json({ error: 'invalid json' }, { status: 400 }); } const v = validateSubdomain(body.subdomain); if (!v.ok) { return NextResponse.json({ error: v.error }, { status: 400 }); } const subdomain = v.value; const admin = getSupabaseAdmin(); // Reject if the subdomain is already owned by another user. const { data: existing, error: existingErr } = await admin .from('tunnels') .select('user_id') .eq('subdomain', subdomain) .maybeSingle<{ user_id: string }>(); if (existingErr) { return NextResponse.json({ error: existingErr.message }, { status: 500 }); } if (existing && existing.user_id !== userId) { return NextResponse.json({ error: 'subdomain taken' }, { status: 409 }); } const token = randomBytes(32).toString('hex'); const { data, error } = await admin .from('tunnels') .upsert( { user_id: userId, subdomain, token, is_active: true, }, { onConflict: 'user_id' }, ) .select('subdomain, token') .single<{ subdomain: string; token: string }>(); if (error) { // 23505 = unique_violation — race on the subdomain column. const code = (error as { code?: string }).code; if (code === '23505') { return NextResponse.json({ error: 'subdomain taken' }, { status: 409 }); } return NextResponse.json({ error: error.message }, { status: 500 }); } return NextResponse.json({ subdomain: data.subdomain, token: data.token }); }