import { base } from '$app/paths'; import * as auth from '$lib/auth.server.js'; import { error, isHttpError, isRedirect, json, redirect } from '@sveltejs/kit'; import * as client from 'openid-client'; // Pre-checker for nonce, not the primary implementation const handleNonce = (nonce: string | null, nonceCookie: string | undefined) => { if (nonce) { try { const n = JSON.parse(nonceCookie ?? '[]'); if (Array.isArray(n) && n.length && typeof n[0] === 'string') { if (!n.includes(nonce)) throw error(400, 'Nonce not in array'); else return n.filter((v) => v !== nonce); } else throw error(400, 'Nonce provided, but nonce cookie not found'); } catch (e) { throw error(400, `Failed parsing nonce: ${e}`); } } else if (nonceCookie) throw error(400, 'Missing Nonce'); }; export const GET = async (event) => { const sp = event.url.searchParams; const remainingNonces = handleNonce( sp.get('nonce'), event.cookies.get('pending-auth-nonces') ); try { const tokens = await auth.authorizeNewSession( new URL(event.url.href), sp.get('nonce') ?? undefined ); auth.setCookies(event.cookies, tokens); event.cookies.set('pending-auth-nonces', JSON.stringify(remainingNonces), { path: '/', secure: true, sameSite: true, httpOnly: true, }); let target = event.cookies.get('next') ?? '/'; if (new URL(target, event.url.href).host !== event.url.host) target = '/'; event.cookies.delete('next', { path: '/', }); throw redirect( 303, `${base}/login/callback/ok?next=${encodeURIComponent(target)}` ); } catch (e) { if (isRedirect(e) || isHttpError(e)) throw e; // @ts-ignore if (e?.cause?.error === 'invalid_grant') throw error( 403, 'Invalid Grant Provided - Does your account have access to all requested resources?' ); else throw error( 500, `Could not authorize new session: ${JSON.stringify(e, null, 2)}` ); } };