/** * MEGA Radio hosted app (https://mega-radio--noah.kody.run/; until December 17, 2026 also * https://noah.kody.run/mega-radio/). Every link uses packageContext.appBasePath ('/mega-radio' on the old * address, '' on the new) and hostedUrl, so both work. The gate lives here, server-side: * * 1. Sign in with Kody gives a verified visitor id (kody.metaGetCurrentUser). * 2. The visitor proves MEGA.dev Discord membership through this app's own Discord OAuth (PKCE public * client, no secret): /discord/start -> Discord -> /discord/callback. (A Kody executor credential need * was dropped: declaring one makes the platform put a consent screen in front of every route.) * 3. The outcome is stored per Kody user id for MEMBERSHIP_TTL_MS; Discord tokens are never stored. * 4. /files/radio/NN.(mp3|png) streams only for a visitor with an active membership record. */ import { kody, packageContext, packageStorage } from 'kody:runtime' import { fileRoute } from './audio-core.ts' import { serveFile } from './audio-store.ts' import { DISCORD_CLIENT_ID, GUILD_INVITE, GUILD_NAME, HOSTED_URL, MEMBERSHIP_DAYS, SIGNUP_URL } from './config.ts' import { authorizeUrl, checkMembership, exchangeCode, pkceChallenge, randomToken, revokeToken, type MembershipResult } from './discord.ts' import { expiresAt, forgetMembership, getMembership, isActive, putMembership, type Membership } from './membership.ts' import { errorPage, movePage, renderPage, withOrigins } from './page.ts' import { MOVE_JS } from './move.ts' import { originsFor } from './origins.ts' import { PLAYER_JS } from './player.ts' import { newArtKey, signArt, verifyArt } from './art.ts' import { loadView } from './catalog.ts' import { loadPlays, recordPlay } from './plays.ts' import { currentVisitor, loginUrl, logoutUrl, type Visitor } from './visitor.ts' const base = () => String(packageContext?.appBasePath ?? '').replace(/\/+$/, '') const appUrl = () => String(packageContext?.hostedUrl ?? HOSTED_URL).replace(/\/+$/, '') /** Must match a redirect URI registered on the Discord application exactly. */ const redirectUri = () => `${appUrl()}/discord/callback` const stateCookie = () => `__Secure-${packageContext?.cookiePrefix ?? 'mega-radio-'}dstate` const PKCE_TTL_MS = 10 * 60 * 1000 /** The random HMAC key for signed cover-art URLs (created on first use; not a credential). */ async function artKey(): Promise { const saved = (await packageStorage().get('art:key')) as string | null if (saved && /^[0-9a-f]{64}$/.test(saved)) return saved const key = newArtKey() await packageStorage().set('art:key', key) return key } /** Signed, cookie-free cover URLs for the released tracks (lock-screen artwork). */ async function signedArt(b: string, view: Awaited>): Promise> { const key = await artKey() const out: Record = {} for (const t of view.tracks) if (t.released) out[t.n] = await signArt(b, t.n, key) return out } const html = (body: string, status = 200, headers: Record = {}) => new Response(withOrigins(body, originsFor(appUrl())), { status, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'private, no-store', ...headers } }) const redirect = (location: string, headers: Record = {}) => new Response(null, { status: 303, headers: { location, 'cache-control': 'no-store', ...headers } }) const json = (data: unknown, status = 200) => Response.json(data, { status, headers: { 'cache-control': 'private, no-store' } }) /** Read one cookie the platform forwarded (only app-prefixed cookies reach the app). */ function cookie(request: Request, name: string): string | null { for (const part of (request.headers.get('cookie') ?? '').split(/;\s*/)) { const i = part.indexOf('=') if (i > 0 && part.slice(0, i) === name) return decodeURIComponent(part.slice(i + 1)) } return null } /** Record the result of a Discord check for this visitor. */ async function record(v: Visitor, r: MembershipResult, via: Membership['via']): Promise { const m: Membership = { kodyUserId: v.userId, kodyUsername: v.username, member: r.member, discordId: r.discordId, discordName: r.discordName, via, checkedAt: new Date().toISOString() } await putMembership(m) return m } /** Per-visitor throttle on Discord checks. */ async function throttled(v: Visitor): Promise { try { const r = await kody.appRateLimit({ key: `discord-check:${v.userId}`, limit: 20, windowSeconds: 3600 }) return !r.allowed } catch { return false // the throttle is anti-abuse only; never lock members out because it errored } } /** Build the status object shared by GET /status and the page. */ async function status() { const v = await currentVisitor() const b = base() const links = { signIn: loginUrl(`${b}/kody/return`), signUp: SIGNUP_URL, app: `${appUrl()}/`, discordInvite: GUILD_INVITE } if (!v) return { signedIn: false, member: false, checkValidDays: MEMBERSHIP_DAYS, guild: GUILD_NAME, links } const m = await getMembership(v.userId) return { signedIn: true, username: v.username, member: isActive(m), checkValidDays: MEMBERSHIP_DAYS, lastCheck: m ? { member: m.member, discordName: m.discordName, via: m.via, checkedAt: m.checkedAt, expiresAt: expiresAt(m) } : null, guild: GUILD_NAME, links, } } export default { async fetch(request: Request): Promise { const url = new URL(request.url) const path = url.pathname.replace(/\/+$/, '') || '/' const b = base() if (path === '/player.js') return new Response(PLAYER_JS, { headers: { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'public, max-age=300' } }) if (path === '/move.js') return new Response(MOVE_JS, { headers: { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'public, max-age=300' } }) // One-time data move between the old and new addresses (src/move.ts); public, no data on the server. if (path === '/move') return html(movePage(b)) if (path === '/tracks.json') { const view = await loadView() const v = await currentVisitor() if (!v || !isActive(await getMembership(v.userId))) return json(view) const plays = await loadPlays(v.userId) return json({ ...view, tracks: view.tracks.map((t) => ({ ...t, plays: plays[t.n]?.total ?? 0, myPlays: plays[t.n]?.mine ?? 0 })) }) } // Listen stats: verified members only, the same gate as the audio. const play = /^\/plays\/(\d{2})$/.exec(path) if (play) { if (request.method !== 'POST') return new Response('Method not allowed', { status: 405, headers: { allow: 'POST' } }) if (!(request.headers.get('content-type') ?? '').startsWith('application/json')) return json({ error: 'Send JSON.' }, 415) // no cross-site form posts const v = await currentVisitor() if (!v) return json({ error: 'Sign in with Kody first.' }, 401) if (!isActive(await getMembership(v.userId))) return json({ error: `Only verified ${GUILD_NAME} Discord members count plays.` }, 403) const t = (await loadView()).tracks.find((x) => x.n === Number(play[1]) && x.released) if (!t) return json({ error: 'Not released yet.' }, 404) const r = await recordPlay(v.userId, t.n, t.length) return json({ n: t.n, ...r }, r.counted ? 200 : 429) } if (path === '/status') return json(await status()) // Signed cover art for the lock screen: no cookies needed, only a valid unexpired signature. const art = /^\/art\/(\d{2})\.png$/.exec(path) if (art) { const n = Number(art[1]) const ok = await verifyArt(n, url.searchParams.get('exp'), url.searchParams.get('sig'), await artKey()) if (!ok) return new Response('Invalid or expired artwork link.', { status: 403, headers: { 'cache-control': 'no-store' } }) if (!(await loadView()).tracks.some((t) => t.n === n && t.released)) return new Response('Not released yet.', { status: 404 }) return serveFile(request, `radio/${art[1]}.png`, `${art[1]}.png`, 'image/png') } // Gated audio and covers. const file = fileRoute(url.pathname) if (file) { const v = await currentVisitor() if (!v) return new Response('Sign in with Kody first.', { status: 401, headers: { 'cache-control': 'no-store' } }) if (!isActive(await getMembership(v.userId))) return new Response(`Only verified ${GUILD_NAME} Discord members can play MEGA Radio.`, { status: 403, headers: { 'cache-control': 'no-store' } }) if (!(await loadView()).tracks.some((t) => t.n === file.n && t.released)) return new Response('Not released yet.', { status: 404 }) return serveFile(request, file.key, file.name, file.type) } if (path === '/kody/return') { await currentVisitor(3) // wait out access-ticket lag after a fresh sign-in return redirect(`${b}/`) } if (path === '/discord/start') { const v = await currentVisitor() if (!v) return redirect(loginUrl(`${b}/kody/return`)) if (!DISCORD_CLIENT_ID) return html(errorPage(b, 'Discord sign-in is not set up yet.'), 503) if (await throttled(v)) return html(errorPage(b, 'Too many Discord checks. Try again in an hour.'), 429) const state = randomToken(24) const verifier = randomToken(48) await packageStorage().set(`pkce:${state}`, { verifier, userId: v.userId, created: Date.now() }) const setCookie = `${stateCookie()}=${state}; Path=${b || '/'}; Max-Age=600; HttpOnly; Secure; SameSite=Lax` return redirect(authorizeUrl({ redirectUri: redirectUri(), state, challenge: await pkceChallenge(verifier) }), { 'set-cookie': setCookie }) } if (path === '/discord/callback') { const v = await currentVisitor() if (!v) return redirect(loginUrl(`${b}/kody/return`)) const clear = { 'set-cookie': `${stateCookie()}=; Path=${b || '/'}; Max-Age=0; HttpOnly; Secure; SameSite=Lax` } const state = url.searchParams.get('state') ?? '' const code = url.searchParams.get('code') const err = url.searchParams.get('error') // Discord returns error=consent_required/interaction_required for prompt=none on a first visit: retry with consent. if (err === 'consent_required' || err === 'interaction_required' || err === 'login_required') { const saved = (await packageStorage().get(`pkce:${state}`)) as { verifier: string; userId: string } | null if (saved && saved.userId === v.userId && cookie(request, stateCookie()) === state) { const u = new URL(authorizeUrl({ redirectUri: redirectUri(), state, challenge: await pkceChallenge(saved.verifier) })) u.searchParams.set('prompt', 'consent') return redirect(u.toString()) } } if (err) return html(errorPage(b, `Discord said: ${err}`), 400, clear) const iss = url.searchParams.get('iss') if (iss && iss !== 'https://discord.com') return html(errorPage(b, 'Unexpected OAuth issuer.'), 400, clear) if (!state || !code || cookie(request, stateCookie()) !== state) return html(errorPage(b, 'This Discord link expired or came from another browser. Start again.'), 400, clear) const saved = (await packageStorage().get(`pkce:${state}`)) as { verifier: string; userId: string; created: number } | null await packageStorage().delete(`pkce:${state}`) if (!saved || saved.userId !== v.userId || Date.now() - saved.created > PKCE_TTL_MS) return html(errorPage(b, 'This Discord link expired. Start again.'), 400, clear) try { const token = await exchangeCode(fetch, { code, verifier: saved.verifier, redirectUri: redirectUri() }) try { await record(v, await checkMembership(fetch, token), 'discord-oauth') } finally { await revokeToken(fetch, token) } } catch (error) { return html(errorPage(b, error instanceof Error ? error.message : String(error)), 502, clear) } return redirect(`${b}/`, clear) } if (path === '/forget' && request.method === 'POST') { const v = await currentVisitor() if (v) await forgetMembership(v.userId) return redirect(`${b}/`) } if (path === '/') { const v = await currentVisitor() if (!v) return html(renderPage(b, { kind: 'signed-out', loginHref: loginUrl(`${b}/kody/return`) })) const m = await getMembership(v.userId) if (m && isActive(m)) { const view = await loadView() return html(renderPage(b, { kind: 'member', username: v.username, logoutHref: logoutUrl(), discordName: m.discordName, expiresAt: expiresAt(m), radio: view, art: await signedArt(b, view), plays: await loadPlays(v.userId) })) } return html( renderPage(b, { kind: 'unverified', username: v.username, logoutHref: logoutUrl(), notMember: m && !m.member ? { discordName: m.discordName } : undefined, expired: !!m && m.member, }), ) } return new Response('Not found', { status: 404 }) }, }