feat(discord): self-serve server->org linking with /drb link (#213 item 1)
- c2-core: POST /discord/link-codes (org owner/admin) mints a single-use,
10-minute code; minting revokes the org's older codes. The bot redeems it
via POST /discord/guilds/{id}/link/redeem (service key) inside one
Firestore transaction, so two servers racing for one code cannot both win
and a server linked to org A refuses org B's code. GET/DELETE
/discord/linked-guilds lists/unlinks the caller's org's servers; unlink
stops that server's streams. Rate-limited (mint per user, redeem per
server and per Discord user); every mint/link/refusal/unlink audited.
- resolve_guild_org: an explicitly unlinked server no longer falls back to
DISCORD_UNLINKED_GUILD_ORG_ID. Linking away from the fallback org stops
the streams it had running for that org.
- Discord bot: /drb link code: (Manage Server, enforced at runtime too);
GatedTree answers every other command in an unlinked server with how to
link (autocomplete returns nothing). With the default fallback org set,
nothing is gated — unchanged behaviour.
- Frontend: "Linked Discord servers" card on Settings -> Organization —
generate code with countdown + copy, polls for the new link, unlink.
- 16 tests: single-use, two-server race, one-server/two-org race, expiry,
revoked/malformed codes, wrong-org takeover, idempotent relink, rate
limits, fallback stop, scoped list, unlink without fallback.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
dc1df72c86
commit
455c55f5c2
@@ -2,16 +2,19 @@ import asyncio
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
from app.config import settings
|
||||
from app.internal.guild_gate import GatedTree
|
||||
from app.internal.logger import logger
|
||||
|
||||
|
||||
class DRBBot(commands.Bot):
|
||||
def __init__(self):
|
||||
intents = discord.Intents.default()
|
||||
super().__init__(command_prefix="!", intents=intents)
|
||||
# GatedTree: unlinked servers get only /drb link and /help (server-26#213).
|
||||
super().__init__(command_prefix="!", intents=intents, tree_cls=GatedTree)
|
||||
|
||||
async def setup_hook(self):
|
||||
await self.load_extension("app.commands.radio")
|
||||
await self.load_extension("app.commands.drb")
|
||||
await self.load_extension("app.commands.trips")
|
||||
|
||||
if settings.dev_guild_id:
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"""/drb — server-level DRB setup. Today: /drb link (server-26#213 item 1)."""
|
||||
import discord
|
||||
from discord import app_commands
|
||||
from discord.ext import commands
|
||||
|
||||
from app.internal import guild_gate
|
||||
from app.internal.c2_client import c2
|
||||
|
||||
|
||||
class DRBCommands(commands.Cog):
|
||||
drb = app_commands.Group(
|
||||
name="drb",
|
||||
description="Set up DRB in this server.",
|
||||
guild_only=True,
|
||||
default_permissions=discord.Permissions(manage_guild=True),
|
||||
)
|
||||
|
||||
def __init__(self, bot: commands.Bot):
|
||||
self.bot = bot
|
||||
|
||||
@drb.command(name="link", description="Link this server to your DRB organization.")
|
||||
@app_commands.describe(code="The code from DRB → Settings → Organization → Discord servers.")
|
||||
async def link(self, interaction: discord.Interaction, code: str):
|
||||
await interaction.response.defer(ephemeral=True)
|
||||
# default_permissions is only the default — a server admin can grant
|
||||
# the command to anyone under Integrations. Linking decides which
|
||||
# organization's radio this whole server gets, so hold the line here.
|
||||
perms = getattr(interaction.user, "guild_permissions", None)
|
||||
if not perms or not perms.manage_guild:
|
||||
await interaction.followup.send("Only members with **Manage Server** can link this server.",
|
||||
ephemeral=True)
|
||||
return
|
||||
ok, body = await c2.redeem_guild_link(
|
||||
interaction.guild_id, code, str(interaction.user.id),
|
||||
interaction.guild.name if interaction.guild else None,
|
||||
)
|
||||
guild_gate.forget(interaction.guild_id)
|
||||
radio = self.bot.get_cog("RadioCommands")
|
||||
if radio is not None:
|
||||
radio._overview.pop(interaction.guild_id, None)
|
||||
if not ok:
|
||||
await interaction.followup.send(body.get("detail") or "DRB could not link this server.",
|
||||
ephemeral=True)
|
||||
return
|
||||
org = body.get("org_name") or "your DRB organization"
|
||||
if body.get("already_linked"):
|
||||
text = f"This server was already linked to **{org}**. Nothing changed."
|
||||
else:
|
||||
text = (f"This server is now linked to **{org}**.\n"
|
||||
"`/join`, `/leave` and `/status` now act for that organization only.")
|
||||
await interaction.followup.send(text, ephemeral=True)
|
||||
|
||||
|
||||
async def setup(bot: commands.Bot):
|
||||
await bot.add_cog(DRBCommands(bot))
|
||||
@@ -226,6 +226,15 @@ class RadioCommands(commands.Cog):
|
||||
@app_commands.command(name="help", description="How to use this bot.")
|
||||
async def help(self, interaction: discord.Interaction):
|
||||
embed = discord.Embed(title="DRB Radio Bot — Help", color=0x5865f2)
|
||||
embed.add_field(
|
||||
name="/drb link `code`",
|
||||
value=(
|
||||
"Link this server to your DRB organization — needed before anything below works. "
|
||||
"An organization owner gets the code in DRB under Settings → Organization → Discord servers; "
|
||||
"someone with Manage Server runs this."
|
||||
),
|
||||
inline=False,
|
||||
)
|
||||
embed.add_field(
|
||||
name="/join `system` [`bot`] [`persistent`]",
|
||||
value=(
|
||||
|
||||
@@ -68,6 +68,28 @@ class C2Client:
|
||||
logger.error(f"C2 stop_guild failed: {e}")
|
||||
return None
|
||||
|
||||
async def redeem_guild_link(self, guild_id: int | str, code: str, discord_user_id: str,
|
||||
guild_name: Optional[str]) -> tuple[bool, dict]:
|
||||
"""/drb link code: (server-26#213). Returns (ok, body); a refusal body
|
||||
carries C2's own ``detail`` text, which is written for the end user."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
r = await client.post(
|
||||
f"{self.base}/discord/guilds/{guild_id}/link/redeem",
|
||||
json={"code": code, "discord_user_id": discord_user_id, "guild_name": guild_name},
|
||||
headers=self._headers(),
|
||||
)
|
||||
body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}
|
||||
if r.status_code == 429:
|
||||
return False, {"detail": "Too many link attempts from this server. Wait ten minutes "
|
||||
"and try again.", "code": "rate_limited"}
|
||||
if r.status_code >= 400:
|
||||
return False, body if isinstance(body, dict) else {"detail": str(body)}
|
||||
return True, body
|
||||
except Exception as e:
|
||||
logger.error(f"C2 redeem_guild_link failed: {e}")
|
||||
return False, {"detail": "Could not reach DRB. Try again in a minute.", "code": "c2_unreachable"}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Trips
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
Unlinked servers see only /drb link and /help (server-26#213).
|
||||
|
||||
Discord registers slash commands globally, so an unlinked server still lists
|
||||
the others in its command picker; this gate answers them with how to link
|
||||
instead of running them. Per-guild command sync would hide them outright but
|
||||
costs one sync per server per change — not worth it while C2 refuses every
|
||||
unlinked request anyway (this gate is UX, C2 is the enforcement).
|
||||
|
||||
Whether a server is "linked" is C2's answer: its own discord_guilds link, or
|
||||
DISCORD_UNLINKED_GUILD_ORG_ID when that is set — so with the default
|
||||
("founding") nothing is gated, exactly as before.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
import discord
|
||||
from discord import app_commands
|
||||
|
||||
from app.internal.c2_client import c2
|
||||
from app.internal.logger import logger
|
||||
|
||||
ALWAYS_ALLOWED = frozenset({"drb link", "help"})
|
||||
LINKED_TTL = 60.0
|
||||
UNLINKED_TTL = 10.0 # short, so a fresh /drb link (or a web-side link) shows up fast
|
||||
|
||||
UNLINKED_TEXT = (
|
||||
"This server is not linked to a DRB organization yet.\n"
|
||||
"An owner of the DRB organization generates a code under **Settings → Organization → Discord servers**; "
|
||||
"then someone with **Manage Server** here runs `/drb link code:<code>`."
|
||||
)
|
||||
|
||||
_cache: dict[int, tuple[float, bool]] = {}
|
||||
|
||||
|
||||
async def is_linked(guild_id: int) -> Optional[bool]:
|
||||
"""True/False from C2, or None when C2 could not be reached."""
|
||||
hit = _cache.get(guild_id)
|
||||
if hit and time.monotonic() < hit[0]:
|
||||
return hit[1]
|
||||
data = await c2.guild_overview(guild_id)
|
||||
if data.get("error"):
|
||||
return None
|
||||
linked = bool(data.get("org_id"))
|
||||
_cache[guild_id] = (time.monotonic() + (LINKED_TTL if linked else UNLINKED_TTL), linked)
|
||||
return linked
|
||||
|
||||
|
||||
def forget(guild_id: int) -> None:
|
||||
_cache.pop(guild_id, None)
|
||||
|
||||
|
||||
class GatedTree(app_commands.CommandTree):
|
||||
async def interaction_check(self, interaction: discord.Interaction) -> bool:
|
||||
if interaction.guild_id is None:
|
||||
return True
|
||||
if interaction.type not in (discord.InteractionType.application_command,
|
||||
discord.InteractionType.autocomplete):
|
||||
return True
|
||||
cmd = interaction.command
|
||||
if cmd is not None and cmd.qualified_name in ALWAYS_ALLOWED:
|
||||
return True
|
||||
# None = C2 unreachable: let the command run and report that itself.
|
||||
if await is_linked(interaction.guild_id) is not False:
|
||||
return True
|
||||
try:
|
||||
if interaction.type is discord.InteractionType.autocomplete:
|
||||
await interaction.response.autocomplete([])
|
||||
else:
|
||||
await interaction.response.send_message(UNLINKED_TEXT, ephemeral=True)
|
||||
except discord.HTTPException as e:
|
||||
logger.warning(f"unlinked-guild reply failed: {e}")
|
||||
return False
|
||||
Reference in New Issue
Block a user