/** Discord OAuth2 (authorization code + state), docs/02, ported from joke-app. */ export interface DiscordUser { id: string; username: string; global_name: string | null; avatar: string | null; } const API = 'https://discord.com/api/v10'; export function authorizeUrl(clientId: string, redirectUri: string, state: string): string { const p = new URLSearchParams({ client_id: clientId, response_type: 'code', redirect_uri: redirectUri, scope: 'identify', state, prompt: 'none', }); return `https://discord.com/oauth2/authorize?${p}`; } export async function exchangeCode( cfg: { clientId: string; clientSecret: string }, code: string, redirectUri: string, fetchImpl: typeof fetch = fetch, ): Promise { const tokenRes = await fetchImpl(`${API}/oauth2/token`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ client_id: cfg.clientId, client_secret: cfg.clientSecret, grant_type: 'authorization_code', code, redirect_uri: redirectUri, }), signal: AbortSignal.timeout(10_000), }); if (!tokenRes.ok) throw new Error(`discord token exchange failed: ${tokenRes.status}`); const token = (await tokenRes.json()) as { access_token: string; token_type: string }; const meRes = await fetchImpl(`${API}/users/@me`, { headers: { Authorization: `${token.token_type} ${token.access_token}` }, signal: AbortSignal.timeout(10_000), }); if (!meRes.ok) throw new Error(`discord /users/@me failed: ${meRes.status}`); return (await meRes.json()) as DiscordUser; } export function avatarUrl(u: DiscordUser): string | null { return u.avatar ? `https://cdn.discordapp.com/avatars/${u.id}/${u.avatar}.png?size=128` : null; } /** Only same-site relative paths are allowed as post-login redirect targets. */ export function safeNext(next: string | null | undefined): string { if (!next || !next.startsWith('/') || next.startsWith('//') || next.includes('\\')) return '/'; return next; }