Feature/discord plugin (#54)

* Add exp_discord plugin for Discord login and account linking

Players log in to the web interface with Discord through OAuth2 with the
identify scope, so no bot token is needed. After logging in they get a
code from the login page and type /link-discord <code> in game to link
that Factorio account. One Discord account can hold up to
exp_discord.max_accounts Factorio accounts (default 3), and linking a
name moves it off any other Discord account.

Sessions and link codes live in memory on the controller plugin, the
links are stored in database/exp_discord/accounts.json. The user page
shows the linked Discord account and lets the user, or anyone with
exp_discord.link.delete, unlink it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Link Discord from the user page and document the setup

The user page gets a Link Discord button. It asks the controller for a
one-time ticket bound to the logged in user, then goes through the
authorize route with it. The callback links the Discord account to that
user directly, without the in-game code, and goes back to the user page.
The link flow always shows the Discord consent screen.

The README covers registering the redirect URL and the config.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: bbassie <17990055+bbassie@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-10-12 14:05:15 +09:00
1 parent 2dfbf970df
commit 0c593cd9fe
22 files changed
+1674

No files matched your search

@@ -0,0 +1,161 @@
import React, { useEffect, useRef, useState } from "react";
import { Alert, Button, Space, Spin, Typography } from "antd";
declare const webRoot: string;
const { Paragraph, Text } = Typography;
const sessionKey = "exp_discord_session";
type Accounts = {
discord: { id: string, name: string },
accounts: string[],
max_accounts: number,
};
async function api(method: "GET" | "POST", route: string, session: string) {
const response = await fetch(`${webRoot}api/exp_discord/${route}`, {
method,
headers: { Authorization: `Bearer ${session}` },
});
const json = await response.json();
if (!response.ok) {
throw new Error(json.error ?? `Bad server response: ${response.status}`);
}
return json;
}
/** Take the outcome of the Discord redirect out of the url, so a reload does not reuse it. */
function readRedirect() {
const params = new URLSearchParams(window.location.hash.slice(1));
const session = params.get("exp_discord_session");
const error = params.get("exp_discord_error");
if (session || error) {
window.history.replaceState(null, "", window.location.pathname + window.location.search);
}
if (session) {
sessionStorage.setItem(sessionKey, session);
}
return { session: session ?? sessionStorage.getItem(sessionKey), error };
}
export default function DiscordLoginForm(props: { setToken(token: string): void }) {
const [redirect] = useState(readRedirect);
const [session, setSession] = useState<string | null>(redirect.session);
const [error, setError] = useState<string | null>(redirect.error);
const [accounts, setAccounts] = useState<Accounts | null>(null);
const [code, setCode] = useState<string | null>(null);
const linkedCount = useRef<number | null>(null);
function forget(message: string | null) {
sessionStorage.removeItem(sessionKey);
setSession(null);
setAccounts(null);
setCode(null);
linkedCount.current = null;
setError(message);
}
useEffect(() => {
if (!session) {
return undefined;
}
let cancelled = false;
async function load() {
try {
const json = await api("GET", "accounts", session!) as Accounts;
if (!cancelled) {
// The code was used once a new account shows up
if (linkedCount.current !== null && json.accounts.length > linkedCount.current) {
setCode(null);
}
linkedCount.current = json.accounts.length;
setAccounts(json);
}
} catch (err: any) {
if (!cancelled) {
forget(err.message);
}
}
}
load();
// While a code is shown, poll until it is used in game
const interval = code ? setInterval(load, 3e3) : undefined;
return () => {
cancelled = true;
clearInterval(interval);
};
}, [session, code]);
async function login(name: string) {
try {
const json = await api("POST", `login?name=${encodeURIComponent(name)}`, session!);
sessionStorage.removeItem(sessionKey);
props.setToken(json.token);
} catch (err: any) {
setError(err.message);
}
}
async function getCode() {
try {
const json = await api("POST", "link_code", session!);
setCode(json.code);
} catch (err: any) {
forget(err.message);
}
}
const errorAlert = error && <Alert type="error" message={error} showIcon style={{ marginBottom: 16 }} />;
if (!session) {
return <>
{errorAlert}
<Paragraph>Log in with your Discord account. Your Factorio account needs to be linked to it first, which you can do after logging in.</Paragraph>
<Button type="primary" href={`${webRoot}api/exp_discord/authorize`}>Log in with Discord</Button>
</>;
}
if (!accounts) {
return <Spin size="large" />;
}
const canLinkMore = accounts.accounts.length < accounts.max_accounts;
return <>
{errorAlert}
<Paragraph>Logged in to Discord as <Text strong>{accounts.discord.name}</Text>.</Paragraph>
{accounts.accounts.length
? <Space direction="vertical" style={{ width: "100%", marginBottom: 16 }}>
{accounts.accounts.map(name => <Button
key={name}
type="primary"
block
onClick={() => { login(name); }}
>Log in as {name}</Button>)}
</Space>
: <Paragraph>No Factorio accounts are linked to this Discord account yet.</Paragraph>}
{code
? <Alert
type="info"
style={{ marginBottom: 16 }}
message="Link your Factorio account"
description={<>
Join any of our servers and type this in the chat:
<Paragraph copyable={{ text: `/link-discord ${code}` }} style={{ margin: "8px 0" }}>
<Text code style={{ fontSize: 18 }}>/link-discord {code}</Text>
</Paragraph>
The code is valid for 10 minutes. This page continues once it has been used.
</>}
/>
: canLinkMore && <Paragraph>
<Button block onClick={() => { getCode(); }}>
{accounts.accounts.length ? "Link another Factorio account" : "Link a Factorio account"}
</Button>
</Paragraph>}
<Button type="link" onClick={() => forget(null)}>Use a different Discord account</Button>
</>;
}
@@ -0,0 +1,87 @@
import React, { useContext, useEffect, useState } from "react";
import { Alert, Button, Descriptions, Popconfirm } from "antd";
import {
ControlContext, PluginExtensionProps, SectionHeader, notifyErrorHandler, useAccount,
} from "@clusterio/web_ui";
import { DiscordLinkGetRequest, DiscordLinkStartRequest, DiscordUnlinkRequest } from "../../messages.js";
declare const webRoot: string;
type Link = { id: string, name: string } | null;
/** An error from linking on Discord, taken out of the url so a reload does not show it again. */
function readError() {
const error = new URLSearchParams(window.location.hash.slice(1)).get("exp_discord_error");
if (error) {
window.history.replaceState(null, "", window.location.pathname + window.location.search);
}
return error;
}
/** The Discord account a user is linked to, shown on their user page. */
export default function UserDiscordLink(props: PluginExtensionProps<"UserViewPage">) {
const control = useContext(ControlContext);
const account = useAccount();
const own = account.name.toLowerCase() === props.user.name.toLowerCase();
const canGet = own || account.hasPermission("exp_discord.link.get");
const canDelete = own || account.hasPermission("exp_discord.link.delete");
const [link, setLink] = useState<Link | undefined>(undefined);
const [error, setError] = useState(readError);
useEffect(() => {
if (!canGet) {
return;
}
control.send(new DiscordLinkGetRequest(props.user.name))
.then(setLink)
.catch(notifyErrorHandler("Error loading Discord link"));
}, [props.user.name, canGet]);
if (!canGet || link === undefined) {
return null;
}
async function unlink() {
await control.send(new DiscordUnlinkRequest(props.user.name));
setLink(null);
}
async function startLink() {
const ticket = await control.send(new DiscordLinkStartRequest(props.user.name));
window.location.href = `${webRoot}api/exp_discord/authorize?link=${encodeURIComponent(ticket)}`;
}
return <>
<SectionHeader title="Discord" />
{error && <Alert
type="error"
message={error}
showIcon
closable
onClose={() => setError(null)}
style={{ marginBottom: 16 }}
/>}
<Descriptions bordered size="small" column={1}>
<Descriptions.Item label="Linked account">
{link ? <>
{link.name}
{canDelete && <Popconfirm
title={`Unlink ${props.user.name} from ${link.name}?`}
onConfirm={() => { unlink().catch(notifyErrorHandler("Error unlinking Discord")); }}
>
<Button danger size="small" style={{ marginLeft: 8 }}>Unlink</Button>
</Popconfirm>}
</> : <>
Not linked
{own && <Button
size="small"
style={{ marginLeft: 8 }}
onClick={() => { startLink().catch(notifyErrorHandler("Error linking Discord")); }}
>Link Discord</Button>}
</>}
</Descriptions.Item>
</Descriptions>
</>;
}
+19
View File
@@ -0,0 +1,19 @@
import React from "react";
import { WebPluginContext } from "@clusterio/web_ui";
import DiscordLoginForm from "./components/DiscordLoginForm";
import UserDiscordLink from "./components/UserDiscordLink";
export default function registerPlugin(context: WebPluginContext) {
context.control.hooks.loginForms.attach("exp_discord", () => [
{
name: "exp_discord",
title: "Discord",
Component: DiscordLoginForm,
},
]);
context.control.hooks.extensionComponents.attach("exp_discord", () => ({
UserViewPage: UserDiscordLink,
}));
}