Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@noah/mega-radio

MEGA Radio (the WAKE album) for members of the MEGA.dev Discord: sign in with Kody, verify with Discord, listen with repeat.

FollowForkOpen app

Files

discord.test.ts

36 lines · 2.0 KB · TypeScript
import assert from 'node:assert/strict'
import { createHash } from 'node:crypto'
import { test } from 'node:test'
import { authorizeUrl, checkMembership, pkceChallenge } from '../src/discord.ts'
import { GUILD_ID } from '../src/config.ts'

const res = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })

test('PKCE S256 is base64url(sha256(verifier)) without padding', async () => {
	const v = 'dBjftJeZ4CVP-mJ92K9ehyQ9g9GqxLxnBjCCbEVpGU0'
	assert.equal(await pkceChallenge(v), createHash('sha256').update(v).digest('base64url'))
})

test('member endpoint: member and non-member', async () => {
	const yes = await checkMembership(async (u) => (u.endsWith('/users/@me') ? res(200, { id: '1', username: 'a' }) : res(200, { roles: ['r'] })), 't')
	assert.deepEqual([yes.member, yes.via, yes.roles], [true, 'member-endpoint', ['r']])
	const no = await checkMembership(async (u) => (u.endsWith('/users/@me') ? res(200, { id: '1' }) : res(404, { code: 10004 })), 't')
	assert.equal(no.member, false)
})

test('falls back to the guild list when guilds.members.read is missing', async () => {
	const r = await checkMembership(async (u) => {
		if (u.endsWith('/users/@me')) return res(200, { id: '1', global_name: 'Noah' })
		if (u.includes('/member')) return res(403, {})
		return res(200, [{ id: '1' }, { id: GUILD_ID }])
	})
	assert.deepEqual([r.member, r.via, r.discordName], [true, 'guild-list', 'Noah'])
})

test('authorize URL carries the Mega.dev client ID, PKCE and the callback', () => {
	const u = new URL(authorizeUrl({ redirectUri: 'https://noah.kody.run/mega-radio/discord/callback', state: 's', challenge: 'c' }))
	assert.equal(u.searchParams.get('client_id'), '1565030809998458920')
	assert.equal(u.searchParams.get('code_challenge_method'), 'S256')
	assert.equal(u.searchParams.get('redirect_uri'), 'https://noah.kody.run/mega-radio/discord/callback')
	assert.equal(u.searchParams.get('scope'), 'identify guilds.members.read')
})