/** * Discord OAuth (authorization code + PKCE, public client, no secret) and the guild membership check. * Runtime-free so it can be unit-tested: callers pass `fetch` (plain global fetch for the app's own OAuth, * or a Kody credential's `fetch` for the visitor's connected Discord account). */ import { DISCORD_CLIENT_ID, DISCORD_SCOPES, GUILD_ID } from './config.ts' const API = 'https://discord.com/api/v10' export const AUTHORIZE_URL = 'https://discord.com/oauth2/authorize' export const TOKEN_URL = `${API}/oauth2/token` type Fetch = (input: string, init?: RequestInit) => Promise const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') /** A random URL-safe string (PKCE verifier or OAuth state). */ export const randomToken = (bytes = 32) => b64url(crypto.getRandomValues(new Uint8Array(bytes))) /** * Derive the S256 PKCE challenge. * * @param verifier - the PKCE code verifier * @returns base64url(SHA-256(verifier)) */ export async function pkceChallenge(verifier: string): Promise { return b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)))) } /** * Build the Discord consent URL. * * @param opts - redirect URI, state and PKCE challenge * @returns the authorize URL */ export function authorizeUrl(opts: { redirectUri: string; state: string; challenge: string }): string { const q = new URLSearchParams({ client_id: DISCORD_CLIENT_ID, response_type: 'code', scope: DISCORD_SCOPES, redirect_uri: opts.redirectUri, state: opts.state, code_challenge: opts.challenge, code_challenge_method: 'S256', prompt: 'none', }) return `${AUTHORIZE_URL}?${q}` } /** * Exchange an authorization code for an access token (public client: client_id + code_verifier, no secret). * * @param f - fetch * @param opts - code, verifier and the exact redirect URI used for authorize * @returns the access token */ export async function exchangeCode(f: Fetch, opts: { code: string; verifier: string; redirectUri: string }): Promise { const res = await f(TOKEN_URL, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'authorization_code', client_id: DISCORD_CLIENT_ID, code: opts.code, code_verifier: opts.verifier, redirect_uri: opts.redirectUri }), }) const body = (await res.json().catch(() => ({}))) as { access_token?: string; error?: string; error_description?: string } if (!res.ok || !body.access_token) throw new Error(`Discord token exchange failed (${res.status}${body.error ? `: ${body.error}` : ''})`) return body.access_token } /** * Best-effort token revocation once the membership check is done, so the app keeps no Discord access. * * @param f - fetch * @param token - the access token */ export async function revokeToken(f: Fetch, token: string): Promise { await f(`${TOKEN_URL}/revoke`, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ client_id: DISCORD_CLIENT_ID, token, token_type_hint: 'access_token' }), }).catch(() => {}) } export type MembershipResult = { member: boolean; discordId: string | null; discordName: string | null; roles: string[]; via: 'member-endpoint' | 'guild-list' } /** * Ask Discord whether the token's user is in the MEGA.dev guild. Uses `/users/@me/guilds/{id}/member` * (scope `guilds.members.read`) and falls back to paging `/users/@me/guilds` (scope `guilds`) when the * token lacks that scope, which is the case for a Kody Discord connection made with `identify guilds`. * * @param f - fetch that already sends `Authorization: Bearer ` (a Kody credential fetch), or plain fetch plus `token` * @param token - access token when `f` does not inject one * @returns whether the user is a member, plus their Discord id/name when known */ export async function checkMembership(f: Fetch, token?: string): Promise { const headers: Record = token ? { authorization: `Bearer ${token}` } : {} const get = (path: string) => f(`${API}${path}`, { headers }) const me = await get('/users/@me') if (me.status === 401) throw new Error('Discord rejected the token (401). Reconnect Discord.') const user = me.ok ? ((await me.json()) as { id?: string; username?: string; global_name?: string }) : {} const discordId = user.id ?? null const discordName = user.global_name || user.username || null const res = await get(`/users/@me/guilds/${GUILD_ID}/member`) if (res.ok) { const m = (await res.json()) as { roles?: string[] } return { member: true, discordId, discordName, roles: m.roles ?? [], via: 'member-endpoint' } } if (res.status === 404) return { member: false, discordId, discordName, roles: [], via: 'member-endpoint' } if (res.status !== 401 && res.status !== 403) throw new Error(`Discord member lookup failed (${res.status})`) // No guilds.members.read on this token: page through the guild list (200 per page). let after = '0' for (let page = 0; page < 10; page++) { const list = await get(`/users/@me/guilds?limit=200&after=${after}`) if (!list.ok) throw new Error(`Discord guild list failed (${list.status}); the connection needs the "guilds" scope`) const guilds = (await list.json()) as { id: string }[] if (guilds.some((g) => g.id === GUILD_ID)) return { member: true, discordId, discordName, roles: [], via: 'guild-list' } if (guilds.length < 200) break after = guilds[guilds.length - 1].id } return { member: false, discordId, discordName, roles: [], via: 'guild-list' } }