From 1c713ba0aa1233043a1c1a19dd340031b46281d1 Mon Sep 17 00:00:00 2001 From: bbassie <17990055+bbassie@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:38:20 +0000 Subject: [PATCH] Address review of the Discord plugin The plugin is now exp_discord_auth, so later Discord plugins can sit next to it. Config keys, permissions, routes and the Lua module moved with it, and the Discord redirect is now api/exp_discord_auth/callback. The controller registers its handlers and routes in the constructor and uses the express types, the instance plugin is a closure, and the Lua commands file returns its commands. The get and unlink responses carry the controller url so the in game messages can name the website. The login form asks the new status route whether Discord is configured and shows the error straight away instead of a button that fails. The button is full width like the link button, and a "Not you?" link next to the Discord name replaces the separate switch account button. Co-Authored-By: Claude Opus 5.5 --- exp_discord/instance.ts | 82 ---------- exp_discord/module/module_exports.lua | 3 - exp_discord_auth/.npmignore | 1 + {exp_discord => exp_discord_auth}/README.md | 18 +-- .../controller.ts | 141 +++++++++--------- {exp_discord => exp_discord_auth}/index.ts | 24 +-- exp_discord_auth/instance.ts | 67 +++++++++ {exp_discord => exp_discord_auth}/messages.ts | 30 ++-- .../module/commands.lua | 20 ++- .../module/control.lua | 42 +++--- .../module/globals.lua | 4 +- .../module/locale/en.cfg | 6 +- .../module/module.json | 2 +- exp_discord_auth/module/module_exports.lua | 3 + .../package.json | 5 +- .../test/controller.test.js | 63 ++++---- .../tsconfig.browser.json | 0 .../tsconfig.json | 0 .../tsconfig.node.json | 0 .../web/components/DiscordLoginForm.tsx | 36 +++-- .../web/components/UserDiscordLink.tsx | 10 +- .../web/index.tsx | 6 +- .../webpack.config.cjs | 4 +- tsconfig.json | 2 +- 24 files changed, 296 insertions(+), 273 deletions(-) delete mode 100644 exp_discord/instance.ts delete mode 100644 exp_discord/module/module_exports.lua create mode 100644 exp_discord_auth/.npmignore rename {exp_discord => exp_discord_auth}/README.md (63%) rename {exp_discord => exp_discord_auth}/controller.ts (80%) rename {exp_discord => exp_discord_auth}/index.ts (77%) create mode 100644 exp_discord_auth/instance.ts rename {exp_discord => exp_discord_auth}/messages.ts (85%) rename {exp_discord => exp_discord_auth}/module/commands.lua (53%) rename {exp_discord => exp_discord_auth}/module/control.lua (63%) rename {exp_discord => exp_discord_auth}/module/globals.lua (75%) rename {exp_discord => exp_discord_auth}/module/locale/en.cfg (82%) rename {exp_discord => exp_discord_auth}/module/module.json (84%) create mode 100644 exp_discord_auth/module/module_exports.lua rename {exp_discord => exp_discord_auth}/package.json (94%) rename {exp_discord => exp_discord_auth}/test/controller.test.js (86%) rename {exp_discord => exp_discord_auth}/tsconfig.browser.json (100%) rename {exp_discord => exp_discord_auth}/tsconfig.json (100%) rename {exp_discord => exp_discord_auth}/tsconfig.node.json (100%) rename {exp_discord => exp_discord_auth}/web/components/DiscordLoginForm.tsx (77%) rename {exp_discord => exp_discord_auth}/web/components/UserDiscordLink.tsx (88%) rename {exp_discord => exp_discord_auth}/web/index.tsx (68%) rename {exp_discord => exp_discord_auth}/webpack.config.cjs (89%) diff --git a/exp_discord/instance.ts b/exp_discord/instance.ts deleted file mode 100644 index 622cc78b..00000000 --- a/exp_discord/instance.ts +++ /dev/null @@ -1,82 +0,0 @@ -import type { Instance, InstancePluginContext } from "@clusterio/host"; -import type * as lib from "@clusterio/lib"; -import * as messages from "./messages.js"; - -/** Sent by the lua side when a player uses a link code. */ -export type IpcLink = { - player_name: string, - code: string, -}; - -/** Sent by the lua side when a player unlinks their Discord account, or asks which one they are linked to. */ -export type IpcPlayer = { - player_name: string, -}; - -/** Bridges the lua side and the controller, the answer is printed to the player once it arrives. */ -export class InstancePlugin { - private constructor( - public instance: Instance, - public logger: lib.Logger, - public name: string, - ) {} - - static async fromContext(context: InstancePluginContext) { - const instance = context.instance; - const plugin = new InstancePlugin(instance, context.logger, context.plugin.name); - - instance.server.handle("exp_discord:link", plugin.handleLinkIPC.bind(plugin)); - instance.server.handle("exp_discord:unlink", plugin.handleUnlinkIPC.bind(plugin)); - instance.server.handle("exp_discord:get", plugin.handleGetIPC.bind(plugin)); - return plugin; - } - - async handleLinkIPC(event: IpcLink) { - try { - const discord = await this.instance.sendTo("controller", new messages.DiscordLinkRequest( - event.player_name, event.code, - )); - await this.luaSend("receive_linked", { player_name: event.player_name, discord_name: discord!.name }); - } catch (err: any) { - await this.luaSend("receive_error", { player_name: event.player_name, message: err.message }); - } - } - - async handleUnlinkIPC(event: IpcPlayer) { - try { - const discord = await this.instance.sendTo("controller", new messages.DiscordUnlinkRequest(event.player_name)); - await this.luaSend("receive_unlinked", { player_name: event.player_name, discord_name: discord?.name }); - } catch (err: any) { - await this.luaSend("receive_error", { player_name: event.player_name, message: err.message }); - } - } - - async handleGetIPC(event: IpcPlayer) { - try { - const discord = await this.instance.sendTo("controller", new messages.DiscordLinkGetRequest(event.player_name)); - await this.luaSend("receive_get", { player_name: event.player_name, discord_name: discord?.name }); - } catch (err: any) { - await this.luaSend("receive_error", { player_name: event.player_name, message: err.message }); - } - } - - /** Hand an answer to lua, unless the instance stopped while it was being fetched. */ - async luaSend(receiver: string, json: any) { - if (this.instance.status !== "running") { - return; - } - // Discord names can contain anything, so pick a long bracket level the json does not close - const text = JSON.stringify(json); - let level = "="; - while (text.includes(`]${level}]`)) { - level += "="; - } - await this.instance.sendRcon( - `/sc exp_discord.${receiver}(helpers.json_to_table[${level}[${text}]${level}])`, true - ); - } -} - -export default async function (context: InstancePluginContext) { - await InstancePlugin.fromContext(context); -} diff --git a/exp_discord/module/module_exports.lua b/exp_discord/module/module_exports.lua deleted file mode 100644 index 77d115e0..00000000 --- a/exp_discord/module/module_exports.lua +++ /dev/null @@ -1,3 +0,0 @@ - --- Access the exports from other modules using require("modules/exp_discord") -return require("modules/exp_discord/control") diff --git a/exp_discord_auth/.npmignore b/exp_discord_auth/.npmignore new file mode 100644 index 00000000..36e20175 --- /dev/null +++ b/exp_discord_auth/.npmignore @@ -0,0 +1 @@ +# Without an .npmignore pnpm packs using the repository .gitignore, which leaves out dist/ \ No newline at end of file diff --git a/exp_discord/README.md b/exp_discord_auth/README.md similarity index 63% rename from exp_discord/README.md rename to exp_discord_auth/README.md index 0c2402ba..7ea795e8 100644 --- a/exp_discord/README.md +++ b/exp_discord_auth/README.md @@ -1,4 +1,4 @@ -# ExpGaming - Discord +# ExpGaming - Discord Auth Lets players log in to the web interface with Discord, and links their Factorio accounts to a Discord account. It only uses the OAuth2 `identify` scope, so no bot is needed. @@ -6,13 +6,13 @@ Lets players log in to the web interface with Discord, and links their Factorio 1. Create an application in the [Discord developer portal](https://discord.com/developers/applications). 2. Under OAuth2, copy the Client ID and reset the Client Secret to get one. -3. Under OAuth2 → Redirects, add `api/exp_discord/callback`. For a controller with `controller.public_url` set to `https://example.com/cluster/` that is `https://example.com/cluster/api/exp_discord/callback`. It must match exactly, including the trailing path and http or https. +3. Under OAuth2 → Redirects, add `api/exp_discord_auth/callback`. For a controller with `controller.public_url` set to `https://example.com/cluster/` that is `https://example.com/cluster/api/exp_discord_auth/callback`. It must match exactly, including the trailing path and http or https. 4. Set the config on the controller: ``` npx clusterioctl controller config set controller.public_url https://example.com/cluster/ -npx clusterioctl controller config set exp_discord.client_id -npx clusterioctl controller config set exp_discord.client_secret +npx clusterioctl controller config set exp_discord_auth.client_id +npx clusterioctl controller config set exp_discord_auth.client_secret ``` `controller.public_url` has to be set, because the redirect URL is built from it and Discord rejects any URL that isn't registered. @@ -23,9 +23,9 @@ All fields are on the controller. | Field | Default | Description | |---|---|---| -| `exp_discord.client_id` | | Application ID of the Discord application. | -| `exp_discord.client_secret` | | OAuth2 client secret of the Discord application. Only readable on the controller. | -| `exp_discord.max_accounts` | 3 | How many Factorio accounts one Discord account can link. | +| `exp_discord_auth.client_id` | | Application ID of the Discord application. | +| `exp_discord_auth.client_secret` | | OAuth2 client secret of the Discord application. Only readable on the controller. | +| `exp_discord_auth.max_accounts` | 3 | How many Factorio accounts one Discord account can link. | ## Linking @@ -36,8 +36,8 @@ There are two ways to link a Factorio account: Linking a Factorio account that is already linked to another Discord account moves it. `/link-discord` without a code shows the current link, and `/unlink-discord` removes it. The user page has an Unlink button too. -Users can always see and remove their own link. The `exp_discord.link.get` and `exp_discord.link.delete` permissions allow it for other users. +Users can always see and remove their own link. The `exp_discord_auth.link.get` and `exp_discord_auth.link.delete` permissions allow it for other users. Once linked, the Discord tab on the login page has a "Log in as" button for each linked account. Banned users can't log in this way. -Links are stored in `database/exp_discord/accounts.json` on the controller. +Links are stored in `database/exp_discord_auth/accounts.json` on the controller. diff --git a/exp_discord/controller.ts b/exp_discord_auth/controller.ts similarity index 80% rename from exp_discord/controller.ts rename to exp_discord_auth/controller.ts index 2edc6f4d..0d575cb5 100644 --- a/exp_discord/controller.ts +++ b/exp_discord_auth/controller.ts @@ -1,4 +1,5 @@ import type { Controller, ControllerPluginContext } from "@clusterio/controller"; +import type { NextFunction, Request, Response } from "express"; import * as lib from "@clusterio/lib"; import * as messages from "./messages.js"; import * as crypto from "node:crypto"; @@ -22,17 +23,6 @@ export type RouteResult = | { redirect: string, cookie?: string } | { status: number, json: unknown }; -type HttpRequest = { - query: Record, - headers: Record, -}; -type HttpResponse = { - status(code: number): HttpResponse, - json(body: unknown): unknown, - redirect(url: string): void, - setHeader(name: string, value: string): unknown, -}; - function readCookie(header: string | string[] | undefined, name: string) { for (const part of String(header ?? "").split(";")) { const [key, ...value] = part.trim().split("="); @@ -60,14 +50,46 @@ export class ControllerPlugin { linkTickets = new Map(); /** Links waiting for the Discord callback, by OAuth state */ pendingLinks = new Map(); - cleanupInterval?: ReturnType; + cleanupInterval = setInterval(() => this.removeExpired(), 60e3).unref(); private constructor( public controller: Controller, public logger: lib.Logger, public name: string, public accounts: lib.SubscribableDatastore, - ) {} + ) { + controller.handle(messages.DiscordLinkRequest, this.handleLinkRequest.bind(this)); + controller.handle(messages.DiscordUnlinkRequest, this.handleUnlinkRequest.bind(this)); + controller.handle(messages.DiscordLinkGetRequest, this.handleLinkGetRequest.bind(this)); + controller.handle(messages.DiscordLinkStartRequest, this.handleLinkStartRequest.bind(this)); + + const route = (handler: (req: Request) => Promise) => ( + (req: Request, res: Response, next: NextFunction) => { + handler(req).then(result => { + if ("redirect" in result) { + if (result.cookie) { + res.setHeader("Set-Cookie", result.cookie); + } + res.redirect(result.redirect); + } else { + res.status(result.status).json(result.json); + } + }).catch(next); + } + ); + const app = controller.app; + app.get("/api/exp_discord_auth/status", route(async () => this.status())); + app.get("/api/exp_discord_auth/authorize", route(async req => this.authorize(req.query.link))); + app.get("/api/exp_discord_auth/callback", route(async req => this.callback( + req.query, readCookie(req.headers.cookie, "exp_discord_auth_state"), + ))); + app.get("/api/exp_discord_auth/accounts", route(async req => this.listAccounts(this.sessionId(req)))); + app.post("/api/exp_discord_auth/login", route(async req => this.login(this.sessionId(req), req.query.name))); + app.post("/api/exp_discord_auth/link_code", route(async req => this.linkCode(this.sessionId(req)))); + + controller.hooks.save.attach(name, this.onSave.bind(this)); + controller.hooks.shutdown.attach(name, this.onShutdown.bind(this)); + } static async fromContext(context: ControllerPluginContext) { const controller = context.controller; @@ -75,25 +97,12 @@ export class ControllerPlugin { const accounts = new lib.SubscribableDatastore( ...await new lib.JsonIdDatastoreProvider( - path.join(databaseDirectory, "exp_discord", "accounts.json"), + path.join(databaseDirectory, "exp_discord_auth", "accounts.json"), messages.DiscordAccountRecord.fromJSON.bind(messages.DiscordAccountRecord), ).bootstrap() ); - const plugin = new ControllerPlugin(controller, context.logger, context.plugin.name, accounts); - - controller.handle(messages.DiscordLinkRequest, plugin.handleLinkRequest.bind(plugin)); - controller.handle(messages.DiscordUnlinkRequest, plugin.handleUnlinkRequest.bind(plugin)); - controller.handle(messages.DiscordLinkGetRequest, plugin.handleLinkGetRequest.bind(plugin)); - controller.handle(messages.DiscordLinkStartRequest, plugin.handleLinkStartRequest.bind(plugin)); - - plugin.addRoutes(); - plugin.cleanupInterval = setInterval(() => plugin.removeExpired(), 60e3); - plugin.cleanupInterval.unref(); - - controller.hooks.save.attach(plugin.name, plugin.onSave.bind(plugin)); - controller.hooks.shutdown.attach(plugin.name, plugin.onShutdown.bind(plugin)); - return plugin; + return new ControllerPlugin(controller, context.logger, context.plugin.name, accounts); } async onSave() { @@ -124,45 +133,19 @@ export class ControllerPlugin { Http routes */ - addRoutes() { - const app = this.controller.app; - const route = (handler: (req: HttpRequest) => Promise) => ( - (req: HttpRequest, res: HttpResponse, next: (err: unknown) => void) => { - handler(req).then(result => { - if ("redirect" in result) { - if (result.cookie) { - res.setHeader("Set-Cookie", result.cookie); - } - res.redirect(result.redirect); - } else { - res.status(result.status).json(result.json); - } - }).catch(next); - } - ); - - app.get("/api/exp_discord/authorize", route(async req => this.authorize(req.query.link))); - app.get("/api/exp_discord/callback", route(async req => this.callback( - req.query, readCookie(req.headers.cookie, "exp_discord_state"), - ))); - app.get("/api/exp_discord/accounts", route(async req => this.listAccounts(this.sessionId(req)))); - app.post("/api/exp_discord/login", route(async req => this.login(this.sessionId(req), req.query.name))); - app.post("/api/exp_discord/link_code", route(async req => this.linkCode(this.sessionId(req)))); - } - - sessionId(req: HttpRequest) { + sessionId(req: Request) { const header = String(req.headers.authorization ?? ""); return header.startsWith("Bearer ") ? header.slice(7) : ""; } redirectUri() { - return new URL("api/exp_discord/callback", this.controller.getControllerUrl()).href; + return new URL("api/exp_discord_auth/callback", this.controller.getControllerUrl()).href; } /** Back to the web ui, with the outcome in the fragment so it never reaches a server log. */ webRedirect(key: "session" | "error", value: string, page = ""): RouteResult { const url = new URL(page, this.controller.getControllerUrl()); - url.hash = `exp_discord_${key}=${encodeURIComponent(value)}`; + url.hash = `exp_discord_auth_${key}=${encodeURIComponent(value)}`; return { redirect: url.href }; } @@ -170,6 +153,18 @@ export class ControllerPlugin { return `users/${encodeURIComponent(playerName)}/view`; } + isConfigured() { + return Boolean( + this.controller.config.get("exp_discord_auth.client_id") + && this.controller.config.get("exp_discord_auth.client_secret") + ); + } + + /** Lets the login form say Discord is not set up before anyone presses the button. */ + async status(): Promise { + return { status: 200, json: { configured: this.isConfigured() } }; + } + async authorize(linkTicket?: unknown): Promise { let link: WebLink | undefined; if (linkTicket !== undefined) { @@ -181,8 +176,7 @@ export class ControllerPlugin { } const page = link ? this.userPage(link.playerName) : ""; - const clientId = this.controller.config.get("exp_discord.client_id"); - if (!clientId || !this.controller.config.get("exp_discord.client_secret")) { + if (!this.isConfigured()) { return this.webRedirect("error", "Discord login is not configured on this controller", page); } @@ -193,7 +187,7 @@ export class ControllerPlugin { const url = new URL("https://discord.com/oauth2/authorize"); url.search = new URLSearchParams({ response_type: "code", - client_id: clientId, + client_id: this.controller.config.get("exp_discord_auth.client_id")!, scope: "identify", state, redirect_uri: this.redirectUri(), @@ -205,7 +199,7 @@ export class ControllerPlugin { const secure = callbackUrl.protocol === "https:" ? "; Secure" : ""; return { redirect: url.href, - cookie: `exp_discord_state=${state}; Path=${callbackUrl.pathname}; Max-Age=${stateTimeoutS}; HttpOnly; SameSite=Lax${secure}`, + cookie: `exp_discord_auth_state=${state}; Path=${callbackUrl.pathname}; Max-Age=${stateTimeoutS}; HttpOnly; SameSite=Lax${secure}`, }; } @@ -264,8 +258,8 @@ export class ControllerPlugin { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ - client_id: this.controller.config.get("exp_discord.client_id") ?? "", - client_secret: this.controller.config.get("exp_discord.client_secret") ?? "", + client_id: this.controller.config.get("exp_discord_auth.client_id") ?? "", + client_secret: this.controller.config.get("exp_discord_auth.client_secret") ?? "", grant_type: "authorization_code", code, redirect_uri: this.redirectUri(), @@ -304,7 +298,7 @@ export class ControllerPlugin { json: { discord: { id: session.id, name: session.name }, accounts: this.accounts.get(session.id)?.factorioNames ?? [], - max_accounts: this.controller.config.get("exp_discord.max_accounts"), + max_accounts: this.controller.config.get("exp_discord_auth.max_accounts"), }, }; } @@ -393,7 +387,9 @@ export class ControllerPlugin { const entry = this.codes.get(code); const session = entry ? this.sessions.get(entry.sessionId) : undefined; if (!entry || !session || entry.expiresMs < Date.now()) { - throw new lib.RequestError("This code is invalid or has expired, get a new one from the website"); + throw new lib.RequestError( + `This code is invalid or has expired, get a new one from ${this.controller.getControllerUrl()}` + ); } const linked = this.linkAccount(session, request.playerName); @@ -407,7 +403,7 @@ export class ControllerPlugin { const name = playerName.toLowerCase(); const existing = this.accounts.get(discordUser.id); const alreadyLinked = existing?.factorioNames.some(linked => linked.toLowerCase() === name); - const maxAccounts = this.controller.config.get("exp_discord.max_accounts"); + const maxAccounts = this.controller.config.get("exp_discord_auth.max_accounts"); if (!alreadyLinked && (existing?.factorioNames.length ?? 0) >= maxAccounts) { throw new lib.RequestError( `${discordUser.name} already has ${maxAccounts} Factorio accounts linked, unlink one first` @@ -426,10 +422,10 @@ export class ControllerPlugin { } async handleUnlinkRequest(request: messages.DiscordUnlinkRequest) { - return this.removeLink(request.playerName); + return { link: this.removeLink(request.playerName), url: this.controller.getControllerUrl() }; } - /** A ticket for /api/exp_discord/authorize?link= which links the Discord account to the user. */ + /** A ticket for /api/exp_discord_auth/authorize?link= which links the Discord account to the user. */ async handleLinkStartRequest(request: messages.DiscordLinkStartRequest) { const ticket = crypto.randomBytes(16).toString("base64url"); this.linkTickets.set(ticket, { playerName: request.playerName, expiresMs: Date.now() + 60e3 }); @@ -438,10 +434,11 @@ export class ControllerPlugin { async handleLinkGetRequest(request: messages.DiscordLinkGetRequest) { const account = this.findAccount(request.playerName); - return account ? { id: account.id, name: account.name } : null; + return { + link: account ? { id: account.id, name: account.name } : null, + url: this.controller.getControllerUrl(), + }; } } -export default async function (context: ControllerPluginContext) { - await ControllerPlugin.fromContext(context); -} +export default ControllerPlugin.fromContext.bind(ControllerPlugin); diff --git a/exp_discord/index.ts b/exp_discord_auth/index.ts similarity index 77% rename from exp_discord/index.ts rename to exp_discord_auth/index.ts index f247c341..3c0d9cb2 100644 --- a/exp_discord/index.ts +++ b/exp_discord_auth/index.ts @@ -3,19 +3,19 @@ import * as messages from "./messages.js"; declare module "@clusterio/lib" { export interface ControllerConfigFields { - "exp_discord.client_id": string | null; - "exp_discord.client_secret": string | null; - "exp_discord.max_accounts": number; + "exp_discord_auth.client_id": string | null; + "exp_discord_auth.client_secret": string | null; + "exp_discord_auth.max_accounts": number; } export interface Permissions { - "exp_discord.link.get": never; - "exp_discord.link.delete": never; + "exp_discord_auth.link.get": never; + "exp_discord_auth.link.delete": never; } } export const plugin: lib.PluginDeclaration = { - name: "exp_discord", - title: "ExpGaming - Discord", + name: "exp_discord_auth", + title: "ExpGaming - Discord Auth", description: "Clusterio plugin linking Factorio accounts to Discord accounts and logging in to the web interface with Discord", features: [ @@ -32,13 +32,13 @@ export const plugin: lib.PluginDeclaration = { permissions: [ { - name: "exp_discord.link.get", + name: "exp_discord_auth.link.get", title: "Get Discord Links", description: "See which Discord account any user is linked to, users can always see their own.", grantByDefault: false, }, { - name: "exp_discord.link.delete", + name: "exp_discord_auth.link.delete", title: "Remove Discord Links", description: "Unlink any user from their Discord account, users can always unlink themselves.", grantByDefault: false, @@ -49,20 +49,20 @@ export const plugin: lib.PluginDeclaration = { controllerEntrypoint: "./dist/node/controller.js", controllerConfigFields: { - "exp_discord.client_id": { + "exp_discord_auth.client_id": { title: "Client ID", description: "Application ID of the Discord application used for logging in.", type: "string", optional: true, }, - "exp_discord.client_secret": { + "exp_discord_auth.client_secret": { title: "Client Secret", description: "OAuth2 client secret of the Discord application used for logging in.", type: "string", credential: ["controller"], optional: true, }, - "exp_discord.max_accounts": { + "exp_discord_auth.max_accounts": { title: "Max Accounts", description: "Number of Factorio accounts which can be linked to one Discord account.", type: "number", diff --git a/exp_discord_auth/instance.ts b/exp_discord_auth/instance.ts new file mode 100644 index 00000000..20a29219 --- /dev/null +++ b/exp_discord_auth/instance.ts @@ -0,0 +1,67 @@ +import type { InstancePluginContext } from "@clusterio/host"; +import * as messages from "./messages.js"; + +/** Sent by the lua side when a player uses a link code. */ +export type IpcLink = { + player_name: string, + code: string, +}; + +/** Sent by the lua side when a player unlinks their Discord account, or asks which one they are linked to. */ +export type IpcPlayer = { + player_name: string, +}; + +/** Bridges the lua side and the controller, the answer is printed to the player once it arrives. */ +export default async function (context: InstancePluginContext) { + const { instance } = context; + + /** Hand an answer to lua, unless the instance stopped while it was being fetched. */ + async function luaSend(receiver: string, json: any) { + if (instance.status !== "running") { + return; + } + // Discord names can contain anything, so pick a long bracket level the json does not close + const text = JSON.stringify(json); + let level = "="; + while (text.includes(`]${level}]`)) { + level += "="; + } + await instance.sendRcon( + `/sc exp_discord_auth.${receiver}(helpers.json_to_table[${level}[${text}]${level}])`, true + ); + } + + instance.server.handle("exp_discord_auth:link", async (event: IpcLink) => { + try { + const discord = await instance.sendTo("controller", new messages.DiscordLinkRequest( + event.player_name, event.code, + )); + await luaSend("receive_linked", { player_name: event.player_name, discord_name: discord!.name }); + } catch (err: any) { + await luaSend("receive_error", { player_name: event.player_name, message: err.message }); + } + }); + + instance.server.handle("exp_discord_auth:unlink", async (event: IpcPlayer) => { + try { + const status = await instance.sendTo("controller", new messages.DiscordUnlinkRequest(event.player_name)); + await luaSend("receive_unlinked", { + player_name: event.player_name, discord_name: status.link?.name, url: status.url, + }); + } catch (err: any) { + await luaSend("receive_error", { player_name: event.player_name, message: err.message }); + } + }); + + instance.server.handle("exp_discord_auth:get", async (event: IpcPlayer) => { + try { + const status = await instance.sendTo("controller", new messages.DiscordLinkGetRequest(event.player_name)); + await luaSend("receive_get", { + player_name: event.player_name, discord_name: status.link?.name, url: status.url, + }); + } catch (err: any) { + await luaSend("receive_error", { player_name: event.player_name, message: err.message }); + } + }); +} diff --git a/exp_discord/messages.ts b/exp_discord_auth/messages.ts similarity index 85% rename from exp_discord/messages.ts rename to exp_discord_auth/messages.ts index 4836866c..a011e82c 100644 --- a/exp_discord/messages.ts +++ b/exp_discord_auth/messages.ts @@ -72,13 +72,19 @@ function selfOnly(user: lib.IUser, message: lib.MessageRequest) { } } -const LinkResponse = lib.plainJson(Type.Union([ +const Link = Type.Union([ Type.Null(), Type.Object({ id: Type.String(), name: Type.String(), }), -])); +]); +const LinkResponse = lib.plainJson(Link); +/** The website is included so the player can be told where to link their account. */ +const LinkStatusResponse = lib.plainJson(Type.Object({ + link: Link, + url: Type.String(), +})); /* Link requests @@ -87,7 +93,7 @@ const LinkResponse = lib.plainJson(Type.Union([ /** Link a player to the Discord account which generated the code, sent when the player uses the code in game. */ export class DiscordLinkRequest { declare ["constructor"]: typeof DiscordLinkRequest; - static plugin = "exp_discord" as const; + static plugin = "exp_discord_auth" as const; static type = "request" as const; static src = "instance" as const; static dst = "controller" as const; @@ -112,15 +118,15 @@ export class DiscordLinkRequest { } } -/** Remove the link of a player, responds with the account it was linked to. */ +/** Remove the link of a player, responds with the account it was linked to and the website url. */ export class DiscordUnlinkRequest { declare ["constructor"]: typeof DiscordUnlinkRequest; - static plugin = "exp_discord" as const; + static plugin = "exp_discord_auth" as const; static type = "request" as const; static src = ["control", "instance"] as const; static dst = "controller" as const; - static permission = selfOrPermission("exp_discord.link.delete"); - static Response = LinkResponse; + static permission = selfOrPermission("exp_discord_auth.link.delete"); + static Response = LinkStatusResponse; constructor( public playerName: string, @@ -139,15 +145,15 @@ export class DiscordUnlinkRequest { } } -/** Get the Discord account a player is linked to. */ +/** Get the Discord account a player is linked to and the website url. */ export class DiscordLinkGetRequest { declare ["constructor"]: typeof DiscordLinkGetRequest; - static plugin = "exp_discord" as const; + static plugin = "exp_discord_auth" as const; static type = "request" as const; static src = ["control", "instance"] as const; static dst = "controller" as const; - static permission = selfOrPermission("exp_discord.link.get"); - static Response = LinkResponse; + static permission = selfOrPermission("exp_discord_auth.link.get"); + static Response = LinkStatusResponse; constructor( public playerName: string, @@ -169,7 +175,7 @@ export class DiscordLinkGetRequest { /** Start linking the Discord account from the user page, responds with a ticket for the authorize route. */ export class DiscordLinkStartRequest { declare ["constructor"]: typeof DiscordLinkStartRequest; - static plugin = "exp_discord" as const; + static plugin = "exp_discord_auth" as const; static type = "request" as const; static src = "control" as const; static dst = "controller" as const; diff --git a/exp_discord/module/commands.lua b/exp_discord_auth/module/commands.lua similarity index 53% rename from exp_discord/module/commands.lua rename to exp_discord_auth/module/commands.lua index eb8f3df6..6b09b3de 100644 --- a/exp_discord/module/commands.lua +++ b/exp_discord_auth/module/commands.lua @@ -1,30 +1,34 @@ ---[[-- ExpDiscord - Commands +--[[-- ExpDiscordAuth - Commands Commands which link and unlink the player's Discord account ]] local Commands = require("modules/exp_commands") -local Discord = require("modules/exp_discord") +local Discord = require("modules/exp_discord_auth") + +--- @class ExpDiscordAuth.commands +local commands = {} --- Links your account to the Discord account which made the code, printed once the controller answers -Commands.new("link-discord", { "exp-discord_commands.description-link" }) - :optional("code", { "exp-discord_commands.arg-code" }, Commands.types.string) +commands.link_discord = Commands.new("link-discord", { "exp-discord-auth_commands.description-link" }) + :optional("code", { "exp-discord-auth_commands.arg-code" }, Commands.types.string) :add_aliases{ "link" } :register(function(player, code) --- @cast code string? if code then Discord.link(player, code) else - Discord.get_link(player) + Discord.get_linked(player) end end) --- Removes the link to your Discord account, printed once the controller answers -Commands.new("unlink-discord", { "exp-discord_commands.description-unlink" }) +commands.unlink_discord = Commands.new("unlink-discord", { "exp-discord-auth_commands.description-unlink" }) :add_aliases{ "unlink" } :register(function(player) Discord.unlink(player) end) --- Access the exports from other modules using require("modules/exp_discord") -return require("modules/exp_discord/control") +return { + commands = commands, +} diff --git a/exp_discord/module/control.lua b/exp_discord_auth/module/control.lua similarity index 63% rename from exp_discord/module/control.lua rename to exp_discord_auth/module/control.lua index 2aa6869a..ee3e1026 100644 --- a/exp_discord/module/control.lua +++ b/exp_discord_auth/module/control.lua @@ -1,4 +1,4 @@ ---[[-- ExpDiscord +--[[-- ExpDiscordAuth Links Factorio accounts to Discord accounts, the links are kept on the controller. A player logs in with Discord on the web interface, which gives them a code. @@ -10,28 +10,28 @@ printed to the player once it arrives, if they are still online. local clusterio_api = require("modules/clusterio/api") local ExpUtil = require("modules/exp_util") ---- @class ExpDiscord -local ExpDiscord = {} +--- @class ExpDiscordAuth +local ExpDiscordAuth = {} local error_settings = { color = ExpUtil.color.orange_red, sound_path = "utility/wire_pickup" } --- Link the player to the Discord account which made the code --- @param player LuaPlayer --- @param code string -function ExpDiscord.link(player, code) - clusterio_api.send_json("exp_discord:link", { player_name = player.name, code = code }) +function ExpDiscordAuth.link(player, code) + clusterio_api.send_json("exp_discord_auth:link", { player_name = player.name, code = code }) end --- Remove the link between the player and their Discord account --- @param player LuaPlayer -function ExpDiscord.unlink(player) - clusterio_api.send_json("exp_discord:unlink", { player_name = player.name }) +function ExpDiscordAuth.unlink(player) + clusterio_api.send_json("exp_discord_auth:unlink", { player_name = player.name }) end --- Print the Discord account the player is linked to --- @param player LuaPlayer -function ExpDiscord.get_link(player) - clusterio_api.send_json("exp_discord:get", { player_name = player.name }) +function ExpDiscordAuth.get_linked(player) + clusterio_api.send_json("exp_discord_auth:get", { player_name = player.name }) end --- A player who can still be printed to, nil once they have left @@ -47,42 +47,42 @@ end --- The controller linked the player --- @param payload { player_name: string, discord_name: string } -function ExpDiscord.receive_linked(payload) +function ExpDiscordAuth.receive_linked(payload) local player = get_online_player(payload.player_name) if not player then return end - player.print{ "exp-discord.linked", payload.discord_name } + player.print{ "exp-discord-auth.linked", payload.discord_name } end --- The controller removed the link, discord_name is nil if there was none ---- @param payload { player_name: string, discord_name: string? } -function ExpDiscord.receive_unlinked(payload) +--- @param payload { player_name: string, discord_name: string?, url: string } +function ExpDiscordAuth.receive_unlinked(payload) local player = get_online_player(payload.player_name) if not player then return end if payload.discord_name then - player.print{ "exp-discord.unlinked", payload.discord_name } + player.print{ "exp-discord-auth.unlinked", payload.discord_name } else - player.print({ "exp-discord.not-linked" }, error_settings) + player.print({ "exp-discord-auth.not-linked", payload.url }, error_settings) end end --- The controller answered which account the player is linked to ---- @param payload { player_name: string, discord_name: string? } -function ExpDiscord.receive_get(payload) +--- @param payload { player_name: string, discord_name: string?, url: string } +function ExpDiscordAuth.receive_get(payload) local player = get_online_player(payload.player_name) if not player then return end if payload.discord_name then - player.print{ "exp-discord.linked-to", payload.discord_name } + player.print{ "exp-discord-auth.linked-to", payload.discord_name } else - player.print{ "exp-discord.not-linked" } + player.print{ "exp-discord-auth.not-linked", payload.url } end end --- The controller refused a request --- @param payload { player_name: string, message: string } -function ExpDiscord.receive_error(payload) +function ExpDiscordAuth.receive_error(payload) local player = get_online_player(payload.player_name) if not player then return end player.print(payload.message, error_settings) end -return ExpDiscord +return ExpDiscordAuth diff --git a/exp_discord/module/globals.lua b/exp_discord_auth/module/globals.lua similarity index 75% rename from exp_discord/module/globals.lua rename to exp_discord_auth/module/globals.lua index 862e1014..17c8f414 100644 --- a/exp_discord/module/globals.lua +++ b/exp_discord_auth/module/globals.lua @@ -6,5 +6,5 @@ Therefore, we advise that this should be the only file in your module to expose --- @diagnostic disable: global-in-non-module --- Access using `/sc exp_discord.foo()` -exp_discord = require("modules/exp_discord/control") +-- Access using `/sc exp_discord_auth.foo()` +exp_discord_auth = require("modules/exp_discord_auth/control") diff --git a/exp_discord/module/locale/en.cfg b/exp_discord_auth/module/locale/en.cfg similarity index 82% rename from exp_discord/module/locale/en.cfg rename to exp_discord_auth/module/locale/en.cfg index 57d0ac13..d5e6ec8a 100644 --- a/exp_discord/module/locale/en.cfg +++ b/exp_discord_auth/module/locale/en.cfg @@ -1,10 +1,10 @@ -[exp-discord] +[exp-discord-auth] linked=Your account is now linked to the Discord account __1__. linked-to=Your account is linked to the Discord account __1__. Use /unlink-discord to remove it. unlinked=Your account is no longer linked to the Discord account __1__. -not-linked=Your account is not linked to a Discord account. Log in with Discord on the website to get a code, then use /link-discord . +not-linked=Your account is not linked to a Discord account. Log in with Discord at __1__ to get a code, then use /link-discord . -[exp-discord_commands] +[exp-discord-auth_commands] description-link=Links your account to Discord using the code from the website, or shows the account you are linked to. description-unlink=Removes the link between your account and Discord. arg-code=Code shown on the website after logging in with Discord. diff --git a/exp_discord/module/module.json b/exp_discord_auth/module/module.json similarity index 84% rename from exp_discord/module/module.json rename to exp_discord_auth/module/module.json index 7fea5b7c..fce6233a 100644 --- a/exp_discord/module/module.json +++ b/exp_discord_auth/module/module.json @@ -1,5 +1,5 @@ { - "name": "exp_discord", + "name": "exp_discord_auth", "load": [ ], "require": [ diff --git a/exp_discord_auth/module/module_exports.lua b/exp_discord_auth/module/module_exports.lua new file mode 100644 index 00000000..ee07ae7e --- /dev/null +++ b/exp_discord_auth/module/module_exports.lua @@ -0,0 +1,3 @@ + +-- Access the exports from other modules using require("modules/exp_discord_auth") +return require("modules/exp_discord_auth/control") diff --git a/exp_discord/package.json b/exp_discord_auth/package.json similarity index 94% rename from exp_discord/package.json rename to exp_discord_auth/package.json index 80694ab6..7777710c 100644 --- a/exp_discord/package.json +++ b/exp_discord_auth/package.json @@ -1,5 +1,5 @@ { - "name": "@expcluster/discord", + "name": "@expcluster/discord-auth", "version": "7.0.0", "description": "Clusterio plugin linking Factorio accounts to Discord accounts and logging in to the web interface with Discord", "author": "Cooldude2606 ", @@ -13,7 +13,7 @@ "coverage": "tap --coverage-report=text test/*.test.js" }, "engines": { - "node": ">=18" + "node": ">=22" }, "peerDependencies": { "@clusterio/controller": "workspace:^", @@ -26,6 +26,7 @@ "@clusterio/host": "workspace:^", "@clusterio/lib": "workspace:^", "@clusterio/web_ui": "workspace:^", + "@types/express": "catalog:", "@types/node": "catalog:", "@types/react": "catalog:", "antd": "catalog:", diff --git a/exp_discord/test/controller.test.js b/exp_discord_auth/test/controller.test.js similarity index 86% rename from exp_discord/test/controller.test.js rename to exp_discord_auth/test/controller.test.js index 707eaf32..c6d084b3 100644 --- a/exp_discord/test/controller.test.js +++ b/exp_discord_auth/test/controller.test.js @@ -26,8 +26,8 @@ async function startPlugin(t2, { config = {} } = {}) { // testdir() empties the folder, so a reload passes the directory in "controller.database_directory": config["controller.database_directory"] ?? t2.testdir(), "controller.public_url": "https://example.com/cluster/", - "exp_discord.client_id": "123", - "exp_discord.client_secret": "secret", + "exp_discord_auth.client_id": "123", + "exp_discord_auth.client_secret": "secret", "controller.auth_secret": Buffer.from("test secret").toString("base64"), ...config, }); @@ -36,7 +36,7 @@ async function startPlugin(t2, { config = {} } = {}) { controller.users.createUser(name); } - const plugin = await ControllerPlugin.fromContext({ plugin: { name: "exp_discord" }, controller, logger }); + const plugin = await ControllerPlugin.fromContext({ plugin: { name: "exp_discord_auth" }, controller, logger }); t2.teardown(() => clearInterval(plugin.cleanupInterval)); return { plugin, controller }; } @@ -57,9 +57,9 @@ async function link(plugin, session, playerName) { t.test("entrypoint", async t2 => { const controllerConfig = new lib.ControllerConfig("controller", { "controller.database_directory": t2.testdir() }); const controller = new Controller(logger, [], controllerConfig); - await entrypoint({ controller, logger, plugin: { name: "exp_discord" }, metrics: undefined }); + await entrypoint({ controller, logger, plugin: { name: "exp_discord_auth" }, metrics: undefined }); for (const hook of ["save", "shutdown"]) { - t2.ok([...controller.hooks[hook].attached].includes("exp_discord"), `attached to ${hook}`); + t2.ok([...controller.hooks[hook].attached].includes("exp_discord_auth"), `attached to ${hook}`); } await controller.hooks.shutdown.invoke(); }); @@ -71,16 +71,23 @@ t.test("oauth", t2 => { const url = new URL(result.redirect); t3.equal(url.origin + url.pathname, "https://discord.com/oauth2/authorize"); t3.equal(url.searchParams.get("client_id"), "123"); - t3.equal(url.searchParams.get("redirect_uri"), "https://example.com/cluster/api/exp_discord/callback"); + t3.equal(url.searchParams.get("redirect_uri"), "https://example.com/cluster/api/exp_discord_auth/callback"); const state = url.searchParams.get("state"); - t3.match(result.cookie, `exp_discord_state=${state}; Path=/cluster/api/exp_discord/callback`); + t3.match(result.cookie, `exp_discord_auth_state=${state}; Path=/cluster/api/exp_discord_auth/callback`); t3.match(result.cookie, "Secure"); }); + t2.test(".status() tells the login form whether Discord is configured", async t3 => { + const { plugin } = await startPlugin(t3); + t3.same(await plugin.status(), { status: 200, json: { configured: true } }); + const { plugin: unconfigured } = await startPlugin(t3, { config: { "exp_discord_auth.client_id": null } }); + t3.same(await unconfigured.status(), { status: 200, json: { configured: false } }); + }); + t2.test(".authorize() without credentials goes back with an error", async t3 => { - const { plugin } = await startPlugin(t3, { config: { "exp_discord.client_secret": null } }); + const { plugin } = await startPlugin(t3, { config: { "exp_discord_auth.client_secret": null } }); const result = await plugin.authorize(); - t3.match(result.redirect, /^https:\/\/example\.com\/cluster\/#exp_discord_error=/); + t3.match(result.redirect, /^https:\/\/example\.com\/cluster\/#exp_discord_auth_error=/); }); t2.test(".callback() rejects a state which does not match the cookie", async t3 => { @@ -88,7 +95,7 @@ t.test("oauth", t2 => { plugin.fetchDiscordUser = async () => t3.fail("should not fetch"); for (const cookie of [undefined, "other"]) { const result = await plugin.callback({ code: "c", state: "s" }, cookie); - t3.match(result.redirect, "#exp_discord_error="); + t3.match(result.redirect, "#exp_discord_auth_error="); } t3.equal(plugin.sessions.size, 0); }); @@ -97,7 +104,7 @@ t.test("oauth", t2 => { const { plugin } = await startPlugin(t3); plugin.fetchDiscordUser = async () => { throw new Error("401"); }; const result = await plugin.callback({ code: "c", state: "s" }, "s"); - t3.match(result.redirect, "#exp_discord_error="); + t3.match(result.redirect, "#exp_discord_auth_error="); }); t2.test(".callback() starts a session", async t3 => { @@ -137,7 +144,8 @@ t.test("linking", t2 => { const { json } = await plugin.linkCode(session); await plugin.handleLinkRequest(new messages.DiscordLinkRequest("Player1", json.code)); await t3.rejects( - plugin.handleLinkRequest(new messages.DiscordLinkRequest("Player2", json.code)), /invalid or has expired/, + plugin.handleLinkRequest(new messages.DiscordLinkRequest("Player2", json.code)), + /invalid or has expired, get a new one from https:\/\/example\.com\/cluster\//, ); }); @@ -156,7 +164,7 @@ t.test("linking", t2 => { }); t2.test("several accounts up to the limit", async t3 => { - const { plugin } = await startPlugin(t3, { config: { "exp_discord.max_accounts": 2 } }); + const { plugin } = await startPlugin(t3, { config: { "exp_discord_auth.max_accounts": 2 } }); const session = await discordLogin(plugin, alice); await link(plugin, session, "Player1"); await link(plugin, session, "Player2"); @@ -189,10 +197,13 @@ t.test("linking", t2 => { t2.test("unlink and get", async t3 => { const { plugin } = await startPlugin(t3); await link(plugin, await discordLogin(plugin, alice), "Player1"); - t3.same(await plugin.handleLinkGetRequest(new messages.DiscordLinkGetRequest("player1")), alice); - t3.same(await plugin.handleUnlinkRequest(new messages.DiscordUnlinkRequest("Player1")), alice); - t3.equal(await plugin.handleLinkGetRequest(new messages.DiscordLinkGetRequest("Player1")), null); - t3.equal(await plugin.handleUnlinkRequest(new messages.DiscordUnlinkRequest("Player1")), null); + const url = "https://example.com/cluster/"; + const get = name => plugin.handleLinkGetRequest(new messages.DiscordLinkGetRequest(name)); + const unlink = name => plugin.handleUnlinkRequest(new messages.DiscordUnlinkRequest(name)); + t3.same(await get("player1"), { link: alice, url }); + t3.same(await unlink("Player1"), { link: alice, url }); + t3.same(await get("Player1"), { link: null, url }); + t3.same(await unlink("Player1"), { link: null, url }); }); t2.test("links are saved and loaded", async t3 => { @@ -242,21 +253,21 @@ t.test("linking from the user page", t2 => { const ticket = await plugin.handleLinkStartRequest(new messages.DiscordLinkStartRequest("Player1")); await plugin.authorize(ticket); const result = await plugin.authorize(ticket); - t3.match(result.redirect, /^https:\/\/example\.com\/cluster\/users#exp_discord_error=Discord%20link%20expired/); + t3.match(result.redirect, /^https:\/\/example\.com\/cluster\/users#exp_discord_auth_error=Discord%20link/); }); t2.test("errors go back to the user page", async t3 => { - const { plugin } = await startPlugin(t3, { config: { "exp_discord.max_accounts": 1 } }); + const { plugin } = await startPlugin(t3, { config: { "exp_discord_auth.max_accounts": 1 } }); await link(plugin, await discordLogin(plugin, alice), "Player2"); let params = await start(plugin, "Player1"); let result = await plugin.callback({ error: "access_denied", state: params.get("state") }, params.get("state")); - t3.match(result.redirect, /\/users\/Player1\/view#exp_discord_error=Discord%20login%20was%20cancelled$/); + t3.match(result.redirect, /\/users\/Player1\/view#exp_discord_auth_error=Discord%20login%20was%20cancelled$/); params = await start(plugin, "Player1"); plugin.fetchDiscordUser = async () => alice; result = await plugin.callback({ code: "c", state: params.get("state") }, params.get("state")); - t3.match(result.redirect, /\/users\/Player1\/view#exp_discord_error=.*already%20has%201/); + t3.match(result.redirect, /\/users\/Player1\/view#exp_discord_auth_error=.*already%20has%201/); t3.same(plugin.accounts.get(alice.id).factorioNames, ["Player2"]); }); @@ -265,7 +276,7 @@ t.test("linking from the user page", t2 => { const params = await start(plugin, "Player1"); plugin.fetchDiscordUser = async () => t3.fail("should not fetch"); const result = await plugin.callback({ code: "c", state: params.get("state") }, undefined); - t3.match(result.redirect, "/users/Player1/view#exp_discord_error="); + t3.match(result.redirect, "/users/Player1/view#exp_discord_auth_error="); t3.notOk(plugin.accounts.has(alice.id)); }); t2.end(); @@ -286,7 +297,9 @@ t.test("permissions", t2 => { const permission = messages.DiscordLinkStartRequest.permission; t3.doesNotThrow(() => permission(user("Alice"), request("alice")), "own account"); t3.throws( - () => permission(user("Alice", ["exp_discord.link.get", "exp_discord.link.delete"]), request("Bob")), + () => permission( + user("Alice", ["exp_discord_auth.link.get", "exp_discord_auth.link.delete"]), request("Bob"), + ), "never someone else's", ); }); @@ -294,8 +307,8 @@ t.test("permissions", t2 => { for (const Request of [messages.DiscordLinkGetRequest, messages.DiscordUnlinkRequest]) { t2.test(Request.name, async t3 => { const permission = Request === messages.DiscordUnlinkRequest - ? "exp_discord.link.delete" - : "exp_discord.link.get"; + ? "exp_discord_auth.link.delete" + : "exp_discord_auth.link.get"; t3.doesNotThrow(() => Request.permission(user("Alice"), request("alice")), "own link"); t3.throws(() => Request.permission(user("Alice"), request("Bob")), "someone else's"); t3.doesNotThrow(() => Request.permission(user("Alice", [permission]), request("Bob")), "with permission"); diff --git a/exp_discord/tsconfig.browser.json b/exp_discord_auth/tsconfig.browser.json similarity index 100% rename from exp_discord/tsconfig.browser.json rename to exp_discord_auth/tsconfig.browser.json diff --git a/exp_discord/tsconfig.json b/exp_discord_auth/tsconfig.json similarity index 100% rename from exp_discord/tsconfig.json rename to exp_discord_auth/tsconfig.json diff --git a/exp_discord/tsconfig.node.json b/exp_discord_auth/tsconfig.node.json similarity index 100% rename from exp_discord/tsconfig.node.json rename to exp_discord_auth/tsconfig.node.json diff --git a/exp_discord/web/components/DiscordLoginForm.tsx b/exp_discord_auth/web/components/DiscordLoginForm.tsx similarity index 77% rename from exp_discord/web/components/DiscordLoginForm.tsx rename to exp_discord_auth/web/components/DiscordLoginForm.tsx index 39f7645e..2c33a5bc 100644 --- a/exp_discord/web/components/DiscordLoginForm.tsx +++ b/exp_discord_auth/web/components/DiscordLoginForm.tsx @@ -3,8 +3,8 @@ import { Alert, Button, Space, Spin, Typography } from "antd"; declare const webRoot: string; -const { Paragraph, Text } = Typography; -const sessionKey = "exp_discord_session"; +const { Link, Paragraph, Text } = Typography; +const sessionKey = "exp_discord_auth_session"; type Accounts = { discord: { id: string, name: string }, @@ -13,7 +13,7 @@ type Accounts = { }; async function api(method: "GET" | "POST", route: string, session: string) { - const response = await fetch(`${webRoot}api/exp_discord/${route}`, { + const response = await fetch(`${webRoot}api/exp_discord_auth/${route}`, { method, headers: { Authorization: `Bearer ${session}` }, }); @@ -27,8 +27,8 @@ async function api(method: "GET" | "POST", route: string, session: string) { /** 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"); + const session = params.get("exp_discord_auth_session"); + const error = params.get("exp_discord_auth_error"); if (session || error) { window.history.replaceState(null, "", window.location.pathname + window.location.search); } @@ -44,6 +44,7 @@ export default function DiscordLoginForm(props: { setToken(token: string): void const [error, setError] = useState(redirect.error); const [accounts, setAccounts] = useState(null); const [code, setCode] = useState(null); + const [configured, setConfigured] = useState(null); const linkedCount = useRef(null); function forget(message: string | null) { @@ -55,6 +56,16 @@ export default function DiscordLoginForm(props: { setToken(token: string): void setError(message); } + useEffect(() => { + if (session || configured !== null) { + return; + } + fetch(`${webRoot}api/exp_discord_auth/status`) + .then(response => response.json()) + .then(json => setConfigured(json.configured)) + .catch(err => setError(`Failed to load Discord login: ${err.message}`)); + }, [session, configured]); + useEffect(() => { if (!session) { return undefined; @@ -110,10 +121,15 @@ export default function DiscordLoginForm(props: { setToken(token: string): void const errorAlert = error && ; if (!session) { + if (configured === false) { + return ; + } return <> {errorAlert} - Log in with your Discord account. Your Factorio account needs to be linked to it first, which you can do after logging in. - + Log in with a linked Discord account. New accounts can be linked after logging in. + ; } @@ -124,7 +140,9 @@ export default function DiscordLoginForm(props: { setToken(token: string): void const canLinkMore = accounts.accounts.length < accounts.max_accounts; return <> {errorAlert} - Logged in to Discord as {accounts.discord.name}. + + Logged in to Discord as {accounts.discord.name}. forget(null)}>Not you? + {accounts.accounts.length ? @@ -155,7 +173,5 @@ export default function DiscordLoginForm(props: { setToken(token: string): void {accounts.accounts.length ? "Link another Factorio account" : "Link a Factorio account"} } - - ; } diff --git a/exp_discord/web/components/UserDiscordLink.tsx b/exp_discord_auth/web/components/UserDiscordLink.tsx similarity index 88% rename from exp_discord/web/components/UserDiscordLink.tsx rename to exp_discord_auth/web/components/UserDiscordLink.tsx index 47ea1249..24d782c9 100644 --- a/exp_discord/web/components/UserDiscordLink.tsx +++ b/exp_discord_auth/web/components/UserDiscordLink.tsx @@ -13,7 +13,7 @@ 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"); + const error = new URLSearchParams(window.location.hash.slice(1)).get("exp_discord_auth_error"); if (error) { window.history.replaceState(null, "", window.location.pathname + window.location.search); } @@ -25,8 +25,8 @@ export default function UserDiscordLink(props: PluginExtensionProps<"UserViewPag 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 canGet = own || account.hasPermission("exp_discord_auth.link.get"); + const canDelete = own || account.hasPermission("exp_discord_auth.link.delete"); const [link, setLink] = useState(undefined); const [error, setError] = useState(readError); @@ -35,7 +35,7 @@ export default function UserDiscordLink(props: PluginExtensionProps<"UserViewPag return; } control.send(new DiscordLinkGetRequest(props.user.name)) - .then(setLink) + .then(response => setLink(response.link)) .catch(notifyErrorHandler("Error loading Discord link")); }, [props.user.name, canGet]); @@ -50,7 +50,7 @@ export default function UserDiscordLink(props: PluginExtensionProps<"UserViewPag async function startLink() { const ticket = await control.send(new DiscordLinkStartRequest(props.user.name)); - window.location.href = `${webRoot}api/exp_discord/authorize?link=${encodeURIComponent(ticket)}`; + window.location.href = `${webRoot}api/exp_discord_auth/authorize?link=${encodeURIComponent(ticket)}`; } return <> diff --git a/exp_discord/web/index.tsx b/exp_discord_auth/web/index.tsx similarity index 68% rename from exp_discord/web/index.tsx rename to exp_discord_auth/web/index.tsx index 31b21b69..cdcd6e87 100644 --- a/exp_discord/web/index.tsx +++ b/exp_discord_auth/web/index.tsx @@ -5,15 +5,15 @@ import DiscordLoginForm from "./components/DiscordLoginForm"; import UserDiscordLink from "./components/UserDiscordLink"; export default function registerPlugin(context: WebPluginContext) { - context.control.hooks.loginForms.attach("exp_discord", () => [ + context.control.hooks.loginForms.attach("exp_discord_auth", () => [ { - name: "exp_discord", + name: "exp_discord_auth", title: "Discord", Component: DiscordLoginForm, }, ]); - context.control.hooks.extensionComponents.attach("exp_discord", () => ({ + context.control.hooks.extensionComponents.attach("exp_discord_auth", () => ({ UserViewPage: UserDiscordLink, })); } diff --git a/exp_discord/webpack.config.cjs b/exp_discord_auth/webpack.config.cjs similarity index 89% rename from exp_discord/webpack.config.cjs rename to exp_discord_auth/webpack.config.cjs index ad9e8b82..0b445740 100644 --- a/exp_discord/webpack.config.cjs +++ b/exp_discord_auth/webpack.config.cjs @@ -13,8 +13,8 @@ module.exports = (env = {}) => merge(common(env), { }, plugins: [ new webpack.container.ModuleFederationPlugin({ - name: "exp_discord", - library: { type: "window", name: "plugin_exp_discord" }, + name: "exp_discord_auth", + library: { type: "window", name: "plugin_exp_discord_auth" }, exposes: { "./": "./index.ts", "./package.json": "./package.json", diff --git a/tsconfig.json b/tsconfig.json index 660ff4d9..aa571e33 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,7 +3,7 @@ "references": [ { "path": "./exp_auto_restart/" }, { "path": "./exp_commands/" }, - { "path": "./exp_discord/" }, + { "path": "./exp_discord_auth/" }, { "path": "./exp_groups/" }, { "path": "./exp_gui/" }, { "path": "./exp_legacy/" },