From 1b58d2c363a0a876ab8a82d36fefb4b34b7cf303 Mon Sep 17 00:00:00 2001 From: gunshiz Date: Sat, 25 Jul 2026 23:43:55 +0700 Subject: [PATCH] feat(form) : force user to join discord server --- lib/auth-options.ts | 13 +++++++++ lib/discord.test.ts | 71 +++++++++++++++++++++++++++++++++++++++++++++ lib/discord.ts | 43 +++++++++++++++++++++++++-- 3 files changed, 124 insertions(+), 3 deletions(-) create mode 100644 lib/discord.test.ts diff --git a/lib/auth-options.ts b/lib/auth-options.ts index 80ce9cc..d37e87a 100644 --- a/lib/auth-options.ts +++ b/lib/auth-options.ts @@ -4,6 +4,7 @@ import { DrizzleAdapter } from "@auth/drizzle-adapter"; import { db } from "@/db"; import { accounts, sessions, users, verificationTokens } from "@/db/schema"; import type { SessionWithDiscord } from "@/lib/auth"; +import { addDiscordGuildMember } from "@/lib/discord"; const discordIdCache = new Map(); @@ -18,9 +19,21 @@ export const authOptions: NextAuthOptions = { DiscordProvider({ clientId: process.env.DISCORD_CLIENT_ID!, clientSecret: process.env.DISCORD_CLIENT_SECRET!, + authorization: { + params: { + scope: "identify email guilds.join", + }, + }, }), ], callbacks: { + async signIn({ account }) { + if (account?.provider === "discord" && account.providerAccountId && account.access_token) { + await addDiscordGuildMember(account.providerAccountId, account.access_token); + } + + return true; + }, async session({ session, user }) { if (session.user) { (session as SessionWithDiscord).user!.id = user.id; diff --git a/lib/discord.test.ts b/lib/discord.test.ts new file mode 100644 index 0000000..89f7114 --- /dev/null +++ b/lib/discord.test.ts @@ -0,0 +1,71 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { addDiscordGuildMember } from "@/lib/discord"; + +const originalFetch = globalThis.fetch; +const originalBotToken = process.env.DISCORD_BOT_TOKEN; +const originalGuildId = process.env.DISCORD_GUILD_ID; + +afterEach(() => { + globalThis.fetch = originalFetch; + if (originalBotToken === undefined) { + delete process.env.DISCORD_BOT_TOKEN; + } else { + process.env.DISCORD_BOT_TOKEN = originalBotToken; + } + if (originalGuildId === undefined) { + delete process.env.DISCORD_GUILD_ID; + } else { + process.env.DISCORD_GUILD_ID = originalGuildId; + } +}); + +function mockFetch(handler: (input: RequestInfo | URL, init?: RequestInit) => Promise) { + globalThis.fetch = handler as unknown as typeof fetch; +} + +describe("Discord guild member join", () => { + test("adds a member with the OAuth access token", async () => { + process.env.DISCORD_BOT_TOKEN = "bot-token"; + process.env.DISCORD_GUILD_ID = "guild-1"; + + mockFetch(async (input, init) => { + expect(input).toBe("https://discord.com/api/v10/guilds/guild-1/members/user-1"); + expect(init?.method).toBe("PUT"); + expect(init?.headers).toEqual({ + Authorization: "Bot bot-token", + "Content-Type": "application/json", + }); + expect(init?.body).toBe(JSON.stringify({ access_token: "oauth-token" })); + + return new Response(null, { status: 204 }); + }); + + await expect(addDiscordGuildMember("user-1", "oauth-token")).resolves.toBeTrue(); + }); + + test("uses the configured Erika guild by default", async () => { + process.env.DISCORD_BOT_TOKEN = "bot-token"; + delete process.env.DISCORD_GUILD_ID; + + mockFetch(async (input) => { + expect(input).toBe("https://discord.com/api/v10/guilds/1302977523310923847/members/user-1"); + return new Response(null, { status: 201 }); + }); + + await expect(addDiscordGuildMember("user-1", "oauth-token")).resolves.toBeTrue(); + }); + + test("does not call Discord when tokens are missing", async () => { + delete process.env.DISCORD_BOT_TOKEN; + process.env.DISCORD_GUILD_ID = "guild-1"; + + let called = false; + mockFetch(async () => { + called = true; + return new Response(null, { status: 204 }); + }); + + await expect(addDiscordGuildMember("user-1", "oauth-token")).resolves.toBeFalse(); + expect(called).toBeFalse(); + }); +}); diff --git a/lib/discord.ts b/lib/discord.ts index b77c5a0..ef6b825 100644 --- a/lib/discord.ts +++ b/lib/discord.ts @@ -23,18 +23,55 @@ interface CacheEntry { const rolesCache: { entry: CacheEntry | null } = { entry: null }; const profileCache = new Map>(); const CACHE_TTL = 60_000; +const DEFAULT_DISCORD_GUILD_ID = "1302977523310923847"; function getCached(entry: CacheEntry | null | undefined): T | null { if (entry && Date.now() < entry.expiresAt) return entry.data; return null; } +function getDiscordGuildId() { + return process.env.DISCORD_GUILD_ID || DEFAULT_DISCORD_GUILD_ID; +} + +export async function addDiscordGuildMember(discordId: string, accessToken: string): Promise { + const token = process.env.DISCORD_BOT_TOKEN; + const guildId = getDiscordGuildId(); + if (!token || !guildId || !discordId || !accessToken) return false; + + try { + const res = await fetch( + `https://discord.com/api/v10/guilds/${encodeURIComponent(guildId)}/members/${encodeURIComponent(discordId)}`, + { + method: "PUT", + headers: { + Authorization: `Bot ${token}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ access_token: accessToken }), + signal: AbortSignal.timeout(5000), + }, + ); + + if (res.status === 201 || res.status === 204) return true; + + const body = await res.text().catch(() => ""); + console.error( + `Failed to add Discord member ${discordId} to guild ${guildId}: ${res.status}${body ? ` ${body.slice(0, 300)}` : ""}`, + ); + return false; + } catch (error) { + console.error(`Failed to add Discord member ${discordId} to guild ${guildId}`, error); + return false; + } +} + export async function getGuildRolesInternal(): Promise { const cached = getCached(rolesCache.entry); if (cached) return cached; const token = process.env.DISCORD_BOT_TOKEN; - const guildId = process.env.DISCORD_GUILD_ID; + const guildId = getDiscordGuildId(); if (!token || !guildId) return []; try { @@ -69,7 +106,7 @@ export async function getGuildRolesInternal(): Promise { export async function getGuildMemberRoles(discordId: string): Promise { const token = process.env.DISCORD_BOT_TOKEN; - const guildId = process.env.DISCORD_GUILD_ID; + const guildId = getDiscordGuildId(); if (!token || !guildId || !discordId) return []; try { @@ -93,7 +130,7 @@ export async function getDiscordMemberProfile(discordId: string): Promise