From 73d3a5d01059e6a65194f0cd4e63af652527abeb Mon Sep 17 00:00:00 2001 From: Musiker15 Date: Thu, 5 Nov 2026 11:29:48 +0100 Subject: [PATCH 1/9] feat(sponsors): link token contract, sponsorship rule and msk_sponsor_links The Discord bot hands a member a signed link into the shop; lib/sponsorLink.ts holds that contract (HMAC-SHA256 over "sponsor-link." + payload, 15 min TTL, guild check), the signed OAuth state cookie and the env check that keeps the feature off with a log line naming what is missing. lib/sponsors.ts asks GitHub for the org's sponsorships and decides who counts: monthly while active, one-time for 30 days, at least $5, users only, the best of several, keyed by databaseId. lib/sponsorLinks.ts stores Discord user to GitHub account, one GitHub account per Discord user, and grants the role. --- database/migrations/004-sponsor-links.sql | 23 +++ database/schema.sql | 20 ++ lib/sponsorLink.ts | 228 ++++++++++++++++++++++ lib/sponsorLinks.ts | 73 +++++++ lib/sponsors.ts | 178 +++++++++++++++++ 5 files changed, 522 insertions(+) create mode 100644 database/migrations/004-sponsor-links.sql create mode 100644 lib/sponsorLink.ts create mode 100644 lib/sponsorLinks.ts create mode 100644 lib/sponsors.ts diff --git a/database/migrations/004-sponsor-links.sql b/database/migrations/004-sponsor-links.sql new file mode 100644 index 0000000..46fcfcf --- /dev/null +++ b/database/migrations/004-sponsor-links.sql @@ -0,0 +1,23 @@ +-- GitHub Sponsors -> Discord "Sponsor" role: which GitHub account belongs to +-- which Discord user. +-- +-- Written by GET /api/sponsor/callback after the GitHub sign-in, read by +-- GET /api/sponsor/members for the bot's daily reconcile. Nothing about the +-- sponsorship itself is stored: GitHub is asked live on every check. +-- +-- Matched by github_user_id (GitHub's databaseId), not by login, because a +-- login can be renamed. The login is kept for display and support only. +-- +-- One GitHub account maps to one Discord account (UNIQUE github_user_id). +-- Linking it again from another Discord account moves it: lib/sponsorLinks.ts +-- deletes the old row in the same transaction. + +CREATE TABLE IF NOT EXISTS msk_sponsor_links ( + discord_user_id VARCHAR(20) NOT NULL PRIMARY KEY, + github_user_id BIGINT UNSIGNED NOT NULL, + github_login VARCHAR(100) NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + + UNIQUE KEY uq_github_user (github_user_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/database/schema.sql b/database/schema.sql index 1bcb2f6..f3fe623 100644 --- a/database/schema.sql +++ b/database/schema.sql @@ -579,3 +579,23 @@ CREATE TABLE IF NOT EXISTS msk_content_reports ( -- -- Aufbewahrung: Widerrufe und Kuendigungen 3 Jahre zum Jahresende (so steht es -- in der Datenschutzerklaerung, Abschnitt 12). Das erledigt `cleanup.js`. + +-- ============================================================================ +-- GitHub Sponsors -> Discord "Sponsor" role (Migration 004-sponsor-links.sql) +-- ============================================================================ +-- Which GitHub account belongs to which Discord user. Written by +-- GET /api/sponsor/callback, read by GET /api/sponsor/members (the bot's daily +-- reconcile). The sponsorship itself is not stored, GitHub is asked live on +-- every check. Matched by github_user_id (databaseId), not by the login, which +-- can be renamed. One GitHub account maps to one Discord account; linking it +-- again moves it (lib/sponsorLinks.ts deletes the old row in the same +-- transaction). +CREATE TABLE IF NOT EXISTS msk_sponsor_links ( + discord_user_id VARCHAR(20) NOT NULL PRIMARY KEY, + github_user_id BIGINT UNSIGNED NOT NULL, + github_login VARCHAR(100) NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + + UNIQUE KEY uq_github_user (github_user_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/lib/sponsorLink.ts b/lib/sponsorLink.ts new file mode 100644 index 0000000..9bce786 --- /dev/null +++ b/lib/sponsorLink.ts @@ -0,0 +1,228 @@ +import { createHmac, randomBytes, timingSafeEqual } from 'crypto' + +// ============================================================================= +// GitHub Sponsors -> Discord role: link tokens, state cookie, bearer check, env +// ============================================================================= +// The Discord bot (discord_multibot) answers a click on its "Verify" button with +// a personal link into the shop: +// +// ${NEXT_PUBLIC_BASE_URL}/api/sponsor/start?t= +// token = base64url(JSON payload) + "." + base64url(HMAC-SHA256( +// key = SPONSOR_LINK_SECRET, +// data = "sponsor-link." + base64url(JSON payload))) +// payload = { v: 1, d: , g: , exp: , n: } +// +// The bot implements the same contract, so nothing here may drift from it: +// the prefix, the field names, seconds (not milliseconds) in `exp`. +// +// The shop then keeps `{ discordId, state }` for the GitHub OAuth round trip in +// a short-lived signed cookie. That cookie is signed with the same secret under +// a different prefix ("sponsor-state."), so a link token can never pass as a +// cookie or the other way round. +// ============================================================================= + +export const SNOWFLAKE_RE = /^\d{17,20}$/ +/** GitHub login: 1 to 39 characters, alphanumeric or single hyphens. */ +export const GITHUB_LOGIN_RE = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/ + +const LINK_PREFIX = 'sponsor-link.' +const STATE_PREFIX = 'sponsor-state.' + +/** Lifetime of the link the bot hands out. The bot sets `exp`, this is documentation. */ +export const SPONSOR_LINK_TTL_S = 15 * 60 +/** Lifetime of the OAuth state cookie. */ +export const SPONSOR_STATE_TTL_S = 10 * 60 +export const SPONSOR_STATE_COOKIE = 'msk_sponsor_state' + +const MIN_SECRET_LENGTH = 32 + +// ── Configuration ──────────────────────────────────────────────────────────── + +export interface SponsorConfig { + linkSecret: string + clientId: string + clientSecret: string + sponsorsToken: string + githubOrg: string + botToken: string + guildId: string + roleId: string +} + +type Env = Record + +function env(e: Env, name: string): string { + return (e[name] ?? '').trim() +} + +/** + * Everything the browser flow (start + callback) needs. Returns the names of + * the missing or invalid variables instead of a config, never their values, + * so the caller can log one clear line and fail closed. + */ +export function readSponsorConfig(e: Env = process.env): { ok: true; config: SponsorConfig } | { ok: false; missing: string[] } { + const missing: string[] = [] + const linkSecret = env(e, 'SPONSOR_LINK_SECRET') + if (linkSecret.length < MIN_SECRET_LENGTH) missing.push('SPONSOR_LINK_SECRET (min. 32 chars)') + + const required = ['GITHUB_SPONSOR_CLIENT_ID', 'GITHUB_SPONSOR_CLIENT_SECRET', 'GITHUB_SPONSORS_TOKEN', 'SPONSOR_DISCORD_BOT_TOKEN'] + for (const name of required) if (!env(e, name)) missing.push(name) + + const guildId = env(e, 'SPONSOR_GUILD_ID') + if (!SNOWFLAKE_RE.test(guildId)) missing.push('SPONSOR_GUILD_ID (snowflake)') + const roleId = env(e, 'SPONSOR_ROLE_ID') + if (!SNOWFLAKE_RE.test(roleId)) missing.push('SPONSOR_ROLE_ID (snowflake)') + + const githubOrg = env(e, 'SPONSOR_GITHUB_ORG') || 'MSK-Scripts' + if (!GITHUB_LOGIN_RE.test(githubOrg)) missing.push('SPONSOR_GITHUB_ORG (GitHub login)') + + if (missing.length) return { ok: false, missing } + return { + ok: true, + config: { + linkSecret, + clientId: env(e, 'GITHUB_SPONSOR_CLIENT_ID'), + clientSecret: env(e, 'GITHUB_SPONSOR_CLIENT_SECRET'), + sponsorsToken: env(e, 'GITHUB_SPONSORS_TOKEN'), + githubOrg, + botToken: env(e, 'SPONSOR_DISCORD_BOT_TOKEN'), + guildId, + roleId, + }, + } +} + +/** The bearer secret of the members endpoint, or null when unset or too short. */ +export function readSyncSecret(e: Env = process.env): string | null { + const s = env(e, 'SPONSOR_SYNC_SECRET') + return s.length >= MIN_SECRET_LENGTH ? s : null +} + +// ── Primitives ─────────────────────────────────────────────────────────────── + +function hmac(secret: string, data: string): string { + return createHmac('sha256', secret).update(data).digest('base64url') +} + +/** Constant-time string comparison; different lengths are simply unequal. */ +export function safeEqual(a: string, b: string): boolean { + const ab = Buffer.from(a) + const bb = Buffer.from(b) + return ab.length === bb.length && timingSafeEqual(ab, bb) +} + +function splitToken(token: string | null | undefined): { b64: string; sig: string } | null { + if (!token || token.length > 2048) return null + const dot = token.lastIndexOf('.') + if (dot <= 0 || dot === token.length - 1) return null + return { b64: token.slice(0, dot), sig: token.slice(dot + 1) } +} + +function decodeJson(b64: string): Record | null { + try { + const value: unknown = JSON.parse(Buffer.from(b64, 'base64url').toString('utf8')) + return value && typeof value === 'object' && !Array.isArray(value) ? value as Record : null + } catch { + return null + } +} + +// ── Link token (created by the bot) ────────────────────────────────────────── + +export interface LinkPayload { + v: 1 + d: string + g: string + exp: number + n: string +} + +/** + * Creates a link token exactly as the bot does. The shop never hands one out; + * this exists for the tests and as the reference for the contract. + */ +export function signLinkToken(payload: LinkPayload, secret: string): string { + const b64 = Buffer.from(JSON.stringify(payload)).toString('base64url') + return `${b64}.${hmac(secret, LINK_PREFIX + b64)}` +} + +/** + * Checks a link token from the bot. Returns the Discord user id, or null for + * anything that is not a valid, unexpired token for our guild. + */ +export function verifyLinkToken( + token: string | null | undefined, + opts: { secret: string; guildId: string; nowMs?: number }, +): { discordId: string } | null { + const parts = splitToken(token) + if (!parts) return null + if (!safeEqual(parts.sig, hmac(opts.secret, LINK_PREFIX + parts.b64))) return null + + const p = decodeJson(parts.b64) + if (!p) return null + const now = Math.floor((opts.nowMs ?? Date.now()) / 1000) + if (p.v !== 1) return null + if (typeof p.exp !== 'number' || !Number.isFinite(p.exp) || p.exp <= now) return null + if (typeof p.d !== 'string' || !SNOWFLAKE_RE.test(p.d)) return null + if (typeof p.g !== 'string' || !SNOWFLAKE_RE.test(p.g)) return null + if (p.g !== opts.guildId) return null + return { discordId: p.d } +} + +// ── OAuth state cookie (shop internal) ─────────────────────────────────────── + +export interface SponsorState { + discordId: string + state: string +} + +export function newOAuthState(): string { + return randomBytes(16).toString('hex') +} + +export function signStateCookie(value: SponsorState, secret: string, nowMs: number = Date.now()): string { + const exp = Math.floor(nowMs / 1000) + SPONSOR_STATE_TTL_S + const b64 = Buffer.from(JSON.stringify({ d: value.discordId, s: value.state, exp })).toString('base64url') + return `${b64}.${hmac(secret, STATE_PREFIX + b64)}` +} + +export function readStateCookie(cookie: string | null | undefined, secret: string, nowMs: number = Date.now()): SponsorState | null { + const parts = splitToken(cookie) + if (!parts) return null + if (!safeEqual(parts.sig, hmac(secret, STATE_PREFIX + parts.b64))) return null + + const p = decodeJson(parts.b64) + if (!p) return null + if (typeof p.exp !== 'number' || p.exp <= Math.floor(nowMs / 1000)) return null + if (typeof p.d !== 'string' || !SNOWFLAKE_RE.test(p.d)) return null + if (typeof p.s !== 'string' || !/^[0-9a-f]{32}$/.test(p.s)) return null + return { discordId: p.d, state: p.s } +} + +// ── Result page ────────────────────────────────────────────────────────────── + +/** + * What the result page (`/sponsor/verify`, German `/sponsor/verifizieren`) can + * report. Anything else in `?status=` reads as `error`. + */ +export const SPONSOR_STATUSES = [ + 'granted', + 'linked_no_sponsorship', + 'role_failed', + 'link_invalid', + 'rate_limited', + 'error', +] as const +export type SponsorStatus = (typeof SPONSOR_STATUSES)[number] + +export function parseSponsorStatus(value: unknown): SponsorStatus { + return (SPONSOR_STATUSES as readonly unknown[]).includes(value) ? value as SponsorStatus : 'error' +} + +// ── Members endpoint ───────────────────────────────────────────────────────── + +/** `Authorization: Bearer `, compared in constant time. */ +export function bearerMatches(header: string | null, secret: string): boolean { + const m = /^Bearer\s+(\S+)$/.exec(header ?? '') + return !!m && safeEqual(m[1], secret) +} diff --git a/lib/sponsorLinks.ts b/lib/sponsorLinks.ts new file mode 100644 index 0000000..d944544 --- /dev/null +++ b/lib/sponsorLinks.ts @@ -0,0 +1,73 @@ +import { query, withTransaction } from '@/lib/db' + +// ============================================================================= +// msk_sponsor_links: which GitHub account belongs to which Discord user +// ============================================================================= +// One row per Discord user, and one GitHub account maps to at most one Discord +// user (UNIQUE github_user_id). Linking a GitHub account that already belongs +// to someone else moves it: the old row goes in the same transaction, so a +// sponsorship can never carry the role for two Discord accounts at once. +// ============================================================================= + +export interface SponsorLink { + discordUserId: string + githubUserId: number + githubLogin: string | null +} + +export async function upsertSponsorLink(discordUserId: string, githubUserId: number, githubLogin: string): Promise { + await withTransaction(async conn => { + await conn.execute( + 'DELETE FROM msk_sponsor_links WHERE github_user_id = ? AND discord_user_id <> ?', + [githubUserId, discordUserId], + ) + await conn.execute( + `INSERT INTO msk_sponsor_links (discord_user_id, github_user_id, github_login) + VALUES (?, ?, ?) + ON DUPLICATE KEY UPDATE github_user_id = VALUES(github_user_id), github_login = VALUES(github_login)`, + [discordUserId, githubUserId, githubLogin], + ) + }) +} + +interface LinkRow { + discord_user_id: string + github_user_id: number | string + github_login: string | null +} + +export async function listSponsorLinks(): Promise { + const rows = await query('SELECT discord_user_id, github_user_id, github_login FROM msk_sponsor_links') + return rows.map(r => ({ + discordUserId: String(r.discord_user_id), + githubUserId: Number(r.github_user_id), + githubLogin: r.github_login, + })) +} + +/** + * Gives the Discord user the sponsor role right away. True on success; false + * when Discord refuses (most often: the user is not on the server) or is + * unreachable. Idempotent on Discord's side, a second PUT is a no-op. + */ +export async function grantSponsorRole( + opts: { botToken: string; guildId: string; roleId: string; discordUserId: string }, + fetchImpl: typeof fetch = fetch, +): Promise { + try { + const res = await fetchImpl( + `https://discord.com/api/v10/guilds/${opts.guildId}/members/${opts.discordUserId}/roles/${opts.roleId}`, + { + method: 'PUT', + headers: { + Authorization: `Bot ${opts.botToken}`, + 'X-Audit-Log-Reason': encodeURIComponent('GitHub Sponsor verified on msk-scripts.de'), + }, + signal: AbortSignal.timeout(10_000), + }, + ) + return res.status === 204 || res.ok + } catch { + return false + } +} diff --git a/lib/sponsors.ts b/lib/sponsors.ts new file mode 100644 index 0000000..bea0701 --- /dev/null +++ b/lib/sponsors.ts @@ -0,0 +1,178 @@ +// ============================================================================= +// GitHub Sponsors: who currently counts as a sponsor +// ============================================================================= +// The org has two tiers, both $5: monthly and one-time. Every payment is worth +// 30 days of the "Sponsor" role on the Discord server. GitHub is asked live on +// every check; nothing about a sponsorship is stored in the shop, only which +// GitHub account belongs to which Discord user (msk_sponsor_links). +// +// The token (GITHUB_SPONSORS_TOKEN) is a classic personal access token of an +// owner of the organization with the scope `read:org`. Only an org owner sees +// private sponsorships and the sponsorships of the org as a maintainer at all; +// with a weaker token the list comes back short, not with an error. +// ============================================================================= + +export const MIN_PRICE_USD = 5 +export const ONE_TIME_DAYS = 30 +const DAY_MS = 24 * 60 * 60 * 1000 + +const GRAPHQL_URL = 'https://api.github.com/graphql' +/** 100 per page, so this is room for 5,000 sponsorships before we stop. */ +const MAX_PAGES = 50 + +export const SPONSORSHIPS_QUERY = `query($org: String!, $cursor: String) { + organization(login: $org) { + sponsorshipsAsMaintainer(first: 100, after: $cursor, activeOnly: false, includePrivate: true) { + pageInfo { hasNextPage endCursor } + nodes { + isActive + isOneTimePayment + createdAt + tierSelectedAt + tier { monthlyPriceInDollars isOneTime } + sponsorEntity { __typename ... on User { login databaseId } } + } + } + } +}` + +/** One node of `sponsorshipsAsMaintainer`, as GitHub returns it. */ +export interface SponsorshipNode { + isActive?: boolean | null + isOneTimePayment?: boolean | null + createdAt?: string | null + tierSelectedAt?: string | null + tier?: { monthlyPriceInDollars?: number | null; isOneTime?: boolean | null } | null + sponsorEntity?: { __typename?: string; login?: string | null; databaseId?: number | null } | null +} + +export type SponsorKind = 'monthly' | 'one_time' + +export interface SponsorGrant { + githubId: number + login: string + kind: SponsorKind + /** null = open-ended (an active monthly sponsorship). */ + validUntil: Date | null +} + +function parseDate(value: string | null | undefined): number | null { + if (!value) return null + const t = Date.parse(value) + return Number.isNaN(t) ? null : t +} + +/** True when `a` is the better grant: open-ended beats dated, later beats earlier. */ +function better(a: SponsorGrant, b: SponsorGrant): boolean { + if (a.validUntil === null) return b.validUntil !== null + if (b.validUntil === null) return false + return a.validUntil.getTime() > b.validUntil.getTime() +} + +/** + * The validity rule, pure so it can be tested without GitHub. + * + * - Only `User` sponsors count, organizations are ignored. + * - The tier must cost at least $5. + * - Monthly: counts while GitHub calls it active, open-ended. + * - One-time: counts for 30 days from the later of `tierSelectedAt` and + * `createdAt`, whatever `isActive` says. + * - Several sponsorships of one user: the best one wins. + * + * A sponsorship counts as one-time when either GitHub flag says so + * (`isOneTimePayment` or `tier.isOneTime`). The stricter reading on purpose: + * a one-time payment mistaken for monthly would grant the role forever. + * + * Keyed by the GitHub database id, never by login: logins can be renamed. + */ +export function evaluateSponsorships(nodes: readonly SponsorshipNode[], nowMs: number = Date.now()): Map { + const out = new Map() + + for (const node of nodes) { + const entity = node.sponsorEntity + if (!entity || entity.__typename !== 'User') continue + const githubId = entity.databaseId + if (typeof githubId !== 'number' || !Number.isSafeInteger(githubId) || githubId <= 0) continue + const login = typeof entity.login === 'string' ? entity.login : '' + + const price = Number(node.tier?.monthlyPriceInDollars ?? 0) + if (!Number.isFinite(price) || price < MIN_PRICE_USD) continue + + let grant: SponsorGrant | null = null + if (node.isOneTimePayment || node.tier?.isOneTime) { + const paidAt = Math.max(parseDate(node.tierSelectedAt) ?? -Infinity, parseDate(node.createdAt) ?? -Infinity) + if (!Number.isFinite(paidAt)) continue + const until = paidAt + ONE_TIME_DAYS * DAY_MS + if (until > nowMs) grant = { githubId, login, kind: 'one_time', validUntil: new Date(until) } + } else if (node.isActive === true) { + grant = { githubId, login, kind: 'monthly', validUntil: null } + } + if (!grant) continue + + const prev = out.get(githubId) + if (!prev || better(grant, prev)) out.set(githubId, grant) + } + + return out +} + +interface GraphQlPage { + data?: { + organization?: { + sponsorshipsAsMaintainer?: { + pageInfo?: { hasNextPage?: boolean; endCursor?: string | null } + nodes?: (SponsorshipNode | null)[] + } | null + } | null + } + errors?: unknown[] +} + +/** + * All sponsorships of the org, every page. Throws on any HTTP, GraphQL or + * shape problem: a failed query must never read as "nobody sponsors", the bot + * would then take the role from everyone. + */ +export async function fetchSponsorships( + opts: { token: string; org: string }, + fetchImpl: typeof fetch = fetch, +): Promise { + const nodes: SponsorshipNode[] = [] + let cursor: string | null = null + + for (let page = 0; page < MAX_PAGES; page++) { + const res = await fetchImpl(GRAPHQL_URL, { + method: 'POST', + headers: { + Authorization: `Bearer ${opts.token}`, + 'Content-Type': 'application/json', + 'User-Agent': 'msk-shop-sponsors', + }, + body: JSON.stringify({ query: SPONSORSHIPS_QUERY, variables: { org: opts.org, cursor } }), + cache: 'no-store', + signal: AbortSignal.timeout(15_000), + }) + if (!res.ok) throw new Error(`GitHub GraphQL HTTP ${res.status}`) + + const json = await res.json() as GraphQlPage + if (json.errors?.length) throw new Error(`GitHub GraphQL returned ${json.errors.length} error(s)`) + const conn = json.data?.organization?.sponsorshipsAsMaintainer + if (!conn || !Array.isArray(conn.nodes)) throw new Error('GitHub GraphQL: unexpected response shape') + + for (const n of conn.nodes) if (n) nodes.push(n) + if (!conn.pageInfo?.hasNextPage) return nodes + cursor = conn.pageInfo.endCursor ?? null + if (!cursor) throw new Error('GitHub GraphQL: hasNextPage without endCursor') + } + + throw new Error(`GitHub GraphQL: more than ${MAX_PAGES} pages`) +} + +/** Current valid sponsors of the org, keyed by GitHub database id. */ +export async function currentSponsors( + opts: { token: string; org: string }, + nowMs: number = Date.now(), + fetchImpl: typeof fetch = fetch, +): Promise> { + return evaluateSponsorships(await fetchSponsorships(opts, fetchImpl), nowMs) +} From 404086826eb74c70ae88e14e2d73bc1d9929cf9d Mon Sep 17 00:00:00 2001 From: Musiker15 Date: Thu, 5 Nov 2026 11:29:48 +0100 Subject: [PATCH 2/9] feat(sponsors): start, callback and members routes for the sponsor role /api/sponsor/start checks the bot's link and sends the browser to GitHub OAuth without a scope. /api/sponsor/callback checks the state, links the accounts, checks the sponsorship and grants the Discord role right away. /api/sponsor/members gives the bot the list of valid sponsors for its daily reconcile, behind a bearer secret, and answers 502 instead of an empty list when GitHub fails. Tests cover the token, the validity rule and the members auth; the route guard test learns readStateCookie and bearerMatches. --- app/api/sponsor/callback/route.ts | 129 ++++++++++++++ app/api/sponsor/members/route.ts | 67 +++++++ app/api/sponsor/start/route.ts | 56 ++++++ tests/routeGuards.test.ts | 6 +- tests/sponsors.test.ts | 281 ++++++++++++++++++++++++++++++ 5 files changed, 537 insertions(+), 2 deletions(-) create mode 100644 app/api/sponsor/callback/route.ts create mode 100644 app/api/sponsor/members/route.ts create mode 100644 app/api/sponsor/start/route.ts create mode 100644 tests/sponsors.test.ts diff --git a/app/api/sponsor/callback/route.ts b/app/api/sponsor/callback/route.ts new file mode 100644 index 0000000..2dd5fe5 --- /dev/null +++ b/app/api/sponsor/callback/route.ts @@ -0,0 +1,129 @@ +import { NextResponse } from 'next/server' +import { cookies } from 'next/headers' + +import { publicPath } from '@/lib/routes' +import { getPreferredLang } from '@/lib/serverLang' +import { absoluteUrl, siteUrl } from '@/lib/siteUrl' +import { + GITHUB_LOGIN_RE, SPONSOR_STATE_COOKIE, readSponsorConfig, readStateCookie, safeEqual, + type SponsorStatus, +} from '@/lib/sponsorLink' +import { grantSponsorRole, upsertSponsorLink } from '@/lib/sponsorLinks' +import { currentSponsors } from '@/lib/sponsors' + +// GitHub sends the browser back here. Log lines name the outcome, never the +// Discord or GitHub id, the token or the code (log injection, privacy). In order: +// 1. state from the query equals the state in our signed cookie (CSRF), the +// cookie is deleted on every path; +// 2. the code is exchanged for a token, which is used once for GET /user and +// then forgotten (never stored, never logged); +// 3. the link Discord user <-> GitHub account is saved; +// 4. the org's sponsorships are checked, and a valid sponsor gets the role +// on Discord right away. Removing it again is the bot's daily reconcile +// against GET /api/sponsor/members. + +export async function GET(req: Request) { + const lang = await getPreferredLang() + const finish = (status: SponsorStatus) => { + const res = NextResponse.redirect(absoluteUrl(publicPath(lang, `/sponsor/verify?status=${status}`))) + res.cookies.set(SPONSOR_STATE_COOKIE, '', { httpOnly: true, secure: true, sameSite: 'lax', maxAge: 0, path: '/api/sponsor' }) + return res + } + + const cfg = readSponsorConfig() + if (!cfg.ok) { + console.error(`[sponsor] feature disabled, missing or invalid env: ${cfg.missing.join(', ')}`) + return finish('error') + } + const { config } = cfg + + const { searchParams } = new URL(req.url) + const code = searchParams.get('code') + const state = searchParams.get('state') + const saved = readStateCookie((await cookies()).get(SPONSOR_STATE_COOKIE)?.value, config.linkSecret) + if (!code || !state || !saved || !safeEqual(state, saved.state)) { + return finish('link_invalid') + } + const discordId = saved.discordId + + // ── GitHub identity ────────────────────────────────────────────────────── + let githubId: number + let githubLogin: string + try { + const tokenRes = await fetch('https://github.com/login/oauth/access_token', { + method: 'POST', + headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, + body: JSON.stringify({ + client_id: config.clientId, + client_secret: config.clientSecret, + code, + redirect_uri: `${siteUrl()}/api/sponsor/callback`, + }), + cache: 'no-store', + signal: AbortSignal.timeout(10_000), + }) + const tokenData = await tokenRes.json() as { access_token?: unknown } + if (typeof tokenData.access_token !== 'string' || !tokenData.access_token) { + console.warn('[sponsor] GitHub code exchange returned no access token') + return finish('error') + } + + const userRes = await fetch('https://api.github.com/user', { + headers: { + Authorization: `Bearer ${tokenData.access_token}`, + Accept: 'application/vnd.github+json', + 'User-Agent': 'msk-shop-sponsors', + }, + cache: 'no-store', + signal: AbortSignal.timeout(10_000), + }) + if (!userRes.ok) { + console.warn(`[sponsor] GitHub /user answered HTTP ${userRes.status}`) + return finish('error') + } + const user = await userRes.json() as { id?: unknown; login?: unknown } + if (typeof user.id !== 'number' || !Number.isSafeInteger(user.id) || user.id <= 0 + || typeof user.login !== 'string' || !GITHUB_LOGIN_RE.test(user.login)) { + console.warn('[sponsor] GitHub /user returned an unexpected shape') + return finish('error') + } + githubId = user.id + githubLogin = user.login + } catch { + console.warn('[sponsor] GitHub OAuth request failed') + return finish('error') + } + + // ── Link ───────────────────────────────────────────────────────────────── + try { + await upsertSponsorLink(discordId, githubId, githubLogin) + } catch (err) { + console.error('[sponsor] saving the link failed:', err instanceof Error ? err.message : 'unknown error') + return finish('error') + } + + // ── Sponsorship ────────────────────────────────────────────────────────── + let isSponsor: boolean + try { + const sponsors = await currentSponsors({ token: config.sponsorsToken, org: config.githubOrg }) + isSponsor = sponsors.has(githubId) + } catch (err) { + // The link is saved, the next daily sync picks a valid sponsor up. + console.error('[sponsor] GitHub sponsorship query failed:', err instanceof Error ? err.message : 'unknown error') + return finish('error') + } + if (!isSponsor) { + console.info('[sponsor] account linked, no valid sponsorship') + return finish('linked_no_sponsorship') + } + + const granted = await grantSponsorRole({ + botToken: config.botToken, guildId: config.guildId, roleId: config.roleId, discordUserId: discordId, + }) + if (!granted) { + console.warn('[sponsor] account linked and sponsorship valid, but the Discord role grant failed') + return finish('role_failed') + } + console.info('[sponsor] account linked, sponsor role granted') + return finish('granted') +} diff --git a/app/api/sponsor/members/route.ts b/app/api/sponsor/members/route.ts new file mode 100644 index 0000000..9036f57 --- /dev/null +++ b/app/api/sponsor/members/route.ts @@ -0,0 +1,67 @@ +import { NextResponse } from 'next/server' + +import { bearerMatches, readSponsorConfig, readSyncSecret } from '@/lib/sponsorLink' +import { listSponsorLinks } from '@/lib/sponsorLinks' +import { currentSponsors } from '@/lib/sponsors' + +// The list the Discord bot reconciles the sponsor role against once a day: +// every linked Discord user whose GitHub account has a valid sponsorship right +// now. Auth: `Authorization: Bearer `, constant-time. +// +// Any failure answers `{ ok: false }` with a non-200 status, and the bot then +// changes nothing. An empty list on a failed GitHub query would read as +// "nobody sponsors" and strip the role from everyone. + +export const dynamic = 'force-dynamic' + +const NO_STORE = { 'Cache-Control': 'no-store' } + +export async function GET(req: Request) { + const secret = readSyncSecret() + if (!secret) { + console.error('[sponsor] members endpoint disabled, SPONSOR_SYNC_SECRET missing or shorter than 32 chars') + return NextResponse.json({ ok: false }, { status: 503, headers: NO_STORE }) + } + if (!bearerMatches(req.headers.get('authorization'), secret)) { + return NextResponse.json({ ok: false }, { status: 401, headers: NO_STORE }) + } + + const cfg = readSponsorConfig() + if (!cfg.ok) { + console.error(`[sponsor] members endpoint disabled, missing or invalid env: ${cfg.missing.join(', ')}`) + return NextResponse.json({ ok: false }, { status: 503, headers: NO_STORE }) + } + + let sponsors + try { + sponsors = await currentSponsors({ token: cfg.config.sponsorsToken, org: cfg.config.githubOrg }) + } catch (err) { + console.error('[sponsor] GitHub sponsorship query failed:', err instanceof Error ? err.message : 'unknown error') + return NextResponse.json({ ok: false }, { status: 502, headers: NO_STORE }) + } + + let links + try { + links = await listSponsorLinks() + } catch (err) { + console.error('[sponsor] reading sponsor links failed:', err instanceof Error ? err.message : 'unknown error') + return NextResponse.json({ ok: false }, { status: 500, headers: NO_STORE }) + } + + const members = links.flatMap(link => { + const grant = sponsors.get(link.githubUserId) + if (!grant) return [] + return [{ + discordId: link.discordUserId, + // GitHub's current login, the stored one may predate a rename. + githubLogin: grant.login || link.githubLogin || '', + kind: grant.kind, + validUntil: grant.validUntil ? grant.validUntil.toISOString() : null, + }] + }) + + return NextResponse.json( + { ok: true, generatedAt: new Date().toISOString(), members }, + { headers: NO_STORE }, + ) +} diff --git a/app/api/sponsor/start/route.ts b/app/api/sponsor/start/route.ts new file mode 100644 index 0000000..89ea120 --- /dev/null +++ b/app/api/sponsor/start/route.ts @@ -0,0 +1,56 @@ +import { NextResponse } from 'next/server' + +import { getClientIp, rateLimit } from '@/lib/rateLimit' +import { publicPath } from '@/lib/routes' +import { getPreferredLang } from '@/lib/serverLang' +import { absoluteUrl, siteUrl } from '@/lib/siteUrl' +import { + SPONSOR_STATE_COOKIE, SPONSOR_STATE_TTL_S, newOAuthState, readSponsorConfig, signStateCookie, + verifyLinkToken, type SponsorStatus, +} from '@/lib/sponsorLink' + +// Entry of the GitHub Sponsors verification. The Discord bot hands a member a +// signed, personal link to this route (contract in lib/sponsorLink.ts). We +// check it, remember the Discord user in a short-lived signed cookie together +// with the OAuth state, and send the browser to GitHub. No scope is requested: +// the public identity (id and login) is all we need, the sponsorship itself is +// read with the org's own token. + +export async function GET(req: Request) { + const lang = await getPreferredLang() + const result = (status: SponsorStatus) => + NextResponse.redirect(absoluteUrl(publicPath(lang, `/sponsor/verify?status=${status}`))) + + if (!rateLimit(`sponsor-start:${getClientIp(req)}`, { limit: 10, windowMs: 10 * 60_000 })) { + return result('rate_limited') + } + + const cfg = readSponsorConfig() + if (!cfg.ok) { + console.error(`[sponsor] feature disabled, missing or invalid env: ${cfg.missing.join(', ')}`) + return result('error') + } + const { config } = cfg + + const token = new URL(req.url).searchParams.get('t') + const link = verifyLinkToken(token, { secret: config.linkSecret, guildId: config.guildId }) + if (!link) return result('link_invalid') + + const state = newOAuthState() + const params = new URLSearchParams({ + client_id: config.clientId, + redirect_uri: `${siteUrl()}/api/sponsor/callback`, + state, + allow_signup: 'true', + }) + + const res = NextResponse.redirect(`https://github.com/login/oauth/authorize?${params.toString()}`) + res.cookies.set(SPONSOR_STATE_COOKIE, signStateCookie({ discordId: link.discordId, state }, config.linkSecret), { + httpOnly: true, + secure: true, + sameSite: 'lax', + maxAge: SPONSOR_STATE_TTL_S, + path: '/api/sponsor', + }) + return res +} diff --git a/tests/routeGuards.test.ts b/tests/routeGuards.test.ts index 911351a..591180c 100644 --- a/tests/routeGuards.test.ts +++ b/tests/routeGuards.test.ts @@ -51,9 +51,11 @@ const GUARDS: Array<{ name: string; pattern: RegExp }> = [ // The bot's API key: the guild is derived from the key, never from the body { name: 'apiKey', pattern: /\bextractApiKey\s*\(|WHERE\s+api_key\s*=\s*\?/ }, // Signed verify/dashboard/giveaway session from the cookie - { name: 'signedSession', pattern: callOf('parseSession', 'parseDashboardSession', 'parseGiveawaySession', 'parseUploadSession') }, + // (readStateCookie: the GitHub Sponsors OAuth state, signed with SPONSOR_LINK_SECRET) + { name: 'signedSession', pattern: callOf('parseSession', 'parseDashboardSession', 'parseGiveawaySession', 'parseUploadSession', 'readStateCookie') }, // The bot's shared secret, compared in constant time - { name: 'sharedSecret', pattern: callOf('timingSafeEqual') }, + // (bearerMatches: lib/sponsorLink.ts, timingSafeEqual behind it) + { name: 'sharedSecret', pattern: callOf('timingSafeEqual', 'bearerMatches') }, // OAuth return channel: code exchange + state check, signing only happens afterwards { name: 'oauthCallback', pattern: callOf('signAdminSession', 'signSession', 'signDashboardSession', 'signGiveawaySession') }, // Stripe webhook: signature check against STRIPE_WEBHOOK_SECRET diff --git a/tests/sponsors.test.ts b/tests/sponsors.test.ts new file mode 100644 index 0000000..2f580d5 --- /dev/null +++ b/tests/sponsors.test.ts @@ -0,0 +1,281 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +/** + * GitHub Sponsors -> Discord role. + * + * What must hold: + * - only a link token signed with SPONSOR_LINK_SECRET, unexpired and for our + * guild starts the GitHub sign-in (the bot implements the same contract); + * - the validity rule: monthly while active, one-time for 30 days, at least + * $5, users only, the best of several sponsorships; + * - the members list is only handed out against the sync secret, and a + * failed GitHub query never reads as an empty list. + */ + +vi.mock('@/lib/db', () => ({ query: vi.fn(async () => []), queryOne: vi.fn(async () => null), withTransaction: vi.fn() })) + +import { GET as membersGET } from '@/app/api/sponsor/members/route' +import { query } from '@/lib/db' +import { + bearerMatches, parseSponsorStatus, readSponsorConfig, readStateCookie, signLinkToken, signStateCookie, + verifyLinkToken, type LinkPayload, +} from '@/lib/sponsorLink' +import { evaluateSponsorships, type SponsorshipNode } from '@/lib/sponsors' + +const SECRET = 'l'.repeat(40) +const SYNC = 's'.repeat(40) +const GUILD = '111111111111111111' +const USER = '400000000000000001' +const NOW = Date.parse('2026-11-05T12:00:00Z') +const DAY = 24 * 60 * 60 * 1000 + +function payload(over: Partial = {}): LinkPayload { + return { v: 1, d: USER, g: GUILD, exp: Math.floor(NOW / 1000) + 900, n: 'a1b2c3d4', ...over } +} + +describe('link token', () => { + const verify = (t: string | null) => verifyLinkToken(t, { secret: SECRET, guildId: GUILD, nowMs: NOW }) + + it('accepts a valid token and returns the Discord user', () => { + expect(verify(signLinkToken(payload(), SECRET))).toEqual({ discordId: USER }) + }) + + it('matches the contract byte for byte (prefix, base64url, HMAC-SHA256)', async () => { + const { createHmac } = await import('crypto') + const b64 = Buffer.from(JSON.stringify(payload())).toString('base64url') + const sig = createHmac('sha256', SECRET).update('sponsor-link.' + b64).digest('base64url') + expect(verify(`${b64}.${sig}`)).toEqual({ discordId: USER }) + }) + + it('rejects a tampered payload', () => { + const [, sig] = signLinkToken(payload(), SECRET).split('.') + const forged = Buffer.from(JSON.stringify(payload({ d: '400000000000000002' }))).toString('base64url') + expect(verify(`${forged}.${sig}`)).toBeNull() + }) + + it('rejects a tampered signature and a foreign secret', () => { + const token = signLinkToken(payload(), SECRET) + expect(verify(token.slice(0, -2) + (token.endsWith('AA') ? 'BB' : 'AA'))).toBeNull() + expect(verify(signLinkToken(payload(), 'x'.repeat(40)))).toBeNull() + }) + + it('rejects an expired token', () => { + expect(verify(signLinkToken(payload({ exp: Math.floor(NOW / 1000) - 1 }), SECRET))).toBeNull() + expect(verify(signLinkToken(payload({ exp: Math.floor(NOW / 1000) }), SECRET))).toBeNull() + }) + + it('rejects a token for another guild', () => { + expect(verify(signLinkToken(payload({ g: '222222222222222222' }), SECRET))).toBeNull() + }) + + it('rejects a wrong version, non-snowflake ids and garbage', () => { + expect(verify(signLinkToken({ ...payload(), v: 2 } as unknown as LinkPayload, SECRET))).toBeNull() + expect(verify(signLinkToken(payload({ d: '123' }), SECRET))).toBeNull() + expect(verify(signLinkToken(payload({ d: `${USER}\n` }), SECRET))).toBeNull() + expect(verify(null)).toBeNull() + expect(verify('nodot')).toBeNull() + expect(verify('.sig')).toBeNull() + }) +}) + +describe('state cookie', () => { + it('round-trips and expires after ten minutes', () => { + const c = signStateCookie({ discordId: USER, state: 'f'.repeat(32) }, SECRET, NOW) + expect(readStateCookie(c, SECRET, NOW + 60_000)).toEqual({ discordId: USER, state: 'f'.repeat(32) }) + expect(readStateCookie(c, SECRET, NOW + 10 * 60_000)).toBeNull() + }) + + it('is not interchangeable with a link token', () => { + expect(readStateCookie(signLinkToken(payload(), SECRET), SECRET, NOW)).toBeNull() + const c = signStateCookie({ discordId: USER, state: 'f'.repeat(32) }, SECRET, NOW) + expect(verifyLinkToken(c, { secret: SECRET, guildId: GUILD, nowMs: NOW })).toBeNull() + }) +}) + +describe('config', () => { + const full = { + SPONSOR_LINK_SECRET: SECRET, GITHUB_SPONSOR_CLIENT_ID: 'id', GITHUB_SPONSOR_CLIENT_SECRET: 'cs', + GITHUB_SPONSORS_TOKEN: 'tok', SPONSOR_DISCORD_BOT_TOKEN: 'bot', SPONSOR_GUILD_ID: GUILD, SPONSOR_ROLE_ID: USER, + } + + it('is complete with all variables and defaults the org', () => { + const r = readSponsorConfig(full) + expect(r.ok && r.config.githubOrg).toBe('MSK-Scripts') + }) + + it('fails closed on a short secret or a missing variable, naming them without values', () => { + const r = readSponsorConfig({ ...full, SPONSOR_LINK_SECRET: 'short', SPONSOR_DISCORD_BOT_TOKEN: '' }) + expect(r.ok).toBe(false) + if (!r.ok) { + expect(r.missing.join()).toContain('SPONSOR_LINK_SECRET') + expect(r.missing.join()).toContain('SPONSOR_DISCORD_BOT_TOKEN') + expect(r.missing.join()).not.toContain('short') + } + }) +}) + +describe('result status', () => { + it('passes known statuses and turns anything else into error', () => { + expect(parseSponsorStatus('granted')).toBe('granted') + expect(parseSponsorStatus('