Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,34 @@ MAIL_FROM="MSK Scripts <noreply@msk-scripts.de>"
DISCORD_VERIFY_CLIENT_ID=your_discord_oauth_client_id
DISCORD_VERIFY_CLIENT_SECRET=your_discord_oauth_client_secret

# ── GitHub Sponsors -> Discord "Sponsor" role ─────────────────────────────────
# The Discord bot (discord_multibot) hands a member a signed personal link to
# /api/sponsor/start. The shop links the Discord user to their GitHub account
# (GitHub OAuth, no scope), checks the sponsorship of the org and grants the role
# right away. The bot reconciles the role daily against /api/sponsor/members.
# Until ALL of these are set (secrets at least 32 chars, ids as snowflakes) the
# feature stays off and every request logs which variable is missing.
#
# Shared with the bot. LINK signs the Verify link (HMAC-SHA256), SYNC is the
# Bearer for /api/sponsor/members. Generate each with: openssl rand -hex 32
SPONSOR_LINK_SECRET=
SPONSOR_SYNC_SECRET=
# GitHub OAuth app (github.com/organizations/MSK-Scripts/settings/applications).
# Authorization callback URL: https://www.msk-scripts.de/api/sponsor/callback
GITHUB_SPONSOR_CLIENT_ID=
GITHUB_SPONSOR_CLIENT_SECRET=
# Classic personal access token of an OWNER of the org with the scopes read:org
# and read:user (isActive, isOneTimePayment, createdAt and tierSelectedAt need it).
# Only an org owner sees the org's sponsorships including private ones; a weaker
# token returns a short list rather than an error.
GITHUB_SPONSORS_TOKEN=
# Sponsorable org login, defaults to MSK-Scripts.
SPONSOR_GITHUB_ORG=MSK-Scripts
# Bot token with "Manage Roles"; its highest role must sit above the Sponsor role.
SPONSOR_DISCORD_BOT_TOKEN=
SPONSOR_GUILD_ID=
SPONSOR_ROLE_ID=

# ── Giveaway Web-Dashboard (bot control endpoint) ─────────────────────────────
# The giveaway bot exposes a localhost-only HTTP control endpoint. The dashboard
# proxies management actions to it. SECRET must match the bot's CONTROL_SECRET.
Expand Down
68 changes: 68 additions & 0 deletions app/[lang]/(site)/sponsor/verify/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import type { Metadata } from 'next'

import { ArrowRight } from '@/components/icons'
import { PageHead } from '@/components/page/PageHead'
import { SITE_CONFIG } from '@/lib/config'
import { packagesTranslations, sponsorTranslations } from '@/lib/i18n'
import { pageSeo } from '@/lib/pageSeo'
import { getRequestLang } from '@/lib/serverLang'
import { parseSponsorStatus } from '@/lib/sponsorLink'

const SPONSORS_URL = 'https://github.com/sponsors/MSK-Scripts'

/**
* noindex and no `alternates`: the page only ever shows the outcome of the
* GitHub Sponsors verification that the Discord bot starts, see
* app/api/sponsor/*. Without a status it reads as an error.
*/
export async function generateMetadata(): Promise<Metadata> {
const { lang } = await getRequestLang()
const seo = pageSeo('/sponsor/verify', lang)
return {
title: seo.title,
description: seo.description,
robots: { index: false, follow: false },
}
}

/** `/en/sponsor/verify`, `/de/sponsor/verifizieren`: one short text per status. */
export default async function SponsorVerifyPage({
searchParams,
}: {
searchParams: Promise<Record<string, string | string[] | undefined>>
}) {
const { lang } = await getRequestLang()
const { status: raw } = await searchParams
const status = parseSponsorStatus(raw)
const t = sponsorTranslations[lang]
const tp = packagesTranslations[lang]

const link = 'flex min-h-11 items-center justify-between gap-3 border-b border-[var(--color-border)] py-2 font-semibold hover:text-[var(--color-primary)]'
const links = [
// Someone who is already a sponsor does not need the way to become one.
...(status === 'granted' ? [] : [{ href: SPONSORS_URL, label: t.sponsor_link }]),
{ href: SITE_CONFIG.discord, label: t.discord_link },
]

return (
<div className="container-page grid gap-[var(--space-section)] pb-[var(--space-section)] pt-[clamp(1rem,0.5rem+1.5vw,3rem)]">
<PageHead
id="sponsor-title"
crumbs={[{ label: tp.breadcrumb_home, href: '/' }, { label: t.breadcrumb }]}
title={t[`${status}_title`]}
lead={t[`${status}_text`]}
/>

<ul className="grid max-w-[34rem] border-t border-[var(--color-border)]">
{links.map(l => (
<li key={l.href}>
<a href={l.href} target="_blank" rel="noopener noreferrer" className={link}>
{l.label}
<ArrowRight className="h-5 w-5 shrink-0 text-[var(--color-primary)]" />
</a>
</li>
))}
</ul>
</div>
)
}
133 changes: 133 additions & 0 deletions app/api/sponsor/callback/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
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_OAUTH_STATE_COOKIE, 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 cookie (CSRF), and the signed
// cookie names the Discord user; both cookies are 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}`)))
for (const name of [SPONSOR_STATE_COOKIE, SPONSOR_OAUTH_STATE_COOKIE]) {
res.cookies.set(name, '', { 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 jar = await cookies()
const saved = readStateCookie(jar.get(SPONSOR_STATE_COOKIE)?.value, config.linkSecret)
const expectedState = jar.get(SPONSOR_OAUTH_STATE_COOKIE)?.value
if (!code || !state || !saved || !expectedState || !safeEqual(state, expectedState)) {
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')
}
67 changes: 67 additions & 0 deletions app/api/sponsor/members/route.ts
Original file line number Diff line number Diff line change
@@ -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 <SPONSOR_SYNC_SECRET>`, 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 },
)
}
58 changes: 58 additions & 0 deletions app/api/sponsor/start/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
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_OAUTH_STATE_COOKIE, 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()}`)
const cookieOptions = {
httpOnly: true,
secure: true,
sameSite: 'lax',
maxAge: SPONSOR_STATE_TTL_S,
path: '/api/sponsor',
} as const
res.cookies.set(SPONSOR_STATE_COOKIE, signStateCookie({ discordId: link.discordId }, config.linkSecret), cookieOptions)
res.cookies.set(SPONSOR_OAUTH_STATE_COOKIE, state, cookieOptions)
return res
}
1 change: 1 addition & 0 deletions app/robots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const BLOCKED = [
'/cart',
'/checkout',
'/login',
'/sponsor/verify',
'/auth/',
'/botproxy',
'/dashboard/',
Expand Down
2 changes: 1 addition & 1 deletion content/legal/avv-de.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

gemäß Art. 28 Abs. 3 DSGVO

Stand: Oktober 2026
Stand: November 2026

Diese Vereinbarung wird Vertragsbestandteil, sobald du als Betreiber eines Discord-Servers den **Ticket-Bot-Transcript-Service**, das **Hosted Bot Management** oder **MSK Forms** aktivierst („Auftraggeber“, „du“). Auftragsverarbeiter ist Moritz Kohm, MSK Scripts, Hauptstraße 103, 68535 Edingen-Neckarhausen („MSK Scripts“, „wir“). Du kannst diese Vereinbarung jederzeit unter https://www.msk-scripts.de/de/rechtliches/avv abrufen und für deine Unterlagen speichern.

Expand Down
2 changes: 1 addition & 1 deletion content/legal/avv.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

pursuant to Art. 28 (3) GDPR

Last updated: October 2026
Last updated: November 2026

This agreement becomes part of the contract as soon as you, as the operator of a Discord server, activate the **Ticket Bot transcript service**, **Hosted Bot Management** or **MSK Forms** ("controller", "you"). The processor is Moritz Kohm, MSK Scripts, Hauptstraße 103, 68535 Edingen-Neckarhausen ("MSK Scripts", "we"). You can access this agreement at any time at https://www.msk-scripts.de/en/legal/dpa and save it for your records.

Expand Down
2 changes: 1 addition & 1 deletion content/legal/imprint-de.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,4 @@ Der Nutzung der hier veröffentlichten Kontaktdaten zur Übersendung nicht ausdr

---

*Stand: Oktober 2026*
*Stand: November 2026*
Loading
Loading