mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-16 23:30:41 +09:00
Enable the player proxy by default and give lobbies an empty save
The player proxy now listens on 34197 by default. New hosts default to the port range 34200-34299 so they don't hand that port to instances, and the controller logs an error and runs without the proxy if the port is taken, as hosts with the old range only skip it when the controller already holds it. Lobby instances start the save lobby.zip, created on first start as a one tile map with no autoplace and with the freeplay scenario replaced by an empty one. This uses the new chooseSave instance hook, which lets plugins pick or create the save to start, and setSaveScenario from @clusterio/host, which sets the scenario the save patcher keeps loading. Map gen settings can't use a width and height of 0 for this, as Factorio takes 0 to mean an unlimited map. The address players reach the proxy on moves from lobby.public_address to controller.player_proxy_public_address. When it's set the player_auth login page lists it once for the instances behind the proxy instead of their own addresses, and lobbies with player_auth loaded get a button that opens the web interface login dialog.
This commit is contained in:
23 files changed
+391
-121
No files matched your search
+6
-1
@@ -35,13 +35,18 @@ Many thanks to the following for contributing to this release:
|
||||
|
||||
### Major Features
|
||||
|
||||
- Added a player proxy on the controller that accepts Factorio clients on a single UDP port, sends each player to an instance picked by plugins or the instance they were last on, and starts stopped instances on demand. Instances can also get a dedicated proxy port with `instance.player_proxy_port`. See [Player proxy](/docs/player-proxy.md).
|
||||
- Added a player proxy on the controller that accepts Factorio clients on a single UDP port, sends each player to an instance picked by plugins or the instance they were last on, and starts stopped instances on demand. It listens on port 34197 by default. Instances can also get a dedicated proxy port with `instance.player_proxy_port`. See [Player proxy](/docs/player-proxy.md).
|
||||
- Added the Lobby plugin, which sends players connecting through the proxy to a lobby running their Factorio version where they pick the instance to join, and can list the cluster and individual instances, including stopped ones, in the Factorio server browser.
|
||||
|
||||
### Features
|
||||
|
||||
- Added the `chooseSave` instance hook for plugins to pick or create the save an instance starts with, and `setSaveScenario` in `@clusterio/host` to make the save patcher stop loading the freeplay scenario of a save.
|
||||
- Added the `playerProxyRoute` controller hook for plugins to decide which instance a player connecting through the player proxy goes to.
|
||||
|
||||
### Changes
|
||||
|
||||
- Changed the default `host.factorio_port_range` of new hosts to 34200-34299, so it doesn't include the player proxy port 34197.
|
||||
|
||||
### Fixes
|
||||
|
||||
- Fixed map positions after the first one in exchange strings being decoded relative to the wrong previous position.
|
||||
|
||||
@@ -222,7 +222,7 @@ Disabled when null.
|
||||
Must be greater than 0.
|
||||
Requires a restart of the controller to take effect.
|
||||
|
||||
Defaults to null.
|
||||
Defaults to 34197, the default port of Factorio servers.
|
||||
|
||||
|
||||
### controller.player_proxy_default_instance_id
|
||||
@@ -401,11 +401,13 @@ Defaults to "localhost".
|
||||
### host.factorio_port_range
|
||||
|
||||
UDP ports the host hands out to instances that don't have factorio.game_port set.
|
||||
Written as a comma separated list of ports and/or ranges of ports separated with a dash, for example "34100-34199" or "34100, 34200-34210".
|
||||
Written as a comma separated list of ports and/or ranges of ports separated with a dash, for example "34200-34299" or "34100, 34200-34210".
|
||||
A port is picked when the instance is started and remembered in factorio.host_assigned_game_port, so an instance keeps the same port as long as it is still free.
|
||||
Starting an instance fails if all ports in the range are taken.
|
||||
|
||||
Defaults to "34100-34199".
|
||||
Defaults to "34200-34299", which leaves out 34197 used by controller.player_proxy_port.
|
||||
Host configs created by older versions of Clusterio have "34100-34199" saved, which includes 34197.
|
||||
Ports in use by another process are skipped when assigning, so this only conflicts if the host is started before a controller on the same machine.
|
||||
|
||||
|
||||
### host.factorio_username
|
||||
|
||||
@@ -15,13 +15,15 @@ Players then only need to know one address, and instances that are stopped are s
|
||||
|
||||
## Enabling the proxy
|
||||
|
||||
Set [controller.player_proxy_port](configuration.md#controllerplayer_proxy_port) to the UDP port to accept players on and restart the controller:
|
||||
The proxy listens on UDP port 34197, the default port of Factorio servers, unless [controller.player_proxy_port](configuration.md#controllerplayer_proxy_port) is changed.
|
||||
Set it to null to turn the proxy off:
|
||||
|
||||
npx clusteriocontroller config set controller.player_proxy_port 34197
|
||||
npx clusteriocontroller config set controller.player_proxy_port null
|
||||
|
||||
Make sure the port is reachable from the Internet and is not in the `host.factorio_port_range` of a host running on the same machine as the controller.
|
||||
Make sure the port is reachable from the Internet.
|
||||
The controller connects to the game port of the instances from the address the host connected to the controller from, so the game ports of the instances must be reachable from the controller.
|
||||
Instances behind the proxy should have `visibility.public` turned off in their `factorio.settings`, otherwise they are listed in the server browser with their own address in addition to the proxy.
|
||||
If the port is taken, for example by an instance of a host on the same machine, the controller logs an error and runs without the proxy.
|
||||
|
||||
|
||||
## How players are routed
|
||||
|
||||
@@ -1089,6 +1089,35 @@ export default class Controller {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Address players reach the player proxy on
|
||||
*
|
||||
* @param port -
|
||||
* Proxy port to give the address for, defaults to the main port.
|
||||
* @returns controller.player_proxy_public_address, or the host name of
|
||||
* controller.public_url with the port if not set. Undefined if the
|
||||
* proxy is disabled or neither is set.
|
||||
*/
|
||||
getPlayerProxyAddress(port?: number) {
|
||||
if (!this.playerProxyServer) {
|
||||
return undefined;
|
||||
}
|
||||
const configured = this.config.get("controller.player_proxy_public_address");
|
||||
if (configured) {
|
||||
if (port === undefined) {
|
||||
return configured;
|
||||
}
|
||||
// Swap the port, host may be a name, IPv4 address or IPv6 address in brackets
|
||||
const host = /^(\[[^\]]+\]|[^:]+)(?::\d+)?$/.exec(configured)?.[1] ?? `[${configured}]`;
|
||||
return `${host}:${port}`;
|
||||
}
|
||||
const publicUrl = this.config.get("controller.public_url");
|
||||
if (!publicUrl) {
|
||||
return undefined;
|
||||
}
|
||||
return `${new URL(publicUrl).hostname}:${port ?? this.playerProxyServer.port}`;
|
||||
}
|
||||
|
||||
private _lastInstanceOfPlayer(name: string) {
|
||||
const user = this.users.getByName(name);
|
||||
let lastId: number | undefined;
|
||||
|
||||
@@ -120,7 +120,16 @@ export default class PlayerProxyServer {
|
||||
if (this._closed) {
|
||||
return;
|
||||
}
|
||||
await this._listen(this._port);
|
||||
try {
|
||||
await this._listen(this._port);
|
||||
} catch (err: any) {
|
||||
// Not fatal so the rest of the controller still works, for example if a host on the
|
||||
// same machine runs an instance on the port.
|
||||
this._logger.error(
|
||||
`Failed to listen on player proxy port ${this._port}, players can't connect through the ` +
|
||||
`proxy: ${err.message}`
|
||||
);
|
||||
}
|
||||
this._controller.instances.records.on("update", this._onInstancesUpdated);
|
||||
await this.syncListeners();
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ export { BaseInstancePlugin, InstanceHooks, type InstancePluginContext } from ".
|
||||
export { default as Host, HostRouter } from "./src/Host.js";
|
||||
export { default as Instance } from "./src/Instance.js";
|
||||
export { default as InstanceConnection } from "./src/InstanceConnection.js";
|
||||
export { setSaveScenario } from "./src/patch.js";
|
||||
|
||||
if (import.meta.main) {
|
||||
bootstrap();
|
||||
|
||||
@@ -24,6 +24,8 @@ export class InstanceHooks extends lib.AsyncHookCollection {
|
||||
this.prepareControllerDisconnect = this.newHook();
|
||||
this.playerEvent = this.newHook();
|
||||
this.autoPauseChanged = this.newHook();
|
||||
// Long timeout as handlers may create a save
|
||||
this.chooseSave = this.newHook(logger, 300_000);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -55,6 +57,19 @@ export class InstanceHooks extends lib.AsyncHookCollection {
|
||||
*/
|
||||
readonly metrics: lib.AsyncHook<[], AsyncIterable<lib.CollectorResult> | void>;
|
||||
|
||||
/**
|
||||
* Called to pick the save to start when none was requested
|
||||
*
|
||||
* Invoked after mods have been synced when the instance is started
|
||||
* without a save being specified. Handlers may create a save in the
|
||||
* saves directory of the instance and return its name to have it
|
||||
* started instead of the newest save. Return undefined to leave the
|
||||
* choice to other plugins and the default of the newest save.
|
||||
*
|
||||
* @returns name of save in the instance's saves directory to start.
|
||||
*/
|
||||
readonly chooseSave: lib.AsyncHook<[], string | undefined>;
|
||||
|
||||
/**
|
||||
* Called after the Factorio server is started
|
||||
*/
|
||||
|
||||
@@ -1045,7 +1045,16 @@ end`.replace(/\r?\n/g, " ");
|
||||
* @returns Name of the save prepared.
|
||||
*/
|
||||
async prepareSave(saveName?: string) {
|
||||
// Use latest save if no save was specified
|
||||
// Let plugins pick the save, otherwise use latest save if no save was specified
|
||||
if (saveName === undefined) {
|
||||
for (const result of await this.hooks.chooseSave.collect()) {
|
||||
if (result) {
|
||||
checkRequestSaveName(result);
|
||||
saveName = result;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (saveName === undefined) {
|
||||
saveName = await lib.getNewestFile(
|
||||
this.path("saves"), (name) => !name.endsWith(".tmp.zip")
|
||||
|
||||
+77
-27
@@ -465,37 +465,87 @@ export async function patch(savePath: string, modules: SaveModule[]) {
|
||||
|
||||
// Write back the save, keeping the order of the entries in the original
|
||||
const added = new Map([...files].map(([relativePath, contents]) => [rootPath(relativePath), contents]));
|
||||
const output = new lib.ZipWriter();
|
||||
let writeStream;
|
||||
[tempSavePath, writeStream] = await lib.createTempWriteStream(savePath);
|
||||
const writing = pipeline(output.outputStream, writeStream);
|
||||
// Awaited below, but a write error can reject it before then.
|
||||
writing.catch(() => {});
|
||||
try {
|
||||
for (const entry of zip.entries.values()) {
|
||||
const name = entry.fileName;
|
||||
if (removed.has(name)) {
|
||||
continue;
|
||||
}
|
||||
const contents = added.get(name);
|
||||
if (contents !== undefined) {
|
||||
await output.addBuffer(contents, name);
|
||||
added.delete(name);
|
||||
} else {
|
||||
await output.addEntry(zip, entry);
|
||||
}
|
||||
tempSavePath = await writeSaveCopy(zip, savePath, added, removed);
|
||||
} finally {
|
||||
zip.close();
|
||||
}
|
||||
await fs.rename(tempSavePath, savePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a copy of a save with entries replaced, added and removed
|
||||
*
|
||||
* The copy is written next to the save, and must be renamed over it after
|
||||
* the save has been closed.
|
||||
*
|
||||
* @param zip - Opened save to copy.
|
||||
* @param savePath - Path the save was opened from.
|
||||
* @param added - Entries by full path in the zip to add or replace.
|
||||
* @param removed - Full paths of entries to leave out.
|
||||
* @returns path to the copy written.
|
||||
*/
|
||||
async function writeSaveCopy(
|
||||
zip: lib.ZipArchive,
|
||||
savePath: string,
|
||||
added: Map<string, Buffer>,
|
||||
removed = new Set<string>(),
|
||||
) {
|
||||
const output = new lib.ZipWriter();
|
||||
const [tempSavePath, writeStream] = await lib.createTempWriteStream(savePath);
|
||||
const writing = pipeline(output.outputStream, writeStream);
|
||||
// Awaited below, but a write error can reject it before then.
|
||||
writing.catch(() => {});
|
||||
try {
|
||||
for (const entry of zip.entries.values()) {
|
||||
const name = entry.fileName;
|
||||
if (removed.has(name)) {
|
||||
continue;
|
||||
}
|
||||
for (const [name, contents] of added) {
|
||||
const contents = added.get(name);
|
||||
if (contents !== undefined) {
|
||||
await output.addBuffer(contents, name);
|
||||
added.delete(name);
|
||||
} else {
|
||||
await output.addEntry(zip, entry);
|
||||
}
|
||||
await output.end();
|
||||
await writing;
|
||||
} catch (err) {
|
||||
output.outputStream.destroy();
|
||||
await writing.catch(() => {});
|
||||
await fs.rm(tempSavePath, { force: true });
|
||||
throw err;
|
||||
}
|
||||
for (const [name, contents] of added) {
|
||||
await output.addBuffer(contents, name);
|
||||
}
|
||||
await output.end();
|
||||
await writing;
|
||||
} catch (err) {
|
||||
output.outputStream.destroy();
|
||||
await writing.catch(() => {});
|
||||
await fs.rm(tempSavePath, { force: true });
|
||||
throw err;
|
||||
}
|
||||
return tempSavePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the scenario code the save patcher keeps loading in a save
|
||||
*
|
||||
* Saves created by Factorio run the freeplay scenario, which the patcher
|
||||
* keeps when patching them. This replaces it with the given scenario info,
|
||||
* for example a scenario that loads no modules to get a save without
|
||||
* freeplay. The save must not have been patched before.
|
||||
*
|
||||
* @param savePath - Path to the save to change.
|
||||
* @param scenario - Scenario modules to load in place of the original scenario.
|
||||
*/
|
||||
export async function setSaveScenario(savePath: string, scenario: lib.ModuleInfo) {
|
||||
const zip = await lib.ZipArchive.fromFile(savePath);
|
||||
let tempSavePath: string;
|
||||
try {
|
||||
const root = lib.findRoot(zip);
|
||||
if (await zip.readFile(path.posix.join(root, "clusterio.json")) !== null) {
|
||||
throw new Error("Unable to set scenario of a save that has already been patched");
|
||||
}
|
||||
const patchInfo = new PatchInfo(0, scenario, []);
|
||||
tempSavePath = await writeSaveCopy(zip, savePath, new Map([[
|
||||
path.posix.join(root, "clusterio.json"), Buffer.from(JSON.stringify(patchInfo, null, " "), "utf8"),
|
||||
]]));
|
||||
} finally {
|
||||
zip.close();
|
||||
}
|
||||
|
||||
@@ -153,9 +153,10 @@ export class AsyncHookCollection {
|
||||
Args extends unknown[],
|
||||
Result = void,
|
||||
> (
|
||||
_logger = this._logger
|
||||
_logger = this._logger,
|
||||
timeoutMs?: number,
|
||||
) {
|
||||
const hook = new AsyncHook<Args, Result>(_logger);
|
||||
const hook = new AsyncHook<Args, Result>(_logger, timeoutMs);
|
||||
this.hooks.push(hook);
|
||||
return hook;
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@ export interface ControllerConfigFields {
|
||||
"controller.proxy_stream_timeout": number;
|
||||
"controller.player_proxy_port": number | null;
|
||||
"controller.player_proxy_default_instance_id": number | null;
|
||||
"controller.player_proxy_public_address": string | null;
|
||||
"controller.factorio_username": string | null;
|
||||
"controller.factorio_token": string | null;
|
||||
"controller.share_factorio_credentials_with_hosts": boolean;
|
||||
@@ -253,6 +254,7 @@ export class ControllerConfig extends classes.Config<ControllerConfigFields> {
|
||||
restartRequired: true,
|
||||
type: "number",
|
||||
optional: true,
|
||||
initialValue: 34197,
|
||||
validator: validators.optional(validators.greaterThanZero),
|
||||
},
|
||||
"controller.player_proxy_default_instance_id": {
|
||||
@@ -263,6 +265,15 @@ export class ControllerConfig extends classes.Config<ControllerConfigFields> {
|
||||
type: "number",
|
||||
optional: true,
|
||||
},
|
||||
"controller.player_proxy_public_address": {
|
||||
title: "Player Proxy Public Address",
|
||||
description:
|
||||
"Address players reach the player proxy on, for example play.example.com:34197. Used by plugins " +
|
||||
"to tell players where to connect. If null plugins may assume the host name of " +
|
||||
"controller.public_url and controller.player_proxy_port.",
|
||||
type: "string",
|
||||
optional: true,
|
||||
},
|
||||
"controller.factorio_username": {
|
||||
title: "Factorio Username",
|
||||
description: "Username to authenticate with Factorio API with.",
|
||||
@@ -433,7 +444,7 @@ export class HostConfig extends classes.Config<HostConfigFields> {
|
||||
"Range of UDP ports to use for game connections. Supports both comma separated values and " +
|
||||
"ranges separated with a dash.",
|
||||
type: "string",
|
||||
initialValue: "34100-34199",
|
||||
initialValue: "34200-34299",
|
||||
// TODO extendedValidation, port range
|
||||
},
|
||||
"host.factorio_username": {
|
||||
|
||||
+9
-14
@@ -7,6 +7,7 @@ Works together with the [player proxy](../../docs/player-proxy.md) on the contro
|
||||
The lobby shows a list of the instances in the cluster, picking one moves the player there with `LuaPlayer.connect_to_server`.
|
||||
- Picking a stopped instance starts it, the player waits in the lobby and is moved once it's running.
|
||||
- Other instances with the plugin loaded get a Servers button that opens the same list.
|
||||
- If the [Player Auth](../player_auth/README.md) plugin is loaded the list has a button for logging into the web interface, which does the same as the `/web-login` command.
|
||||
- The cluster can be listed in the Factorio server browser as one game per Factorio version a lobby runs, showing the players online in the whole cluster.
|
||||
- Instances can also be listed in the server browser as their own game on a dedicated proxy port, including while they are stopped.
|
||||
|
||||
@@ -25,12 +26,15 @@ Substitute clusteriocontroller with clusteriohost or clusterioctl if this a dedi
|
||||
|
||||
## Setting up a lobby
|
||||
|
||||
1. Enable the player proxy by setting `controller.player_proxy_port` and restart the controller.
|
||||
2. Set `lobby.public_address` to the address and port players reach the proxy on, for example `play.example.com:34197`.
|
||||
This is the address players are sent to when they pick an instance.
|
||||
1. Make sure the player proxy is enabled, it listens on `controller.player_proxy_port` which defaults to 34197.
|
||||
2. Set `controller.player_proxy_public_address` to the address and port players reach the proxy on, for example `play.example.com:34197`.
|
||||
This is the address players are sent to when they pick an instance, and what's published in the server browser.
|
||||
If it's not set the host name of `controller.public_url` and `controller.player_proxy_port` is used.
|
||||
3. Create an instance to act as the lobby, set `lobby.is_lobby` to true on it and start it.
|
||||
Players are made spectators in the lobby, so any map works.
|
||||
Create one lobby for each Factorio version you want to accept players on.
|
||||
Lobbies always start the save `lobby.zip`, which is created the first time as an empty one tile map without the freeplay scenario, and players are made spectators in it.
|
||||
To use a different map, replace `lobby.zip` with a save of your own.
|
||||
Starting a specific save from the web interface or clusterioctl still works.
|
||||
Create one lobby for each Factorio version you want to accept players on, by setting `factorio.version` on it.
|
||||
4. Optionally set `lobby.listed` to false on instances that should not be shown in the list.
|
||||
|
||||
Players who connect to the proxy now end up in the lobby for their version.
|
||||
@@ -50,15 +54,6 @@ Players joining it while it's stopped wait in a lobby running their version unti
|
||||
|
||||
## Controller Configuration
|
||||
|
||||
### lobby.public_address
|
||||
|
||||
Address and port players reach the player proxy on, for example `play.example.com:34197`.
|
||||
Players are sent here when they pick an instance in a lobby, and the host name is resolved to the address published in the server browser.
|
||||
If null the host name of `controller.public_url` and `controller.player_proxy_port` is used.
|
||||
If the player proxy is disabled players are sent straight to the address of the host of the instance instead.
|
||||
|
||||
Defaults to null.
|
||||
|
||||
### lobby.server_browser_listing
|
||||
|
||||
List the cluster in the Factorio server browser as one game for each Factorio version a lobby is running.
|
||||
|
||||
@@ -145,15 +145,7 @@ export class LobbyController {
|
||||
/** Address players use to connect to an instance, through the proxy if it's enabled */
|
||||
connectAddress(instance: Readonly<InstanceRecord>) {
|
||||
if (this.proxy) {
|
||||
const configured = this.controller.config.get("lobby.public_address");
|
||||
if (configured) {
|
||||
return configured;
|
||||
}
|
||||
const publicUrl = this.controller.config.get("controller.public_url");
|
||||
if (publicUrl) {
|
||||
return `${new URL(publicUrl).hostname}:${this.proxy.port}`;
|
||||
}
|
||||
return undefined;
|
||||
return this.controller.getPlayerProxyAddress();
|
||||
}
|
||||
|
||||
const hostId = instance.config.get("instance.assigned_host");
|
||||
@@ -328,15 +320,14 @@ export class LobbyController {
|
||||
return listings;
|
||||
}
|
||||
|
||||
const configured = this.controller.config.get("lobby.public_address");
|
||||
const publicUrl = this.controller.config.get("controller.public_url");
|
||||
const { host, port } = configured
|
||||
? parseAddress(configured)
|
||||
: { host: publicUrl ? new URL(publicUrl).hostname : "", port: undefined };
|
||||
if (!host) {
|
||||
this._warnListing("lobby.public_address or controller.public_url must be set to list servers");
|
||||
const address = this.controller.getPlayerProxyAddress();
|
||||
if (!address) {
|
||||
this._warnListing(
|
||||
"controller.player_proxy_public_address or controller.public_url must be set to list servers"
|
||||
);
|
||||
return listings;
|
||||
}
|
||||
const { host, port } = parseAddress(address);
|
||||
let hostAddress = host;
|
||||
if (!isIP(host)) {
|
||||
try {
|
||||
|
||||
@@ -4,7 +4,6 @@ import * as messages from "./messages.js";
|
||||
|
||||
declare module "@clusterio/lib" {
|
||||
export interface ControllerConfigFields {
|
||||
"lobby.public_address": string | null;
|
||||
"lobby.server_browser_listing": boolean;
|
||||
"lobby.server_browser_name": string | null;
|
||||
"lobby.server_browser_description": string;
|
||||
@@ -28,15 +27,6 @@ export const plugin: lib.PluginDeclaration = {
|
||||
instanceEntrypoint: "dist/node/instance.js",
|
||||
|
||||
controllerConfigFields: {
|
||||
"lobby.public_address": {
|
||||
title: "Public Address",
|
||||
description:
|
||||
"Address and port players reach the player proxy on, for example play.example.com:34197. " +
|
||||
"Players are sent here when they pick an instance in a lobby. If null the host name of " +
|
||||
"controller.public_url and controller.player_proxy_port is used.",
|
||||
type: "string",
|
||||
optional: true,
|
||||
},
|
||||
"lobby.server_browser_listing": {
|
||||
title: "Server Browser Listing",
|
||||
description:
|
||||
|
||||
@@ -1,10 +1,36 @@
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
import type { InstancePluginContext } from "@clusterio/host";
|
||||
import { type InstancePluginContext, setSaveScenario } from "@clusterio/host";
|
||||
|
||||
import { ServerListRequest, TransferRequest, TransferStatus, TransferStatusEvent } from "./messages.js";
|
||||
|
||||
const SERVER_LIST_INTERVAL_MS = 5_000;
|
||||
|
||||
/** Save lobby instances start, created if it doesn't exist */
|
||||
export const LOBBY_SAVE = "lobby.zip";
|
||||
|
||||
/**
|
||||
* Map gen settings for an empty world
|
||||
*
|
||||
* A width or height of 0 means unlimited to Factorio, so the map is made
|
||||
* a single tile with everything outside it out of map.
|
||||
*/
|
||||
export const lobbyMapGenSettings = {
|
||||
width: 1,
|
||||
height: 1,
|
||||
starting_points: [{ x: 0, y: 0 }],
|
||||
peaceful_mode: true,
|
||||
no_enemies_mode: true,
|
||||
default_enable_all_autoplace_controls: false,
|
||||
autoplace_controls: {},
|
||||
autoplace_settings: {
|
||||
entity: { treat_missing_as_default: false, settings: {} },
|
||||
decorative: { treat_missing_as_default: false, settings: {} },
|
||||
},
|
||||
cliff_settings: { name: "cliff", richness: 0 },
|
||||
};
|
||||
|
||||
// ./module/lobby.lua
|
||||
type IpcConnect = {
|
||||
player: string,
|
||||
@@ -30,7 +56,9 @@ export default async function loadInstancePlugin(context: InstancePluginContext)
|
||||
|
||||
async function configure() {
|
||||
const isLobby = instance.config.get("lobby.is_lobby");
|
||||
await sendOrderedRcon(`/sc lobby.configure(${isLobby}, ${instance.id})`);
|
||||
// The player_auth module opens its login dialog from the same IPC message as its /web-login command
|
||||
const webLogin = [...instance.loadedPlugins].some(info => info.name === "player_auth");
|
||||
await sendOrderedRcon(`/sc lobby.configure(${isLobby}, ${instance.id}, ${webLogin})`);
|
||||
}
|
||||
|
||||
async function updateServerList() {
|
||||
@@ -64,6 +92,22 @@ export default async function loadInstancePlugin(context: InstancePluginContext)
|
||||
await sendOrderedRcon(`/sc lobby.set_player_status("${name}", "${lib.escapeString(text)}")`);
|
||||
}
|
||||
|
||||
instance.hooks.chooseSave.attach(plugin.name, async () => {
|
||||
if (!instance.config.get("lobby.is_lobby")) {
|
||||
return undefined;
|
||||
}
|
||||
const savePath = instance.path("saves", LOBBY_SAVE);
|
||||
try {
|
||||
await fs.access(savePath);
|
||||
} catch {
|
||||
logger.info("Creating empty lobby save");
|
||||
await instance.server.create(LOBBY_SAVE, undefined, lobbyMapGenSettings);
|
||||
// Saves are created with the freeplay scenario, replace it with one that does nothing
|
||||
await setSaveScenario(savePath, new lib.ModuleInfo("lobby", "0.0.0"));
|
||||
}
|
||||
return LOBBY_SAVE;
|
||||
});
|
||||
|
||||
instance.hooks.start.attach(plugin.name, async () => {
|
||||
await configure();
|
||||
lastServerListJson = "";
|
||||
|
||||
@@ -12,6 +12,7 @@ local mod_gui = require("mod-gui")
|
||||
--- @class LobbyScriptData
|
||||
--- @field is_lobby boolean
|
||||
--- @field instance_id integer?
|
||||
--- @field web_login boolean Show button for logging into the web interface with the player_auth plugin
|
||||
--- @field servers LobbyServer[]
|
||||
--- @field status table<string, string> Status text by player name
|
||||
|
||||
@@ -106,11 +107,15 @@ local function open_browser(player)
|
||||
local inner = frame.add { type = "frame", name = "content", direction = "vertical",
|
||||
style = "inside_shallow_frame_with_padding" }
|
||||
inner.style.horizontally_stretchable = true
|
||||
local buttons = frame.add { type = "flow", name = "buttons", direction = "horizontal" }
|
||||
buttons.style.top_margin = 8
|
||||
if data.web_login then
|
||||
buttons.add { type = "button", name = "lobby_web_login", caption = "Log in to web interface",
|
||||
tooltip = "Same as the /web-login command" }
|
||||
end
|
||||
local filler = buttons.add { type = "empty-widget" }
|
||||
filler.style.horizontally_stretchable = true
|
||||
if not data.is_lobby then
|
||||
local buttons = frame.add { type = "flow", direction = "horizontal" }
|
||||
buttons.style.top_margin = 8
|
||||
local filler = buttons.add { type = "empty-widget" }
|
||||
filler.style.horizontally_stretchable = true
|
||||
buttons.add { type = "button", name = "lobby_close", caption = "Close" }
|
||||
end
|
||||
end
|
||||
@@ -194,6 +199,8 @@ lobby_module.events[defines.events.on_gui_click] = function(event)
|
||||
end
|
||||
elseif element.name == "lobby_close" then
|
||||
close_browser(player)
|
||||
elseif element.name == "lobby_web_login" then
|
||||
clusterio_api.send_json("player_auth", { type = "open_dialog", player = player.name })
|
||||
elseif element.tags and element.tags.lobby_instance_id then
|
||||
local data = get_script_data()
|
||||
local instance_id = element.tags.lobby_instance_id
|
||||
@@ -214,14 +221,15 @@ lobby = {}
|
||||
|
||||
--- @param is_lobby boolean
|
||||
--- @param instance_id integer
|
||||
function lobby.configure(is_lobby, instance_id)
|
||||
--- @param web_login boolean?
|
||||
function lobby.configure(is_lobby, instance_id, web_login)
|
||||
local data = get_script_data()
|
||||
data.is_lobby = is_lobby
|
||||
data.instance_id = instance_id
|
||||
if not is_lobby then
|
||||
for _, player in pairs(game.players) do
|
||||
close_browser(player)
|
||||
end
|
||||
data.web_login = web_login == true
|
||||
-- Rebuilt so the frame matches the new configuration
|
||||
for _, player in pairs(game.players) do
|
||||
close_browser(player)
|
||||
end
|
||||
refresh_all()
|
||||
end
|
||||
|
||||
@@ -300,7 +300,7 @@ describe("lobby plugin", function () {
|
||||
|
||||
it("should build server browser listings", async function () {
|
||||
controller.config.set("lobby.server_browser_listing", true);
|
||||
controller.config.set("lobby.public_address", "203.0.113.5:40000");
|
||||
controller.config.set("controller.player_proxy_public_address", "203.0.113.5:40000");
|
||||
controller.instances.getMutable(4).config.set("lobby.server_browser_listing", true);
|
||||
proxy.serverVersions.set(1, v2_1_19);
|
||||
proxy.serverVersions.set(2, v2_0_72);
|
||||
@@ -353,11 +353,17 @@ describe("lobby plugin", function () {
|
||||
it("should configure the module and send the server list on start", async function () {
|
||||
await instance.hooks.start.invoke();
|
||||
const commands = instance.server.rconCommands;
|
||||
assert.equal(commands[0], "/sc lobby.configure(true, 7357)");
|
||||
assert.equal(commands[0], "/sc lobby.configure(true, 7357, false)");
|
||||
assert(commands[1].startsWith("/sc lobby.set_servers(\""), commands[1]);
|
||||
assert(commands[1].includes("Instance \\\\\\\"3\\\\\\\""), commands[1]);
|
||||
});
|
||||
|
||||
it("should enable the web login button when player_auth is loaded", async function () {
|
||||
instance.loadedPlugins.add({ name: "player_auth" });
|
||||
await instance.hooks.start.invoke();
|
||||
assert.equal(instance.server.rconCommands[0], "/sc lobby.configure(true, 7357, true)");
|
||||
});
|
||||
|
||||
it("should move players once their transfer is ready", async function () {
|
||||
instance.server.emit("ipc-lobby:connect", { player: "Player", instance_id: 3 });
|
||||
await lib.wait(10);
|
||||
|
||||
@@ -34,5 +34,6 @@ Defaults to `120`.
|
||||
|
||||
Show the address to connect to for each server in the server list on the login page of the web interface, made up of host.public_address and the game port of the instance.
|
||||
This list is visible to anyone who can reach the web interface, so leave it off if you don't want unauthenticated users to see where the servers are.
|
||||
If `controller.player_proxy_public_address` is set the list shows that address once for all instances without an `instance.player_proxy_port`, as they are reached through the [player proxy](../../docs/player-proxy.md), and the proxy address with the dedicated port for the others.
|
||||
|
||||
Defaults to `false`.
|
||||
@@ -46,6 +46,13 @@ export default async function loadControllerPlugin(context: ControllerPluginCont
|
||||
|
||||
controller.app.get("/api/player_auth/servers", (req: Request, res: Response) => {
|
||||
const servers: Static<typeof PlayerAuthServer.jsonSchema>[] = [];
|
||||
const includeAddress = controller.config.get("player_auth.show_connect_address");
|
||||
// When players are meant to connect through the player proxy, instances without a dedicated proxy
|
||||
// port are only reachable through its main port, which is listed once for all of them.
|
||||
const proxyAddress = controller.config.get("controller.player_proxy_public_address")
|
||||
? controller.getPlayerProxyAddress()
|
||||
: undefined;
|
||||
const proxiedVersions = new Set<string | undefined>();
|
||||
|
||||
for (const instance of controller.instances.values()) {
|
||||
const pluginLoaded = instance.config.get("player_auth.load_plugin");
|
||||
@@ -59,16 +66,34 @@ export default async function loadControllerPlugin(context: ControllerPluginCont
|
||||
continue;
|
||||
}
|
||||
|
||||
const address = instance.gamePort !== undefined
|
||||
? `${host.publicAddress}:${instance.gamePort}`
|
||||
: host.publicAddress;
|
||||
let address: string | undefined;
|
||||
if (proxyAddress) {
|
||||
const proxyPort = instance.config.get("instance.player_proxy_port");
|
||||
if (proxyPort === null) {
|
||||
proxiedVersions.add(instance.factorioVersion);
|
||||
continue;
|
||||
}
|
||||
address = controller.getPlayerProxyAddress(proxyPort);
|
||||
} else if (host.publicAddress !== "") {
|
||||
address = instance.gamePort !== undefined
|
||||
? `${host.publicAddress}:${instance.gamePort}`
|
||||
: host.publicAddress;
|
||||
}
|
||||
|
||||
const settings = instance.config.get("factorio.settings");
|
||||
const includeAddress = controller.config.get("player_auth.show_connect_address");
|
||||
servers.push({
|
||||
name: settings["name"] as string || "unnamed server",
|
||||
factorioVersion: instance.factorioVersion,
|
||||
address: (includeAddress && host.publicAddress !== "") ? address : undefined,
|
||||
address: includeAddress ? address : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
if (proxiedVersions.size) {
|
||||
const [version] = proxiedVersions;
|
||||
servers.unshift({
|
||||
name: controller.config.get("controller.name"),
|
||||
factorioVersion: proxiedVersions.size === 1 ? version : undefined,
|
||||
address: includeAddress ? proxyAddress : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -138,32 +138,35 @@ describe("player_auth", function() {
|
||||
});
|
||||
|
||||
describe("/api/player_auth/servers", function() {
|
||||
it("should return a list of running servers with player_auth loaded", async function() {
|
||||
function addInstance(id, status, load, name, version, gamePort, host=1) {
|
||||
mockController.instances.records.set(id, {
|
||||
config: {
|
||||
get(field) {
|
||||
if (field === "player_auth.load_plugin") {
|
||||
return load;
|
||||
}
|
||||
if (field === "factorio.settings") {
|
||||
return { name };
|
||||
}
|
||||
if (field === "instance.id") {
|
||||
return id;
|
||||
}
|
||||
if (field === "instance.assigned_host") {
|
||||
return host;
|
||||
}
|
||||
throw new Error(`field ${field} not implemented`);
|
||||
},
|
||||
function addInstance(id, status, load, name, version, gamePort, host=1, proxyPort=null) {
|
||||
mockController.instances.records.set(id, {
|
||||
config: {
|
||||
get(field) {
|
||||
if (field === "player_auth.load_plugin") {
|
||||
return load;
|
||||
}
|
||||
if (field === "factorio.settings") {
|
||||
return { name };
|
||||
}
|
||||
if (field === "instance.id") {
|
||||
return id;
|
||||
}
|
||||
if (field === "instance.assigned_host") {
|
||||
return host;
|
||||
}
|
||||
if (field === "instance.player_proxy_port") {
|
||||
return proxyPort;
|
||||
}
|
||||
throw new Error(`field ${field} not implemented`);
|
||||
},
|
||||
status,
|
||||
gamePort,
|
||||
factorioVersion: version,
|
||||
});
|
||||
}
|
||||
},
|
||||
status,
|
||||
gamePort,
|
||||
factorioVersion: version,
|
||||
});
|
||||
}
|
||||
|
||||
it("should return a list of running servers with player_auth loaded", async function() {
|
||||
addInstance(1, "running", true, "running loaded", "1.1.1", 34197);
|
||||
addInstance(2, "stopped", true, "stopped loaded", "1.1.2", 34197);
|
||||
addInstance(3, "running", false, "running unloaded", "1.1.3", 34197);
|
||||
@@ -186,6 +189,31 @@ describe("player_auth", function() {
|
||||
{ name: "no version", address: "127.0.0.1:34197" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should list the player proxy once for instances behind it", async function() {
|
||||
for (const id of [...mockController.instances.records.keys()]) {
|
||||
mockController.instances.records.delete(id);
|
||||
}
|
||||
mockController.mockConfigEntries.set("controller.name", "Cluster");
|
||||
mockController.mockConfigEntries.set(
|
||||
"controller.player_proxy_public_address", "play.example:34197"
|
||||
);
|
||||
mockController.getPlayerProxyAddress = port => `play.example:${port ?? 34197}`;
|
||||
try {
|
||||
addInstance(1, "running", true, "behind proxy", "2.1.19", 34201);
|
||||
addInstance(2, "running", true, "also behind proxy", "2.1.19", 34202);
|
||||
addInstance(3, "running", true, "dedicated port", "2.1.19", 34203, 1, 34300);
|
||||
addInstance(4, "stopped", true, "stopped", "2.1.19", 34204, 1, 34301);
|
||||
|
||||
const result = await fetch(`${controllerUrl}/api/player_auth/servers`);
|
||||
assert.deepEqual(await result.json(), [
|
||||
{ name: "Cluster", address: "play.example:34197", factorioVersion: "2.1.19" },
|
||||
{ name: "dedicated port", address: "play.example:34300", factorioVersion: "2.1.19" },
|
||||
]);
|
||||
} finally {
|
||||
mockController.mockConfigEntries.set("controller.player_proxy_public_address", null);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("/api/player_auth/player_code", function() {
|
||||
|
||||
@@ -369,6 +369,22 @@ describe("controller/Controller.resolvePlayerRoute()", function () {
|
||||
assert.equal(await controller.resolvePlayerRoute(request({ portInstanceId: 2 })), 4);
|
||||
});
|
||||
|
||||
it("should give the public address of the proxy", function () {
|
||||
assert.equal(controller.getPlayerProxyAddress(), undefined, "proxy disabled");
|
||||
controller.playerProxyServer = { port: 34197 };
|
||||
assert.equal(controller.getPlayerProxyAddress(), undefined, "no address configured");
|
||||
controller.config.set("controller.public_url", "https://cluster.example/");
|
||||
assert.equal(controller.getPlayerProxyAddress(), "cluster.example:34197");
|
||||
assert.equal(controller.getPlayerProxyAddress(34200), "cluster.example:34200");
|
||||
controller.config.set("controller.player_proxy_public_address", "play.example:5000");
|
||||
assert.equal(controller.getPlayerProxyAddress(), "play.example:5000");
|
||||
assert.equal(controller.getPlayerProxyAddress(34200), "play.example:34200");
|
||||
controller.config.set("controller.player_proxy_public_address", "[::1]");
|
||||
assert.equal(controller.getPlayerProxyAddress(34200), "[::1]:34200");
|
||||
controller.config.set("controller.player_proxy_public_address", "::1");
|
||||
assert.equal(controller.getPlayerProxyAddress(34200), "[::1]:34200");
|
||||
});
|
||||
|
||||
it("should skip instances that can't be routed to", async function () {
|
||||
controller.hooks.playerProxyRoute.attach("test", () => 5);
|
||||
assert.equal(await controller.resolvePlayerRoute(request({ portInstanceId: 99 })), 1);
|
||||
|
||||
@@ -271,4 +271,35 @@ describe("host/patch", function() {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("setSaveScenario()", function() {
|
||||
it("should let a save with an unknown scenario be patched without loading it", async function() {
|
||||
await fs.mkdir(path.join("temp", "test"), { recursive: true });
|
||||
const zipPath = path.join("temp", "test", "set-scenario.zip");
|
||||
await fs.writeFile(zipPath, await createZipBuffer([
|
||||
["world/control.lua", "-- unknown\n"],
|
||||
["world/level.dat", "level"],
|
||||
]));
|
||||
|
||||
await patch.setSaveScenario(zipPath, new lib.ModuleInfo("empty", "0.0.0"));
|
||||
await patch.patch(zipPath, []);
|
||||
|
||||
const zip = await lib.ZipArchive.fromFile(zipPath);
|
||||
try {
|
||||
const info = JSON.parse((await zip.readFile("world/clusterio.json")).toString());
|
||||
assert.equal(info.scenario.name, "empty");
|
||||
assert.deepEqual(info.scenario.load, []);
|
||||
assert.equal(info.patch_number, 1);
|
||||
assert.equal((await zip.readFile("world/level.dat")).toString(), "level");
|
||||
assert.doesNotMatch((await zip.readFile("world/control.lua")).toString(), /unknown/);
|
||||
} finally {
|
||||
zip.close();
|
||||
}
|
||||
|
||||
await assert.rejects(
|
||||
patch.setSaveScenario(zipPath, new lib.ModuleInfo("empty", "0.0.0")),
|
||||
new Error("Unable to set scenario of a save that has already been patched")
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -182,6 +182,7 @@ export class MockController {
|
||||
["controller.auth_secret", "TestSecretDoNotUse"],
|
||||
["controller.proxy_stream_timeout", 1],
|
||||
["controller.metrics_timeout", 1],
|
||||
["controller.player_proxy_public_address", null],
|
||||
]);
|
||||
this.config = {
|
||||
get: (name) => {
|
||||
|
||||
Reference in new issue
Block a user