Merge branch 'main' into translate

This commit is contained in:
phidias authored and GitHub committed 2026-11-26 13:04:32 +09:00
commit 429a62be40
21 files changed
+1626 -22

No files matched your search

+1
View File
@@ -51,6 +51,7 @@ Each plugin has a readme in its folder with its config, permissions and API.
| [Reports (@expcluster/reports)](exp_reports/README.md) | Lets players report each other in game or from the web interface, with optional Discord and JSON webhooks. |
| [Server List (@expcluster/server-list)](exp_server_list/README.md) | Shares the details of every instance with the others, for the server list in game. |
| [Discord Auth (@expcluster/discord-auth)](exp_discord_auth/README.md) | Log in to the web interface with Discord, and link Factorio accounts to a Discord account. |
| [Discord Sync (@expcluster/discord-sync)](exp_discord_sync/README.md) | Gives linked players the Discord roles mapped to their clusterio roles. |
| [Auto Restart (@expcluster/auto-restart)](exp_auto_restart/README.md) | Restarts hosts, and optionally the controller, that need a restart once nobody is playing on them. |
| [Server UPS (@expcluster/server-ups)](exp_server_ups/README.md) | Shows the UPS the server is running at, toggled with `/server-ups`. |
| [Commands (@expcluster/lib_commands)](exp_commands/README.md) | Lua library for commands with typed arguments, aliases and permission checks. |
+3 -3
View File
@@ -56,12 +56,12 @@ ExpDiscordAuth.get_linked(player) -- Prints the Discord account the player is li
## Other plugins
Controller plugins can read links and react to them. Import the plugin class from the controller entrypoint and look it up with the controller.
Controller plugins can read links and react to them. Wait for the plugin from your entrypoint, the class is only needed for its type.
```ts
import { ControllerPlugin as DiscordAuth } from "@expcluster/discord-auth/dist/node/controller.js";
import type { ControllerPlugin as DiscordAuth } from "@expcluster/discord-auth/dist/node/controller.js";
const discordAuth = DiscordAuth.get(controller); // undefined if exp_discord_auth is not loaded
const discordAuth = await plugins.waitFor<DiscordAuth>("exp_discord_auth"); // undefined if exp_discord_auth is not loaded
discordAuth.getLink("Player1"); // { id, name } of the Discord account, or undefined
discordAuth.getAccount(discordId); // { id, name, playerNames }, or undefined
discordAuth.getAccounts(); // every linked Discord account
+1 -10
View File
@@ -50,14 +50,7 @@ export class DiscordAuthHooks extends lib.AsyncHookCollection {
readonly unlinked = this.newHook<[playerName: string, discordUser: DiscordUser]>();
}
const loaded = new WeakMap<Controller, ControllerPlugin>();
export class ControllerPlugin {
/** The plugin loaded on a controller, for other plugins to read links from. */
static get(controller: Controller) {
return loaded.get(controller);
}
hooks: DiscordAuthHooks;
/** Logins which have been through Discord, by session id */
sessions = new Map<string, Session>();
@@ -118,9 +111,7 @@ export class ControllerPlugin {
messages.DiscordAccountRecord.fromJSON.bind(messages.DiscordAccountRecord),
));
const plugin = new ControllerPlugin(controller, context.logger, context.plugin.name, accounts);
loaded.set(controller, plugin);
return plugin;
return new ControllerPlugin(controller, context.logger, context.plugin.name, accounts);
}
async onSave() {
-9
View File
@@ -295,15 +295,6 @@ t.test("api for other plugins", t2 => {
return calls;
}
t2.test("static get() returns the plugin loaded on a controller", async t3 => {
const { plugin, controller } = await startPlugin(t3);
t3.equal(ControllerPlugin.get(controller), plugin);
const other = new Controller(logger, [], new lib.ControllerConfig("controller", {
"controller.database_directory": t3.testdir(),
}));
t3.equal(ControllerPlugin.get(other), undefined);
});
t2.test(".getLink(), .getAccount() and .getAccounts() read links", async t3 => {
const { plugin } = await startPlugin(t3);
const session = await discordLogin(plugin, alice);
+1
View File
@@ -0,0 +1 @@
# Without an .npmignore pnpm packs using the repository .gitignore, which leaves out dist/
+47
View File
@@ -0,0 +1,47 @@
# ExpGaming - Discord Sync
Gives players the Discord roles that match their clusterio roles. Only players who linked their Factorio account with [Discord Auth](../exp_discord_auth/README.md) get roles, and only the Discord roles picked on a role page are ever added or removed.
## Setup
1. In the [Discord developer portal](https://discord.com/developers/applications), open the application (the one used by Discord Auth is fine) and go to Bot. Reset the token to get one, and turn on Server Members Intent.
2. Invite the bot to the server with the Manage Roles permission: `https://discord.com/oauth2/authorize?client_id=<client id>&scope=bot&permissions=268435456`.
3. In the server settings, drag the bot's role above every role it should give. Discord refuses changes to roles above the bot's highest role.
4. Turn on Developer Mode in Discord, right click the server and Copy Server ID.
5. Set the config on the controller:
```
npx clusterioctl controller config set exp_discord_sync.bot_token <bot token>
npx clusterioctl controller config set exp_discord_sync.guild_id <server id>
```
Without Server Members Intent the bot still syncs roles, but a player who joins the Discord server after linking only gets their roles at the next sync instead of straight away.
## Config
All fields are on the controller.
| Field | Default | Description |
|---|---|---|
| `exp_discord_sync.bot_token` | | Token of the Discord bot. Only readable on the controller. |
| `exp_discord_sync.guild_id` | | ID of the Discord server to give roles in. |
## Role mapping
Each role page has a Discord Roles section. Pick roles from the list, which comes from the bot, or type a role ID. Changing it needs the `exp_discord_sync.mapping.update` permission, which nobody has by default. The plugin doesn't compare the editor's own roles against the ones they map, so only give this permission to cluster admins.
A linked player gets every Discord role mapped to any clusterio role held by any of the Factorio accounts linked to their Discord account. A mapped Discord role the player shouldn't have is removed. Roles which are not mapped are never touched, and neither are members who haven't linked.
Removing a role from the mapping, or deleting the clusterio role, leaves that Discord role on the members who have it.
Mappings are stored in `database/exp_discord_sync/role_mappings.json` on the controller.
## When roles are synced
- A player links or unlinks their Discord account.
- A user's clusterio roles change.
- A linked player joins the Discord server (needs Server Members Intent).
- A role mapping changes, which syncs every linked player.
- The bot connects to Discord, which syncs every linked player. This happens on startup and whenever the connection to Discord drops and comes back, so joins missed while disconnected are caught up.
Requests go to Discord one at a time and wait when Discord answers with a rate limit.
+333
View File
@@ -0,0 +1,333 @@
import type { Controller, ControllerPluginContext } from "@clusterio/controller";
import * as lib from "@clusterio/lib";
import * as path from "node:path";
import type { ControllerPlugin as DiscordAuth } from "@expcluster/discord-auth/dist/node/controller.js";
import * as messages from "./messages.js";
import {
DiscordApiError, DiscordGateway, DiscordRest, GuildMember, gatewayIntents,
} from "./discord.js";
const snowflake = /^\d{17,20}$/;
function roleKey(roleIds: Iterable<number>) {
return [...roleIds].sort((a, b) => a - b).join(",");
}
export class ControllerPlugin {
/** Discord accounts waiting to be synced */
pending = new Set<string>();
syncAll = false;
/** Resolves once the queue is empty */
draining?: Promise<void>;
/** Roles of each user as last seen, so updates which don't touch roles are ignored */
userRoles = new Map<string, string>();
private constructor(
public controller: Controller,
public logger: lib.Logger,
public name: string,
public mappings: lib.SubscribableDatastore<messages.RoleMappingRecord>,
/** Undefined if exp_discord_auth did not load, nothing is synced then */
public discordAuth: DiscordAuth | undefined,
public rest: DiscordRest,
public gateway: DiscordGateway,
) {}
static async fromContext(context: ControllerPluginContext) {
const controller = context.controller;
const databaseDirectory = controller.config.get("controller.database_directory");
const mappings = await lib.SubscribableDatastore.fromProvider(new lib.JsonIdDatastoreProvider(
path.join(databaseDirectory, "exp_discord_sync", "role_mappings.json"),
messages.RoleMappingRecord.fromJSON.bind(messages.RoleMappingRecord),
));
const discordAuth = await context.plugins.waitFor<DiscordAuth>("exp_discord_auth");
const token = () => controller.config.get("exp_discord_sync.bot_token") ?? "";
const rest = new DiscordRest(token);
const gateway = new DiscordGateway(token, gatewayIntents.GUILD_MEMBERS, context.logger);
const plugin = new ControllerPlugin(
controller, context.logger, context.plugin.name, mappings, discordAuth, rest, gateway,
);
plugin.sweepMappings();
for (const user of controller.users.values()) {
plugin.userRoles.set(user.id, roleKey(user.roleIds));
}
controller.subscriptions.handle(
messages.RoleMappingUpdatedEvent, plugin.handleMappingSubscription.bind(plugin)
);
controller.handle(messages.RoleMappingUpdateRequest, plugin.handleMappingUpdateRequest.bind(plugin));
controller.handle(messages.GuildRoleListRequest, plugin.handleGuildRoleListRequest.bind(plugin));
mappings.on("update", plugin.mappingsUpdated.bind(plugin));
controller.roles.on("update", plugin.sweepMappings.bind(plugin));
controller.users.records.on("update", plugin.usersUpdated.bind(plugin));
const hooks = controller.hooks;
hooks.save.attach(plugin.name, plugin.onSave.bind(plugin));
hooks.shutdown.attach(plugin.name, plugin.onShutdown.bind(plugin));
hooks.controllerConfigFieldChanged.attach(plugin.name, plugin.onControllerConfigFieldChanged.bind(plugin));
discordAuth?.hooks.linked.attach(plugin.name, plugin.onLinkChanged.bind(plugin));
discordAuth?.hooks.unlinked.attach(plugin.name, plugin.onLinkChanged.bind(plugin));
gateway.on("ready", plugin.onGatewayReady.bind(plugin));
gateway.on("dispatch", plugin.onGatewayDispatch.bind(plugin));
gateway.on("fatalClose", plugin.onGatewayFatalClose.bind(plugin));
plugin.connect();
return plugin;
}
async onSave() {
await this.mappings.save();
}
async onShutdown() {
this.disconnect();
await this.mappings.save();
}
async onControllerConfigFieldChanged(field: string) {
if (field === "exp_discord_sync.bot_token" || field === "exp_discord_sync.guild_id") {
this.disconnect();
this.connect();
}
}
/*
Discord connection
*/
/** The configured guild, or undefined if the bot is not configured or can't sync */
get guildId() {
const token = this.controller.config.get("exp_discord_sync.bot_token");
const guildId = this.controller.config.get("exp_discord_sync.guild_id");
return token && guildId && this.discordAuth ? guildId : undefined;
}
connect() {
const token = this.controller.config.get("exp_discord_sync.bot_token");
const guildId = this.controller.config.get("exp_discord_sync.guild_id");
if (!token || !guildId) {
return;
}
if (!this.discordAuth) {
this.logger.error("exp_discord_auth is not loaded, Discord roles can not be synced");
return;
}
this.gateway.start();
}
disconnect() {
this.gateway.stop();
this.pending.clear();
this.syncAll = false;
}
// Joins are missed while disconnected, so every (re)connect syncs everyone
onGatewayReady() {
this.queueAll();
}
onGatewayDispatch(type: string, data: any) {
if (type === "GUILD_MEMBER_ADD" && data.guild_id === this.guildId) {
this.queue(data.user.id);
}
}
onGatewayFatalClose(code: number, reason: string) {
if (code === 4014) {
this.logger.warn(
"The Discord bot is missing the Server Members intent, joining the server does not give roles"
);
this.queueAll();
} else {
this.logger.error(`Discord gateway refused the bot with ${code}: ${reason}`);
}
}
onLinkChanged(_playerName: string, discordUser: { id: string }) {
this.queue(discordUser.id);
}
/*
Syncing
*/
queue(discordId: string) {
if (!this.guildId) {
return;
}
this.pending.add(discordId);
this.drain();
}
queueAll() {
if (!this.guildId) {
return;
}
this.syncAll = true;
this.drain();
}
drain() {
this.draining ??= this._processQueue().finally(() => { this.draining = undefined; });
return this.draining;
}
private async _processQueue() {
while (this.syncAll || this.pending.size) {
if (this.syncAll) {
this.syncAll = false;
for (const account of this.discordAuth?.getAccounts() ?? []) {
this.pending.add(account.id);
}
}
const [discordId] = this.pending;
if (discordId === undefined) {
continue;
}
this.pending.delete(discordId);
try {
await this.syncAccount(discordId);
} catch (err: any) {
if (err instanceof DiscordApiError && err.status === 403) {
this.logger.warn(
`Discord refused to change roles of ${discordId}, the bot needs Manage Roles `
+ "and a role above every mapped role"
);
} else {
this.logger.warn(`Failed to sync Discord roles of ${discordId}: ${err.message}`);
}
}
}
}
/** Every Discord role this plugin gives, any other role is left alone. */
managedRoleIds() {
const managed = new Set<string>();
for (const mapping of this.mappings.values()) {
for (const id of mapping.discordRoleIds) {
managed.add(id);
}
}
return managed;
}
/** The mapped Discord roles for the clusterio roles of every player linked to the account. */
wantedRoleIds(discordId: string) {
const wanted = new Set<string>();
const account = this.discordAuth?.getAccount(discordId);
for (const playerName of account?.playerNames ?? []) {
const user = this.controller.users.getByName(playerName);
for (const roleId of user?.roleIds ?? []) {
for (const id of this.mappings.get(roleId)?.discordRoleIds ?? []) {
wanted.add(id);
}
}
}
return wanted;
}
async syncAccount(discordId: string) {
const managed = this.managedRoleIds();
const guildId = this.guildId;
if (!guildId || !managed.size) {
return;
}
const rest = this.rest;
const member: GuildMember | undefined = await rest.getGuildMember(guildId, discordId);
if (!member) {
return;
}
const wanted = this.wantedRoleIds(discordId);
const current = new Set(member.roles);
for (const id of wanted) {
if (!current.has(id)) {
await rest.addMemberRole(guildId, discordId, id);
}
}
for (const id of current) {
if (managed.has(id) && !wanted.has(id)) {
await rest.removeMemberRole(guildId, discordId, id);
}
}
}
usersUpdated(users: lib.UserDetails[]) {
for (const user of users) {
const key = user.isDeleted ? "" : roleKey(user.roleIds);
if (this.userRoles.get(user.id) === key) {
continue;
}
if (user.isDeleted) {
this.userRoles.delete(user.id);
} else {
this.userRoles.set(user.id, key);
}
const link = this.guildId ? this.discordAuth?.getLink(user.name) : undefined;
if (link) {
this.queue(link.id);
}
}
}
/*
Role mappings
*/
/** Mappings of deleted roles, the Discord roles they gave stay on members. */
sweepMappings() {
const orphaned = [...this.mappings.valuesMutable()].filter(mapping => !this.controller.roles.has(mapping.id));
if (orphaned.length) {
this.mappings.deleteMany(orphaned);
}
}
mappingsUpdated(updates: messages.RoleMappingRecord[]) {
this.controller.subscriptions.broadcast(new messages.RoleMappingUpdatedEvent(updates));
}
async handleMappingSubscription(request: lib.SubscriptionRequest) {
const updates = [...this.mappings.values()].filter(mapping => mapping.updatedAtMs > request.lastRequestTimeMs);
return updates.length ? new messages.RoleMappingUpdatedEvent(updates) : null;
}
async handleMappingUpdateRequest(request: messages.RoleMappingUpdateRequest) {
if (!this.controller.roles.has(request.roleId)) {
throw new lib.NotFoundError(`Role with ID ${request.roleId} does not exist`);
}
const discordRoleIds = [...new Set(request.discordRoleIds)];
const invalid = discordRoleIds.filter(id => !snowflake.test(id));
if (invalid.length) {
throw new lib.ValidationError(`Not a Discord role ID: ${invalid.join(", ")}`);
}
const existing = this.mappings.getMutable(request.roleId);
if (!discordRoleIds.length) {
if (existing) {
this.mappings.delete(existing);
}
} else {
this.mappings.set(new messages.RoleMappingRecord(request.roleId, discordRoleIds));
}
this.queueAll();
}
async handleGuildRoleListRequest() {
const guildId = this.guildId;
if (!guildId) {
throw new lib.UnavailableError("The Discord bot is not configured");
}
const roles = await this.rest.getGuildRoles(guildId);
return roles
// @everyone has the guild id, and integration roles can't be given by bots
.filter(role => role.id !== guildId && !role.managed)
.sort((a, b) => b.position - a.position)
.map(role => ({ id: role.id, name: role.name, color: role.color }));
}
}
export default ControllerPlugin.fromContext.bind(ControllerPlugin);
+265
View File
@@ -0,0 +1,265 @@
import * as lib from "@clusterio/lib";
import { EventEmitter } from "node:events";
import { setTimeout as sleep } from "node:timers/promises";
export const discordApi = "https://discord.com/api/v10";
export const discordGateway = "wss://gateway.discord.gg/?v=10&encoding=json";
const userAgent = "DiscordBot (https://github.com/explosivegaming/ExpCluster, 7)";
const maxRetries = 5;
export type GuildRole = { id: string, name: string, color: number, position: number, managed: boolean };
export type GuildMember = { user: { id: string }, roles: string[] };
export class DiscordApiError extends Error {
constructor(
public status: number,
message: string,
) {
super(message);
}
}
/** Bot requests to the Discord REST API, sent one at a time and waiting out rate limits. */
export class DiscordRest {
/** Requests wait until this time when Discord says a rate limit is used up */
waitUntilMs = 0;
private _queue: Promise<unknown> = Promise.resolve();
constructor(
/** Read on every request so a new token applies right away */
private _token: () => string,
public baseUrl = discordApi,
) {}
request(method: string, route: string): Promise<unknown> {
const result = this._queue.then(() => this._send(method, route));
this._queue = result.catch(() => {});
return result;
}
private async _send(method: string, route: string) {
for (let attempt = 0; ; attempt++) {
const waitMs = this.waitUntilMs - Date.now();
if (waitMs > 0) {
await sleep(waitMs);
}
const response = await fetch(`${this.baseUrl}${route}`, {
method,
headers: { "Authorization": `Bot ${this._token()}`, "User-Agent": userAgent },
});
if (response.headers.get("x-ratelimit-remaining") === "0") {
const resetAfter = Number(response.headers.get("x-ratelimit-reset-after")) || 0;
this.waitUntilMs = Date.now() + resetAfter * 1e3;
}
if (response.status === 429 && attempt < maxRetries) {
const body = await response.json().catch(() => ({})) as { retry_after?: number };
const retryAfter = body.retry_after ?? (Number(response.headers.get("retry-after")) || 1);
this.waitUntilMs = Date.now() + retryAfter * 1e3;
continue;
}
if (!response.ok) {
throw new DiscordApiError(
response.status, `${method} ${route} responded with ${response.status}: ${await response.text()}`
);
}
return response.status === 204 ? undefined : response.json();
}
}
async getGuildRoles(guildId: string) {
return await this.request("GET", `/guilds/${guildId}/roles`) as GuildRole[];
}
/** Undefined when the user is not in the guild. */
async getGuildMember(guildId: string, userId: string) {
try {
return await this.request("GET", `/guilds/${guildId}/members/${userId}`) as GuildMember;
} catch (err) {
if (err instanceof DiscordApiError && err.status === 404) {
return undefined;
}
throw err;
}
}
async addMemberRole(guildId: string, userId: string, roleId: string) {
await this.request("PUT", `/guilds/${guildId}/members/${userId}/roles/${roleId}`);
}
async removeMemberRole(guildId: string, userId: string, roleId: string) {
await this.request("DELETE", `/guilds/${guildId}/members/${userId}/roles/${roleId}`);
}
}
export const gatewayIntents = { GUILD_MEMBERS: 1 << 1 };
/** Close codes after which reconnecting would fail the same way, such as a bad token or missing intent. */
export const fatalCloseCodes = new Set([4004, 4010, 4011, 4012, 4013, 4014]);
type GatewayPayload = { op: number, d: any, s: number | null, t: string | null };
/**
* stopped: not started, stopped, or closed with a fatal code.
* connecting: socket open, waiting for Hello.
* identifying: identify sent, waiting for READY.
* ready: receiving dispatches.
* waiting: closed, reconnecting after a backoff.
*/
export type GatewayState = "stopped" | "connecting" | "identifying" | "ready" | "waiting";
const gatewayTransitions: Record<GatewayState, GatewayState[]> = {
stopped: ["connecting"],
connecting: ["identifying", "waiting", "stopped"],
identifying: ["ready", "waiting", "stopped"],
ready: ["waiting", "stopped"],
waiting: ["connecting", "stopped"],
};
export type GatewayEvents = {
ready: [],
dispatch: [type: string, data: any],
fatalClose: [code: number, reason: string],
};
/**
* Minimal Discord gateway connection which only receives dispatch events.
*
* It identifies again on every reconnect instead of resuming, so events sent
* while disconnected are missed. The ready event is the place to catch up on them.
*/
export class DiscordGateway extends EventEmitter<GatewayEvents> {
state: GatewayState = "stopped";
backoff = new lib.ExponentialBackoff({ base: 2, max: 60 });
private _ws?: WebSocket;
private _heartbeatTimer?: ReturnType<typeof setTimeout>;
private _reconnectTimer?: ReturnType<typeof setTimeout>;
private _sequence: number | null = null;
private _acked = true;
constructor(
/** Read on every identify so a new token applies on the next start */
private _token: () => string,
private _intents: number,
private _logger: lib.Logger,
public url = discordGateway,
) {
super();
}
start() {
this._connect();
}
stop() {
if (this.state === "stopped") {
return;
}
this._setState("stopped");
clearTimeout(this._reconnectTimer);
this._close(1000);
}
private _setState(next: GatewayState) {
if (!gatewayTransitions[this.state].includes(next)) {
throw new Error(`Invalid Discord gateway transition from ${this.state} to ${next}`);
}
this.state = next;
}
private _connect() {
this._setState("connecting");
const ws = new WebSocket(this.url);
this._ws = ws;
this._acked = true;
ws.addEventListener("message", event => {
try {
this._receive(JSON.parse(String(event.data)));
} catch (err: any) {
this._logger.error(`Discord gateway failed to handle a message:\n${err.stack}`);
}
});
ws.addEventListener("close", event => this._closed(ws, event.code, event.reason));
ws.addEventListener("error", () => {});
}
private _close(code: number) {
clearTimeout(this._heartbeatTimer);
if (this._ws && this._ws.readyState <= WebSocket.OPEN) {
this._ws.close(code);
}
}
private _send(op: number, d: unknown) {
this._ws?.send(JSON.stringify({ op, d }));
}
private _heartbeat(intervalMs: number) {
if (!this._acked) {
this._logger.warn("Discord gateway stopped answering heartbeats, reconnecting");
this._close(4000);
return;
}
this._acked = false;
this._send(1, this._sequence);
this._heartbeatTimer = setTimeout(() => this._heartbeat(intervalMs), intervalMs);
}
private _receive(payload: GatewayPayload) {
if (payload.s !== null && payload.s !== undefined) {
this._sequence = payload.s;
}
switch (payload.op) {
case 10: { // Hello
this._setState("identifying");
const intervalMs = payload.d.heartbeat_interval;
this._heartbeatTimer = setTimeout(() => this._heartbeat(intervalMs), intervalMs * Math.random());
this._send(2, {
token: this._token(),
intents: this._intents,
properties: { os: process.platform, browser: "exp_discord_sync", device: "exp_discord_sync" },
});
break;
}
case 11: // Heartbeat ACK
this._acked = true;
break;
case 1: // Heartbeat request
this._send(1, this._sequence);
break;
case 7: // Reconnect
case 9: // Invalid session
this._close(4000);
break;
case 0: // Dispatch
if (payload.t === "READY") {
this._setState("ready");
this.emit("ready");
} else {
this.emit("dispatch", payload.t!, payload.d);
}
break;
default:
}
}
private _closed(ws: WebSocket, code: number, reason: string) {
if (ws !== this._ws) {
return;
}
clearTimeout(this._heartbeatTimer);
this._sequence = null;
if (this.state === "stopped") {
return;
}
if (fatalCloseCodes.has(code)) {
this._setState("stopped");
this.emit("fatalClose", code, reason);
return;
}
this._setState("waiting");
const delayMs = this.backoff.delay();
this._logger.verbose(`Discord gateway closed with ${code}, reconnecting in ${Math.round(delayMs / 1e3)}s`);
this._reconnectTimer = setTimeout(() => this._connect(), delayMs);
}
}
+52
View File
@@ -0,0 +1,52 @@
import * as lib from "@clusterio/lib";
import * as messages from "./messages.js";
declare module "@clusterio/lib" {
export interface ControllerConfigFields {
"exp_discord_sync.bot_token": string | null;
"exp_discord_sync.guild_id": string | null;
}
export interface Permissions {
"exp_discord_sync.mapping.update": never;
}
}
export const plugin: lib.PluginDeclaration = {
name: "exp_discord_sync",
title: "ExpGaming - Discord Sync",
description: "Clusterio plugin giving players linked with exp_discord_auth the Discord roles mapped to their clusterio roles",
messages: [
messages.RoleMappingUpdatedEvent,
messages.RoleMappingUpdateRequest,
messages.GuildRoleListRequest,
],
permissions: [
{
name: "exp_discord_sync.mapping.update",
title: "Update Discord Roles",
description: "Change which Discord roles are given to players holding a role.",
grantByDefault: false,
},
],
controllerEntrypoint: "./dist/node/controller.js",
controllerConfigFields: {
"exp_discord_sync.bot_token": {
title: "Bot Token",
description: "Token of the Discord bot which gives the roles.",
type: "string",
credential: ["controller"],
optional: true,
},
"exp_discord_sync.guild_id": {
title: "Guild ID",
description: "ID of the Discord server to give roles in.",
type: "string",
optional: true,
},
},
webEntrypoint: "./web",
};
+115
View File
@@ -0,0 +1,115 @@
import * as lib from "@clusterio/lib";
import { Type, Static } from "@sinclair/typebox";
/*
Data records
*/
/** The Discord roles given to linked players holding a clusterio role. */
export class RoleMappingRecord {
constructor(
/** Clusterio role id */
public id: number,
public discordRoleIds: string[],
public updatedAtMs: number = 0,
public isDeleted: boolean = false,
) {}
static jsonSchema = Type.Object({
id: Type.Integer(),
discord_role_ids: Type.Array(Type.String()),
updated_at_ms: Type.Optional(Type.Number()),
is_deleted: Type.Optional(Type.Boolean()),
});
toJSON() {
const json: Static<typeof RoleMappingRecord.jsonSchema> = {
id: this.id,
discord_role_ids: this.discordRoleIds,
};
if (this.updatedAtMs) {
json.updated_at_ms = this.updatedAtMs;
}
if (this.isDeleted) {
json.is_deleted = true;
}
return json;
}
static fromJSON(json: Static<typeof this.jsonSchema>) {
return new this(json.id, json.discord_role_ids, json.updated_at_ms ?? 0, json.is_deleted ?? false);
}
}
export class RoleMappingUpdatedEvent {
declare ["constructor"]: typeof RoleMappingUpdatedEvent;
static plugin = "exp_discord_sync" as const;
static type = "event" as const;
static src = "controller" as const;
static dst = "control" as const;
static permission = "core.role.subscribe" as const;
constructor(
public updates: RoleMappingRecord[],
) {}
static jsonSchema = Type.Object({
updates: Type.Array(RoleMappingRecord.jsonSchema),
});
toJSON() {
return { updates: this.updates.map(mapping => mapping.toJSON()) };
}
static fromJSON(json: Static<typeof this.jsonSchema>) {
return new this(json.updates.map(mapping => RoleMappingRecord.fromJSON(mapping)));
}
}
/** Set the Discord roles of a clusterio role, an empty list removes the mapping. */
export class RoleMappingUpdateRequest {
declare ["constructor"]: typeof RoleMappingUpdateRequest;
static plugin = "exp_discord_sync" as const;
static type = "request" as const;
static src = "control" as const;
static dst = "controller" as const;
static permission = "exp_discord_sync.mapping.update" as const;
constructor(
public roleId: number,
public discordRoleIds: string[],
) {}
static jsonSchema = Type.Object({
role_id: Type.Integer(),
discord_role_ids: Type.Array(Type.String()),
});
toJSON() {
return { role_id: this.roleId, discord_role_ids: this.discordRoleIds };
}
static fromJSON(json: Static<typeof this.jsonSchema>) {
return new this(json.role_id, json.discord_role_ids);
}
}
const GuildRole = Type.Object({
id: Type.String(),
name: Type.String(),
color: Type.Integer(),
});
/** The roles of the configured guild which the bot can give, highest first. */
export class GuildRoleListRequest {
declare ["constructor"]: typeof GuildRoleListRequest;
static plugin = "exp_discord_sync" as const;
static type = "request" as const;
static src = "control" as const;
static dst = "controller" as const;
static permission = "core.role.list" as const;
static Response = lib.plainJson(Type.Array(GuildRole));
}
+54
View File
@@ -0,0 +1,54 @@
{
"name": "@expcluster/discord-sync",
"version": "7.0.5",
"description": "Clusterio plugin giving players linked with exp_discord_auth the Discord roles mapped to their clusterio roles",
"author": "Cooldude2606 <https://github.com/Cooldude2606>",
"license": "MIT",
"repository": "explosivegaming/ExpCluster",
"type": "module",
"main": "dist/node/index.js",
"scripts": {
"prepare": "tsc --build && vite build",
"test": "tap --type-strip-only --disable-coverage --allow-empty-coverage test/*.test.js",
"coverage": "tap --coverage-report=text test/*.test.js"
},
"engines": {
"node": ">=22"
},
"peerDependencies": {
"@clusterio/controller": "workspace:^",
"@clusterio/lib": "workspace:^"
},
"peerDependenciesMeta": {
"@clusterio/controller": {
"optional": true
}
},
"devDependencies": {
"@clusterio/controller": "workspace:^",
"@clusterio/lib": "workspace:^",
"@clusterio/web_ui": "workspace:^",
"@types/node": "catalog:",
"@types/react": "catalog:",
"antd": "catalog:",
"react": "catalog:",
"react-dom": "catalog:",
"react-router-dom": "catalog:",
"tap": "^21.1.0",
"typescript": "catalog:",
"vite": "catalog:",
"ws": "catalog:"
},
"dependencies": {
"@sinclair/typebox": "catalog:",
"@expcluster/discord-auth": "workspace:^"
},
"publishConfig": {
"access": "public"
},
"keywords": [
"clusterio",
"clusterio-plugin",
"factorio"
]
}
+320
View File
@@ -0,0 +1,320 @@
import t from "tap";
import { fileURLToPath } from "node:url";
import * as lib from "@clusterio/lib";
import { Controller } from "@clusterio/controller";
import { plugin as discordAuthDeclaration } from "@expcluster/discord-auth/dist/node/index.js";
import entrypoint, { ControllerPlugin } from "../dist/node/controller.js";
import * as messages from "../dist/node/messages.js";
import { plugin as pluginDeclaration } from "../dist/node/index.js";
import { guildId, startFakeDiscord, until } from "./fake_discord.js";
for (const Message of [...pluginDeclaration.messages, ...discordAuthDeclaration.messages]) {
lib.Link.register(Message);
}
lib.addPluginConfigFields([pluginDeclaration, discordAuthDeclaration]);
const warnings = [];
const logger = {
child: () => logger, info: () => {}, error: msg => warnings.push(msg), verbose: () => {},
warn: msg => warnings.push(msg),
};
/** Plugin infos as the controller has them, sync is listed before auth */
const packagePath = relative => fileURLToPath(new URL(relative, import.meta.url));
const pluginInfos = [
{ ...pluginDeclaration, packagePath: packagePath("../package.json") },
{ ...discordAuthDeclaration, packagePath: packagePath("../../exp_discord_auth/package.json") },
];
const noPlugins = { waitFor: async () => undefined, checkInstalled: () => false, checkEnabled: () => false };
lib.logger.silent = true;
t.after(() => {
lib.logger.silent = false;
});
const discordRoles = { moderator: "200000000000000001", trusted: "200000000000000002", other: "200000000000000003" };
const alice = { id: "300000000000000001", name: "Alice" };
const bob = { id: "300000000000000002", name: "Bob" };
const role = (id, name) => new lib.Role(id, name, "", new Set());
/**
* exp_discord_sync and exp_discord_auth on a real controller, talking to a fake Discord.
*
* Loaded the way the controller loads them, with sync listed before auth.
*/
const defaultMappings = { 5: [discordRoles.moderator], 6: [discordRoles.trusted] };
async function startPlugin(t2, { fakeOptions, mappings = defaultMappings } = {}) {
const fake = await startFakeDiscord(fakeOptions);
t2.teardown(fake.close);
fake.roles.push(
{ id: discordRoles.moderator, name: "Moderator", color: 0xff0000, position: 3, managed: false },
{ id: discordRoles.trusted, name: "Trusted", color: 0, position: 2, managed: false },
{ id: discordRoles.other, name: "Other", color: 0, position: 1, managed: false },
{ id: "200000000000000004", name: "Some Bot", color: 0, position: 4, managed: true },
);
const controllerConfig = new lib.ControllerConfig("controller", {
"controller.database_directory": t2.testdir(),
"controller.auth_secret": Buffer.from("test secret").toString("base64"),
});
const controller = new Controller(logger, [], controllerConfig);
controller.roles.set(role(5, "Moderator"));
controller.roles.set(role(6, "Trusted"));
controller.roles.set(role(7, "Regular"));
for (const name of ["Player1", "Player2", "Player3"]) {
controller.users.createUser(name);
}
const { loaded } = await lib.PluginLoader.load({
type: "controller",
context: { controller, metrics: undefined },
logger,
installed: pluginInfos,
load: pluginInfos,
});
const [plugin, auth] = loaded.values();
t2.teardown(() => plugin.disconnect());
t2.teardown(() => clearInterval(auth.cleanupInterval));
for (const [roleId, ids] of Object.entries(mappings)) {
plugin.mappings.set(new messages.RoleMappingRecord(Number(roleId), ids));
}
plugin.rest.baseUrl = fake.apiBase;
plugin.gateway.url = fake.gatewayUrl;
controller.config.set("exp_discord_sync.bot_token", "token");
controller.config.set("exp_discord_sync.guild_id", guildId);
if (plugin.gateway.state === "stopped") {
plugin.connect();
}
return { plugin, auth, controller, fake };
}
function setRoles(controller, name, roleIds) {
controller.users.getByNameMutable(name).set("roleIds", new Set(roleIds));
}
const rolesOf = (fake, id) => [...fake.members.get(id)].sort();
async function settled(plugin) {
await until(() => !plugin.draining && !plugin.pending.size);
}
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_sync" }, metrics: undefined, plugins: noPlugins,
});
for (const hook of ["save", "shutdown", "controllerConfigFieldChanged"]) {
t2.ok([...controller.hooks[hook].attached].includes("exp_discord_sync"), `attached to ${hook}`);
}
await controller.hooks.shutdown.invoke();
});
t.test("syncing", t2 => {
t2.test("connecting syncs every linked account and only touches mapped roles", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3);
await plugin.drain();
fake.members.set(alice.id, new Set([discordRoles.trusted, discordRoles.other]));
fake.members.set(bob.id, new Set([discordRoles.trusted]));
setRoles(controller, "Player1", [5]);
auth.linkAccount(alice, "Player1");
await settled(plugin);
plugin.disconnect();
fake.members.set(alice.id, new Set([discordRoles.trusted, discordRoles.other]));
plugin.connect();
await until(() => fake.identifies.length === 2);
await until(() => rolesOf(fake, alice.id).join() === [discordRoles.moderator, discordRoles.other].join());
t3.same(rolesOf(fake, bob.id), [discordRoles.trusted], "unlinked member is left alone");
});
t2.test("roles come from every player linked to the account", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3);
fake.members.set(alice.id, new Set());
setRoles(controller, "Player1", [5]);
setRoles(controller, "Player2", [6, 7]);
auth.linkAccount(alice, "Player1");
auth.linkAccount(alice, "Player2");
await until(() => rolesOf(fake, alice.id).length === 2);
t3.same(rolesOf(fake, alice.id), [discordRoles.moderator, discordRoles.trusted]);
});
t2.test("unlinking takes the roles away", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3);
fake.members.set(alice.id, new Set([discordRoles.other]));
setRoles(controller, "Player1", [5]);
auth.linkAccount(alice, "Player1");
await until(() => rolesOf(fake, alice.id).length === 2);
auth.removeLink("Player1");
await until(() => rolesOf(fake, alice.id).length === 1);
t3.same(rolesOf(fake, alice.id), [discordRoles.other]);
await settled(plugin);
});
t2.test("role changes in clusterio are passed on, other user updates are not", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3);
fake.members.set(alice.id, new Set());
auth.linkAccount(alice, "Player1");
await settled(plugin);
setRoles(controller, "Player1", [6]);
await until(() => rolesOf(fake, alice.id).length === 1);
t3.same(rolesOf(fake, alice.id), [discordRoles.trusted]);
setRoles(controller, "Player1", [5]);
await until(() => rolesOf(fake, alice.id)[0] === discordRoles.moderator);
t3.same(rolesOf(fake, alice.id), [discordRoles.moderator]);
await settled(plugin);
fake.requests.length = 0;
controller.users.getByNameMutable("Player1").set("isAdmin", true);
setRoles(controller, "Player2", [5]);
await settled(plugin);
t3.same(fake.requests, [], "no requests for unlinked users or other fields");
});
t2.test("a member joining the guild gets their roles", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3);
setRoles(controller, "Player1", [5]);
auth.linkAccount(alice, "Player1");
await settled(plugin);
fake.members.set(alice.id, new Set());
fake.dispatch("GUILD_MEMBER_ADD", { guild_id: guildId, user: { id: alice.id }, roles: [] });
await until(() => rolesOf(fake, alice.id).length === 1);
t3.same(rolesOf(fake, alice.id), [discordRoles.moderator]);
});
t2.test("roles Discord refuses are logged and the rest carry on", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3);
fake.roles.find(r => r.id === discordRoles.moderator).name = "Above bot";
fake.members.set(alice.id, new Set());
fake.members.set(bob.id, new Set());
setRoles(controller, "Player1", [5]);
setRoles(controller, "Player2", [6]);
warnings.length = 0;
auth.linkAccount(alice, "Player1");
auth.linkAccount(bob, "Player2");
await until(() => rolesOf(fake, bob.id).length === 1);
t3.ok(warnings.some(msg => /Discord refused to change roles of 300000000000000001/.test(msg)));
await settled(plugin);
});
t2.test("a bot without the members intent still syncs", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3, { fakeOptions: { closeCode: 4014 } });
await until(() => fake.identifies.length === 1);
await settled(plugin);
fake.members.set(alice.id, new Set());
setRoles(controller, "Player1", [5]);
auth.linkAccount(alice, "Player1");
await until(() => rolesOf(fake, alice.id).length === 1);
t3.equal(plugin.gateway.state, "stopped", "gateway gave up, REST carries on");
t3.ok(warnings.some(msg => /missing the Server Members intent/.test(msg)));
});
t2.test("nothing is sent while the bot is not configured", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3);
await settled(plugin);
controller.config.set("exp_discord_sync.bot_token", null);
plugin.disconnect();
plugin.connect();
fake.requests.length = 0;
fake.members.set(alice.id, new Set());
setRoles(controller, "Player1", [5]);
auth.linkAccount(alice, "Player1");
await settled(plugin);
t3.same(fake.requests, []);
t3.ok(await plugin.handleGuildRoleListRequest().catch(err => err) instanceof lib.UnavailableError);
});
t2.test("nothing is synced without exp_discord_auth", async t3 => {
const controller = new Controller(logger, [], new lib.ControllerConfig("controller", {
"controller.database_directory": t3.testdir(),
}));
controller.config.set("exp_discord_sync.bot_token", "token");
controller.config.set("exp_discord_sync.guild_id", guildId);
warnings.length = 0;
const { loaded } = await lib.PluginLoader.load({
type: "controller",
context: { controller, metrics: undefined },
logger,
installed: pluginInfos,
load: [pluginInfos[0]],
});
const [plugin] = loaded.values();
t3.equal(plugin.discordAuth, undefined);
t3.equal(plugin.gateway.state, "stopped", "does not connect");
t3.ok(warnings.some(msg => /exp_discord_auth is not loaded/.test(msg)));
});
t2.end();
});
t.test("role mappings", t2 => {
t2.test("RoleMappingUpdateRequest sets, validates and removes mappings", async t3 => {
const { fake, auth, controller, plugin } = await startPlugin(t3, { mappings: {} });
fake.members.set(alice.id, new Set());
setRoles(controller, "Player1", [7]);
auth.linkAccount(alice, "Player1");
await settled(plugin);
const update = (roleId, ids) => plugin.handleMappingUpdateRequest(
new messages.RoleMappingUpdateRequest(roleId, ids)
);
await update(7, [discordRoles.other, discordRoles.other]);
t3.same(plugin.mappings.get(7).discordRoleIds, [discordRoles.other], "duplicates are dropped");
await until(() => rolesOf(fake, alice.id).length === 1);
t3.ok(await update(7, ["abc"]).catch(err => err) instanceof lib.ValidationError);
t3.ok(await update(99, [discordRoles.other]).catch(err => err) instanceof lib.NotFoundError);
await update(7, []);
t3.notOk(plugin.mappings.has(7), "empty list removes the mapping");
await settled(plugin);
t3.same(rolesOf(fake, alice.id), [discordRoles.other], "roles no longer mapped are left on members");
});
t2.test("mapping changes are broadcast", async t3 => {
const { controller, plugin } = await startPlugin(t3, { mappings: {} });
const sent = [];
controller.subscriptions.broadcast = event => sent.push(event);
await plugin.handleMappingUpdateRequest(new messages.RoleMappingUpdateRequest(5, [discordRoles.moderator]));
t3.equal(sent.length, 1);
t3.same(sent[0].updates.map(m => [m.id, m.discordRoleIds]), [[5, [discordRoles.moderator]]]);
const event = await plugin.handleMappingSubscription({ lastRequestTimeMs: 0 });
t3.same(event.updates.map(m => m.id), [5]);
await settled(plugin);
});
t2.test("mappings of deleted roles are removed", async t3 => {
const { controller, plugin } = await startPlugin(t3);
controller.roles.delete(controller.roles.get(6));
t3.same([...plugin.mappings.values()].map(m => m.id), [5]);
await settled(plugin);
});
t2.test("mappings are saved and loaded", async t3 => {
const { controller, plugin } = await startPlugin(t3);
await plugin.onShutdown();
const restarted = new Controller(logger, [], new lib.ControllerConfig("controller", {
"controller.database_directory": controller.config.get("controller.database_directory"),
}));
restarted.roles.set(role(5, "Moderator"));
restarted.roles.set(role(6, "Trusted"));
const reloaded = await ControllerPlugin.fromContext({
plugin: { name: "exp_discord_sync" }, controller: restarted, logger, plugins: noPlugins,
});
t3.same([...reloaded.mappings.values()].map(m => [m.id, m.discordRoleIds]), [
[5, [discordRoles.moderator]],
[6, [discordRoles.trusted]],
]);
});
t2.test("GuildRoleListRequest lists roles the bot can give, highest first", async t3 => {
const { plugin } = await startPlugin(t3);
t3.same(await plugin.handleGuildRoleListRequest(), [
{ id: discordRoles.moderator, name: "Moderator", color: 0xff0000 },
{ id: discordRoles.trusted, name: "Trusted", color: 0 },
{ id: discordRoles.other, name: "Other", color: 0 },
]);
await settled(plugin);
});
t2.end();
});
+178
View File
@@ -0,0 +1,178 @@
import t from "tap";
import * as lib from "@clusterio/lib";
import { DiscordApiError, DiscordGateway, DiscordRest, gatewayIntents } from "../dist/node/discord.js";
import { guildId, startFakeDiscord, until } from "./fake_discord.js";
const logger = { child: () => logger, info: () => {}, warn: () => {}, error: () => {}, verbose: () => {} };
const memberId = "300000000000000000";
const roleId = "200000000000000001";
t.test("class DiscordRest", async t2 => {
const fake = await startFakeDiscord();
t2.teardown(fake.close);
fake.members.set(memberId, new Set());
t2.test(".getGuildMember() returns the member, or undefined when not in the guild", async t3 => {
const rest = new DiscordRest(() => "token", fake.apiBase);
t3.same(await rest.getGuildMember(guildId, memberId), { user: { id: memberId }, roles: [] });
t3.equal(await rest.getGuildMember(guildId, "1"), undefined);
});
t2.test(".addMemberRole() and .removeMemberRole() change roles", async t3 => {
const rest = new DiscordRest(() => "token", fake.apiBase);
await rest.addMemberRole(guildId, memberId, roleId);
t3.same([...fake.members.get(memberId)], [roleId]);
await rest.removeMemberRole(guildId, memberId, roleId);
t3.same([...fake.members.get(memberId)], []);
});
t2.test("waits out 429 responses and retries", async t3 => {
const rest = new DiscordRest(() => "token", fake.apiBase);
fake.requests.length = 0;
fake.rateLimit = 2;
const start = Date.now();
await rest.getGuildRoles(guildId);
t3.equal(fake.requests.length, 3);
t3.ok(Date.now() - start >= 90, "waited retry_after twice");
});
t2.test("gives up after repeated 429 responses", async t3 => {
const rest = new DiscordRest(() => "token", fake.apiBase);
fake.rateLimit = 6;
await t3.rejects(rest.getGuildRoles(guildId), { status: 429 });
fake.rateLimit = 0;
});
t2.test("throws DiscordApiError with the status", async t3 => {
const rest = new DiscordRest(() => "wrong", fake.apiBase);
const err = await rest.getGuildRoles(guildId).catch(e => e);
t3.ok(err instanceof DiscordApiError);
t3.equal(err.status, 401);
});
t2.test("sends one request at a time", async t3 => {
const rest = new DiscordRest(() => "token", fake.apiBase);
fake.requests.length = 0;
fake.rateLimit = 1;
await Promise.all([rest.getGuildRoles(guildId), rest.getGuildMember(guildId, memberId)]);
t3.same(fake.requests, [
`GET /guilds/${guildId}/roles`,
`GET /guilds/${guildId}/roles`,
`GET /guilds/${guildId}/members/${memberId}`,
]);
});
});
t.test("class DiscordGateway", async t2 => {
t2.test("identifies with the intents and passes on dispatches", async t3 => {
const fake = await startFakeDiscord();
t3.teardown(fake.close);
const events = [];
const gateway = new DiscordGateway(() => "token", gatewayIntents.GUILD_MEMBERS, logger, fake.gatewayUrl);
gateway.on("ready", () => events.push("ready"));
gateway.on("dispatch", (type, data) => events.push([type, data]));
t3.teardown(() => gateway.stop());
gateway.start();
await until(() => events.length);
t3.equal(fake.identifies[0].token, "token");
t3.equal(fake.identifies[0].intents, gatewayIntents.GUILD_MEMBERS);
fake.dispatch("GUILD_MEMBER_ADD", { guild_id: guildId, user: { id: memberId } });
await until(() => events.length === 2);
t3.same(events, ["ready", ["GUILD_MEMBER_ADD", { guild_id: guildId, user: { id: memberId } }]]);
});
t2.test("reconnects when the connection drops", async t3 => {
const fake = await startFakeDiscord();
t3.teardown(fake.close);
let ready = 0;
const gateway = new DiscordGateway(() => "token", 0, logger, fake.gatewayUrl);
gateway.on("ready", () => { ready += 1; });
gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 });
t3.teardown(() => gateway.stop());
gateway.start();
await until(() => ready === 1);
for (const ws of fake.sockets) {
ws.terminate();
}
await until(() => ready === 2);
t3.equal(fake.identifies.length, 2);
});
t2.test("stops on a fatal close code", async t3 => {
const fake = await startFakeDiscord({ closeCode: 4014 });
t3.teardown(fake.close);
let closed;
const gateway = new DiscordGateway(() => "token", 0, logger, fake.gatewayUrl);
gateway.on("fatalClose", (code, reason) => { closed = { code, reason }; });
gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 });
gateway.start();
await until(() => closed);
t3.same(closed, { code: 4014, reason: "closed by fake" });
t3.equal(gateway.state, "stopped");
await new Promise(resolve => setTimeout(resolve, 100));
t3.equal(fake.identifies.length, 1, "did not reconnect");
});
t2.test(".stop() closes without reconnecting", async t3 => {
const fake = await startFakeDiscord();
t3.teardown(fake.close);
let ready = 0;
const gateway = new DiscordGateway(() => "token", 0, logger, fake.gatewayUrl);
gateway.on("ready", () => { ready += 1; });
gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 });
gateway.start();
await until(() => ready === 1);
gateway.stop();
await until(() => fake.sockets.size === 0);
await new Promise(resolve => setTimeout(resolve, 100));
t3.equal(fake.identifies.length, 1);
t3.equal(gateway.state, "stopped");
});
t2.test("goes through the states in order", async t3 => {
const fake = await startFakeDiscord();
t3.teardown(fake.close);
const gateway = new DiscordGateway(() => "token", 0, logger, fake.gatewayUrl);
gateway.backoff = new lib.ExponentialBackoff({ base: 0.01, max: 0.02 });
t3.teardown(() => gateway.stop());
const states = [gateway.state];
const setState = gateway._setState;
gateway._setState = function(next) {
setState.call(this, next);
states.push(next);
};
gateway.start();
await until(() => gateway.state === "ready");
for (const ws of fake.sockets) {
ws.terminate();
}
await until(() => states.length === 8);
gateway.stop();
t3.same(states, [
"stopped", "connecting", "identifying", "ready", "waiting", "connecting", "identifying", "ready", "stopped",
]);
});
t2.test("asserts on invalid transitions", async t3 => {
const gateway = new DiscordGateway(() => "token", 0, logger, "ws://127.0.0.1:1");
t3.throws(() => gateway._setState("ready"), /from stopped to ready/);
t3.equal(gateway.state, "stopped");
gateway.stop();
t3.equal(gateway.state, "stopped", "stopping while stopped does nothing");
});
t2.test("a message in the wrong state is logged, not thrown", async t3 => {
const fake = await startFakeDiscord();
t3.teardown(fake.close);
const errors = [];
const errorLogger = { ...logger, error: msg => errors.push(msg) };
const gateway = new DiscordGateway(() => "token", 0, errorLogger, fake.gatewayUrl);
t3.teardown(() => gateway.stop());
gateway.start();
await until(() => gateway.state === "ready");
fake.dispatch("READY", {});
await until(() => errors.length);
t3.match(errors[0], /from ready to ready/);
t3.equal(gateway.state, "ready");
});
});
+118
View File
@@ -0,0 +1,118 @@
import * as http from "node:http";
import { WebSocketServer } from "ws";
export const guildId = "100000000000000000";
/**
* Discord REST and gateway for one guild on a local port.
*
* members maps user id to a Set of role ids. rateLimit makes the next n
* requests answer 429. The gateway sends READY after identify, more events
* go through dispatch().
*/
export async function startFakeDiscord({ token = "token", closeCode } = {}) {
const fake = {
roles: [
{ id: guildId, name: "@everyone", color: 0, position: 0, managed: false },
],
members: new Map(),
requests: [],
rateLimit: 0,
identifies: [],
sockets: new Set(),
dispatch(t, d) {
for (const ws of fake.sockets) {
ws.send(JSON.stringify({ op: 0, s: 2, t, d }));
}
},
};
const server = http.createServer((req, res) => {
const route = `${req.method} ${req.url.replace(/^\/api\/v10/, "")}`;
fake.requests.push(route);
const reply = (status, body) => {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(body === undefined ? undefined : JSON.stringify(body));
};
if (req.headers.authorization !== `Bot ${token}`) {
reply(401, { message: "401: Unauthorized" });
return;
}
if (fake.rateLimit > 0) {
fake.rateLimit -= 1;
reply(429, { message: "You are being rate limited.", retry_after: 0.05, global: false });
return;
}
let match;
if (route === `GET /guilds/${guildId}/roles`) {
reply(200, fake.roles);
} else if ((match = route.match(new RegExp(`^GET /guilds/${guildId}/members/(\\d+)$`)))) {
const roles = fake.members.get(match[1]);
if (roles) {
reply(200, { user: { id: match[1] }, roles: [...roles] });
} else {
reply(404, { message: "Unknown Member", code: 10007 });
}
} else if ((match = route.match(new RegExp(`^(PUT|DELETE) /guilds/${guildId}/members/(\\d+)/roles/(\\d+)$`)))) {
const roles = fake.members.get(match[2]);
if (!roles) {
reply(404, { message: "Unknown Member", code: 10007 });
} else if (fake.roles.find(role => role.id === match[3])?.name === "Above bot") {
reply(403, { message: "Missing Permissions", code: 50013 });
} else {
roles[match[1] === "PUT" ? "add" : "delete"](match[3]);
reply(204);
}
} else {
reply(404, { message: "404: Not Found" });
}
});
const wss = new WebSocketServer({ server });
wss.on("connection", ws => {
fake.sockets.add(ws);
ws.on("close", () => fake.sockets.delete(ws));
ws.send(JSON.stringify({ op: 10, s: null, t: null, d: { heartbeat_interval: 45000 } }));
ws.on("message", data => {
const payload = JSON.parse(String(data));
if (payload.op === 1) {
ws.send(JSON.stringify({ op: 11, s: null, t: null, d: null }));
} else if (payload.op === 2) {
fake.identifies.push(payload.d);
if (closeCode) {
ws.close(closeCode, "closed by fake");
} else if (payload.d.token !== token) {
ws.close(4004, "Authentication failed.");
} else {
ws.send(JSON.stringify({ op: 0, s: 1, t: "READY", d: { session_id: "s" } }));
}
}
});
});
await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
const port = server.address().port;
fake.apiBase = `http://127.0.0.1:${port}/api/v10`;
fake.gatewayUrl = `ws://127.0.0.1:${port}/?v=10&encoding=json`;
fake.close = async () => {
for (const ws of wss.clients) {
ws.terminate();
}
wss.close();
server.closeAllConnections();
await new Promise(resolve => server.close(resolve));
};
return fake;
}
/** Wait until check() is truthy, failing after a second. */
export async function until(check) {
for (let i = 0; i < 100; i++) {
if (check()) {
return;
}
await new Promise(resolve => setTimeout(resolve, 10));
}
throw new Error("timed out waiting");
}
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "../tsconfig.browser.json",
"include": [ "web/**/*.tsx", "web/**/*.ts", "index.ts", "messages.ts", "package.json" ],
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.node.json" },
{ "path": "./tsconfig.browser.json" }
]
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "../tsconfig.node.json",
"references": [
{ "path": "../exp_discord_auth/tsconfig.node.json" },
],
"include": ["./**/*.ts"],
"exclude": ["test/*", "./dist/*"],
}
+6
View File
@@ -0,0 +1,6 @@
import { defineConfig } from "vite";
import { clusterioPlugin } from "@clusterio/web_ui/vite.mjs";
export default defineConfig({
plugins: [clusterioPlugin()],
});
@@ -0,0 +1,90 @@
import React, { useContext, useEffect, useState } from "react";
import { Alert, Button, Select, Typography } from "antd";
import { ControlContext, PluginExtensionProps, SectionHeader, notifyErrorHandler, useAccount } from "@clusterio/web_ui";
import { GuildRoleListRequest, RoleMappingUpdateRequest } from "../../messages.js";
import { useRoleMappings } from "..";
type GuildRole = { id: string, name: string, color: number };
function roleColor(color: number) {
return color ? `#${color.toString(16).padStart(6, "0")}` : undefined;
}
/** The Discord roles given to linked players holding this role. */
export default function RoleDiscordRoles(props: PluginExtensionProps<"RoleViewPageBeforePermissions">) {
const control = useContext(ControlContext);
const account = useAccount();
const [mappings, synced] = useRoleMappings();
const [guildRoles, setGuildRoles] = useState<GuildRole[]>([]);
const [guildError, setGuildError] = useState<string>();
const [selected, setSelected] = useState<string[]>();
const [applying, setApplying] = useState(false);
const canUpdate = account.hasPermission("exp_discord_sync.mapping.update");
const saved = (props.role ? mappings.get(props.role.id)?.discordRoleIds : undefined) ?? [];
const value = selected ?? saved;
const changed = selected !== undefined && selected.join() !== saved.join();
useEffect(() => {
control.send(new GuildRoleListRequest())
.then(roles => { setGuildRoles(roles); setGuildError(undefined); })
.catch(err => setGuildError(err.message));
}, []);
useEffect(() => setSelected(undefined), [props.role?.id, saved.join()]);
if (!props.role || !synced) {
return null;
}
async function apply() {
await control.send(new RoleMappingUpdateRequest(props.role!.id, value));
setSelected(undefined);
}
const options = guildRoles.map(role => ({
value: role.id,
label: <span style={{ color: roleColor(role.color) }}>{role.name}</span>,
search: role.name,
}));
return <>
<SectionHeader
title="Discord Roles"
extra={canUpdate ? <Button
type="primary"
disabled={!changed}
loading={applying}
onClick={() => {
setApplying(true);
apply()
.catch(notifyErrorHandler("Error updating Discord roles"))
.finally(() => setApplying(false));
}}
>Apply Discord roles</Button> : undefined}
/>
{guildError && <Alert
type="warning"
showIcon
message={`Could not list the Discord roles: ${guildError}`}
description={canUpdate ? "Role IDs can still be typed in." : undefined}
style={{ marginBottom: 8 }}
/>}
<Select
mode="tags"
style={{ width: "100%" }}
placeholder={canUpdate ? "Select Discord roles or type a role ID" : "None"}
disabled={!canUpdate}
value={value}
options={options}
optionFilterProp="search"
tokenSeparators={[",", " "]}
onChange={setSelected}
/>
<Typography.Paragraph type="secondary" style={{ marginTop: 8 }}>
Players linked to Discord get these roles while they hold this role.
</Typography.Paragraph>
</>;
}
+22
View File
@@ -0,0 +1,22 @@
import { useCallback, useSyncExternalStore } from "react";
import { WebPluginContext } from "@clusterio/web_ui";
import * as lib from "@clusterio/lib";
import * as messages from "../messages.js";
import RoleDiscordRoles from "./components/RoleDiscordRoles";
let mappings: lib.MapSubscriber<messages.RoleMappingUpdatedEvent> | undefined;
export function useRoleMappings() {
const subscribe = useCallback((cb: () => void) => mappings!.subscribe(cb), []);
return useSyncExternalStore(subscribe, () => mappings!.getSnapshot());
}
export default function registerPlugin(context: WebPluginContext) {
context.control.hooks.extensionComponents.attach("exp_discord_sync", () => ({
RoleViewPageBeforePermissions: RoleDiscordRoles,
}));
mappings = new lib.MapSubscriber(messages.RoleMappingUpdatedEvent, context.control);
}
+1
View File
@@ -4,6 +4,7 @@
{ "path": "./exp_auto_restart/" },
{ "path": "./exp_commands/" },
{ "path": "./exp_discord_auth/" },
{ "path": "./exp_discord_sync/" },
{ "path": "./exp_groups/" },
{ "path": "./exp_gui/" },
{ "path": "./exp_reports/" },