import { redirect, type RequestHandler } from '@sveltejs/kit'; import { randomBytes } from 'crypto'; export const GET: RequestHandler = async ({ url, cookies }) => { // Generate a random state parameter for CSRF protection const state = randomBytes(32).toString('hex'); // Store the state in a cookie to verify later cookies.set('oauth_state', state, { path: '/', httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax', maxAge: 60 * 10, // 10 minutes }); // Build the OAuth authorization URL const clientId = process.env.OAUTH_CLIENT_ID; const redirectUri = process.env.OAUTH_REDIRECT_URI || `${url.origin}/oauth/callback`; const scope = 'openid profile email'; // Adjust scopes as needed if (!clientId) { throw new Error('OAUTH_CLIENT_ID environment variable is not set'); } const authUrl = new URL('https://huggingface.co/oauth/authorize'); authUrl.searchParams.set('client_id', clientId); authUrl.searchParams.set('redirect_uri', redirectUri); authUrl.searchParams.set('scope', scope); authUrl.searchParams.set('state', state); authUrl.searchParams.set('response_type', 'code'); // Redirect to the OAuth provider throw redirect(303, authUrl.toString()); };