import { getAuthorizeUrl } from '$lib/auth.server.js'; import { redirect } from '@sveltejs/kit'; export const GET = async (event) => { let target = event.url.searchParams.get('next') ?? '/'; let desiredScopes = event.url.searchParams.get('scope') ?? 'default'; desiredScopes = desiredScopes .split(' ') .flatMap((v) => (v === 'default' ? 'vm-own-read vm-own-write' : v)) .join(' '); if (new URL(target, event.url.href).host !== event.url.host) target = '/'; const existingScopes = (event.cookies.get('oid__scopes') ?? '').split(' '); const authed = await event.locals.auth(); const missingScopes = !!desiredScopes .split(' ') .filter((v) => v) .find((v) => !existingScopes.includes(v)); if ( // if we're not authenticated !authed || // or we're missing scopes missingScopes ) { const { nonce, redirectTo } = await getAuthorizeUrl( event.url.href, desiredScopes.split(' ') ); if (nonce) { let existingNonces = []; try { const n = JSON.parse(event.cookies.get('pending-auth-nonces') ?? '[]'); if (Array.isArray(n) && n.length && typeof n[0] === 'string') existingNonces = n; } catch (error) { // revoke all existing nonces } event.cookies.set( 'pending-auth-nonces', JSON.stringify([...existingNonces, nonce]), { path: '/', httpOnly: true, secure: true, sameSite: true, } ); } else event.cookies.delete('pending-auth-nonces', { path: '/', }); event.cookies.set('next', target, { path: '/', }); throw redirect(303, redirectTo); } else { event.cookies.delete('next', { path: '/', }); throw redirect(303, target); } }; export const POST = GET;