diff --git a/README.md b/README.md index 52ac01bc..4427194f 100644 --- a/README.md +++ b/README.md @@ -251,6 +251,7 @@ Do not install the [Clusterio mod](https://mods.factorio.com/mod/clusterio), thi After completing the installation and creating your admin user, start up the controller and at least one host separately. The installer provides the `run-controller` and `run-host` scripts to make this simple. Once the controller process is running you can log into the web interface which is hosted by default on http://localhost:8080/ (adjust the port number if you changed it), use the admin authentication token provided from the installation to log in. +The first time a host starts it prints a link for approving it, open the link and click Approve. The basics of setting up a Factorio server from the web interface is to create an instance, assign it to a host and then click start. You can also use the "Connect via Steam" button to launch Factorio directly and connect to the server using Steam's protocol handler. @@ -272,9 +273,23 @@ If you have copied these files over to `/etc/systemd/system/` then you can start ## Setting up remote hosts -Run the installer as described in the installation section and choose "Host only" as the operating mode to install, it'll ask for a controller URL and an authentication token. -The URL is the same as what is needed to connect to the web interface, and the authentication token can be generated on the Hosts page in the web interface. -Once you start up the host it should show up in the Hosts list and be available for assigning and running instances on. +Run the installer as described in the installation section and choose "Host only" as the operating mode to install, it'll ask for a name for the host and a controller URL. +The URL is the same as what is needed to connect to the web interface. +Then start the host, the first time it starts it prints a code and waits for the host to be approved: + + Waiting for approval of "my-host" with code ABC-DEF, open this link to approve it: + https://example.com/hosts?approve=ABC-DEF + Or run: npx clusterioctl host approve ABC-DEF + +Open the link to approve it in the web interface, where you can also change its name, or click Add host on the Hosts page and approve the request with the same code, or run `npx clusterioctl host approve `. +The host then saves its connection details and starts up, it should show up in the Hosts list and be available for assigning and running instances on. +Only approve a request if its code matches the one shown by the host, approving gives the host full access to the cluster. +Approving requires the `core.host.approve` permission, which the Cluster Admin role has. +If you have that permission you can skip the wait by starting the host with `npx clusteriohost run --user-token ` and your own authentication token, it is only used to approve the host and is not saved. + +To remove a host from the cluster, click Revoke host access on the page for the host in the web interface, or run `npx clusterioctl host revoke `. +This disconnects the host, its instances become unassigned and its saved connection details stop working. +To add the computer back to the cluster start the host again, it asks for approval again. ## Setting up clusterioctl diff --git a/docs/config-system.md b/docs/config-system.md index 1102d43e..f1d9e5c7 100644 --- a/docs/config-system.md +++ b/docs/config-system.md @@ -45,6 +45,7 @@ For plugins the group name is the name of the plugin, e.g., the `level` field of **initialValue** (optional if optional is true): Value this config field should take in a newly initialized config. This can also be a synchronous function returning the value to use. + The function is called with the config after its stored fields are loaded, so it can base the value on other fields. **validator** (optional): Function called with the value being set and the config it belongs to. diff --git a/docs/configuration.md b/docs/configuration.md index 1818a357..803e51f8 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -48,6 +48,23 @@ Must be greater than 0. Defaults to 60. +### controller.host_pairing_timeout + +Time in seconds a host can wait for approval before its request expires, after which the host requests again with a new code. +Set to 0 for no limit. + +Defaults to 3600. + + +### controller.host_pairing_max_pending + +Maximum number of hosts that can wait for approval at the same time. +Hosts over the limit keep trying until there is room. +Set to 0 for no limit. + +Defaults to 50. + + ### controller.http_port Port to host HTTP server on. @@ -93,7 +110,7 @@ Defaults to null meaning the header is never trusted. ### controller.public_url Public address the controller is accessible on. -Used as the URL in configs generated with `clusteriocontroller bootstrap create-ctl-config` and `clusterioctl host create-config`, and by plugins like Player Auth that need to show the address of the web interface in-game. +Used as the URL in configs generated with `clusteriocontroller bootstrap create-ctl-config`, and by plugins like Player Auth that need to show the address of the web interface in-game. This should be a full URL ending with a /. Defaults to null meaning assume localhost. @@ -277,6 +294,7 @@ Defaults to 1000. Whether the `controller update` command in clusterioctl and the update button in the web interface are allowed to update the `@clusterio/controller` package with npm. For security reasons this can only be changed locally with `clusteriocontroller config set` while the controller is stopped, and it is hidden in the web interface. +The installer sets this, controller.allow_plugin_updates and controller.allow_plugin_install from one question about remote updates and plugin installs. See [Managing a Cluster](/docs/managing-a-cluster.md) for details on remote updates. Defaults to true. @@ -326,6 +344,7 @@ Defaults to "New Host". ### host.id Immutable numeric id of the host which uniquely identifies this host in the cluster. +The controller picks the id when the host is approved and the host writes it here, the controller does not accept hosts with an id it has not approved. Hidden in the web interface. Defaults to a random 31 bit number. @@ -335,6 +354,7 @@ Defaults to a random 31 bit number. Directory to look for the Factorio server(s) in. This can either point to a Factorio server directory, or to a directory containing multiple versions of the Factorio server. +The headless build has no graphics, so when exporting data from an instance running it the base game's icons are read from a full install of the same major and minor version in this directory instead, if there is one. Defaults to "factorio". @@ -365,7 +385,9 @@ Defaults to "http://localhost:8080/". ### host.controller_token Access token used for authenticating with the controller. -You can generate an access token with `clusterioctl host generate-token --id `, or use the `clusterioctl host create-config` to create a new host config with the correct url and token in it. +The host saves it together with host.id when it is approved, see [Setting up remote hosts](/README.md#setting-up-remote-hosts). +The token only works while the host exists on the controller, if the host is revoked it asks to be approved again the next time it starts. +Set it to `enter token here` to make the host ask to join again. The value can only be read and changed from the host itself. Defaults to "enter token here". @@ -418,6 +440,7 @@ Defaults to 60. Whether the `host update` command in clusterioctl and the update button in the web interface are allowed to update the `@clusterio/host` package with npm. For security reasons this can only be changed locally with `clusteriohost config set` while the host is stopped, and it is hidden in the web interface. +The installer sets this, host.allow_plugin_updates and host.allow_plugin_install from one question about remote updates and plugin installs. See [Managing a Cluster](/docs/managing-a-cluster.md) for details on remote updates. Defaults to true. @@ -498,6 +521,31 @@ This allows you to prevent certain instances from being started when using the b Defaults to false. +### instance.is_template + +If enabled this instance is a template other instances can inherit config values from. +Templates cannot be assigned to a host and therefore never start. +Hidden from `instance list` in clusterioctl unless `--templates` is passed, and listed separately in the web interface. +An instance cannot stop being a template while other instances inherit from it. +Hidden in the web interface, set when creating the template. + +Defaults to false. + + +### instance.template_id + +ID of the template to inherit config values from. +Inherited fields take their value from the template and follow it when it changes, setting a field on this instance stops inheriting it. +Object fields like `factorio.settings` are inherited per property, properties set on this instance override the ones from the template. +When set on an existing instance fields with the same value as the template or the default value become inherited, except the server name in `factorio.settings`. +`instance.name`, `instance.is_template`, `instance.template_id`, the port fields, `factorio.rcon_password` and hidden fields are never inherited. +A template may itself inherit from another template, but not from itself through a chain of templates. +The fields currently inherited are stored in the hidden `instance.inherited_fields` field. +In the web interface inherited values are linked and read only until they are unlinked. + +Defaults to null meaning no template. + + ### factorio.version Version of Factorio to use for this instance. @@ -591,6 +639,8 @@ Most plugins require the use of save patching to function. Turning it off makes it possible to use Clusterio to run and manage regular vanilla games and scenarios not compatible with Clusterio. Plugins that need save patching can't be loaded on the instance while this is disabled. Disabling it while such a plugin is loaded is rejected, and so is loading such a plugin while it is disabled. +Saves patched before are restored to their original control.lua and have the modules removed when started with this disabled. +Data the modules stored in the game is left in place. Defaults to true. @@ -741,9 +791,9 @@ Defaults to 5. Whether to load the given plugin on the instance. Note that plugins need to be loaded on the controller and the host in order for them to be loaded on instances. -Loading a plugin that requires save patching or script commands is rejected while factorio.enable_save_patching or factorio.enable_script_commands respectively is disabled on the instance. +Loading a plugin that requires save patching, script commands or Lua UDP is rejected while factorio.enable_save_patching, factorio.enable_script_commands or factorio.enable_lua_udp respectively is disabled on the instance. -Defaults to true. +Defaults to true, or false if the instance does not have the features the plugin requires. ## Ctl Configuration diff --git a/docs/contributing.md b/docs/contributing.md index a206de81..0692fd8b 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -87,10 +87,12 @@ Install dependencies with: This installs dependencies and builds the packages. `pnpm-lock.yaml` is intentionally ignored; do not force-add it or assume a frozen-lockfile install is supported. -For a fresh development cluster, run the installer and select standalone mode to create `config-controller.json`, `config-host.json`, and the credentials needed to connect them: +For a fresh development cluster, run the installer and select standalone mode to create `config-controller.json` and `config-host.json`: node packages/create --dev +The first time the host starts it prints a link for approving it in the web interface. + You can skip this step if you already have a working controller and host configuration. To add plugins to use in the development environment use @@ -123,6 +125,7 @@ For web development on the controller there are also the following flags: `--dev` - Serve the `web_ui` package from source through Vite's development server with hot module replacement. `--dev-plugin [name]` - Serve the web module for the given plugin from source the same way. +This also serves the `web_ui` package from source, as the plugin has to share its modules with it. These options can be combined and multiple plugins can be actived for dev mode. Keep in mind if you're working on external plugins the `--dev-plugin` option is likely to only work if the plugin is placed inside the `external_plugins` directory and its dependencies are installed with pnpm as part of the clusterio repository workspace. diff --git a/docs/devs/plugin-migration-to-2.1.md b/docs/devs/plugin-migration-to-2.1.md index 30545fdf..42471313 100644 --- a/docs/devs/plugin-migration-to-2.1.md +++ b/docs/devs/plugin-migration-to-2.1.md @@ -59,3 +59,47 @@ Imports of `assert`, `buffer`, `events`, `os`, `path`, `process`, `stream`, `uti The `container` property of `WebPluginContext` is now the plugin's ES module namespace, `await container.get("./web")` returns the module instead of a factory function. `lib.PluginWebpackEnvInfo` is renamed to `lib.PluginWebEnvInfo`. + + +## Renamed lib functions + +`lib.safeOutputFile` is renamed to `lib.atomicOverwriteFile`. +It takes the same arguments. + + +## Host pairing + +Host tokens are no longer generated by users. +A host joins the cluster by having the code it shows when it first starts approved, see [Host pairing](protocol.md#host-pairing) for the HTTP endpoints it uses. + +- `HostGenerateTokenRequest` and `HostConfigCreateRequest` are removed. + Pending requests are listed with `HostPairingListRequest`, approved with `HostPairingApproveRequest` and rejected with `HostPairingRejectRequest`, and changes to them are sent to subscribers of `HostPairingUpdatesEvent`. +- `HostRevokeTokensRequest` is replaced by `HostRevokeRequest`, which deletes the host instead of only invalidating its tokens. + Instances assigned to the host become unassigned. +- The permissions `core.host.generate_token`, `core.host.revoke_token` and `core.host.create_config` are removed. + Check `core.host.approve` and `core.host.revoke` instead. +- `clusteriocontroller bootstrap generate-host-token` is removed, scripts that set up hosts can start the host with `--user-token` to approve it with a user token. + +Host records are no longer created when a host connects, only by approving it, and the controller rejects hosts it has no record of. +Revoking a host deletes its record and note. +Plugins that keep data per host should remove it when the host is deleted. +On the controller the `update` event of `controller.hosts.records` gives the record with `isDeleted` set to true, and subscribers of `HostUpdatesEvent` receive the host with `isDeleted` set to true. +A host that is revoked and approved again gets a new id. + + +## Host manager + +`controller.hosts` is now a `HostManager`, like `controller.users` is a `UserManager`. +`get`, `getMutable`, `has` and `values` work as before. +Everything else on the datastore, like `set`, `delete`, `size` and the `update` event, is on `controller.hosts.records`. + +The host manager also signs and checks host tokens and creates and deletes hosts: + +- `controller.generateHostToken(hostId)` is now `controller.hosts.signHostToken(hostId)`. +- `controller.verifyHostToken(token)` is now `controller.hosts.verifyHostToken(token)`. + It returns the `HostRecord` instead of the host id. +- `controller.hostPairing.createHost(name)` is now `controller.hosts.createHost(name)`. + It returns the new `HostRecord` instead of `{ hostId, token, name }`, sign a token for it with `signHostToken`. +- `controller.hosts.revokeHost(hostId, revokedBy)` deletes a host the same way `HostRevokeRequest` does. + +User tokens are checked with `controller.users.verifyUserToken(token)`, which returns the user or throws if the token is invalid. diff --git a/docs/devs/protocol.md b/docs/devs/protocol.md index 0f9cf15e..07c71a6c 100644 --- a/docs/devs/protocol.md +++ b/docs/devs/protocol.md @@ -32,6 +32,63 @@ The [send-buffer setting](../configuration.md#controllermax_send_buffer_size) co ![Connection flow](../assets/connection_flow.svg) +## Host pairing + +The host id and token sent in `registerHost` are requested by the host over HTTP the first time it starts, before it connects. +Hosts are only added to the controller by approving a pairing request, and `registerHost` is rejected with close code 3000 (Unauthorized) for a host id the controller has no record of. +Revoking a host deletes its record, so its token stops working and the host has to be approved again the next time it starts, which gives it a new id. +See [Setting up remote hosts](/README.md#setting-up-remote-hosts) for how this looks to the user. + +The endpoints below take and return JSON bodies and are sent with `Cache-Control: no-store`. +The `POST` endpoints return errors as `{"error": ""}` and respond with 503 while the controller is in recovery mode. +A request body that is not valid JSON or is larger than 4 kB is rejected with 400 or 413 before it reaches the endpoint, without a JSON body. +`GET /api/host-pairing/check` also works in recovery mode, and responds to a token that is not valid with a plain 401 without a JSON body. +A user or host token is sent in either an `Authorization: Bearer ` header or an `X-Access-Token` header. + +### `POST /api/host-pairing` + +Creates a request for a host to join the cluster. + +- `name: string` - Name of the host, at most 100 characters after trimming whitespace, without control characters. +- `version: string` (optional) - Version of the host. + +Responds with 202 and `{"requestId": string, "code": string}`. +The `code` is shown to the user to approve the request with, formatted as six characters like `ABC-DEF`. +Codes are matched ignoring case and anything that is not a letter or digit, so `abcdef` matches `ABC-DEF`. +The `requestId` is a secret used to poll for the result, it is never shown to users. + +If a user token is sent and the user has the `core.host.approve` permission the host is created right away and the response is 200 with the same body as an approved poll. +An invalid token gives 401 and a user without the permission gives 403, a token is never ignored to create a pending request instead. + +A missing or too long name gives 400. +Too many pending requests from the same address, or in total as set by [controller.host_pairing_max_pending](/docs/configuration.md#controllerhost_pairing_max_pending), gives 429 with a `Retry-After` header in seconds. + +### `POST /api/host-pairing/poll` + +- `requestId: string` - Id returned when the request was created. + +Responds with 202 and `{"status": "pending"}` while the request is waiting for approval. +Once approved it responds with 200 and `{"hostId": integer, "token": string, "name": string}`, where `name` is the name the host was approved with, which can differ from the one asked for. +Rejected requests give 403, and unknown or expired requests give 404. +The result of an approved or rejected request is only returned once, after which the request is gone. + +A pending request expires 30 seconds after it was last polled, and after waiting for the time set by [controller.host_pairing_timeout](/docs/configuration.md#controllerhost_pairing_timeout). +The host polls every 2 seconds, and makes a new request when the previous one has expired. + +### `POST /api/host-pairing/cancel` + +- `requestId: string` - Id returned when the request was created. + +Removes a pending request, sent by the host when it stops waiting. +Responds with 204 whether or not the request existed. + +### `GET /api/host-pairing/check` + +Checks a host token. +Responds with 200 and `{"valid": true}` if the token is valid and the host it was issued to still exists, and with 401 otherwise. +A host with a saved token checks it with this when it starts, and requests to join again if the token is not accepted. + + ## Connector flow To manage the complexity of connecting, reconnecting, resuming or invalidating dropped sessions the WebSocket connection for a `Link` class is managed by a connector. @@ -119,6 +176,11 @@ Host handshake for establishing a new connection session. - `plugins: Object` - Object mapping plugin names to plugin version for plugins that are available on the host. +The controller closes the connection with code 3000 (Unauthorized) if the token is invalid, was issued for another id, or if there is no host with this id, see [Host pairing](#host-pairing). +The host checks its token before connecting and requests to join again if it is not accepted, so this normally only happens to a host that is already running. +A host that has been rejected exits with code 8, and the run scripts created by the installer do not restart it. +A host that is revoked while connected is disconnected, is rejected when it tries to connect again, and shuts down. + #### `registerControl` Control handshake for enstablishing a new connection session. diff --git a/docs/how-it-works.md b/docs/how-it-works.md index cf99000d..d3736cad 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -27,6 +27,7 @@ The save patching is based on the built in [event_handler](https://github.com/wu Mods on the other hand work without modifications. This can be disabled with the `factorio.enable_save_patching` config on a per instance basis, however disabling it means that modules are not loaded into the game and most plugins will not function. +A save that was patched before has its modules removed again when it's started with save patching disabled. To use the modules outside of Clusterio the `npx clusteriohost create-scenario` command creates a scenario with the modules patched into it. Note that the IPC between the game and the host is not available outside of Clusterio, so modules that depend on it will not work as expected in such a scenario. diff --git a/docs/managing-a-cluster.md b/docs/managing-a-cluster.md index b96c57e8..5a048c27 100644 --- a/docs/managing-a-cluster.md +++ b/docs/managing-a-cluster.md @@ -16,17 +16,40 @@ The easiest way to do this is to run `npx clusteriocontroller bootstrap create-c Lists all hosts. -### Generate token +Hosts are added to the cluster by running the installer on the computer the host runs on and approving the code it shows, see [Setting up remote hosts](/README.md#setting-up-remote-hosts). +Listing, approving and rejecting hosts waiting for approval needs the `core.host.approve` permission. - ctl> host generate-token [--id ] +### List pending hosts -Generate a token for a host. `--id` is the host id. + ctl> host pending -### Create config +Lists hosts waiting for approval with the code they show, the name they asked for, the address they connected from and how long they have been waiting. +A request goes away when its host stops waiting, and after the time set by `controller.host_pairing_timeout`, an hour by default, after which the host asks again with a new code. - ctl> host create-config [--id ] [--name ] [--generate-token ] [--output ] +### Approve host -Create a host config. `--id` id the host id. `--name` is the host name. `--generate-token` decides whether to also generate a token, defaulting to `0`. `--output` is the filename for the output of the config; Default is "config-host.json", "-" for stdout. + ctl> host approve [--name ] + +Approves the host showing the code and prints the id of the new host. +The code is not case sensitive and the dash can be left out. +`--name` gives the host a different name than the one it asked for. +Approving gives the host full access to the cluster, check with `host pending` that the name and address match the computer you are setting up. + +### Reject host + + ctl> host reject + +Rejects the host showing the code, the host then exits with an error. + +### Revoke host + + ctl> host revoke + +Specify the host by name or ID. +Removes the host from the cluster, disconnects it and makes its token stop working. +Instances assigned to the host become unassigned, their files stay on the computer. +Requires the `core.host.revoke` permission. +To add the computer back to the cluster, start the host again and approve it. ### Update Clusterio @@ -56,15 +79,16 @@ Marks the host as requiring a restart, the same way a plugin update does. Use it ### List Instances - ctl> instance list + ctl> instance list [--templates] List instances. +Templates are only listed if `--templates` is passed. ### Create instance - ctl> instance create [--id ] + ctl> instance create [--id ] [--from ] [--template ] [--as-template] -Create a new instance. `name` is the instance name. `--id` is the optional id. +Create a new instance. `name` is the instance name. `--id` is the optional id. `--from` copies the config of an existing instance. `--template` makes the new instance inherit all config values from the given template. `--as-template` creates the instance as a template, see `instance.is_template` in the [configuration docs](configuration.md). Use `--as-template --from ` to make a template out of an existing instance. ### Kill instance @@ -97,7 +121,7 @@ Most notably Clusterio records wall clock time while the save time is recorded i ctl> instance config list -List config values for an instance. `instance` is the instance whose config values to list. +List config values for an instance. `instance` is the instance whose config values to list. Values inherited from a template are marked with `(inherited)`, object fields also list the properties set on the instance. #### Set config value @@ -109,11 +133,17 @@ Set field in instance config. `instance` is instance to set. `field` is field to To be written. +#### Inherit config value + + ctl> instance config inherit [prop] + +Make a field in the instance config take its value from the template again, undoing a previous `set`. `instance` is the instance to update, `field` is the field to inherit, `prop` limits it to one property of an object field. + #### Edit instance config ctl> instance config edit [editor] -Edit instance config in a text editor. Once file is saved and editor has been exited, config values will be read back in. `instance` is the instance to edit, `editor` is the editor to use. If `editor` is not given, clusterioctl will read from the `EDITOR` or `VISUAL` enviroment variables. +Edit instance config in a text editor. Once file is saved and editor has been exited, changed config values will be read back in. `instance` is the instance to edit, `editor` is the editor to use. If `editor` is not given, clusterioctl will read from the `EDITOR` or `VISUAL` enviroment variables. ### Assign instance to host @@ -270,9 +300,11 @@ To be written. ## Plugins (Remote) -By default, remote updates are enabled unless you selected "no" during installation. -Remote updates allow ctl and the web UI to update plugins on machines within the cluster. -However, remote installations are disabled by default to prevent the risk of arbitrary code execution through the installation of malicious npm packages onto the machine. See below if you wish to enable this feature. +The installer asks "Allow remote updates and plugin installs from the web interface?" and the answer sets `allow_remote_updates`, `allow_plugin_updates` and `allow_plugin_install` together on that machine, pass `--remote-npm` or `--no-remote-npm` to answer it from the command line. +Remote updates allow ctl and the web UI to update Clusterio and plugins on machines within the cluster. +Remote installs allow them to install any package from npm onto the machine, which is a risk of arbitrary code execution through malicious npm packages, so only allow them if you trust everyone with access to install plugins. +In a config created without the installer remote updates are enabled and remote installs are disabled by default. +See below for changing these settings after installing. ### List diff --git a/docs/setting-up-tls.md b/docs/setting-up-tls.md index 500a6356..89073068 100644 --- a/docs/setting-up-tls.md +++ b/docs/setting-up-tls.md @@ -69,7 +69,7 @@ This creates a private key file named `key.pem` and a public certificate file na npx clusteriocontroller config set controller.tls_certificate cert.pem npx clusteriocontroller config set controller.tls_private_key key.pem -Additionally you will need copy the `cert.pem` file to all of the computers you want to set up as hosts and configure node to trust it by setting the `NODE_EXTRA_CA_CERTS` environment variable to a path to this file before the host is started. You can do this by passing `--self-signed-cert path/to/cert` to the installer when setting up a host, or manually by editing run-host.cmd, run-host.sh and/or clusteriohost.service by adding the following line next to the one setting `NODE_OPTIONS`: +Additionally you will need copy the `cert.pem` file to all of the computers you want to set up as hosts and configure node to trust it by setting the `NODE_EXTRA_CA_CERTS` environment variable to a path to this file before the host is started. You can do this by passing `--self-signed-cert path/to/cert` to the installer when setting up a host, which also makes the installer trust the certificate when it asks the controller to approve the host, or manually by editing run-host.cmd, run-host.sh and/or clusteriohost.service by adding the following line next to the one setting `NODE_OPTIONS`: **For run-host.cmd** diff --git a/docs/writing-plugins.md b/docs/writing-plugins.md index d2a2a82f..18d32b64 100644 --- a/docs/writing-plugins.md +++ b/docs/writing-plugins.md @@ -16,6 +16,7 @@ Each entrypoint of a plugin exports a function that attaches handlers to hooks c - [Defining Link Messages](#defining-link-messages) - [Sending Link Messages](#sending-link-messages) - [Handling connection events](#handling-connection-events) +- [Web Pages for a Single Resource](#web-pages-for-a-single-resource) - [Collecting Statistics](#collecting-statistics) - [Adding Custom Commands to clusterioctl](#adding-custom-commands-to-clusterioctl) @@ -318,6 +319,7 @@ export const plugin = { ``` Enabling the plugin on an instance that has the feature turned off then fails config validation, so the mistake is caught when the config is edited instead of when the instance starts. +Instances that have the feature turned off get the plugin disabled by default when it is added. Other constraints on config fields are expressed with a `validator` on the field definition, which throws when the value is not acceptable. Use `dependsOn` when the check involves other fields so that the validator runs when those change too. @@ -842,6 +844,34 @@ This means that if your plugin sends a lot of events or requests, they can end u To avoid this you should be throtteling and/or stopping your requests/events after `drop` has been raised, and continue back as normal when `resume` is raised. +## Web Pages for a Single Resource + +A web page showing one resource from a subscription has more to handle than the resource itself. +It can still be loading, it might not exist, it can be deleted while the page is open, and the subscription is rejected if the user lacks the permission for it. +`useResourceState` and `ResourceState` from `@clusterio/web_ui` show these the same way as the pages for hosts, instances and the other built in resources. + +```tsx +function FrobberPage() { + const id = Number(useParams().id); + const [frobbers, synced, error] = useSyncExternalStore(subscribe, () => frobberSubscriber.getSnapshot()); + const frobber = frobbers.get(id); + const state = useResourceState(frobber, synced, error, id); + + const nav = [{ name: "Frobbers", path: "/frobbers" }, { name: frobber?.name ?? String(id) }]; + if (!frobber) { + return ; + } + + return {frobber.name}; +} +``` + +`useResourceState` returns `"ok"` when there is a value and otherwise `"loading"`, `"missing"`, `"deleted"` or `"error"`. +It tells deleted from missing by remembering if it has seen a value for that id. +`ResourceState` renders the whole page for the states without a value, with a link back to the page at `listPath`. +The `useHost`, `useInstance`, `useUser`, `useRole` and `useModPack` hooks return `[value, synced, error]` so they can be used the same way. + + ## Collecting Statistics Clusterio comes with its own Prometheus client implementation, one part due to Not Invented Here and another part due to collectors in prom-client being difficult to get to work nicely with collecting data from plugins optionally loaded at runtime on different computers. diff --git a/packages/controller/controller.ts b/packages/controller/controller.ts index 9e154c47..29334ed4 100644 --- a/packages/controller/controller.ts +++ b/packages/controller/controller.ts @@ -23,7 +23,6 @@ import util from "util"; import winston from "winston"; import DailyRotateFile from "winston-daily-rotate-file"; -import jwt from "jsonwebtoken"; // homebrew modules // Reduce startup time by lazy compiling schemas. @@ -188,14 +187,6 @@ async function handleBootstrapCommand( // eslint-disable-next-line no-console console.log(userManager.signUserToken(user)); - } else if (subCommand === "generate-host-token") { - // eslint-disable-next-line no-console - console.log(jwt.sign( - { aud: "host", host: args.id }, - // Auth secret is never null after startup - Buffer.from(controllerConfig.get("controller.auth_secret")!, "base64") - )); - } else if (subCommand === "create-ctl-config") { let admin = userManager.getByName(args.name); if (!admin) { @@ -218,7 +209,7 @@ async function handleBootstrapCommand( console.log(content); } else { logger.info(`Writing ${args.output}`); - await lib.safeOutputFile(args.output, content, { mode: 0o600 }); + await lib.atomicOverwriteFile(args.output, content, { mode: 0o600 }); } } } @@ -325,9 +316,6 @@ async function initialize(): Promise { .command("generate-user-token ", "Generate authentication token for the given user", yargs => { yargs.positional("name", { describe: "Name of the user", type: "string" }); }) - .command("generate-host-token ", "Generate authentication token for the given host", yargs => { - yargs.positional("id", { describe: "ID of the host", type: "number" }); - }) .command("create-ctl-config ", "Create clusterioctl config for the given user", yargs => { yargs.option("output", { describe: "Path to output config (- for stdout)", type: "string", diff --git a/packages/controller/index.ts b/packages/controller/index.ts index 6a8937b6..eec80517 100644 --- a/packages/controller/index.ts +++ b/packages/controller/index.ts @@ -5,7 +5,9 @@ export { default as ControlConnection } from "./src/ControlConnection.js"; export { default as HostConnection } from "./src/HostConnection.js"; export { default as InstanceRecord } from "./src/InstanceRecord.js"; export { default as InstanceManager } from "./src/InstanceManager.js"; +export { default as HostManager } from "./src/HostManager.js"; export { default as HostRecord } from "./src/HostRecord.js"; +export { default as HostPairingManager, HostPairingError } from "./src/HostPairingManager.js"; export { BaseControllerPlugin, ControllerHooks, type ControllerPluginContext } from "./src/BaseControllerPlugin.js"; export { default as UserManager } from "./src/UserManager.js"; export { default as UserRecord } from "./src/UserRecord.js"; diff --git a/packages/controller/src/ControlConnection.ts b/packages/controller/src/ControlConnection.ts index d0f7b636..05c1e833 100644 --- a/packages/controller/src/ControlConnection.ts +++ b/packages/controller/src/ControlConnection.ts @@ -8,6 +8,7 @@ import { logFilter, logger } from "@clusterio/lib"; import BaseConnection from "./BaseConnection.js"; import User from "./User.js"; import UserRecord from "./UserRecord.js"; +import type InstanceRecord from "./InstanceRecord.js"; import * as routes from "./routes.js"; import Controller from "./Controller.js"; @@ -81,10 +82,11 @@ export default class ControlConnection extends BaseConnection { this.handle(lib.ControllerConfigSetRequest, this.handleControllerConfigSetRequest.bind(this)); this.handle(lib.ControllerConfigSetFieldRequest, this.handleControllerConfigSetFieldRequest.bind(this)); this.handle(lib.ControllerConfigSetPropRequest, this.handleControllerConfigSetPropRequest.bind(this)); - this.handle(lib.HostRevokeTokensRequest, this.handleHostRevokeTokensRequest.bind(this)); + this.handle(lib.HostRevokeRequest, this.handleHostRevokeRequest.bind(this)); this.handle(lib.HostListRequest, this.handleHostListRequest.bind(this)); - this.handle(lib.HostGenerateTokenRequest, this.handleHostGenerateTokenRequest.bind(this)); - this.handle(lib.HostConfigCreateRequest, this.handleHostConfigCreateRequest.bind(this)); + this.handle(lib.HostPairingListRequest, this.handleHostPairingListRequest.bind(this)); + this.handle(lib.HostPairingApproveRequest, this.handleHostPairingApproveRequest.bind(this)); + this.handle(lib.HostPairingRejectRequest, this.handleHostPairingRejectRequest.bind(this)); this.handle(lib.InstanceDetailsGetRequest, this.handleInstanceDetailsGetRequest.bind(this)); this.handle(lib.InstanceDetailsListRequest, this.handleInstanceDetailsListRequest.bind(this)); this.handle(lib.InstanceCreateRequest, this.handleInstanceCreateRequest.bind(this)); @@ -93,6 +95,7 @@ export default class ControlConnection extends BaseConnection { this.handle(lib.InstanceConfigSetRequest, this.handleInstanceConfigSetRequest.bind(this)); this.handle(lib.InstanceConfigSetFieldRequest, this.handleInstanceConfigSetFieldRequest.bind(this)); this.handle(lib.InstanceConfigSetPropRequest, this.handleInstanceConfigSetPropRequest.bind(this)); + this.handle(lib.InstanceConfigInheritFieldRequest, this.handleInstanceConfigInheritFieldRequest.bind(this)); this.handle(lib.InstanceAssignRequest, this.handleInstanceAssignRequest.bind(this)); this.handle(lib.InstanceSaveDetailsListRequest, this.handleInstanceSaveDetailsListRequest.bind(this)); this.handle(lib.InstanceRenameSaveRequest, controller.sendRequestToHostByInstanceId.bind(controller)); @@ -248,49 +251,25 @@ export default class ControlConnection extends BaseConnection { this._controller.config.setProp(field as keyof lib.ControllerConfigFields, prop, value, "control"); } - async handleHostRevokeTokensRequest(request: lib.HostRevokeTokensRequest) { - const host = this._controller.hosts.getMutable(request.hostId); - if (!host) { - throw new Error(`Unknown host id (${request.hostId})`); - } - - host.tokenValidAfter = Math.floor(Date.now() / 1000); - - const hostConnection = this._controller.wsServer.hostConnections.get(request.hostId); - if (hostConnection) { - hostConnection.connector.terminate(); - } - - this._controller.hosts.set(host); + async handleHostRevokeRequest(request: lib.HostRevokeRequest) { + await this._controller.hosts.revokeHost(request.hostId, this.user.name); } async handleHostListRequest(): Promise { return [...this._controller.hosts.values()].map(host => host.toHostDetails()); } - async handleHostGenerateTokenRequest(message: lib.HostGenerateTokenRequest) { - let hostId = message.hostId; - if (hostId === undefined) { - hostId = Math.random() * 2**31 | 0; - } - return this._controller.generateHostToken(hostId); + async handleHostPairingListRequest(): Promise { + this._controller.hostPairing.prune(); + return [...this._controller.hostPairing.records.values()]; } - async handleHostConfigCreateRequest(request: lib.HostConfigCreateRequest) { - const hostConfig = new lib.HostConfig("host"); + async handleHostPairingApproveRequest(request: lib.HostPairingApproveRequest) { + return this._controller.hostPairing.approve(request.code, request.name, this.user.name); + } - hostConfig.set("host.controller_url", this._controller.getControllerUrl()); - if (request.id !== undefined) { - hostConfig.set("host.id", request.id); - } - if (request.name !== undefined) { - hostConfig.set("host.name", request.name); - } - if (request.generateToken) { - this.user.checkPermission("core.host.generate_token"); - hostConfig.set("host.controller_token", this._controller.generateHostToken(hostConfig.get("host.id"))); - } - return hostConfig.toJSON(); + async handleHostPairingRejectRequest(request: lib.HostPairingRejectRequest) { + this._controller.hostPairing.reject(request.code, this.user.name); } async handleInstanceDetailsGetRequest(request: lib.InstanceDetailsGetRequest) { @@ -315,6 +294,12 @@ export default class ControlConnection extends BaseConnection { instanceConfig.set("instance.assigned_host", null); // New instances are unassigned } instanceConfig.update(request.config, false, "control"); + this._controller.instances.checkInheritance( + instanceConfig, instanceConfig.get("instance.is_template"), instanceConfig.get("instance.template_id") + ); + if (Object.hasOwn(request.config, "instance.template_id")) { + this._controller.instances.applyTemplate(instanceConfig, Object.keys(request.config)); + } await this._controller.instances.createInstance(instanceConfig); } @@ -355,17 +340,41 @@ export default class ControlConnection extends BaseConnection { } } + this.checkStagedInheritance(instance); instance.config.commitStaging(); + for (const [fieldName, fieldValue] of Object.entries(request.fields)) { + const props = typeof fieldValue === "object" + ? Object.keys(fieldValue).filter(prop => fieldValue[prop] !== undefined) + : undefined; + this._controller.instances.overrideField(instance, fieldName, props); + } await this._controller.instanceConfigUpdated(instance); } finally { instance.config.revertStaging(); } } + private checkStagedInheritance(instance: InstanceRecord) { + const staged = instance.config.staging; + this._controller.instances.checkInheritance( + instance.config, staged.get("instance.is_template"), staged.get("instance.template_id") + ); + } + async handleInstanceConfigSetFieldRequest(request: lib.InstanceConfigSetFieldRequest) { const instance = this._controller.instances.getForRequest(request.instanceId); - ControlConnection.validateInstanceConfigSetField(request.field); - instance.config.set(request.field as keyof lib.InstanceConfigFields, request.value, "control"); + const field = request.field as keyof lib.InstanceConfigFields; + ControlConnection.validateInstanceConfigSetField(field); + if (["instance.is_template", "instance.template_id"].includes(field)) { + try { + instance.config.stage(field, request.value, "control"); + this.checkStagedInheritance(instance); + } finally { + instance.config.revertStaging(); + } + } + instance.config.set(field, request.value, "control"); + this._controller.instances.overrideField(instance, field); await this._controller.instanceConfigUpdated(instance); } @@ -374,9 +383,18 @@ export default class ControlConnection extends BaseConnection { let { field, prop, value } = request; ControlConnection.validateInstanceConfigSetField(field); instance.config.setProp(field as keyof lib.InstanceConfigFields, prop, value, "control"); + if (value !== undefined) { + this._controller.instances.overrideField(instance, field, [prop]); + } await this._controller.instanceConfigUpdated(instance); } + async handleInstanceConfigInheritFieldRequest(request: lib.InstanceConfigInheritFieldRequest) { + ControlConnection.validateInstanceConfigSetField(request.field); + this._controller.instances.inheritField(request.instanceId, request.field, request.prop); + await this._controller.instanceConfigUpdated(this._controller.instances.getForRequest(request.instanceId)); + } + async handleInstanceAssignRequest(request: lib.InstanceAssignRequest) { await this._controller.instances.assignInstance(request.instanceId, request.hostId ?? null); } diff --git a/packages/controller/src/Controller.ts b/packages/controller/src/Controller.ts index bbd2286d..e5058ff2 100644 --- a/packages/controller/src/Controller.ts +++ b/packages/controller/src/Controller.ts @@ -11,7 +11,6 @@ import events from "events"; import fs from "node:fs/promises"; import http from "http"; import https from "https"; -import jwt from "jsonwebtoken"; import path from "path"; import semver from "semver"; import stream from "stream"; @@ -28,7 +27,9 @@ import User from "./User.js"; import UserRecord from "./UserRecord.js"; import UserManager from "./UserManager.js"; import WsServer from "./WsServer.js"; +import HostManager from "./HostManager.js"; import HostRecord from "./HostRecord.js"; +import HostPairingManager from "./HostPairingManager.js"; import { BaseControllerPlugin, ControllerHooks } from "./BaseControllerPlugin.js"; import ControllerRouter from "./ControllerRouter.js"; import InstanceManager from "./InstanceManager.js"; @@ -87,10 +88,14 @@ export default class Controller { /** Event subscription controller */ subscriptions: lib.SubscriptionController; + /** Host manager for the cluster, also contains access to the host records */ + hosts: HostManager; /** User manager for the cluster, also contains access to the user records */ users: UserManager; /** Instance manager for the cluster, also contains access to the user records */ instances: InstanceManager; + /** Pending requests from hosts to join the cluster */ + hostPairing: HostPairingManager; // Possible states are new, starting, running, stopping, stopped private _state: string = "new"; @@ -135,7 +140,7 @@ export default class Controller { const cachePath = path.join(this.config.get("controller.database_directory"), "latest-releases.json"); try { const releases = await lib.fetchLatestReleases(); - await lib.safeOutputFile(cachePath, JSON.stringify(releases, null, "\t")); + await lib.atomicOverwriteFile(cachePath, JSON.stringify(releases, null, "\t")); return releases; } catch (err: any) { logger.warn(`Failed to retrieve Factorio releases ${err.message}`); @@ -223,6 +228,8 @@ export default class Controller { await fs.mkdir(modsDirectory, { recursive: true }); const modStore = await lib.ModStore.fromDirectory(modsDirectory); + await this.validateExports(modPacks, "static"); + // Add default mod packs if (modPacks.size === 0) { modPacks.setMany(lib.ModPack.defaultModPacks); @@ -267,7 +274,7 @@ export default class Controller { public recoveryMode: boolean = false, public systems = new lib.SubscribableDatastore(), /** Mapping of host id to host record */ - public hosts = new lib.SubscribableDatastore(), + hosts = new lib.SubscribableDatastore(), /** Mapping of instance id to instance record */ instances = new lib.SubscribableDatastore(), /** Mapping of save id to save details */ @@ -294,8 +301,10 @@ export default class Controller { this.trustedProxies = this.parseTrustedProxies(); this.wsServer = new WsServer(this); + this.hosts = new HostManager(hosts, this); this.users = new UserManager(users, roles, config); this.instances = new InstanceManager(instances, this); + this.hostPairing = new HostPairingManager(this); this.modStore.on("change", mod => { this.modsUpdated([mod]); @@ -305,6 +314,7 @@ export default class Controller { this.subscriptions = new lib.SubscriptionController(config.get("controller.max_subscription_filters")); this.subscriptions.handle(lib.SystemInfoUpdateEvent, this.handleSystemInfoSubscription.bind(this)); this.subscriptions.handle(lib.HostUpdatesEvent, this.handleHostSubscription.bind(this)); + this.subscriptions.handle(lib.HostPairingUpdatesEvent, this.handleHostPairingSubscription.bind(this)); this.subscriptions.handle(lib.InstanceDetailsUpdatesEvent, this.handleInstanceDetailsSubscription.bind(this)); this.subscriptions.handle( lib.InstanceSaveDetailsUpdatesEvent, this.handleInstanceSaveDetailsSubscription.bind(this) @@ -317,7 +327,8 @@ export default class Controller { // Handle updates for datastores this.systems.on("update", this.systemsUpdated.bind(this)); - this.hosts.on("update", this.hostsUpdated.bind(this)); + this.hosts.records.on("update", this.hostsUpdated.bind(this)); + this.hostPairing.records.on("update", this.hostPairingRequestsUpdated.bind(this)); this.instances.records.on("update", this.instanceUpdated.bind(this)); this.saves.on("update", this.savesUpdated.bind(this)); this.modPacks.on("update", this.modPacksUpdated.bind(this)); @@ -420,7 +431,7 @@ export default class Controller { this.app.use(this.devServer.middlewares); } - if (!args.dev) { + if (!this.devServer) { let manifestPath = path.join(import.meta.dirname, "..", "..", "web", "manifest.json"); let manifest = await Controller.loadJsonObject(manifestPath); @@ -489,6 +500,7 @@ export default class Controller { logger.info(`Listening for HTTPS on port ${(this.httpsServer.address() as AddressInfo).port}`); } + this.hostPairing.start(); this.onAutosaveIntervalChanged(); this.onSystemMetricsIntervalChanged(); @@ -527,14 +539,14 @@ export default class Controller { }, plugins: [webUiVite.clusterioDevPlugins(pluginDirs)], }); - if (args.dev) { - this.app.locals.webBundle = { - main: this.devServer.config.plugins.find(p => p.name === "clusterio:app")!.api.entry, - imports: Object.fromEntries(webUiVite.sharedModules.map( - name => [name, webUiVite.devSharedUrl(name)] - )), - }; - } + // Plugins served from source import the shared modules from the development server, the web + // interface has to use the same copies, so it is served from source as well with --dev-plugin. + this.app.locals.webBundle = { + main: this.devServer.config.plugins.find(p => p.name === "clusterio:app")!.api.entry, + imports: Object.fromEntries(webUiVite.sharedModules.map( + name => [name, webUiVite.devSharedUrl(name)] + )), + }; this.app.locals.devServer = this.devServer; } @@ -582,6 +594,8 @@ export default class Controller { this.autosaveInterval = undefined; } + this.hostPairing.stop(); + if (this.clusterLogIndex) { await this.clusterLogIndex.save(); } @@ -785,7 +799,7 @@ export default class Controller { await Promise.all([ this.config.save(), this.systems.save(), - this.hosts.save(), + this.hosts.records.save(), this.instances.records.save(), this.saves.save(), this.modPacks.save(), @@ -867,8 +881,43 @@ export default class Controller { }); } + /** Remove export manifests that reference files missing from staticDirectory */ + static async validateExports(modPacks: lib.SubscribableDatastore, staticDirectory: string) { + const invalid: lib.ModPack[] = []; + for (const modPack of modPacks.valuesMutable()) { + if (!modPack.exportManifest) { + continue; + } + const missing: string[] = []; + for (const file of Object.values(modPack.exportManifest.assets)) { + const valid = path.basename(file) === file + && await fs.stat(path.join(staticDirectory, file)).then(s => s.isFile(), () => false); + if (!valid) { + missing.push(file); + } + } + if (missing.length) { + Controller.dropExport(modPack, `missing ${missing.join(", ")}`); + invalid.push(modPack); + } + } + if (invalid.length) { + modPacks.setMany(invalid); + } + } + + /** Clear the export manifest of a mutable mod pack, caller must save it */ + static dropExport(modPack: lib.ModPack, reason: string) { + logger.warn(`Removing export data of mod pack ${modPack.name} (id ${modPack.id}): ${reason}`); + modPack.exportManifest = undefined; + } + static migrateRoles(rawJson: unknown[]): Static[] { const serialized = rawJson as Static[]; + // migrate: host token permissions were removed with host pairing in 2.1 + const removedPermissions = new Set([ + "core.host.generate_token", "core.host.revoke_token", "core.host.create_config", + ]); return serialized.map(json => { json.permissions = json.permissions.map(permission => { // migrate: core.instance.save.list.subscribe was renamed in alpha 17 @@ -876,7 +925,7 @@ export default class Controller { return "core.instance.save.subscribe"; } return permission; - }); + }).filter(permission => !removedPermissions.has(permission)); return lib.Role.pluginMigrations.reduce(json); }); } @@ -971,6 +1020,7 @@ export default class Controller { express.static(path.join(import.meta.dirname, "..", "..", "web", "static"), staticOptions) ); app.use("/static", express.static("static", staticOptions)); // Used for data export files + app.use("/static", routes.missingExportAsset); // Add API routes routes.addRouteHandlers(app); @@ -1002,21 +1052,25 @@ export default class Controller { return systems.length ? new lib.SystemInfoUpdateEvent(systems) : null; } - /** - * Generate access token for host - * - * @returns access token for host - * @param hostId - ID of host to generate a token for. - */ - generateHostToken(hostId: number): string { - return jwt.sign({ aud: "host", host: hostId }, this.authSecret); - } - hostsUpdated(hosts: HostRecord[]) { let updates = hosts.map(host => host.toHostDetails()); this.subscriptions.broadcast(new lib.HostUpdatesEvent(updates)); } + hostPairingRequestsUpdated(requests: lib.HostPairingDetails[]) { + this.subscriptions.broadcast(new lib.HostPairingUpdatesEvent(requests)); + } + + async handleHostPairingSubscription(request: lib.SubscriptionRequest) { + if (request.action === "unsubscribe") { + return null; + } + const requests = [...this.hostPairing.records.values()].filter( + pairing => pairing.updatedAtMs > request.lastRequestTimeMs, + ); + return requests.length ? new lib.HostPairingUpdatesEvent(requests) : null; + } + async handleHostSubscription(request: lib.SubscriptionRequest) { if (request.action === "unsubscribe") { return null; diff --git a/packages/controller/src/HostConnection.ts b/packages/controller/src/HostConnection.ts index 56d5d489..5df65ab3 100644 --- a/packages/controller/src/HostConnection.ts +++ b/packages/controller/src/HostConnection.ts @@ -34,20 +34,17 @@ export default class HostConnection extends BaseConnection { this.plugins = new Map(Object.entries(registerData.plugins)); - const previousHostInfo = this._controller.hosts.get(registerData.id); - this.info = new HostRecord( - registerData.id, - previousHostInfo?.name ?? "", - registerData.version, - this.plugins, - true, - remoteAddress, - previousHostInfo?.publicAddress, - previousHostInfo?.tokenValidAfter, - 0, - false, - ); - this._controller.hosts.set(this.info); + // Hosts are only created by approving them, WsServer rejects hosts without a record. + const record = this._controller.hosts.getMutable(registerData.id); + if (!record) { + throw new Error(`Host ${registerData.id} is not registered`); + } + record.version = registerData.version; + record.plugins = this.plugins; + record.connected = true; + record.remoteAddress = remoteAddress; + this.info = record; + this._controller.hosts.records.set(this.info); this._checkPluginVersions(); @@ -71,7 +68,7 @@ export default class HostConnection extends BaseConnection { this._controller.instances.records.setMany(instances); this.info.connected = false; - this._controller.hosts.set(this.info); + this.saveRecord(); }); this.handle(lib.GetFactorioCredentialsRequest, this.handleGetFactorioCredentialsRequest.bind(this)); @@ -175,10 +172,17 @@ export default class HostConnection extends BaseConnection { return {}; } + /** Store changes to the host record, unless the host was revoked */ + saveRecord() { + if (this._controller.hosts.getMutable(this.id) === this.info) { + this._controller.hosts.records.set(this.info); + } + } + async handleHostInfoUpdateEvent(event: lib.HostInfoUpdateEvent) { this.info.name = event.update.name; this.info.publicAddress = event.update.publicAddress; - this._controller.hosts.set(this.info); + this.saveRecord(); } async handleInstanceStatusChangedEvent(request: lib.InstanceStatusChangedEvent) { diff --git a/packages/controller/src/HostManager.ts b/packages/controller/src/HostManager.ts new file mode 100644 index 00000000..94783de8 --- /dev/null +++ b/packages/controller/src/HostManager.ts @@ -0,0 +1,149 @@ +import crypto from "node:crypto"; +import jwt from "jsonwebtoken"; + +import * as lib from "@clusterio/lib"; +import { logger } from "@clusterio/lib"; + +import type Controller from "./Controller.js"; +import HostRecord from "./HostRecord.js"; + +/** + * Access layer for hosts on the controller. + * + * @alias module:controller/src/HostManager + */ +export default class HostManager { + constructor( + public readonly records: lib.SubscribableDatastore, + private readonly _controller: Controller, + ) { } + + /* ------------------------------------------------------------------------- */ + /* Basic Accessors */ + /* ------------------------------------------------------------------------- */ + + has(id: HostRecord["id"]): boolean { + return this.records.has(id); + } + + getMutable(id: HostRecord["id"]): HostRecord | undefined { + return this.records.getMutable(id); + } + + get(id: HostRecord["id"]): Readonly | undefined { + return this.records.get(id); + } + + valuesMutable(): IterableIterator { + return this.records.values(); + } + + values(): IterableIterator> { + return this.valuesMutable(); + } + + /** + * Get host by ID for a request. + * + * @param hostId - ID of host to get. + * @returns The host record. + * @throws {module:lib.NotFoundError} if the host does not exist. + */ + getForRequest(hostId: number): HostRecord { + const host = this.records.getMutable(hostId); + if (!host) { + throw new lib.NotFoundError(`Unknown host id (${hostId})`); + } + return host; + } + + /* ------------------------------------------------------------------------- */ + /* Lifecycle */ + /* ------------------------------------------------------------------------- */ + + /** + * Create a host record with a new random id + * + * @param name - Name of the host. + * @returns the created host record. + */ + createHost(name: string): HostRecord { + let hostId; + do { + hostId = crypto.randomInt(1, 2 ** 31); + } while (this.records.has(hostId)); + + const host = new HostRecord( + hostId, name, "", new Map(), false, "", "", Math.floor(Date.now() / 1000), + ); + this.records.set(host); + return host; + } + + /** + * Delete a host, disconnect it and unassign its instances + * + * @param hostId - ID of host to revoke. + * @param revokedBy - Name of the user revoking it, for logging. + */ + async revokeHost(hostId: number, revokedBy: string) { + const host = this.getForRequest(hostId); + this.records.delete(host); + this._controller.deleteNote("host", hostId, revokedBy); + const system = this._controller.systems.getMutable(hostId); + if (system) { + this._controller.systems.delete(system); + } + + // Disconnected first so unassigning the instances does not depend on the host responding. + const hostConnection = this._controller.wsServer.hostConnections.get(hostId); + if (hostConnection) { + hostConnection.connector.terminate(); + } + const assigned = [...this._controller.instances.values()].filter( + instance => instance.config.get("instance.assigned_host") === hostId + ); + for (const instance of assigned) { + await this._controller.instances.unassignInstance(instance.id); + } + logger.audit(`User ${revokedBy} revoked host ${host.name} (${host.id})`); + } + + /* ------------------------------------------------------------------------- */ + /* Helpers */ + /* ------------------------------------------------------------------------- */ + + /** + * Sign access token for the given host + * + * @param hostId - ID of host to sign token for. + * @returns JWT access token for the host. + */ + signHostToken(hostId: number): string { + return jwt.sign({ aud: "host", host: hostId }, this._controller.authSecret); + } + + /** + * Check a host token + * + * @param token - Host token to check. + * @returns the host the token was issued to. + * @throws if the token is invalid, its host is not registered or it was issued before tokenValidAfter. + */ + verifyHostToken(token: string): HostRecord { + // migrate: allow pre-rename tokens issued to hosts before alpha-14 + const payload = jwt.verify(token, this._controller.authSecret, { audience: ["host", "slave"] }); + if (typeof payload === "string") { + throw new Error("unexpected JsonWebToken type"); + } + const hostId = payload.host !== undefined ? payload.host : payload.slave; + const host = this.records.getMutable(hostId); + if (!host) { + throw new Error("host is not registered, start the host again to request to join the cluster"); + } + if (!payload.iat || payload.iat < host.tokenValidAfter) { + throw new Error("invalid token"); + } + return host; + } +} diff --git a/packages/controller/src/HostPairingManager.ts b/packages/controller/src/HostPairingManager.ts new file mode 100644 index 00000000..eceb925e --- /dev/null +++ b/packages/controller/src/HostPairingManager.ts @@ -0,0 +1,299 @@ +import type Controller from "./Controller.js"; + +import crypto from "crypto"; +import net from "net"; + +import * as lib from "@clusterio/lib"; +import { logger } from "@clusterio/lib"; + +/** Symbols used in pairing codes, avoids 0/O and 1/I/L */ +const codeAlphabet = "23456789ABCDEFGHJKMNPQRSTUVWXYZ"; +const codeLength = 6; + +/** Time a request is kept after the last poll from the host */ +export const pollTimeoutMs = 30e3; +/** Maximum number of pending requests from one address */ +export const maxPendingPerAddress = 3; +/** Maximum length of a host name */ +export const maxNameLength = 100; +/** Control and bidirectional override characters refused in host names */ +const nameControlCharacters = /[\p{Cc}\u202a-\u202e\u2066-\u2069]/u; + +/** Result of an approved request, sent to the host */ +export interface HostPairingResult { + hostId: number, + token: string, + name: string, +} + +/** Error with an HTTP status code to respond to the host with */ +export class HostPairingError extends Error { + constructor( + message: string, + public status: number, + /** Seconds to wait before trying again, for status 429 */ + public retryAfter?: number, + ) { + super(message); + } +} + +type PairingRequest = { + /** Secret the host polls with, never shown to users */ + secret: string, + details: lib.HostPairingDetails, + /** Address with IPv6 addresses grouped by /64, used for limits */ + addressKey: string, + lastPollMs: number, +} & ( + { state: "pending" | "rejected" } | { state: "approved", result: HostPairingResult } +); + +/** + * Strips the IPv4 mapped prefix and groups IPv6 addresses by their /64 + * + * @param address - Address to make a key for + * @returns key used to count requests from an address. + */ +export function addressKey(address: string) { + if (address.startsWith("::ffff:") && net.isIPv4(address.slice(7))) { + return address.slice(7); + } + if (!net.isIPv6(address)) { + return address; + } + const [head, tail = ""] = address.split("::"); + const headParts = head ? head.split(":") : []; + const tailParts = tail ? tail.split(":") : []; + const missing = 8 - headParts.length - tailParts.length; + const parts = address.includes("::") + ? [...headParts, ...new Array(missing).fill("0"), ...tailParts] + : headParts; + return `${parts.slice(0, 4).map(part => part.toLowerCase().replace(/^0+(?=.)/, "")).join(":")}::/64`; +} + +/** + * Normalise a pairing code typed by a user + * + * @param code - Code as typed, may contain dashes and lower case letters. + * @returns code formatted as shown by the host. + */ +export function normaliseCode(code: string) { + const plain = code.toUpperCase().replace(/[^0-9A-Z]/g, ""); + return `${plain.slice(0, 3)}-${plain.slice(3)}`; +} + +function generateCode() { + let code = ""; + for (let i = 0; i < codeLength; i++) { + code += codeAlphabet[crypto.randomInt(codeAlphabet.length)]; + } + return normaliseCode(code); +} + +/** + * Keeps track of requests from hosts to join the cluster + * + * Requests only live in memory, and only while the host keeps polling + * for the result. + */ +export default class HostPairingManager { + /** Pending requests by code, broadcast to subscribed control links */ + records = new lib.SubscribableDatastore(); + private _bySecret = new Map(); + private _byCode = new Map(); + private _pruneInterval?: ReturnType; + + constructor( + private _controller: Controller, + ) { } + + start() { + this._pruneInterval = setInterval(() => this.prune(), 5e3); + this._pruneInterval.unref(); + } + + stop() { + clearInterval(this._pruneInterval); + this._pruneInterval = undefined; + } + + /** + * Check and trim a host name given by a host or a user + * + * @param name - Name to check. + * @returns the trimmed name. + */ + static validateName(name: unknown) { + if (typeof name !== "string" || !name.trim()) { + throw new HostPairingError("Host name is required", 400); + } + const trimmed = name.trim(); + if (trimmed.length > maxNameLength) { + throw new HostPairingError(`Host name must be at most ${maxNameLength} characters`, 400); + } + // Names come from unauthenticated requests and are printed to terminals and logs. + if (nameControlCharacters.test(trimmed)) { + throw new HostPairingError("Host name may not contain control characters", 400); + } + return trimmed; + } + + /** + * Create a pending request + * + * @param name - Name the host asked for. + * @param version - Version of the host. + * @param remoteAddress - Address the request came from. + * @returns the secret to poll with and the code to show the user. + */ + create(name: string, version: string, remoteAddress: string) { + this.prune(); + const key = addressKey(remoteAddress); + const now = Date.now(); + const pendingFromAddress = [...this._bySecret.values()].filter( + request => request.addressKey === key && request.state === "pending" + ).length; + if (pendingFromAddress >= maxPendingPerAddress) { + throw new HostPairingError("Too many pending requests from this address", 429, 30); + } + const maxPending = this._controller.config.get("controller.host_pairing_max_pending"); + if (maxPending && this.records.size >= maxPending) { + throw new HostPairingError("Too many pending requests", 429, 30); + } + + let code; + do { + code = generateCode(); + } while (this._byCode.has(code)); + + const request: PairingRequest = { + secret: crypto.randomBytes(32).toString("base64url"), + details: new lib.HostPairingDetails(code, name, remoteAddress, version, now), + addressKey: key, + lastPollMs: now, + state: "pending", + }; + this._bySecret.set(request.secret, request); + this._byCode.set(code, request); + this.records.set(request.details); + logger.verbose(`Host pairing request ${code} for "${name}" from ${remoteAddress}`); + return { requestId: request.secret, code }; + } + + /** + * Poll for the result of a request + * + * @param secret - Request id returned when the request was created. + * @returns the result if the request was approved, or null if still pending. + */ + poll(secret: string): HostPairingResult | null { + this.prune(); + const request = this._bySecret.get(secret); + if (!request) { + throw new HostPairingError("Request not found", 404); + } + request.lastPollMs = Date.now(); + if (request.state === "approved") { + this._remove(request); + return request.result; + } + if (request.state === "rejected") { + this._remove(request); + throw new HostPairingError("Request was rejected", 403); + } + return null; + } + + /** + * Cancel a pending request + * + * @param secret - Request id returned when the request was created. + */ + cancel(secret: string) { + const request = this._bySecret.get(secret); + if (request && request.state === "pending") { + logger.verbose(`Host pairing request ${request.details.code} cancelled by the host`); + this._remove(request); + } + } + + private _pending(code: string) { + this.prune(); + const request = this._byCode.get(normaliseCode(code)); + if (!request || request.state !== "pending") { + throw new lib.NotFoundError(`No pending host request with code ${code}`); + } + return request; + } + + /** + * Approve a pending request, creating the host + * + * @param code - Code of the request. + * @param name - Name to give the host, defaults to the requested name. + * @param approvedBy - Name of the user approving it, for logging. + * @returns the id of the new host. + */ + approve(code: string, name: string | undefined, approvedBy: string) { + const request = this._pending(code); + let hostName; + try { + hostName = name === undefined ? request.details.name : HostPairingManager.validateName(name); + } catch (err: any) { + throw new lib.ValidationError(err.message); + } + + const host = this._controller.hosts.createHost(hostName); + const result = { hostId: host.id, token: this._controller.hosts.signHostToken(host.id), name: host.name }; + Object.assign(request, { state: "approved", result }); + this.records.delete(request.details); + logger.audit( + `User ${approvedBy} approved host ${result.name} (${result.hostId}) with code ` + + `${request.details.code} from ${request.details.remoteAddress}` + ); + return result.hostId; + } + + /** + * Reject a pending request + * + * @param code - Code of the request. + * @param rejectedBy - Name of the user rejecting it, for logging. + */ + reject(code: string, rejectedBy: string) { + const request = this._pending(code); + request.state = "rejected"; + this.records.delete(request.details); + logger.audit( + `User ${rejectedBy} rejected host ${request.details.name} with code ` + + `${request.details.code} from ${request.details.remoteAddress}` + ); + } + + private _remove(request: PairingRequest) { + this._bySecret.delete(request.secret); + this._byCode.delete(request.details.code); + this.records.delete(request.details); + } + + /** Remove requests the host stopped polling for or that waited too long */ + prune() { + const now = Date.now(); + const timeoutMs = this._controller.config.get("controller.host_pairing_timeout") * 1000; + for (const request of this._bySecret.values()) { + const timedOut = request.state === "pending" && timeoutMs > 0 + && now - request.details.createdAtMs > timeoutMs; + if (!timedOut && now - request.lastPollMs <= pollTimeoutMs) { + continue; + } + if (request.state === "approved") { + logger.warn( + `Approved host ${request.result.name} (${request.result.hostId}) was never picked up ` + + "by the host, revoke it on the hosts page if it is not needed" + ); + } + this._remove(request); + } + } +} diff --git a/packages/controller/src/InstanceManager.ts b/packages/controller/src/InstanceManager.ts index 4323d59a..572243c0 100644 --- a/packages/controller/src/InstanceManager.ts +++ b/packages/controller/src/InstanceManager.ts @@ -1,9 +1,14 @@ +import { isDeepStrictEqual } from "node:util"; import * as lib from "@clusterio/lib"; +import { logger } from "@clusterio/lib"; import type Controller from "./Controller.js"; import type HostConnection from "./HostConnection.js"; import InstanceRecord from "./InstanceRecord.js"; +type InheritedFields = lib.InstanceConfigFields["instance.inherited_fields"]; +type InheritableField = keyof lib.InstanceConfigFields & string; + export default class InstanceManager { private static readonly DefaultFactorioSettings = { tags: ["clusterio"], @@ -24,6 +29,9 @@ export default class InstanceManager { non_blocking_saving: false, } as const; + /** Non-zero while template values are being copied into inheriting instances */ + private _inheriting = 0; + constructor( public readonly records: lib.SubscribableDatastore, private readonly _controller: Controller, @@ -106,11 +114,271 @@ export default class InstanceManager { */ addInstanceHooks(instance: InstanceRecord): void { instance.config.on("fieldChanged", (field: string, curr: unknown, prev: unknown) => { + if (field === "instance.template_id") { + this._linkMatchingFields(instance); + } else if (!this._inheriting && instance.config.isInherited(field)) { + this._unlinkEditedField(instance, field, curr, prev); + } this.records.set(instance); this._notifyConfigFieldChanged(instance, field, curr, prev); + this._updateInheritors(instance, field, curr); }); } + /* ------------------------------------------------------------------------- */ + /* Inheritance */ + /* ------------------------------------------------------------------------- */ + + /** + * Get the instances that inherit directly from the given template. + * + * @param templateId - ID of the template. + * @returns Instances with `instance.template_id` set to templateId. + */ + inheritorsOf(templateId: number): InstanceRecord[] { + return [...this.records.values()].filter( + instance => instance.config.get("instance.template_id") === templateId + ); + } + + /** + * Check that new values for `instance.is_template` and `instance.template_id` are allowed. + * + * @param config - Current config of the instance. + * @param isTemplate - New value for `instance.is_template`. + * @param templateId - New value for `instance.template_id`. + * @throws {module:lib.ValidationError} if the template is not a template or would create a cycle. + * @throws {module:lib.ConflictError} if the instance is assigned or still has inheritors. + */ + checkInheritance(config: lib.InstanceConfig, isTemplate: boolean, templateId: number | null): void { + const instanceId = config.get("instance.id"); + if (isTemplate && config.get("instance.assigned_host") !== null) { + throw new lib.ConflictError("Instance must be unassigned before it can be made a template"); + } + if (!isTemplate && config.get("instance.is_template")) { + const count = this.inheritorsOf(instanceId).length; + if (count) { + throw new lib.ConflictError(`Instance is the template of ${count} other instance(s)`); + } + } + if (templateId === null) { + return; + } + const template = this.records.get(templateId); + if (!template) { + throw new lib.NotFoundError(`Instance with ID ${templateId} does not exist`); + } + if (!template.config.get("instance.is_template")) { + throw new lib.ValidationError(`Instance ${template.config.get("instance.name")} is not a template`); + } + const visited = new Set(); + for (let id: number | null = templateId; id !== null && !visited.has(id);) { + if (id === instanceId) { + throw new lib.ValidationError("Templates cannot inherit from themselves"); + } + visited.add(id); + id = this.records.get(id)?.config.get("instance.template_id") ?? null; + } + } + + /** + * Copy the inheritable values from the template set in `instance.template_id` + * into a config that is not yet part of the cluster and mark them inherited. + * + * @param config - Config of the instance to be created. + * @param own - Fields set by the creator, object fields keep their properties as overrides. + */ + applyTemplate(config: lib.InstanceConfig, own: string[] = []): void { + const template = this._templateOf(config); + if (!template) { + return; + } + const inherited: InheritedFields = {}; + for (const name of InstanceManager._inheritableFields()) { + const def = lib.InstanceConfig.fieldDefinitions[name]; + if (def.type === "object") { + inherited[name] = own.includes(name) ? Object.keys(config.get(name) as object ?? {}) : []; + } else if (!own.includes(name)) { + inherited[name] = true; + } + } + config.set("instance.inherited_fields", inherited); + config.update(InstanceManager._inheritedValues(config, template.config, Object.keys(inherited)), false); + } + + /** + * Make a field, or a property of an object field, take its value from the template again. + * + * @param instanceId - ID of the instance to update. + * @param field - Name of the field to inherit. + * @param prop - Property of an object field to inherit, inherits all properties if not given. + * @throws {module:lib.ValidationError} if the instance has no template or the field cannot be inherited. + */ + inheritField(instanceId: number, field: string, prop?: string): void { + const instance = this.getForRequest(instanceId); + if (!this._templateOf(instance.config)) { + throw new lib.ValidationError("Instance does not have a template"); + } + if (!lib.InstanceConfig.isInheritable(field)) { + throw new lib.ValidationError(`Field ${field} cannot be inherited`); + } + const name = field as InheritableField; + const inherited = { ...instance.config.get("instance.inherited_fields") }; + if (lib.InstanceConfig.fieldDefinitions[name].type !== "object") { + inherited[field] = true; + } else if (prop === undefined) { + inherited[field] = []; + } else { + const entry = inherited[field]; + const overrides = entry instanceof Array ? entry : Object.keys(instance.config.get(name) as object ?? {}); + inherited[field] = overrides.filter(p => p !== prop); + } + instance.config.set("instance.inherited_fields", inherited); + this._copyInheritedValues(instance, [field]); + } + + /** + * Stop inheriting the given field or properties, used when a value is explicitly set. + * + * @param instance - Instance the field was set on. + * @param field - Name of the field set. + * @param props - Properties set on an object field. + */ + overrideField(instance: InstanceRecord, field: string, props?: string[]): void { + const entry = instance.config.get("instance.inherited_fields")[field]; + if (!instance.config.isInherited(field)) { + return; + } + const inherited = { ...instance.config.get("instance.inherited_fields") }; + if (entry instanceof Array && props) { + inherited[field] = [...new Set([...entry, ...props])]; + } else { + delete inherited[field]; + } + instance.config.set("instance.inherited_fields", inherited); + } + + private _templateOf(config: lib.InstanceConfig) { + const templateId = config.get("instance.template_id"); + return templateId !== null ? this.records.get(templateId) : undefined; + } + + private static _inheritableFields() { + return Object.keys(lib.InstanceConfig.fieldDefinitions).filter( + name => lib.InstanceConfig.isInheritable(name) + ) as InheritableField[]; + } + + /** Default value of a field for the given config */ + private static _defaultValue(name: InheritableField, config: lib.InstanceConfig): unknown { + const def = lib.InstanceConfig.fieldDefinitions[name]; + if (name === "factorio.settings") { + return InstanceManager.DefaultFactorioSettings; + } + return typeof def.initialValue === "function" ? def.initialValue(config) : def.initialValue ?? null; + } + + /** Values the given inherited fields take from the template, with object overrides applied */ + private static _inheritedValues(config: lib.InstanceConfig, template: lib.InstanceConfig, fields: string[]) { + const inherited = config.get("instance.inherited_fields"); + const values: Record = {}; + for (const field of fields) { + const name = field as InheritableField; + const entry = inherited[field]; + if (!entry) { + continue; + } + const value = structuredClone(template.get(name)) as any; + if (entry instanceof Array) { + const own = config.get(name) as Record ?? {}; + for (const prop of entry) { + if (Object.hasOwn(own, prop)) { + value[prop] = structuredClone(own[prop]); + } + } + } + values[field] = value; + } + return values; + } + + /** Update the given inherited fields of a live instance from its template */ + private _copyInheritedValues(instance: InstanceRecord, fields: string[]): void { + const template = this._templateOf(instance.config); + if (!template) { + return; + } + const values = InstanceManager._inheritedValues(instance.config, template.config, fields); + this._inheriting += 1; + try { + instance.config.update(values, true); + } finally { + this._inheriting -= 1; + } + } + + /** Unlink a field, or the changed properties of an object field, edited on the instance */ + private _unlinkEditedField(instance: InstanceRecord, field: string, curr: unknown, prev: unknown): void { + const entry = instance.config.get("instance.inherited_fields")[field]; + if (!(entry instanceof Array)) { + this.overrideField(instance, field); + return; + } + const currObj = curr as Record ?? {}; + const prevObj = prev as Record ?? {}; + const changed = Object.keys(currObj).filter(p => !isDeepStrictEqual(currObj[p], prevObj[p])); + const removed = Object.keys(prevObj).filter(p => !Object.hasOwn(currObj, p)); + const overrides = [...new Set([...entry, ...changed])].filter(p => !removed.includes(p)); + const inherited = { ...instance.config.get("instance.inherited_fields"), [field]: overrides }; + instance.config.set("instance.inherited_fields", inherited); + if (removed.length) { + // Removed properties fall back to the template value + this._copyInheritedValues(instance, [field]); + } + } + + /** Recompute inherited fields after template_id changed, values equal to the template or default are inherited */ + private _linkMatchingFields(instance: InstanceRecord): void { + const template = this._templateOf(instance.config); + const inherited: InheritedFields = {}; + if (template) { + for (const name of InstanceManager._inheritableFields()) { + const value = instance.config.get(name) as any; + const templateValue = template.config.get(name) as any; + const defaultValue = InstanceManager._defaultValue(name, instance.config) as any; + if (lib.InstanceConfig.fieldDefinitions[name].type === "object") { + inherited[name] = Object.keys(value ?? {}).filter(prop => !( + isDeepStrictEqual(value[prop], templateValue?.[prop]) + || defaultValue && isDeepStrictEqual(value[prop], defaultValue[prop]) + ) || name === "factorio.settings" && prop === "name"); + } else if ( + isDeepStrictEqual(value, templateValue) + || defaultValue !== undefined && isDeepStrictEqual(value, defaultValue) + ) { + inherited[name] = true; + } + } + } + instance.config.set("instance.inherited_fields", inherited); + this._copyInheritedValues(instance, Object.keys(inherited)); + } + + /** Copy a changed value from a template to the instances inheriting it */ + private _updateInheritors(template: InstanceRecord, field: string, value: unknown): void { + if (!lib.InstanceConfig.isInheritable(field)) { + return; + } + for (const instance of this.inheritorsOf(template.id)) { + if (!instance.config.isInherited(field)) { + continue; + } + this._copyInheritedValues(instance, [field]); + this._controller.instanceConfigUpdated(instance).catch(err => { + logger.error(`Failed to send config of instance ${instance.id} to its host:\n${err.stack}`); + }); + } + } + /* ------------------------------------------------------------------------- */ /* Lifecycle */ /* ------------------------------------------------------------------------- */ @@ -137,12 +405,23 @@ export default class InstanceManager { } const controllerName = this._controller.config.get("controller.name"); - instanceConfig.set("factorio.settings", { - name: `${controllerName} - ${instanceConfig.get("instance.name")}`, - description: `Clusterio instance for ${controllerName}`, - ...InstanceManager.DefaultFactorioSettings, - ...instanceConfig.get("factorio.settings"), - }); + const serverName = `${controllerName} - ${instanceConfig.get("instance.name")}`; + const settings = instanceConfig.get("factorio.settings"); + if (!instanceConfig.isInherited("factorio.settings")) { + instanceConfig.set("factorio.settings", { + name: serverName, + description: `Clusterio instance for ${controllerName}`, + ...InstanceManager.DefaultFactorioSettings, + ...settings, + }); + } else if (instanceConfig.isInherited("factorio.settings", "name")) { + // Each instance gets its own server name + instanceConfig.setProp("factorio.settings", "name", serverName); + const inherited = instanceConfig.get("instance.inherited_fields"); + instanceConfig.set("instance.inherited_fields", { + ...inherited, "factorio.settings": [...inherited["factorio.settings"] as string[], "name"], + }); + } const instance = new InstanceRecord(instanceConfig, "unassigned"); this.addInstanceHooks(instance); @@ -186,6 +465,9 @@ export default class InstanceManager { if (currentAssignedHost === hostId) { return; } + if (hostId !== null && instance.config.get("instance.is_template")) { + throw new lib.ValidationError("Templates cannot be assigned to a host"); + } let newHostConnection: HostConnection | undefined; if (hostId !== null) { @@ -252,6 +534,10 @@ export default class InstanceManager { async deleteInstance(instanceId: number): Promise { const instance = this.getForRequest(instanceId); const hostId = instance.config.get("instance.assigned_host"); + const inheritors = this.inheritorsOf(instanceId).length; + if (inheritors) { + throw new lib.ConflictError(`Instance is the template of ${inheritors} other instance(s)`); + } if (hostId !== null) { await this._controller.sendTo( diff --git a/packages/controller/src/InstanceRecord.ts b/packages/controller/src/InstanceRecord.ts index 9ad0db58..f1c6a410 100644 --- a/packages/controller/src/InstanceRecord.ts +++ b/packages/controller/src/InstanceRecord.ts @@ -83,6 +83,9 @@ export default class InstanceRecord { this.startedAtMs, this.updatedAtMs, this.config.get("instance.exclude_from_start_all"), + this.config.get("instance.is_template"), + this.config.get("instance.template_id") ?? undefined, + this.config.get("factorio.mod_pack_id") ?? undefined, ); } diff --git a/packages/controller/src/UserManager.ts b/packages/controller/src/UserManager.ts index 9ef56d7c..c143ef82 100644 --- a/packages/controller/src/UserManager.ts +++ b/packages/controller/src/UserManager.ts @@ -40,8 +40,8 @@ export default class UserManager { } // We intentionally write the roles first because if it fails then the old user file will still contain them - await lib.safeOutputFile(rolesFilePath, JSON.stringify(combinedJson.roles)); - await lib.safeOutputFile(usersFilePath, JSON.stringify(combinedJson.users)); + await lib.atomicOverwriteFile(rolesFilePath, JSON.stringify(combinedJson.roles)); + await lib.atomicOverwriteFile(usersFilePath, JSON.stringify(combinedJson.users)); } catch (err: any) { if (err.code !== "ENOENT") { throw err; @@ -151,11 +151,34 @@ export default class UserManager { * @returns JWT access token for the user. */ signUserToken(user: UserRecord): string { - return jwt.sign( - { aud: "user", user: user.id }, - // auth secret is never null after startup - Buffer.from(this._controllerConfig.get("controller.auth_secret")!, "base64") - ); + return jwt.sign({ aud: "user", user: user.id }, this._authSecret); + } + + /** + * Check a user token + * + * @param token - User token to check. + * @returns the user the token was issued to. + * @throws if the token is invalid, its user does not exist or it was issued before tokenValidAfter. + */ + verifyUserToken(token: string): User { + const payload = jwt.verify(token, this._authSecret, { audience: "user" }); + if (typeof payload === "string") { + throw new Error("unexpected JsonWebToken type"); + } + const user = this.getByNameMutable(payload.user); + if (!user) { + throw new Error("invalid user"); + } + if (!payload.iat || payload.iat < user.tokenValidAfter) { + throw new Error("invalid token"); + } + return user; + } + + private get _authSecret() { + // auth secret is never null after startup + return Buffer.from(this._controllerConfig.get("controller.auth_secret")!, "base64"); } /** Clear all player stats for specific instance */ diff --git a/packages/controller/src/WsServer.ts b/packages/controller/src/WsServer.ts index ce4bb2b3..7fcc85b0 100644 --- a/packages/controller/src/WsServer.ts +++ b/packages/controller/src/WsServer.ts @@ -252,21 +252,9 @@ ${err.stack}` } try { - // migrate: allow pre-rename tokens issued to hosts before alpha-14 - const tokenPayload = jwt.verify(data.token, this.controller.authSecret, { audience: ["host", "slave"] }); - if (typeof tokenPayload === "string") { - throw new Error("unexpected JsonWebToken type"); - } - - // migrate: allow pre-rename tokens issued to hosts before alpha-14 - if ((tokenPayload.host !== undefined ? tokenPayload.host : tokenPayload.slave) !== data.id) { + if (this.controller.hosts.verifyHostToken(data.token).id !== data.id) { throw new Error("missmatched host id"); } - - let host = this.controller.hosts.get(data.id); - if (!tokenPayload.iat || tokenPayload.iat < (host?.tokenValidAfter ?? 0)) { - throw new Error("invalid token"); - } } catch (err: any) { logger.verbose(`WsServer | authentication failed for ${this.remoteAddr(req)}`); wsRejectedConnectionsCounter.inc(); @@ -303,6 +291,13 @@ ${err.stack}` ); } + // The host may have been revoked while waiting for the old connection to close. + if (!this.controller.hosts.has(data.id)) { + wsRejectedConnectionsCounter.inc(); + socket.close(lib.ConnectionClosed.Unauthorized, "Authentication failed: host was revoked"); + return; + } + let [connector, sessionToken] = this.createSession(new lib.Address(lib.Address.host, data.id)); // Handle close before HostConnection does. This avoids a host @@ -325,18 +320,7 @@ ${err.stack}` async registerControl(data: lib.RegisterControlData, socket: WebSocket, req: IncomingMessage) { let user; try { - const tokenPayload = jwt.verify(data.token, this.controller.authSecret, { audience: "user" }); - if (typeof tokenPayload === "string") { - throw new Error("unexpected JsonWebToken type"); - } - - user = this.controller.users.getByNameMutable(tokenPayload.user); - if (!user) { - throw new Error("invalid user"); - } - if ((tokenPayload.iat || 0) < user.tokenValidAfter) { - throw new Error("invalid token"); - } + user = this.controller.users.verifyUserToken(data.token); user.checkPermission("core.control.connect"); } catch (err: any) { diff --git a/packages/controller/src/routes.ts b/packages/controller/src/routes.ts index 767451ca..8d7518a7 100644 --- a/packages/controller/src/routes.ts +++ b/packages/controller/src/routes.ts @@ -1,11 +1,11 @@ -import type { Application, Request, Response } from "express"; +import express, { type Application, type Request, type Response } from "express"; import Controller from "./Controller.js"; +import HostPairingManager, { HostPairingError } from "./HostPairingManager.js"; import busboy from "busboy"; import crypto from "crypto"; import events from "events"; import fs from "node:fs/promises"; -import jwt from "jsonwebtoken"; import path from "path"; import nodeStream from "stream"; import util from "util"; @@ -188,17 +188,7 @@ function validateHostToken(req: Request, res: Response, next: any) { } try { - const tokenPayload = jwt.verify(token, req.app.locals.controller.authSecret, { audience: "host" }); - if (typeof tokenPayload === "string") { - throw new Error("unexpected JsonWebToken type"); - } - let host = req.app.locals.controller.hosts.get(tokenPayload.host); - if (!host) { - throw new Error("invalid host"); - } - if (!tokenPayload.iat || tokenPayload.iat < (host.tokenValidAfter ?? 0)) { - throw new Error("invalid token"); - } + req.app.locals.controller.hosts.verifyHostToken(token); } catch (err) { res.sendStatus(401); return; @@ -215,19 +205,7 @@ function validateUserToken(req: Request, res: Response, next: any) { } try { - const tokenPayload = jwt.verify(token, req.app.locals.controller.authSecret, { audience: "user" }); - if (typeof tokenPayload === "string") { - throw new Error("unexpected JsonWebToken type"); - } - let user = req.app.locals.controller.users.getByName(tokenPayload.user); - if (!user) { - throw new Error("invalid user"); - } - if (!tokenPayload.iat || tokenPayload.iat < user.tokenValidAfter) { - throw new Error("invalid token"); - } - res.locals.user = user; - + res.locals.user = req.app.locals.controller.users.verifyUserToken(token); } catch (err) { res.sendStatus(401); return; @@ -236,6 +214,105 @@ function validateUserToken(req: Request, res: Response, next: any) { next(); } +// Responds with the status of a pairing error, returns false for other errors. +function sendHostPairingError(res: Response, err: unknown) { + if (!(err instanceof HostPairingError)) { + return false; + } + if (err.retryAfter !== undefined) { + res.set("Retry-After", String(err.retryAfter)); + } + res.status(err.status).json({ error: err.message }); + return true; +} + +// Checks recovery mode and the request id for the pairing endpoints, returns false if responded to. +function checkHostPairingRequest(req: Request, res: Response, needsRequestId: boolean) { + if (req.app.locals.controller.recoveryMode) { + res.status(503).json({ error: "Controller is in recovery mode" }); + return false; + } + if (needsRequestId && typeof req.body?.requestId !== "string") { + res.status(400).json({ error: "requestId is required" }); + return false; + } + return true; +} + +// Request from a host for a host to join the cluster. +function createHostPairing(req: Request, res: Response) { + if (!checkHostPairingRequest(req, res, false)) { + return; + } + const controller = req.app.locals.controller; + const remoteAddress = controller.wsServer.remoteAddr(req); + try { + const name = HostPairingManager.validateName(req.body?.name); + const version = typeof req.body?.version === "string" ? req.body.version.slice(0, 64) : ""; + + // A user allowed to approve hosts can skip the wait by passing their token. + const token = getAccessToken(req); + if (token !== undefined) { + let user; + try { + user = controller.users.verifyUserToken(token); + } catch (err) { + res.status(401).json({ error: "Invalid user token" }); + return; + } + try { + user.checkPermission("core.host.approve"); + } catch (err) { + logger.audit( + `User ${user.name} tried to approve host ${name} from ${remoteAddress} without permission` + ); + res.status(403).json({ error: `User ${user.name} is not allowed to approve hosts` }); + return; + } + const host = controller.hosts.createHost(name); + logger.audit( + `User ${user.name} approved host ${host.name} (${host.id}) from ${remoteAddress} with their token` + ); + res.status(200).json({ hostId: host.id, token: controller.hosts.signHostToken(host.id), name: host.name }); + return; + } + + res.status(202).json(controller.hostPairing.create(name, version, remoteAddress)); + } catch (err) { + if (!sendHostPairingError(res, err)) { + throw err; + } + } +} + +// Poll from a host for the result of its request. +function pollHostPairing(req: Request, res: Response) { + if (!checkHostPairingRequest(req, res, true)) { + return; + } + try { + const result = req.app.locals.controller.hostPairing.poll(req.body.requestId); + if (result) { + res.status(200).json(result); + } else { + res.status(202).json({ status: "pending" }); + } + } catch (err) { + if (!sendHostPairingError(res, err)) { + throw err; + } + } +} + +// Cancel from a host that stopped waiting. +function cancelHostPairing(req: Request, res: Response) { + if (!checkHostPairingRequest(req, res, true)) { + return; + } + req.app.locals.controller.hostPairing.cancel(req.body.requestId); + res.sendStatus(204); +} + // Handle an uploaded export package. async function uploadExport(req: Request, res: Response) { if (req.get("Content-Type") !== "application/zip") { @@ -290,7 +367,7 @@ async function uploadExport(req: Request, res: Response) { let { name, ext } = path.posix.parse(filePath); let hash = await lib.hashStream(await zip.openStream(file)); assets[name] = `${name}.${hash}${ext}`; - await lib.safeOutputFile(path.join("static", `${name}.${hash}${ext}`), content); + await lib.atomicOverwriteFile(path.join("static", `${name}.${hash}${ext}`), content); } modPack.exportManifest = new lib.ExportManifest(assets, new Date().toISOString()); @@ -300,6 +377,30 @@ async function uploadExport(req: Request, res: Response) { res.sendStatus(200); } +// Reached when no static file matched, drops exports whose files were removed +export function missingExportAsset(req: Request, res: Response, next: any) { + const file = req.path.slice(1); + if (!["GET", "HEAD"].includes(req.method) || !file) { + next(); + return; + } + const modPacks = res.app.locals.controller.modPacks; + const affected = [...modPacks.valuesMutable()].filter( + modPack => modPack.exportManifest && Object.values(modPack.exportManifest.assets).includes(file) + ); + if (!affected.length) { + next(); + return; + } + for (const modPack of affected) { + Controller.dropExport(modPack, `${file} was removed from disk`); + } + modPacks.setMany(affected); + res.status(404).type("text/plain").send( + `Export data file ${file} is missing, run export-data on an instance to regenerate it` + ); +} + type ProxyStreamEvents = { "error": [ err: any ], "close": [], @@ -716,6 +817,18 @@ export function addRouteHandlers(app: Application) { ); app.get("/api/plugins", getPlugins); app.get("/api/cluster-name", getClusterName); + // Set before parsing so errors from the body parser and token check are not cached either. + const noStore = (req: Request, res: Response, next: any) => { + res.set("Cache-Control", "no-store"); + next(); + }; + const pairingJson = express.json({ limit: "4kb" }); + app.post("/api/host-pairing", noStore, pairingJson, createHostPairing); + app.post("/api/host-pairing/poll", noStore, pairingJson, pollHostPairing); + app.post("/api/host-pairing/cancel", noStore, pairingJson, cancelHostPairing); + app.get("/api/host-pairing/check", noStore, validateHostToken, (req: Request, res: Response) => { + res.json({ valid: true }); + }); app.put("/api/upload-export", validateHostToken, (req:Request, res:Response, next:any) => uploadExport(req, res).catch(next) diff --git a/packages/create/README.md b/packages/create/README.md index 2483f03b..38cc24cd 100644 --- a/packages/create/README.md +++ b/packages/create/README.md @@ -4,3 +4,113 @@ Installer for Clusterio. Install the latest [Node.js LTS release](https://nodejs.org/en/download) before running the installer. See [the Clusterio installation guide](https://github.com/clusterio/clusterio#installation) for platform-specific instructions. + +Run the installer in a new empty directory: + + npm init "@clusterio" + +It asks which components to install and how to set them up. +Every question can be answered with an option instead, pass options to the installer after `--`: + + npm init "@clusterio" -- --mode host --host-name my-host --controller-url https://example.com/ + +The installer runs without prompts when all the questions for the mode are answered with options. + + +## Modes + +- `standalone`: controller and host on this computer. The host is approved like any other host the first time it starts. +- `controller`: controller only. +- `host`: host only, joins the cluster of an existing controller, see [Setting up a host](#setting-up-a-host). +- `ctl`: the clusterioctl command line interface only. +- `plugins`: plugins only, for adding plugins to an existing installation. +- `plugin-template`: files for writing a new plugin. + + +## Options + +| Option | Modes | Description | +| --- | --- | --- | +| `--mode ` | all | Operating mode to install. | +| `--admin ` | controller | Name of the admin account to create. | +| `--http-port ` | controller | Port the controller web interface listens on, defaults to 8080. | +| `--host-name ` | host | Name to request for the host, defaults to the name of the computer. | +| `--controller-url ` | host, ctl | URL of the controller, the same as for its web interface. | +| `--controller-token ` | ctl | Authentication token saved for clusterioctl. | +| `--public-address
` | host | DNS name or IP address players connect to this computer with. | +| `--factorio-dir ` | host | Path to the Factorio installation. | +| `--self-signed-cert ` | host | Certificate to trust for a controller using a self-signed certificate. It is added to the run scripts. | +| `--remote-npm`, `--no-remote-npm` | controller, host | Allow or deny remote updates, plugin updates and plugin installs from the web interface. | +| `--plugins ` | all | Plugins to install, pass `--plugins` without packages to install none. | +| `--plugin-template `, `--plugin-name ` | plugin-template | Templates to use and name of the new plugin. | +| `--log-level ` | all | Log level to print, defaults to info. | +| `--allow-install-as-root` | all | Linux only, allow installing as root (not recommended). | +| `--migrate-rename` | | Migrate an installation from before the slave/master rename. | + +Options for the `controller` and `host` modes also work in the `standalone` mode, except for `--controller-url` as the host connects to the controller on the same computer. +`--host-name` defaults to `local` in the `standalone` mode. + + +## Setting up a host + +A new host has to be approved before it can join the cluster: + +1. Run the installer with the host mode on the computer for the host. + It asks for a name for the host, the controller URL, the public address, the Factorio installation, whether to allow remote updates and which plugins to install. + +2. Start the host with `run-host.cmd`, `run-host.sh` or the systemd service in the `systemd` folder. + The first time it starts it prints a code and waits for the host to be approved: + + Waiting for approval of "my-host" with code ABC-DEF, open this link to approve it: + https://example.com/hosts?approve=ABC-DEF + Or run: npx clusterioctl host approve ABC-DEF + +3. Open the link to approve the request in the web interface, where its name can be changed first. + It can also be approved under Add host on the Hosts page, or with `npx clusterioctl host approve ABC-DEF`. + Only approve a request if its code matches the one shown by the host. + Approving requires the `core.host.approve` permission. + +4. The host saves `host.id`, `host.name` and `host.controller_token` to `config-host.json` and starts up. + Later starts connect to the cluster straight away. + +The host keeps waiting until the request is approved, also if the controller is restarted or can't be reached for a while. +Press Ctrl+C to stop waiting. +If the request is rejected the host exits with code 8, which the run scripts do not restart on. + +Start the host with `npx clusteriohost run --user-token ` and the token of a user that has the `core.host.approve` permission to approve the host without waiting. +The token is only used for approving the host and is not saved. + +If the controller uses a self-signed certificate pass it with `--self-signed-cert `, see [setting up TLS](https://github.com/clusterio/clusterio/blob/master/docs/setting-up-tls.md#creating-and-using-a-self-signed-certificate). +The installer adds it to the run scripts. + +When a host is revoked in the web interface or with `npx clusterioctl host revoke ` its token stops working and a running host shuts down. +Starting it again requests to join the cluster again, and the host gets a new id once approved. + +To move a host to another controller, change `host.controller_url` with `npx clusteriohost config set host.controller_url `. +The new controller does not accept the token of the host, so the host requests to join it the next time it starts. + + +## Docker + +To run a host in a container install it when building the image with all answers given as options. +The host requests to join the cluster the first time the container starts. + +```dockerfile +FROM node:22 +# Install the Factorio headless server to /opt/factorio here +RUN mkdir /clusterio && chown node:node /clusterio +USER node +WORKDIR /clusterio +RUN npm init "@clusterio" -- --mode host --host-name my-host --controller-url https://example.com/ \ + --public-address factorio.example.com --factorio-dir /opt/factorio --no-remote-npm --plugins +VOLUME /clusterio +CMD exec ./node_modules/.bin/clusteriohost run ${USER_TOKEN:+--user-token "$USER_TOKEN"} +``` + + docker run -d --name my-host -v my-host:/clusterio -p 34100-34199:34100-34199/udp my-host-image + docker logs my-host + +- The volume holds `config-host.json`, without it every new container requests to join as a new host. + Docker copies the installation from the image into a new empty volume, later image updates do not change the installation in an existing volume. +- The code to approve is printed to the container log, or set `USER_TOKEN` to approve the host without waiting. +- Stop the container after revoking its host, otherwise a restart requests to join again. diff --git a/packages/create/create.js b/packages/create/create.js index 342fa6a6..d5d91505 100755 --- a/packages/create/create.js +++ b/packages/create/create.js @@ -1,10 +1,14 @@ #!/usr/bin/env node +import checkbox from "@inquirer/checkbox"; +import confirm from "@inquirer/confirm"; +import input from "@inquirer/input"; +import select from "@inquirer/select"; import child_process from "node:child_process"; import fs from "node:fs/promises"; -import inquirer from "inquirer"; import os from "node:os"; import path from "node:path"; +import readline from "node:readline"; import stream from "node:stream"; import util from "node:util"; import yargs from "yargs"; @@ -16,15 +20,13 @@ const scriptExt = process.platform === "win32" ? ".cmd" : ""; import { escapeArg } from "./escape_arg.js"; // I hate this, there is a bug with rl.close on windows that was meant to have been fixed in Node14.4 -// See nodejs/node#21771 and nodejs/node#30701 for the apparent fix that was applied -// One option is to not call rl.close: SBoudrias/Inquirer.js#767 -// But this comes with its own issues: SBoudrias/Inquirer.js#899 +// See nodejs/node#21771, nodejs/node#30701 and nodejs/node#31762 // The solution below was adapted from aws-amplify/amplify-cli#12347 if (process.platform === "win32") { - const _inquirer_close = inquirer.ui.Prompt.prototype.close; - inquirer.ui.Prompt.prototype.close = function() { - this.rl.terminal = false; - _inquirer_close.call(this); + const close = readline.Interface.prototype.close; + readline.Interface.prototype.close = function() { + this.terminal = false; + close.call(this); }; } @@ -102,7 +104,7 @@ async function pathExists(filePath) { return true; } -async function safeOutputFile(file, data, options={}) { +async function atomicOverwriteFile(file, data, options={}) { let { dir, name, ext } = path.parse(file); let temporary = path.join(dir, `${name}.tmp${ext}`); if (dir) { @@ -161,21 +163,48 @@ async function execCtl(args) { return await execFile(path.join("node_modules", ".bin", `clusterioctl${scriptExt}`), args); } -function validateHostToken(token) { - let parts = token.split("."); - if (parts.length !== 3) { - throw new InstallError("Invalid token"); - } +// Same characters as the controller refuses in host names. +const hostNameControlCharacters = /[\p{Cc}\u202a-\u202e\u2066-\u2069]/u; - let parsed; +function validateHostName(value) { + if (!value || !value.trim()) { + return "Host name may not be empty"; + } + if (value.trim().length > 100) { + return "Host name may be at most 100 characters"; + } + if (hostNameControlCharacters.test(value)) { + return "Host name may not contain control characters"; + } + return true; +} + +function validateControllerUrl(value) { + let url; try { - parsed = JSON.parse(Buffer.from(parts[1], "base64")); + url = new URL(value); } catch (err) { - throw new InstallError("Invalid token"); + return "Controller URL must be a URL like https://example.com/"; } + if (!["http:", "https:"].includes(url.protocol)) { + return "Controller URL must start with http:// or https://"; + } + return true; +} - if (parsed.aud !== "host" || !Number.isInteger(parsed.host)) { - throw new InstallError("Invalid token"); +// The host requires the controller URL to end with a slash. +function normaliseControllerUrl(value) { + const url = new URL(value); + if (!url.pathname.endsWith("/")) { + url.pathname += "/"; + } + return url.href; +} + +// Remote updates, plugin updates and plugin installs are allowed or denied together. +async function setRemoteUpdates(exec, component, allow) { + for (let field of ["allow_remote_updates", "allow_plugin_updates", "allow_plugin_install"]) { + await exec(["config", "set", `${component}.${field}`, allow]); } } @@ -228,7 +257,7 @@ async function migrateRename(args) { async function migrateConfig(source, destination) { if (await pathExists(source) && !await pathExists(destination)) { - await safeOutputFile(destination, JSON.stringify( + await atomicOverwriteFile(destination, JSON.stringify( renameConfig(JSON.parse(await fs.readFile(source))), null, "\t" ), { mode: 0o600 }); logger.info(`Migrated ${source} to ${destination}`); @@ -240,7 +269,7 @@ async function migrateRename(args) { let instancesFile = path.join("database", "instances.json"); if (await pathExists(instancesFile)) { - await safeOutputFile(instancesFile, JSON.stringify( + await atomicOverwriteFile(instancesFile, JSON.stringify( JSON.parse(await fs.readFile(instancesFile)).map(renameConfig), null, "\t" )); logger.info(`Migrated ${instancesFile}`); @@ -252,7 +281,7 @@ async function migrateRename(args) { for (let role of users["roles"]) { role["permissions"] = role["permissions"].map(rename); } - await safeOutputFile(usersFile, JSON.stringify(users, null, "\t")); + await atomicOverwriteFile(usersFile, JSON.stringify(users, null, "\t")); logger.info(`Migrated ${usersFile}`); } @@ -280,7 +309,7 @@ async function migrateRename(args) { lines.push(inputLine); } } - safeOutputFile(outputFile, Buffer.concat(lines)); + atomicOverwriteFile(outputFile, Buffer.concat(lines)); } async function migrateLogsDir(inputLogs, outputLogs) { @@ -405,7 +434,7 @@ async function groupIdToName(gid) { async function writeScripts(mode, selfSignedCert) { if (["standalone", "controller"].includes(mode)) { if (process.platform === "win32") { - await safeOutputFile( + await atomicOverwriteFile( "run-controller.cmd", `\ @echo off @@ -418,7 +447,7 @@ goto restart ` ); } else { - await safeOutputFile( + await atomicOverwriteFile( "run-controller.sh", `\ #!/bin/bash @@ -430,7 +459,7 @@ done `, { mode: 0o755 }, ); - await safeOutputFile( + await atomicOverwriteFile( "systemd/clusteriocontroller.service", `\ [Unit] @@ -457,7 +486,7 @@ WantedBy=multi-user.target if (["standalone", "host"].includes(mode)) { if (process.platform === "win32") { let extraCaCertsLine = selfSignedCert ? `set "NODE_EXTRA_CA_CERTS=${selfSignedCert}"\n` : ""; - await safeOutputFile( + await atomicOverwriteFile( "run-host.cmd", `\ @echo off @@ -471,7 +500,7 @@ goto restart ); } else { let extraCaCertsLine = selfSignedCert ? `export "NODE_EXTRA_CA_CERTS=${selfSignedCert}"\n` : ""; - await safeOutputFile( + await atomicOverwriteFile( "run-host.sh", `\ #!/bin/bash @@ -484,7 +513,7 @@ done { mode: 0o755 }, ); extraCaCertsLine = selfSignedCert ? `Environment=NODE_EXTRA_CA_CERTS=${selfSignedCert}\n` : ""; - await safeOutputFile( + await atomicOverwriteFile( "systemd/clusteriohost.service", `\ [Unit] @@ -510,96 +539,87 @@ WantedBy=multi-user.target } // eslint-disable-next-line complexity -async function inquirerMissingArgs(args) { +async function promptMissingArgs(args) { let answers = {}; if (args.mode) { answers.mode = args.mode; } if (args["plugin-template"]) { answers.mode = "plugin-template"; } - answers = await inquirer.prompt([ - { - type: "list", - name: "mode", - message: "Operating mode to install", - default: "standalone", - choices: [ - { name: "Standalone (install both controller and host on this computer)", value: "standalone" }, - { name: "Controller only", value: "controller" }, - { name: "Host only", value: "host" }, - { name: "Ctl only", value: "ctl" }, - { name: "Plugins only", value: "plugins" }, - { name: "Plugin template", value: "plugin-template" }, - ], - }, - ], answers); + answers.mode ??= await select({ + message: "Operating mode to install", + default: "standalone", + choices: [ + { name: "Standalone (install both controller and host on this computer)", value: "standalone" }, + { name: "Controller only", value: "controller" }, + { name: "Host only", value: "host" }, + { name: "Ctl only", value: "ctl" }, + { name: "Plugins only", value: "plugins" }, + { name: "Plugin template", value: "plugin-template" }, + ], + }); if (["standalone", "controller"].includes(answers.mode)) { if (args.admin) { answers.admin = args.admin; } - answers = await inquirer.prompt([ - { - type: "input", - name: "admin", - message: "Admin account name", - validate: input => { - if (!input) { - return "May not be empty"; - } - return true; - }, + answers.admin ??= await input({ + message: "Admin account name", + validate: value => { + if (!value) { + return "May not be empty"; + } + return true; }, - ], answers); + }); if (args.httpPort) { answers.httpPort = args.httpPort; } - answers = await inquirer.prompt([ - { - type: "input", - name: "httpPort", - message: "HTTP port to listen on", - default: 8080, - validate: input => { - if (!input) { - return "May not be empty"; - } - if (!Number.isInteger(Number(input))) { - return "Must be a number"; - } - return true; - }, + answers.httpPort ??= await input({ + message: "HTTP port to listen on", + default: "8080", + validate: value => { + if (!value) { + return "May not be empty"; + } + if (!Number.isInteger(Number(value))) { + return "Must be a number"; + } + return true; }, - ], answers); + }); + } + + if (answers.mode === "standalone") { + answers.hostName = args.hostName ?? "local"; + const result = validateHostName(answers.hostName); + if (result !== true) { + throw new InstallError(result); + } } if (answers.mode === "host") { if (args.hostName) { answers.hostName = args.hostName; } - answers = await inquirer.prompt([ - { - type: "input", - name: "hostName", - message: "Name of host", - }, - ], answers); + if (args.controllerUrl) { answers.controllerUrl = args.controllerUrl; } + answers.hostName ??= await input({ + message: "Name of host", + default: os.hostname(), + validate: validateHostName, + }); + answers.controllerUrl ??= await input({ + message: "Controller URL", + validate: validateControllerUrl, + }); + + // The prompts do not validate answers given as arguments + for (let result of [validateHostName(answers.hostName), validateControllerUrl(answers.controllerUrl)]) { + if (result !== true) { + throw new InstallError(result); + } + } + answers.controllerUrl = normaliseControllerUrl(answers.controllerUrl); } - if (["host", "ctl"].includes(answers.mode)) { + if (answers.mode === "ctl") { if (args.controllerUrl) { answers.controllerUrl = args.controllerUrl; } - answers = await inquirer.prompt([ - { - type: "input", - name: "controllerUrl", - message: "Controller URL", - }, - ], answers); + answers.controllerUrl ??= await input({ message: "Controller URL" }); if (args.controllerToken) { answers.controllerToken = args.controllerToken; } - answers = await inquirer.prompt([ - { - type: "input", - name: "controllerToken", - message: "Controller authentication Token", - }, - ], answers); - } - - if (answers.mode === "host") { - validateHostToken(answers.controllerToken); + answers.controllerToken ??= await input({ message: "Controller authentication Token" }); } if (["standalone", "host"].includes(answers.mode)) { @@ -612,14 +632,10 @@ async function inquirerMissingArgs(args) { myIp = await result.text(); } catch (err) { /* ignore */ } } - answers = await inquirer.prompt([ - { - type: "input", - name: "publicAddress", - message: "Public DNS/IP address of this server", - default: myIp, - }, - ], answers); + answers.publicAddress ??= await input({ + message: "Public DNS/IP address of this server", + default: myIp, + }); if (args.factorioDir) { answers.factorioDir = args.factorioDir; } let locations = factorioLocations[process.platform] || []; @@ -630,28 +646,17 @@ async function inquirerMissingArgs(args) { } } - answers = await inquirer.prompt([ - { - type: "list", - name: "factorioDir", - message: "Path to Factorio installation", - choices: [ - ...foundLocations.map(location => ({ name: `${location} (auto detected)`, value: location })), - { name: "Use local factorio directory, you must copy an installation to it", value: "factorio" }, - { name: "Provide path manually", value: null }, - ], - }, - ], answers); + answers.factorioDir ??= await select({ + message: "Path to Factorio installation", + choices: [ + ...foundLocations.map(location => ({ name: `${location} (auto detected)`, value: location })), + { name: "Use local factorio directory, you must copy an installation to it", value: "factorio" }, + { name: "Provide path manually", value: null }, + ], + }); if (answers.factorioDir === null) { - answers = await inquirer.prompt([ - { - type: "input", - name: "factorioDir", - message: "Path to Factorio installation", - askAnswered: true, - }, - ], answers); + answers.factorioDir = await input({ message: "Path to Factorio installation" }); } else if (answers.factorioDir === "factorio") { await fs.mkdir("factorio", { recursive: true }); } @@ -659,14 +664,10 @@ async function inquirerMissingArgs(args) { if (["standalone", "controller", "host"].includes(answers.mode)) { if (args.hasOwnProperty("remoteNpm")) { answers.remoteNpm = args.remoteNpm; } - answers = await inquirer.prompt([ - { - type: "confirm", - name: "remoteNpm", - message: "Allow remote updates via npm?", - default: true, - }, - ], answers); + answers.remoteNpm ??= await confirm({ + message: "Allow remote updates and plugin installs from the web interface?", + default: true, + }); } if (answers.mode === "plugin-template") { @@ -677,29 +678,23 @@ async function inquirerMissingArgs(args) { answers.pluginName = args["plugin-name"]; } answers.plugins = []; - answers = await inquirer.prompt([ - { - type: "checkbox", - name: "pluginTemplate", - message: "Plugin templates to use", - choices: [ - { name: "Controller", value: "controller" }, - { name: "Host", value: "host" }, - { name: "Instance", value: "instance" }, - { name: "Lua Module", value: "module" }, - { name: "Command Line", value: "ctl" }, - { name: "Web UI", value: "web" }, - { name: "No Typescript", value: "js" }, - { name: "No Config", value: "no_config" }, - ], - }, - { - type: "input", - name: "pluginName", - message: "Name of your new plugin", - default: path.basename(path.resolve()), - }, - ], answers); + answers.pluginTemplate ??= await checkbox({ + message: "Plugin templates to use", + choices: [ + { name: "Controller", value: "controller" }, + { name: "Host", value: "host" }, + { name: "Instance", value: "instance" }, + { name: "Lua Module", value: "module" }, + { name: "Command Line", value: "ctl" }, + { name: "Web UI", value: "web" }, + { name: "No Typescript", value: "js" }, + { name: "No Config", value: "no_config" }, + ], + }); + answers.pluginName ??= await input({ + message: "Name of your new plugin", + default: path.basename(path.resolve()), + }); } if (dev) { @@ -707,15 +702,11 @@ async function inquirerMissingArgs(args) { } else if (args.plugins) { answers.plugins = args.plugins; } - answers = await inquirer.prompt([ - { - type: "checkbox", - name: "plugins", - message: "Plugins to install", - choices: availablePlugins, - pageSize: 20, - }, - ], answers); + answers.plugins ??= await checkbox({ + message: "Plugins to install", + choices: availablePlugins, + pageSize: 20, + }); return answers; } @@ -743,13 +734,13 @@ async function main() { nargs: 1, describe: "HTTP port to listen on [standalone/controller]", type: "number", }) .option("host-name", { - nargs: 1, describe: "Host name [host]", type: "string", + nargs: 1, describe: "Host name [standalone/host]", type: "string", }) .option("controller-url", { nargs: 1, describe: "Controller URL [host/ctl]", type: "string", }) .option("controller-token", { - nargs: 1, describe: "Controller authentication token [host/ctl]", type: "string", + nargs: 1, describe: "Controller authentication token [ctl]", type: "string", }) .option("public-address", { nargs: 1, describe: "DNS/IP Address to connect to this server [standalone/host]", type: "string", @@ -761,7 +752,8 @@ async function main() { nargs: 1, describe: "Path to self-signed certificate of the controller [standalone/host]", type: "string", }) .option("remote-npm", { - nargs: 0, description: "Allow remote updates via npm [standalone/controller/host]", type: "boolean", + nargs: 0, type: "boolean", description: + "Allow remote updates and plugin installs from the web interface [standalone/controller/host]", }) .option("plugins", { array: true, describe: "Plugins to install", type: "string", @@ -798,7 +790,7 @@ async function main() { return; } - let answers = await inquirerMissingArgs(args); + let answers = await promptMissingArgs(args); logger.verbose(JSON.stringify(answers)); if (answers.pluginTemplate) { @@ -816,44 +808,28 @@ async function main() { await execController(["config", "create"]); await execController(["bootstrap", "create-admin", answers.admin]); await execController(["config", "set", "controller.http_port", answers.httpPort]); - await execController(["config", "set", "controller.allow_remote_updates", answers.remoteNpm]); - await execController(["config", "set", "controller.allow_plugin_updates", answers.remoteNpm]); + await setRemoteUpdates(execController, "controller", answers.remoteNpm); let result = await execController(["bootstrap", "generate-user-token", answers.admin]); adminToken = result.stdout.split("\n").slice(-2)[0]; } - if (answers.mode === "standalone") { + if (["standalone", "host"].includes(answers.mode)) { logger.info("Setting up host"); await execHost(["config", "create"]); - await execHost(["config", "set", "host.name", "local"]); - - let result = await execHost(["config", "show", "host.id"]); - let hostId = Number.parseInt(result.stdout.split("\n").slice(-2)[0], 10); - - result = await execController(["bootstrap", "generate-host-token", hostId]); - let hostToken = result.stdout.split("\n").slice(-2)[0]; - - // Default to localhost on correct port for host in standalone mode - await execHost(["config", "set", "host.controller_url", `http://localhost:${answers.httpPort}/`]); - await execHost(["config", "set", "host.controller_token", hostToken]); - await execHost(["config", "set", "host.public_address", answers.publicAddress]); - await execHost(["config", "set", "host.factorio_directory", answers.factorioDir]); - await execHost(["config", "set", "host.allow_remote_updates", answers.remoteNpm]); - await execHost(["config", "set", "host.allow_plugin_updates", answers.remoteNpm]); } - if (answers.mode === "host") { - logger.info("Setting up host"); - let hostId = JSON.parse(Buffer.from(answers.controllerToken.split(".")[1], "base64")).host; - await execHost(["config", "create"]); - await execHost(["config", "set", "host.id", hostId]); + if (answers.mode === "standalone") { + // Default to localhost on correct port for host in standalone mode + answers.controllerUrl = `http://localhost:${answers.httpPort}/`; + } + + if (["standalone", "host"].includes(answers.mode)) { + // The host requests to join the cluster when it is started. await execHost(["config", "set", "host.name", answers.hostName]); await execHost(["config", "set", "host.controller_url", answers.controllerUrl]); - await execHost(["config", "set", "host.controller_token", answers.controllerToken]); await execHost(["config", "set", "host.public_address", answers.publicAddress]); await execHost(["config", "set", "host.factorio_directory", answers.factorioDir]); - await execHost(["config", "set", "host.allow_remote_updates", answers.remoteNpm]); - await execHost(["config", "set", "host.allow_plugin_updates", answers.remoteNpm]); + await setRemoteUpdates(execHost, "host", answers.remoteNpm); } if (!dev && ["standalone", "controller", "host"].includes(answers.mode)) { @@ -878,7 +854,10 @@ async function main() { if (import.meta.main) { main().catch(err => { process.exitCode = 1; - if (err instanceof InstallError) { + if (err.name === "ExitPromptError") { + // Ctrl+C at a prompt + process.exitCode = 130; + } else if (err instanceof InstallError) { logger.error(err.message); } else { logger.fatal(` diff --git a/packages/create/package.json b/packages/create/package.json index ba34a393..e76b220b 100644 --- a/packages/create/package.json +++ b/packages/create/package.json @@ -32,8 +32,11 @@ }, "dependencies": { + "@inquirer/checkbox": "^5.2.8", + "@inquirer/confirm": "^6.3.5", + "@inquirer/input": "^5.1.9", + "@inquirer/select": "^5.2.8", "chalk": "catalog:", - "inquirer": "^8.2.7", "yargs": "catalog:" } } diff --git a/packages/ctl/src/commands_host.ts b/packages/ctl/src/commands_host.ts index 91bd83c5..041a81a8 100644 --- a/packages/ctl/src/commands_host.ts +++ b/packages/ctl/src/commands_host.ts @@ -5,7 +5,6 @@ import os from "os"; import child_process from "child_process"; import * as lib from "@clusterio/lib"; -import { logger } from "@clusterio/lib"; import type { Ctl } from "../ctl.js"; import { print } from "./command_ops.js"; import { serializedConfigToString, getEditor, configToKeyVal } from "./config_ops.js"; @@ -51,62 +50,78 @@ hostCommands.add(new lib.Command({ }, })); +/** Format a duration in milliseconds as a short age like "1m 5s" */ +function formatAge(ms: number) { + const seconds = Math.max(0, Math.floor(ms / 1000)); + if (seconds < 60) { + return `${seconds}s`; + } + if (seconds < 3600) { + return `${Math.floor(seconds / 60)}m ${seconds % 60}s`; + } + return `${Math.floor(seconds / 3600)}h ${Math.floor(seconds / 60) % 60}m`; +} + +/** Strip case and separators the same way the controller does when matching pairing codes */ +function plainCode(code: string) { + return code.toUpperCase().replace(/[^0-9A-Z]/g, ""); +} + hostCommands.add(new lib.Command({ - definition: ["generate-token", "Generate token for a host", (yargs) => { - yargs.option("id", { type: "number", nargs: 1, describe: "Host id" }); - }], - handler: async function(args: { id?: number }, ctl: Ctl) { - let hostId = typeof args.id === "number" ? args.id : undefined; - let response = await ctl.send(new lib.HostGenerateTokenRequest(hostId)); - print(response); + definition: ["pending", "List host installers waiting for approval"], + handler: async function(args: object, ctl: Ctl) { + let requests = await ctl.send(new lib.HostPairingListRequest()); + if (!requests.length) { + print("No pending host requests"); + return; + } + let now = Date.now(); + print(asTable(requests.map(request => ({ + code: request.code, + name: request.name, + address: request.remoteAddress, + age: formatAge(now - request.createdAtMs), + })))); }, })); hostCommands.add(new lib.Command({ - definition: ["revoke-token ", "Revoke all tokens for a host", (yargs) => { - yargs.positional("host", { describe: "Host to revoke tokens for", type: "string" }); + definition: ["approve ", "Approve a host installer waiting for approval", (yargs) => { + yargs.positional("code", { describe: "Code shown by the installer", type: "string" }); + yargs.option("name", { + type: "string", nargs: 1, describe: "Name to give the host instead of the one it asked for", + }); + }], + handler: async function(args: { code: string, name?: string }, ctl: Ctl) { + let name = args.name?.trim(); + if (name === undefined) { + let requests = await ctl.send(new lib.HostPairingListRequest()); + name = requests.find(request => plainCode(request.code) === plainCode(args.code))?.name; + } + let hostId = await ctl.send(new lib.HostPairingApproveRequest(args.code, args.name)); + print(name ? `Approved host ${name} with id ${hostId}` : `Approved host with id ${hostId}`); + }, +})); + +hostCommands.add(new lib.Command({ + definition: ["reject ", "Reject a host installer waiting for approval", (yargs) => { + yargs.positional("code", { describe: "Code shown by the installer", type: "string" }); + }], + handler: async function(args: { code: string }, ctl: Ctl) { + await ctl.send(new lib.HostPairingRejectRequest(args.code)); + }, +})); + +hostCommands.add(new lib.Command({ + definition: ["revoke ", "Remove a host from the cluster and disconnect it", (yargs) => { + yargs.positional("host", { describe: "Host to revoke", type: "string" }); }], handler: async function(args: { host: string }, ctl: Ctl) { let hostId = await lib.resolveHost(ctl, args.host); - await ctl.send(new lib.HostRevokeTokensRequest(hostId)); + await ctl.send(new lib.HostRevokeRequest(hostId)); }, })); -hostCommands.add(new lib.Command({ - definition: ["create-config", "Create host config", (yargs) => { - yargs.option("id", { type: "number", nargs: 1, describe: "Host id" }); - yargs.option("name", { type: "string", nargs: 1, describe: "Host name" }); - yargs.option("generate-token", { - type: "boolean", nargs: 0, describe: "Generate authentication token", default: false, - }); - yargs.option("output", { - type: "string", nargs: 1, describe: "Path to output config (- for stdout)", default: "config-host.json", - }); - }], - handler: async function( - args: { id?: number, name?: string, generateToken: boolean, output: string }, - ctl: Ctl - ) { - let config = await ctl.send( - new lib.HostConfigCreateRequest(args.id, args.name, args.generateToken) - ); - - let content = JSON.stringify(config, null, "\t"); - if (args.output === "-") { - print(content); - } else { - logger.info(`Writing ${args.output}`); - try { - await fs.writeFile(args.output, content, { flag: "wx", mode: 0o600 }); - } catch (err: any) { - if (err.code === "EEXIST") { - throw new lib.CommandError(`File ${args.output} already exists`); - } - throw err; - } - } - }, -})); hostCommands.add(new lib.Command({ definition: ["update ", "Update the host", (yargs) => { yargs.positional("host", { describe: "Host to update", type: "string" }); diff --git a/packages/ctl/src/commands_instance.ts b/packages/ctl/src/commands_instance.ts index 63440875..ff57d1af 100644 --- a/packages/ctl/src/commands_instance.ts +++ b/packages/ctl/src/commands_instance.ts @@ -20,10 +20,14 @@ export const instanceCommands = new lib.CommandTree({ name: "instance", alias: ["i"], description: "Instance management", }); instanceCommands.add(new lib.Command({ - definition: [["list", "l"], "List instances known to the controller"], - handler: async function(args: object, ctl: Ctl) { + definition: [["list", "l"], "List instances known to the controller", (yargs) => { + yargs.options({ + "templates": { describe: "Include templates", nargs: 0, type: "boolean", default: false }, + }); + }], + handler: async function(args: { templates: boolean }, ctl: Ctl) { let list = await ctl.send(new lib.InstanceDetailsListRequest()); - print(asTable(list)); + print(asTable(list.filter(instance => args.templates || !instance.isTemplate))); }, })); @@ -34,18 +38,30 @@ instanceCommands.add(new lib.Command({ yargs.options({ "id": { type: "number", nargs: 1, describe: "Instance id" }, "from": { type: "number", nargs: 1, describe: "Clone config from instance id" }, + "template": { type: "string", nargs: 1, describe: "Template to inherit config from" }, + "as-template": { type: "boolean", nargs: 0, describe: "Create the instance as a template" }, }); }], - handler: async function(args: { name: string, id?: number, from?: number, }, ctl: Ctl) { + handler: async function( + args: { name: string, id?: number, from?: number, template?: string, asTemplate?: boolean }, + ctl: Ctl, + ) { let instanceConfig = new lib.InstanceConfig("control"); + let fields: (keyof lib.InstanceConfigFields)[] = ["instance.id", "instance.name"]; if (args.id !== undefined) { instanceConfig.set("instance.id", args.id); } instanceConfig.set("instance.name", args.name); + if (args.template !== undefined) { + instanceConfig.set("instance.template_id", await lib.resolveInstance(ctl, args.template)); + fields.push("instance.template_id"); + } + if (args.asTemplate) { + instanceConfig.set("instance.is_template", true); + fields.push("instance.is_template"); + } await ctl.send(new lib.InstanceCreateRequest( - instanceConfig.toRemote("controller", [ - "instance.id", "instance.name", - ]), + instanceConfig.toRemote("controller", fields), args.from )); }, @@ -61,13 +77,42 @@ instanceConfigCommands.add(new lib.Command({ handler: async function(args: { instance: string }, ctl: Ctl) { let instanceId = await lib.resolveInstance(ctl, args.instance); let config = await ctl.send(new lib.InstanceConfigGetRequest(instanceId)); + const inherited = config["instance.template_id"] !== null + ? config["instance.inherited_fields"] as Record ?? {} + : {}; for (let [name, value] of Object.entries(config)) { - print(`${name} ${JSON.stringify(value)}`); + if (name === "instance.inherited_fields") { + continue; + } + const entry = inherited[name]; + let note = ""; + if (entry instanceof Array && entry.length) { + note = ` (inherited except ${entry.join(", ")})`; + } else if (entry) { + note = " (inherited)"; + } + print(`${name} ${JSON.stringify(value)}${note}`); } }, })); +instanceConfigCommands.add(new lib.Command({ + definition: [ + "inherit [prop]", + "Make field or property in instance config use the value of its template", + (yargs) => { + yargs.positional("instance", { describe: "Instance to update config on", type: "string" }); + yargs.positional("field", { describe: "Field to inherit", type: "string" }); + yargs.positional("prop", { describe: "Property of object field to inherit", type: "string" }); + }, + ], + handler: async function(args: { instance: string, field: string, prop?: string }, ctl: Ctl) { + let instanceId = await lib.resolveInstance(ctl, args.instance); + await ctl.send(new lib.InstanceConfigInheritFieldRequest(instanceId, args.field, args.prop)); + }, +})); + instanceConfigCommands.add(new lib.Command({ definition: ["set [value]", "Set field in instance config", (yargs) => { yargs.positional("instance", { describe: "Instance to set config on", type: "string" }); @@ -170,8 +215,10 @@ instanceConfigCommands.add(new lib.Command({ await events.once(editorSpawn, "exit"); const data = await fs.readFile(tmpFile, "utf8"); const final = await configToKeyVal(data); + const original = await configToKeyVal(allConfigElements); for (let index in final) { - if (index in final) { + // Unchanged fields are skipped so they keep inheriting from the template + if (index in final && final[index] !== original[index]) { try { await ctl.send(new lib.InstanceConfigSetFieldRequest( instanceId, diff --git a/packages/host/README.md b/packages/host/README.md index d305077e..b719227b 100644 --- a/packages/host/README.md +++ b/packages/host/README.md @@ -132,6 +132,10 @@ Lists up all configuration entries with their currently configured values. ### `run` Runs the host. +A host that has not been approved prints a code and a link and waits for approval before it connects, see [Setting up a host](https://github.com/clusterio/clusterio/blob/master/packages/create/README.md#setting-up-a-host). +If the controller no longer accepts the token of the host when it starts, for example because the host was revoked, it asks to be approved again. +If its request is rejected it exits with code 8 and the run scripts created by the installer do not restart it. +A host that is revoked while it runs shuts down. ## See Also diff --git a/packages/host/host.ts b/packages/host/host.ts index e9af8f0b..a5302b70 100755 --- a/packages/host/host.ts +++ b/packages/host/host.ts @@ -27,6 +27,7 @@ import { ConsoleTransport, levels, logger } from "@clusterio/lib"; import type Host from "./src/Host.js"; import { createScenarioCommand, handleCreateScenarioCommand } from "./src/create_scenario.js"; +import { PairingError, ensurePaired } from "./src/pairing.js"; let host: Host | undefined; @@ -136,6 +137,10 @@ async function startHost() { type: "boolean", nargs: 0, default: false, describe: "Start the host in recovery mode with all plugins disabled and controller disconnected", }); + yargs.option("user-token", { + type: "string", nargs: 1, + describe: "Token of a user allowed to approve hosts, approves this host without waiting. Not saved", + }); }) .demandCommand(1, "You need to specify a command to run") .strict() @@ -214,19 +219,6 @@ async function startHost() { // and as the process name in ps/top on linux. process.title = "clusteriohost"; - // make sure we have the controller access token - if (hostConfig.get("host.controller_token") === "enter token here") { - logger.fatal("ERROR invalid config!"); - logger.fatal( - "Controller requires an access token for socket operations. As clusterio\n"+ - "hosts depends upon this, please set your token using the command npx\n"+ - "clusteriohost config set host.controller_token . You can generate an\n"+ - "auth token using npx clusterioctl generate-host-token." - ); - process.exitCode = 1; - return; - } - // make sure url ends with / if (!hostConfig.get("host.controller_url").endsWith("/")) { logger.fatal("ERROR invalid config!"); @@ -235,6 +227,37 @@ async function startHost() { return; } + if (!args.recovery) { + const abort = new AbortController(); + const onSignal = () => { abort.abort(); }; + process.on("SIGINT", onSignal); + process.on("SIGTERM", onSignal); + process.on("SIGHUP", onSignal); + try { + await ensurePaired(hostConfig, { + version: packageConfig.version, + userToken: args.userToken as string | undefined, + signal: abort.signal, + }); + } catch (err: any) { + if (abort.signal.aborted) { + logger.info("Stopped waiting for approval"); + return; + } + if (err instanceof PairingError) { + logger.fatal(`Unable to join the cluster: ${err.message}`); + // Exit code 8 stops the run scripts from restarting the host. + process.exitCode = err.status === 403 ? 8 : 1; + return; + } + throw err; + } finally { + process.off("SIGINT", onSignal); + process.off("SIGTERM", onSignal); + process.off("SIGHUP", onSignal); + } + } + // Loaded here as the server is not needed by the other commands const { default: Host } = await import("./src/Host.js"); let hostConnector = new HostConnector(hostConfig, pluginInfos); diff --git a/packages/host/index.ts b/packages/host/index.ts index c9d81c49..4420639d 100644 --- a/packages/host/index.ts +++ b/packages/host/index.ts @@ -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 { PairingError, checkHostToken, pairHost } from "./src/pairing.js"; if (import.meta.main) { bootstrap(); diff --git a/packages/host/src/Instance.ts b/packages/host/src/Instance.ts index 6cee6a7b..d6cfe046 100644 --- a/packages/host/src/Instance.ts +++ b/packages/host/src/Instance.ts @@ -11,7 +11,7 @@ const execAsync = util.promisify(exec); import * as lib from "@clusterio/lib"; import { FactorioServer, checkForUpdates } from "./server.js"; -import { loadModules, patch } from "./patch.js"; +import { loadModules, patch, unpatch } from "./patch.js"; import { exportData } from "./export.js"; import type Host from "./Host.js"; import { BaseInstancePlugin, InstanceHooks } from "./BaseInstancePlugin.js"; @@ -693,7 +693,7 @@ end`.replace(/\r?\n/g, " "); players: [...this.playerStats], player_autosave_slot: this._playerAutosaveSlot, }, null, "\t"); - await lib.safeOutputFile(this.path("instance-stats.json"), content); + await lib.atomicOverwriteFile(this.path("instance-stats.json"), content); } /** @@ -870,7 +870,7 @@ end`.replace(/\r?\n/g, " "); "_comment_warning": warning, ...await this.resolveServerSettings(this.config.get("factorio.settings"), includeCredentials), }; - await lib.safeOutputFile( + await lib.atomicOverwriteFile( this.server.writePath("server-settings.json"), JSON.stringify(serverSettings, null, "\t") ); @@ -996,7 +996,7 @@ end`.replace(/\r?\n/g, " "); if (this.config.get("factorio.sync_adminlist") !== "disabled") { this.logger.verbose("Writing server-adminlist.json"); - await lib.safeOutputFile( + await lib.atomicOverwriteFile( this.server.writePath("server-adminlist.json"), JSON.stringify([...this._host.adminlist], null, "\t") ); @@ -1004,7 +1004,7 @@ end`.replace(/\r?\n/g, " "); if (this.config.get("factorio.sync_banlist") !== "disabled") { this.logger.verbose("Writing server-banlist.json"); - await lib.safeOutputFile( + await lib.atomicOverwriteFile( this.server.writePath("server-banlist.json"), JSON.stringify([...this._host.banlist].map( ([username, reason]) => ({ username, reason }) @@ -1014,7 +1014,7 @@ end`.replace(/\r?\n/g, " "); if (this.config.get("factorio.sync_whitelist") !== "disabled") { this.logger.verbose("Writing server-whitelist.json"); - await lib.safeOutputFile( + await lib.atomicOverwriteFile( this.server.writePath("server-whitelist.json"), JSON.stringify([...this._host.whitelist], null, "\t") ); @@ -1082,6 +1082,9 @@ end`.replace(/\r?\n/g, " "); } if (!this.config.get("factorio.enable_save_patching")) { + if (await unpatch(this.path("saves", saveName))) { + this.logger.info("Removed Clusterio modules from save as save patching is disabled"); + } return saveName; } diff --git a/packages/host/src/export.ts b/packages/host/src/export.ts index 5df9d1df..e77ff46e 100644 --- a/packages/host/src/export.ts +++ b/packages/host/src/export.ts @@ -10,7 +10,7 @@ import yazl from "yazl"; import * as lib from "@clusterio/lib"; import * as libBuildMod from "@clusterio/lib/dist/node/build_mod.js"; -import type { FactorioServer } from "./server.js"; +import { findVersion, isHeadless, type FactorioServer } from "./server.js"; import { definesPrototypesFallback } from "./export_fallback.js"; interface SimpleIconSpecification { @@ -95,6 +95,16 @@ async function loadZip(server: FactorioServer, modVersions: Map, return modZip; } +/** Where icon files are read from during an export. */ +interface ExportFiles { + /** Mod zips opened during the export, closed when it ends. */ + zipCache: ZipCache; + /** Data dir of a full install to fall back to for builtin mod files. */ + graphicsDataDir?: string; + /** Why no full install was found for a headless server. */ + graphicsError?: string; +} + function closeZipCache(zipCache: ZipCache) { for (const { zip } of zipCache.values()) { zip.close(); @@ -107,7 +117,7 @@ function closeZipCache(zipCache: ZipCache) { * * @param server - The server to load the file from. * @param modVersions - Mapping of mod to version used. - * @param zipCache - Mod zips opened by this export. + * @param files - Where to read files from. * @param modPath - Factorio style path to the file to load. * @returns The content of the file or null if not found. * @internal @@ -115,7 +125,7 @@ function closeZipCache(zipCache: ZipCache) { async function loadFile( server: FactorioServer, modVersions: Map, - zipCache: ZipCache, + files: ExportFiles, modPath: string, ) { let match = /^__([^\/]+)__\/(.*)$/.exec(modPath); @@ -128,19 +138,25 @@ async function loadFile( const builtinModNames = ["core", ...lib.ModPack.getBuiltinModNames(server.version!)]; if (builtinModNames.includes(mod)) { - try { - return await fs.readFile(server.dataPath(mod, filePath)); - } catch (err: any) { - if (err.code === "ENOENT") { - return null; - } - throw err; + const dataDirs = [server.dataPath()]; + if (files.graphicsDataDir) { + dataDirs.push(files.graphicsDataDir); } + for (const dataDir of dataDirs) { + try { + return await fs.readFile(path.join(dataDir, mod, filePath)); + } catch (err: any) { + if (err.code !== "ENOENT") { + throw err; + } + } + } + return null; } let modZip; try { - modZip = await loadZip(server, modVersions, zipCache, mod); + modZip = await loadZip(server, modVersions, files.zipCache, mod); } catch (err: any) { if (err.code === "ENOENT") { return null; @@ -158,7 +174,7 @@ type IconCache = Map; async function loadIcon( server: FactorioServer, modVersions: Map, - zipCache: ZipCache, + files: ExportFiles, iconPath: string, iconSize: number, iconMipmaps: number, @@ -166,7 +182,7 @@ async function loadIcon( ) { let icon = iconCache.get(iconPath); if (icon === undefined) { - let fileContent = await loadFile(server, modVersions, zipCache, iconPath); + let fileContent = await loadFile(server, modVersions, files, iconPath); if (fileContent) { icon = await Jimp.fromBuffer(fileContent) as Image; icon.crop({ x: 0, y: 0, w: iconSize, h: iconSize }); @@ -182,12 +198,12 @@ async function loadIcon( async function loadSimpleIcon( server: FactorioServer, modVersions: Map, - zipCache: ZipCache, + files: ExportFiles, item: SimpleIconSpecification, size: number, iconCache: IconCache, ): Promise { - let icon = await loadIcon(server, modVersions, zipCache, item.icon, item.icon_size ?? 64, 0, iconCache); + let icon = await loadIcon(server, modVersions, files, item.icon, item.icon_size ?? 64, 0, iconCache); if (icon) { let iconScale = size / (item.icon_size ?? 64); if (iconScale !== 1) { @@ -201,11 +217,11 @@ async function loadSimpleIcon( async function loadLayeredIcon( server: FactorioServer, modVersions: Map, - zipCache: ZipCache, + files: ExportFiles, item: LayeredIconSpecification, size: number, iconCache: IconCache, -): Promise { +): Promise { let baseLayerSize = (item.icons[0].icon_size || item.icon_size) ?? 64; let icon = new Jimp({ width: size, height: size }); @@ -218,11 +234,12 @@ async function loadLayeredIcon( for (let layer of item.icons) { let layerSize = (layer.icon_size || item.icon_size) ?? 64; let iconLayer = await loadIcon( - server, modVersions, zipCache, layer.icon, layerSize, layer.icon_mipmaps || 0, iconCache, + server, modVersions, files, layer.icon, layerSize, layer.icon_mipmaps || 0, iconCache, ); + // A partial icon would be wrong, skip it like a missing simple icon if (!iconLayer) { - continue; + return null; } iconLayer = iconLayer.clone(); @@ -337,7 +354,7 @@ async function growSheet(state: SheetState) { async function exportIcon( server: FactorioServer, modVersions: Map, - zipCache: ZipCache, + files: ExportFiles, state: SheetState, prototype: PrototypeWithIcon, ) { @@ -348,9 +365,11 @@ async function exportIcon( if (prototype.icons) { icon = await loadLayeredIcon( - server, modVersions, zipCache, prototype, SHEET_ICON_SIZE, state.iconCache, + server, modVersions, files, prototype, SHEET_ICON_SIZE, state.iconCache, ); - iconPos = state.pos; + if (icon) { + iconPos = state.pos; + } iconPath = prototype.icons[0].icon; } else if (prototype.icon) { @@ -358,7 +377,7 @@ async function exportIcon( iconPath = prototype.icon; if (iconPos === undefined) { icon = await loadSimpleIcon( - server, modVersions, zipCache, prototype, SHEET_ICON_SIZE, state.iconCache, + server, modVersions, files, prototype, SHEET_ICON_SIZE, state.iconCache, ); if (icon) { iconPos = state.pos; @@ -394,7 +413,7 @@ async function exportIcon( * * @param server - The server to load icons from. * @param modVersions - Mapping of mod name to version. - * @param zipCache - Mod zips opened by this export. + * @param files - Where to read icon files from. * @param prototypes - Array of prototypes with icon to export for this base type. * @param baseName - name of base type (used in metadata). * @param state - Shared spritesheet state (mutated in place). @@ -404,7 +423,7 @@ async function exportIcon( async function exportIcons( server: FactorioServer, modVersions: Map, - zipCache: ZipCache, + files: ExportFiles, prototypes: PrototypeWithIcon[], baseName: string, state: SheetState, @@ -413,7 +432,13 @@ async function exportIcons( state.metadata[baseName] ??= metadata; let count = 0; for (let prototype of prototypes) { - const icon = await exportIcon(server, modVersions, zipCache, state, prototype); + let icon: lib.ExportMetadataEntry["icon"]; + try { + icon = await exportIcon(server, modVersions, files, state, prototype); + } catch (err: any) { + // One broken icon should not stop the rest of the export + server._logger.warn(`Skipping icon of ${prototype.type} ${prototype.name}: ${err.message}`); + } if (icon) { count += 1; } @@ -484,6 +509,7 @@ async function exportLocale( modZip = await loadZip(server, modVersions, zipCache, mod); } catch (err: any) { if (err.code === "ENOENT") { + server._logger.warn(`Skipping locale of ${mod}, its mod zip was not found`); continue; } throw err; @@ -503,20 +529,67 @@ async function exportLocale( /** * Export locale, icons and metadata for the given factorio server * + * If the server runs the headless build, builtin mod graphics are read + * from a full install of the same major and minor version found next to + * it, if there is one. + * * @param server - The server to export the data from. * @returns zip file with exported data. */ export async function exportData(server: FactorioServer) { - const zipCache: ZipCache = new Map(); + const files: ExportFiles = { zipCache: new Map() }; + if (await isHeadless(server.dataPath())) { + const majorMinor = server.version!.replace(/\.\d+$/, "") as lib.MajorMinorVersion; + try { + [files.graphicsDataDir] = await findVersion(server._factorioDir, majorMinor, false); + } catch (err: any) { + // Without it the export still has everything but the base game icons + files.graphicsError = err.message; + } + } try { - return await buildExport(server, zipCache); + return await buildExport(server, files); } finally { // Free up the zip files loaded during the export. - closeZipCache(zipCache); + closeZipCache(files.zipCache); } } -async function buildExport(server: FactorioServer, zipCache: ZipCache) { +/** + * Warn if any builtin mod icon files could not be found + * + * @param server - The server the export ran on. + * @param files - Where icon files were read from. + * @param iconCache - Icons loaded by the export, null for missing files. + * @internal + */ +function checkMissingBuiltinIcons(server: FactorioServer, files: ExportFiles, iconCache: IconCache) { + const builtinModNames = ["core", ...lib.ModPack.getBuiltinModNames(server.version!)]; + let missing = 0; + for (const [iconPath, icon] of iconCache) { + const mod = /^__([^\/]+)__\//.exec(iconPath)?.[1]; + if (icon === null && mod && builtinModNames.includes(mod)) { + missing += 1; + } + } + if (!missing) { + return; + } + + const dirs = [server.dataPath(), files.graphicsDataDir].filter(Boolean).join(" or "); + let message = + `${missing} icon files of the base game were not found in ${dirs}, icons using them were not exported.`; + if (files.graphicsError !== undefined) { + const majorMinor = server.version!.replace(/\.\d+$/, ""); + message += + ` The headless build of Factorio has no graphics and no full install was found (${files.graphicsError}).` + + ` Add a full install of Factorio ${majorMinor} to host.factorio_directory to read them from there,` + + " or export the data on a host with a full install."; + } + server._logger.warn(message); +} + +async function buildExport(server: FactorioServer, files: ExportFiles) { await generateExportMod(server); let settings: lib.ExportSettings = {}; @@ -596,7 +669,7 @@ async function buildExport(server: FactorioServer, zipCache: ZipCache) { } } - let locale = await exportLocale(server, modVersions, zipCache, modOrder, "en"); + let locale = await exportLocale(server, modVersions, files.zipCache, modOrder, "en"); let zip = new yazl.ZipFile(); const addJson = (name: string, value: unknown) => zip.addBuffer(Buffer.from(JSON.stringify(value)), name); @@ -617,9 +690,10 @@ async function buildExport(server: FactorioServer, zipCache: ZipCache) { if (prototypesWithIcons.length === 0) { continue; } - const count = await exportIcons(server, modVersions, zipCache, prototypesWithIcons, baseName, state); + const count = await exportIcons(server, modVersions, files, prototypesWithIcons, baseName, state); server._logger.info(`Exported ${count} ${baseName} icons`); } + checkMissingBuiltinIcons(server, files, state.iconCache); // Crop sheet to actual used height and write single spritesheet + metadata. const usedRows = Math.ceil(state.pos / (SHEET_WIDTH / SHEET_ICON_SIZE)); @@ -635,6 +709,9 @@ async function buildExport(server: FactorioServer, zipCache: ZipCache) { // For testing only +export const _createSheetState = createSheetState; +export const _exportIcons = exportIcons; export const _exportLocale = exportLocale; export const _loadSimpleIcon = loadSimpleIcon; export const _loadLayeredIcon = loadLayeredIcon; +export const _checkMissingBuiltinIcons = checkMissingBuiltinIcons; diff --git a/packages/host/src/pairing.ts b/packages/host/src/pairing.ts new file mode 100644 index 00000000..ab1ceda5 --- /dev/null +++ b/packages/host/src/pairing.ts @@ -0,0 +1,305 @@ +import { setTimeout as sleep } from "node:timers/promises"; + +import * as lib from "@clusterio/lib"; +import { logger } from "@clusterio/lib"; + +/** Time to wait for a response from the controller */ +const requestTimeoutMs = 30e3; +/** Placeholder token of a host that has not been paired */ +const unpairedToken = "enter token here"; + +/** Error responded by the controller */ +export class PairingError extends Error { + constructor( + message: string, + /** HTTP status the controller responded with */ + public status?: number, + ) { + super(message); + this.name = "PairingError"; + } +} + +export interface PairingResult { + hostId: number; + token: string; + name: string; +} + +export interface PairHostOptions { + /** URL of the controller, ending with a slash */ + controllerUrl: string; + /** Name to request for the host */ + name: string; + /** Version of the host, shown with the request */ + version?: string; + /** Token of a user allowed to approve hosts, approves the host without waiting */ + token?: string; + /** Interval to poll for the result at */ + pollIntervalMs?: number; + /** Delay before trying again when the controller can't be reached or is busy */ + retryDelayMs?: number; + /** Called with the code to approve the request with each time a request is made */ + onPending?: (code: string) => void; + /** Called when the controller can't be reached or is busy and the request is retried */ + onRetry?: (err: Error, delayMs: number) => void; + /** Signal to cancel pairing with */ + signal?: AbortSignal; +} + +interface Response { + status: number; + headers: Headers; + json: any; +} + +async function request( + controllerUrl: string, + route: string, + options: { body?: object, token?: string, signal?: AbortSignal, timeoutMs?: number }, +): Promise { + const headers: Record = { "Accept": "application/json" }; + if (options.body) { + headers["Content-Type"] = "application/json"; + } + if (options.token) { + headers["Authorization"] = `Bearer ${options.token}`; + } + const timeout = AbortSignal.timeout(options.timeoutMs ?? requestTimeoutMs); + const response = await fetch(new URL(route, controllerUrl), { + method: options.body ? "POST" : "GET", + headers, + body: options.body ? JSON.stringify(options.body) : undefined, + signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout, + }); + let json; + try { + json = await response.json(); + } catch { + json = undefined; + } + return { status: response.status, headers: response.headers, json }; +} + +function responseError(response: Response) { + const message = typeof response.json?.error === "string" + ? response.json.error + : `Unexpected response from controller: ${response.status}`; + return new PairingError(message, response.status); +} + +function pairingResult(response: Response): PairingResult { + const { hostId, token, name } = response.json ?? {}; + if (!Number.isInteger(hostId) || typeof token !== "string" || typeof name !== "string") { + throw new PairingError("Invalid response from controller", response.status); + } + return { hostId, token, name }; +} + +/** Responses that are worth trying again later */ +function isTemporary(status: number) { + return status === 429 || status >= 500; +} + +function retryDelay(response: Response, defaultMs: number) { + const seconds = Number(response.headers.get("retry-after")); + return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : defaultMs; +} + +/** + * Poll a request until it is approved, rejected or no longer known by the controller + * + * @returns the result if approved, or null if the controller no longer knows the request. + */ +async function poll( + requestId: string, + options: Required> & PairHostOptions, +) { + let delayMs = options.pollIntervalMs; + while (true) { + await sleep(delayMs, undefined, { signal: options.signal }); + delayMs = options.pollIntervalMs; + let response; + try { + response = await request(options.controllerUrl, "api/host-pairing/poll", { + body: { requestId }, signal: options.signal, + }); + } catch (err: any) { + if (options.signal?.aborted) { + throw err; + } + // Keep polling through network errors, the request is made again if it expired meanwhile. + delayMs = options.retryDelayMs; + options.onRetry?.(err, delayMs); + continue; + } + if (response.status === 200) { + return pairingResult(response); + } + if (response.status === 404) { + return null; + } + if (isTemporary(response.status)) { + delayMs = retryDelay(response, options.retryDelayMs); + options.onRetry?.(responseError(response), delayMs); + continue; + } + if (response.status !== 202) { + throw responseError(response); + } + } +} + +/** + * Request to join the cluster and wait until the request is approved + * + * Waits through network errors and controller restarts, making a new request + * if the controller no longer knows the previous one. + * + * @param options - Pairing options. + * @returns id, token and approved name of the host. + * @throws {PairingError} if the controller refuses or rejects the request. + * @throws {DOMException} AbortError if the signal is aborted. + */ +export async function pairHost(options: PairHostOptions): Promise { + const opts = { pollIntervalMs: 2000, retryDelayMs: 10e3, version: "", ...options }; + let requestId: string | undefined; + try { + while (true) { + opts.signal?.throwIfAborted(); + let response; + try { + response = await request(opts.controllerUrl, "api/host-pairing", { + body: { name: opts.name, version: opts.version }, token: opts.token, signal: opts.signal, + }); + } catch (err: any) { + if (opts.signal?.aborted) { + throw err; + } + opts.onRetry?.(err, opts.retryDelayMs); + await sleep(opts.retryDelayMs, undefined, { signal: opts.signal }); + continue; + } + + if (response.status === 200) { + return pairingResult(response); + } + if (isTemporary(response.status)) { + const delayMs = retryDelay(response, opts.retryDelayMs); + opts.onRetry?.(responseError(response), delayMs); + await sleep(delayMs, undefined, { signal: opts.signal }); + continue; + } + if (response.status === 404) { + throw new PairingError("The controller must be updated to a version that supports host pairing", 404); + } + if (response.status !== 202) { + throw responseError(response); + } + if (typeof response.json?.requestId !== "string" || typeof response.json.code !== "string") { + throw new PairingError("Invalid response from controller", response.status); + } + + requestId = response.json.requestId as string; + opts.onPending?.(response.json.code); + const result = await poll(requestId, opts); + requestId = undefined; + if (result) { + return result; + } + } + + } catch (err) { + if (!opts.signal?.aborted) { + throw err; + } + if (requestId !== undefined) { + await request(opts.controllerUrl, "api/host-pairing/cancel", { + body: { requestId }, timeoutMs: 5e3, + }).catch(() => {}); + } + throw new DOMException("Pairing was cancelled", "AbortError"); + } +} + +/** + * Check if the controller accepts a host token + * + * @param controllerUrl - URL of the controller, ending with a slash. + * @param token - Host token to check. + * @param signal - Signal to cancel the check with. + * @returns true if the token is valid and its host is registered. + * @throws {PairingError} if the controller gives an unexpected response. + */ +export async function checkHostToken(controllerUrl: string, token: string, signal?: AbortSignal) { + const response = await request(controllerUrl, "api/host-pairing/check", { token, signal }); + if (response.status === 200) { + return true; + } + if (response.status === 401) { + return false; + } + throw responseError(response); +} + +/** + * Pair the host with the controller if it has not been paired, or the controller no longer accepts it + * + * Waits until the request is approved and saves the id, name and token of the host to its config. + * + * @param config - Config of the host. + * @param options - Pairing options. + * @throws {PairingError} if the controller refuses or rejects the request. + * @throws {DOMException} AbortError if the signal is aborted. + */ +export async function ensurePaired( + config: lib.HostConfig, + options: { version: string, userToken?: string, signal?: AbortSignal }, +) { + const controllerUrl = config.get("host.controller_url"); + const token = config.get("host.controller_token"); + if (token && token !== unpairedToken) { + let valid; + try { + valid = await checkHostToken(controllerUrl, token, options.signal); + } catch (err: any) { + if (options.signal?.aborted) { + throw err; + } + // Connecting reports the problem, or authenticates if the controller predates pairing. + logger.verbose(`Unable to check if the controller accepts this host: ${err.message}`); + return; + } + if (valid) { + return; + } + logger.warn("The controller no longer accepts this host, requesting to join again"); + } + + const name = config.get("host.name"); + logger.info(`Requesting to join the cluster at ${controllerUrl} as "${name}"`); + const result = await pairHost({ + controllerUrl, + name, + version: options.version, + token: options.userToken, + signal: options.signal, + onPending: code => { + const approveUrl = new URL(`hosts?approve=${code}`, controllerUrl).href; + // Logged as warnings for the systemd service, which only prints warnings and above. + // The link is logged on its own so terminals can make it clickable without it wrapping. + logger.warn(`Waiting for approval of "${name}" with code ${code}, open this link to approve it:`); + logger.warn(approveUrl); + logger.warn(`Or run: npx clusterioctl host approve ${code}`); + }, + onRetry: (err, delayMs) => { + logger.warn(`Requesting to join failed: ${err.message}, trying again in ${Math.ceil(delayMs / 1000)}s`); + }, + }); + + config.set("host.id", result.hostId); + config.set("host.name", result.name); + config.set("host.controller_token", result.token); + await config.save(); + logger.info(`Host approved as "${result.name}" with id ${result.hostId}`); +} diff --git a/packages/host/src/patch.ts b/packages/host/src/patch.ts index dbf3022d..81e0f300 100644 --- a/packages/host/src/patch.ts +++ b/packages/host/src/patch.ts @@ -227,6 +227,7 @@ export class PatchInfo { json.patch_number, lib.ModuleInfo.fromJSON(json.scenario), await Promise.all(json.modules.map(m => SaveModule.fromSave(m, zip, root))), + json.version, ); } } @@ -381,6 +382,72 @@ const knownScenarios: Record = { "3af547d2f4db3728b75ac5d1b3a4f47830dc48e7": new lib.ModuleInfo("freeplay", "2.0.29", [], ["scenario"]), }; +/** + * Names of the zip entries added by patching for the modules in the patch info + */ +function moduleEntries(zip: lib.ZipArchive, patchInfo: PatchInfo, root: string) { + const entries = new Set(); + if (patchInfo.version === 0) { + const modulesPath = path.posix.join(root, "modules/"); + for (const name of zip.entries.keys()) { + if (name.startsWith(modulesPath)) { + entries.add(name); + } + } + } else { + for (const module of patchInfo.modules) { + for (const filepath of module.files.keys()) { + entries.add(path.posix.join(root, filepath)); + } + } + } + return entries; +} + +/** + * Write a copy of the save next to it with entries removed and added + * + * Keeps the order of the entries in the original. + * + * @returns Path to the temporary file written. + */ +async function rewriteSave( + zip: lib.ZipArchive, savePath: string, removed: Set, added: Map +) { + added = new Map(added); + 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; + } + const contents = added.get(name); + if (contents !== undefined) { + await output.addBuffer(contents, name); + added.delete(name); + } else { + await output.addEntry(zip, entry); + } + } + 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; +} + /** * Patch a save with the given modules * @@ -412,6 +479,16 @@ export async function patch(savePath: string, modules: SaveModule[]) { ); } + // Unpatching put the original control.lua back in place of scenario.lua + const scenarioRequired = [...patchInfo.scenario.load, ...patchInfo.scenario.require].includes("scenario"); + if (scenarioRequired && !zip.file(rootPath("scenario.lua"))) { + const control = await zip.readFile(rootPath("control.lua")); + if (control === null) { + throw new Error("Unable to patch save, missing control.lua file."); + } + files.set("scenario.lua", control); + } + // No info file present, try to detect if it's a known compatible scenario. } else { const controlFile = zip.file(rootPath("control.lua")); @@ -432,22 +509,8 @@ export async function patch(savePath: string, modules: SaveModule[]) { patchInfo.patchNumber = patchInfo.patchNumber + 1; // Remove any existing modules from the save - const removed = new Set(); - if (patchInfo.version === 0) { - const modulesPath = rootPath("modules/"); - for (const name of zip.entries.keys()) { - if (name.startsWith(modulesPath)) { - removed.add(name); - } - } - } else { - for (const module of patchInfo.modules) { - for (const filepath of module.files.keys()) { - removed.add(rootPath(filepath)); - } - } - patchInfo.modules = []; - } + const removed = moduleEntries(zip, patchInfo, root); + patchInfo.modules = []; reorderDependencies(modules); @@ -463,45 +526,64 @@ export async function patch(savePath: string, modules: SaveModule[]) { files.set("control.lua", Buffer.from(generateLoader(patchInfo), "utf8")); files.set("clusterio.json", Buffer.from(JSON.stringify(patchInfo, null, "\t"), "utf8")); - // 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); - } - } - 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; - } + tempSavePath = await rewriteSave(zip, savePath, removed, added); } finally { zip.close(); } await fs.rename(tempSavePath, savePath); } +/** + * Remove the modules patched into a save + * + * Moves the original control.lua that patching kept as scenario.lua back + * and removes the module files. The patch info is kept with no modules so that + * the patch number keeps counting if the save is patched again. + * + * @param savePath - Path to the Factorio save to unpatch. + * @returns true if the save was changed. + */ +export async function unpatch(savePath: string) { + const zip = await lib.ZipArchive.fromFile(savePath); + let tempSavePath: string; + try { + const root = lib.findRoot(zip); + const rootPath = (relativePath: string) => path.posix.join(root, relativePath); + const patchInfoContent = await zip.readFile(rootPath("clusterio.json")); + if (patchInfoContent === null) { + return false; + } + const patchInfo = await PatchInfo.fromSave(JSON.parse(patchInfoContent.toString("utf8")), zip, root); + if (patchInfo.version > PatchInfo.currentVersion) { + throw new Error( + `Save patch version ${patchInfo.version} is newer than the patch version this ` + + `version of Clusterio can unpatch (${PatchInfo.currentVersion})` + ); + } + if (patchInfo.version !== 0 && !patchInfo.modules.length) { + return false; + } + + const removed = moduleEntries(zip, patchInfo, root); + patchInfo.modules = []; + const scenario = await zip.readFile(rootPath("scenario.lua")); + if (scenario !== null) { + removed.add(rootPath("scenario.lua")); + } + // Scenarios made for Clusterio have no scenario.lua, keep loading them without modules + const control = scenario ?? Buffer.from(generateLoader(patchInfo), "utf8"); + tempSavePath = await rewriteSave(zip, savePath, removed, new Map([ + [rootPath("control.lua"), control], + [rootPath("clusterio.json"), Buffer.from(JSON.stringify(patchInfo, null, "\t"), "utf8")], + ])); + } finally { + zip.close(); + } + await fs.rename(tempSavePath, savePath); + return true; +} + // For testing only export const _generateLoader = generateLoader; export const _reorderDependencies = reorderDependencies; diff --git a/packages/host/src/server.ts b/packages/host/src/server.ts index df3e85f7..1e1526a5 100644 --- a/packages/host/src/server.ts +++ b/packages/host/src/server.ts @@ -262,15 +262,33 @@ export async function checkForUpdates( * @param targetVersion - * Version to look for, supports the special value "latest" for the * latest version available. + * @param headless - + * Only consider headless installs if true, or only full installs if + * false. * @returns Array with path to data dir and version found. */ export async function findVersion( factorioDir: string, targetVersion: lib.TargetVersion, + headless?: boolean, ): Promise<[string, lib.FullVersion]> { + let kind = ""; + if (headless !== undefined) { + kind = headless ? "headless " : "full "; + } + const checkInstallType = async (dir: string) => ( + headless === undefined || await isHeadless(path.join(dir, "data")) === headless + ); + // Check if this is a direct installation dir const directVersion = await getFactorioVersion(factorioDir); if (directVersion !== null) { + if (!await checkInstallType(factorioDir)) { + throw new Error( + `Unable to find a ${kind}install of Factorio ${targetVersion}: ${factorioDir} is a direct ` + + `(single-version) install of the ${headless ? "full" : "headless"} build.` + ); + } if (targetVersion === "latest" || directVersion === targetVersion || directVersion.startsWith(targetVersion)) { return [path.join(factorioDir, "data"), directVersion]; } @@ -287,7 +305,7 @@ export async function findVersion( // Avoid any fancy directory detection in order to follow symlinks const fullPath = path.join(factorioDir, name); const version = await getFactorioVersion(fullPath); - if (version === null) { + if (version === null || !await checkInstallType(fullPath)) { continue; } @@ -299,7 +317,7 @@ export async function findVersion( } if (!versions.size) { - throw new Error(`Unable to find any Factorio install in ${factorioDir}`); + throw new Error(`Unable to find any ${kind}Factorio install in ${factorioDir}`); } if (lib.isPartialVersion(targetVersion)) { @@ -315,7 +333,26 @@ export async function findVersion( return [path.join(factorioDir, versions.get(latest)!, "data"), latest]; } - throw new Error(`Unable to find Factorio version ${targetVersion}`); + throw new Error(`Unable to find ${kind}Factorio version ${targetVersion}`); +} + +/** + * Check if a Factorio install is the headless build + * + * The headless build has no icons, which is what tells it apart. + * + * @param dataDir - Path to the data dir of the install. + */ +export async function isHeadless(dataDir: string) { + try { + await fs.access(path.join(dataDir, "base", "graphics", "icons")); + return false; + } catch (err: any) { + if (err.code === "ENOENT" || err.code === "ENOTDIR") { + return true; + } + throw err; + } } /** diff --git a/packages/lib/src/ModStore.ts b/packages/lib/src/ModStore.ts index 999157f3..3efb7a5b 100644 --- a/packages/lib/src/ModStore.ts +++ b/packages/lib/src/ModStore.ts @@ -3,7 +3,7 @@ import path from "path"; import events from "events"; import { Static } from "@sinclair/typebox"; import { logger } from "./logging.js"; -import { downloadFile, safeOutputFile } from "./file_ops.js"; +import { downloadFile, atomicOverwriteFile } from "./file_ops.js"; import { ModPortalReleaseSchema, ModPortalDetailsSchema, ModNameVersionPair } from "./data/messages_mod.js"; import { ModInfo, ModPack, MajorMinorVersion, ModVersionEquality, SourceVersion } from "./data/index.js"; @@ -148,7 +148,7 @@ export default class ModStore extends events.EventEmitter { if (files.size) { logger.info(`Loaded info for ${files.size} mods`); const content: ModInfoCache = [...files.values()].map(mod => mod.toJSON()); - await safeOutputFile(cacheFilename, JSON.stringify(content)); + await atomicOverwriteFile(cacheFilename, JSON.stringify(content)); } return new this(modsDirectory, files); diff --git a/packages/lib/src/config/classes.ts b/packages/lib/src/config/classes.ts index 19a7dbe0..c6871929 100644 --- a/packages/lib/src/config/classes.ts +++ b/packages/lib/src/config/classes.ts @@ -7,7 +7,7 @@ import isDeepStrictEqual from "#is_deep_strict_equal"; import { basicType } from "../helpers.js"; import * as libSchema from "../schema.js"; import { StringEnum } from "../data/composites.js"; -import { safeOutputFile } from "../file_ops.js"; +import { atomicOverwriteFile } from "../file_ops.js"; import * as validators from "./validators.js"; import { InvalidAccessError, InvalidFieldError, InvalidValueError } from "../errors.js"; import type { SyncHook } from "../SyncHook.js"; @@ -88,10 +88,11 @@ export interface FieldDefinition< optional?: Type extends null ? true : false; /** * Value this config field should take in a newly initialized config. - * This can also be a synchronous function returning the value to use. + * This can also be a synchronous function returning the value to use, + * it is called after the stored fields are loaded so that it can read them. * Promise results are not awaited. */ - initialValue?: unknown | (() => unknown); + initialValue?: unknown | ((config: Config) => unknown); /** * Array of all values that are acceptible. Useful for making * enumerated values. @@ -140,9 +141,6 @@ function defaultValue(def: FieldDefinition) { if (def.initialValue === undefined) { return null; } - if (typeof def.initialValue === "function") { - return def.initialValue(); - } return def.initialValue; } @@ -246,14 +244,12 @@ export class Config< } super(); + const defs = Object.entries(this.constructor.fieldDefinitions).filter( + ([name, def]) => this._checkAccess(name, def, location, ConfigAccess.read, false) + ); + // Function initial values are left undefined until the stored fields are loaded this.fields = Object.fromEntries( - Object.entries( - this.constructor.fieldDefinitions - ).filter( - ([name, def]) => this._checkAccess(name, def, location, ConfigAccess.read, false) - ).map( - ([name, def]) => [name, defaultValue(def)] - ) + defs.map(([name, def]) => [name, typeof def.initialValue === "function" ? undefined : defaultValue(def)]) ) as Fields; if (fields) { @@ -264,6 +260,12 @@ export class Config< this.update(migrated, false, location); } + for (const [name, def] of defs) { + if (this.fields[name as keyof Fields] === undefined) { + this.fields[name as keyof Fields] = (def.initialValue as (config: Config) => any)(this); + } + } + for (const [pluginName, version] of this.constructor.pluginVersions) { const name = `${pluginName}.version` as keyof Fields & string; if (name in this.fields && this.fields[name] !== version) { @@ -475,7 +477,7 @@ export class Config< if (!this.filepath) { throw new Error("Cannot save config which has no filepath"); } - await safeOutputFile(this.filepath, JSON.stringify(this, null, "\t"), { mode: 0o600 }); + await atomicOverwriteFile(this.filepath, JSON.stringify(this, null, "\t"), { mode: 0o600 }); this._dirty = false; } diff --git a/packages/lib/src/config/definitions.ts b/packages/lib/src/config/definitions.ts index 5d19897a..5fd9e64f 100644 --- a/packages/lib/src/config/definitions.ts +++ b/packages/lib/src/config/definitions.ts @@ -37,6 +37,8 @@ export interface ControllerConfigFields { "controller.default_mod_pack_id": number | null; "controller.default_role_id": number | null; "controller.autosave_interval": number; + "controller.host_pairing_timeout": number; + "controller.host_pairing_max_pending": number; "controller.mod_portal_cache_duration_minutes": number; "controller.mod_portal_page_size": number; "controller.allow_remote_updates": boolean; @@ -98,6 +100,20 @@ export class ControllerConfig extends classes.Config { initialValue: 60, validator: validators.greaterThanZero, }, + "controller.host_pairing_timeout": { + title: "Host Pairing Timeout", + description: "Time in seconds a host can wait for approval before it has to request again, 0 for no limit.", + type: "number", + initialValue: 3600, + validator: validators.greaterThanEqualZero, + }, + "controller.host_pairing_max_pending": { + title: "Host Pairing Max Pending", + description: "Maximum number of hosts that can wait for approval at the same time, 0 for no limit.", + type: "number", + initialValue: 50, + validator: validators.all(validators.integer, validators.greaterThanEqualZero), + }, "controller.http_port": { title: "HTTP Port", description: "Port to listen for HTTP connections on, set to null to not listen for HTTP connections.", @@ -472,6 +488,9 @@ export interface InstanceConfigFields { "instance.assigned_host": number | null; "instance.auto_start": boolean; "instance.exclude_from_start_all": boolean; + "instance.is_template": boolean; + "instance.template_id": number | null; + "instance.inherited_fields": Record; [key: `${string}.load_plugin`]: boolean; [key: `${string}.version`]: string; @@ -523,6 +542,38 @@ export class InstanceConfig extends classes.Config { return config; } + /** Fields that are never inherited from a template, ports clash on a shared host and secrets stay per instance */ + static uninheritableFields = [ + "instance.name", "instance.is_template", "instance.template_id", + "factorio.game_port", "factorio.rcon_port", "factorio.rcon_password", "factorio.lua_udp_port", + ]; + + /** True if the field can take its value from a template */ + static isInheritable(name: string) { + const def = this.fieldDefinitions[name as keyof InstanceConfigFields]; + return Boolean(def) + && !def.hidden + && (def.access ?? this.defaultAccess).includes("controller") + && !this.uninheritableFields.includes(name); + } + + /** + * True if the field, or the given property of an object field, takes its value from the template + * + * @param name - Name of field to check. + * @param prop - Property of an object field to check. + */ + isInherited(name: string, prop?: string) { + if (this.get("instance.template_id") === null) { + return false; + } + const entry = this.get("instance.inherited_fields")[name]; + if (entry instanceof Array) { + return prop === undefined || !entry.includes(prop); + } + return Boolean(entry); + } + static fieldDefinitions: classes.ConfigDefs = { "instance.name": { type: "string", @@ -550,6 +601,33 @@ export class InstanceConfig extends classes.Config { type: "boolean", initialValue: false, }, + "instance.is_template": { + description: + "Mark this instance as a template other instances can inherit config from. " + + "Templates cannot be assigned to a host or started.", + access: ["controller", "control"], + type: "boolean", + initialValue: false, + hidden: true, + }, + "instance.template_id": { + title: "Template", + description: "ID of the template to inherit config values from", + access: ["controller", "control"], + inputComponent: "instance_template", + type: "number", + optional: true, + // Checked by the controller + }, + "instance.inherited_fields": { + description: + "Fields whose value comes from the template, for object fields the properties set on this instance", + access: ["controller", "control"], + readonly: ["controller"], + type: "object", + initialValue: {}, + hidden: true, + }, "factorio.version": { description: "Version of the game to run. Use 'latest' for the latest installed version, a release " + @@ -800,36 +878,31 @@ export function addPluginFieldDefinitions( // The validator is dynamic based on the feature requirements of the plugin if (kind === "instanceConfigFields" && pluginInfo.features) { - fieldDef.dependsOn = []; - - const savePatching = pluginInfo.features.includes("SavePatching"); - if (savePatching) { - fieldDef.dependsOn.push("factorio.enable_save_patching"); + const requirements: [string, string][] = []; + if (pluginInfo.features.includes("SavePatching")) { + requirements.push(["factorio.enable_save_patching", "save patching"]); + } + if (pluginInfo.features.includes("ScriptCommands")) { + requirements.push(["factorio.enable_script_commands", "script commands"]); + } + if (pluginInfo.features.includes("LuaUdp")) { + requirements.push(["factorio.enable_lua_udp", "Lua UDP"]); } - const scriptCommands = pluginInfo.features.includes("ScriptCommands"); - if (scriptCommands) { - fieldDef.dependsOn.push("factorio.enable_script_commands"); - } - - const luaUdp = pluginInfo.features.includes("LuaUdp"); - if (luaUdp) { - fieldDef.dependsOn.push("factorio.enable_lua_udp"); - } - - if (scriptCommands || savePatching || luaUdp) { + if (requirements.length) { + fieldDef.dependsOn = requirements.map(([field]) => field); + // Default to not loaded when the instance does not meet the requirements + fieldDef.initialValue = (config: classes.Config) => requirements.every( + ([field]) => config.get(field) + ); fieldDef.validator = (enabled, config) => { if (!enabled) { return; } - if (savePatching && !config.get("factorio.enable_save_patching")) { - throw new Error(`Plugin ${pluginInfo.name} requires save patching`); - } - if (scriptCommands && !config.get("factorio.enable_script_commands")) { - throw new Error(`Plugin ${pluginInfo.name} requires script commands`); - } - if (luaUdp && !config.get("factorio.enable_lua_udp")) { - throw new Error(`Plugin ${pluginInfo.name} requires Lua UDP`); + for (const [field, description] of requirements) { + if (!config.get(field)) { + throw new Error(`Plugin ${pluginInfo.name} requires ${description}`); + } } }; } diff --git a/packages/lib/src/data/HostPairingDetails.ts b/packages/lib/src/data/HostPairingDetails.ts new file mode 100644 index 00000000..7ef079fc --- /dev/null +++ b/packages/lib/src/data/HostPairingDetails.ts @@ -0,0 +1,73 @@ +import { Type, Static } from "@sinclair/typebox"; + +/** + * A pending request from a host to join the cluster + * + * Requests are kept in memory on the controller only while the host + * waits for them to be approved or rejected. + */ +export default class HostPairingDetails { + constructor( + /** Code shown by the host, used to identify the request. */ + public code: string, + /** Name the host asked to have. */ + public name: string, + /** Address the request was made from. */ + public remoteAddress: string, + /** Version of the host that made the request. */ + public version = "", + /** Millisecond Unix timestamp the request was made at. */ + public createdAtMs = 0, + /** Millisecond Unix timestamp this entry was last updated at. */ + public updatedAtMs = 0, + /** True if this request is no longer pending. */ + public isDeleted = false, + ) { } + + get id() { + return this.code; + } + + static jsonSchema = Type.Object({ + "code": Type.String(), + "name": Type.String(), + "remoteAddress": Type.String(), + "version": Type.Optional(Type.String()), + "createdAtMs": Type.Optional(Type.Number()), + "updatedAtMs": Type.Optional(Type.Number()), + "isDeleted": Type.Optional(Type.Boolean()), + }); + + static fromJSON(json: Static) { + return new this( + json.code, + json.name, + json.remoteAddress, + json.version, + json.createdAtMs, + json.updatedAtMs, + json.isDeleted, + ); + } + + toJSON() { + const json: Static = { + code: this.code, + name: this.name, + remoteAddress: this.remoteAddress, + }; + if (this.version !== "") { + json.version = this.version; + } + if (this.createdAtMs !== 0) { + json.createdAtMs = this.createdAtMs; + } + if (this.updatedAtMs !== 0) { + json.updatedAtMs = this.updatedAtMs; + } + if (this.isDeleted) { + json.isDeleted = this.isDeleted; + } + return json; + } +} diff --git a/packages/lib/src/data/InstanceDetails.ts b/packages/lib/src/data/InstanceDetails.ts index adf0b9d8..1d5b05b4 100644 --- a/packages/lib/src/data/InstanceDetails.ts +++ b/packages/lib/src/data/InstanceDetails.ts @@ -41,7 +41,11 @@ export default class InstanceDetails { public startedAtMs = 0, /** Millisecond Unix timestamp this entry was last updated at */ public updatedAtMs = 0, - public excludeFromStartAll = false + public excludeFromStartAll = false, + public isTemplate = false, + public templateId?: number, + /** Value of factorio.mod_pack_id, undefined means the controller default is used */ + public modPackId?: number, ) {} get isDeleted() { @@ -61,6 +65,9 @@ export default class InstanceDetails { "startedAtMs": Type.Optional(Type.Number()), "updatedAtMs": Type.Optional(Type.Number()), "excludeFromStartAll": Type.Optional(Type.Boolean()), + "isTemplate": Type.Optional(Type.Boolean()), + "templateId": Type.Optional(Type.Integer()), + "modPackId": Type.Optional(Type.Integer()), }); static fromJSON(json: Static) { @@ -73,7 +80,10 @@ export default class InstanceDetails { json.factorioVersion, json.startedAtMs, json.updatedAtMs, - json.excludeFromStartAll + json.excludeFromStartAll, + json.isTemplate, + json.templateId, + json.modPackId, ); } @@ -102,6 +112,15 @@ export default class InstanceDetails { if (this.excludeFromStartAll !== false) { json.excludeFromStartAll = this.excludeFromStartAll; } + if (this.isTemplate !== false) { + json.isTemplate = this.isTemplate; + } + if (this.templateId !== undefined) { + json.templateId = this.templateId; + } + if (this.modPackId !== undefined) { + json.modPackId = this.modPackId; + } return json; } diff --git a/packages/lib/src/data/index.ts b/packages/lib/src/data/index.ts index 19ce86eb..41571354 100644 --- a/packages/lib/src/data/index.ts +++ b/packages/lib/src/data/index.ts @@ -15,6 +15,7 @@ export { default as Role } from "./Role.js"; export { default as Note } from "./Note.js"; export { default as InstanceDetails, InstanceStatus } from "./InstanceDetails.js"; export { default as HostDetails } from "./HostDetails.js"; +export { default as HostPairingDetails } from "./HostPairingDetails.js"; export { default as UserDetails } from "./UserDetails.js"; export type { IUser } from "./UserDetails.js"; export * from "./composites.js"; diff --git a/packages/lib/src/data/messages_controller.ts b/packages/lib/src/data/messages_controller.ts index 41f0ec1d..e7d534b8 100644 --- a/packages/lib/src/data/messages_controller.ts +++ b/packages/lib/src/data/messages_controller.ts @@ -1,9 +1,10 @@ import { Type, Static } from "@sinclair/typebox"; -import { JsonString, StringEnum, StringKey, plainJson } from "./composites.js"; +import { JsonNumber, StringEnum, StringKey, jsonArray, plainJson } from "./composites.js"; import { type LogEntry, levels } from "../logging.js"; -import { ControllerConfig, HostConfig } from "../config/index.js"; +import { ControllerConfig } from "../config/index.js"; import { ExternalFactorioVersionSchema, LatestReleasesSchema } from "../external/index.js"; import { PluginDetails } from "./messages_plugin.js"; +import HostPairingDetails from "./HostPairingDetails.js"; const LogEntrySchema = Type.Object({ "level": StringKey(levels), @@ -120,52 +121,81 @@ export class ControllerConfigSetPropRequest { } } -export class HostGenerateTokenRequest { - declare ["constructor"]: typeof HostGenerateTokenRequest; +export class HostPairingListRequest { + declare ["constructor"]: typeof HostPairingListRequest; static type = "request" as const; static src = "control" as const; static dst = "controller" as const; - static permission = "core.host.generate_token" as const; - - constructor( - public hostId?: number, - ) { } - - static jsonSchema = Type.Object({ - "hostId": Type.Optional(Type.Integer()), - }); - - static fromJSON(json: Static) { - return new this(json.hostId); - } - - static Response = JsonString; + static permission = "core.host.approve" as const; + static Response = jsonArray(HostPairingDetails); } -export class HostConfigCreateRequest { - declare ["constructor"]: typeof HostConfigCreateRequest; - static type = "request" as const; - static src = "control" as const; - static dst = "controller" as const; - static permission = "core.host.create_config" as const; +export class HostPairingUpdatesEvent { + declare ["constructor"]: typeof HostPairingUpdatesEvent; + static type = "event" as const; + static src = "controller" as const; + static dst = "control" as const; + static permission = "core.host.approve" as const; constructor( - public id: number | undefined, - public name: string | undefined, - public generateToken: boolean, + public updates: HostPairingDetails[], ) { } static jsonSchema = Type.Object({ - "id": Type.Optional(Type.Integer()), - "name": Type.Optional(Type.String()), - "generateToken": Type.Boolean(), + "updates": Type.Array(HostPairingDetails.jsonSchema), }); static fromJSON(json: Static) { - return new this(json.id, json.name, json.generateToken); + return new this(json.updates.map(update => HostPairingDetails.fromJSON(update))); + } +} + +export class HostPairingApproveRequest { + declare ["constructor"]: typeof HostPairingApproveRequest; + static type = "request" as const; + static src = "control" as const; + static dst = "controller" as const; + static permission = "core.host.approve" as const; + + constructor( + /** Code of the pending request, case and dashes are ignored. */ + public code: string, + /** Name to give the host instead of the one it asked for. */ + public name?: string, + ) { } + + static jsonSchema = Type.Object({ + "code": Type.String(), + "name": Type.Optional(Type.String()), + }); + + static fromJSON(json: Static) { + return new this(json.code, json.name); } - static Response = plainJson(HostConfig.jsonSchema); + /** Id of the host created. */ + static Response = JsonNumber; +} + +export class HostPairingRejectRequest { + declare ["constructor"]: typeof HostPairingRejectRequest; + static type = "request" as const; + static src = "control" as const; + static dst = "controller" as const; + static permission = "core.host.approve" as const; + + constructor( + /** Code of the pending request, case and dashes are ignored. */ + public code: string, + ) { } + + static jsonSchema = Type.Object({ + "code": Type.String(), + }); + + static fromJSON(json: Static) { + return new this(json.code); + } } export class GetFactorioCredentialsRequest { diff --git a/packages/lib/src/data/messages_host.ts b/packages/lib/src/data/messages_host.ts index 41e8e107..e89b236a 100644 --- a/packages/lib/src/data/messages_host.ts +++ b/packages/lib/src/data/messages_host.ts @@ -259,12 +259,12 @@ export class SyncUserListsEvent { } } -export class HostRevokeTokensRequest { - declare["constructor"]: typeof HostRevokeTokensRequest; +export class HostRevokeRequest { + declare ["constructor"]: typeof HostRevokeRequest; static type = "request" as const; static src = "control" as const; static dst = "controller" as const; - static permission = "core.host.revoke_token" as const; + static permission = "core.host.revoke" as const; constructor( public hostId: number, diff --git a/packages/lib/src/data/messages_instance.ts b/packages/lib/src/data/messages_instance.ts index d107632c..77500fab 100644 --- a/packages/lib/src/data/messages_instance.ts +++ b/packages/lib/src/data/messages_instance.ts @@ -176,6 +176,30 @@ export class InstanceConfigSetPropRequest { } } +export class InstanceConfigInheritFieldRequest { + declare ["constructor"]: typeof InstanceConfigInheritFieldRequest; + static type = "request" as const; + static src = "control" as const; + static dst = "controller" as const; + static permission = "core.instance.update_config" as const; + + constructor( + public instanceId: number, + public field: string, + public prop?: string, + ) { } + + static jsonSchema = Type.Object({ + "instanceId": Type.Integer(), + "field": Type.String(), + "prop": Type.Optional(Type.String()), + }); + + static fromJSON(json: Static) { + return new this(json.instanceId, json.field, json.prop); + } +} + export class InstanceAssignRequest { declare ["constructor"]: typeof InstanceAssignRequest; static type = "request" as const; diff --git a/packages/lib/src/database.ts b/packages/lib/src/database.ts index 1e94d298..2b833e5f 100644 --- a/packages/lib/src/database.ts +++ b/packages/lib/src/database.ts @@ -79,7 +79,7 @@ export async function loadJsonAsMap(filePath: string): Promise) { let obj = mapToObject(map); - await libFileOps.safeOutputFile(filePath, JSON.stringify(obj, null, "\t")); + await libFileOps.atomicOverwriteFile(filePath, JSON.stringify(obj, null, "\t")); } /** @@ -139,7 +139,7 @@ export async function loadJsonArrayAsMap(filePath: string): Promise) { - await libFileOps.safeOutputFile(filePath, JSON.stringify([...map.values()], null, "\t")); + await libFileOps.atomicOverwriteFile(filePath, JSON.stringify([...map.values()], null, "\t")); } diff --git a/packages/lib/src/datastore.ts b/packages/lib/src/datastore.ts index 212a7bbb..2b39d94b 100644 --- a/packages/lib/src/datastore.ts +++ b/packages/lib/src/datastore.ts @@ -2,7 +2,7 @@ import path from "path"; import fs from "node:fs/promises"; import { EventEmitter } from "events"; -import { safeOutputFile } from "./file_ops.js"; +import { atomicOverwriteFile } from "./file_ops.js"; import { SubscribableValue } from "./subscriptions.js"; import { logger } from "./logging.js"; import { ControllerConfig } from "./config/index.js"; @@ -56,7 +56,7 @@ export class JsonDatastoreProvider< // Save the data to the json file async save(data: Map) { logger.verbose(`Saving ${this.filePath}`); - await safeOutputFile(this.filePath, JSON.stringify(Object.fromEntries(data), null, "\t")); + await atomicOverwriteFile(this.filePath, JSON.stringify(Object.fromEntries(data), null, "\t")); } // Load the data from the json file @@ -91,7 +91,7 @@ export class JsonDatastoreProvider< logger.warn( `Duplicates detected in ${this.filePath}, a backup was written to: ${backupPath}` ); - await safeOutputFile(backupPath, JSON.stringify(rawJson, null, "\t")); + await atomicOverwriteFile(backupPath, JSON.stringify(rawJson, null, "\t")); } return result; @@ -115,7 +115,7 @@ export class JsonIdDatastoreProvider< // Save the data to the json file async save(data: Map) { logger.verbose(`Saving ${this.filePath}`); - await safeOutputFile(this.filePath, JSON.stringify([...data.values()], null, "\t")); + await atomicOverwriteFile(this.filePath, JSON.stringify([...data.values()], null, "\t")); } // Load the data from the json file @@ -150,7 +150,7 @@ export class JsonIdDatastoreProvider< logger.warn( `Duplicates detected in ${this.filePath}, a backup was written to: ${backupPath}` ); - await safeOutputFile(backupPath, JSON.stringify(rawJson, null, "\t")); + await atomicOverwriteFile(backupPath, JSON.stringify(rawJson, null, "\t")); } return result; @@ -166,6 +166,7 @@ export abstract class Datastore< "update": [ updates: U[] ], }> { private dirty = false; + private saving: Promise = Promise.resolve(); constructor( private provider: DatastoreProvider = new MemoryDatastoreProvider(), @@ -181,10 +182,22 @@ export abstract class Datastore< // Save the datastore to the provider async save() { - if (this.dirty) { - await this.provider.save(this.data); + // Saves run one at a time so an older snapshot can't be written after a newer one. + const save = this.saving.catch(() => {}).then(async () => { + if (!this.dirty) { + return; + } + // Cleared before writing so changes made while saving are saved by the next save. this.dirty = false; - } + try { + await this.provider.save(this.data); + } catch (err) { + this.dirty = true; + throw err; + } + }); + this.saving = save; + await save; } // Load the datastore from the provider diff --git a/packages/lib/src/file_ops.ts b/packages/lib/src/file_ops.ts index de8b30c4..16701808 100644 --- a/packages/lib/src/file_ops.ts +++ b/packages/lib/src/file_ops.ts @@ -89,7 +89,7 @@ export async function getTempFile(prefix = "tmp.", suffix = "", tmpdir = "./") { } /** - * Safely overwrite file data + * Atomically overwrite file data * * Writes the passed data to a temporary file and rename it over the target * file. If the operation fails because the parent directory does not exist, it @@ -105,7 +105,7 @@ export async function getTempFile(prefix = "tmp.", suffix = "", tmpdir = "./") { * @param data - Content to write. * @param options - see fs.writeFile, `flag` and `flush` may not be used. */ -export async function safeOutputFile( +export async function atomicOverwriteFile( file: string, data: string | Buffer, options?: Omit< diff --git a/packages/lib/src/link/messages.ts b/packages/lib/src/link/messages.ts index c4d95dcb..c0ea4940 100644 --- a/packages/lib/src/link/messages.ts +++ b/packages/lib/src/link/messages.ts @@ -29,8 +29,10 @@ export const dataClasses: (RequestClass | EventClass) controller.ControllerConfigSetRequest, controller.ControllerConfigSetFieldRequest, controller.ControllerConfigSetPropRequest, - controller.HostGenerateTokenRequest, - controller.HostConfigCreateRequest, + controller.HostPairingListRequest, + controller.HostPairingUpdatesEvent, + controller.HostPairingApproveRequest, + controller.HostPairingRejectRequest, controller.GetFactorioCredentialsRequest, controller.LogSetSubscriptionsRequest, controller.LogQueryRequest, @@ -59,7 +61,7 @@ export const dataClasses: (RequestClass | EventClass) host.ControllerConnectionEvent, host.PrepareControllerDisconnectRequest, host.SyncUserListsEvent, - host.HostRevokeTokensRequest, + host.HostRevokeRequest, instance.InstanceDetailsGetRequest, instance.InstanceDetailsListRequest, @@ -69,6 +71,7 @@ export const dataClasses: (RequestClass | EventClass) instance.InstanceConfigSetRequest, instance.InstanceConfigSetFieldRequest, instance.InstanceConfigSetPropRequest, + instance.InstanceConfigInheritFieldRequest, instance.InstanceAssignRequest, instance.InstanceMetricsRequest, instance.InstanceStartRequest, diff --git a/packages/lib/src/load_plugin_list.ts b/packages/lib/src/load_plugin_list.ts index d6838206..65f1e2fd 100644 --- a/packages/lib/src/load_plugin_list.ts +++ b/packages/lib/src/load_plugin_list.ts @@ -328,7 +328,7 @@ export async function loadPluginList( hasChanges = await findNpmPlugins(pluginList, skippedNpmPlugins) || hasChanges; if (hasChanges) { - await libFileOps.safeOutputFile(pluginListPath, JSON.stringify([...pluginList], null, "\t")); + await libFileOps.atomicOverwriteFile(pluginListPath, JSON.stringify([...pluginList], null, "\t")); } return pluginList; diff --git a/packages/lib/src/logging_utils.ts b/packages/lib/src/logging_utils.ts index 2a02f57d..ab235182 100644 --- a/packages/lib/src/logging_utils.ts +++ b/packages/lib/src/logging_utils.ts @@ -312,7 +312,7 @@ export class LogIndex { * was loaded/created from. */ async save() { - await libFileOps.safeOutputFile( + await libFileOps.atomicOverwriteFile( path.join(this.logDirectory, "index.json"), JSON.stringify(this.serialize(), null, "\t") ); diff --git a/packages/lib/src/permissions.ts b/packages/lib/src/permissions.ts index 16c1d8e6..9a5e6acb 100644 --- a/packages/lib/src/permissions.ts +++ b/packages/lib/src/permissions.ts @@ -196,19 +196,16 @@ export const corePermissions = [ grantByDefault: true, }, { - name: "core.host.generate_token", - title: "Generate host token", - description: "Generate tokens for hosts to connect to the cluster with.", + name: "core.host.approve", + title: "Approve hosts", + description: + "List, approve and reject requests from hosts to join the cluster, and approve hosts " + + "directly by starting them with a user token. Approving gives the new host full access to the cluster.", }, { - name: "core.host.revoke_token", - title: "Revoke host token", - description: "Revoke access token and terminate existing connection for hosts.", - }, - { - name: "core.host.create_config", - title: "Create host config", - description: "Create host configs via the controller.", + name: "core.host.revoke", + title: "Revoke hosts", + description: "Remove hosts from the cluster, disconnecting them and making their access tokens invalid.", }, { diff --git a/packages/lib/src/shared_commands.ts b/packages/lib/src/shared_commands.ts index 7767ce8e..155be8f3 100644 --- a/packages/lib/src/shared_commands.ts +++ b/packages/lib/src/shared_commands.ts @@ -199,7 +199,7 @@ export async function handlePluginCommand( } pluginList.set(pluginInfo.name, pluginPath); - await libFileOps.safeOutputFile(pluginListPath, JSON.stringify([...pluginList], null, "\t")); + await libFileOps.atomicOverwriteFile(pluginListPath, JSON.stringify([...pluginList], null, "\t")); print(`Added ${pluginInfo.name}`); } else if (command === "remove") { @@ -209,7 +209,7 @@ export async function handlePluginCommand( return; } - await libFileOps.safeOutputFile(pluginListPath, JSON.stringify([...pluginList], null, "\t")); + await libFileOps.atomicOverwriteFile(pluginListPath, JSON.stringify([...pluginList], null, "\t")); print(`Removed ${args.name}`); } else if (command === "list") { diff --git a/packages/lib/src/subscriptions.ts b/packages/lib/src/subscriptions.ts index cc66781e..e5deea6c 100644 --- a/packages/lib/src/subscriptions.ts +++ b/packages/lib/src/subscriptions.ts @@ -480,6 +480,8 @@ export class EventSubscriber { protected Event: EventClass, public control: Link, protected filteredHandler?: EventSubscriberCallback, + /** Nothing is sent to the controller while this returns false, for accounts without permission */ + protected permitted: () => boolean = () => true, ) { control.handle(Event, this._handleEvent.bind(this)); // The events below exist only on websocket connectors, we can't early return because of test mocking @@ -670,7 +672,7 @@ export class EventSubscriber { * Update the subscription with the controller based on current handler counts */ private async _sendRequest(action: SubscriptionAction, filters: SubscriptionFilters) { - if (!this.control.connector.valid) { + if (!this.control.connector.valid || !this.permitted()) { return; } @@ -725,6 +727,16 @@ export class MapSubscriber< /** Current value of the subscribed resource */ values = new Map(); + override handleConnectionEvent(event: "connect" | "drop" | "resume" | "close") { + if (event === "connect") { + // A new session is only sent values that exist, not ones removed while disconnected, + // so everything is fetched again. + this.values.clear(); + this.lastUpdatedMs = -1; + } + super.handleConnectionEvent(event); + } + protected override getLastUpdatedTimeMs(event: E) { let maxTime = this.lastUpdatedMs; for (const update of event.updates) { diff --git a/packages/web_ui/src/bootstrap.tsx b/packages/web_ui/src/bootstrap.tsx index d3e9f739..b87d4852 100644 --- a/packages/web_ui/src/bootstrap.tsx +++ b/packages/web_ui/src/bootstrap.tsx @@ -8,6 +8,7 @@ import * as lib from "@clusterio/lib"; import App from "./components/App"; import InputRole from "./components/InputRole"; import InputModPack from "./components/InputModPack"; +import { InputInstanceTemplate } from "./components/InputInstance"; import { InputTargetVersion, InputPartialVersion, InputFullVersion } from "./components/InputVersion"; import { Control, ControlConnector } from "./util/websocket"; import { loadedPluginSetKey } from "./util/pluginSet"; @@ -148,6 +149,7 @@ async function inputComponentsFromHooks(control: Control) { "target_version": InputTargetVersion, "mod_pack": InputModPack, "role": InputRole, + "instance_template": InputInstanceTemplate, }]); const iterable = result.map( diff --git a/packages/web_ui/src/components/BaseConfigTree.tsx b/packages/web_ui/src/components/BaseConfigTree.tsx index 058487ce..f352acb4 100644 --- a/packages/web_ui/src/components/BaseConfigTree.tsx +++ b/packages/web_ui/src/components/BaseConfigTree.tsx @@ -2,6 +2,8 @@ import React, { useContext, useEffect, useState } from "react"; import { Button, Card, Checkbox, Form, FormInstance, Input, InputNumber, Select, Space, Spin, Tooltip, Tree, Typography, } from "antd"; +import DisconnectOutlined from "@ant-design/icons/DisconnectOutlined"; +import LinkOutlined from "@ant-design/icons/LinkOutlined"; import ReloadOutlined from "@ant-design/icons/ReloadOutlined"; import * as lib from "@clusterio/lib"; @@ -65,8 +67,28 @@ function renderInput(inputComponents: Map, def: lib.Fiel return `Unknown type ${def.type}`; } +/** Lets fields follow the value of another config, inherited values are locked until unlinking */ +export type ConfigInheritance = { + canInherit: (config: lib.Config, field: string) => boolean; + isInherited: (config: lib.Config, field: string, prop?: string) => boolean; + inherit: (field: string, prop?: string) => Promise; + templateValue: (field: string, prop?: string) => unknown; + notice?: (config: lib.Config) => React.ReactNode; +}; + +type Linking = Map; + +type LinkState = { + inheritance?: ConfigInheritance; + unlinking: Set; + setUnlinking: (unlinking: Set) => void; + linking: Linking; + setLinking: (linking: Linking) => void; +}; + type BaseConfigTreeProps = { ConfigClass: typeof lib.ControllerConfig | typeof lib.HostConfig | typeof lib.InstanceConfig; + inheritance?: ConfigInheritance; retrieveConfig: () => Promise; setConfig: (fields: Record>) => Promise; id?: number; @@ -79,6 +101,8 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) { let [changedFields, setChangedFields] = useState>(new Set()); let [errorFields, setErrorFields] = useState(new Map()); let [applying, setApplying] = useState(false); + let [unlinking, setUnlinking] = useState>(new Set()); + let [linking, setLinking] = useState(new Map()); const available = props.available ?? true; const control = useContext(ControlContext); @@ -136,6 +160,18 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) { } } + async function applyChanges(fields: Record>) { + if (Object.keys(fields).length) { + await props.setConfig(fields); + } + for (const [field, prop] of linking.values()) { + await props.inheritance!.inherit(field, prop); + } + setChangedFields(new Set()); + setUnlinking(new Set()); + setLinking(new Map()); + } + const [propsMap, treeData] = computeTreeData( control, form, @@ -145,6 +181,7 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) { setConfig, props.ConfigClass, onValuesChange, + { inheritance: props.inheritance, unlinking, setUnlinking, linking, setLinking }, ); return <> @@ -158,7 +195,8 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) { onClick={async () => { setApplying(true); const fields: Record> = {}; - for (const field of changedFields) { + // Unlinked fields are sent even when unchanged so they stop following the template + for (const field of new Set([...changedFields, ...unlinking])) { const value = form.getFieldValue(field); if (propsMap.has(field)) { const [fieldName, prop] = propsMap.get(field)!; @@ -179,21 +217,26 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) { } } + let applied = false; try { - await props.setConfig(fields); - setChangedFields(new Set()); + await applyChanges(fields); + applied = true; } catch (err: any) { notify(err.message, "error"); } - await updateConfig(); + const newConfig = await updateConfig(); + if (applied) { + // Linking can change other values + form.setFieldsValue(getInitialValues(newConfig, props)); + } setApplying(false); if (props.onApply) { props.onApply(); } }} - disabled={changedFields.size === 0} + disabled={changedFields.size === 0 && linking.size === 0 && unlinking.size === 0} > Apply @@ -202,6 +245,8 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) { onClick={() => { form.resetFields(); setChangedFields(new Set()); + setUnlinking(new Set()); + setLinking(new Map()); setErrorFields(new Map()); }} > @@ -210,6 +255,7 @@ export default function BaseConfigTree(props: BaseConfigTreeProps) { + {props.inheritance?.notice?.(config)}
) => void, ConfigClass: BaseConfigTreeProps["ConfigClass"], onValuesChange: (changedValues: object) => void, + link: LinkState, ) { let restartTip = void, + ) => + + ; +} + export default function HostViewPage() { let params = useParams(); let hostId = Number(params.id); - let control = useContext(ControlContext); let account = useAccount(); let [instances] = useInstances(); const [systems] = useSystems(); const system = systems.get(hostId); - const [host, synced] = useHost(hostId); + const [host, synced, error] = useHost(hostId); + const state = useResourceState(host, synced, error, hostId); const [maxLevel, setMaxLevel] = useState("info"); const canShowNpm = hasNpmButtonPermission(false); const hostInstances = new Map([...instances].filter(([_id, instance]) => instance.assignedHost === hostId)); let nav = [{ name: "Hosts", path: "/hosts" }, { name: host?.name ?? String(hostId) }]; if (!host) { - if (!synced) { - return ; - } - - return - -

Host with id {hostId} was not found on the controller.

-
; + return ; } let hostButtons = - { - account.hasPermission("core.host.revoke_token") - && { - control.send(new lib.HostRevokeTokensRequest(host.id!)) - .then(() => notify("Host tokens revoked")) - .catch(notifyErrorHandler(`Error revoking tokens for host id:${host.id}`)); - }} - > - - - } + {account.hasPermission("core.host.revoke") && } {canShowNpm && ( )} @@ -175,13 +180,6 @@ export default function HostViewPage() { {host.publicAddress} - { - host.tokenValidAfter - ? - {formatTimestamp(host.tokenValidAfter*1000)} - - : null - } {account.hasPermission("core.instance.list") && <> diff --git a/packages/web_ui/src/components/HostsPage.tsx b/packages/web_ui/src/components/HostsPage.tsx index 40684bc5..654ae644 100644 --- a/packages/web_ui/src/components/HostsPage.tsx +++ b/packages/web_ui/src/components/HostsPage.tsx @@ -1,6 +1,9 @@ -import React, { useContext, useRef, useState, useEffect } from "react"; -import { Button, Flex, Form, InputNumber, Modal, Space, Switch, Table, Tooltip, Typography } from "antd"; -import { ExclamationCircleOutlined, CopyOutlined } from "@ant-design/icons"; +import React, { useContext, useState, useEffect } from "react"; +import { useSearchParams } from "react-router-dom"; +import { + Badge, Button, Descriptions, Flex, Input, Modal, Result, Space, Spin, Switch, Table, Tooltip, Typography, +} from "antd"; +import { ExclamationCircleOutlined, CopyOutlined, PlusOutlined } from "@ant-design/icons"; import * as lib from "@clusterio/lib"; @@ -16,9 +19,10 @@ import { MetricDiskUsed, MetricDiskRatio, RestartRequired, } from "./system_metrics"; -import { useHosts } from "../model/host"; +import { useHostPairings, useHosts } from "../model/host"; import { useSystems } from "../model/system"; import notify, { notifyErrorHandler } from "../util/notify"; +import { formatDuration } from "../util/time_format"; import useTableQueryState from "../util/useTableQueryState"; import useColumnSearch from "../util/useColumnSearch"; import useRowNavigation from "../util/useRowNavigation"; @@ -27,133 +31,228 @@ import Link from "./Link"; const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare; -function GenerateHostTokenButton() { - let control = useContext(ControlContext); - let [open, setOpen] = useState(false); - let [token, setToken] = useState(null); - let [hostId, setHostId] = useState(null); - let [form] = Form.useForm(); - let [pluginList, setPluginList] = useState([]); +/** Current time in milliseconds, updated every second while active */ +function useNow(active: boolean) { + const [now, setNow] = useState(Date.now); useEffect(() => { - (async () => { - let response = await fetch(`${webRoot}api/plugins`); - if (response.ok) { - const plugins = await response.json(); - setPluginList(plugins); - } else { - notify("Failed to load plugin list"); - } - })(); - }, []); - - async function generateToken() { - let id; - let values = form.getFieldsValue(); - if (values.hostId) { - id = Number.parseInt(values.hostId, 10); - if (Number.isNaN(id)) { - form.setFields([{ name: "hostId", errors: ["Must be an integer"] }]); - return; - } - form.setFields([{ name: "hostId", errors: [] }]); + if (!active) { + return undefined; } + setNow(Date.now()); + const interval = setInterval(() => { setNow(Date.now()); }, 1000); + return () => { clearInterval(interval); }; + }, [active]); + return now; +} - let newToken = await control.send(new lib.HostGenerateTokenRequest(id)); - setToken(newToken); - setHostId(id ?? null); +function AddHostModal(props: { open: boolean, onClose: () => void }) { + const [requests, synced] = useHostPairings(); + const [, setParams] = useSearchParams(); + const now = useNow(props.open); + + const controllerUrl = new URL(webRoot, document.location.href).href; + const installCommand = `npm init "@clusterio" -- --mode host --controller-url ${controllerUrl}`; + + function review(code: string) { + setParams(current => { + const next = new URLSearchParams(current); + next.set("approve", code); + return next; + }, { replace: true }); } - // Generate a new random - useEffect(() => { - if (open) { - generateToken().catch(notifyErrorHandler("Error generating token")); - } - }, [open]); + return + + Run the installer in an empty directory on the machine the host will run on, then start the host + with the run-host script. It shows a code and waits for the request to be approved here. + +
+ +

> mkdir clusterio

+

> cd clusterio

+

+ > npm init "@clusterio" -- --mode host + --controller-url {controllerUrl} +

+
+ + Once approved the host saves its connection details and starts up. + Later starts connect to the cluster straight away. + + Waiting for approval + a.createdAtMs - b.createdAtMs)} + locale={{ emptyText: "No hosts are waiting for approval" }} + columns={[ + { + title: "Name", + dataIndex: "name", + }, + { + title: "Code", + dataIndex: "code", + render: (_, request) => {request.code}, + }, + { + title: "Address", + dataIndex: "remoteAddress", + }, + { + title: "Age", + key: "age", + render: (_, request) => + {formatDuration(Math.max(0, now - request.createdAtMs))} + , + }, + { + key: "action", + align: "right", + render: (_, request) => , + }, + ]} + /> + ; +} - const pluginString = pluginList.filter(p => p.npmPackage).map(p => `"${p.npmPackage}"`).join(" "); - return <> - - { - setOpen(false); - setToken(null); - form.resetFields(); - }} - width="700px" - > - - - { - generateToken().catch(notifyErrorHandler("Error generating token")); - }} /> - - +/** Format a code like the controller does, matching any case and without the dash */ +function normaliseCode(code: string) { + const plain = code.toUpperCase().replace(/[^0-9A-Z]/g, ""); + return `${plain.slice(0, 3)}-${plain.slice(3)}`; +} + +/** Dialog opened by the link a waiting host prints, for approving that host */ +function ApproveHostModal(props: { code: string, onClose: () => void }) { + const control = useContext(ControlContext); + const account = useAccount(); + const [requests, synced] = useHostPairings(); + const code = normaliseCode(props.code); + const request = requests.get(code); + const [name, setName] = useState(); + const [busy, setBusy] = useState(false); + const now = useNow(true); + const permitted = account.hasPermission("core.host.approve"); + const hostName = (name ?? request?.name ?? "").trim(); + + function approve() { + if (!request) { + return; + } + setBusy(true); + control.send( + new lib.HostPairingApproveRequest(request.code, hostName !== request.name ? hostName : undefined) + ).then(() => { + notify(`Approved host ${hostName}`, "success"); + props.onClose(); + }).catch( + notifyErrorHandler(`Error approving host ${request.name}`) + ).finally(() => { + setBusy(false); + }); + } + + function reject() { + if (!request) { + return; + } + setBusy(true); + control.send(new lib.HostPairingRejectRequest(request.code)).then(() => { + notify(`Rejected host ${request.name}`); + props.onClose(); + }).catch( + notifyErrorHandler(`Error rejecting host ${request.name}`) + ).finally(() => { + setBusy(false); + }); + } + + let content; + if (!permitted) { + content = ; + } else if (!request && !synced) { + content = ; + } else if (!request) { + content = No host is waiting with code {code}} + subTitle={ + "It may have been approved or rejected already, or stopped waiting. " + + "A host that is still waiting shows a new code." + } + />; + } else { + content = <> - Host IDs are randomly generated and unique, leave blank to use a new ID, - otherwise the ID of an existing host can be found using: + A host is asking to join the cluster. + Only approve it if the code below matches the code shown by the host, + an approved host has full access to the cluster. -
- - npx clusteriohost config get host.id -
- {token !== null && <> - - Host auth token: - -
- - {token} -
- - You can set the token on an existing host with the following command: - -
- - npx clusteriohost config set host.id {token} -
- - A new host can be setup using the following commands: - -
- -

> mkdir clusterio

-

> cd clusterio

-

- > npm init "@clusterio" -- - --controller-token {token} - --mode "host" - --download-headless - --controller-url {document.location.origin}/ - --host-name {hostId ? `Host ${hostId}` : "Host"} - --public-address localhost - {pluginString.length ? "--plugins" : ""} {pluginString} -

-

> ./run-host

-
- } -
+ + {request.code} + + + {request.remoteAddress} + {request.version && {request.version}} + + {formatDuration(Math.max(0, now - request.createdAtMs))} + + + Name + { setName(event.target.value); }} + onPressEnter={approve} + style={{ margin: "4px 0 24px" }} + /> + + + + + ; + } + + return + {content} + ; +} + +function AddHostButton() { + const [open, setOpen] = useState(false); + const [requests] = useHostPairings(); + return <> + + + + { setOpen(false); }} /> ; } @@ -212,11 +311,22 @@ export default function HostsPage() { }); const nameSearch = useColumnSearch(tableState, "name", host => host.name, "Search hosts"); const rowNav = useRowNavigation(); + const [params, setParams] = useSearchParams(); + const approveCode = params.get("approve"); + + function closeApprove() { + setParams(current => { + const next = new URLSearchParams(current); + next.delete("approve"); + return next; + }, { replace: true }); + } return + {approveCode !== null && } : undefined} + extra={account.hasPermission("core.host.approve") ? : undefined} />
>(new Set()); - const [modPack] = useModPack(modPackId); + const [modPack, synced, error] = useModPack(modPackId); + const state = useResourceState(modPack, synced, error, modPackId); const manifest = modPack?.exportManifest; const prototypes = useExportPrototypeMetadata(modPack); const filtered = useMemo(() => filterPrototypes(prototypes, filter), [prototypes, filter]); @@ -100,6 +106,10 @@ export default function IconReferencePage() { { name: modPack?.name ?? String(modPackId), path: `/mods/mod-packs/${modPackId}/view` }, { name: "Icon Reference" }, ]; + if (!modPack) { + return ; + } + return ( @@ -130,7 +140,15 @@ export default function IconReferencePage() { setFilter(e.target.value)} + onChange={e => { + const values = e.target.value ? [e.target.value] : null; + queryState.setFilter("search", values); + if (!values) { + queryState.commitFilter("search", null); + } + }} + onBlur={() => queryState.commitFilter("search")} + onPressEnter={() => queryState.commitFilter("search")} allowClear style={{ width: 320 }} /> diff --git a/packages/web_ui/src/components/InputInstance.tsx b/packages/web_ui/src/components/InputInstance.tsx index 6564311c..0a503d89 100644 --- a/packages/web_ui/src/components/InputInstance.tsx +++ b/packages/web_ui/src/components/InputInstance.tsx @@ -5,6 +5,7 @@ import { useInstances } from "../model/instance"; interface BaseInputInstanceProps extends InputComponentProps { includeAll?: boolean; + templates?: boolean; } function BaseInputInstance(props: BaseInputInstanceProps) { @@ -12,7 +13,9 @@ function BaseInputInstance(props: BaseInputInstanceProps) { const options = [ ...(props.includeAll ? [{ label: "All instances", value: null }] : []), - ...[...instances.values()].map(instance => ({ + ...[...instances.values()].filter( + instance => Boolean(instance.isTemplate) === Boolean(props.templates) + ).map(instance => ({ label: instance.name ?? `Instance ${instance.id}`, value: instance.id, })), @@ -40,3 +43,7 @@ export function InputInstanceWithAll(props: InputComponentProps) { export function InputInstance(props: InputComponentProps) { return ; } + +export function InputInstanceTemplate(props: InputComponentProps) { + return ; +} diff --git a/packages/web_ui/src/components/InstanceConfigTree.tsx b/packages/web_ui/src/components/InstanceConfigTree.tsx index ff028ddd..9ef8d633 100644 --- a/packages/web_ui/src/components/InstanceConfigTree.tsx +++ b/packages/web_ui/src/components/InstanceConfigTree.tsx @@ -1,30 +1,73 @@ -import React, { useContext } from "react"; +import React, { useContext, useRef } from "react"; +import { Alert } from "antd"; import * as lib from "@clusterio/lib"; -import BaseConfigTree from "./BaseConfigTree"; +import BaseConfigTree, { ConfigInheritance } from "./BaseConfigTree"; import ControlContext from "./ControlContext"; +import Link from "./Link"; +import { useInstance } from "../model/instance"; type InstanceConfigTreeProps = { id: number; }; +function TemplateNotice(props: { templateId: number }) { + const [template] = useInstance(props.templateId); + return + Linked values are inherited from the template{" "} + {template?.name ?? props.templateId}. + Unlink a value to set your own on this instance. + } + />; +} + export default function InstanceConfigTree(props: InstanceConfigTreeProps) { let control = useContext(ControlContext); + const templateConfig = useRef({}); async function retrieveConfig() { - return await control.send(new lib.InstanceConfigGetRequest(props.id)); + const config = await control.send(new lib.InstanceConfigGetRequest(props.id)); + const templateId = config["instance.template_id"]; + templateConfig.current = typeof templateId === "number" + ? await control.send(new lib.InstanceConfigGetRequest(templateId)) + : {}; + return config; } async function setConfig(fields: Record>) { await control.send(new lib.InstanceConfigSetRequest(props.id, fields)); } + const inheritance: ConfigInheritance = { + canInherit: (config, field) => ( + (config as lib.InstanceConfig).get("instance.template_id") !== null + && lib.InstanceConfig.isInheritable(field) + ), + isInherited: (config, field, prop) => (config as lib.InstanceConfig).isInherited(field, prop), + inherit: async (field, prop) => { + await control.send(new lib.InstanceConfigInheritFieldRequest(props.id, field, prop)); + }, + templateValue: (field, prop) => { + const value = templateConfig.current[field] as any; + return prop === undefined ? value : value?.[prop]; + }, + notice: (config) => { + const templateId = (config as lib.InstanceConfig).get("instance.template_id"); + return templateId !== null ? : null; + }, + }; + return ; } diff --git a/packages/web_ui/src/components/InstanceList.tsx b/packages/web_ui/src/components/InstanceList.tsx index 02315695..bd54f153 100644 --- a/packages/web_ui/src/components/InstanceList.tsx +++ b/packages/web_ui/src/components/InstanceList.tsx @@ -7,12 +7,14 @@ import type { ColumnType } from "antd/es/table/interface"; import { useAccount } from "../model/account"; import { useSystems } from "../model/system"; import { useHosts } from "../model/host"; +import { useDefaultModPack, useModPacks } from "../model/mod_pack"; import { RestartRequired } from "./system_metrics"; import InstanceStatusTag from "./InstanceStatusTag"; +import InstanceModPack from "./InstanceModPack"; import InstanceControlButton, { InstanceControlButtonPermissions } from "./InstanceControlButton"; import * as lib from "@clusterio/lib"; import Link from "./Link"; -import { instancePublicAddress } from "../util/instance"; +import { instanceModPack, instancePublicAddress } from "../util/instance"; import useTableQueryState from "../util/useTableQueryState"; import useColumnSearch from "../util/useColumnSearch"; import useRowNavigation from "../util/useRowNavigation"; @@ -29,6 +31,8 @@ export default function InstanceList(props: InstanceListProps) { let account = useAccount(); let [hosts] = useHosts(); const [systems] = useSystems(); + const [modPacks] = useModPacks(); + const defaultModPack = useDefaultModPack(); const tableState = useTableQueryState({ namespace: "instance", defaultSortKey: "name", }); @@ -44,6 +48,15 @@ export default function InstanceList(props: InstanceListProps) { return hosts.get(hostId)?.name ?? String(hostId); } + function modPackOf(instance: lib.InstanceDetails) { + return instanceModPack(instance.modPackId, modPacks, defaultModPack); + } + + function modPackName(instance: lib.InstanceDetails) { + const { id, modPack } = modPackOf(instance); + return modPack?.name ?? (id !== undefined ? String(id) : ""); + } + function integerFactorioVersionOrDefault(instance: lib.InstanceDetails) { const v = instance.factorioVersion; if (v && lib.isPartialVersion(v)) { @@ -115,6 +128,15 @@ export default function InstanceList(props: InstanceListProps) { sortOrder: tableState.sortOrder("version"), responsive: ["xl"], }, + { + title: "Mod Pack", + key: "modPack", + className: "table-link-cell", + render: (_, instance) => , + sorter: (a, b) => strcmp(modPackName(a), modPackName(b)), + sortOrder: tableState.sortOrder("modPack"), + responsive: ["lg"], + }, { title: "Status", key: "status", diff --git a/packages/web_ui/src/components/InstanceModPack.tsx b/packages/web_ui/src/components/InstanceModPack.tsx new file mode 100644 index 00000000..ee9807df --- /dev/null +++ b/packages/web_ui/src/components/InstanceModPack.tsx @@ -0,0 +1,20 @@ +import React from "react"; +import { Space, Tag, Tooltip } from "antd"; + +import Link from "./Link"; +import type { ResolvedModPack } from "../util/instance"; + +export default function InstanceModPack(props: { resolved: ResolvedModPack }) { + const { id, modPack, isDefault } = props.resolved; + if (id === undefined) { + return Controller default; + } + return + e.stopPropagation()}> + {modPack?.name ?? id} + + {isDefault && + Default + } + ; +} diff --git a/packages/web_ui/src/components/InstanceViewPage.tsx b/packages/web_ui/src/components/InstanceViewPage.tsx index ab52b69a..e6d6fae1 100644 --- a/packages/web_ui/src/components/InstanceViewPage.tsx +++ b/packages/web_ui/src/components/InstanceViewPage.tsx @@ -1,7 +1,7 @@ import React, { useContext, useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { - Alert, Button, Descriptions, Dropdown, Flex, MenuProps, Modal, Segmented, Space, Spin, Tooltip, Typography, + Button, Descriptions, Dropdown, Flex, MenuProps, Modal, Segmented, Space, Tag, Tooltip, Typography, message, } from "antd"; import CopyOutlined from "@ant-design/icons/CopyOutlined"; @@ -16,6 +16,7 @@ import PageHeader from "./PageHeader"; import PageLayout from "./PageLayout"; import PluginExtra from "./PluginExtra"; import ResourceNotes from "./ResourceNotes"; +import ResourceState from "./ResourceState"; import InstanceConfigTree from "./InstanceConfigTree"; import LogConsole, { SelectMaxLogLevel } from "./LogConsole"; import InstanceRcon from "./InstanceRcon"; @@ -25,12 +26,16 @@ import LoadScenarioModal from "./LoadScenarioModal"; import SavesList from "./SavesList"; import OnlinePlayersList from "./OnlinePlayersList"; import { notifyErrorHandler } from "../util/notify"; -import { useInstance } from "../model/instance"; +import { useInstance, useInstances } from "../model/instance"; +import { CreateInstanceButton } from "./InstancesPage"; import { useHost } from "../model/host"; import InstanceStatusTag from "./InstanceStatusTag"; import Link from "./Link"; -import { instancePublicAddress } from "../util/instance"; +import { instanceModPack, instancePublicAddress } from "../util/instance"; +import { useDefaultModPack, useModPacks } from "../model/mod_pack"; +import InstanceModPack from "./InstanceModPack"; import useLocalStorage from "../util/useLocalStorage"; +import useResourceState from "../util/useResourceState"; import { MetricRelativeDate } from "./system_metrics"; type MenuItem = Required["items"][number]; @@ -43,6 +48,37 @@ type InstanceDescriptionProps = { host?: Readonly; instance: Readonly; }; +function TemplateDescription(props: { instance: Readonly }) { + const [instances] = useInstances(); + const inheritors = [...instances.values()].filter(i => i.templateId === props.instance.id); + return + + {inheritors.length + ? + {inheritors.map(i => {i.name})} + + : No instances} + + {props.instance.templateId !== undefined && + + } + + + + ; +} + +function ModPackDescription(props: { modPackId?: number }) { + const [modPacks] = useModPacks(); + const defaultModPack = useDefaultModPack(); + return ; +} + +function TemplateLink(props: { id: number }) { + const [template] = useInstance(props.id); + return {template?.name ?? props.id}; +} + function InstanceDescription(props: InstanceDescriptionProps) { let account = useAccount(); @@ -92,9 +128,15 @@ function InstanceDescription(props: InstanceDescriptionProps) { {instance.factorioVersion ?? "unknown"} + + + + {instance.templateId !== undefined && + + } ; } @@ -106,6 +148,8 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) { let instance = props.instance; let instanceId = instance.id!; let [host] = useHost(instance.assignedHost); + const [instances] = useInstances(); + const canCreate = account.hasPermission("core.instance.create"); let instanceButtonMenuItems: MenuItem[] = []; if (account.hasPermission("core.instance.export_data")) { @@ -134,6 +178,21 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) { label: "Delete", }); } + function confirmDelete() { + Modal.confirm({ + autoFocusButton: "cancel", + content: "Permamently delete instance and server saves?", + okText: "Delete", + okButtonProps: { danger: true }, + onOk: () => { + control.send( + new lib.InstanceDeleteRequest(instanceId) + ).then(() => { + navigate("/instances"); + }).catch(notifyErrorHandler("Error deleting instance")); + }, + }); + } let instanceButtonsMenuProps: MenuProps = { items: instanceButtonMenuItems, onClick: ({ key }: { key: string }) => { @@ -155,22 +214,25 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) { ).catch(notifyErrorHandler("Error extracting player data")); } else if (key === "delete") { - Modal.confirm({ - autoFocusButton: "cancel", - content: "Permamently delete instance and server saves?", - okText: "Delete", - okButtonProps: { danger: true }, - onOk: () => { - control.send( - new lib.InstanceDeleteRequest(instanceId) - ).then(() => { - navigate("/instances"); - }).catch(notifyErrorHandler("Error deleting instance")); - }, - }); + confirmDelete(); } }, }; + if (instance.isTemplate) { + return + {canCreate && } + {account.hasPermission("core.instance.delete") && } + ; + } + return { account.hasAnyPermission(...InstanceControlButtonPermissions) @@ -188,6 +250,12 @@ function InstanceButtons(props: { instance: lib.InstanceDetails }) { Connect via Steam {account.hasPermission("core.instance.load_scenario") && } + {canCreate && } {account.hasAnyPermission( "core.instance.export_data", "core.instance.extract_players", @@ -208,36 +276,30 @@ export default function InstanceViewPage() { let navigate = useNavigate(); let account = useAccount(); - let [instance, synced] = useInstance(instanceId); + let [instance, synced, error] = useInstance(instanceId); + const state = useResourceState(instance, synced, error, instanceId); let [host] = useHost(instance?.assignedHost); let nav = [{ name: "Instances", path: "/instances" }, { name: instance?.name ?? String(instanceId) }]; if (!instance) { - if (!synced) { - return ; - } - - return - Instance with id {instanceId} was not found on the controller.} - type="warning" - action={ - Go back to instances list - } - /> - ; + return ; } return } + status={instance.isTemplate + ? Template + : } extra={} /> - + {instance.isTemplate + ? + : } + {!instance.isTemplate && <> {account.hasPermission("core.user.list") && } @@ -284,6 +346,7 @@ export default function InstanceViewPage() { account.hasPermission("core.instance.send_rcon") && } + } {account.hasPermission("core.instance.get_config") && } diff --git a/packages/web_ui/src/components/InstancesPage.tsx b/packages/web_ui/src/components/InstancesPage.tsx index ed1498a2..7fbbd3b8 100644 --- a/packages/web_ui/src/components/InstancesPage.tsx +++ b/packages/web_ui/src/components/InstancesPage.tsx @@ -1,6 +1,7 @@ import React, { useContext, useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; -import { Button, Checkbox, Form, Input, Modal, Select, Space, Tooltip, Typography } from "antd"; +import { Button, Checkbox, Form, Input, Modal, Select, Space, Table, Tooltip, Typography } from "antd"; +import type { ColumnType } from "antd/es/table/interface"; import * as lib from "@clusterio/lib"; @@ -13,13 +14,89 @@ import { useHosts } from "../model/host"; import { useInstanceConfig, useInstances } from "../model/instance"; import { useSaves } from "../model/saves"; import InstanceList from "./InstanceList"; +import Link from "./Link"; +import useRowNavigation from "../util/useRowNavigation"; import { notifyErrorHandler } from "../util/notify"; +import type { Control } from "../util/websocket"; type SaveMode = "none" | "copy" | "save_and_copy"; const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare; -function CreateInstanceButton(props: { instances: ReturnType[0] }) { +function ConfigSourceFields(props: { + instances: ReturnType[0]; + templateId?: number | null; + source?: Readonly; + asTemplate: boolean; +}) { + const templates = [...props.instances.values()].filter(i => i.isTemplate); + const hasTemplate = typeof props.templateId === "number"; + return <> + {(templates.length > 0 || hasTemplate) && + + !i.isTemplate), + ].map(i => ({ value: i.id, label: i.name }))} + /> + + + {props.asTemplate && props.source && + Make {props.source.name} inherit from the new template + } + ; +} + +async function linkToTemplate(control: Control, source: lib.InstanceDetails | undefined, templateId: number) { + if (source) { + await control.send(new lib.InstanceConfigSetFieldRequest( + source.id, "instance.template_id", String(templateId), + )); + } +} + +function setTemplateFields( + config: lib.InstanceConfig, + fields: (keyof lib.InstanceConfigFields)[], + templateId: unknown, + asTemplate: boolean, +) { + if (typeof templateId === "number") { + config.set("instance.template_id", templateId); + fields.push("instance.template_id"); + } + if (asTemplate) { + config.set("instance.is_template", true); + fields.push("instance.is_template"); + } +} + +type CreateInstanceInitial = { + instanceClone?: number; + template?: number; + asTemplate?: boolean; + linkSource?: boolean; +}; + +export function CreateInstanceButton({ buttonText = "Create", buttonType = "primary", ...props }: { + instances: ReturnType[0]; + initial?: CreateInstanceInitial; + buttonText?: string; + buttonType?: "primary" | "default"; + buttonSize?: "small"; +}) { let control = useContext(ControlContext); let account = useAccount(); let navigate = useNavigate(); @@ -31,9 +108,11 @@ function CreateInstanceButton(props: { instances: ReturnType= 0 ? props.instances.get(cloneId) : undefined; const sourceRunning = source?.status === "running"; const activeSave = source ? [...saves.values()].find( @@ -42,6 +121,7 @@ function CreateInstanceButton(props: { instances: ReturnType | undefined; const sourceServerName = typeof sourceSettings?.name === "string" ? sourceSettings.name : undefined; + const copySettings = sourceSettings !== undefined && !asTemplate; useEffect(() => { if (open && sourceServerName !== undefined) { @@ -68,7 +148,8 @@ function CreateInstanceButton(props: { instances: ReturnType + >{buttonText}
- {canAssign && + + + Create as template + + + {canAssign && !asTemplate && } - - - @@ -194,10 +286,59 @@ function CreateInstanceButton(props: { instances: ReturnType; } +function TemplateList(props: { instances: ReturnType[0] }) { + const account = useAccount(); + const rowNav = useRowNavigation(); + const all = [...props.instances.values()]; + const inheritors = (id: number) => all.filter(instance => instance.templateId === id).length; + const columns: ColumnType[] = [ + { + title: "Name", + dataIndex: "name", + defaultSortOrder: "ascend", + sorter: (a, b) => strcmp(a.name, b.name), + render: (_, template) => + {template.name} + , + }, + { + title: "Inherited by", + key: "inheritors", + render: (_, template) => `${inheritors(template.id)} instance(s)`, + sorter: (a, b) => inheritors(a.id) - inheritors(b.id), + }, + ]; + if (account.hasPermission("core.instance.create")) { + columns.push({ + key: "action", + align: "right", + // Clicks inside the modal bubble through the React tree to the row + render: (_, template) => e.stopPropagation()}> + + , + }); + } + return
instance.isTemplate)} + rowKey={template => template.id} + pagination={false} + onRow={record => rowNav(`/instances/${record.id}/view`)} + />; +} + export default function InstancesPage() { let control = useContext(ControlContext); let account = useAccount(); let [instances] = useInstances(); + const plainInstances = new Map([...instances].filter(([, instance]) => !instance.isTemplate)); + const hasTemplates = plainInstances.size !== instances.size; return } /> - + + {hasTemplates && <> + Templates + + } ; } diff --git a/packages/web_ui/src/components/ModPackViewPage.tsx b/packages/web_ui/src/components/ModPackViewPage.tsx index 575b3361..3bd8558f 100644 --- a/packages/web_ui/src/components/ModPackViewPage.tsx +++ b/packages/web_ui/src/components/ModPackViewPage.tsx @@ -3,8 +3,8 @@ import { useNavigate, useParams } from "react-router-dom"; import { Button, Card, ColorPicker, Checkbox, Col, ConfigProvider, Descriptions, Form, Input, Pagination, - Popconfirm, Row, Table, Tag, Typography, Select, Skeleton, Space, Spin, Switch, Modal, Tooltip, - TablePaginationConfig, Alert, notification, FormProps, + Popconfirm, Row, Table, Tag, Typography, Select, Skeleton, Space, Switch, Modal, Tooltip, + TablePaginationConfig, Alert, notification, FormProps, Collapse, } from "antd"; import { @@ -21,11 +21,15 @@ import { useAccount } from "../model/account"; import { useModPack } from "../model/mod_pack"; import { useMods } from "../model/mods"; import { useClipboard } from "../util/clipboard"; +import { modSettingFields, ModSettingField, ModSettingScope } from "../util/mod_settings"; import notify, { notifyErrorHandler } from "../util/notify"; +import { modSettingDescription, modSettingName, modSettingValueName } from "../util/locale"; +import useResourceState from "../util/useResourceState"; import PageHeader from "./PageHeader"; import PageLayout from "./PageLayout"; import SectionHeader from "./SectionHeader"; import ResourceNotes from "./ResourceNotes"; +import ResourceState from "./ResourceState"; import ModDetails from "./ModDetails"; import { InputPartialVersion } from "./InputVersion"; import Link from "./Link"; @@ -854,11 +858,6 @@ function hasChange(changes: ModChange[], field:Partial) { .every(([key, value]) => (change as any)[key] === value)); } -// picks out the value property from settings. -function pickValue(map: Map): [string, lib.ModSetting["value"]][] { - return [...map].map(([name, value]) => [name, value.value]); -} - function groupToMap(array: any[], fn: (...args:any) => any) { const map = new Map(); for (let index = 0; index < array.length; index++) { @@ -901,10 +900,19 @@ function InputColor(props: { type SettingsTableFieldProps = { name: string; type: string; - scope: string; + scope: ModSettingScope; allowedValues: any; + localisedName?: lib.FactorioLocalisedString; + localisedDescription?: lib.FactorioLocalisedString; locale: Map; changed: boolean; + /** Saved value of the setting, used when the field is created and when the form is reset */ + initialValue: lib.ModSetting["value"] | undefined; + /** Show a remove link, or a revert link if removed is set */ + removable?: boolean; + removed?: boolean; + onChange?: (change: ModChange) => void; + onRevert?: (change: ModChange) => void; }; const SettingsTableField = memo((props: SettingsTableFieldProps) => { const name = props.name; @@ -912,6 +920,7 @@ const SettingsTableField = memo((props: SettingsTableFieldProps) => { const isColor = props.type === "color-setting"; const isNumber = ["int-setting", "double-setting"].includes(props.type); const isSelect = Boolean(props.allowedValues); + const prototype = { name, localised_name: props.localisedName, localised_description: props.localisedDescription }; let input; if (isBoolean) { input = ; @@ -919,40 +928,61 @@ const SettingsTableField = memo((props: SettingsTableFieldProps) => { const PartialInputColor = InputColor as () => React.JSX.Element; input = ; } else if (isSelect) { - const options = Object.values(props.allowedValues).map(value => ({ + const options = Object.values(props.allowedValues as (string | number)[]).map(value => ({ value, - label: props.locale.get(`string-mod-setting.${name}-${value}`) || value, + label: modSettingValueName(props.locale, name, value), })); input = ; } + const label = modSettingName(props.locale, prototype); + const change: ModChange = { + type: "settings.delete", scope: props.scope, name, value: { value: props.initialValue! }, + }; return {label} : label} + tooltip={modSettingDescription(props.locale, prototype)} labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} - valuePropName={isBoolean ? "checked" : "value"} - rules={[...isNumber ? [{ - validator(rule: any, value: any) { - if (Number.isNaN(Number(value))) { - return Promise.reject(new Error("Must be a number")); - } - return Promise.resolve(); - }, - }] : []]} className={props.changed ? "changed" : ""} > - {input} + + + {input} + + {props.removable && !props.removed && props.onChange?.(change)} + >remove} + {props.removable && props.removed && props.onRevert?.(change)} + >revert} + ; }); type SettingsTableProps = { modPack: lib.ModPack; - prototypes: any; + /** Mod pack without unsaved changes, reverting the form goes back to its values */ + savedModPack: lib.ModPack; + /** Exported setting prototypes, undefined if the mod pack has no export data */ + prototypes: lib.ExportSettings | undefined; locale: any; changes: ModChange[]; onChange: (change: ModChange) => void; @@ -966,55 +996,52 @@ function SettingsTable(props: SettingsTableProps) { .map(mod => [mod.name, mod.title]) ); - const types = ["bool-setting", "int-setting", "double-setting", "string-setting", "color-setting"]; - let prototypes = Object.entries(props.prototypes) - .filter(([type, _]) => types.includes(type)) - .flatMap(([_, settingPrototypes]: [string, any]) => Object.values(settingPrototypes)) - ; + function field(scope: ModSettingScope, setting: ModSettingField, removable = false) { + return ; + } - function controls( - scope: "startup"|"runtime-global"|"runtime-per-user", - storedFields: [string, lib.ModSetting["value"]][] - ) { - let fields = new Map(prototypes - .filter(p => p.setting_type === scope) - .sort((a, b) => strcmp(a.mod, b.mod) || strcmp(a.order || "", b.order || "") || strcmp(a.name, b.name)) - .map(p => [p.name, p]) - ); - for (let [name, value] of storedFields) { - if (!fields.has(name)) { - let type; - if (typeof value === "boolean") { - type = "bool-setting"; - } else if (typeof value === "number") { - type = "double-setting"; - } else if (typeof value === "string") { - type = "string-setting"; - } else if (typeof value === "object" && "r" in value) { - type = "color-setting"; - } else { - throw Error(`Unhandled setting type ${typeof value}`); - } - fields.set(name, { mod: "Unknown Fields", name, setting_type: scope, type }); - } - } - let fieldsByMod = groupToMap([...fields.values()], prototype => prototype.mod); - return [...fieldsByMod].map(([mod, fieldsForMod]) => - - {props.locale.get(`mod-name.${mod}`) || modTitles.get(mod) || mod} - - {[...fieldsForMod].map( - prototype => - )} - ); + function controls(scope: ModSettingScope) { + // Listed from the saved pack so removed settings stay visible until applied + const { known, unknown } = modSettingFields(props.prototypes, scope, props.savedModPack.settings[scope]); + const fieldsByMod = groupToMap(known, setting => setting.mod); + return <> + {[...fieldsByMod].map(([mod, fieldsForMod]) => + {mod !== undefined && + {props.locale.get(`mod-name.${mod}`) || modTitles.get(mod) || mod} + } + {fieldsForMod.map((setting: ModSettingField) => field(scope, setting))} + )} + {unknown.length > 0 && + + No mod in the exported data defines these settings. They are kept so the values come back + if a mod that uses them is added again. + + {unknown.map(setting => field(scope, setting, true))} + , + }]} + />} + ; } return <> @@ -1023,15 +1050,15 @@ function SettingsTable(props: SettingsTableProps) { /> Run export data on an instance to update available fields. Startup - {controls("startup", pickValue(props.modPack.settings["startup"]))} + {controls("startup")} Map These only apply for new saves. - {controls("runtime-global", pickValue(props.modPack.settings["runtime-global"]))} + {controls("runtime-global")} Per Player Default settings for new players, these only apply for new saves. - {controls("runtime-per-user", pickValue(props.modPack.settings["runtime-per-user"]))} + {controls("runtime-per-user")} ; } @@ -1093,14 +1120,16 @@ function ExportButton(props: { modPack: lib.ModPack }) { } function useExportedAsset(modPack: lib.ModPack | undefined, asset: "settings"|"locale"): Map | any { - let [assetData, setAssetData] = useState|any>(asset === "locale" ? new Map() : {}); + let [assetData, setAssetData] = useState|any>(asset === "locale" ? new Map() : undefined); let assetFilename: string | undefined; if (modPack instanceof lib.ModPack && modPack.exportManifest?.assets[asset]) { assetFilename = modPack.exportManifest.assets[asset]; } useEffect(() => { async function load() { + const empty = asset === "locale" ? new Map() : undefined; if (!assetFilename) { + setAssetData(empty); return; } @@ -1109,7 +1138,14 @@ function useExportedAsset(modPack: lib.ModPack | undefined, asset: "settings"|"l let data = await response.json(); setAssetData(asset === "locale" ? new Map(data) : data); } else { - logger.error(`Error loading mod pack asset "${asset}" (${response.status}): ${await response.text()}`); + if (response.status === 404) { + logger.warn(`Mod pack asset "${asset}" is missing on the controller`); + } else { + logger.error( + `Error loading mod pack asset "${asset}" (${response.status}): ${await response.text()}` + ); + } + setAssetData(empty); } } @@ -1183,8 +1219,9 @@ export default function ModPackViewPage() { let modPackId = Number(params.id); const [form] = Form.useForm(); - const [modPack, synced] = useModPack(modPackId); - let prototypes: any = useExportedAsset(modPack, "settings"); + const [modPack, synced, error] = useModPack(modPackId); + const state = useResourceState(modPack, synced, error, modPackId); + let prototypes: lib.ExportSettings | undefined = useExportedAsset(modPack, "settings"); let locale: Map = useExportedAsset(modPack, "locale"); let [changes, setChanges] = useState([]); let syncTimeout = useRef|undefined>(); @@ -1214,7 +1251,7 @@ export default function ModPackViewPage() { setChanges(oldChanges => { const newChanges = [...oldChanges]; const index = newChanges.findLastIndex(reference => ( - change.type === reference.type && change.name === reference.name + change.type === reference.type && change.name === reference.name && change.scope === reference.scope )); if (index === -1) { logger.error(`Unable to revert ${change.type} ${change.name}: change not found`); @@ -1237,6 +1274,9 @@ export default function ModPackViewPage() { } } else if (["startup", "runtime-global", "runtime-per-user"].includes(field.name[0])) { let [scope, settingName]: ["startup"|"runtime-global"|"runtime-per-user", string] = field.name; + if (modPack!.settings[scope].has(settingName) && !modifiedModPack!.settings[scope].has(settingName)) { + continue; // Removed + } let value = field.value; if (typeof modPack!.settings[scope].get(settingName)?.value === "number") { value = Number(value); @@ -1253,17 +1293,7 @@ export default function ModPackViewPage() { let nav = [{ name: "Mods", path: "/mods" }, { name: "Mod Packs" }, { name: modPack?.name ?? String(modPackId) }]; if (!modifiedModPack || !modPack) { - if (!synced) { - return - - - ; - } - - return - -

Mod pack with id {modPackId} was not found on the controller.

-
; + return ; } return @@ -1301,13 +1331,12 @@ export default function ModPackViewPage() { syncTimeout.current = setTimeout(syncPack.bind(undefined, allFields), 500); } }} + // Mod settings get their value on each field instead, the form only applies initialValues when it is + // created, so settings added by an export while the page is open would show up empty. initialValues={{ name: modPack.name, description: modPack.description, factorioVersion: modPack.factorioVersion, - "startup": Object.fromEntries(pickValue(modPack.settings["startup"])), - "runtime-global": Object.fromEntries(pickValue(modPack.settings["runtime-global"])), - "runtime-per-user": Object.fromEntries(pickValue(modPack.settings["runtime-per-user"])), }} > @@ -1356,6 +1385,7 @@ export default function ModPackViewPage() { /> Promise, + /** Why machines is not available, if it's not just still loading */ + error: Error | null, }; /** @@ -44,7 +46,7 @@ type MachinePluginsState = { export function useMachinePlugins(): MachinePluginsState { const control = useContext(ControlContext); const account = useAccount(); - const [hosts, hostsSynced] = useHosts(); + const [hosts, hostsSynced, hostsError] = useHosts(); const [systems, systemsSynced] = useSystems(); // Lists fetched directly, used until the system metrics of the machine update const [listed, setListed] = useState(new Map()); @@ -88,8 +90,12 @@ export function useMachinePlugins(): MachinePluginsState { } }, [canList, hostsSynced, connectedKey]); - if (!canList || !hostsSynced || (!systemsSynced && !listed.size)) { - return { machines: undefined, unknown: [], refresh }; + if (!canList) { + const error = new lib.PermissionError("Missing permission core.plugin.list"); + return { machines: undefined, unknown: [], refresh, error }; + } + if (!hostsSynced || (!systemsSynced && !listed.size)) { + return { machines: undefined, unknown: [], refresh, error: hostsError }; } const machines: MachinePlugins[] = []; const unknown: Machine[] = []; @@ -105,7 +111,7 @@ export function useMachinePlugins(): MachinePluginsState { unknown.push(machine); } } - return { machines, unknown, refresh }; + return { machines, unknown, refresh, error: null }; } /** Latest version published on npm of each package */ diff --git a/packages/web_ui/src/components/PluginViewPage.tsx b/packages/web_ui/src/components/PluginViewPage.tsx index 2a7e6c8e..6903f258 100644 --- a/packages/web_ui/src/components/PluginViewPage.tsx +++ b/packages/web_ui/src/components/PluginViewPage.tsx @@ -1,15 +1,15 @@ import React, { useEffect, useContext, useState } from "react"; import { useParams } from "react-router-dom"; -import { Alert, Descriptions, Spin } from "antd"; +import { Alert, Descriptions } from "antd"; import * as lib from "@clusterio/lib"; import type { PluginWebApi } from "@clusterio/lib"; import ControlContext from "./ControlContext"; import PageLayout from "./PageLayout"; -import PageHeader from "./PageHeader"; +import ResourceState from "./ResourceState"; import SectionHeader from "./SectionHeader"; -import notify from "../util/notify"; +import useResourceState from "../util/useResourceState"; import { usePluginInstaller } from "./PluginInstall"; import { PluginMachinesTable, PluginUpdateButton, useLatestVersions, useMachinePlugins } from "./PluginClusterStatus"; import { PluginStatus, computePluginStatuses, pluginStatusKey } from "../util/plugin_status"; @@ -89,18 +89,18 @@ export default function PluginViewPage() { let params = useParams(); const control = useContext(ControlContext); let [pluginList, setPluginList] = useState(); + const [pluginListError, setPluginListError] = useState(null); let pluginName = String(params.name); - const { machines, unknown, refresh } = useMachinePlugins(); + const { machines, unknown, refresh, error: machinesError } = useMachinePlugins(); useEffect(() => { (async () => { let response = await fetch(`${webRoot}api/plugins`); - if (response.ok) { - setPluginList(await response.json()); - } else { - notify("Failed to load plugin list"); + if (!response.ok) { + throw new Error(`Failed to load plugin list: ${response.status} ${response.statusText}`); } - })(); + setPluginList(await response.json()); + })().catch(setPluginListError); }, []); const pluginMeta = pluginList?.find(p => p.name === pluginName); @@ -110,19 +110,16 @@ export default function PluginViewPage() { : undefined; const pluginInfo = control.pluginInfos.get(pluginName); const pluginTitle = pluginInfo?.title ?? status?.title ?? pluginName; + // Machines are only needed for plugins not on the controller, which isn't known until the list has loaded + const error = pluginListError ?? (pluginList ? machinesError : null); + const state = useResourceState( + pluginList && (pluginMeta ?? status), Boolean(pluginList && machines), error, pluginName + ); let nav = [{ name: "Plugins", path: "/plugins" }, { name: pluginTitle }]; - if (!pluginList || (!pluginMeta && !machines)) { - return - - - ; - } - - if (!pluginMeta && !status) { - return - -

Plugin with name {pluginName} was not found on the controller or any host.

-
; + if (state !== "ok") { + return ; } return diff --git a/packages/web_ui/src/components/ResourceState.tsx b/packages/web_ui/src/components/ResourceState.tsx new file mode 100644 index 00000000..d2587704 --- /dev/null +++ b/packages/web_ui/src/components/ResourceState.tsx @@ -0,0 +1,49 @@ +import React from "react"; +import { Result, ResultProps, Spin } from "antd"; + +import Link from "./Link"; +import PageHeader from "./PageHeader"; +import PageLayout from "./PageLayout"; +import type { ResourceStatus } from "../util/useResourceState"; + +type ResourceStateProps = { + /** Status from useResourceState */ + state: ResourceStatus; + /** Capitalised name of the kind of resource, e.g. "Mod pack" */ + type: string; + /** Id or name of the resource */ + id: number | string; + nav: React.ComponentProps["nav"]; + /** Page listing this kind of resource */ + listPath: string; + /** Error from the subscription */ + error: Error | null; +}; + +/** Whole page to render in place of a view page when its resource can't be shown */ +export default function ResourceState(props: ResourceStateProps) { + const { state, type, id, nav } = props; + if (state === "ok") { + return null; + } + + if (state === "loading") { + return + + + ; + } + + const results: Record = { + missing: { status: "warning", title: `${type} not found`, subTitle: `${type} ${id} was not found.` }, + deleted: { status: "warning", title: `${type} ${id} has been deleted` }, + error: { status: "error", title: `Could not load ${type.toLowerCase()}`, subTitle: props.error?.message }, + }; + + return + Back to {type.toLowerCase()} list} + /> + ; +} diff --git a/packages/web_ui/src/components/RoleViewPage.tsx b/packages/web_ui/src/components/RoleViewPage.tsx index 5e61df85..5a7d8ba4 100644 --- a/packages/web_ui/src/components/RoleViewPage.tsx +++ b/packages/web_ui/src/components/RoleViewPage.tsx @@ -1,6 +1,6 @@ -import React, { useEffect, useContext, useState, useMemo, useRef } from "react"; +import React, { useEffect, useContext, useState, useMemo } from "react"; import { useNavigate, useParams } from "react-router-dom"; -import { Button, Checkbox, Col, Grid, Input, Popconfirm, Row, Space, Spin, Tooltip } from "antd"; +import { Button, Checkbox, Col, Grid, Input, Popconfirm, Row, Space, Tooltip } from "antd"; import { ExclamationCircleOutlined, StarOutlined, DeleteOutlined} from "@ant-design/icons"; import * as lib from "@clusterio/lib"; @@ -12,7 +12,9 @@ import PageHeader from "./PageHeader"; import PageLayout from "./PageLayout"; import PluginExtra from "./PluginExtra"; import ResourceNotes from "./ResourceNotes"; +import ResourceState from "./ResourceState"; import { notifyErrorHandler } from "../util/notify"; +import useResourceState from "../util/useResourceState"; /** Splits a permission name into parts, removing the last part */ @@ -162,14 +164,14 @@ export default function RoleViewPage() { const navigate = useNavigate(); const account = useAccount(); const control = useContext(ControlContext); - const [role, synced] = useRole(roleId); + const [role, synced, error] = useRole(roleId); + const state = useResourceState(role, synced, error, roleId); // Local edits on top of the live role const [nameEdit, setNameEdit] = useState(); const [descriptionEdit, setDescriptionEdit] = useState(); const [permissionEdits, setPermissionEdits] = useState>({}); const [search, setSearch] = useState(""); - const loadedRoleId = useRef(undefined); // Hidden below lg, where the site sider leaves too little room; undefined until measured const screens = Grid.useBreakpoint(); const showGroupList = screens.lg !== false; @@ -203,27 +205,9 @@ export default function RoleViewPage() { setPermissionEdits({}); }, [roleId]); - if (role) { - loadedRoleId.current = roleId; - } - - // If no role then display either the loading screen or the not found screen if (!role) { const nav = [{ name: "Roles", path: "/roles" }, { name: String(roleId) }]; - - if (!synced) { - return - - - ; - } - - return - -

Role with id {roleId} { - loadedRoleId.current === roleId ? "has been deleted" : "was not found on the controller" - }.

-
; + return ; } const name = nameEdit ?? role.name; diff --git a/packages/web_ui/src/components/UserViewPage.tsx b/packages/web_ui/src/components/UserViewPage.tsx index 02e9733b..5e3581c0 100644 --- a/packages/web_ui/src/components/UserViewPage.tsx +++ b/packages/web_ui/src/components/UserViewPage.tsx @@ -2,7 +2,7 @@ import React, { useEffect, useContext, useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; import { Button, Col, Descriptions, Form, Input, Popconfirm, - Row, Table, Tag, Select, Space, Spin, Switch, + Row, Table, Tag, Select, Space, Switch, } from "antd"; import DeleteOutlined from "@ant-design/icons/DeleteOutlined"; @@ -18,7 +18,9 @@ import PageLayout from "./PageLayout"; import PluginExtra from "./PluginExtra"; import SectionHeader from "./SectionHeader"; import ResourceNotes from "./ResourceNotes"; +import ResourceState from "./ResourceState"; import useRowNavigation from "../util/useRowNavigation"; +import useResourceState from "../util/useResourceState"; import Link from "./Link"; import notify, { notifyErrorHandler } from "../util/notify"; import { formatDuration } from "../util/time_format"; @@ -40,7 +42,8 @@ export default function UserViewPage() { let account = useAccount(); let control = useContext(ControlContext); let [instances] = useInstances(); - const [user, synced] = useUser(userName); + const [user, synced, error] = useUser(userName); + const state = useResourceState(user, synced, error, userName); let [roles, rolesSynced] = useRoles(); let [form] = Form.useForm(); const statsTable = useTableQueryState<[number, lib.PlayerStats]>({ @@ -78,17 +81,7 @@ export default function UserViewPage() { let nav = [{ name: "Users", path: "/users" }, { name: userName }]; if (!user) { - if (!synced) { - return - - - ; - } - - return - -

User with name {userName} was not found on the controller.

-
; + return ; } let roleSelector = (null); + // Kept in the URL with the users table state so back/forward restores it + const tableState = useTableQueryState({ namespace: "user" }); + const instanceParam = Number(tableState.filteredValue("instance")?.[0]); + const instanceId = Number.isInteger(instanceParam) ? instanceParam : null; return setInstanceId(value as number)} + onChange={value => tableState.commitFilter( + "instance", value === null ? null : [String(value)] + )} fieldDefinition={{ optional: true } as any} disabled={false} />} diff --git a/packages/web_ui/src/index.ts b/packages/web_ui/src/index.ts index 755b51f6..1b849be6 100644 --- a/packages/web_ui/src/index.ts +++ b/packages/web_ui/src/index.ts @@ -40,6 +40,7 @@ export { default as PageLayout } from "./components/PageLayout"; export { default as SavesList } from "./components/SavesList"; export { default as SectionHeader } from "./components/SectionHeader"; export { default as ResourceNotes } from "./components/ResourceNotes"; +export { default as ResourceState } from "./components/ResourceState"; export { default as Link } from "./components/Link"; @@ -48,3 +49,4 @@ export { default as FactorioIcon } from "./components/FactorioIcon"; export { default as useTableQueryState } from "./util/useTableQueryState"; export { default as useColumnSearch } from "./util/useColumnSearch"; export { default as useRowNavigation } from "./util/useRowNavigation"; +export { default as useResourceState, type ResourceStatus } from "./util/useResourceState"; diff --git a/packages/web_ui/src/model/host.ts b/packages/web_ui/src/model/host.ts index c6e28ff3..4be0d266 100644 --- a/packages/web_ui/src/model/host.ts +++ b/packages/web_ui/src/model/host.ts @@ -2,8 +2,8 @@ import { useCallback, useContext, useSyncExternalStore } from "react"; import ControlContext from "../components/ControlContext"; export function useHost(id?: number) { - const [hosts, synced] = useHosts(); - return [id !== undefined ? hosts.get(id) : undefined, synced] as const; + const [hosts, synced, error] = useHosts(); + return [id !== undefined ? hosts.get(id) : undefined, synced, error] as const; } export function useHosts() { @@ -11,3 +11,10 @@ export function useHosts() { const subscribe = useCallback((callback: () => void) => control.hosts.subscribe(callback), [control]); return useSyncExternalStore(subscribe, () => control.hosts.getSnapshot()); } + +/** Requests from hosts waiting to be approved, empty if the account may not approve hosts */ +export function useHostPairings() { + const control = useContext(ControlContext); + const subscribe = useCallback((callback: () => void) => control.hostPairings.subscribe(callback), [control]); + return useSyncExternalStore(subscribe, () => control.hostPairings.getSnapshot()); +} diff --git a/packages/web_ui/src/model/instance.ts b/packages/web_ui/src/model/instance.ts index 0ad6cb32..2537ef02 100644 --- a/packages/web_ui/src/model/instance.ts +++ b/packages/web_ui/src/model/instance.ts @@ -4,8 +4,8 @@ import { Config, InstanceConfigGetRequest } from "@clusterio/lib"; import ControlContext from "../components/ControlContext"; export function useInstance(id?: number) { - const [instances, synced] = useInstances(); - return [id !== undefined ? instances.get(id) : undefined, synced] as const; + const [instances, synced, error] = useInstances(); + return [id !== undefined ? instances.get(id) : undefined, synced, error] as const; } export function useInstances() { diff --git a/packages/web_ui/src/model/mod_pack.ts b/packages/web_ui/src/model/mod_pack.ts index a3b63bb2..c7e1c448 100644 --- a/packages/web_ui/src/model/mod_pack.ts +++ b/packages/web_ui/src/model/mod_pack.ts @@ -4,8 +4,8 @@ import { defaultModPackStore } from "../store/default_mod_pack_store"; export function useModPack(id?: number) { - const [modPacks, synced] = useModPacks(); - return [id !== undefined ? modPacks.get(id) : undefined, synced] as const; + const [modPacks, synced, error] = useModPacks(); + return [id !== undefined ? modPacks.get(id) : undefined, synced, error] as const; } export function useModPacks() { diff --git a/packages/web_ui/src/model/roles.ts b/packages/web_ui/src/model/roles.ts index 5e3bcffc..381472fc 100644 --- a/packages/web_ui/src/model/roles.ts +++ b/packages/web_ui/src/model/roles.ts @@ -12,8 +12,8 @@ export function useRolesOfUser(user?: lib.UserDetails) { } export function useRole(id?: number) { - const [roles, synced] = useRoles(); - return [id !== undefined ? roles.get(id) : undefined, synced] as const; + const [roles, synced, error] = useRoles(); + return [id !== undefined ? roles.get(id) : undefined, synced, error] as const; } export function useRoles() { diff --git a/packages/web_ui/src/model/user.tsx b/packages/web_ui/src/model/user.tsx index 86501102..1c965e13 100644 --- a/packages/web_ui/src/model/user.tsx +++ b/packages/web_ui/src/model/user.tsx @@ -89,8 +89,8 @@ export function sortLastSeen( } export function useUser(name?: string) { - const [users, synced] = useUsers(); - return [name !== undefined ? users.get(name.toLowerCase()) : undefined, synced] as const; + const [users, synced, error] = useUsers(); + return [name !== undefined ? users.get(name.toLowerCase()) : undefined, synced, error] as const; } export function useUsers() { diff --git a/packages/web_ui/src/store/export_locale_stores.ts b/packages/web_ui/src/store/export_locale_stores.ts index e15c6aa8..800c130e 100644 --- a/packages/web_ui/src/store/export_locale_stores.ts +++ b/packages/web_ui/src/store/export_locale_stores.ts @@ -24,19 +24,24 @@ class ExportLocaleStore { let response = await fetch(`${staticRoot}${cacheEntry.localePath}`); if (response.ok) { cacheEntry.data = new Map(await response.json() as ExportLocale); - for (const callback of cacheEntry.callbacks) { - callback(); - } } else { - notify( - `Failed to locale for mod pack ${modPackId}, server returned: ` + - `${response.status} ${response.statusText}` - ); + if (response.status === 404) { + logger.warn(`Locale for mod pack ${modPackId} is missing on the controller`); + } else { + notify( + `Failed to locale for mod pack ${modPackId}, server returned: ` + + `${response.status} ${response.statusText}` + ); + } + cacheEntry.data = new Map(); + } + for (const callback of cacheEntry.callbacks) { + callback(); } } subscribe(modPackId: number | undefined, localePath: string | undefined, callback: () => void) { - if (modPackId === undefined || !localePath) { + if (modPackId === undefined) { return () => {}; } diff --git a/packages/web_ui/src/store/export_prototype_metadata_store.ts b/packages/web_ui/src/store/export_prototype_metadata_store.ts index cd919658..1023363e 100644 --- a/packages/web_ui/src/store/export_prototype_metadata_store.ts +++ b/packages/web_ui/src/store/export_prototype_metadata_store.ts @@ -28,10 +28,14 @@ class ExportPrototypeMetadataStore { const response = await fetch(`${staticRoot}${cacheEntry.metadataPath}`); if (!response.ok) { - notify( - `Failed to fetch prototype metadata for mod pack ${modPackId}, server returned: ` + - `${response.status} ${response.statusText}` - ); + if (response.status === 404) { + logger.warn(`Prototype metadata for mod pack ${modPackId} is missing on the controller`); + } else { + notify( + `Failed to fetch prototype metadata for mod pack ${modPackId}, server returned: ` + + `${response.status} ${response.statusText}` + ); + } // eslint-disable-next-line node/no-sync cacheEntry.styleSheet.replaceSync(""); cacheEntry.metadata = new Map(); diff --git a/packages/web_ui/src/util/host_pairing.ts b/packages/web_ui/src/util/host_pairing.ts new file mode 100644 index 00000000..480a8455 --- /dev/null +++ b/packages/web_ui/src/util/host_pairing.ts @@ -0,0 +1,42 @@ +import * as lib from "@clusterio/lib"; + +/** + * Subscriber for the requests from hosts waiting to be approved + * + * The requests only live in the controller's memory and it does not tell + * subscribers about requests removed while nothing was subscribed, so they + * are cleared when subscribing again after the last handler unsubscribed. + */ +export class HostPairingSubscriber extends lib.MapSubscriber { + private _handlers = 0; + + /** + * @param control - Link to the controller. + * @param permitted - Returns true if the account may approve hosts. + */ + constructor(control: lib.Link, permitted: () => boolean) { + super(lib.HostPairingUpdatesEvent, control, undefined, permitted); + } + + override subscribe(handler: lib.EventSubscriberCallback) { + if (this._handlers === 0) { + this.values.clear(); + this.lastUpdatedMs = -1; + } + this._handlers += 1; + const unsubscribe = super.subscribe(handler); + let unsubscribed = false; + return () => { + if (unsubscribed) { + return; + } + unsubscribed = true; + unsubscribe(); + // Deferred like the unsubscribe in EventSubscriber, so moving between pages + // that both subscribe keeps the requests. + setTimeout(() => { + this._handlers -= 1; + }); + }; + } +} diff --git a/packages/web_ui/src/util/instance.ts b/packages/web_ui/src/util/instance.ts index b7f1f411..abf06622 100644 --- a/packages/web_ui/src/util/instance.ts +++ b/packages/web_ui/src/util/instance.ts @@ -9,3 +9,29 @@ export function instancePublicAddress(instance: lib.InstanceDetails, host?: lib. } return `${host.publicAddress}:${instance.gamePort}`; } + +export type ResolvedModPack = { + /** ID of the mod pack, undefined if the default is used and not known */ + id?: number; + modPack?: lib.ModPack; + isDefault: boolean; +}; + +/** Resolve the mod pack an instance starts with, falling back to the controller default */ +export function instanceModPack( + modPackId: number | undefined, + modPacks: ReadonlyMap, + defaultModPack?: lib.ModPack, +): ResolvedModPack { + if (modPackId !== undefined) { + return { id: modPackId, modPack: modPacks.get(modPackId), isDefault: false }; + } + if (!defaultModPack) { + return { isDefault: true }; + } + return { + id: defaultModPack.id, + modPack: modPacks.get(defaultModPack.id) ?? defaultModPack, + isDefault: true, + }; +} diff --git a/packages/web_ui/src/util/locale.ts b/packages/web_ui/src/util/locale.ts new file mode 100644 index 00000000..16181c0e --- /dev/null +++ b/packages/web_ui/src/util/locale.ts @@ -0,0 +1,160 @@ +import type { FactorioLocalisedString } from "@clusterio/lib"; + +type Locale = Map; + +const maxDepth = 20; +const prototypeReferences: Record = { + ENTITY: "entity-name", + ITEM: "item-name", + TILE: "tile-name", + FLUID: "fluid-name", +}; + +function substitute(locale: Locale, template: string, parameters: string[]) { + return template.replace(/__([A-Z_]+)__([^_\s][^\s]*?)__|__(\d+)__/g, (match, kind, name, index) => { + if (index !== undefined) { + return parameters[Number(index) - 1] ?? match; + } + const category = prototypeReferences[kind]; + return category ? locale.get(`${category}.${name}`) ?? name : match; + }); +} + +function resolve(locale: Locale, value: unknown, depth: number): string | undefined { + if (typeof value === "string") { + return value; + } + if (typeof value === "number" || typeof value === "boolean") { + return String(value); + } + if (!Array.isArray(value) || typeof value[0] !== "string" || depth > maxDepth) { + return undefined; + } + const [key, ...rest] = value; + if (key === "?") { + for (const alternative of rest) { + const result = resolve(locale, alternative, depth + 1); + if (result !== undefined) { + return result; + } + } + return undefined; + } + const parameters: string[] = []; + for (const parameter of rest) { + const result = resolve(locale, parameter, depth + 1); + if (result === undefined) { + return undefined; + } + parameters.push(result); + } + if (key === "") { + return parameters.join(""); + } + const template = locale.get(key); + return template === undefined ? undefined : substitute(locale, template, parameters); +} + +/** + * Resolve a Factorio LocalisedString against exported locale. + * + * @param locale - Flattened locale from the mod pack export. + * @param value - Localised string to resolve. + * @returns the resolved text, or undefined if a key used is missing from the locale. + * @see https://lua-api.factorio.com/stable/types/LocalisedString.html + */ +export function resolveLocalisedString(locale: Locale, value: FactorioLocalisedString) { + return resolve(locale, value, 0); +} + +const iconTags: Record = { + "item": "item-name", + "entity": "entity-name", + "fluid": "fluid-name", + "tile": "tile-name", + "recipe": "recipe-name", + "technology": "technology-name", + "item-group": "item-group-name", + "virtual-signal": "virtual-signal-name", + "space-location": "space-location-name", + "planet": "space-location-name", + "quality": "quality-name", +}; +const otherTags = [ + "color", "font", "img", "achievement", "gps", "special-item", "armor", "train", "train-stop", "tooltip", + "shortcut", "tip", +]; +const richTextPattern = new RegExp( + `\\[(?:/(?:color|font|tooltip)|(${[...Object.keys(iconTags), ...otherTags].join("|")})(?:=([^\\]]*))?)\\]`, + "g", +); + +/** + * Remove Factorio rich text tags from text, replacing icons of prototypes with their name. + * + * @param locale - Flattened locale from the mod pack export. + * @param text - Text that may contain rich text tags. + * @returns plain text + * @see https://wiki.factorio.com/Rich_text + */ +export function stripRichText(locale: Locale, text: string) { + return text.replace(richTextPattern, (_match, tag: string | undefined, value: string | undefined) => { + const category = tag ? iconTags[tag] : undefined; + if (!category || !value) { + return ""; + } + const name = value.split(",")[0]; + return locale.get(`${category}.${name}`) ?? name; + }).trim(); +} + +function localisedText(locale: Locale, localised: FactorioLocalisedString | undefined, key: string) { + let text: string | undefined; + if (localised !== undefined) { + text = resolveLocalisedString(locale, localised); + } + text ??= resolveLocalisedString(locale, [key]); + return text === undefined ? undefined : stripRichText(locale, text); +} + +type SettingPrototype = { + name: string, + localised_name?: FactorioLocalisedString, + localised_description?: FactorioLocalisedString, +}; + +/** + * Display name of a mod setting, falling back the same way Factorio does. + * + * @param locale - Flattened locale from the mod pack export. + * @param prototype - Mod setting prototype. + * @returns localised name, or the internal name if there is none. + */ +export function modSettingName(locale: Locale, prototype: SettingPrototype) { + return localisedText(locale, prototype.localised_name, `mod-setting-name.${prototype.name}`) || prototype.name; +} + +/** + * Description of a mod setting, falling back the same way Factorio does. + * + * @param locale - Flattened locale from the mod pack export. + * @param prototype - Mod setting prototype. + * @returns localised description, or undefined if there is none. + */ +export function modSettingDescription(locale: Locale, prototype: SettingPrototype) { + return localisedText( + locale, prototype.localised_description, `mod-setting-description.${prototype.name}` + ) || undefined; +} + +/** + * Display name of an allowed value of a string mod setting. + * + * @param locale - Flattened locale from the mod pack export. + * @param name - Internal name of the mod setting. + * @param value - Allowed value. + * @returns localised value, or the value itself if there is none. + */ +export function modSettingValueName(locale: Locale, name: string, value: string | number) { + return localisedText(locale, undefined, `string-mod-setting.${name}-${value}`) || String(value); +} diff --git a/packages/web_ui/src/util/mod_settings.ts b/packages/web_ui/src/util/mod_settings.ts new file mode 100644 index 00000000..e4361338 --- /dev/null +++ b/packages/web_ui/src/util/mod_settings.ts @@ -0,0 +1,67 @@ +import type * as lib from "@clusterio/lib"; + +export type ModSettingScope = "startup" | "runtime-global" | "runtime-per-user"; + +export type ModSettingField = { + name: string; + type: string; + mod?: string; + order?: string; + allowed_values?: unknown; + localised_name?: lib.FactorioLocalisedString; + localised_description?: lib.FactorioLocalisedString; +}; + +const settingTypes = ["bool-setting", "int-setting", "double-setting", "string-setting", "color-setting"]; +const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare; + +function typeFromValue(value: lib.ModSetting["value"]) { + if (typeof value === "boolean") { + return "bool-setting"; + } else if (typeof value === "number") { + return "double-setting"; + } else if (typeof value === "string") { + return "string-setting"; + } else if (typeof value === "object" && "r" in value) { + return "color-setting"; + } + throw Error(`Unhandled setting type ${typeof value}`); +} + +/** + * Split the settings of a scope into ones defined by the exported prototypes and stored ones + * no prototype defines. Without export data there is nothing to compare to, so none are unknown. + */ +export function modSettingFields( + prototypes: lib.ExportSettings | undefined, + scope: ModSettingScope, + stored: Map, +) { + const fromStored = (name: string): ModSettingField => ({ name, type: typeFromValue(stored.get(name)!.value) }); + if (!prototypes) { + return { known: [...stored.keys()].map(fromStored), unknown: [] }; + } + + const known: ModSettingField[] = Object.entries(prototypes) + .filter(([type]) => settingTypes.includes(type)) + .flatMap(([_, settings]) => Object.values(settings)) + .filter(p => p.setting_type === scope) + .map(p => ({ + name: p.name, + type: p.type, + mod: p.mod as string, + order: p.order, + allowed_values: p.allowed_values, + localised_name: p.localised_name, + localised_description: p.localised_description, + })) + .sort((a, b) => strcmp(a.mod, b.mod) || strcmp(a.order || "", b.order || "") || strcmp(a.name, b.name)) + ; + const knownNames = new Set(known.map(field => field.name)); + const unknown = [...stored.keys()] + .filter(name => !knownNames.has(name)) + .sort(strcmp) + .map(fromStored) + ; + return { known, unknown }; +} diff --git a/packages/web_ui/src/util/useResourceState.ts b/packages/web_ui/src/util/useResourceState.ts new file mode 100644 index 00000000..96d611d3 --- /dev/null +++ b/packages/web_ui/src/util/useResourceState.ts @@ -0,0 +1,37 @@ +import { useRef } from "react"; + +export type ResourceStatus = "loading" | "ok" | "missing" | "deleted" | "error"; + +export function getResourceStatus( + exists: boolean, + seen: boolean, + synced: boolean, + error: Error | null, +): ResourceStatus { + if (exists) { + return "ok"; + } + // A retry only clears the error when its response arrives, which can be after the update that synced it + if (synced) { + return seen ? "deleted" : "missing"; + } + return error ? "error" : "loading"; +} + +/** + * Status of the resource shown on a view page, for use with the ResourceState component + * + * @param value - The resource, undefined or null if the subscription does not have it. + * @param synced - The synced property from the subscription. + * @param error - The error property from the subscription. + * @param id - Identifies the resource shown, the router reuses the page when navigating between resources. + * @returns "ok" if there is a value to show, otherwise why there isn't. + */ +export default function useResourceState(value: unknown, synced: boolean, error: Error | null, id: number | string) { + const seenId = useRef(undefined); + const exists = value !== undefined && value !== null; + if (exists) { + seenId.current = id; + } + return getResourceStatus(exists, seenId.current === id, synced, error); +} diff --git a/packages/web_ui/src/util/websocket.ts b/packages/web_ui/src/util/websocket.ts index 20d3b8eb..805899a4 100644 --- a/packages/web_ui/src/util/websocket.ts +++ b/packages/web_ui/src/util/websocket.ts @@ -1,9 +1,16 @@ import * as lib from "@clusterio/lib"; import packageJson from "../../package.json"; import * as WebPlugin from "../BaseWebPlugin"; +import { HostPairingSubscriber } from "./host_pairing"; const { logFilter, logger } = lib; +function rolesHavePermission(roles: lib.AccountRole[] | null, permission: lib.PermissionName) { + return (roles ?? []).some( + role => role.permissions.includes("core.admin") || role.permissions.includes(permission) + ); +} + type accountHandler = (account: lib.AccountDetails) => void; type hostHandler = (hostDetails: lib.HostDetails) => void; type instanceHandler = (instanceDetails: lib.InstanceDetails) => void; @@ -67,6 +74,7 @@ export class Control extends lib.Link { /** Updates handled by the subscription service */ systems = new lib.MapSubscriber(lib.SystemInfoUpdateEvent, this); hosts = new lib.MapSubscriber(lib.HostUpdatesEvent, this); + hostPairings = new HostPairingSubscriber(this, () => rolesHavePermission(this.accountRoles, "core.host.approve")); instances = new lib.MapSubscriber(lib.InstanceDetailsUpdatesEvent, this); saves = new lib.MapSubscriber(lib.InstanceSaveDetailsUpdatesEvent, this); modPacks = new lib.MapSubscriber(lib.ModPackUpdatesEvent, this); diff --git a/plugins/player_auth/test/plugin.js b/plugins/player_auth/test/plugin.js index d419bad5..274c9014 100644 --- a/plugins/player_auth/test/plugin.js +++ b/plugins/player_auth/test/plugin.js @@ -174,9 +174,7 @@ describe("player_auth", function() { addInstance(8, "running", true, "invalid host", "1.1.8", 34197, 2); addInstance(9, "running", true, "no version", undefined, 34197); - mockController.hosts.set(1, { - publicAddress: "127.0.0.1", - }); + mockController.hosts.records.set({ id: 1, publicAddress: "127.0.0.1" }); const result = await fetch(`${controllerUrl}/api/player_auth/servers`); assert.deepEqual(await result.json(), [ diff --git a/plugins/player_sync/README.md b/plugins/player_sync/README.md index 5f7c16c3..5c663358 100644 --- a/plugins/player_sync/README.md +++ b/plugins/player_sync/README.md @@ -77,8 +77,12 @@ The greatly simplified data flow is as follows: 7. Scenario displays and updates a progress bar as each chunk is received. 8. Once all chunks have loaded the player's synced inventory is recreated from the data and the player can start playing. +While the player is a spectator waiting for the data they can look around, and their controller comes back where it was. +A mod that teleports the spectator more than 16 tiles, or to another surface, moves where the controller comes back to. + When the player leaves the inventory is uploaded if it's a synced inventory and the exclusive access the scenario script holds is released. Should an error occur during this process the player is given the option to use a temporary inventory instead, which will be merged back into the synced inventory the next time the sync succeeds on that instance. +A download that stops part way, for example because the controller went down, is started over the next time the player joins, and nothing is uploaded for the player until it finishes. Instances can leave parts of the player out of the sync with the `player_sync.sync_*` options below. A part which is not synced is left as it is when the player joins, and the instance's copy of it is not uploaded, so the stored copy from other instances stays as it was. diff --git a/plugins/player_sync/controller.ts b/plugins/player_sync/controller.ts index 0df18cb1..a94800cc 100644 --- a/plugins/player_sync/controller.ts +++ b/plugins/player_sync/controller.ts @@ -63,7 +63,7 @@ async function saveDatabase( let file = path.resolve(controllerConfig.get("controller.database_directory"), "player_sync.json"); logger.verbose(`writing ${file}`); let content = JSON.stringify([...playerDatastore, ...tombstones]); - await lib.safeOutputFile(file, content); + await lib.atomicOverwriteFile(file, content); } export default async function(context: ControllerPluginContext) { diff --git a/plugins/player_sync/instance.ts b/plugins/player_sync/instance.ts index 30ed0223..4c185527 100644 --- a/plugins/player_sync/instance.ts +++ b/plugins/player_sync/instance.ts @@ -87,6 +87,22 @@ export function recipeNotificationDelta(stored: string[], current: string[]): Re return delta; } +/** + * Decode a list of cleared recipe names, Factorio serializes an empty list as {} + * @param encoded - Encoded JSON list of recipe names + * @returns the recipe names + */ +async function decodeRecipeNames(encoded: string): Promise { + const names = JSON.parse(await decodeLuaString(encoded)); + if (Array.isArray(names)) { + return names; + } + if (names !== null && typeof names === "object" && Object.keys(names).length === 0) { + return []; + } + throw new Error(`Expected a list of recipe names, got ${JSON.stringify(names)}`); +} + /** * Replace the stored recipe notifications with the difference from the * current state on the instance to reduce the amount of data sent to Lua. @@ -101,9 +117,9 @@ export async function applyRecipeNotificationDelta( return; } try { - const stored = JSON.parse(await decodeLuaString(playerData.recipe_notifications)); + const stored = await decodeRecipeNames(playerData.recipe_notifications); const delta: RecipeNotificationDelta = current - ? recipeNotificationDelta(stored, JSON.parse(await decodeLuaString(current))) + ? recipeNotificationDelta(stored, await decodeRecipeNames(current)) : { ...recipeNotificationDelta(stored, []), full: true }; playerData.recipe_notifications = await encodeLuaString(JSON.stringify(delta)); } catch (err: any) { diff --git a/plugins/player_sync/module/gui/dialog_failed_download.lua b/plugins/player_sync/module/gui/dialog_failed_download.lua index 1884d007..52b07a28 100644 --- a/plugins/player_sync/module/gui/dialog_failed_download.lua +++ b/plugins/player_sync/module/gui/dialog_failed_download.lua @@ -1,4 +1,5 @@ local ensure_character = require("modules/player_sync/ensure_character") +local restore_position = require("modules/player_sync/restore_position") local get_script_data = require("modules/player_sync/get_script_data") local dialog_failed_download = {} @@ -129,10 +130,15 @@ dialog_failed_download.events = { ensure_character(player) local player_sync = get_script_data() player.gui.screen.dialog_failed_download.destroy() - player_sync.players[player.name].dirty = true - player_sync.players[player.name].sync = false - player_sync.players[player.name].sync_in_progress = false - player_sync.players[player.name].local_controller = nil + local player_record = player_sync.players[player.name] + if player_record.restore_location then + restore_position(player, player_record.restore_location) + end + player_record.dirty = true + player_record.sync = false + player_record.sync_in_progress = false + player_record.local_controller = nil + player_record.restore_location = nil elseif event.element.name == "player_sync_failed_download_retry" then -- Retry acquiring the player from the controller diff --git a/plugins/player_sync/module/player_sync.lua b/plugins/player_sync/module/player_sync.lua index 1ee077f2..b2df31b6 100644 --- a/plugins/player_sync/module/player_sync.lua +++ b/plugins/player_sync/module/player_sync.lua @@ -73,27 +73,48 @@ local function remove_inventory_bonus_raise(script_data, player_name) end end +-- Where the player's controller is, in the shape restore_position takes +local function controller_location(player) + local location = { vehicle = player.driving and player.vehicle or nil } + if v2_remote_controller then + location.surface = player.physical_surface + location.position = player.physical_position + else + location.surface = player.surface + location.position = player.position + end + return location +end + +-- Copy a location, with where a spectator was last seen, into target +local function copy_location(target, location) + target.surface = location.surface + target.position = location.position + target.vehicle = location.vehicle + target.last_surface = location.last_surface + target.last_position = location.last_position + return target +end + -- Turn a synced player into a spectator while their player data is downloaded or applied, if this instance syncs --- inventories, and keep where their body stood in record for restore_position. The old body goes, with its crafting --- queue. Until the data is applied, the player's state isn't persisted. +-- inventories, and keep the controller's location in record for restore_position. The old controller goes, with its +-- crafting queue. Until the data is applied, the player's state isn't persisted. local function spectate(player, player_record, record) -- Indicate the current state shouldn't be persisted player_record.sync_in_progress = true + -- A dropped download already took the controller, and kept its location + local kept = player_record.restore_location + player_record.restore_location = nil + if kept and record.position == nil then + copy_location(record, kept) + end + if player_record.sync and serialize.syncs(record.components, "inventories") then -- Store original position to teleport back to. Only once per record: a rejoin while a prefetched copy is held - -- spectates again, and the spectator's position then isn't where the body stood + -- spectates again, and the spectator's position then isn't where the controller was if record.position == nil then - if v2_remote_controller then - record.surface = player.physical_surface - record.position = player.physical_position - else - record.surface = player.surface - record.position = player.position - end - if player.driving then - record.vehicle = player.vehicle - end + copy_location(record, controller_location(player)) end save_local_controller(player, player_record, record.components) @@ -103,6 +124,32 @@ local function spectate(player, player_record, record) end end +-- Sync code took the player's controller and hasn't given one back: a download that never finished, or a failed +-- acquire. The local state is gone whatever the generations say. +local function controller_taken(player_record) + return player_record.sync_in_progress or player_record.local_controller ~= nil + or player_record.restore_location ~= nil +end + +-- Keep the controller's location when a download record that took it is dropped, for the download or abort that follows +local function keep_restore_location(player_record, record) + if player_record and record.position ~= nil then + player_record.restore_location = copy_location({}, record) + end +end + +-- Where the controller goes back when sync code gives it back, if it took it +local function find_restore_location(script_data, player_name) + for _, downloads in ipairs({ script_data.active_downloads, script_data.finished_downloads }) do + local record = downloads[player_name] + if record and record.position ~= nil then + return record + end + end + local player_record = script_data.players[player_name] + return player_record and player_record.restore_location +end + player_sync = {} -- This function is called by instance.js as /sc player_sync.download_inventory("danielv", Escaped JSON string, package_number, total_packages_count) with data from the controller @@ -209,7 +256,9 @@ function player_sync.deserialize_player(player, finished_record) -- An earlier raise not removed yet is replaced, the character's inventory bonus is restored with the data script_data.inventory_bonus_raises[player.name] = nil local failed, spill, inventory_bonus_raise = - serialize.deserialize_player(player, serialized_player, finished_record.components, local_controller) + serialize.deserialize_player( + player, serialized_player, finished_record.components, local_controller, finished_record.recipe_notifications + ) script_data.failed_deserialization[player.name] = failed player_record.local_controller = nil if inventory_bonus_raise and inventory_bonus_raise > 0 then @@ -372,19 +421,17 @@ function player_sync.sync_player(acquire_response) -- restart path below, which only sees a different generation or epoch. A copy this save doesn't need goes too, -- keeping the local data: an upload from an instance with older data can take the generation this save already -- holds. - -- A copy confirmed at an earlier join already took the body (spectate keeps where it stood), and the local data + -- A copy confirmed at an earlier join already took the controller (spectate keeps its location), and the local data -- went with it, so a join that drops that copy downloads. - local body_taken -- the dropped copy that took the body + local player_record = script_data.players[acquire_response.player_name] for _, downloads in ipairs({ script_data.finished_downloads, script_data.active_downloads }) do local record = downloads[acquire_response.player_name] if record and record.prefetch and (not ( acquire_response.status == "acquired" and record.generation == acquire_response.generation and (record.epoch or 0) == epoch and record.token == acquire_response.token and serialize.same_components(record.components, script_data.components) - ) or not download_needed(script_data.players[acquire_response.player_name], acquire_response, script_data)) then - if record.position ~= nil then - body_taken = record - end + ) or not download_needed(player_record, acquire_response, script_data)) then + keep_restore_location(player_record, record) downloads[acquire_response.player_name] = nil end end @@ -397,7 +444,7 @@ function player_sync.sync_player(acquire_response) and (finished_record.epoch or 0) == epoch then if finished_record.prefetch then - -- As a download does: the body left here goes, and the copy makes a new character where it stood + -- As a download does: the controller left here goes, and the copy makes a new character in its location spectate(player, script_data.players[player.name], finished_record) if player_sync.finish_download(player, finished_record) then log("Applied prefetched player data for " .. player.name) @@ -456,17 +503,18 @@ function player_sync.sync_player(acquire_response) if acquire_response.status == "busy" then -- Somehow another instance has claimed the player while we're -- downloading it. Abort it and send failure to the player. + keep_restore_location(player_record, download_record) script_data.active_downloads[acquire_response.player_name] = nil end end - local player_record = script_data.players[acquire_response.player_name] if acquire_response.status ~= "acquired" then if player_record.sync and (not player_record.dirty or player_record.sync_in_progress) then if serialize.syncs(player_record.components, "inventories") and player.controller_type == defines.controllers.character then save_local_controller(player, player_record, player_record.components) + player_record.restore_location = controller_location(player) local character = player.character player.set_controller({ type = defines.controllers.spectator }) if character then character.destroy() end @@ -479,15 +527,9 @@ function player_sync.sync_player(acquire_response) end local stale = (player_record.epoch or 0) ~= epoch - if body_taken or download_needed(player_record, acquire_response, script_data) then + -- Without stored data the download gives the player an empty character (download_inventory, total 0) + if controller_taken(player_record) or download_needed(player_record, acquire_response, script_data) then player_sync.initiate_inventory_download(player, player_record, acquire_response.generation, epoch) - if body_taken then - -- spectate kept the spectator's place, the body stood where the dropped copy kept - local download = script_data.active_downloads[player.name] - download.surface = body_taken.surface - download.position = body_taken.position - download.vehicle = body_taken.vehicle - end else if acquire_response.generation == 0 then @@ -553,6 +595,32 @@ player_sync.events[defines.events.on_player_joined_game] = function(event) script_data.active_uploads[player.name] = nil end +-- A spectator whose controller sync code took may look around. A jump of more than 16 tiles from where it was last +-- seen, or to another surface, is another mod's teleport and moves the restore location. +player_sync.events[defines.events.on_player_changed_position] = function(event) + local player = assert(game.get_player(event.player_index)) + if player.controller_type ~= defines.controllers.spectator then + return + end + local location = find_restore_location(get_script_data(), player.name) + if not location then + return + end + + local position = player.position --[[@as MapPosition.struct]] + local last_surface = location.last_surface or location.surface + local last_position = location.last_position or location.position + local dx = position.x - last_position.x + local dy = position.y - last_position.y + if player.surface ~= last_surface or dx * dx + dy * dy > 16 * 16 then + location.surface = player.surface + location.position = position + location.vehicle = nil + end + location.last_surface = player.surface + location.last_position = position +end + -- Raised for a restored armor after its equipment's inventory bonus applied, the temporary bonus is no longer needed player_sync.events[defines.events.on_player_armor_inventory_changed] = function(event) local player = assert(game.get_player(event.player_index)) @@ -605,7 +673,7 @@ player_sync.events[defines.events.on_pre_player_left_game] = function(event) return end - if not player_record.dirty or not player_record.sync or player_record.sync_in_progress then + if not player_record.dirty or not player_record.sync or controller_taken(player_record) then -- Nothing to upload, release the acquisition so other instances are not blocked clusterio_api.send_json("player_sync_release", { player_name = player.name }) return @@ -675,6 +743,8 @@ function player_sync.initiate_inventory_download(player, player_record, generati recipe_notifications = serialize.serialize_crafting_notifications(player) end + -- Kept to rebuild the stored list from the delta once the player's force is restored + record.recipe_notifications = recipe_notifications clusterio_api.send_json("player_sync_download", { player_name = player.name, recipe_notifications = recipe_notifications, @@ -692,6 +762,8 @@ function player_sync.check_active_downloads() for player_name, record in pairs(script_data.active_downloads) do if record.last_active <= game.ticks_played - 600 then script_data.active_downloads[player_name] = nil + -- sync_in_progress stays set, so the next acquire downloads again + keep_restore_location(script_data.players[player_name], record) local player = game.get_player(player_name) if player then log("ERROR: Inventory download failed for " .. player_name) @@ -765,11 +837,11 @@ function player_sync.prefetch_inventory(player_name, generation, data, number, t rcon.print("Refused prefetch for " .. player_name .. ": generation " .. generation .. " is not newer") return end - -- A held copy (or offline-finished download) whose join took the body knows where it stood, and that the body - -- is gone (sync_player's body_taken): the copy replacing it keeps both + -- A held copy (or offline-finished download) whose join took the controller knows its location, and that the + -- controller is gone (sync_player's controller_taken): the copy replacing it keeps both local held = active or finished script_data.finished_downloads[player_name] = nil - script_data.active_downloads[player_name] = { + local copy = { started = game.ticks_played, last_active = game.ticks_played, generation = generation, @@ -778,10 +850,11 @@ function player_sync.prefetch_inventory(player_name, generation, data, number, t token = token, epoch = epoch, components = components and compat.json_to_table(components), - surface = held and held.surface, - position = held and held.position, - vehicle = held and held.vehicle, } + if held then + copy_location(copy, held) + end + script_data.active_downloads[player_name] = copy end local record = script_data.active_downloads[player_name] diff --git a/plugins/player_sync/module/serialize.lua b/plugins/player_sync/module/serialize.lua index 7a79d9ed..cab17c6d 100644 --- a/plugins/player_sync/module/serialize.lua +++ b/plugins/player_sync/module/serialize.lua @@ -863,29 +863,36 @@ function serialize.deserialize_crafting_queue(player, serialized) player.crafting_queue_progress = serialized.crafting_queue_progress end +--- @param player LuaPlayer +--- @return table enabled Recipes which can have a notification on this server +--- @return table cleared Enabled recipes without a notification +local function crafting_notification_state(player) + local enabled = {} + local cleared = {} + for _, recipe in pairs(player.force.recipes) do + if recipe.enabled and not recipe.hidden then + enabled[recipe.name] = true + cleared[recipe.name] = true + end + end + for _, recipe in pairs(player.get_recipe_notifications()) do + cleared[recipe.name] = nil + end + return enabled, cleared +end + ---@param player LuaPlayer ---@param failed string[]? ---@return string? function serialize.serialize_crafting_notifications(player, failed) - -- Get all unlocked recipes - local recipes = {} - for _, recipe in pairs(player.force.recipes) do - if recipe.enabled and not recipe.hidden then - recipes[recipe.name] = true - end - end - - -- Remove those with notifications - for _, recipe in pairs(player.get_recipe_notifications()) do - recipes[recipe.name] = nil - end + local _, cleared = crafting_notification_state(player) -- Convert to a list of names, including previously failed recipes if any local recipe_names = {} for _, name in ipairs(failed or {}) do recipe_names[#recipe_names + 1] = name end - for name in pairs(recipes) do + for name in pairs(cleared) do recipe_names[#recipe_names + 1] = name end @@ -893,57 +900,53 @@ function serialize.serialize_crafting_notifications(player, failed) end --- @class CraftingNotificationDelta ---- @field add string[]? Recipes cleared elsewhere that still have a notification here ---- @field remove string[]? Recipes with a notification elsewhere that are cleared here +--- @field add string[]? Stored recipes missing from the cleared list sent with the download request +--- @field remove string[]? Recipes in the sent list that are not stored --- @field full boolean? add is the whole stored list, sent without this save's (a prefetched copy) --- @param player LuaPlayer ---- @param serialized string Encoded delta against the state sent with the download request +--- @param serialized string Encoded delta against the cleared list sent with the download request +--- @param sent string? That list, as sent. Without it the delta applies to the player's current list --- @return string[]? failed Recipe names that do not exist -function serialize.deserialize_crafting_notifications(player, serialized) +function serialize.deserialize_crafting_notifications(player, serialized, sent) --- @type CraftingNotificationDelta local delta = helpers.json_to_table(assert(helpers.decode_string(serialized))) assert(type(delta) == "table", "wrong type decoded from json_to_table") + local enabled, cleared_here = crafting_notification_state(player) - -- Recipes which can have a notification on this server - local enabled = {} - for _, recipe in pairs(player.force.recipes) do - if recipe.enabled and not recipe.hidden then - enabled[recipe.name] = true - end - end - - -- Clear notifications the player has cleared elsewhere, this means "add seen notification" - local failed = {} - for _, recipe_name in pairs(delta.add or {}) do - if enabled[recipe_name] then - player.clear_recipe_notification(recipe_name) - else - failed[#failed + 1] = recipe_name -- Recipe does not exist on this server - end - end - - -- Add notifications the player has elsewhere, this means "remove seen notification" - for _, recipe_name in pairs(delta.remove or {}) do - if enabled[recipe_name] then - player.add_recipe_notification(recipe_name) - end - end - - -- A full delta has no remove: recipes cleared here that aren't in add get their notification back, as remove does - if delta.full then - local stored = {} - for _, recipe_name in pairs(delta.add or {}) do - stored[recipe_name] = true - end - local notified = {} - for _, recipe in pairs(player.get_recipe_notifications()) do - notified[recipe.name] = true - end - for recipe_name in pairs(enabled) do - if not stored[recipe_name] and not notified[recipe_name] then - player.add_recipe_notification(recipe_name) + -- Rebuild the stored list, then merge it against the force the player has now + local stored = {} + if not delta.full then + if sent then + local sent_names = helpers.json_to_table(assert(helpers.decode_string(sent))) + assert(type(sent_names) == "table", "wrong type decoded from json_to_table") + for _, recipe_name in pairs(sent_names) do + stored[recipe_name] = true end + else + for recipe_name in pairs(cleared_here) do + stored[recipe_name] = true + end + end + for _, recipe_name in pairs(delta.remove or {}) do + stored[recipe_name] = nil + end + end + for _, recipe_name in pairs(delta.add or {}) do + stored[recipe_name] = true + end + + local failed = {} + for recipe_name in pairs(stored) do + if not enabled[recipe_name] then + failed[#failed + 1] = recipe_name -- Recipe does not exist on this server + elseif not cleared_here[recipe_name] then + player.clear_recipe_notification(recipe_name) + end + end + for recipe_name in pairs(cleared_here) do + if not stored[recipe_name] then + player.add_recipe_notification(recipe_name) end end @@ -1287,9 +1290,10 @@ end --- @param serialized SerializedPlayerData --- @param components SyncComponents --- @param local_controller LocalControllerState? Controller to restore when the controller is not synced +--- @param sent_recipe_notifications string? Cleared recipes sent with the download request --- @return FailedDeserializationPlayerData?, table[]? Serialized stacks which did not fit, see spill_items --- @return integer? inventory_bonus_raise See raise_inventory_bonus -function serialize.deserialize_player(player, serialized, components, local_controller) +function serialize.deserialize_player(player, serialized, components, local_controller, sent_recipe_notifications) local failed_deserialization = {} local sync_controller = syncs(components, "controller") local sync_inventories = syncs(components, "inventories") @@ -1448,8 +1452,9 @@ function serialize.deserialize_player(player, serialized, components, local_cont -- Deserialize recipe notifications if recipe_notifications_api and syncs(components, "recipe_notifications") and serialized.recipe_notifications then - failed_deserialization.recipe_notifications = - serialize.deserialize_crafting_notifications(player, serialized.recipe_notifications) + failed_deserialization.recipe_notifications = serialize.deserialize_crafting_notifications( + player, serialized.recipe_notifications, sent_recipe_notifications + ) end return next(failed_deserialization) and failed_deserialization or nil, spill, inventory_bonus_raise diff --git a/plugins/player_sync/test/instance.js b/plugins/player_sync/test/instance.js index 12209271..67132ce6 100644 --- a/plugins/player_sync/test/instance.js +++ b/plugins/player_sync/test/instance.js @@ -64,6 +64,29 @@ describe("player_sync", function() { await apply(playerData, undefined); assert.deepEqual(await decode(playerData.recipe_notifications), { full: true }); }); + // helpers.table_to_json in Factorio encodes an empty list as {} + it("should treat an empty current list encoded as {} as empty", async function() { + const playerData = { name: "test", recipe_notifications: await encode(["a", "b"]) }; + await apply(playerData, await encode({})); + assert.deepEqual(await decode(playerData.recipe_notifications), { add: ["a", "b"] }); + }); + it("should treat an empty stored list encoded as {} as empty", async function() { + const playerData = { name: "test", recipe_notifications: await encode({}) }; + await apply(playerData, await encode(["a"])); + assert.deepEqual(await decode(playerData.recipe_notifications), { remove: ["a"] }); + }); + it("should mark an empty stored list encoded as {} full without a current list", async function() { + const playerData = { name: "test", recipe_notifications: await encode({}) }; + await apply(playerData, undefined); + assert.deepEqual(await decode(playerData.recipe_notifications), { full: true }); + }); + it("should drop the field when the list is a non-empty object", async function() { + const playerData = { name: "test", recipe_notifications: await encode({ a: 1 }) }; + const count = warnings.length; + await apply(playerData, await encode(["a"])); + assert.equal(playerData.recipe_notifications, undefined); + assert.equal(warnings.length, count + 1); + }); it("should do nothing without stored notifications", async function() { const playerData = { name: "test" }; await apply(playerData, await encode(["a"])); @@ -71,9 +94,10 @@ describe("player_sync", function() { }); it("should drop the field on invalid input", async function() { const playerData = { name: "test", recipe_notifications: "not base64 zlib" }; + const count = warnings.length; await apply(playerData, await encode(["a"])); assert.equal(playerData.recipe_notifications, undefined); - assert.equal(warnings.length, 1); + assert.equal(warnings.length, count + 1); }); }); diff --git a/plugins/research_sync/README.md b/plugins/research_sync/README.md index 767ed5e6..e4ed6720 100644 --- a/plugins/research_sync/README.md +++ b/plugins/research_sync/README.md @@ -16,7 +16,8 @@ It is on by default. The first server to turn following on with something queued shares its queue as the cluster queue, and servers that turn it on after that take the cluster's. A server's first start counts as turning it on; a later restart takes the cluster queue, even an empty one. Whenever the cluster queue is empty (for example, everything in it has finished), the next server that turns following on shares its queue again. -Every change to the cluster queue prints a chat line on every server. +Every change to the cluster queue prints a chat line on every server naming the technologies added, removed or moved, with the level each queued entry researches. +Entries dropped because their research finished only print the "Researched" line. It needs Factorio 2.0.56 or later, older servers ignore the queue. To turn it off without the GUI, run `/sc research_sync.set_follow(false)` on that server. diff --git a/plugins/research_sync/controller.ts b/plugins/research_sync/controller.ts index 3f29a3a3..f390c3cb 100644 --- a/plugins/research_sync/controller.ts +++ b/plugins/research_sync/controller.ts @@ -15,6 +15,7 @@ import { TechnologyProgress, QueueUpdateEvent, QueueEvent, + QueueChange, QueueSyncRequest, } from "./messages.js"; @@ -49,7 +50,7 @@ async function saveTechnologies( ) { let filePath = path.join(controllerConfig.get("controller.database_directory"), "technologies.json"); logger.verbose(`writing ${filePath}`); - await lib.safeOutputFile(filePath, JSON.stringify([...technologies.entries()], null, "\t")); + await lib.atomicOverwriteFile(filePath, JSON.stringify([...technologies.entries()], null, "\t")); } const MAX_QUEUE = 7; @@ -71,7 +72,60 @@ async function loadQueue(controllerConfig: lib.ControllerConfig, logger: lib.Log async function saveQueue(controllerConfig: lib.ControllerConfig, queue: string[], logger: lib.Logger) { let filePath = path.join(controllerConfig.get("controller.database_directory"), "research_queue.json"); logger.verbose(`writing ${filePath}`); - await lib.safeOutputFile(filePath, JSON.stringify(queue, null, "\t")); + await lib.atomicOverwriteFile(filePath, JSON.stringify(queue, null, "\t")); +} + +/** + * Lists the entries removed, added and moved between two queues. An entry is identified by its name and how many + * entries for the same name come before it, so extra levels of an infinite technology count as added or removed + * at the end. Moved entries are those outside the longest common subsequence of the kept entries. + */ +export function queueChanges(oldQueue: string[], newQueue: string[]): QueueChange[] { + function keyed(queue: string[]) { + const seen = new Map(); + return queue.map((name, index) => { + const offset = seen.get(name) ?? 0; + seen.set(name, offset + 1); + return { name, offset, position: index + 1, key: `${offset}:${name}` }; + }); + } + const oldEntries = keyed(oldQueue); + const newEntries = keyed(newQueue); + const oldKeys = new Set(oldEntries.map(e => e.key)); + const newKeys = new Set(newEntries.map(e => e.key)); + const keptOld = oldEntries.filter(e => newKeys.has(e.key)); + const keptNew = newEntries.filter(e => oldKeys.has(e.key)); + + // lcs[i][j] is the length of the longest common subsequence of keptOld[i..] and keptNew[j..] + const lcs = Array.from({ length: keptOld.length + 1 }, () => new Array(keptNew.length + 1).fill(0)); + for (let i = keptOld.length - 1; i >= 0; i--) { + for (let j = keptNew.length - 1; j >= 0; j--) { + lcs[i][j] = keptOld[i].key === keptNew[j].key + ? lcs[i + 1][j + 1] + 1 + : Math.max(lcs[i + 1][j], lcs[i][j + 1]); + } + } + const inPlace = new Set(); + for (let i = 0, j = 0; i < keptOld.length && j < keptNew.length;) { + if (keptOld[i].key === keptNew[j].key) { + inPlace.add(keptOld[i].key); + i += 1; + j += 1; + } else if (lcs[i + 1][j] >= lcs[i][j + 1]) { + i += 1; + } else { + j += 1; + } + } + + const change = (type: QueueChange["type"], e: { name: string, offset: number, position: number }) => ( + new QueueChange(type, e.name, e.offset, e.position) + ); + return [ + ...oldEntries.filter(e => !newKeys.has(e.key)).map(e => change("removed", e)), + ...newEntries.filter(e => !oldKeys.has(e.key)).map(e => change("added", e)), + ...keptNew.filter(e => !inPlace.has(e.key)).map(e => change("moved", e)), + ]; } export default async function(context: ControllerPluginContext) { @@ -112,9 +166,10 @@ export default async function(context: ControllerPluginContext) { if (newQueue.length === queue.length && newQueue.every((name, i) => name === queue[i])) { return; } + const changes = queueChanges(queue, newQueue); queue = newQueue; queueDirty = true; - controller.sendTo("allInstances", new QueueEvent(queue, player, instanceName(src))); + controller.sendTo("allInstances", new QueueEvent(queue, player, instanceName(src), changes)); } function broadcastProgress() { diff --git a/plugins/research_sync/instance.ts b/plugins/research_sync/instance.ts index 464e91ea..95406481 100644 --- a/plugins/research_sync/instance.ts +++ b/plugins/research_sync/instance.ts @@ -8,6 +8,7 @@ import { SyncTechnologiesRequest, QueueUpdateEvent, QueueEvent, + QueueChange, QueueSyncRequest, } from "./messages.js"; @@ -22,6 +23,7 @@ type IpcFinished = { level: number, }; type IpcQueue = { queue: unknown, player?: string }; +type ApplyQueue = { queue: string[], instance?: string, player?: string, changes?: QueueChange[] }; export default async function(context: InstancePluginContext) { const { instance, host, logger, plugin } = context; @@ -49,7 +51,7 @@ export default async function(context: InstancePluginContext) { return Array.isArray(v) ? v : []; } - async function applyQueue(data: { queue: string[], instance?: string, player?: string }) { + async function applyQueue(data: ApplyQueue) { await sendOrderedRcon(`/sc research_sync.apply_queue("${lib.escapeString(JSON.stringify(data))}")`, true); } @@ -177,13 +179,16 @@ export default async function(context: InstancePluginContext) { if (!syncStarted || !["starting", "running"].includes(instance.status)) { return; } - let data: { queue: string[], instance?: string, player?: string } = { queue: event.queue }; + let data: ApplyQueue = { queue: event.queue }; if (event.instance !== null) { data.instance = event.instance; } if (event.player !== null) { data.player = event.player; } + if (event.changes?.length) { + data.changes = event.changes; + } queueEventsApplied += 1; await applyQueue(data); }); diff --git a/plugins/research_sync/messages.ts b/plugins/research_sync/messages.ts index 58d5a38d..31882b8f 100644 --- a/plugins/research_sync/messages.ts +++ b/plugins/research_sync/messages.ts @@ -160,6 +160,29 @@ export class QueueUpdateEvent { } } +export class QueueChange { + constructor( + public type: "added" | "removed" | "moved", + public name: string, + /** Entries for the same technology before this one, the level above the first queued level */ + public offset: number, + /** 1-based position in the new queue, or in the old queue for removed */ + public position: number, + ) { + } + + static jsonSchema = Type.Object({ + "type": Type.Union([Type.Literal("added"), Type.Literal("removed"), Type.Literal("moved")]), + "name": Type.String(), + "offset": Type.Integer(), + "position": Type.Integer(), + }); + + static fromJSON(json: Static): QueueChange { + return new this(json.type, json.name, json.offset, json.position); + } +} + export class QueueEvent { declare ["constructor"]: typeof QueueEvent; static type = "event" as const; @@ -171,6 +194,8 @@ export class QueueEvent { public queue: string[], public player: string | null, public instance: string | null, + /** What changed, null for a silent update or an older controller */ + public changes: QueueChange[] | null = null, ) { } @@ -178,10 +203,16 @@ export class QueueEvent { "queue": Type.Array(Type.String()), "player": Type.Union([Type.String(), Type.Null()]), "instance": Type.Union([Type.String(), Type.Null()]), + "changes": Type.Optional(Type.Union([Type.Array(QueueChange.jsonSchema), Type.Null()])), }); static fromJSON(json: Static): QueueEvent { - return new this(json.queue, json.player, json.instance); + return new this( + json.queue, + json.player, + json.instance, + json.changes ? json.changes.map(c => QueueChange.fromJSON(c)) : null, + ); } } diff --git a/plugins/research_sync/module/sync.lua b/plugins/research_sync/module/sync.lua index 3b675c43..f6087464 100644 --- a/plugins/research_sync/module/sync.lua +++ b/plugins/research_sync/module/sync.lua @@ -177,17 +177,43 @@ local function write_queue(force, names) end end ---- @param names string[] ---- @return string -local function format_queue(names) - if #names == 0 then - return "(empty)" +--- localised_name of a levelled technology includes its current level, so build the name with the given level +--- @param tech LuaTechnology +--- @param level number +--- @return LocalisedString +local function technology_label(tech, level) + if tech.name:find("-%d+$") then + return {"", {"technology-name." .. tech.name:gsub("-%d+$", "")}, " ", level} end - local tags = {} - for _, name in ipairs(names) do - table.insert(tags, "[technology=" .. name .. "]") + return tech.localised_name +end + +--- @class ResearchSyncQueueChange +--- @field type "added"|"removed"|"moved" +--- @field name string +--- @field offset integer +--- @field position integer + +--- @param changes ResearchSyncQueueChange[] +--- @return LocalisedString[] +local function format_changes(changes) + local force = game.forces["player"] + local parts = {} + for i, change in ipairs(changes) do + local tech = force.technologies[change.name] + local label + if tech then + label = technology_label(tech, tech.level + change.offset) + else + label = change.name + end + local part = {"", i > 1 and ", " or "", change.type, " ", label} + if change.type == "moved" then + table.insert(part, " to position " .. change.position) + end + table.insert(parts, part) end - return table.concat(tags, " ") + return parts end --- @param player LuaPlayer @@ -392,11 +418,7 @@ function research_sync.research_technology(name, level) tech.level = level tech.researched = true - if tech.name:find("-%d+$") then - game.print {"", "Researched ", {"technology-name." .. tech.name:gsub("-%d+$", "")}, " ", level} - else - game.print {"", "Researched ", {"technology-name." .. tech.name}} - end + game.print {"", "Researched ", technology_label(tech, level)} game.play_sound { path = "utility/research_completed" } end script_data.ignore_research_finished = false @@ -424,19 +446,28 @@ function research_sync.queue_state() })) end ---- @param data string JSON {queue: string[], player?: string, instance?: string} +--- @param data string JSON {queue: string[], player?: string, instance?: string, changes?: ResearchSyncQueueChange[]} function research_sync.apply_queue(data) if not research_queue_api then return end local msg = compat.json_to_table(data) --[[@as table]] local queue = msg.queue or {} - if msg.instance then - local list = format_queue(queue) + if msg.instance and msg.changes then + -- "Bob added X on 0_1", or "Research queue on 0_1: added X" + local text = {"", msg.player and msg.player .. " " or "Research queue on " .. msg.instance .. ": "} + for _, part in ipairs(format_changes(msg.changes)) do + table.insert(text, part) + end if msg.player then - game.print(msg.player .. " changed the research queue on " .. msg.instance .. ": " .. list) + table.insert(text, " on " .. msg.instance) + end + game.print(text) + elseif msg.instance then + if msg.player then + game.print(msg.player .. " changed the research queue on " .. msg.instance) else - game.print("The research queue was changed on " .. msg.instance .. ": " .. list) + game.print("The research queue was changed on " .. msg.instance) end end diff --git a/plugins/research_sync/test/controller.js b/plugins/research_sync/test/controller.js index 69584a15..fadf395a 100644 --- a/plugins/research_sync/test/controller.js +++ b/plugins/research_sync/test/controller.js @@ -4,10 +4,10 @@ import path from "node:path"; import * as lib from "@clusterio/lib"; import * as mock from "../../../test/mock.js"; -import controllerEntrypoint from "../dist/node/controller.js"; +import controllerEntrypoint, { queueChanges } from "../dist/node/controller.js"; import { plugin as info } from "../dist/node/index.js"; import { - ContributionEvent, FinishedEvent, QueueEvent, QueueSyncRequest, QueueUpdateEvent, + ContributionEvent, FinishedEvent, QueueChange, QueueEvent, QueueSyncRequest, QueueUpdateEvent, SyncTechnologiesRequest, TechnologySync, } from "../dist/node/messages.js"; @@ -58,6 +58,24 @@ describe("research_sync controller", function() { assert.equal(sent[0][1].instance, "rs-1"); assert.deepEqual(await sync(), ["a", "b"]); }); + it("should send what changed with an update", async function() { + await update(["a", "b"], "Bob"); + await update(["b", "a", "c"], "Bob"); + assert.deepEqual(queueEvents().map(([, m]) => m.changes), [ + [new QueueChange("added", "a", 0, 1), new QueueChange("added", "b", 0, 2)], + [new QueueChange("added", "c", 0, 3), new QueueChange("moved", "a", 0, 2)], + ]); + }); + it("should send what changed when seeding from a sync request", async function() { + await sync(["x"], "Bob"); + assert.deepEqual(queueEvents()[0][1].changes, [new QueueChange("added", "x", 0, 1)]); + }); + it("should send no changes when dropping a finished technology", async function() { + await update(["x", "y"]); + sent.length = 0; + await mock.getHandler(controller, FinishedEvent)(new FinishedEvent("x", 1), src); + assert.equal(queueEvents()[0][1].changes, null); + }); it("should not broadcast an unchanged update", async function() { await update(["a", "b"]); await update(["a", "b"]); @@ -213,6 +231,41 @@ describe("research_sync controller", function() { }); }); + describe("queueChanges()", function() { + const added = (name, offset, position) => new QueueChange("added", name, offset, position); + const removed = (name, offset, position) => new QueueChange("removed", name, offset, position); + const moved = (name, offset, position) => new QueueChange("moved", name, offset, position); + + it("should return nothing for equal queues", function() { + assert.deepEqual(queueChanges(["a", "b"], ["a", "b"]), []); + assert.deepEqual(queueChanges([], []), []); + }); + it("should list an entry added anywhere", function() { + assert.deepEqual(queueChanges(["a", "b"], ["a", "x", "b"]), [added("x", 0, 2)]); + assert.deepEqual(queueChanges([], ["a"]), [added("a", 0, 1)]); + }); + it("should list an entry removed with its old position", function() { + assert.deepEqual(queueChanges(["a", "x", "b"], ["a", "b"]), [removed("x", 0, 2)]); + assert.deepEqual(queueChanges(["a"], []), [removed("a", 0, 1)]); + }); + it("should list a moved entry with its new position", function() { + assert.deepEqual(queueChanges(["a", "b", "c", "d"], ["d", "a", "b", "c"]), [moved("d", 0, 1)]); + assert.deepEqual(queueChanges(["a", "b", "c", "d"], ["b", "c", "a", "d"]), [moved("a", 0, 3)]); + }); + it("should give repeated levels increasing offsets", function() { + assert.deepEqual(queueChanges(["m", "m"], ["m", "m", "m"]), [added("m", 2, 3)]); + assert.deepEqual(queueChanges([], ["m", "a", "m"]), [added("m", 0, 1), added("a", 0, 2), added("m", 1, 3)]); + }); + it("should remove the highest levels when a repeated technology shrinks", function() { + assert.deepEqual(queueChanges(["m", "m", "m"], ["m"]), [removed("m", 1, 2), removed("m", 2, 3)]); + }); + it("should list removed, then added, then moved", function() { + assert.deepEqual(queueChanges(["a", "b", "c"], ["c", "x", "a"]), [ + removed("b", 0, 2), added("x", 0, 2), moved("a", 0, 3), + ]); + }); + }); + it("should persist the queue across loads", async function() { await update(["a", "b"]); await controller.hooks.save.invoke(); diff --git a/plugins/research_sync/test/instance.js b/plugins/research_sync/test/instance.js index 64138a78..95d6f4c7 100644 --- a/plugins/research_sync/test/instance.js +++ b/plugins/research_sync/test/instance.js @@ -5,8 +5,8 @@ import * as mock from "../../../test/mock.js"; import loadInstancePlugin from "../dist/node/instance.js"; import { plugin as info } from "../dist/node/index.js"; import { - ContributionEvent, FinishedEvent, QueueEvent, QueueSyncRequest, QueueUpdateEvent, SyncTechnologiesRequest, - TechnologySync, + ContributionEvent, FinishedEvent, QueueChange, QueueEvent, QueueSyncRequest, QueueUpdateEvent, + SyncTechnologiesRequest, TechnologySync, } from "../dist/node/messages.js"; describe("research_sync instance", function() { @@ -75,6 +75,11 @@ describe("research_sync instance", function() { await handler()(new QueueEvent(["a"], "Bob", "rs-2")); assert.equal(lastCommand(), applyCommand({ queue: ["a"], instance: "rs-2", player: "Bob" })); }); + it("should pass on the changes", async function() { + const changes = [new QueueChange("added", "a", 0, 1)]; + await handler()(new QueueEvent(["a"], "Bob", "rs-2", changes)); + assert.equal(lastCommand(), applyCommand({ queue: ["a"], instance: "rs-2", player: "Bob", changes })); + }); it("should leave out a null player", async function() { await handler()(new QueueEvent(["a"], null, "rs-2")); assert.equal(lastCommand(), applyCommand({ queue: ["a"], instance: "rs-2" })); diff --git a/plugins/subspace_storage/controller.ts b/plugins/subspace_storage/controller.ts index cad2ec52..8f28b801 100644 --- a/plugins/subspace_storage/controller.ts +++ b/plugins/subspace_storage/controller.ts @@ -64,7 +64,7 @@ async function saveDatabase( let file = path.resolve(controllerConfig.get("controller.database_directory"), "items.json"); logger.verbose(`writing ${file}`); let content = JSON.stringify(items.serialize()); - await lib.safeOutputFile(file, content); + await lib.atomicOverwriteFile(file, content); } else if (items) { logger.error(`Item database too large, not saving (${items.size})`); } diff --git a/plugins/subspace_storage/index.ts b/plugins/subspace_storage/index.ts index bdbecf03..295268cd 100644 --- a/plugins/subspace_storage/index.ts +++ b/plugins/subspace_storage/index.ts @@ -46,6 +46,7 @@ export const plugin: lib.PluginDeclaration = { }, features: [ + "SavePatching", "ScriptCommands", ], diff --git a/scripts/version-compat-test.js b/scripts/version-compat-test.js index e9e7aa32..1a00a427 100644 --- a/scripts/version-compat-test.js +++ b/scripts/version-compat-test.js @@ -298,6 +298,48 @@ async function pollCtl(ctl, cliArgs, expectRegex, description, timeoutMs = 30e3) } } +/** + * Pair the host with the running controller and write its config + * + * The pairing API is probed instead of checking which side is local, as releases that support + * pairing no longer have ctl host create-config to fall back on. + * + * @returns true if the host was paired, false if the controller predates host pairing. + */ +async function pairHostWithController() { + // Written by bootstrap create-ctl-config, holds the admin token which approves the host directly. + const ctlConfig = JSON.parse(await fs.readFile(path.join(controllerDir, "config-ctl.json"), "utf8")); + const controllerUrl = ctlConfig["ctl.controller_url"]; + console.log(`| pairing host with ${controllerUrl}`); + // A user allowed to approve hosts gets the host straight away, without waiting for approval. + const response = await fetch(new URL("api/host-pairing", controllerUrl), { + method: "POST", + headers: { "Content-Type": "application/json", "Authorization": `Bearer ${ctlConfig["ctl.controller_token"]}` }, + body: JSON.stringify({ name: "host" }), + }); + if (response.status === 404) { + console.log("| controller does not support host pairing"); + return false; + } + if (response.status !== 200) { + throw new Error(`Pairing host failed with ${response.status}: ${await response.text()}`); + } + const pairing = await response.json(); + console.log(`| paired host ${pairing.name} with id ${pairing.hostId}`); + + // The same fields the installer sets, which every host version reads. + const hostConfig = { + "host.id": pairing.hostId, + "host.name": pairing.name, + "host.controller_url": controllerUrl, + "host.controller_token": pairing.token, + }; + await fs.writeFile( + path.join(hostDir, "config-host.json"), JSON.stringify(hostConfig, null, "\t"), { flag: "wx", mode: 0o600 } + ); + return true; +} + async function main() { const options = parseArgs(); const breaks = await loadBreaks(); @@ -356,10 +398,12 @@ async function main() { ); try { - await run("ctl", ctl, [ - "host", "create-config", "--id", "1", "--name", "host", "--generate-token", - "--output", path.join(hostDir, "config-host.json"), - ], controllerDir); + if (!await pairHostWithController()) { + await run("ctl", ctl, [ + "host", "create-config", "--id", "1", "--name", "host", "--generate-token", + "--output", path.join(hostDir, "config-host.json"), + ], controllerDir); + } // Started host is only logged after the connection to the controller is established. const hostProc = await spawnDaemon("host", host, ["run"], hostDir, /Started host/); diff --git a/test/controller/ControlConnection.test.js b/test/controller/ControlConnection.test.js index 6cb50dd8..c3bac0c7 100644 --- a/test/controller/ControlConnection.test.js +++ b/test/controller/ControlConnection.test.js @@ -1,8 +1,11 @@ import assert from "node:assert/strict"; import events from "node:events"; import * as lib from "@clusterio/lib"; -import { Controller, ControlConnection, ControllerHooks, InstanceManager } from "@clusterio/controller"; +import { + Controller, ControlConnection, ControllerHooks, HostConnection, HostRecord, InstanceManager, InstanceRecord, +} from "@clusterio/controller"; import { MockConnector, MockController, MockLogger } from "../mock.js"; +import "../setup_logging.js"; const addr = lib.Address.fromShorthand; @@ -153,6 +156,142 @@ describe("controller/src/ControlConnection", function() { assert.equal(clone.config.get("instance.name"), "clone"); assert.equal(clone.config.get("instance.assigned_host"), null); }); + + it("creates an instance inheriting from a template", async function() { + await create({ "instance.id": 4001, "instance.name": "template", "instance.is_template": true }); + mockController.instances.getMutable(4001).config.set("factorio.version", "2.0"); + + await create({ "instance.id": 4002, "instance.name": "child", "instance.template_id": 4001 }); + const child = mockController.instances.get(4002); + assert.equal(child.config.get("factorio.version"), "2.0"); + assert.equal(child.config.isInherited("factorio.version"), true); + assert.equal(child.config.isInherited("instance.name"), false); + }); + + it("rejects a template that is not a template", async function() { + await create({ "instance.id": 4001, "instance.name": "plain" }); + await assert.rejects( + create({ "instance.id": 4002, "instance.name": "child", "instance.template_id": 4001 }), + new lib.ValidationError("Instance plain is not a template"), + ); + assert.equal(mockController.instances.has(4002), false); + }); + }); + + describe("instance config set handlers", function() { + let mockController; + let connection; + + beforeEach(async function() { + mockController = new MockController(); + mockController.mockConfigEntries.set("controller.name", "Test"); + mockController.instances = new InstanceManager(new lib.SubscribableDatastore(), mockController); + mockController.instanceConfigUpdated = async () => {}; + connection = { + _controller: mockController, + checkStagedInheritance: ControlConnection.prototype.checkStagedInheritance, + }; + for (const [id, fields] of [ + [1, { "instance.is_template": true, "factorio.version": "2.0" }], + [2, { "instance.template_id": 1 }], + ]) { + const config = new lib.InstanceConfig("controller", { + "instance.id": id, "instance.name": `i${id}`, ...fields, + }); + if (fields["instance.template_id"]) { + mockController.instances.applyTemplate( + config, ["instance.id", "instance.name", "instance.template_id"], + ); + } + await mockController.instances.createInstance(config); + } + }); + + function call(handler, request) { + return ControlConnection.prototype[handler].call(connection, request); + } + async function create(config, cloneFromId) { + await ControlConnection.prototype.handleInstanceCreateRequest.call( + connection, new lib.InstanceCreateRequest(config, cloneFromId), + ); + } + const setField = (...args) => new lib.InstanceConfigSetFieldRequest(...args); + const setFields = (...args) => new lib.InstanceConfigSetRequest(...args); + + it("stops inheriting a field set to the inherited value", async function() { + await call("handleInstanceConfigSetFieldRequest", setField(2, "factorio.version", "2.0")); + assert.equal(mockController.instances.get(2).config.isInherited("factorio.version"), false); + }); + + it("stops inheriting a field set through set request", async function() { + await call("handleInstanceConfigSetRequest", setFields(2, { "factorio.version": "2.0" })); + assert.equal(mockController.instances.get(2).config.isInherited("factorio.version"), false); + }); + + it("stops inheriting a property set through set-prop", async function() { + await call( + "handleInstanceConfigSetPropRequest", + new lib.InstanceConfigSetPropRequest(2, "factorio.settings", "max_players", 0), + ); + const config = mockController.instances.get(2).config; + assert.equal(config.isInherited("factorio.settings", "max_players"), false); + assert.equal(config.isInherited("factorio.settings", "auto_pause"), true); + }); + + it("rejects template_id pointing at a non-template", async function() { + await assert.rejects( + call("handleInstanceConfigSetFieldRequest", setField(1, "instance.template_id", "2")), + new lib.ValidationError("Instance i2 is not a template"), + ); + assert.equal(mockController.instances.get(1).config.get("instance.template_id"), null); + }); + + it("rejects unmarking a template with inheritors through set request", async function() { + await assert.rejects( + call("handleInstanceConfigSetRequest", setFields(1, { "instance.is_template": "false" })), + new lib.ConflictError("Instance is the template of 1 other instance(s)"), + ); + assert.equal(mockController.instances.get(1).config.get("instance.is_template"), true); + }); + + it("stops inheriting only the properties set through set request", async function() { + await call("handleInstanceConfigSetRequest", setFields(2, { "factorio.settings": { max_players: 3 } })); + const config = mockController.instances.get(2).config; + assert.equal(config.isInherited("factorio.settings", "max_players"), false); + assert.equal(config.isInherited("factorio.settings", "auto_pause"), true); + }); + + it("inherits a property again", async function() { + await call("handleInstanceConfigSetPropRequest", new lib.InstanceConfigSetPropRequest( + 2, "factorio.settings", "max_players", 3, + )); + await call( + "handleInstanceConfigInheritFieldRequest", + new lib.InstanceConfigInheritFieldRequest(2, "factorio.settings", "max_players"), + ); + const config = mockController.instances.get(2).config; + assert.equal(config.get("factorio.settings").max_players, 0); + assert.equal(config.isInherited("factorio.settings", "max_players"), true); + }); + + it("creates a template from an existing instance", async function() { + await create({ "instance.id": 3, "instance.name": "copy", "instance.is_template": true }, 2); + const config = mockController.instances.get(3).config; + assert.equal(config.get("instance.is_template"), true); + assert.equal(config.get("instance.template_id"), 1); + assert.equal(config.get("factorio.version"), "2.0"); + }); + + it("inherits a field again", async function() { + await call("handleInstanceConfigSetFieldRequest", setField(2, "factorio.version", "2.1")); + await call( + "handleInstanceConfigInheritFieldRequest", + new lib.InstanceConfigInheritFieldRequest(2, "factorio.version"), + ); + const config = mockController.instances.get(2).config; + assert.equal(config.get("factorio.version"), "2.0"); + assert.equal(config.isInherited("factorio.version"), true); + }); }); describe("close cleanup", function() { @@ -272,4 +411,164 @@ describe("controller/src/ControlConnection", function() { assert.equal(player.connector.terminated, true); }); }); + + describe("host management", function() { + /** @type {Controller} */ + let controller; + /** @type {ControlConnection} */ + let connection; + let audits; + let originalAudit; + + beforeEach(function() { + const config = new lib.ControllerConfig("controller"); + config.set("controller.auth_secret", Buffer.from("TestSecretDoNotUse").toString("base64")); + controller = new Controller(lib.logger, [], config); + const connector = new lib.VirtualConnector(addr("controller"), addr({ controlId: 1 })); + const user = controller.users.getOrCreateUser("admin"); + connection = new ControlConnection({ version: "2.0.0" }, connector, controller, user, 1); + audits = []; + originalAudit = lib.logger.audit; + lib.logger.audit = msg => { audits.push(msg); }; + }); + afterEach(function() { + lib.logger.audit = originalAudit; + }); + + describe(".handleHostRevokeRequest()", function() { + let record; + let broadcasts; + + beforeEach(function() { + record = new HostRecord(10, "host-10", "", new Map()); + controller.hosts.records.set(record); + broadcasts = []; + controller.subscriptions.broadcast = event => { + if (event instanceof lib.HostUpdatesEvent) { + broadcasts.push(...event.updates.map(host => ({ id: host.id, isDeleted: host.isDeleted }))); + } + }; + }); + + function assignInstance(id, name, hostId) { + const instanceConfig = new lib.InstanceConfig("controller"); + instanceConfig.set("instance.id", id); + instanceConfig.set("instance.name", name); + instanceConfig.set("instance.assigned_host", hostId); + controller.instances.records.set(new InstanceRecord(instanceConfig, "stopped")); + } + + async function revoke(hostId = 10) { + await connection.handleHostRevokeRequest(new lib.HostRevokeRequest(hostId)); + } + + it("deletes the host record", async function() { + await revoke(); + assert.equal(controller.hosts.has(10), false); + assert.deepEqual(broadcasts, [{ id: 10, isDeleted: true }]); + assert.equal(audits.length, 1); + assert.match(audits[0], /User admin revoked host host-10 \(10\)/); + }); + it("deletes the note of the host", async function() { + controller.setNote("host", "10", "rack 3", "someone"); + controller.setNote("host", "11", "rack 4", "someone"); + await revoke(); + const note = controller.notes.get("host/10"); + assert.equal(note.isDeleted, true); + assert.equal(note.content, ""); + assert.equal(note.updatedBy, "admin"); + assert.equal(controller.notes.get("host/11").isDeleted, false); + }); + it("terminates the connection of the host", async function() { + let terminated = false; + controller.wsServer.hostConnections.set(10, { connector: { terminate() { terminated = true; } } }); + await revoke(); + assert.equal(terminated, true); + }); + it("does not leave a host record behind when the connection closes", async function() { + const connector = new MockConnector(addr("controller"), addr({ hostId: 10 })); + connector.terminate = () => { connector.emit("close"); }; + const hostConnection = new HostConnection( + new lib.RegisterHostData("", "2.0.0", 10, {}), connector, controller, "10.0.0.1" + ); + controller.wsServer.hostConnections.set(10, hostConnection); + assert.equal(controller.hosts.get(10).connected, true); + + await revoke(); + assert.equal(controller.hosts.has(10), false, "host record was recreated"); + assert.deepEqual(broadcasts.at(-1), { id: 10, isDeleted: true }); + }); + it("unassigns the instances of the host without waiting for it", async function() { + let closing = false; + controller.wsServer.hostConnections.set(10, { + connector: { terminate() { closing = true; }, get closing() { return closing; } }, + send: () => new Promise(() => {}), + }); + assignInstance(101, "alpha", 10); + assignInstance(102, "beta", 10); + assignInstance(201, "gamma", 20); + + await revoke(); + assert.equal(controller.hosts.has(10), false); + for (const id of [101, 102]) { + const instance = controller.instances.get(id); + assert.equal(instance.config.get("instance.assigned_host"), null); + assert.equal(instance.status, "unassigned"); + } + assert.equal(controller.instances.get(201).config.get("instance.assigned_host"), 20); + }); + it("removes the system metrics of the host", async function() { + controller.systems.set(await lib.gatherSystemInfo(10, false, false, 0)); + controller.systems.set(await lib.gatherSystemInfo("controller", false, false, 0)); + await revoke(); + assert.equal(controller.systems.has(10), false); + assert.equal(controller.systems.has("controller"), true); + }); + it("throws NotFoundError for an unknown host", async function() { + await assert.rejects(revoke(99), new lib.NotFoundError("Unknown host id (99)")); + assert.equal(controller.hosts.has(10), true); + }); + }); + + describe("host pairing requests", function() { + it("lists pending requests", async function() { + const first = controller.hostPairing.create("Host A", "2.0.0", "10.0.0.1"); + const second = controller.hostPairing.create("Host B", "2.0.0", "10.0.0.2"); + const list = await connection.handleHostPairingListRequest(new lib.HostPairingListRequest()); + assert(list.every(details => details instanceof lib.HostPairingDetails)); + assert.deepEqual(list.map(details => details.code).sort(), [first.code, second.code].sort()); + assert.equal(list.find(details => details.code === first.code).name, "Host A"); + }); + it("leaves out expired, approved and rejected requests when listing", async function() { + const expired = controller.hostPairing.create("Host A", "", "10.0.0.1"); + const approved = controller.hostPairing.create("Host B", "", "10.0.0.2"); + const rejected = controller.hostPairing.create("Host C", "", "10.0.0.3"); + const pending = controller.hostPairing.create("Host D", "", "10.0.0.4"); + controller.hostPairing._bySecret.get(expired.requestId).lastPollMs -= 60e3; + controller.hostPairing.approve(approved.code, undefined, "admin"); + controller.hostPairing.reject(rejected.code, "admin"); + + const list = await connection.handleHostPairingListRequest(new lib.HostPairingListRequest()); + assert.deepEqual(list.map(details => details.code), [pending.code]); + }); + it("approves a request and returns the new host id", async function() { + const { requestId, code } = controller.hostPairing.create("Host A", "", "10.0.0.1"); + const hostId = await connection.handleHostPairingApproveRequest( + new lib.HostPairingApproveRequest(code.toLowerCase().replace("-", "")) + ); + assert.equal(typeof hostId, "number"); + assert.equal(controller.hosts.get(hostId).name, "Host A"); + assert.equal(controller.hostPairing.poll(requestId).hostId, hostId); + assert(audits.some(msg => msg.startsWith(`User admin approved host Host A (${hostId})`))); + }); + it("rejects a request", async function() { + const { requestId, code } = controller.hostPairing.create("Host A", "", "10.0.0.1"); + await connection.handleHostPairingRejectRequest(new lib.HostPairingRejectRequest(code.toLowerCase())); + assert.equal(controller.hostPairing.records.has(code), false); + assert.throws(() => controller.hostPairing.poll(requestId), /Request was rejected/); + assert.equal(controller.hosts.records.size, 0); + assert(audits.some(msg => msg.startsWith(`User admin rejected host Host A with code ${code}`))); + }); + }); + }); }); diff --git a/test/controller/Controller.js b/test/controller/Controller.js index 68f535bd..9a5908c0 100644 --- a/test/controller/Controller.js +++ b/test/controller/Controller.js @@ -34,6 +34,10 @@ class MockInstanceConfig extends EventEmitter { this._data.set(field, value); this.emit("fieldChanged", field, value, prev); } + + isInherited() { + return false; + } } describe("controller/src/Controller", function() { @@ -89,6 +93,75 @@ describe("controller/src/Controller", function() { assert(loaded.modPacks.size > 0, "default mod packs were not added"); await fs.access(modsDirectory); }); + it("should start and stop with an existing database", async function() { + this.timeout(10000); + const databaseDirectory = path.join(dir, "database"); + await fs.mkdir(databaseDirectory); + const records = { + "hosts.json": [new HostRecord(5, "existing-host", controllerVersion, new Map(), true)], + "instances.json": [ + new InstanceRecord(new InstanceConfig("controller", { + "instance.id": 100, "instance.assigned_host": 5, + }), "running"), + new InstanceRecord(new InstanceConfig("controller", { "instance.id": 101 }), "unassigned"), + ], + "mod-packs.json": [ModPack.fromJSON({ id: 7, name: "existing-pack" })], + "users.json": [new UserRecord(0, "admin", new Set([0]), new Set(), true)], + }; + for (const [file, content] of Object.entries(records)) { + await fs.writeFile(path.join(databaseDirectory, file), JSON.stringify(content)); + } + + // Port 0 means not configured, so ask the OS for a free one. + const portProbe = http.createServer(); + portProbe.listen(0, "127.0.0.1"); + await events.once(portProbe, "listening"); + const port = portProbe.address().port; + portProbe.close(); + await events.once(portProbe, "close"); + + const config = new ControllerConfig("controller", { + "controller.version": controllerVersion, + "controller.database_directory": databaseDirectory, + "controller.mods_directory": path.join(dir, "mods"), + "controller.http_port": port, + "controller.bind_address": "127.0.0.1", + }); + + const errors = []; + const errorCapture = new lib.ConsoleTransport({ + level: "error", + filter: info => { + // pnpm build does not produce the production web bundle + if (!info.message.includes("Missing main entry")) { + errors.push(info.message); + } + return false; + }, + }); + lib.logger.add(errorCapture); + let loaded; + try { + loaded = await Controller.fromConfig(config, [], lib.logger); + await loaded.start({ logDirectory: path.join(dir, "logs"), _: ["run"] }); + assert.deepEqual( + [...loaded.instances.values()].map(instance => [instance.id, instance.status]), + [[100, "unknown"], [101, "unassigned"]], + ); + assert.equal(loaded.hosts.get(5).connected, false); + assert.equal(loaded.modPacks.get(7).name, "existing-pack"); + assert(loaded.users.getByName("admin"), "existing user was not loaded"); + const response = await fetch(`http://127.0.0.1:${port}/`); + assert.equal(response.status, 200); + await response.text(); + } finally { + await loaded?.stop(); + lib.logger.remove(errorCapture); + } + assert.deepEqual(errors, []); + const saved = JSON.parse(await fs.readFile(path.join(databaseDirectory, "instances.json"), "utf8")); + assert.deepEqual(saved.map(instance => instance.config["instance.id"]), [100, 101]); + }); describe("with a plugin version change", function() { before(function() { addPluginConfigFields([{ name: "from_config_plugin", version: "1.2.0", instanceEntrypoint: "x" }]); @@ -129,6 +202,43 @@ describe("controller/src/Controller", function() { }); }); }); + describe(".validateExports()", function() { + let dir; + before(async function() { + dir = await fs.mkdtemp(path.join(os.tmpdir(), "clusterio-exports-")); + await fs.writeFile(path.join(dir, "locale.abc.json"), "[]"); + await fs.writeFile(path.join(dir, "metadata.abc.json"), "{}"); + }); + after(async function() { + await fs.rm(dir, { recursive: true, force: true }); + }); + it("should drop export manifests with missing or invalid files", async function() { + const provider = new lib.MemoryDatastoreProvider(); + const modPacks = new lib.SubscribableDatastore(provider, new Map()); + const packs = [ + { id: 1, assets: { locale: "locale.abc.json", metadata: "metadata.abc.json" } }, + { id: 2, assets: { locale: "locale.abc.json", metadata: "metadata.def.json" } }, + { id: 3, assets: { locale: "../locale.abc.json" } }, + { id: 4 }, + ].map(({ id, assets }) => { + const modPack = ModPack.fromJSON({ id, name: `pack ${id}` }); + if (assets) { + modPack.exportManifest = new lib.ExportManifest(assets); + } + return modPack; + }); + modPacks.setMany(packs); + const updates = []; + modPacks.on("update", updated => updates.push(...updated)); + + await Controller.validateExports(modPacks, dir); + assert.deepEqual(modPacks.get(1).exportManifest.assets, packs[0].exportManifest.assets); + assert.equal(modPacks.get(2).exportManifest, undefined); + assert.equal(modPacks.get(3).exportManifest, undefined); + assert.equal(modPacks.get(4).exportManifest, undefined); + assert.deepEqual(updates.map(modPack => modPack.id), [2, 3]); + }); + }); describe(".loadJsonObject()", function() { let dir; before(async function() { diff --git a/test/controller/HostConnection.test.js b/test/controller/HostConnection.test.js index 7c86e278..123c9d3d 100644 --- a/test/controller/HostConnection.test.js +++ b/test/controller/HostConnection.test.js @@ -1,6 +1,9 @@ import assert from "node:assert/strict"; import * as lib from "@clusterio/lib"; -import { HostConnection } from "@clusterio/controller"; +import { Controller, HostConnection, HostRecord } from "@clusterio/controller"; +import { MockConnector } from "../mock.js"; + +const addr = lib.Address.fromShorthand; function makeSave(instanceId, name) { return new lib.SaveDetails(instanceId, "file", name, 0, 0, false, false, 0, false); @@ -40,6 +43,99 @@ function makeInstances(assignments, names = new Map()) { } describe("controller/src/HostConnection", function() { + describe("host record", function() { + /** @type {Controller} */ + let controller; + let record; + let connector; + let updates; + + beforeEach(function() { + controller = new Controller(lib.logger, [], new lib.ControllerConfig("controller")); + record = new HostRecord(10, "host-10", "1.0.0", new Map(), false, "", "203.0.113.1", 123); + controller.hosts.records.set(record); + connector = new MockConnector(addr("controller"), addr({ hostId: 10 })); + updates = []; + controller.hosts.records.on("update", changed => { + updates.push(...changed.map(host => ({ id: host.id, name: host.name, isDeleted: host.isDeleted }))); + }); + }); + + function connect(id = 10) { + return new HostConnection( + new lib.RegisterHostData("", "2.0.0", id, {}), connector, controller, "10.0.0.1" + ); + } + + function revoke() { + controller.hosts.records.delete(record); + updates.length = 0; + } + + it("should refuse a host without a record", function() { + assert.throws(() => connect(11), /Host 11 is not registered/); + assert.equal(controller.hosts.has(11), false); + assert.deepEqual(updates, []); + }); + it("should update the existing record on connect", function() { + const connection = connect(); + assert.equal(controller.hosts.get(10), record, "host record was replaced"); + assert.equal(connection.id, 10); + assert.equal(record.connected, true); + assert.equal(record.version, "2.0.0"); + assert.equal(record.remoteAddress, "10.0.0.1"); + assert.equal(record.name, "host-10"); + assert.equal(record.publicAddress, "203.0.113.1"); + assert.equal(record.tokenValidAfter, 123); + assert.deepEqual(updates, [{ id: 10, name: "host-10", isDeleted: false }]); + }); + it("should mark the host disconnected when the connection closes", function() { + connect(); + updates.length = 0; + connector.emit("close"); + assert.equal(controller.hosts.get(10), record); + assert.equal(record.connected, false); + assert.deepEqual(updates, [{ id: 10, name: "host-10", isDeleted: false }]); + }); + it("should save info updates from the host", async function() { + const connection = connect(); + updates.length = 0; + await connection.handleHostInfoUpdateEvent( + new lib.HostInfoUpdateEvent(new lib.HostInfoUpdate("renamed", "198.51.100.1")) + ); + assert.equal(controller.hosts.get(10).name, "renamed"); + assert.equal(controller.hosts.get(10).publicAddress, "198.51.100.1"); + assert.deepEqual(updates, [{ id: 10, name: "renamed", isDeleted: false }]); + }); + it("should not recreate the record of a revoked host when the connection closes", function() { + connect(); + revoke(); + connector.emit("close"); + assert.equal(controller.hosts.has(10), false, "host record was recreated"); + assert.deepEqual(updates, []); + }); + it("should not recreate the record of a revoked host on info updates", async function() { + const connection = connect(); + revoke(); + await connection.handleHostInfoUpdateEvent( + new lib.HostInfoUpdateEvent(new lib.HostInfoUpdate("renamed", "198.51.100.1")) + ); + assert.equal(controller.hosts.has(10), false, "host record was recreated"); + assert.deepEqual(updates, []); + }); + it("should not overwrite a newer record with the same id", function() { + connect(); + revoke(); + const newer = new HostRecord(10, "newer", "", new Map()); + controller.hosts.records.set(newer); + updates.length = 0; + connector.emit("close"); + assert.equal(controller.hosts.get(10), newer); + assert.equal(newer.name, "newer"); + assert.deepEqual(updates, []); + }); + }); + describe(".handleInstanceSaveDetailsUpdatesEvent()", function() { // Instance 1 is on host 10, instance 2 is on host 20. const assignments = new Map([[1, 10], [2, 20]]); diff --git a/test/controller/HostManager.test.js b/test/controller/HostManager.test.js new file mode 100644 index 00000000..d148abd6 --- /dev/null +++ b/test/controller/HostManager.test.js @@ -0,0 +1,123 @@ +import assert from "node:assert/strict"; +import crypto from "node:crypto"; +import jwt from "jsonwebtoken"; + +import * as lib from "@clusterio/lib"; +import { Controller, HostManager, HostRecord } from "@clusterio/controller"; + +import "../setup_logging.js"; + +describe("controller/src/HostManager", function() { + /** @type {Controller} */ + let controller; + /** @type {HostManager} */ + let hosts; + + beforeEach(function() { + const config = new lib.ControllerConfig("controller"); + config.set("controller.auth_secret", Buffer.from("TestSecretDoNotUse").toString("base64")); + controller = new Controller(lib.logger, [], config); + hosts = controller.hosts; + }); + + it("should be the host manager of the controller", function() { + assert(hosts instanceof HostManager); + }); + + describe(".has() / .get() / .getMutable() / .values() / .getForRequest()", function() { + it("should return the host when it exists", function() { + const record = new HostRecord(5, "five", "", new Map()); + hosts.records.set(record); + assert.equal(hosts.has(5), true); + assert.equal(hosts.get(5), record); + assert.equal(hosts.getMutable(5), record); + assert.deepEqual([...hosts.values()], [record]); + assert.equal(hosts.getForRequest(5), record); + }); + it("should return undefined or throw when the host does not exist", function() { + assert.equal(hosts.has(5), false); + assert.equal(hosts.get(5), undefined); + assert.equal(hosts.getMutable(5), undefined); + assert.throws(() => hosts.getForRequest(5), new lib.NotFoundError("Unknown host id (5)")); + }); + }); + + describe(".createHost()", function() { + let originalRandomInt; + afterEach(function() { + if (originalRandomInt) { + crypto.randomInt = originalRandomInt; + originalRandomInt = undefined; + } + }); + + it("should create a host record that its tokens are valid for", function() { + const before = Math.floor(Date.now() / 1000); + const host = hosts.createHost("Host A"); + + assert(host instanceof HostRecord); + assert(Number.isInteger(host.id), "id is not an integer"); + assert(host.id >= 1 && host.id < 2 ** 31, `id ${host.id} out of range`); + assert.equal(hosts.get(host.id), host); + assert.equal(host.name, "Host A"); + assert.equal(host.connected, false); + assert(host.tokenValidAfter >= before, "tokenValidAfter predates the call"); + assert(host.tokenValidAfter <= Math.floor(Date.now() / 1000), "tokenValidAfter is in the future"); + assert.equal(hosts.verifyHostToken(hosts.signHostToken(host.id)), host); + }); + it("should not reuse the id of an existing host", function() { + hosts.records.set(new HostRecord(5, "existing", "", new Map())); + const values = [5, 5, 6]; + originalRandomInt = crypto.randomInt; + crypto.randomInt = (...args) => (values.length ? values.shift() : originalRandomInt(...args)); + const host = hosts.createHost("Host A"); + assert.equal(host.id, 6); + assert.equal(hosts.get(5).name, "existing"); + assert.equal(hosts.get(6).name, "Host A"); + }); + }); + + describe(".signHostToken()", function() { + it("should return a host token for the id", function() { + const payload = jwt.verify(hosts.signHostToken(5), controller.authSecret); + const { iat, ...rest } = payload; + assert.equal(typeof iat, "number"); + assert.deepEqual(rest, { aud: "host", host: 5 }); + }); + }); + + describe(".verifyHostToken()", function() { + beforeEach(function() { + hosts.records.set(new HostRecord(5, "five", "", new Map())); + }); + + it("should return the mutable host record", function() { + assert.equal(hosts.verifyHostToken(hosts.signHostToken(5)), hosts.getMutable(5)); + }); + it("should accept a token from before the slave rename", function() { + const token = jwt.sign({ aud: "slave", slave: 5 }, controller.authSecret); + assert.equal(hosts.verifyHostToken(token).id, 5); + }); + it("should reject a token for an unknown host", function() { + assert.throws(() => hosts.verifyHostToken(hosts.signHostToken(6)), /host is not registered/); + }); + it("should reject a token issued before tokenValidAfter", function() { + const now = Math.floor(Date.now() / 1000); + hosts.getMutable(5).tokenValidAfter = now; + const token = jwt.sign({ aud: "host", host: 5, iat: now - 1 }, controller.authSecret); + assert.throws(() => hosts.verifyHostToken(token), new Error("invalid token")); + }); + it("should reject user tokens and bad signatures", function() { + const userToken = jwt.sign({ aud: "user", user: "test" }, controller.authSecret); + assert.throws(() => hosts.verifyHostToken(userToken), /audience invalid/); + const forged = jwt.sign({ aud: "host", host: 5 }, "wrong secret"); + assert.throws(() => hosts.verifyHostToken(forged), /invalid signature/); + }); + }); + + describe(".revokeHost()", function() { + it("should throw for an unknown host", async function() { + await assert.rejects(hosts.revokeHost(5, "admin"), new lib.NotFoundError("Unknown host id (5)")); + }); + }); +}); diff --git a/test/controller/HostPairingManager.test.js b/test/controller/HostPairingManager.test.js new file mode 100644 index 00000000..9294ceeb --- /dev/null +++ b/test/controller/HostPairingManager.test.js @@ -0,0 +1,461 @@ +import assert from "node:assert/strict"; +import crypto from "node:crypto"; +import jwt from "jsonwebtoken"; + +import * as lib from "@clusterio/lib"; +import { Controller, HostPairingManager, HostPairingError } from "@clusterio/controller"; +import { + pollTimeoutMs, maxPendingPerAddress, maxNameLength, +} from "@clusterio/controller/dist/node/src/HostPairingManager.js"; + +import "../setup_logging.js"; + +const codePattern = /^[2-9A-HJKMNP-Z]{3}-[2-9A-HJKMNP-Z]{3}$/; + +function makeController() { + const config = new lib.ControllerConfig("controller"); + config.set("controller.auth_secret", Buffer.from("TestSecretDoNotUse").toString("base64")); + return new Controller(lib.logger, [], config); +} + +/** + * Make crypto.randomInt return the given values before falling back to random ones + * + * @param {number[]} values - Values to return, in order. + * @returns {() => void} function restoring crypto.randomInt. + */ +function stubRandomInt(values) { + const original = crypto.randomInt; + crypto.randomInt = (...args) => (values.length ? values.shift() : original(...args)); + return () => { crypto.randomInt = original; }; +} + +function assertPairingError(fn, status, message) { + assert.throws(fn, err => { + assert(err instanceof HostPairingError, `expected HostPairingError, got ${err}`); + assert.equal(err.status, status); + if (message) { + assert.equal(err.message, message); + } + return true; + }); +} + +describe("controller/src/HostPairingManager", function() { + + describe("HostPairingManager.validateName()", function() { + it("should require a non-empty string", function() { + for (const name of [undefined, null, 5, {}, "", " "]) { + assertPairingError(() => HostPairingManager.validateName(name), 400, "Host name is required"); + } + }); + it("should trim the name", function() { + assert.equal(HostPairingManager.validateName(" Host A \t"), "Host A"); + }); + it("should limit the length of the name", function() { + const longest = "x".repeat(maxNameLength); + assert.equal(maxNameLength, 100); + assert.equal(HostPairingManager.validateName(longest), longest); + assert.equal(HostPairingManager.validateName(` ${longest} `), longest); + assertPairingError( + () => HostPairingManager.validateName(`${longest}x`), + 400, "Host name must be at most 100 characters", + ); + }); + it("should refuse control and bidirectional override characters", function() { + for (const name of ["x\u001b]0;title\u0007", "line\nfaked", "a\rb", "del\u007f", "c1\u009b", "x\u202ey"]) { + assertPairingError( + () => HostPairingManager.validateName(name), 400, "Host name may not contain control characters", + ); + } + }); + it("should allow other unicode characters", function() { + for (const name of ["Fabrikk p\u00e5 \u00d8stlandet", "\u5de5\u5382 1", "box \u{1F44D}\u200d"]) { + assert.equal(HostPairingManager.validateName(name), name); + } + }); + }); + + describe("class HostPairingManager", function() { + /** @type {Controller} */ + let controller; + /** @type {HostPairingManager} */ + let manager; + let updates; + let restoreRandomInt; + + beforeEach(function() { + controller = makeController(); + manager = controller.hostPairing; + updates = []; + manager.records.on("update", changed => { + updates.push(...changed.map(details => ({ code: details.code, isDeleted: details.isDeleted }))); + }); + restoreRandomInt = undefined; + }); + afterEach(function() { + manager.stop(); + if (restoreRandomInt) { + restoreRandomInt(); + } + }); + + function internal(requestId) { + return manager._bySecret.get(requestId); + } + + // Pretend the host last polled the request ms milliseconds earlier. + function idle(requestId, ms) { + internal(requestId).lastPollMs -= ms; + } + + describe(".create()", function() { + it("should create a pending request", function() { + const before = Date.now(); + const { requestId, code } = manager.create("Host A", "2.0.0", "10.0.0.1"); + + assert.equal(typeof requestId, "string"); + assert(requestId.length >= 32, "requestId is too short to be a secret"); + assert.match(code, codePattern); + assert.notEqual(requestId, code); + + const details = manager.records.get(code); + assert(details instanceof lib.HostPairingDetails); + assert.equal(details.code, code); + assert.equal(details.name, "Host A"); + assert.equal(details.version, "2.0.0"); + assert.equal(details.remoteAddress, "10.0.0.1"); + assert(details.createdAtMs >= before && details.createdAtMs <= Date.now()); + assert(details.updatedAtMs > 0); + assert.equal(details.isDeleted, false); + assert(!JSON.stringify(details).includes(requestId), "requestId is exposed to users"); + assert.deepEqual(updates, [{ code, isDeleted: false }]); + }); + it("should create unique codes", function() { + const codes = new Set(); + for (let i = 0; i < 50; i++) { + const { code } = manager.create(`Host ${i}`, "", `10.1.${i}.1`); + assert.match(code, codePattern); + codes.add(code); + } + assert.equal(codes.size, 50); + }); + it("should not reuse the code of a pending request", function() { + restoreRandomInt = stubRandomInt([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]); + assert.equal(manager.create("Host A", "", "10.0.0.1").code, "222-222"); + assert.equal(manager.create("Host B", "", "10.0.0.2").code, "333-333"); + }); + it("should not reuse the code of an approved request not yet picked up", function() { + restoreRandomInt = stubRandomInt([0, 0, 0, 0, 0, 0, 1234, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]); + const { code } = manager.create("Host A", "", "10.0.0.1"); + assert.equal(code, "222-222"); + assert.equal(manager.approve(code, undefined, "admin"), 1234); + assert.equal(manager.create("Host B", "", "10.0.0.2").code, "333-333"); + }); + }); + + describe("limits", function() { + it("should limit pending requests per address", function() { + assert.equal(maxPendingPerAddress, 3); + for (let i = 0; i < maxPendingPerAddress; i++) { + manager.create("Host", "", "10.0.0.1"); + } + assert.throws(() => manager.create("Host", "", "10.0.0.1"), err => { + assert(err instanceof HostPairingError); + assert.equal(err.status, 429); + assert.equal(err.retryAfter, 30); + assert.equal(err.message, "Too many pending requests from this address"); + return true; + }); + // Other addresses are not affected + manager.create("Host", "", "10.0.0.2"); + assert.equal(manager.records.size, maxPendingPerAddress + 1); + }); + it("should count IPv4 mapped addresses as the IPv4 address", function() { + manager.create("Host", "", "10.0.0.1"); + manager.create("Host", "", "::ffff:10.0.0.1"); + manager.create("Host", "", "10.0.0.1"); + assertPairingError(() => manager.create("Host", "", "::ffff:10.0.0.1"), 429); + }); + it("should group IPv6 addresses by /64", function() { + manager.create("Host", "", "2001:db8:0:1::1"); + manager.create("Host", "", "2001:db8:0:1::2"); + manager.create("Host", "", "2001:db8::1:ffff:0:0:3"); + assertPairingError( + () => manager.create("Host", "", "2001:0db8:0000:0001:0000:0000:0000:0004"), + 429, "Too many pending requests from this address", + ); + manager.create("Host", "", "2001:db8:0:2::1"); + }); + it("should free the slot when a request is no longer pending", function() { + const first = manager.create("Host", "", "10.0.0.1"); + const second = manager.create("Host", "", "10.0.0.1"); + const third = manager.create("Host", "", "10.0.0.1"); + assertPairingError(() => manager.create("Host", "", "10.0.0.1"), 429); + + manager.cancel(first.requestId); + const fourth = manager.create("Host", "", "10.0.0.1"); + assertPairingError(() => manager.create("Host", "", "10.0.0.1"), 429); + + // Approved and rejected results waiting to be picked up do not count + manager.approve(second.code, undefined, "admin"); + manager.reject(third.code, "admin"); + manager.create("Host", "", "10.0.0.1"); + manager.create("Host", "", "10.0.0.1"); + assertPairingError(() => manager.create("Host", "", "10.0.0.1"), 429); + assert(manager.records.has(fourth.code)); + }); + it("should limit the total number of pending requests", function() { + const maxPending = controller.config.get("controller.host_pairing_max_pending"); + assert.equal(maxPending, 50); + for (let i = 0; i < maxPending; i++) { + manager.create(`Host ${i}`, "", `10.1.${i}.1`); + } + assert.throws(() => manager.create("Host", "", "10.2.0.1"), err => { + assert(err instanceof HostPairingError); + assert.equal(err.status, 429); + assert.equal(err.retryAfter, 30); + assert.equal(err.message, "Too many pending requests"); + return true; + }); + assert.equal(manager.records.size, maxPending); + }); + it("should not limit the total number of pending requests when set to 0", function() { + controller.config.set("controller.host_pairing_max_pending", 0); + for (let i = 0; i < 60; i++) { + manager.create(`Host ${i}`, "", `10.1.${i}.1`); + } + assert.equal(manager.records.size, 60); + }); + }); + + describe(".poll()", function() { + it("should return null while pending", function() { + const { requestId } = manager.create("Host A", "", "10.0.0.1"); + assert.equal(manager.poll(requestId), null); + assert.equal(manager.poll(requestId), null); + }); + it("should throw 404 for an unknown request", function() { + assertPairingError(() => manager.poll("invalid"), 404, "Request not found"); + }); + it("should not accept the code in place of the request id", function() { + const { code } = manager.create("Host A", "", "10.0.0.1"); + assertPairingError(() => manager.poll(code), 404); + }); + it("should hand over an approved result once", function() { + const { requestId, code } = manager.create("Host A", "", "10.0.0.1"); + const hostId = manager.approve(code, undefined, "admin"); + const result = manager.poll(requestId); + assert.deepEqual(Object.keys(result).sort(), ["hostId", "name", "token"]); + assert.equal(result.hostId, hostId); + assert.equal(result.name, "Host A"); + const payload = jwt.verify(result.token, controller.authSecret, { audience: "host" }); + assert.equal(payload.host, hostId); + + assertPairingError(() => manager.poll(requestId), 404, "Request not found"); + assert.equal(manager._byCode.has(code), false); + }); + it("should report a rejection once", function() { + const { requestId, code } = manager.create("Host A", "", "10.0.0.1"); + manager.reject(code, "admin"); + assertPairingError(() => manager.poll(requestId), 403, "Request was rejected"); + assertPairingError(() => manager.poll(requestId), 404, "Request not found"); + }); + }); + + describe(".cancel()", function() { + it("should remove a pending request", function() { + const { requestId, code } = manager.create("Host A", "", "10.0.0.1"); + manager.cancel(requestId); + assert.equal(manager.records.has(code), false); + assertPairingError(() => manager.poll(requestId), 404); + assert.deepEqual(updates, [{ code, isDeleted: false }, { code, isDeleted: true }]); + assert.throws(() => manager.reject(code, "admin"), lib.NotFoundError); + }); + it("should ignore unknown requests", function() { + manager.cancel("invalid"); + }); + it("should not throw away an approved result", function() { + const { requestId, code } = manager.create("Host A", "", "10.0.0.1"); + const hostId = manager.approve(code, undefined, "admin"); + manager.cancel(requestId); + assert.equal(manager.poll(requestId).hostId, hostId); + }); + it("should not throw away a rejection", function() { + const { requestId, code } = manager.create("Host A", "", "10.0.0.1"); + manager.reject(code, "admin"); + manager.cancel(requestId); + assertPairingError(() => manager.poll(requestId), 403); + }); + }); + + describe(".approve()", function() { + it("should create the host with the requested name", function() { + const { code } = manager.create("Host A", "", "10.0.0.1"); + const hostId = manager.approve(code, undefined, "admin"); + assert.equal(controller.hosts.get(hostId).name, "Host A"); + assert.equal(manager.records.has(code), false); + assert.deepEqual(updates, [{ code, isDeleted: false }, { code, isDeleted: true }]); + }); + it("should accept codes in any case and without the dash", function() { + const { code } = manager.create("Host A", "", "10.0.0.1"); + const hostId = manager.approve(code.toLowerCase().replace("-", ""), undefined, "admin"); + assert(controller.hosts.has(hostId)); + }); + it("should use and trim the name given", function() { + const { requestId, code } = manager.create("Host A", "", "10.0.0.1"); + const hostId = manager.approve(code, " Renamed ", "admin"); + assert.equal(controller.hosts.get(hostId).name, "Renamed"); + assert.equal(manager.poll(requestId).name, "Renamed"); + }); + it("should reject an invalid name and keep the request pending", function() { + const { requestId, code } = manager.create("Host A", "", "10.0.0.1"); + assert.throws( + () => manager.approve(code, "", "admin"), + new lib.ValidationError("Host name is required"), + ); + assert.throws( + () => manager.approve(code, "x".repeat(maxNameLength + 1), "admin"), + new lib.ValidationError("Host name must be at most 100 characters"), + ); + assert.equal(controller.hosts.records.size, 0); + assert.equal(manager.poll(requestId), null); + manager.approve(code, undefined, "admin"); + assert.equal(controller.hosts.records.size, 1); + }); + it("should throw NotFoundError for an unknown code", function() { + assert.throws( + () => manager.approve("ZZZ-ZZZ", undefined, "admin"), + new lib.NotFoundError("No pending host request with code ZZZ-ZZZ"), + ); + }); + it("should only approve a request once", function() { + const { code } = manager.create("Host A", "", "10.0.0.1"); + manager.approve(code, undefined, "admin"); + assert.throws(() => manager.approve(code, undefined, "admin"), lib.NotFoundError); + assert.equal(controller.hosts.records.size, 1); + }); + }); + + describe(".reject()", function() { + it("should remove the request from the pending list", function() { + const { code } = manager.create("Host A", "", "10.0.0.1"); + manager.reject(code.toLowerCase(), "admin"); + assert.equal(manager.records.has(code), false); + assert.deepEqual(updates, [{ code, isDeleted: false }, { code, isDeleted: true }]); + assert.equal(controller.hosts.records.size, 0); + }); + it("should throw NotFoundError for an unknown code", function() { + assert.throws( + () => manager.reject("ZZZ-ZZZ", "admin"), + new lib.NotFoundError("No pending host request with code ZZZ-ZZZ"), + ); + }); + it("should not reject an approved request", function() { + const { requestId, code } = manager.create("Host A", "", "10.0.0.1"); + const hostId = manager.approve(code, undefined, "admin"); + assert.throws(() => manager.reject(code, "admin"), lib.NotFoundError); + assert.equal(manager.poll(requestId).hostId, hostId); + }); + }); + + describe(".prune()", function() { + let warnings; + let originalWarn; + beforeEach(function() { + warnings = []; + originalWarn = lib.logger.warn; + lib.logger.warn = msg => { warnings.push(msg); }; + }); + afterEach(function() { + lib.logger.warn = originalWarn; + }); + + it("should expire a request the host stopped polling", function() { + const { requestId, code } = manager.create("Host A", "", "10.0.0.1"); + idle(requestId, pollTimeoutMs + 1); + manager.prune(); + assert.equal(manager.records.has(code), false); + assert.deepEqual(updates, [{ code, isDeleted: false }, { code, isDeleted: true }]); + assertPairingError(() => manager.poll(requestId), 404); + assert.throws(() => manager.reject(code, "admin"), lib.NotFoundError); + }); + it("should keep a request that is still polled", function() { + assert.equal(pollTimeoutMs, 30e3); + const { requestId, code } = manager.create("Host A", "", "10.0.0.1"); + idle(requestId, pollTimeoutMs - 1000); + manager.prune(); + assert.equal(manager.poll(requestId), null); + idle(requestId, pollTimeoutMs - 1000); + manager.prune(); + assert(manager.records.has(code)); + }); + it("should expire a request that has been pending for too long", function() { + const timeoutMs = controller.config.get("controller.host_pairing_timeout") * 1000; + assert.equal(timeoutMs, 60 * 60e3); + const { requestId, code } = manager.create("Host A", "", "10.0.0.1"); + internal(requestId).details.createdAtMs -= timeoutMs - 1000; + manager.prune(); + assert.equal(manager.poll(requestId), null); + internal(requestId).details.createdAtMs -= 1001; + manager.prune(); + assert.equal(manager.records.has(code), false); + assertPairingError(() => manager.poll(requestId), 404); + }); + it("should not limit how long a request is pending when the timeout is 0", function() { + controller.config.set("controller.host_pairing_timeout", 0); + const { requestId, code } = manager.create("Host A", "", "10.0.0.1"); + internal(requestId).details.createdAtMs -= 365 * 24 * 60 * 60e3; + manager.prune(); + assert(manager.records.has(code)); + assert.equal(manager.poll(requestId), null); + }); + it("should drop and warn about an approved host never picked up", function() { + const { requestId, code } = manager.create("Host A", "", "10.0.0.1"); + const hostId = manager.approve(code, undefined, "admin"); + idle(requestId, pollTimeoutMs + 1); + manager.prune(); + assertPairingError(() => manager.poll(requestId), 404); + assert.equal(warnings.length, 1); + assert.match(warnings[0], new RegExp(`Approved host Host A \\(${hostId}\\) was never picked up`)); + // The host stays until revoked + assert(controller.hosts.has(hostId)); + }); + it("should drop a rejection never picked up", function() { + const { requestId, code } = manager.create("Host A", "", "10.0.0.1"); + manager.reject(code, "admin"); + idle(requestId, pollTimeoutMs + 1); + manager.prune(); + assertPairingError(() => manager.poll(requestId), 404); + assert.equal(warnings.length, 0); + }); + }); + + describe("Controller integration", function() { + it("should broadcast changes to pending requests", function() { + const broadcasts = []; + controller.subscriptions.broadcast = event => { + if (event instanceof lib.HostPairingUpdatesEvent) { + broadcasts.push(event.updates.map(details => [details.code, details.isDeleted])); + } + }; + const { code } = manager.create("Host A", "", "10.0.0.1"); + manager.reject(code, "admin"); + assert.deepEqual(broadcasts, [[[code, false]], [[code, true]]]); + }); + it("should send pending requests to new subscribers", async function() { + const { code } = manager.create("Host A", "", "10.0.0.1"); + const event = await controller.handleHostPairingSubscription( + new lib.SubscriptionRequest(lib.HostPairingUpdatesEvent.name, true, 0) + ); + assert(event instanceof lib.HostPairingUpdatesEvent); + assert.deepEqual(event.updates.map(details => details.code), [code]); + + const lastUpdate = manager.records.get(code).updatedAtMs; + assert.equal(await controller.handleHostPairingSubscription( + new lib.SubscriptionRequest(lib.HostPairingUpdatesEvent.name, true, lastUpdate) + ), null); + }); + }); + }); +}); diff --git a/test/controller/InstanceManager.test.js b/test/controller/InstanceManager.test.js index dc254629..25b9e839 100644 --- a/test/controller/InstanceManager.test.js +++ b/test/controller/InstanceManager.test.js @@ -393,4 +393,253 @@ describe("controller/InstanceManager", function () { assert.equal(sentRequest.instanceId, 1); }); }); + + describe("inheritance", function () { + /** @type {InstanceRecord} */ + let template; + /** @type {InstanceRecord} */ + let child; + let updated; + + async function createInheritor(id, templateId, fields = {}) { + const config = new lib.InstanceConfig("controller", { + "instance.id": id, "instance.name": `Instance ${id}`, "instance.template_id": templateId, ...fields, + }); + instances.applyTemplate( + config, ["instance.id", "instance.name", "instance.template_id", ...Object.keys(fields)] + ); + return await instances.createInstance(config); + } + + beforeEach(async function () { + template = await instances.createInstance(new lib.InstanceConfig("controller", { + "instance.id": 10, + "instance.name": "Template", + "instance.is_template": true, + "factorio.version": "2.0", + "factorio.game_port": 34190, + "factorio.settings": { name: "Template server", max_players: 5 }, + })); + child = await createInheritor(11, 10, { "factorio.game_port": 34197 }); + updated = []; + controller.instanceConfigUpdated = async (inst) => { updated.push(inst.id); }; + }); + + describe(".applyTemplate()", function () { + it("should copy template values and mark them inherited", function () { + assert.equal(child.config.get("factorio.version"), "2.0"); + assert.equal(child.config.isInherited("factorio.version"), true); + assert.equal(child.config.get("factorio.game_port"), 34197); + assert.equal(child.config.isInherited("factorio.game_port"), false); + assert.equal(child.config.isInherited("instance.name"), false); + }); + it("should never inherit ports or the rcon password", function () { + template.config.set("factorio.rcon_password", "secret"); + const config = new lib.InstanceConfig("controller", { "instance.id": 12, "instance.template_id": 10 }); + instances.applyTemplate(config, ["instance.id", "instance.template_id"]); + assert.equal(config.get("factorio.game_port"), null); + assert.equal(config.isInherited("factorio.game_port"), false); + assert.equal(config.get("factorio.rcon_password"), null); + assert.equal(config.isInherited("factorio.rcon_password"), false); + }); + it("should inherit factorio.settings per property with its own server name", function () { + const settings = child.config.get("factorio.settings"); + assert.equal(settings.max_players, 5); + assert.equal(settings.name, "TestController - Instance 11"); + assert.equal(child.config.isInherited("factorio.settings", "max_players"), true); + assert.equal(child.config.isInherited("factorio.settings", "name"), false); + }); + it("should keep properties given by the creator as overrides", async function () { + const other = await createInheritor(12, 10, { "factorio.settings": { max_players: 8 } }); + assert.equal(other.config.get("factorio.settings").max_players, 8); + assert.equal(other.config.isInherited("factorio.settings", "max_players"), false); + assert.equal(other.config.isInherited("factorio.settings", "auto_pause"), true); + }); + }); + + describe("template changes", function () { + it("should propagate to inherited fields and send the config to the host", function () { + template.config.set("factorio.version", "2.1"); + assert.equal(child.config.get("factorio.version"), "2.1"); + assert.equal(child.config.isInherited("factorio.version"), true); + assert.deepEqual(updated, [11]); + }); + it("should mark the inheritor as requiring restart", function () { + child.config.restartRequired = false; + template.config.set("factorio.version", "2.1"); + assert.equal(child.config.restartRequired, true); + }); + it("should not touch fields the inheritor has set", function () { + child.config.set("factorio.version", "2.1"); + template.config.set("factorio.version", "2.2"); + assert.equal(child.config.get("factorio.version"), "2.1"); + }); + it("should merge object properties and keep overrides", function () { + template.config.setProp("factorio.settings", "max_players", 10); + template.config.setProp("factorio.settings", "name", "Renamed"); + template.config.setProp("factorio.settings", "auto_pause", true); + const settings = child.config.get("factorio.settings"); + assert.equal(settings.max_players, 10); + assert.equal(settings.auto_pause, true); + assert.equal(settings.name, "TestController - Instance 11"); + }); + it("should propagate through several levels", async function () { + child.config.set("instance.is_template", true); + const grandchild = await createInheritor(12, 11); + template.config.setProp("factorio.settings", "max_players", 10); + assert.equal(grandchild.config.get("factorio.settings").max_players, 10); + assert.deepEqual(updated.sort(), [11, 12]); + }); + }); + + describe("inheritor changes", function () { + it("should stop inheriting a field that is changed", function () { + child.config.set("factorio.version", "2.1"); + assert.equal(child.config.isInherited("factorio.version"), false); + }); + it("should only override the properties changed in an object", function () { + child.config.setProp("factorio.settings", "max_players", 3); + assert.equal(child.config.isInherited("factorio.settings", "max_players"), false); + assert.equal(child.config.isInherited("factorio.settings", "auto_pause"), true); + }); + it("should restore the template value of a removed property", function () { + child.config.setProp("factorio.settings", "max_players", 3); + child.config.setProp("factorio.settings", "max_players"); + assert.equal(child.config.get("factorio.settings").max_players, 5); + assert.equal(child.config.isInherited("factorio.settings", "max_players"), true); + }); + it("should stop inheriting with overrideField() even if the value is unchanged", function () { + instances.overrideField(child, "factorio.version"); + instances.overrideField(child, "factorio.settings", ["auto_pause"]); + assert.equal(child.config.isInherited("factorio.version"), false); + assert.equal(child.config.isInherited("factorio.settings", "auto_pause"), false); + }); + }); + + describe(".inheritField()", function () { + it("should restore the template value", function () { + child.config.set("factorio.version", "2.1"); + instances.inheritField(11, "factorio.version"); + assert.equal(child.config.get("factorio.version"), "2.0"); + assert.equal(child.config.isInherited("factorio.version"), true); + }); + it("should restore a single property", function () { + child.config.setProp("factorio.settings", "max_players", 3); + instances.inheritField(11, "factorio.settings", "max_players"); + assert.equal(child.config.get("factorio.settings").max_players, 5); + assert.equal(child.config.get("factorio.settings").name, "TestController - Instance 11"); + }); + it("should restore all properties", function () { + instances.inheritField(11, "factorio.settings"); + assert.equal(child.config.get("factorio.settings").name, "Template server"); + }); + it("should throw if the instance has no template", function () { + assert.throws( + () => instances.inheritField(1, "factorio.version"), + new lib.ValidationError("Instance does not have a template"), + ); + }); + it("should throw for fields that cannot be inherited", function () { + assert.throws( + () => instances.inheritField(11, "instance.name"), + new lib.ValidationError("Field instance.name cannot be inherited"), + ); + assert.throws( + () => instances.inheritField(11, "factorio.rcon_port"), + new lib.ValidationError("Field factorio.rcon_port cannot be inherited"), + ); + }); + }); + + describe("template_id changes", function () { + it("should inherit fields equal to the template or the default", function () { + instance.config.set("factorio.version", "2.0"); + instance.config.set("factorio.verbose_logging", true); + template.config.set("instance.auto_start", true); + instance.config.set("instance.template_id", 10); + assert.equal(instance.config.isInherited("factorio.version"), true); + assert.equal(instance.config.isInherited("instance.auto_start"), true); + assert.equal(instance.config.get("instance.auto_start"), true); + assert.equal(instance.config.isInherited("factorio.verbose_logging"), false); + }); + it("should inherit object properties equal to the template or the default", function () { + instance.config.setProp("factorio.settings", "max_players", 0); + instance.config.setProp("factorio.settings", "game_password", "secret"); + instance.config.set("instance.template_id", 10); + const settings = instance.config.get("factorio.settings"); + assert.equal(settings.max_players, 5); + assert.equal(settings.game_password, "secret"); + assert.equal(instance.config.isInherited("factorio.settings", "game_password"), false); + assert.equal(instance.config.isInherited("factorio.settings", "max_players"), true); + }); + it("should keep the server name of the instance", function () { + instance.config.setProp("factorio.settings", "name", "Template server"); + instance.config.set("instance.template_id", 10); + assert.equal(instance.config.isInherited("factorio.settings", "name"), false); + }); + it("should clear inherited fields when the template is removed", function () { + child.config.set("instance.template_id", null); + assert.deepEqual(child.config.get("instance.inherited_fields"), {}); + assert.equal(child.config.get("factorio.version"), "2.0"); + }); + }); + + describe(".checkInheritance()", function () { + it("should accept a valid template", function () { + instances.checkInheritance(instance.config, false, 10); + }); + it("should reject a missing template", function () { + assert.throws( + () => instances.checkInheritance(instance.config, false, 99), + new lib.NotFoundError("Instance with ID 99 does not exist"), + ); + }); + it("should reject an instance that is not a template", function () { + assert.throws( + () => instances.checkInheritance(instance.config, false, 11), + new lib.ValidationError("Instance Instance 11 is not a template"), + ); + }); + it("should reject cycles", function () { + child.config.set("instance.is_template", true); + assert.throws( + () => instances.checkInheritance(template.config, true, 11), + new lib.ValidationError("Templates cannot inherit from themselves"), + ); + }); + it("should reject making an assigned instance a template", function () { + instance.config.set("instance.assigned_host", 5); + assert.throws( + () => instances.checkInheritance(instance.config, true, null), + new lib.ConflictError("Instance must be unassigned before it can be made a template"), + ); + }); + it("should reject unmarking a template that has inheritors", function () { + assert.throws( + () => instances.checkInheritance(template.config, false, null), + new lib.ConflictError("Instance is the template of 1 other instance(s)"), + ); + }); + }); + + it("should not assign a template to a host", async function () { + controller.wsServer.hostConnections.set(5, { send: async () => {}, connector: { closing: false } }); + await assert.rejects( + instances.assignInstance(10, 5), + new lib.ValidationError("Templates cannot be assigned to a host"), + ); + }); + + it("should not delete a template that has inheritors", async function () { + await assert.rejects( + instances.deleteInstance(10), + new lib.ConflictError("Instance is the template of 1 other instance(s)"), + ); + }); + + it("should report templates in instance details", function () { + assert.equal(template.toInstanceDetails().isTemplate, true); + assert.equal(child.toInstanceDetails().isTemplate, false); + }); + }); }); diff --git a/test/controller/InstanceRecord.test.js b/test/controller/InstanceRecord.test.js index 7b496bad..37216599 100644 --- a/test/controller/InstanceRecord.test.js +++ b/test/controller/InstanceRecord.test.js @@ -153,6 +153,17 @@ describe("controller/InstanceRecord", function () { assert.equal(details.startedAtMs, 100); assert.equal(details.updatedAtMs, 200); assert.equal(details.excludeFromStartAll, false); + assert.equal(details.modPackId, undefined); + }); + + it("should include the mod pack set in the config", function () { + const config = new lib.InstanceConfig("controller", { + "instance.id": 1, + "instance.name": "TestInstance", + "factorio.mod_pack_id": 3, + }); + const details = new InstanceRecord(config, "stopped").toInstanceDetails(); + assert.equal(details.modPackId, 3); }); }); diff --git a/test/controller/UserManager.test.js b/test/controller/UserManager.test.js index 62ca5209..c9034274 100644 --- a/test/controller/UserManager.test.js +++ b/test/controller/UserManager.test.js @@ -135,6 +135,31 @@ describe("controller/UserManager", function () { }); }); + describe(".verifyUserToken()", function () { + const secret = () => Buffer.from(config.get("controller.auth_secret"), "base64"); + + it("should return the user the token was signed for", function () { + const user = userManager.createUser("Judy"); + assert.equal(userManager.verifyUserToken(userManager.signUserToken(user)).id, user.id); + }); + it("should reject a token for an unknown user", function () { + const token = userManager.signUserToken({ id: "nobody" }); + assert.throws(() => userManager.verifyUserToken(token), new Error("invalid user")); + }); + it("should reject a token issued before tokenValidAfter", function () { + const user = userManager.createUser("Mallory"); + const token = jwt.sign({ aud: "user", user: user.id, iat: user.tokenValidAfter - 1 }, secret()); + assert.throws(() => userManager.verifyUserToken(token), new Error("invalid token")); + }); + it("should reject host tokens and bad signatures", function () { + const user = userManager.createUser("Niaj"); + const hostToken = jwt.sign({ aud: "host", host: 5 }, secret()); + assert.throws(() => userManager.verifyUserToken(hostToken), /audience invalid/); + const forged = jwt.sign({ aud: "user", user: user.id }, "wrong secret"); + assert.throws(() => userManager.verifyUserToken(forged), /invalid signature/); + }); + }); + describe(".clearStatsOfInstance()", function () { it("should clear instance stats for all users", function () { const instanceId = 42; diff --git a/test/controller/WsServer.js b/test/controller/WsServer.js index c366b1ab..f6fc513f 100644 --- a/test/controller/WsServer.js +++ b/test/controller/WsServer.js @@ -1,7 +1,32 @@ import assert from "node:assert/strict"; import events from "node:events"; -import { Controller, WsServer } from "@clusterio/controller"; +import jwt from "jsonwebtoken"; +import * as lib from "@clusterio/lib"; +import { Controller, HostRecord, WsServer } from "@clusterio/controller"; import { ControllerConfig } from "@clusterio/lib"; +import packageJson from "@clusterio/controller/package.json" with { type: "json" }; + +import "../setup_logging.js"; + +class MockWebSocket extends events.EventEmitter { + constructor() { + super(); + this.sent = []; + this.closed = null; + } + + send(message) { + this.sent.push(JSON.parse(message)); + } + + close(code, reason) { + this.closed = { code, reason }; + } + + terminate() { + this.emit("close", 1006, ""); + } +} describe("controller/src/WsServer", function() { describe("class WsServer", function() { @@ -88,4 +113,104 @@ describe("controller/src/WsServer", function() { }); }); }); + describe(".registerHost()", function() { + const secret = Buffer.from("TestSecretDoNotUse"); + const req = { socket: { remoteAddress: "10.0.0.1", remoteFamily: "IPv4" }, headers: {} }; + /** @type {Controller} */ + let controller; + /** @type {WsServer} */ + let wsServer; + let socket; + beforeEach(function() { + const config = new ControllerConfig("controller"); + config.set("controller.auth_secret", secret.toString("base64")); + controller = new Controller(lib.logger, [], config); + wsServer = controller.wsServer; + socket = new MockWebSocket(); + }); + afterEach(function() { + for (const connection of wsServer.hostConnections.values()) { + connection.connector.terminate(); + } + }); + + function addHost(id, tokenValidAfter = 0) { + const record = new HostRecord(id, `host-${id}`, "", new Map(), false, "", "203.0.113.1", tokenValidAfter); + controller.hosts.records.set(record); + return record; + } + + async function register(token, id = 5) { + await wsServer.registerHost(new lib.RegisterHostData(token, packageJson.version, id, {}), socket, req); + } + + function assertRejected(reason) { + assert.deepEqual(socket.closed, { code: lib.ConnectionClosed.Unauthorized, reason }); + assert.equal(socket.closed.code, 3000); + assert.equal(wsServer.hostConnections.size, 0); + assert(!socket.sent.some(message => message.type === "ready"), "ready was sent"); + } + + it("should reject a validly signed token for a host that is not registered", async function() { + await register(controller.hosts.signHostToken(5)); + assertRejected( + "Authentication failed: host is not registered, start the host again to request to join the cluster" + ); + assert.equal(controller.hosts.has(5), false, "host record was created"); + }); + it("should accept a registered host", async function() { + const record = addHost(5); + await register(controller.hosts.signHostToken(5)); + assert.equal(socket.closed, null); + assert(socket.sent.some(message => message.type === "ready"), "ready was not sent"); + assert(wsServer.hostConnections.has(5)); + + assert.equal(controller.hosts.records.size, 1); + assert.equal(controller.hosts.get(5), record, "host record was replaced"); + assert.equal(record.connected, true); + assert.equal(record.version, packageJson.version); + assert.equal(record.remoteAddress, "10.0.0.1"); + assert.equal(record.name, "host-5"); + assert.equal(record.publicAddress, "203.0.113.1"); + + wsServer.hostConnections.get(5).connector.terminate(); + assert.equal(wsServer.hostConnections.has(5), false); + assert.equal(controller.hosts.get(5).connected, false); + }); + it("should reject a token issued before tokenValidAfter", async function() { + const token = controller.hosts.signHostToken(5); + addHost(5, Math.floor(Date.now() / 1000) + 60); + await register(token); + assertRejected("Authentication failed: invalid token"); + }); + it("should accept a token issued at tokenValidAfter", async function() { + const now = Math.floor(Date.now() / 1000); + addHost(5, now); + await register(jwt.sign({ aud: "host", host: 5, iat: now }, secret)); + assert.equal(socket.closed, null); + assert(wsServer.hostConnections.has(5)); + }); + it("should reject a host revoked while its previous connection closes", async function() { + const record = addHost(5); + wsServer.hostConnections.set(5, { + remoteAddress: "10.0.0.1", + async disconnect() { + controller.hosts.records.delete(record); + wsServer.hostConnections.delete(5); + }, + }); + await register(controller.hosts.signHostToken(5)); + assertRejected("Authentication failed: host was revoked"); + assert.equal(controller.hosts.has(5), false, "host record was recreated"); + }); + it("should reject hosts in recovery mode", async function() { + addHost(5); + controller.recoveryMode = true; + await register(controller.hosts.signHostToken(5)); + assert.deepEqual(socket.closed, { + code: lib.ConnectionClosed.RecoveryMode, + reason: "Connection Refused: Controller in recovery mode", + }); + }); + }); }); diff --git a/test/controller/routes.js b/test/controller/routes.js index 6469fac1..b99f8507 100644 --- a/test/controller/routes.js +++ b/test/controller/routes.js @@ -1,8 +1,15 @@ import assert from "node:assert/strict"; import events from "node:events"; +import fs from "node:fs/promises"; import http from "node:http"; +import os from "node:os"; +import path from "node:path"; +import jwt from "jsonwebtoken"; +import express from "express"; + +import * as lib from "@clusterio/lib"; +import { HostPairingManager, HostRecord } from "@clusterio/controller"; -import { wait, expositionContentType } from "@clusterio/lib"; import * as routes from "@clusterio/controller/dist/node/src/routes.js"; import * as mock from "../mock.js"; @@ -100,7 +107,7 @@ describe("controller/src/routes", function() { stream = await routes.createProxyStream(controller.app); responses = await Promise.all([ (async function() { - await wait(100); + await lib.wait(100); return await fetch(`${endpoint}/${stream.id}`, { method: "PUT", body: "test content", }); @@ -116,7 +123,7 @@ describe("controller/src/routes", function() { method: "PUT", body: "test content", }), (async function() { - await wait(100); + await lib.wait(100); return await fetch(`${endpoint}/${stream.id}`); }()), ]); @@ -163,7 +170,7 @@ describe("controller/src/routes", function() { let response = await fetch(endpoint, { headers }); assert.equal(response.status, 200); const contentType = response.headers.get("content-type"); - for (const part of expositionContentType.split("; ")) { + for (const part of lib.expositionContentType.split("; ")) { assert(contentType.includes(part), `expected ${part} in content type ${contentType}`); } assert(/^# HELP /m.test(await response.text()), "expected exposition text"); @@ -173,7 +180,7 @@ describe("controller/src/routes", function() { let calls = 0; controller.hooks.metrics.attach("test", async () => { calls += 1; - await wait(100); + await lib.wait(100); }); const headers = { "X-Access-Token": testToken }; let responses = await Promise.all([ @@ -190,6 +197,42 @@ describe("controller/src/routes", function() { assert.equal(calls, 2); }); }); + describe("missingExportAsset()", function() { + let dir; + beforeEach(async function() { + dir = await fs.mkdtemp(path.join(os.tmpdir(), "clusterio-static-")); + await fs.writeFile(path.join(dir, "locale.abc.json"), "[]"); + const provider = new lib.MemoryDatastoreProvider(); + controller.modPacks = new lib.SubscribableDatastore(provider, new Map()); + const modPack = lib.ModPack.fromJSON({ id: 1, name: "test" }); + modPack.exportManifest = new lib.ExportManifest({ + locale: "locale.abc.json", metadata: "metadata.abc.json", + }); + controller.modPacks.set(modPack); + controller.app.use("/static", express.static(dir)); + controller.app.use("/static", routes.missingExportAsset); + }); + afterEach(async function() { + await fs.rm(dir, { recursive: true, force: true }); + }); + it("should serve export files that exist", async function() { + const response = await fetch(`http://localhost:${port}/static/locale.abc.json`); + assert.equal(response.status, 200); + assert(controller.modPacks.get(1).exportManifest); + }); + it("should drop the export and explain when a file is missing", async function() { + const response = await fetch(`http://localhost:${port}/static/metadata.abc.json`); + assert.equal(response.status, 404); + assert.match(await response.text(), /metadata\.abc\.json is missing/); + assert.equal(controller.modPacks.get(1).exportManifest, undefined); + }); + it("should pass through files not in an export", async function() { + const response = await fetch(`http://localhost:${port}/static/other.js`); + assert.equal(response.status, 404); + assert.doesNotMatch(await response.text(), /export-data/); + assert(controller.modPacks.get(1).exportManifest); + }); + }); describe("stripStaticPrefix()", function() { it("should remove a leading static/", function() { assert.equal(routes.stripStaticPrefix("static/main.abc.js"), "main.abc.js"); @@ -262,6 +305,293 @@ describe("controller/src/routes", function() { assert.deepEqual(data, { name: "Test Cluster" }); }); }); + describe("/api/host-pairing", function() { + let endpoint, adminToken, playerToken; + beforeEach(function() { + endpoint = `http://localhost:${port}/api/host-pairing`; + // The mock controller lacks what pairing needs, use the real implementations. + controller.hostPairing = new HostPairingManager(controller); + controller.wsServer.remoteAddr = req => req.socket.remoteAddress; + adminToken = controller.users.signUserToken(controller.users.getByName("test")); + playerToken = controller.users.signUserToken(controller.users.getByName("player")); + }); + + function createHost(name) { + const host = controller.hosts.createHost(name); + return { hostId: host.id, token: controller.hosts.signHostToken(host.id) }; + } + + function post(urlPath, body, headers = {}) { + return fetch(`${endpoint}${urlPath}`, { + method: "POST", + headers: { "Content-Type": "application/json", ...headers }, + body: typeof body === "string" || body === undefined ? body : JSON.stringify(body), + }); + } + + async function assertResponse(response, status, body) { + assert.equal(response.status, status); + assert.equal(response.headers.get("cache-control"), "no-store"); + if (body !== undefined) { + assert.deepEqual(await response.json(), body); + } + } + + async function createRequest(name = "Host A") { + const response = await post("", { name }); + assert.equal(response.status, 202); + return await response.json(); + } + + function check(headers) { + return fetch(`${endpoint}/check`, { headers }); + } + + function assertNothingCreated() { + assert.equal(controller.hostPairing.records.size, 0, "a pending request was created"); + assert.equal(controller.hosts.records.size, 0, "a host was created"); + } + + describe("POST /api/host-pairing", function() { + it("should create a pending request", async function() { + const response = await post("", { name: "Host A", version: "2.0.0" }); + assert.equal(response.status, 202); + assert.equal(response.headers.get("cache-control"), "no-store"); + const body = await response.json(); + assert.deepEqual(Object.keys(body).sort(), ["code", "requestId"]); + assert.match(body.code, /^[2-9A-HJKMNP-Z]{3}-[2-9A-HJKMNP-Z]{3}$/); + + const details = controller.hostPairing.records.get(body.code); + assert.equal(details.name, "Host A"); + assert.equal(details.version, "2.0.0"); + assert.match(details.remoteAddress, /127\.0\.0\.1|::1/); + assert.equal(controller.hosts.records.size, 0); + }); + it("should trim the name and limit the version", async function() { + let { code } = await (await post("", { name: " Host A ", version: "x".repeat(100) })).json(); + let details = controller.hostPairing.records.get(code); + assert.equal(details.name, "Host A"); + assert.equal(details.version, "x".repeat(64)); + + ({ code } = await (await post("", { name: "Host B", version: 5 })).json()); + details = controller.hostPairing.records.get(code); + assert.equal(details.version, ""); + }); + it("should respond with 400 for a missing or invalid name", async function() { + const required = { error: "Host name is required" }; + await assertResponse(await post("", {}), 400, required); + await assertResponse(await post("", { name: "" }), 400, required); + await assertResponse(await post("", { name: " " }), 400, required); + await assertResponse(await post("", { name: 5 }), 400, required); + await assertResponse(await post("", undefined), 400, required); + await assertResponse(await post("", "name=Host", { "Content-Type": "text/plain" }), 400, required); + await assertResponse( + await post("", { name: "x".repeat(101) }), + 400, { error: "Host name must be at most 100 characters" }, + ); + assertNothingCreated(); + }); + it("should respond with 400 for malformed JSON", async function() { + controller.app.set("env", "test"); // Silence the default error handler + const response = await post("", "{\"name\":"); + assert.equal(response.status, 400); + assertNothingCreated(); + }); + it("should respond with 413 for a body over 4kb", async function() { + controller.app.set("env", "test"); // Silence the default error handler + const response = await post("", { name: "x".repeat(5000) }); + assert.equal(response.status, 413); + assertNothingCreated(); + }); + it("should respond with 429 and Retry-After when limited", async function() { + for (let i = 0; i < 3; i++) { + await createRequest(); + } + const response = await post("", { name: "Host A" }); + assert.equal(response.headers.get("retry-after"), "30"); + await assertResponse(response, 429, { error: "Too many pending requests from this address" }); + assert.equal(controller.hostPairing.records.size, 3); + }); + it("should respond with 503 in recovery mode", async function() { + controller.recoveryMode = true; + const recovery = { error: "Controller is in recovery mode" }; + await assertResponse(await post("", { name: "Host A" }), 503, recovery); + await assertResponse( + await post("", { name: "Host A" }, { "Authorization": `Bearer ${adminToken}` }), 503, recovery + ); + assertNothingCreated(); + }); + it("should approve directly with the token of a user allowed to approve hosts", async function() { + for (const headers of [ + { "Authorization": `Bearer ${adminToken}` }, + { "Authorization": `bearer ${adminToken}` }, + { "X-Access-Token": adminToken }, + ]) { + const response = await post("", { name: "Host A" }, headers); + assert.equal(response.status, 200); + assert.equal(response.headers.get("cache-control"), "no-store"); + const body = await response.json(); + assert.deepEqual(Object.keys(body).sort(), ["hostId", "name", "token"]); + assert.equal(body.name, "Host A"); + assert.equal(controller.hosts.get(body.hostId).name, "Host A"); + const payload = jwt.verify(body.token, controller.authSecret, { audience: "host" }); + assert.equal(payload.host, body.hostId); + } + assert.equal(controller.hosts.records.size, 3); + assert.equal(controller.hostPairing.records.size, 0, "a pending request was created"); + }); + it("should validate the name before approving directly", async function() { + await assertResponse( + await post("", {}, { "Authorization": `Bearer ${adminToken}` }), + 400, { error: "Host name is required" }, + ); + assertNothingCreated(); + }); + it("should respond with 403 for a user not allowed to approve hosts", async function() { + await assertResponse( + await post("", { name: "Host A" }, { "Authorization": `Bearer ${playerToken}` }), + 403, { error: "User player is not allowed to approve hosts" }, + ); + assertNothingCreated(); + }); + it("should respond with 401 for an invalid token without creating a request", async function() { + // The admin user's tokens are revoked after signing this one + const revokedToken = adminToken; + const user = controller.users.getOrCreateUser("test"); + user.tokenValidAfter = Math.floor((Date.now() + 60e3) / 1000); + user.saveRecord(); + controller.hosts.records.set(new HostRecord(5, "five", "", new Map())); + const hostToken = controller.hosts.signHostToken(5); + controller.hosts.records.delete(controller.hosts.get(5)); + + for (const headers of [ + { "Authorization": "Bearer invalid" }, + { "X-Access-Token": "invalid" }, + { "Authorization": `Bearer ${controller.users.signUserToken({ id: "nobody" })}` }, + { "Authorization": `Bearer ${revokedToken}` }, + { "Authorization": `Bearer ${hostToken}` }, + ]) { + await assertResponse( + await post("", { name: "Host A" }, headers), 401, { error: "Invalid user token" } + ); + } + assertNothingCreated(); + }); + }); + + describe("POST /api/host-pairing/poll", function() { + it("should respond with 202 while pending", async function() { + const { requestId } = await createRequest(); + await assertResponse(await post("/poll", { requestId }), 202, { status: "pending" }); + await assertResponse(await post("/poll", { requestId }), 202, { status: "pending" }); + }); + it("should hand over the result of an approved request once", async function() { + const { requestId, code } = await createRequest(); + const hostId = controller.hostPairing.approve(code, "Renamed", "test"); + + const response = await post("/poll", { requestId }); + assert.equal(response.status, 200); + assert.equal(response.headers.get("cache-control"), "no-store"); + const body = await response.json(); + assert.deepEqual(Object.keys(body).sort(), ["hostId", "name", "token"]); + assert.equal(body.hostId, hostId); + assert.equal(body.name, "Renamed"); + assert.equal(jwt.verify(body.token, controller.authSecret, { audience: "host" }).host, hostId); + + await assertResponse(await post("/poll", { requestId }), 404, { error: "Request not found" }); + }); + it("should respond with 403 once for a rejected request", async function() { + const { requestId, code } = await createRequest(); + controller.hostPairing.reject(code, "test"); + await assertResponse(await post("/poll", { requestId }), 403, { error: "Request was rejected" }); + await assertResponse(await post("/poll", { requestId }), 404, { error: "Request not found" }); + }); + it("should respond with 404 for an unknown request", async function() { + const { code } = await createRequest(); + const notFound = { error: "Request not found" }; + await assertResponse(await post("/poll", { requestId: "invalid" }), 404, notFound); + await assertResponse(await post("/poll", { requestId: code }), 404, notFound); + }); + it("should respond with 400 without a requestId in the body", async function() { + const { requestId } = await createRequest(); + const required = { error: "requestId is required" }; + await assertResponse(await post("/poll", {}), 400, required); + await assertResponse(await post("/poll", { requestId: 5 }), 400, required); + await assertResponse(await post(`/poll?requestId=${encodeURIComponent(requestId)}`, {}), 400, required); + }); + it("should respond with 503 in recovery mode", async function() { + const { requestId } = await createRequest(); + controller.recoveryMode = true; + await assertResponse( + await post("/poll", { requestId }), 503, { error: "Controller is in recovery mode" } + ); + }); + }); + + describe("POST /api/host-pairing/cancel", function() { + it("should cancel a pending request", async function() { + const { requestId, code } = await createRequest(); + await assertResponse(await post("/cancel", { requestId }), 204); + assert.equal(controller.hostPairing.records.has(code), false); + await assertResponse(await post("/poll", { requestId }), 404, { error: "Request not found" }); + }); + it("should respond with 204 for an unknown request", async function() { + const { code } = await createRequest(); + await assertResponse(await post("/cancel", { requestId: "invalid" }), 204); + await assertResponse(await post("/cancel", { requestId: code }), 204); + assert(controller.hostPairing.records.has(code), "cancelled by the code"); + }); + }); + + describe("request ids", function() { + it("should not be accepted in the URL", async function() { + const { requestId } = await createRequest(); + const id = encodeURIComponent(requestId); + for (const [method, urlPath] of [ + ["GET", `/poll?requestId=${id}`], + ["GET", `/poll/${id}`], + ["POST", `/poll/${id}`], + ["POST", `/${id}`], + ["GET", `/${id}`], + ["POST", `/cancel/${id}`], + ]) { + const response = await fetch(`${endpoint}${urlPath}`, { method }); + assert.equal(response.status, 404, `${method} ${urlPath}`); + } + await assertResponse(await post("/poll", { requestId }), 202, { status: "pending" }); + }); + }); + + describe("GET /api/host-pairing/check", function() { + it("should respond with 200 for a valid host token", async function() { + const { hostId, token } = createHost("Host A"); + for (const headers of [ + { "Authorization": `Bearer ${token}` }, + { "X-Access-Token": token }, + ]) { + await assertResponse(await check(headers), 200, { valid: true }); + } + assert(controller.hosts.has(hostId)); + }); + it("should respond with 200 for a host token from before the slave rename", async function() { + const { hostId } = createHost("Host A"); + const token = jwt.sign({ aud: "slave", slave: hostId }, controller.authSecret); + await assertResponse(await check({ "Authorization": `Bearer ${token}` }), 200, { valid: true }); + }); + it("should respond with 401 without a valid host token", async function() { + createHost("Host A"); + assert.equal((await check({})).status, 401); + assert.equal((await check({ "Authorization": "Bearer invalid" })).status, 401); + assert.equal((await check({ "Authorization": `Bearer ${adminToken}` })).status, 401); + }); + it("should respond with 401 once the host is revoked", async function() { + const { hostId, token } = createHost("Host A"); + await assertResponse(await check({ "Authorization": `Bearer ${token}` }), 200, { valid: true }); + controller.hosts.records.delete(controller.hosts.get(hostId)); + assert.equal((await check({ "Authorization": `Bearer ${token}` })).status, 401); + }); + }); + }); describe("/api/upload-save", function() { let endpoint, testToken; beforeEach(function() { diff --git a/test/create.js b/test/create.js index a52d0304..36f0559c 100644 --- a/test/create.js +++ b/test/create.js @@ -5,6 +5,8 @@ import os from "node:os"; import path from "node:path"; import { promisify } from "node:util"; +import { escapeArg } from "../packages/create/escape_arg.js"; + const execFileAsync = promisify(execFile); const installer = path.resolve(import.meta.dirname, "../packages/create/create.js"); const discoveryUrl = new URL("../packages/lib/dist/node/src/load_plugin_list.js", import.meta.url).href; @@ -123,4 +125,112 @@ describe("create installer CLI", function() { return true; }); }); + + describe("host setup", function() { + const scriptExt = process.platform === "win32" ? ".cmd" : ""; + const hostBin = path.join("node_modules", ".bin", `clusteriohost${scriptExt}`); + const controllerBin = path.join("node_modules", ".bin", `clusteriocontroller${scriptExt}`); + const hostSet = (field, value) => `${hostBin} config set ${field} ${escapeArg(String(value))}`; + const controllerUrl = "http://controller.example.com:8080/"; + + function run(args, env = {}) { + // Record the commands for npm and the clusterio CLIs instead of running them. + const mockExec = ` + import childProcess from "node:child_process"; + import fs from "node:fs"; + import { PassThrough } from "node:stream"; + childProcess.execFile = (command, options, callback) => { + fs.appendFileSync(process.env.CREATE_TEST_COMMANDS, JSON.stringify(command) + "\\n"); + const stdout = new PassThrough(); + const stderr = new PassThrough(); + queueMicrotask(() => { + stdout.end(); + stderr.end(); + callback(null, "", ""); + }); + return { stdout, stderr }; + }; + `; + return execFileAsync(process.execPath, [ + "--import", `data:text/javascript,${encodeURIComponent(mockExec)}`, + installer, + ...(process.platform === "linux" ? ["--allow-install-as-root"] : []), + ...args, + ], { + cwd: directory, + env: { ...process.env, CREATE_TEST_COMMANDS: path.join(directory, "commands.jsonl"), ...env }, + }); + } + + // Commands run by the installer, without the getent lookups made when writing systemd units. + async function commands() { + const content = await fs.readFile(path.join(directory, "commands.jsonl"), "utf8"); + return content.split("\n").filter(Boolean).map(line => JSON.parse(line)) + .filter(command => !command.startsWith("getent ")); + } + + function hostArgs(url = controllerUrl) { + return [ + "--mode", "host", "--host-name", "Test Host", "--controller-url", url, + "--public-address", "host.example.com", "--factorio-dir", "factorio", "--no-remote-npm", "--plugins", + ]; + } + + it("writes the host config and leaves joining the cluster to the host", async function() { + const { stdout } = await run(hostArgs()); + assert.match(stdout, /Successfully installed host/); + + const recorded = await commands(); + assert.match(recorded[0], /^npm(?:\.cmd)? install @clusterio\/host$/); + assert.deepEqual(recorded.slice(1), [ + `${hostBin} config create`, + hostSet("host.name", "Test Host"), + hostSet("host.controller_url", controllerUrl), + hostSet("host.public_address", "host.example.com"), + hostSet("host.factorio_directory", "factorio"), + hostSet("host.allow_remote_updates", false), + hostSet("host.allow_plugin_updates", false), + hostSet("host.allow_plugin_install", false), + ]); + await fs.access(path.join(directory, `run-host${process.platform === "win32" ? ".cmd" : ".sh"}`)); + }); + + it("adds the trailing slash the host requires to the controller URL", async function() { + await run(hostArgs(controllerUrl.slice(0, -1))); + assert((await commands()).includes(hostSet("host.controller_url", controllerUrl))); + }); + + it("leaves joining the cluster to the host of a standalone install", async function() { + await fs.writeFile(path.join(directory, "config-controller.json"), "{}"); + const { stdout } = await run([ + "--mode", "standalone", "--admin", "admin", "--http-port", "8123", "--public-address", "localhost", + "--factorio-dir", "factorio", "--remote-npm", "--plugins", + ]); + assert.match(stdout, /Successfully installed standalone/); + + const recorded = await commands(); + for (const expected of [ + hostSet("host.name", "local"), + hostSet("host.controller_url", "http://localhost:8123/"), + `${controllerBin} config set controller.allow_remote_updates true`, + `${controllerBin} config set controller.allow_plugin_updates true`, + `${controllerBin} config set controller.allow_plugin_install true`, + hostSet("host.allow_remote_updates", true), + hostSet("host.allow_plugin_updates", true), + hostSet("host.allow_plugin_install", true), + ]) { + assert(recorded.includes(expected), `missing ${expected}`); + } + assert(!recorded.some(command => command.includes("host.controller_token"))); + }); + + it("uses the host name given for a standalone install", async function() { + await fs.writeFile(path.join(directory, "config-controller.json"), "{}"); + await run([ + "--mode", "standalone", "--admin", "admin", "--http-port", "8123", "--public-address", "localhost", + "--factorio-dir", "factorio", "--remote-npm", "--plugins", "--host-name", "Test Host", + ]); + assert((await commands()).includes(hostSet("host.name", "Test Host"))); + }); + }); }); diff --git a/test/file/factorio-mixed/full/data/base/graphics/icons/graphics-icon.png b/test/file/factorio-mixed/full/data/base/graphics/icons/graphics-icon.png new file mode 100644 index 00000000..b2f06ccc Binary files /dev/null and b/test/file/factorio-mixed/full/data/base/graphics/icons/graphics-icon.png differ diff --git a/test/file/factorio-mixed/full/data/changelog.txt b/test/file/factorio-mixed/full/data/changelog.txt new file mode 100644 index 00000000..2b12ff4b --- /dev/null +++ b/test/file/factorio-mixed/full/data/changelog.txt @@ -0,0 +1,3 @@ +--------------------------------------------------------------------------------------------------- +Version: 0.1.2 +About: Dummy changelog.txt for FactorioServer tests diff --git a/test/file/factorio-mixed/headless/data/changelog.txt b/test/file/factorio-mixed/headless/data/changelog.txt new file mode 100644 index 00000000..2b12ff4b --- /dev/null +++ b/test/file/factorio-mixed/headless/data/changelog.txt @@ -0,0 +1,3 @@ +--------------------------------------------------------------------------------------------------- +Version: 0.1.2 +About: Dummy changelog.txt for FactorioServer tests diff --git a/test/host/export.js b/test/host/export.js index 43109532..b5f12579 100644 --- a/test/host/export.js +++ b/test/host/export.js @@ -2,7 +2,9 @@ import assert from "node:assert/strict"; import path from "node:path"; import { FactorioServer } from "@clusterio/host/dist/node/src/server.js"; -import { _exportLocale, _loadLayeredIcon, _loadSimpleIcon } from "@clusterio/host/dist/node/src/export.js"; +import { + _checkMissingBuiltinIcons, _createSheetState, _exportIcons, _exportLocale, _loadLayeredIcon, _loadSimpleIcon, +} from "@clusterio/host/dist/node/src/export.js"; describe("host/src/export", function() { @@ -12,7 +14,25 @@ describe("host/src/export", function() { testServer = await FactorioServer.fromOptions(path.join("test", "file", "factorio"), writePath, {}); }); + let warnings; + let originalLogger; + beforeEach(function() { + warnings = []; + originalLogger = testServer._logger; + testServer._logger = Object.create(originalLogger, { warn: { value: message => warnings.push(message) } }); + }); + afterEach(function() { + testServer._logger = originalLogger; + }); + describe("exportLocale()", function() { + it("warns about mods without a zip and exports the rest", async function() { + const locale = await _exportLocale( + testServer, new Map([["missing_mod", "1.0.0"]]), new Map(), ["base", "missing_mod"], "en" + ); + assert.equal(locale.size > 0, true); + assert.deepEqual(warnings, ["Skipping locale of missing_mod, its mod zip was not found"]); + }); it("returns a flattened mapping with locale definitions", async function() { let locale = await _exportLocale(testServer, new Map(), new Map(), ["base"], "en"); assert.deepEqual(locale, new Map([ @@ -30,20 +50,59 @@ describe("host/src/export", function() { // test-icon.png is a red 64px icon followed by a blue 32px mipmap const red = 0xff0000ff; + describe("exportIcons()", function() { + it("skips icons that fail to load and exports the rest", async function() { + const state = await _createSheetState(); + const icon = "__base__/graphics/icons/test-icon.png"; + const prototypes = [ + { type: "item", name: "first", icon, icon_size: 64 }, + { type: "item", name: "no-layers", icons: [] }, + { type: "item", name: "unknown-mod", icon: "__not-a-mod__/graphics/icons/x.png", icon_size: 64 }, + { type: "item", name: "last", icon, icon_size: 64 }, + ]; + const count = await _exportIcons(testServer, new Map(), { zipCache: new Map() }, prototypes, "item", state); + assert.equal(count, 2); + assert.deepEqual( + state.metadata.item.map(entry => [entry.name, Boolean(entry.icon)]), + [["first", true], ["no-layers", false], ["unknown-mod", false], ["last", true]], + ); + assert.equal(warnings.length, 2); + assert.match(warnings[0], /^Skipping icon of item no-layers: /); + assert.match(warnings[1], /^Skipping icon of item unknown-mod: Got path for unknown mod not-a-mod/); + }); + }); + + // Stands in for the data dir of a full install + const graphicsDataDir = path.join("test", "file", "factorio-mixed", "full", "data"); describe("loadSimpleIcon()", function() { it("defaults icon_size to 64", async function() { const icon = await _loadSimpleIcon( - testServer, new Map(), new Map(), { icon: "__base__/graphics/icons/test-icon.png" }, 32, new Map() + testServer, new Map(), { zipCache: new Map() }, + { icon: "__base__/graphics/icons/test-icon.png" }, 32, new Map(), ); assert.equal(icon.bitmap.width, 32); assert.equal(icon.bitmap.height, 32); assert.equal(icon.getPixelColor(31, 16), red); }); + it("returns null when the icon file is missing", async function() { + const icon = await _loadSimpleIcon( + testServer, new Map(), { zipCache: new Map() }, + { icon: "__base__/graphics/icons/graphics-icon.png" }, 32, new Map(), + ); + assert.equal(icon, null); + }); + it("falls back to graphicsDataDir for builtin mod files", async function() { + const icon = await _loadSimpleIcon( + testServer, new Map(), { zipCache: new Map(), graphicsDataDir }, + { icon: "__base__/graphics/icons/graphics-icon.png" }, 32, new Map(), + ); + assert.equal(icon.getPixelColor(31, 16), red); + }); }); describe("loadLayeredIcon()", function() { it("defaults icon_size to 64", async function() { const icon = await _loadLayeredIcon( - testServer, new Map(), new Map(), + testServer, new Map(), { zipCache: new Map() }, { icons: [{ icon: "__base__/graphics/icons/test-icon.png" }] }, 32, new Map(), ); assert.equal(icon.bitmap.width, 32); @@ -51,5 +110,43 @@ describe("host/src/export", function() { assert.equal(icon.getPixelColor(0, 0), red); assert.equal(icon.getPixelColor(31, 31), red); }); + it("returns null when a layer is missing", async function() { + const icon = await _loadLayeredIcon( + testServer, new Map(), { zipCache: new Map() }, + { icons: [ + { icon: "__base__/graphics/icons/test-icon.png" }, + { icon: "__base__/graphics/icons/missing.png" }, + ] }, 32, new Map(), + ); + assert.equal(icon, null); + }); + }); + describe("checkMissingBuiltinIcons()", function() { + it("warns once with the number of missing builtin files", function() { + _checkMissingBuiltinIcons(testServer, { zipCache: new Map() }, new Map([ + ["__base__/graphics/icons/a.png", null], + ["__core__/graphics/icons/b.png", null], + ["__base__/graphics/icons/c.png", {}], + ["__some_mod__/graphics/icons/d.png", null], + ])); + assert.equal(warnings.length, 1); + assert.match(warnings[0], /^2 icon files of the base game were not found/); + assert.doesNotMatch(warnings[0], /headless/); + }); + it("explains the headless build when no full install was found", function() { + _checkMissingBuiltinIcons(testServer, { zipCache: new Map(), graphicsError: "Not found" }, new Map([ + ["__base__/graphics/icons/a.png", null], + ])); + assert.equal(warnings.length, 1); + assert.match(warnings[0], /has no graphics and no full install was found \(Not found\)/); + assert.match(warnings[0], /Add a full install of Factorio 0\.1 to host\.factorio_directory/); + }); + it("does not warn when no builtin files are missing", function() { + _checkMissingBuiltinIcons(testServer, { zipCache: new Map() }, new Map([ + ["__base__/graphics/icons/c.png", {}], + ["__some_mod__/graphics/icons/d.png", null], + ])); + assert.deepEqual(warnings, []); + }); }); }); diff --git a/test/host/pairing.js b/test/host/pairing.js new file mode 100644 index 00000000..bb5e98c6 --- /dev/null +++ b/test/host/pairing.js @@ -0,0 +1,334 @@ +import assert from "node:assert/strict"; +import events from "node:events"; +import fs from "node:fs/promises"; +import http from "node:http"; +import os from "node:os"; +import path from "node:path"; + +import * as lib from "@clusterio/lib"; +import { PairingError, checkHostToken, pairHost } from "@clusterio/host"; +import { ensurePaired } from "@clusterio/host/dist/node/src/pairing.js"; + +import "../setup_logging.js"; + +// Stub controller recording requests, responding with what the test's handler returns. +async function startStub() { + const stub = { + requests: [], + handler: () => [500, { error: "No handler" }], + }; + stub.server = http.createServer(async (req, res) => { + const chunks = []; + for await (const chunk of req) { + chunks.push(chunk); + } + const entry = { + method: req.method, + url: req.url, + headers: req.headers, + body: chunks.length ? JSON.parse(Buffer.concat(chunks)) : undefined, + }; + stub.requests.push(entry); + const [status, json, headers = {}] = await stub.handler(entry); + res.writeHead(status, { "Content-Type": "application/json", ...headers }); + res.end(json === undefined ? undefined : JSON.stringify(json)); + }); + stub.server.listen(0, "127.0.0.1"); + await events.once(stub.server, "listening"); + stub.url = `http://127.0.0.1:${stub.server.address().port}/`; + stub.close = async () => { + stub.server.closeAllConnections(); + stub.server.close(); + await events.once(stub.server, "close"); + }; + return stub; +} + +const approved = { hostId: 1234, token: "host-token", name: "Approved" }; + +// Handler for requests that are approved after the given number of pending polls. +function approveAfter(polls, result = approved) { + let pending = 0; + let requests = 0; + return ({ url }) => { + if (url === "/api/host-pairing") { + requests += 1; + return [202, { requestId: `secret-${requests}`, code: `ABC-DE${requests}` }]; + } + if (url === "/api/host-pairing/poll") { + pending += 1; + return pending > polls ? [200, result] : [202, { status: "pending" }]; + } + if (url === "/api/host-pairing/cancel") { + return [204, undefined]; + } + return [404, { error: "Not found" }]; + }; +} + +describe("host/src/pairing", function() { + let stub; + beforeEach(async function() { + stub = await startStub(); + }); + afterEach(async function() { + await stub.close(); + }); + + function pair(options = {}) { + return pairHost({ controllerUrl: stub.url, name: "Host", pollIntervalMs: 10, retryDelayMs: 10, ...options }); + } + + describe("pairHost()", function() { + it("returns the host when approved with a user token", async function() { + stub.handler = ({ headers }) => (headers.authorization === "Bearer user-token" + ? [200, approved] + : [401, { error: "Invalid user token" }] + ); + const result = await pair({ token: "user-token", onPending: () => assert.fail("should not wait") }); + assert.deepEqual(result, approved); + assert.equal(stub.requests.length, 1); + }); + + it("polls until the request is approved", async function() { + stub.handler = approveAfter(2); + const codes = []; + const result = await pair({ version: "2.1.0", onPending: code => { codes.push(code); } }); + assert.deepEqual(result, approved); + assert.deepEqual(codes, ["ABC-DE1"]); + assert.deepEqual(stub.requests[0].body, { name: "Host", version: "2.1.0" }); + assert.equal(stub.requests[0].headers.authorization, undefined); + for (const poll of stub.requests.slice(1)) { + assert.deepEqual(poll.body, { requestId: "secret-1" }); + } + }); + + it("resolves routes under the path of the controller URL", async function() { + stub.handler = ({ url }) => (url === "/sub/api/host-pairing" ? [200, approved] : [404, {}]); + const result = await pair({ controllerUrl: `${stub.url}sub/` }); + assert.equal(result.hostId, 1234); + }); + + it("makes a new request when the previous one expired", async function() { + const handler = approveAfter(0); + let expired = false; + stub.handler = entry => { + if (entry.url === "/api/host-pairing/poll" && !expired) { + expired = true; + return [404, { error: "Request not found" }]; + } + return handler(entry); + }; + const codes = []; + const result = await pair({ onPending: code => { codes.push(code); } }); + assert.deepEqual(result, approved); + assert.deepEqual(codes, ["ABC-DE1", "ABC-DE2"]); + }); + + it("waits and tries again when the controller is busy", async function() { + const handler = approveAfter(0); + let busy = 2; + stub.handler = entry => { + if (entry.url === "/api/host-pairing" && busy > 0) { + busy -= 1; + return busy ? [429, { error: "Too many requests" }] : [503, { error: "Recovery mode" }]; + } + return handler(entry); + }; + const retries = []; + const result = await pair({ onRetry: err => { retries.push(err.message); } }); + assert.deepEqual(result, approved); + assert.deepEqual(retries, ["Too many requests", "Recovery mode"]); + }); + + it("keeps trying while the controller can't be reached", async function() { + const { url } = stub; + await stub.close(); + const abort = new AbortController(); + const errors = []; + await assert.rejects( + pairHost({ + controllerUrl: url, name: "Host", retryDelayMs: 10, signal: abort.signal, + onRetry: err => { + errors.push(err); + if (errors.length === 3) { + abort.abort(); + } + }, + }), + { name: "AbortError" }, + ); + assert.equal(errors.length, 3); + stub = await startStub(); + }); + + it("keeps polling while the controller is busy", async function() { + const handler = approveAfter(0); + let busy = 2; + stub.handler = entry => { + if (entry.url === "/api/host-pairing/poll" && busy > 0) { + busy -= 1; + return [503, { error: "Recovery mode" }]; + } + return handler(entry); + }; + const retries = []; + const result = await pair({ onRetry: err => { retries.push(err.message); } }); + assert.deepEqual(result, approved); + assert.deepEqual(retries, ["Recovery mode", "Recovery mode"]); + }); + + it("throws when the request is rejected", async function() { + const handler = approveAfter(Infinity); + stub.handler = entry => (entry.url === "/api/host-pairing/poll" && stub.requests.length > 2 + ? [403, { error: "Request was rejected" }] + : handler(entry) + ); + await assert.rejects( + pair(), + err => err instanceof PairingError && err.status === 403 && err.message === "Request was rejected", + ); + }); + + it("throws if the controller does not support pairing", async function() { + stub.handler = () => [404, undefined]; + await assert.rejects( + pair(), + err => err instanceof PairingError && err.status === 404 && /must be updated/.test(err.message), + ); + }); + + it("throws on an invalid user token without waiting", async function() { + stub.handler = () => [401, { error: "Invalid user token" }]; + await assert.rejects( + pair({ token: "bad" }), + err => err instanceof PairingError && err.status === 401 && err.message === "Invalid user token", + ); + assert.equal(stub.requests.length, 1); + }); + + it("cancels the request when aborted", async function() { + const abort = new AbortController(); + const handler = approveAfter(Infinity); + stub.handler = entry => { + if (entry.url === "/api/host-pairing/poll") { + abort.abort(); + } + return handler(entry); + }; + await assert.rejects(pair({ signal: abort.signal }), { name: "AbortError" }); + const cancel = stub.requests.find(r => r.url === "/api/host-pairing/cancel"); + assert.deepEqual(cancel?.body, { requestId: "secret-1" }); + }); + + it("does not send anything if already aborted", async function() { + await assert.rejects(pair({ signal: AbortSignal.abort() }), { name: "AbortError" }); + assert.equal(stub.requests.length, 0); + }); + }); + + describe("checkHostToken()", function() { + it("returns true if the controller accepts the token", async function() { + stub.handler = ({ url, headers }) => ( + url === "/api/host-pairing/check" && headers.authorization === "Bearer host-token" + ? [200, { valid: true }] + : [401, undefined] + ); + assert.equal(await checkHostToken(stub.url, "host-token"), true); + assert.equal(await checkHostToken(stub.url, "other-token"), false); + }); + + it("throws on other responses", async function() { + stub.handler = () => [404, undefined]; + await assert.rejects(checkHostToken(stub.url, "host-token"), PairingError); + }); + }); + + describe("ensurePaired()", function() { + let directory; + let config; + beforeEach(async function() { + directory = await fs.mkdtemp(path.join(os.tmpdir(), "clusterio-pairing-")); + config = new lib.HostConfig("host", undefined, path.join(directory, "config-host.json")); + config.set("host.name", "My Host"); + config.set("host.controller_url", stub.url); + }); + afterEach(async function() { + await fs.rm(directory, { recursive: true, force: true, maxRetries: 10 }); + }); + + async function savedConfig() { + return JSON.parse(await fs.readFile(path.join(directory, "config-host.json"), "utf8")); + } + + it("waits for approval and saves the host when not paired", async function() { + this.timeout(5000); // Polls at the default interval of 2 seconds + stub.handler = approveAfter(0); + const warnings = []; + const originalWarn = lib.logger.warn; + lib.logger.warn = message => { warnings.push(message); }; + try { + await ensurePaired(config, { version: "2.1.0" }); + } finally { + lib.logger.warn = originalWarn; + } + assert.deepEqual(stub.requests[0].body, { name: "My Host", version: "2.1.0" }); + // The systemd service created by the installer only prints warnings and above. + assert(warnings.includes(`${stub.url}hosts?approve=ABC-DE1`), "approval link is not a warning"); + const saved = await savedConfig(); + assert.equal(saved["host.id"], 1234); + assert.equal(saved["host.name"], "Approved"); + assert.equal(saved["host.controller_token"], "host-token"); + }); + + it("does nothing when the controller accepts the saved token", async function() { + config.set("host.controller_token", "valid-token"); + stub.handler = ({ headers }) => (headers.authorization === "Bearer valid-token" + ? [200, { valid: true }] + : [401, undefined] + ); + await ensurePaired(config, { version: "2.1.0" }); + assert.deepEqual(stub.requests.map(r => r.url), ["/api/host-pairing/check"]); + assert.equal(config.get("host.controller_token"), "valid-token"); + }); + + it("asks to join again with the user token when the saved token is not accepted", async function() { + config.set("host.controller_token", "revoked-token"); + stub.handler = ({ url, headers }) => { + if (url === "/api/host-pairing/check") { + return [401, undefined]; + } + return headers.authorization === "Bearer user-token" + ? [200, { hostId: 5, token: "new-token", name: "My Host" }] + : [401, { error: "Invalid user token" }]; + }; + await ensurePaired(config, { version: "2.1.0", userToken: "user-token" }); + const saved = await savedConfig(); + assert.equal(saved["host.id"], 5); + assert.equal(saved["host.controller_token"], "new-token"); + assert(!JSON.stringify(saved).includes("user-token"), "user token must not be saved"); + }); + + it("stops when aborted while checking the saved token", async function() { + config.set("host.controller_token", "some-token"); + const abort = new AbortController(); + stub.handler = () => { + abort.abort(); + return new Promise(() => {}); + }; + await assert.rejects( + ensurePaired(config, { version: "2.1.0", signal: abort.signal }), + { name: "AbortError" }, + ); + assert.equal(config.get("host.controller_token"), "some-token"); + }); + + it("keeps the saved token when it can't be checked", async function() { + config.set("host.controller_token", "some-token"); + stub.handler = () => [404, undefined]; + await ensurePaired(config, { version: "2.1.0" }); + assert.equal(config.get("host.controller_token"), "some-token"); + assert.equal(stub.requests.length, 1); + }); + }); +}); diff --git a/test/host/patch.js b/test/host/patch.js index 7c3e7267..e3f3ab3a 100644 --- a/test/host/patch.js +++ b/test/host/patch.js @@ -271,4 +271,92 @@ describe("host/patch", function() { ); }); }); + + describe("unpatch()", function() { + const freeplayControl = "require('__base__/script/freeplay/control.lua')\n"; + const zipPath = path.join("temp", "test", "unpatch.zip"); + let testModule; + before(async function() { + testModule = new patch.SaveModule(new lib.ModuleInfo("test", "1.0.0")); + await testModule.loadFiles("test/file/modules/test"); + }); + async function readSave() { + const zip = await lib.ZipArchive.fromFile(zipPath); + try { + const files = new Map(); + for (const name of zip.entries.keys()) { + files.set(name, (await zip.readFile(name)).toString("utf8")); + } + return files; + } finally { + zip.close(); + } + } + + it("should leave saves that are not patched untouched", async function() { + await fs.writeFile(zipPath, await createZipBuffer([["world/control.lua", freeplayControl]])); + assert.equal(await patch.unpatch(zipPath), false); + assert.deepEqual([...(await readSave()).keys()], ["world/control.lua"]); + }); + it("should restore control.lua and remove module files", async function() { + await fs.writeFile(zipPath, await createZipBuffer([ + ["world/control.lua", freeplayControl], + ["world/level.dat0", "level"], + ])); + await patch.patch(zipPath, [testModule]); + assert.equal(await patch.unpatch(zipPath), true); + + const files = await readSave(); + assert.deepEqual( + [...files.keys()].sort(), + ["world/clusterio.json", "world/control.lua", "world/level.dat0"], + ); + assert.equal(files.get("world/control.lua"), freeplayControl); + const patchInfo = JSON.parse(files.get("world/clusterio.json")); + assert.equal(patchInfo.patch_number, 1); + assert.deepEqual(patchInfo.modules, []); + + assert.equal(await patch.unpatch(zipPath), false, "unpatched twice"); + }); + it("should throw on a newer patch version", async function() { + const scenario = new lib.ModuleInfo("freeplay", "2.0.29", [], ["scenario"]); + const patchInfo = { version: 2, patch_number: 1, scenario, modules: [] }; + await fs.writeFile(zipPath, await createZipBuffer([ + ["world/control.lua", freeplayControl], + ["world/clusterio.json", JSON.stringify(patchInfo)], + ])); + await assert.rejects(patch.unpatch(zipPath), /Save patch version 2 is newer/); + await assert.rejects(patch.patch(zipPath, []), /Save patch version 2 is newer/); + }); + it("should keep counting the patch number when patched again", async function() { + await fs.writeFile(zipPath, await createZipBuffer([["world/control.lua", freeplayControl]])); + await patch.patch(zipPath, [testModule]); + await patch.unpatch(zipPath); + await patch.patch(zipPath, [testModule]); + + const files = await readSave(); + assert.equal(JSON.parse(files.get("world/clusterio.json")).patch_number, 2); + assert(files.has("world/modules/test/test.lua")); + assert.equal(files.get("world/scenario.lua"), freeplayControl); + assert.match(files.get("world/control.lua"), /^-- Auto generated scenario module loader/); + }); + it("should keep the loader of scenarios made for Clusterio", async function() { + const scenario = new lib.ModuleInfo("custom", "1.0.0", [], ["custom"]); + const patchInfo = new patch.PatchInfo(3, scenario, [testModule]); + await fs.writeFile(zipPath, await createZipBuffer([ + ["world/control.lua", patch._generateLoader(patchInfo)], + ["world/clusterio.json", JSON.stringify(patchInfo)], + ["world/custom.lua", "-- custom\n"], + ...[...testModule.files].map(([name, content]) => [`world/${name}`, content]), + ])); + assert.equal(await patch.unpatch(zipPath), true); + + const files = await readSave(); + assert.deepEqual( + [...files.keys()].sort(), + ["world/clusterio.json", "world/control.lua", "world/custom.lua"], + ); + assert.equal(files.get("world/control.lua"), patch._generateLoader(new patch.PatchInfo(3, scenario, []))); + }); + }); }); diff --git a/test/host/server.js b/test/host/server.js index da6169a9..043aae0c 100644 --- a/test/host/server.js +++ b/test/host/server.js @@ -105,6 +105,38 @@ describe("host/server", function() { ); }); }); + describe("headless argument", function() { + const mixedDir = path.join("test", "file", "factorio-mixed"); + it("should find only full installs when false", async function() { + const [dir] = await hostServer.findVersion(mixedDir, "0.1.2", false); + assert.equal(dir, path.join(mixedDir, "full", "data")); + }); + it("should find only headless installs when true", async function() { + const [dir] = await hostServer.findVersion(mixedDir, "0.1.2", true); + assert.equal(dir, path.join(mixedDir, "headless", "data")); + }); + it("should skip installs of the other build when matching a partial version", async function() { + const installDir = path.join("test", "file", "factorio"); + const [dir, version] = await hostServer.findVersion(installDir, "0.1", false); + assert.deepEqual([dir, version], [path.join(installDir, "0.1.2", "data"), "0.1.2"]); + }); + it("should reject a direct install of the other build", async function() { + const installDir = path.join(mixedDir, "headless"); + await assert.rejects( + hostServer.findVersion(installDir, "0.1.2", false), + new Error( + `Unable to find a full install of Factorio 0.1.2: ${installDir} is a direct ` + + "(single-version) install of the headless build." + ) + ); + }); + it("should reject if no install of that build has the version", async function() { + await assert.rejects( + hostServer.findVersion(path.join("test", "file", "factorio"), "0.1.2", true), + new Error("Unable to find headless Factorio version 0.1.2") + ); + }); + }); }); describe("_listFactorioVersions()", function() { diff --git a/test/integration/clusterio.js b/test/integration/clusterio.js index ef8fec1c..db4c34d8 100644 --- a/test/integration/clusterio.js +++ b/test/integration/clusterio.js @@ -10,11 +10,12 @@ import * as libBuildMod from "@clusterio/lib/build_mod.js"; import * as testStrings from "../lib/factorio/test_strings.js"; import { - TestControl, TestControlConnector, url, controlToken, + TestControl, TestControlConnector, TestHostConnector, url, controlToken, hostId, execCtl, execCtlProcess, execController, execHost, sendRcon, getControl, spawnNode, instancesDir, factorioDir, databaseDir, controllerConfigPath, - requiresFactorio, hasFactorio, + requiresFactorio, hasFactorio, pairTestHost, writeHostConfig, } from "./index.js"; +import { pairHost, checkHostToken, PairingError } from "@clusterio/host"; import { externalTest, slowTest } from "../common.js"; import { getTestRconPort } from "./rcon_port.js"; import { ControllerEcho, HostEchoReceived, InstanceEcho } from "../file/test_plugin/messages.js"; @@ -31,6 +32,18 @@ async function checkInstanceStatus(id, status) { assert.equal(instances.get(44).status, status, "incorrect instance status"); } +// Factorio directory relative to temp/test where the hosts are run from +const hostFactorioDir = path.isAbsolute(factorioDir) ? factorioDir : path.join("..", "..", factorioDir); + +/** Id, token and name of the alt-host, paired the first time it starts */ +const altHost = { hostId: undefined, token: undefined, name: undefined }; + +async function pairAltHost() { + if (altHost.hostId === undefined) { + Object.assign(altHost, await pairTestHost("alt-host")); + } +} + async function spawnAltHost(config = "alt-host-config.json") { return await spawnNode("alt-host:", `../../packages/host run --config ${config}`, /Started host/); } @@ -41,10 +54,10 @@ async function startAltHost() { await fs.rm(configPath, { force: true }); await fs.rm(path.join("temp", "test", "alt-instances"), { force: true, recursive: true, maxRetries: 10 }); await fs.rm(path.join("temp", "test", "alt-mods"), { force: true, recursive: true, maxRetries: 10 }); - await execCtl(`host create-config --id 5 --name alt-host --generate-token --output ${config}`); + await pairAltHost(); + await writeHostConfig(configPath, altHost); await execHost(`--config ${config} config set host.instances_directory alt-instances`); - const dir = path.isAbsolute(factorioDir) ? factorioDir : path.join("..", "..", factorioDir); - await execHost(`--config ${config} config set host.factorio_directory ${dir}`); + await execHost(`--config ${config} config set host.factorio_directory ${hostFactorioDir}`); await execHost(`--config ${config} config set host.mods_directory alt-mods`); return await spawnAltHost(config); } @@ -57,7 +70,7 @@ async function stopAltHost(hostProcess) { "timeout" ).catch(() => {}); try { - await execCtl("host stop 5"); + await execCtl(`host stop ${altHost.hostId}`); } catch (err) { // Some tests cause the host to stop } @@ -105,6 +118,28 @@ function jsonArg(value) { return `"${JSON.stringify(value).replace(/"/g, process.platform === "win32" ? '""' : '\\"')}"`; } +/** Run a ctl command in this process and return what it printed */ +async function execCtlOutput(command) { + const lines = []; + const originalLog = console.log; // eslint-disable-line no-console + console.log = (...args) => lines.push(args.join(" ")); // eslint-disable-line no-console + try { + await execCtl(command); + } finally { + console.log = originalLog; // eslint-disable-line no-console + } + return lines.join("\n"); +} + +/** Validator for assert.rejects expecting a PairingError with the given HTTP status */ +function pairingError(status) { + return err => { + assert(err instanceof PairingError, `Expected a PairingError, got ${err.stack}`); + assert.equal(err.status, status, err.message); + return true; + }; +} + describe("Integration of Clusterio", function() { describe("clusteriocontroller", function() { describe("bootstrap generate-user-token", function() { @@ -281,11 +316,15 @@ describe("Integration of Clusterio", function() { describe("hostUpdateEventHandler()", function() { it("should trigger when a new host is added", async function() { slowTest(this); + // Pairing sends an update for the new host before it connects, which is not what is tested here. + // The round trip makes sure that update has been received before clearing the updates. + await pairAltHost(); + await getControl().send(new lib.HostListRequest()); getControl().hostUpdates = []; await runWithAltHost(async () => { await execCtl("instance create alt-test --id 99"); - await execCtl("instance assign alt-test 5"); + await execCtl(`instance assign alt-test ${altHost.hostId}`); }); let sawUpdate = false; @@ -311,7 +350,7 @@ describe("Integration of Clusterio", function() { let result = await getControl().send(new lib.HostListRequest()); let hosts = new Map(result.map(instance => [instance.id, instance])); - assert(hosts.has(5), "Host list was not updated"); + assert(hosts.has(altHost.hostId), "Host list was not updated"); }); }); it("should download mods from controller", async function() { @@ -325,7 +364,7 @@ describe("Integration of Clusterio", function() { } assert(!await checkModDownloaded(), "mod was downloaded before the test"); await execCtl("instance create alt-mod --id 98"); - await execCtl("instance assign alt-mod 5"); + await execCtl(`instance assign alt-mod ${altHost.hostId}`); await execCtl("instance save create alt-mod"); assert(await checkModDownloaded(), "mod was not downloaded by the test"); }); @@ -340,7 +379,7 @@ describe("Integration of Clusterio", function() { hostProcess = await startAltHost(); await execCtl("instance create alt-start --id 97"); await execCtl(`instance config set alt-start factorio.rcon_port ${await getTestRconPort()}`); - await execCtl("instance assign alt-start 5"); + await execCtl(`instance assign alt-start ${altHost.hostId}`); await execCtl("instance config set alt-start instance.auto_start true"); const visibility = jsonArg({ lan: false, public: false }); await execCtlProcess(`instance config set-prop alt-start factorio.settings visibility ${visibility}`); @@ -447,7 +486,7 @@ describe("Integration of Clusterio", function() { }); it("should load the plugin on the host", async function() { - const details = await pluginDetails({ hostId: 4 }); + const details = await pluginDetails({ hostId }); assert.equal(details.state, "loaded", "test_plugin is not loaded on the host"); }); @@ -468,7 +507,7 @@ describe("Integration of Clusterio", function() { }); it("should route a plugin request from control to a host", async function() { - const received = await getControl().sendTo({ hostId: 4 }, new HostEchoReceived("never-broadcast")); + const received = await getControl().sendTo({ hostId }, new HostEchoReceived("never-broadcast")); assert.equal(received, false); }); @@ -478,7 +517,7 @@ describe("Integration of Clusterio", function() { // The broadcast is sent without waiting for the hosts to receive it. let received = false; for (let attempt = 0; attempt < 100 && !received; attempt++) { - received = await getControl().sendTo({ hostId: 4 }, new HostEchoReceived("to-hosts")); + received = await getControl().sendTo({ hostId }, new HostEchoReceived("to-hosts")); if (!received) { await lib.wait(20); } @@ -591,31 +630,31 @@ describe("Integration of Clusterio", function() { describe("host config", function() { it("changes host config", async function() { - await execCtl("host config set 4 host.name My-Host"); - const result = await execCtlProcess("host config list 4"); + await execCtl(`host config set ${hostId} host.name My-Host`); + const result = await execCtlProcess(`host config list ${hostId}`); assert(/My-Host/.test(result.stdout), "New host name not in config output"); }); it("should not allow setting host.controller_token", async function() { await assert.rejects( - execCtl("host config set 4 host.controller_token xyz"), + execCtl(`host config set ${hostId} host.controller_token xyz`), /Field 'host\.controller_token' is not accessible/, ); }); it("should not allow setting host.id", async function() { await assert.rejects( - execCtl("host config set 4 host.id 200"), + execCtl(`host config set ${hostId} host.id 200`), /Setting 'host\.id' while host is running is not supported/, ); }); it("should not leak host.controller_token", async function() { - let result = await getControl().sendTo({ hostId: 4 }, new lib.HostConfigGetRequest()); + let result = await getControl().sendTo({ hostId }, new lib.HostConfigGetRequest()); assert.equal(Object.prototype.hasOwnProperty.call(result, "host.controller_token"), false); }); }); describe("host plugin list", function() { it("runs", async function() { - await execCtl("host plugin list 4"); + await execCtl(`host plugin list ${hostId}`); }); }); @@ -623,7 +662,7 @@ describe("Integration of Clusterio", function() { it("runs", async function() { // In dev plugins have no npm package, so best we can do is get an error from the host await assert.rejects( - execCtl("host plugin update 4 foo"), + execCtl(`host plugin update ${hostId} foo`), /Plugin foo is not installed on this machine/ ); }); @@ -635,7 +674,7 @@ describe("Integration of Clusterio", function() { // Default is to disallow updates, changing this value would require a restart // Additionally, it can not be changed via ctl, so best we can do is get an error from the host await assert.rejects( - execCtl("host plugin install 4 foo"), + execCtl(`host plugin install ${hostId} foo`), /Plugin installs are disabled on this machine/ ); }); @@ -644,15 +683,15 @@ describe("Integration of Clusterio", function() { describe("host update", function() { it("runs", async function() { - await execCtl("host update 4"); + await execCtl(`host update ${hostId}`); }); it("accepts --all", async function() { - await execCtl("host update 4 --all"); + await execCtl(`host update ${hostId} --all`); }); it("accepts --restart", async function() { // We cannot restart the host, so we check for host error instead await assert.rejects( - execCtl("host update 4 --restart"), + execCtl(`host update ${hostId} --restart`), /Cannot restart, host does not have a process monitor to restart it./ ); }); @@ -662,7 +701,7 @@ describe("Integration of Clusterio", function() { it("runs", async function() { // We cannot restart the host, so we check for host error instead await assert.rejects( - execCtl("host restart 4"), + execCtl(`host restart ${hostId}`), /Cannot restart, host does not have a process monitor to restart it./ ); }); @@ -670,41 +709,226 @@ describe("Integration of Clusterio", function() { describe("host mark-restart-required", function() { it("runs", async function() { - await execCtl("host mark-restart-required 4"); + await execCtl(`host mark-restart-required ${hostId}`); }); }); - describe("host generate-token", function() { - it("runs", async function() { - await execCtl("host generate-token --id 42"); + describe("host pending, approve and reject", function() { + let pairings = []; + afterEach(async function() { + // Stop hosts left waiting by a failed test + for (const pairing of pairings) { + pairing.abort.abort(); + } + await Promise.allSettled(pairings.map(pairing => pairing.result)); + pairings = []; }); - it("runs without an id", async function() { - await execCtl("host generate-token"); - }); - }); - describe("host revoke-token", async function() { - it("should disconnect existing host", async function() { - slowTest(this); - let sawDisconnected; - await runWithAltHost(async () => { - const control = getControl(); - control.hostUpdates = []; - await wait(50); // Allow for host to update instances - await execCtl("host revoke-token 5"); - await wait(50); // Allow controller to notify control - for (let update of control.hostUpdates) { - if (update.name !== "alt-host") { - continue; - } - - if (!update.connected) { - sawDisconnected = true; - } - } + // Start pairing like a host without a user token, returns once the request is pending. + async function requestPairing(name) { + const abort = new AbortController(); + let onPending; + const pending = new Promise(resolve => { onPending = resolve; }); + const result = pairHost({ + controllerUrl: url, name, pollIntervalMs: 100, signal: abort.signal, onPending, }); + const pairing = { abort, result, code: undefined }; + pairings.push(pairing); + const ended = result.then(() => { + throw new Error("Pairing finished before the request was pending"); + }); + ended.catch(() => {}); // Only of interest while racing the pending request + pairing.code = await Promise.race([pending, ended]); + return pairing; + } - assert(sawDisconnected, "No host update with status disconnected was sent after revoking token"); + it("should list a waiting request and hand the host over when approved", async function() { + const control = getControl(); + control.hostPairingUpdates = []; + const pairing = await requestPairing("pending-host"); + assert.match(pairing.code, /^[2-9A-HJKMNP-Z]{3}-[2-9A-HJKMNP-Z]{3}$/); + + const pendingOutput = await execCtlOutput("host pending"); + const pendingLines = pendingOutput.split("\n"); + assert( + pendingLines.some(line => line.includes(pairing.code) && line.includes("pending-host")), + `Request missing from host pending output:\n${pendingOutput}`, + ); + assert( + control.hostPairingUpdates.some(update => update.code === pairing.code && !update.isDeleted), + "No pairing update was sent for the new request", + ); + + // Codes are matched ignoring case and separators + const typedCode = pairing.code.replace("-", "").toLowerCase(); + const approveOutput = await execCtlOutput(`host approve ${typedCode} --name approved-host`); + const approved = await pairing.result; + assert.equal(approved.name, "approved-host"); + assert(approveOutput.includes(String(approved.hostId)), `Host id missing from: ${approveOutput}`); + assert( + control.hostPairingUpdates.some(update => update.code === pairing.code && update.isDeleted), + "No pairing update was sent for the approved request", + ); + + const requests = await control.send(new lib.HostPairingListRequest()); + assert(!requests.some(request => request.code === pairing.code), "Approved request is still pending"); + const hosts = await control.send(new lib.HostListRequest()); + assert.equal(hosts.find(host => host.id === approved.hostId)?.name, "approved-host"); + assert.equal(await checkHostToken(url, approved.token), true); + + await execCtl(`host revoke ${approved.hostId}`); + }); + + it("should make the host fail when the request is rejected", async function() { + const pairing = await requestPairing("rejected-host"); + await execCtl(`host reject ${pairing.code}`); + await assert.rejects(pairing.result, pairingError(403)); + + const requests = await getControl().send(new lib.HostPairingListRequest()); + assert(!requests.some(request => request.code === pairing.code), "Rejected request is still pending"); + const hosts = await getControl().send(new lib.HostListRequest()); + assert(!hosts.some(host => host.name === "rejected-host"), "Rejected host was added"); + }); + + it("should remove the request when the host stops waiting", async function() { + const pairing = await requestPairing("cancelled-host"); + pairing.abort.abort(); + await assert.rejects(pairing.result, err => err.name === "AbortError"); + + const requests = await getControl().send(new lib.HostPairingListRequest()); + assert(!requests.some(request => request.code === pairing.code), "Cancelled request is still pending"); + }); + + it("should fail for a code that is not pending", async function() { + await assert.rejects(execCtl("host approve 222-222"), /No pending host request with code 222-222/); + await assert.rejects(execCtl("host reject 222-222"), /No pending host request with code 222-222/); + }); + + it("should refuse an invalid user token instead of waiting for approval", async function() { + await assert.rejects( + pairHost({ controllerUrl: url, name: "invalid-token-host", token: "invalid" }), pairingError(401) + ); + const requests = await getControl().send(new lib.HostPairingListRequest()); + assert(!requests.some(request => request.name === "invalid-token-host"), "Request was created"); + }); + + it("should refuse a user token without permission to approve hosts", async function() { + await getControl().send(new lib.UserCreateRequest("pairing-player")); + try { + const token = jwt.sign( + { aud: "user", user: "pairing-player" }, Buffer.from("TestSecretDoNotUse", "base64") + ); + await assert.rejects( + pairHost({ controllerUrl: url, name: "unapproved-host", token }), pairingError(403) + ); + } finally { + await getControl().send(new lib.UserDeleteRequest("pairing-player")); + } + const requests = await getControl().send(new lib.HostPairingListRequest()); + assert(!requests.some(request => request.name === "unapproved-host"), "Request was created"); + const hosts = await getControl().send(new lib.HostListRequest()); + assert(!hosts.some(host => host.name === "unapproved-host"), "Host was added"); + }); + }); + + describe("host revoke", function() { + it("should remove the host and invalidate its token", async function() { + const pairing = await pairTestHost("revokee-host"); + assert.equal(await checkHostToken(url, pairing.token), true); + await execCtl(`note set host ${pairing.hostId} short-lived`); + + const control = getControl(); + control.hostUpdates = []; + await execCtl(`host revoke ${pairing.hostId}`); + assert( + control.hostUpdates.some(update => update.id === pairing.hostId && update.isDeleted), + "No host update with isDeleted was sent", + ); + const hosts = await control.send(new lib.HostListRequest()); + assert(!hosts.some(host => host.id === pairing.hostId), "Host was not removed"); + assert.equal(await checkHostToken(url, pairing.token), false); + const notes = await control.send(new lib.NoteListRequest()); + assert(!notes.some(note => note.id === `host/${pairing.hostId}`), "Note of the host was not removed"); + }); + + it("should unassign the instances of the host", async function() { + const pairing = await pairTestHost("assigned-host"); + // Instances can only be assigned to connected hosts, a link that accepts the assignment is enough. + const connector = new TestHostConnector(url, 0.2); + connector.token = pairing.token; + connector.hostId = pairing.hostId; + const link = new lib.Link(connector); + link.handle(lib.InstanceAssignInternalRequest, async () => {}); + await connector.connect(); + await execCtl("instance create revoke-assigned --id 45"); + try { + await execCtl(`instance assign revoke-assigned ${pairing.hostId}`); + connector.setClosing(); // Stops it from reconnecting after being revoked + await execCtl(`host revoke ${pairing.hostId}`); + + const hosts = await getControl().send(new lib.HostListRequest()); + assert(!hosts.some(host => host.id === pairing.hostId), "Host was not removed"); + const instance = await getControl().send(new lib.InstanceDetailsGetRequest(45)); + assert.equal(instance.assignedHost, undefined); + assert.equal(instance.status, "unassigned"); + } finally { + await execCtl("instance delete revoke-assigned"); + } + }); + + it("should stop a running host and have it ask to join again when started", async function() { + slowTest(this); + this.timeout(30000); + const config = "revoke-host-config.json"; + const pairing = await pairTestHost("running-revokee"); + await writeHostConfig(path.join("temp", "test", config), pairing, { + "host.factorio_directory": hostFactorioDir, + "host.instances_directory": "revoke-instances", + "host.mods_directory": "revoke-mods", + }); + const hostProcess = await spawnNode( + "revoke-host:", `../../packages/host run --config ${config}`, /Started host/ + ); + try { + const exited = events.once(hostProcess, "exit"); + await execCtl(`host revoke ${pairing.hostId}`); + assert.notEqual( + await lib.timeout(exited, 10e3, "timeout"), "timeout", "Host did not stop after being revoked" + ); + } finally { + if (hostProcess.exitCode === null && hostProcess.signalCode === null) { + hostProcess.kill("SIGINT"); + } + } + + // Starting it again asks to join the cluster again, and it starts up once approved + const rejoining = await spawnNode( + "revoke-host:", `../../packages/host run --config ${config}`, /Waiting for approval/ + ); + const exited = events.once(rejoining, "exit"); + try { + const started = new Promise(resolve => { + rejoining.stdout.on("data", chunk => { + if (String(chunk).includes("Started host")) { + resolve(); + } + }); + }); + const requests = await getControl().send(new lib.HostPairingListRequest()); + const request = requests.find(entry => entry.name === "running-revokee"); + assert(request, "Revoked host did not ask to join again"); + const newHostId = await getControl().send(new lib.HostPairingApproveRequest(request.code)); + assert.notEqual(newHostId, pairing.hostId); + assert.notEqual( + await lib.timeout(started, 10e3, "timeout"), "timeout", "Host did not start once approved" + ); + await execCtl(`host revoke ${newHostId}`); + await lib.timeout(exited, 10e3, "timeout"); + } finally { + if (rejoining.exitCode === null && rejoining.signalCode === null) { + rejoining.kill("SIGINT"); + } + } }); }); @@ -747,9 +971,79 @@ describe("Integration of Clusterio", function() { }); }); + describe("instance template inheritance", function() { + after(async function() { + for (const id of [4403, 4402, 4401, 4400]) { + await getControl().send(new lib.InstanceDeleteRequest(id)).catch(() => {}); + } + }); + it("creates a template and an instance inheriting from it", async function() { + await execCtl("instance create inheritTemplate --id 4400 --as-template"); + await execCtl("instance config set inheritTemplate factorio.version 2.0"); + await execCtl("instance create inheritChild --id 4401 --template inheritTemplate"); + const config = await getControl().send(new lib.InstanceConfigGetRequest(4401)); + assert.equal(config["instance.template_id"], 4400); + assert.equal(config["factorio.version"], "2.0"); + assert.equal(config["instance.inherited_fields"]["factorio.version"], true); + assert.equal((await getInstances()).get(4400).isTemplate, true); + }); + it("propagates template changes per property", async function() { + await execCtl("instance config set inheritTemplate factorio.version 2.1"); + await execCtl("instance config set-prop inheritChild factorio.settings max_players 3"); + await execCtl("instance config set-prop inheritTemplate factorio.settings max_players 7"); + await execCtl("instance config set-prop inheritTemplate factorio.settings afk_autokick_interval 9"); + const config = await getControl().send(new lib.InstanceConfigGetRequest(4401)); + assert.equal(config["factorio.version"], "2.1"); + assert.equal(config["factorio.settings"].max_players, 3); + assert.equal(config["factorio.settings"].afk_autokick_interval, 9); + }); + it("creates a template from an existing instance", async function() { + await execCtl("instance create inheritCopy --id 4403 --as-template --from 4401"); + const config = await getControl().send(new lib.InstanceConfigGetRequest(4403)); + assert.equal(config["instance.is_template"], true); + assert.equal(config["factorio.settings"].max_players, 3); + }); + it("rejects inheriting from an instance that is not a template", async function() { + await assert.rejects( + execCtl("instance create inheritBad --id 4402 --template inheritChild"), + new lib.ValidationError("Instance inheritChild is not a template"), + ); + }); + it("rejects assigning a template to a host", async function() { + await assert.rejects( + execCtl(`instance assign inheritTemplate ${hostId}`), + new lib.ValidationError("Templates cannot be assigned to a host"), + ); + }); + describe("instance list --templates", function() { + it("runs", async function() { + await execCtl("instance list --templates"); + }); + }); + describe("instance config list", function() { + it("runs on an inheriting instance", async function() { + await execCtl("instance config list inheritChild"); + }); + }); + describe("instance config inherit", function() { + it("runs", async function() { + await execCtl("instance config set inheritChild factorio.version 2.0"); + let config = await getControl().send(new lib.InstanceConfigGetRequest(4401)); + assert.equal(config["instance.inherited_fields"]["factorio.version"], undefined); + + await execCtl("instance config inherit inheritChild factorio.version"); + await execCtl("instance config inherit inheritChild factorio.settings max_players"); + config = await getControl().send(new lib.InstanceConfigGetRequest(4401)); + assert.equal(config["factorio.version"], "2.1"); + assert.equal(config["instance.inherited_fields"]["factorio.version"], true); + assert.equal(config["factorio.settings"].max_players, 7); + }); + }); + }); + describe("instance assign", function() { it("creates the instance files", async function() { - await execCtl("instance assign test 4"); + await execCtl(`instance assign test ${hostId}`); await assert.doesNotReject( fs.access(path.join(instancesDir, "test")), "Instance directory was not created" @@ -1044,14 +1338,14 @@ describe("Integration of Clusterio", function() { assert.equal(controllerEntry.host_id, undefined); assert.equal(controllerEntry.instance_id, undefined); - const hostEntry = await findLog({ hostIds: [4] }, "test_plugin host echo log-tagging"); + const hostEntry = await findLog({ hostIds: [hostId] }, "test_plugin host echo log-tagging"); assert.equal(hostEntry.plugin, "test_plugin"); - assert.equal(hostEntry.host_id, 4); + assert.equal(hostEntry.host_id, hostId); assert.equal(hostEntry.instance_id, undefined); const instanceEntry = await findLog({ instanceIds: [44] }, "test_plugin instance echo log-tagging"); assert.equal(instanceEntry.plugin, "test_plugin"); - assert.equal(instanceEntry.host_id, 4); + assert.equal(instanceEntry.host_id, hostId); assert.equal(instanceEntry.instance_id, 44); }); }); @@ -1521,7 +1815,7 @@ describe("Integration of Clusterio", function() { before(async function() { slowTest(this); await execCtlProcess("instance create spam --id 66"); - await execCtlProcess("instance assign spam 4"); + await execCtlProcess(`instance assign spam ${hostId}`); await execCtlProcess("instance create unassign --id 77"); }); after(async function() { @@ -1548,7 +1842,7 @@ describe("Integration of Clusterio", function() { hostProcess = await startAltHost(); await execCtlProcess("instance create save-test --id 88"); - await execCtlProcess("instance assign save-test 5"); + await execCtlProcess(`instance assign save-test ${altHost.hostId}`); }); after(async function() { await stopAltHost(hostProcess); @@ -1976,9 +2270,9 @@ describe("Integration of Clusterio", function() { describe("note set", function() { it("should set the note of the given resource", async function() { - await execCtl("note set host 4 basement-box"); + await execCtl(`note set host ${hostId} basement-box`); const notes = await getControl().send(new lib.NoteListRequest()); - const note = notes.find(n => n.id === "host/4"); + const note = notes.find(n => n.id === `host/${hostId}`); assert.equal(note.content, "basement-box"); assert.equal(note.updatedBy, "test"); }); @@ -1999,7 +2293,7 @@ describe("Integration of Clusterio", function() { const originalLog = console.log; // eslint-disable-line no-console console.log = (...args) => lines.push(args.join(" ")); // eslint-disable-line no-console try { - await execCtl("note get host 4"); + await execCtl(`note get host ${hostId}`); } finally { console.log = originalLog; // eslint-disable-line no-console } @@ -2015,9 +2309,9 @@ describe("Integration of Clusterio", function() { describe("note delete", function() { it("should remove the note of the given resource", async function() { - await execCtl("note delete host 4"); + await execCtl(`note delete host ${hostId}`); const notes = await getControl().send(new lib.NoteListRequest()); - assert(!notes.find(n => n.id === "host/4"), "Note was not deleted"); + assert(!notes.find(n => n.id === `host/${hostId}`), "Note was not deleted"); }); }); diff --git a/test/integration/index.js b/test/integration/index.js index 158bbd2a..781f5cf1 100644 --- a/test/integration/index.js +++ b/test/integration/index.js @@ -12,6 +12,7 @@ import { LineSplitter, logger } from "@clusterio/lib"; import { selectTargetCommand, initialize as initializeCtl } from "@clusterio/ctl"; import { _listFactorioVersions } from "@clusterio/host/dist/node/src/server.js"; +import { pairHost } from "@clusterio/host"; import "../setup_logging.js"; @@ -26,6 +27,7 @@ export class TestControl extends lib.Link { constructor(connector, subscribe = true) { super(connector); this.hostUpdates = []; + this.hostPairingUpdates = []; this.instanceUpdates = []; this.saveUpdates = []; this.modUpdates = []; @@ -39,6 +41,9 @@ export class TestControl extends lib.Link { this.send( new lib.SubscriptionRequest(lib.HostUpdatesEvent.name, true) ).catch(err => logger.error(`Error setting host subscriptions:\n${err.stack}`)); + this.send( + new lib.SubscriptionRequest(lib.HostPairingUpdatesEvent.name, true) + ).catch(err => logger.error(`Error setting host pairing subscriptions:\n${err.stack}`)); this.send( new lib.SubscriptionRequest(lib.InstanceDetailsUpdatesEvent.name, true) ).catch(err => logger.error(`Error setting instance subscriptions:\n${err.stack}`)); @@ -58,6 +63,7 @@ export class TestControl extends lib.Link { this.handle(lib.AccountUpdateEvent); this.handle(lib.HostUpdatesEvent, this.handleHostUpdatesEvent.bind(this)); + this.handle(lib.HostPairingUpdatesEvent, this.handleHostPairingUpdatesEvent.bind(this)); this.handle(lib.InstanceDetailsUpdatesEvent, this.handleInstanceDetailsUpdatesEvent.bind(this)); this.handle(lib.InstanceSaveDetailsUpdatesEvent, this.handleInstanceSaveDetailsUpdatesEvent.bind(this)); this.handle(lib.ModUpdatesEvent, this.handleModUpdatesEvent.bind(this)); @@ -69,6 +75,10 @@ export class TestControl extends lib.Link { this.hostUpdates.push(...event.updates); } + async handleHostPairingUpdatesEvent(event) { + this.hostPairingUpdates.push(...event.updates); + } + async handleInstanceDetailsUpdatesEvent(event) { this.instanceUpdates.push(...event.updates); } @@ -181,6 +191,8 @@ const baseHostConfig = loadJSON("config-host.json"); export let url = "https://localhost:4443/"; // Signed in the root before hook, as the user has to exist before the token is issued export let controlToken; +// Id of the test host, assigned by the controller when it is paired in the root before hook +export let hostId; export let instancesDir = path.join("temp", "test", "instances"); export let modsDir = path.join("temp", "test", "mods"); export let databaseDir = path.join("temp", "test", "database"); @@ -253,6 +265,35 @@ export function getControl() { return control; } +/** + * Pair a new host with the test controller, approved right away with the admin token + * + * @param {string} name - Name to give the host. + * @returns {Promise<{ hostId: number, token: string, name: string }>} the paired host. + */ +export async function pairTestHost(name) { + return await pairHost({ controllerUrl: url, name, token: controlToken }); +} + +/** + * Write a new host config for a paired host, with the fields the installer and pairing set + * + * @param {string} configPath - Path to write the config to. + * @param {{ hostId: number, token: string, name: string }} pairing - Host returned by pairing. + * @param {Record} fields - Other fields to set in the config. + */ +export async function writeHostConfig(configPath, pairing, fields = {}) { + const hostConfig = new lib.HostConfig("host"); + hostConfig.set("host.id", pairing.hostId); + hostConfig.set("host.name", pairing.name); + hostConfig.set("host.controller_url", url); + hostConfig.set("host.controller_token", pairing.token); + for (const [name, value] of Object.entries(fields)) { + hostConfig.set(name, value); + } + await fs.writeFile(configPath, JSON.stringify(hostConfig, null, "\t"), { mode: 0o600 }); +} + /** @returns {Promise} */ export function spawn(name, cmd, waitFor, options = {}) { @@ -270,22 +311,19 @@ export function spawn(name, cmd, waitFor, options = {}) { let process = child_process.spawn(parts[0], parts.slice(1), childOptions(options)); let stdout = new LineSplitter({ readableObjectMode: true }); let stderr = new LineSplitter({ readableObjectMode: true }); - let onDataOut = line => { + let onData = line => { line = line.toString("utf8"); if (waitFor.test(line)) { if (silent) { - stdout.off("data", onDataOut); - stderr.off("data", onDataErr); + stdout.off("data", onData); + stderr.off("data", onData); } resolve(process); } log(name, line); }; - let onDataErr = line => { - log(name, line.toString("utf8")); - }; - stdout.on("data", onDataOut); - stderr.on("data", onDataErr); + stdout.on("data", onData); + stderr.on("data", onData); process.stdout.pipe(stdout); process.stderr.pipe(stderr); }); @@ -366,7 +404,9 @@ before(async function() { haveFactorioInstall = factorioVersions.size > 0; const relativeFactorioDir = path.isAbsolute(factorioDir) ? factorioDir : path.join("..", "..", factorioDir); - await execCtlProcess("host create-config --id 4 --name host --generate-token"); + const pairing = await pairTestHost("host"); + hostId = pairing.hostId; + await writeHostConfig(hostConfigPath, pairing); await execHost("config create"); await execHost(`config set host.factorio_directory ${relativeFactorioDir}`); diff --git a/test/integration/instance.js b/test/integration/instance.js index c12bee72..d8fe5206 100644 --- a/test/integration/instance.js +++ b/test/integration/instance.js @@ -8,7 +8,7 @@ import fs from "node:fs/promises"; import { slowTest, testMatrix } from "../common.js"; import { execCtl, execCtlProcess, sendRcon, getControl, - requiresFactorio, hasFactorio, getFactorioVersion, instancesDir, + requiresFactorio, hasFactorio, getFactorioVersion, instancesDir, hostId, } from "./index.js"; import { getTestRconPort } from "./rcon_port.js"; @@ -96,7 +96,7 @@ describe("Clusterio Instance", function() { await execCtl(`instance config set ${instName} factorio.enable_whitelist true`); await execCtlProcess(`instance config set-prop ${instName} factorio.settings visibility "${visibility}"`); await execCtl(`instance config set-prop ${instName} factorio.settings require_user_verification false`); - await execCtl(`instance assign ${instName} 4`); + await execCtl(`instance assign ${instName} ${hostId}`); // Exclude main test instance from start-all to prevent interference await execCtl(`instance config set ${instName} instance.exclude_from_start_all true`); @@ -112,7 +112,7 @@ describe("Clusterio Instance", function() { await execCtl(`instance config set ${instAltName} factorio.enable_whitelist true`); await execCtlProcess(`instance config set-prop ${instAltName} factorio.settings visibility "${visibility}"`); await execCtl(`instance config set-prop ${instAltName} factorio.settings require_user_verification false`); - await execCtl(`instance assign ${instAltName} 4`); + await execCtl(`instance assign ${instAltName} ${hostId}`); // Exclude alt test instance from start-all to prevent interference await execCtl(`instance config set ${instAltName} instance.exclude_from_start_all true`); await execCtl(`instance start ${instAltName}`); @@ -153,6 +153,25 @@ describe("Clusterio Instance", function() { assert.deepEqual(whitelist, ["test_user"]); }); }); + describe("save patching disabled", function() { + it("should remove the modules from a save patched before", async function() { + this.timeout(40000); + const hasApi = "/sc rcon.print(tostring(remote.interfaces.clusterio_api ~= nil))"; + await execCtl(`${instSetConfig} factorio.enable_save_patching true`); + await execCtl(`instance save create ${instName}`); + await execCtl(`instance start ${instName}`); + assert.equal(await sendRcon(instId, hasApi), "true\n"); + await execCtl(`instance stop ${instName}`); + + await execCtl(`${instSetConfig} factorio.enable_save_patching false`); + await execCtl(`instance start ${instName}`); + try { + assert.equal(await sendRcon(instId, hasApi), "false\n"); + } finally { + await execCtl(`instance stop ${instName}`); + } + }); + }); for (const [savePatchingEnabled, scriptCommandsEnabled] of testMatrix([true, false], [true, false])) { const strSavePatching = `save patching: ${savePatchingEnabled ? "Enabled" : "Disabled"}`; const strScriptCommands = `script commands: ${scriptCommandsEnabled ? "Enabled" : "Disabled"}`; @@ -340,9 +359,9 @@ describe("start-all and stop-all commands", function() { await execCtl(`instance create ${testInstName3} --id ${testInstId3}`); // Configure instances - await execCtl(`instance assign ${testInstName1} 4`); - await execCtl(`instance assign ${testInstName2} 4`); - await execCtl(`instance assign ${testInstName3} 4`); + await execCtl(`instance assign ${testInstName1} ${hostId}`); + await execCtl(`instance assign ${testInstName2} ${hostId}`); + await execCtl(`instance assign ${testInstName3} ${hostId}`); const visibility = JSON.stringify({ lan: false, public: false }).replace( /"/g, process.platform === "win32" ? '""' : '\\"' ); diff --git a/test/integration/link.js b/test/integration/link.js index 57ecbeaa..20404542 100644 --- a/test/integration/link.js +++ b/test/integration/link.js @@ -3,25 +3,36 @@ import events from "node:events"; import jwt from "jsonwebtoken"; import { - TestControlConnector, TestHostConnector, TestControl, url, controlToken, getControl, + TestControlConnector, TestHostConnector, TestControl, url, controlToken, getControl, hostId, pairTestHost, } from "./index.js"; import * as lib from "@clusterio/lib"; import { ConnectionClosed, ProtocolError, PolicyViolation, AuthenticationFailed } from "@clusterio/lib"; import { slowTest } from "../common.js"; -let tokenHost = jwt.sign({ aud: "host", host: 0 }, Buffer.from("TestSecretDoNotUse", "base64")); +// Valid token for a host id that was never approved +let tokenUnregistered = jwt.sign({ aud: "host", host: 0 }, Buffer.from("TestSecretDoNotUse", "base64")); describe("Integration of lib/link", function() { let control; let controlConnector; let hostConnector; + // Hosts can only connect once approved, so the host connections use a paired host + let linkHost; + before(async function() { + linkHost = await pairTestHost("link-test"); + }); + after(async function() { + if (linkHost) { + await getControl().send(new lib.HostRevokeRequest(linkHost.hostId)); + } + }); beforeEach(async function() { controlConnector = new TestControlConnector(url, 0.2); controlConnector.token = controlToken; control = new TestControl(controlConnector, false); hostConnector = new TestHostConnector(url, 0.2); - hostConnector.token = tokenHost; - hostConnector.hostId = 0; + hostConnector.token = linkHost.token; + hostConnector.hostId = linkHost.hostId; }); afterEach(async function() { await controlConnector.disconnect(); @@ -138,13 +149,24 @@ describe("Integration of lib/link", function() { }); it("should refuse connection with mismatched ids", async function() { - hostConnector.hostId = 1; + hostConnector.hostId = linkHost.hostId + 1; await assert.rejects( hostConnector.connect(), new Error("Authentication failed: missmatched host id") ); }); + it("should refuse connection for a host that is not registered", async function() { + hostConnector.token = tokenUnregistered; + hostConnector.hostId = 0; + await assert.rejects( + hostConnector.connect(), + new Error( + "Authentication failed: host is not registered, start the host again to request to join the cluster" + ) + ); + }); + it("should close old connections from the same address", async function() { slowTest(this); // Without a link the disconnect prepare goes unanswered and the controller waits 10 s for it @@ -165,8 +187,8 @@ describe("Integration of lib/link", function() { it("should refuse duplicate host connections", async function() { this.skip(); // Can't be checked because the remote address for both connections is the same - hostConnector.token = jwt.sign({ aud: "host", host: 4 }, Buffer.from("TestSecretDoNotUse", "base64")); - hostConnector.hostId = 4; // Same as already running host + hostConnector.token = jwt.sign({ aud: "host", host: hostId }, Buffer.from("TestSecretDoNotUse", "base64")); + hostConnector.hostId = hostId; // Same as already running host await assert.rejects( hostConnector.connect(), new Error("Authentication failed: missmatched host id") diff --git a/test/integration/routing.js b/test/integration/routing.js index 6a0103bd..7e93d449 100644 --- a/test/integration/routing.js +++ b/test/integration/routing.js @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import * as lib from "@clusterio/lib"; import { Host, Instance, InstanceConnection } from "@clusterio/host"; -import { ControlConnection, Controller, HostConnection, InstanceRecord } from "@clusterio/controller"; +import { ControlConnection, Controller, HostConnection, HostRecord, InstanceRecord } from "@clusterio/controller"; import { MockServer } from "../mock.js"; // Although there are no imports, the file has side-effects such as "before" which can effect tests @@ -19,6 +19,8 @@ class Control extends lib.Link { } function connectHost(controller, hostId, plugins) { const [controllerSide, hostSide] = lib.VirtualConnector.makePair(addr("controller"), addr({ hostId })); const registerData = new lib.RegisterHostData("", "0.0.0", hostId, plugins); + // Hosts can only connect once approved, which creates their record. + controller.hosts.records.set(new HostRecord(hostId, `host-${hostId}`, "", new Map())); const hostConnection = new HostConnection(registerData, controllerSide, controller, "host-a.test"); controller.wsServer.hostConnections.set(hostId, hostConnection); const hostConfig = new lib.HostConfig("host"); @@ -39,7 +41,8 @@ function connectInstance(controller, host, instanceId) { instanceConfig.set("instance.id", instanceId); instanceConfig.set("instance.assigned_host", host.config.get("host.id")); host.assignedInstances.set(instanceId, { path: "invalid", config: instanceConfig }); - controller.instances.records.set(new InstanceRecord(instanceConfig, "stopped")); + const controllerConfig = new lib.InstanceConfig("controller", instanceConfig.toRemote("controller")); + controller.instances.records.set(new InstanceRecord(controllerConfig, "stopped")); const instance = new Instance(host, instanceSide, "invalid", instanceConfig, new MockServer()); const instanceConnection = new InstanceConnection(hostSide, host, instance); host.instanceConnections.set(instanceId, instanceConnection); diff --git a/test/lib/config/classes.js b/test/lib/config/classes.js index 538e5f27..b835fc35 100644 --- a/test/lib/config/classes.js +++ b/test/lib/config/classes.js @@ -145,6 +145,20 @@ describe("lib/config/classes", function() { assert.equal(testInstance.get("test.func"), 42); assert.equal(testInstance.get("test.priv"), null); }); + it("should call initialValue functions with the loaded config", function() { + class DerivedConfig extends lib.Config { + static defaultAccess = ["local"]; + static fieldDefinitions = { + "test.base": { type: "number", initialValue: 1 }, + "test.derived": { type: "number", initialValue: config => config.get("test.base") * 2 }, + }; + } + assert.equal(new DerivedConfig("local").get("test.derived"), 2); + assert.equal(new DerivedConfig("local", { "test.base": 5 }).get("test.derived"), 10); + assert.equal(new DerivedConfig("local", { "test.base": 5, "test.derived": 3 }).get("test.derived"), 3); + const invalid = new DerivedConfig("local", { "test.base": 5, "test.derived": "x" }); + assert.equal(invalid.get("test.derived"), 10); + }); it("should not initalize inaccessible fields", function() { let testInstance = new TestConfig("remote"); assert.equal(testInstance.fields["test.enum"], "b"); diff --git a/test/lib/config/definitions.js b/test/lib/config/definitions.js index a406f579..a20f4354 100644 --- a/test/lib/config/definitions.js +++ b/test/lib/config/definitions.js @@ -4,6 +4,59 @@ import * as lib from "@clusterio/lib"; describe("lib/config/definitions", function() { + describe("InstanceConfig", function() { + describe("isInheritable()", function() { + it("should allow regular fields", function() { + assert.equal(lib.InstanceConfig.isInheritable("factorio.version"), true); + assert.equal(lib.InstanceConfig.isInheritable("instance.auto_start"), true); + }); + it("should reject identity, hidden, host only and unknown fields", function() { + for (const name of [ + "instance.name", "instance.id", "instance.assigned_host", "instance.is_template", + "instance.template_id", "instance.inherited_fields", "factorio.host_assigned_game_port", + "factorio.game_port", "factorio.rcon_port", "factorio.rcon_password", "factorio.lua_udp_port", + "no.field", + ]) { + assert.equal(lib.InstanceConfig.isInheritable(name), false, name); + } + }); + }); + describe(".isInherited()", function() { + it("should only report fields as inherited when a template is set", function() { + const config = new lib.InstanceConfig("controller", { + "instance.inherited_fields": { "factorio.version": true }, + }); + assert.equal(config.isInherited("factorio.version"), false); + config.set("instance.template_id", 1); + assert.equal(config.isInherited("factorio.version"), true); + assert.equal(config.isInherited("factorio.game_port"), false); + }); + it("should report object properties not overridden as inherited", function() { + const config = new lib.InstanceConfig("controller", { + "instance.template_id": 1, + "instance.inherited_fields": { "factorio.settings": ["name"] }, + }); + assert.equal(config.isInherited("factorio.settings"), true); + assert.equal(config.isInherited("factorio.settings", "max_players"), true); + assert.equal(config.isInherited("factorio.settings", "name"), false); + }); + }); + it("should not send inheritance fields to the host", function() { + const config = new lib.InstanceConfig("controller", { "instance.template_id": 1 }); + const remote = config.toRemote("host"); + for (const name of ["instance.is_template", "instance.template_id", "instance.inherited_fields"]) { + assert(!Object.hasOwn(remote, name), name); + } + }); + it("should not let control write inherited_fields", function() { + const config = new lib.InstanceConfig("controller"); + assert.throws( + () => config.set("instance.inherited_fields", { "factorio.version": true }, "control"), + new lib.InvalidAccessError("Field 'instance.inherited_fields' is not accessible from control"), + ); + }); + }); + describe("addPluginConfigFields()", function() { after(function() { delete lib.CtlConfig.fieldDefinitions["ctl_test.field"]; diff --git a/test/lib/config/validators.test.js b/test/lib/config/validators.test.js index db5113f4..da345b9e 100644 --- a/test/lib/config/validators.test.js +++ b/test/lib/config/validators.test.js @@ -369,6 +369,49 @@ describe("lib/config/definitions/validators", function() { assert.doesNotThrow(() => config.set("factorio.enable_lua_udp", true)); assert.doesNotThrow(() => config.set("lua_udp.load_plugin", true)); }); + it("should default load_plugin to false when a required feature is disabled", function() { + class TestInstanceConfig extends InstanceConfig { + static fieldDefinitions = { ...InstanceConfig.fieldDefinitions }; + } + + lib.addPluginFieldDefinitions( + { name: "requires_features", features: ["SavePatching", "ScriptCommands"] }, + "instanceConfigFields", TestInstanceConfig + ); + + assert.equal(new TestInstanceConfig("controller").get("requires_features.load_plugin"), true); + for (const field of ["factorio.enable_save_patching", "factorio.enable_script_commands"]) { + const config = new TestInstanceConfig("controller", { [field]: false }); + assert.equal(config.get("requires_features.load_plugin"), false); + // Other fields can be edited since the config is valid + assert.doesNotThrow(() => config.set("instance.name", "test")); + } + + // An explicit value is kept + const config = new TestInstanceConfig("controller", { + "factorio.enable_save_patching": false, + "requires_features.load_plugin": true, + }); + assert.equal(config.get("requires_features.load_plugin"), true); + }); + it("should reject disabling a feature required by a loaded plugin", function() { + class TestInstanceConfig extends InstanceConfig { + static fieldDefinitions = { ...InstanceConfig.fieldDefinitions }; + static _fieldDependents; // Don't reuse the cache from InstanceConfig + } + + lib.addPluginFieldDefinitions( + { name: "save_patching", features: ["SavePatching"] }, + "instanceConfigFields", TestInstanceConfig + ); + + const config = new TestInstanceConfig("controller"); + assert.throws( + () => config.set("factorio.enable_save_patching", false), + /requires save patching/ + ); + assert.equal(config.get("factorio.enable_save_patching"), true); + }); it("should allow when no feature flags are present", function() { class TestInstanceConfig extends InstanceConfig { static fieldDefinitions = { ...InstanceConfig.fieldDefinitions }; diff --git a/test/lib/data/HostPairingDetails.test.js b/test/lib/data/HostPairingDetails.test.js new file mode 100644 index 00000000..5064c901 --- /dev/null +++ b/test/lib/data/HostPairingDetails.test.js @@ -0,0 +1,18 @@ +import { HostPairingDetails } from "@clusterio/lib"; + +import { testMatrix, testRoundTripJsonSerialisable } from "../../common.js"; + +describe("lib/data/HostPairingDetails", function () { + + it("should be round trip serialisable", function () { + testRoundTripJsonSerialisable(HostPairingDetails, testMatrix( + ["ABC-DEF"], // code (required) + ["New Host", ""], // name (required) + ["10.0.0.1", "2001:db8::1"], // remoteAddress (required) + [undefined, "2.0.0"], // version + [undefined, 123456], // createdAtMs + [undefined, 999999], // updatedAtMs + [undefined, true], // isDeleted + )); + }); +}); diff --git a/test/lib/data/InstanceDetails.test.js b/test/lib/data/InstanceDetails.test.js index 95058653..094f1a3c 100644 --- a/test/lib/data/InstanceDetails.test.js +++ b/test/lib/data/InstanceDetails.test.js @@ -16,6 +16,9 @@ describe("lib/data/InstanceDetails", function () { [undefined, 1234], // startedAtMs [undefined, 9999], // updatedAtMs [undefined, true], // excludeFromStartAll + [undefined, true], // isTemplate + [undefined, 7], // templateId + [undefined, 3], // modPackId )); }); diff --git a/test/lib/datastore.js b/test/lib/datastore.js index 4c829e76..5959bf0b 100644 --- a/test/lib/datastore.js +++ b/test/lib/datastore.js @@ -346,6 +346,41 @@ describe("lib/datastore", function() { await datastore.save(); assert.equal(datastoreProvider.methodCalls.length, 2); }); + it("should write overlapping saves in order with the latest data", async function() { + const written = []; + let release; + datastoreProvider.save = async data => { + const keys = [...data.keys()]; + if (!written.length) { + await new Promise(resolve => { release = resolve; }); + } + written.push(keys); + }; + datastore = new MockDatastore(datastoreProvider, new Map([["a", 1]])); + datastore.callTouch(); + const first = datastore.save(); + await new Promise(resolve => setImmediate(resolve)); // First write in progress + datastore.getData().set("b", 2); + datastore.callTouch(); + const second = datastore.save(); + release(); + await Promise.all([first, second]); + assert.deepEqual(written, [["a"], ["a", "b"]]); + }); + it("should save again after a failed save", async function() { + let fail = true; + datastoreProvider.save = async () => { + if (fail) { + fail = false; + throw new Error("disk full"); + } + datastoreProvider.methodCalls.push(["save"]); + }; + datastore.callTouch(); + await assert.rejects(datastore.save(), /disk full/); + await datastore.save(); + assert.deepEqual(datastoreProvider.methodCalls.at(-1), ["save"]); + }); }); describe("load", function() { diff --git a/test/lib/file_ops.js b/test/lib/file_ops.js index 3e8dd21f..a44e069f 100644 --- a/test/lib/file_ops.js +++ b/test/lib/file_ops.js @@ -51,7 +51,7 @@ describe("lib/file_ops", function() { }); }); - describe("safeOutputFile()", function() { + describe("atomicOverwriteFile()", function() { async function assertNoTemporary(target) { let { dir, name } = path.parse(target); let entries = (await fs.readdir(dir)).filter( @@ -61,14 +61,14 @@ describe("lib/file_ops", function() { } it("should write new target file", async function() { let target = path.join(baseDir, "safe", "simple.txt"); - await lib.safeOutputFile(target, "a text file", "utf8"); + await lib.atomicOverwriteFile(target, "a text file", "utf8"); await assertNoTemporary(target); assert.equal(await fs.readFile(target, "utf8"), "a text file"); }); it("should overwrite existing target file", async function() { let target = path.join(baseDir, "safe", "exists.txt"); await fs.writeFile(target, "previous", "utf8"); - await lib.safeOutputFile(target, "current", "utf8"); + await lib.atomicOverwriteFile(target, "current", "utf8"); await assertNoTemporary(target); assert.equal(await fs.readFile(target, "utf8"), "current"); }); @@ -77,7 +77,7 @@ describe("lib/file_ops", function() { this.skip(); } let target = path.join(baseDir, "safe", "mode.txt"); - await lib.safeOutputFile(target, "private", { mode: 0o600 }); + await lib.atomicOverwriteFile(target, "private", { mode: 0o600 }); assert.equal((await fs.stat(target)).mode & 0o777, 0o600); assert.equal(await fs.readFile(target, "utf8"), "private"); }); @@ -85,7 +85,7 @@ describe("lib/file_ops", function() { let target = path.join(baseDir, "safe", "concurrent.txt"); let writes = []; for (let i = 0; i < 20; i++) { - writes.push(lib.safeOutputFile(target, `write ${i}`, "utf8")); + writes.push(lib.atomicOverwriteFile(target, `write ${i}`, "utf8")); } // Ignore errors from concurrently renaming onto the same file. await Promise.allSettled(writes); @@ -95,13 +95,13 @@ describe("lib/file_ops", function() { it("should remove the temporary file when the rename fails", async function() { let target = path.join(baseDir, "safe", "rename-fails"); await fs.mkdir(target, { recursive: true }); - await assert.rejects(lib.safeOutputFile(target, "data", "utf8")); + await assert.rejects(lib.atomicOverwriteFile(target, "data", "utf8")); await assertNoTemporary(target); }); it("should handle creating file in current working directory", async function() { let target = "temporary-file-made-to-test-cwd.txt"; try { - await lib.safeOutputFile(target, "a text file", "utf8"); + await lib.atomicOverwriteFile(target, "a text file", "utf8"); } finally { try { await fs.unlink(target); diff --git a/test/lib/subscriptions.test.js b/test/lib/subscriptions.test.js index 461ca0ee..1d4c535d 100644 --- a/test/lib/subscriptions.test.js +++ b/test/lib/subscriptions.test.js @@ -1250,6 +1250,36 @@ describe("lib/subscriptions", function() { }); }); + describe("permitted", function() { + let permitted; + let subscriber; + + beforeEach(function() { + mockControl = new MockControl(new MockConnector(addr({ controlId: 0 }), addr("controller"))); + permitted = false; + subscriber = new lib.EventSubscriber(RegisteredEvent, mockControl, undefined, () => permitted); + }); + + it("should send nothing while not permitted", async function() { + subscriber.subscribe(() => {}); + mockControl.connector.emit("connect"); + subscriber.handleConnectionEvent("resume"); + subscriber.handleAccountEvent(); + await new Promise(r => setImmediate(r)); + assertNoMessageSent(); + }); + + it("should subscribe when the account becomes permitted", async function() { + subscriber.subscribe(() => {}); + permitted = true; + subscriber.handleAccountEvent(); + await onceConnectorSend(); + assertLastMessage(new lib.SubscriptionRequest( + RegisteredEvent.name, "replace", -1, lib.SubscriptionFilters.all() + )); + }); + }); + describe(".handleAccountEvent()", function() { it("should send replace(all) if subscribed", async function() { eventSubscriber.subscribe(() => {}); @@ -1584,6 +1614,34 @@ describe("lib/subscriptions", function() { assert.equal(snap2.has(2), true); }); + it("should fetch everything again when a new session starts", async function() { + subscriber.subscribe(() => {}); + await events.once(mockControl.connector, "send"); + await subscriber._handleEvent(new MapEvent([ + { id: 1, updatedAtMs: 10, isDeleted: false }, + ])); + const [before] = subscriber.getSnapshot(); + mockControl.connector.sentMessages.length = 0; + + mockControl.connector.emit("connect"); + assert.equal(subscriber.values.size, 0); + assert.notStrictEqual(subscriber.getSnapshot()[0], before); + await new Promise(resolve => setImmediate(resolve)); + const requests = mockControl.connector.sentMessages.filter(m => m.name === "SubscriptionRequest"); + assert.equal(requests.length, 1); + assert.equal(requests[0].data.lastRequestTimeMs, -1); + }); + + it("should keep values when a session is resumed", async function() { + await subscriber._handleEvent(new MapEvent([ + { id: 1, updatedAtMs: 10, isDeleted: false }, + ])); + subscriber.handleConnectionEvent("drop"); + subscriber.handleConnectionEvent("resume"); + assert.equal(subscriber.values.size, 1); + assert.equal(subscriber.lastUpdatedMs, 10); + }); + it("should handle multiple updates correctly", async function() { await subscriber._handleEvent(new MapEvent([ { id: 1, updatedAtMs: 10, isDeleted: false }, diff --git a/test/messages/controller.test.js b/test/messages/controller.test.js index 0bd48c34..5c0c2eae 100644 --- a/test/messages/controller.test.js +++ b/test/messages/controller.test.js @@ -200,6 +200,34 @@ describe("messages/controller", function() { }); }); + describe("Host pairing", function() { + const details = [ + new lib.HostPairingDetails("ABC-DEF", "Host A", "10.0.0.1", "2.0.0", 100, 200), + new lib.HostPairingDetails("GHJ-KMN", "Host B", "2001:db8::1", "", 0, 300, true), + ]; + + it("round trips HostPairingListRequest responses", function() { + const validate = lib.compile(lib.HostPairingListRequest.Response.jsonSchema); + const json = JSON.parse(JSON.stringify(details)); + assert(validate(json), JSON.stringify(validate.errors)); + assert.deepEqual(lib.HostPairingListRequest.Response.fromJSON(json), details); + }); + it("round trips HostPairingUpdatesEvent", function() { + testRoundTripJsonSerialisable(lib.HostPairingUpdatesEvent, [[[]], [details]]); + }); + it("round trips HostPairingApproveRequest", function() { + testRoundTripJsonSerialisable(lib.HostPairingApproveRequest, testMatrix( + ["ABC-DEF", "abcdef"], // code + [undefined, "Renamed"], // name + )); + const validate = lib.compile(lib.HostPairingApproveRequest.Response.jsonSchema); + assert(validate(1234)); + }); + it("round trips HostPairingRejectRequest", function() { + testRoundTripJsonSerialisable(lib.HostPairingRejectRequest, [["ABC-DEF"], ["abcdef"]]); + }); + }); + describe("InstanceConfigGetRequest", function() { it("runs", async function() { const config = await controlConnection.handleInstanceConfigGetRequest( diff --git a/test/messages/host.test.js b/test/messages/host.test.js index 1b31129a..16d8dae5 100644 --- a/test/messages/host.test.js +++ b/test/messages/host.test.js @@ -18,6 +18,12 @@ describe("messages/host", function() { host = new Host(hostConnector, hostConfig, []); }); + describe("HostRevokeRequest", function() { + it("is round trip json serialisable", function() { + testRoundTripJsonSerialisable(lib.HostRevokeRequest, [[1], [2 ** 31 - 1]]); + }); + }); + describe("HostUpdateRequest", function() { it("runs", async function() { host.config.set("host.allow_remote_updates", true); diff --git a/test/mock.js b/test/mock.js index 035a54fb..57b428a7 100644 --- a/test/mock.js +++ b/test/mock.js @@ -3,7 +3,7 @@ import http from "node:http"; import express from "express"; import * as lib from "@clusterio/lib"; -import { User, UserManager, UserRecord, InstanceManager, ControllerHooks } from "@clusterio/controller"; +import { User, UserManager, UserRecord, HostManager, InstanceManager, ControllerHooks } from "@clusterio/controller"; import { HostHooks, InstanceHooks } from "@clusterio/host"; const addr = lib.Address.fromShorthand; @@ -176,6 +176,8 @@ export class MockController { ["controller.auth_secret", "TestSecretDoNotUse"], ["controller.proxy_stream_timeout", 1], ["controller.metrics_timeout", 1], + ["controller.host_pairing_timeout", 3600], + ["controller.host_pairing_max_pending", 50], ]); this.config = { get: (name) => { @@ -206,7 +208,7 @@ export class MockController { this.instances = new InstanceManager(new lib.KeyValueDatastore(), this); - this.hosts = new lib.KeyValueDatastore(); + this.hosts = new HostManager(new lib.SubscribableDatastore(), this); this.handles = new Map(); this.hooks = new ControllerHooks(new MockLogger()); this.loadedPlugins = new Set(); diff --git a/test/web_ui/host_pairing.js b/test/web_ui/host_pairing.js new file mode 100644 index 00000000..41078578 --- /dev/null +++ b/test/web_ui/host_pairing.js @@ -0,0 +1,59 @@ +import assert from "node:assert/strict"; +import events from "node:events"; + +import * as lib from "@clusterio/lib"; +import { MockConnector, MockControl } from "../mock.js"; +import "../setup_logging.js"; + +import { HostPairingSubscriber } from "../../packages/web_ui/src/util/host_pairing.ts"; + +const addr = lib.Address.fromShorthand; + +describe("web_ui/util/host_pairing", function() { + describe("class HostPairingSubscriber", function() { + let mockControl; + let subscriber; + + beforeEach(function() { + mockControl = new MockControl(new MockConnector(addr({ controlId: 0 }), addr("controller"))); + subscriber = new HostPairingSubscriber(mockControl, () => true); + }); + + function pairing(code, updatedAtMs) { + return new lib.HostPairingDetails(code, `Host ${code}`, "192.0.2.1", "", updatedAtMs, updatedAtMs); + } + + async function settle() { + await new Promise(resolve => setImmediate(resolve)); + } + + function sentRequests() { + return mockControl.connector.sentMessages.filter(message => message.name === "SubscriptionRequest"); + } + + it("should clear requests when subscribing again after the last unsubscribe", async function() { + const unsubscribe = subscriber.subscribe(() => {}); + await events.once(mockControl.connector, "send"); + await subscriber._handleEvent(new lib.HostPairingUpdatesEvent([pairing("ABC-DEF", 10)])); + unsubscribe(); + await new Promise(resolve => setTimeout(resolve)); + mockControl.connector.sentMessages.length = 0; + + subscriber.subscribe(() => {}); + assert.equal(subscriber.values.size, 0); + await settle(); + assert.equal(sentRequests().length, 1); + assert.equal(sentRequests()[0].data.lastRequestTimeMs, -1); + }); + + it("should keep requests when a page that subscribes replaces another", async function() { + const unsubscribe = subscriber.subscribe(() => {}); + await events.once(mockControl.connector, "send"); + await subscriber._handleEvent(new lib.HostPairingUpdatesEvent([pairing("ABC-DEF", 10)])); + unsubscribe(); + subscriber.subscribe(() => {}); + assert.equal(subscriber.values.size, 1); + assert.equal(subscriber.lastUpdatedMs, 10); + }); + }); +}); diff --git a/test/web_ui/instance.js b/test/web_ui/instance.js new file mode 100644 index 00000000..9fb36a0d --- /dev/null +++ b/test/web_ui/instance.js @@ -0,0 +1,34 @@ +import assert from "node:assert/strict"; +import * as lib from "@clusterio/lib"; + +import { instanceModPack } from "../../packages/web_ui/src/util/instance.ts"; + +function modPack(id, name) { + return lib.ModPack.fromJSON({ id, name, factorio_version: "2.0" }); +} + +describe("web_ui/util/instance", function() { + describe("instanceModPack()", function() { + const base = modPack(1, "Base"); + const space = modPack(2, "Space Age"); + const modPacks = new Map([[1, base], [2, space]]); + + it("should use the mod pack set on the instance", function() { + assert.deepEqual(instanceModPack(2, modPacks, base), { id: 2, modPack: space, isDefault: false }); + }); + it("should keep the id of a mod pack that is not known", function() { + assert.deepEqual(instanceModPack(9, modPacks, base), { id: 9, modPack: undefined, isDefault: false }); + }); + it("should fall back to the controller default", function() { + assert.deepEqual(instanceModPack(undefined, modPacks, base), { id: 1, modPack: base, isDefault: true }); + }); + it("should prefer the subscribed copy of the default mod pack", function() { + const stale = modPack(1, "Old name"); + assert.equal(instanceModPack(undefined, modPacks, stale).modPack, base); + assert.equal(instanceModPack(undefined, new Map(), stale).modPack, stale); + }); + it("should mark the default as unknown when it is not available", function() { + assert.deepEqual(instanceModPack(undefined, modPacks, undefined), { isDefault: true }); + }); + }); +}); diff --git a/test/web_ui/locale.js b/test/web_ui/locale.js new file mode 100644 index 00000000..fd9add2c --- /dev/null +++ b/test/web_ui/locale.js @@ -0,0 +1,113 @@ +import assert from "node:assert/strict"; + +import { + modSettingDescription, modSettingName, modSettingValueName, resolveLocalisedString, stripRichText, +} from "../../packages/web_ui/src/util/locale.ts"; + +describe("web_ui/util/locale", function() { + const locale = new Map([ + ["phi-cl.combine", "__1__ __2__"], + ["mod-setting-name-prefix.PHI-MB", "[color=255,254,42]MB[/color]"], + ["mod-setting-name.PHI-MB", "[color=255,254,42]Enable better entity[/color]"], + ["mod-setting-name.plain", "Plain setting"], + ["mod-setting-description.plain", "Plain description"], + ["string-mod-setting.mode-fast", "[font=default-bold]Fast[/font]"], + ["item-name.iron-plate", "Iron plate"], + ["entity-name.inserter", "Inserter"], + ["uses", "Uses __ITEM__iron-plate__ and __ENTITY__inserter__"], + ["greeting", "Hello __1__"], + ]); + + describe("resolveLocalisedString()", function() { + it("should return plain strings and numbers as is", function() { + assert.equal(resolveLocalisedString(locale, "text"), "text"); + assert.equal(resolveLocalisedString(locale, 5), "5"); + }); + it("should substitute parameters", function() { + assert.equal(resolveLocalisedString(locale, ["greeting", "world"]), "Hello world"); + assert.equal(resolveLocalisedString(locale, ["greeting", ["greeting", 2]]), "Hello Hello 2"); + }); + it("should leave parameters that were not given", function() { + assert.equal(resolveLocalisedString(locale, ["greeting"]), "Hello __1__"); + }); + it("should substitute prototype names", function() { + assert.equal(resolveLocalisedString(locale, ["uses"]), "Uses Iron plate and Inserter"); + }); + it("should concatenate with an empty key", function() { + assert.equal(resolveLocalisedString(locale, ["", "a", ["greeting", "b"], 3]), "aHello b3"); + }); + it("should use the first alternative that resolves with a ? key", function() { + assert.equal(resolveLocalisedString(locale, ["?", ["missing"], ["greeting", "x"], "y"]), "Hello x"); + assert.equal(resolveLocalisedString(locale, ["?", ["missing"]]), undefined); + }); + it("should return undefined if a key is missing", function() { + assert.equal(resolveLocalisedString(locale, ["missing"]), undefined); + assert.equal(resolveLocalisedString(locale, ["greeting", ["missing"]]), undefined); + }); + it("should return undefined for nesting that is too deep", function() { + let value = "end"; + for (let i = 0; i < 30; i++) { + value = ["", value]; + } + assert.equal(resolveLocalisedString(locale, value), undefined); + }); + }); + + describe("stripRichText()", function() { + it("should remove formatting tags", function() { + assert.equal(stripRichText(locale, "[color=red]A[/color] [font=default-bold]B[/font]"), "A B"); + }); + it("should replace prototype icons with their name", function() { + assert.equal(stripRichText(locale, "[item=iron-plate] plates"), "Iron plate plates"); + assert.equal(stripRichText(locale, "[item=iron-plate,quality=rare]"), "Iron plate"); + assert.equal(stripRichText(locale, "[fluid=unknown]"), "unknown"); + }); + it("should remove other icons", function() { + assert.equal(stripRichText(locale, "[img=utility/warning_icon] Warning"), "Warning"); + }); + it("should keep brackets that are not tags", function() { + assert.equal(stripRichText(locale, "[Beta] [x=1]"), "[Beta] [x=1]"); + }); + }); + + describe("modSettingName()", function() { + it("should resolve localised_name", function() { + const prototype = { + name: "PHI-MB", + localised_name: ["phi-cl.combine", ["mod-setting-name-prefix.PHI-MB"], ["mod-setting-name.PHI-MB"]], + }; + assert.equal(modSettingName(locale, prototype), "MB Enable better entity"); + }); + it("should fall back to the mod-setting-name key", function() { + assert.equal(modSettingName(locale, { name: "plain" }), "Plain setting"); + assert.equal(modSettingName(locale, { name: "plain", localised_name: ["missing"] }), "Plain setting"); + }); + it("should fall back to the internal name", function() { + assert.equal(modSettingName(locale, { name: "other" }), "other"); + assert.equal(modSettingName(new Map(), { name: "plain" }), "plain"); + }); + }); + + describe("modSettingDescription()", function() { + it("should resolve localised_description", function() { + const prototype = { name: "plain", localised_description: ["greeting", "desc"] }; + assert.equal(modSettingDescription(locale, prototype), "Hello desc"); + }); + it("should fall back to the mod-setting-description key", function() { + assert.equal(modSettingDescription(locale, { name: "plain" }), "Plain description"); + }); + it("should return undefined without a description", function() { + assert.equal(modSettingDescription(locale, { name: "other" }), undefined); + }); + }); + + describe("modSettingValueName()", function() { + it("should resolve the string-mod-setting key", function() { + assert.equal(modSettingValueName(locale, "mode", "fast"), "Fast"); + }); + it("should fall back to the value", function() { + assert.equal(modSettingValueName(locale, "mode", "slow"), "slow"); + assert.equal(modSettingValueName(locale, "mode", 3), "3"); + }); + }); +}); diff --git a/test/web_ui/mod_settings.js b/test/web_ui/mod_settings.js new file mode 100644 index 00000000..607e3b71 --- /dev/null +++ b/test/web_ui/mod_settings.js @@ -0,0 +1,59 @@ +import assert from "node:assert/strict"; + +import { modSettingFields } from "../../packages/web_ui/src/util/mod_settings.ts"; + +describe("web_ui/util/mod_settings", function() { + describe("modSettingFields()", function() { + const stored = new Map([ + ["kept", { value: true }], + ["gone-number", { value: 2 }], + ["gone-color", { value: { r: 1, g: 0, b: 0, a: 1 } }], + ["gone-string", { value: "x" }], + ]); + const prototypes = { + "bool-setting": { + "kept": { type: "bool-setting", name: "kept", mod: "b", setting_type: "startup", default_value: false }, + "map": { + type: "bool-setting", name: "map", mod: "a", setting_type: "runtime-global", default_value: false, + }, + }, + "string-setting": { + "first": { + type: "string-setting", name: "first", mod: "a", setting_type: "startup", + default_value: "x", allowed_values: ["x", "y"], + localised_name: ["name.first"], localised_description: ["description.first"], + }, + }, + "unrelated": { "gone-number": { type: "unrelated", name: "gone-number", setting_type: "startup" } }, + }; + + it("should split stored settings no prototype defines into unknown", function() { + const { known, unknown } = modSettingFields(prototypes, "startup", stored); + assert.deepEqual(known.map(field => field.name), ["first", "kept"]); + assert.deepEqual(known[0].allowed_values, ["x", "y"]); + assert.deepEqual(known[0].localised_name, ["name.first"]); + assert.deepEqual(known[0].localised_description, ["description.first"]); + assert.deepEqual( + unknown.map(field => [field.name, field.type]), + [["gone-color", "color-setting"], ["gone-number", "double-setting"], ["gone-string", "string-setting"]], + ); + }); + it("should only use prototypes of the given scope", function() { + const kept = new Map([["kept", { value: true }]]); + const { known, unknown } = modSettingFields(prototypes, "runtime-global", kept); + assert.deepEqual(known.map(field => field.name), ["map"]); + assert.deepEqual(unknown.map(field => field.name), ["kept"]); + }); + it("should not call settings unknown without export data", function() { + const { known, unknown } = modSettingFields(undefined, "startup", stored); + assert.deepEqual(known.map(field => field.name), [...stored.keys()]); + assert(known.every(field => field.mod === undefined)); + assert.deepEqual(unknown, []); + }); + it("should treat every stored setting as unknown if the export has no settings", function() { + const { known, unknown } = modSettingFields({}, "startup", stored); + assert.deepEqual(known, []); + assert.equal(unknown.length, stored.size); + }); + }); +}); diff --git a/test/web_ui/useResourceState.js b/test/web_ui/useResourceState.js new file mode 100644 index 00000000..50666001 --- /dev/null +++ b/test/web_ui/useResourceState.js @@ -0,0 +1,37 @@ +import assert from "node:assert/strict"; + +import { getResourceStatus } from "../../packages/web_ui/src/util/useResourceState.ts"; + +describe("web_ui/util/useResourceState", function() { + describe("getResourceStatus()", function() { + const error = new Error("Permission denied"); + + it("should be ok when the resource exists", function() { + assert.equal(getResourceStatus(true, true, true, null), "ok"); + }); + it("should keep showing a resource after the subscription stopped syncing", function() { + assert.equal(getResourceStatus(true, true, false, null), "ok"); + assert.equal(getResourceStatus(true, true, false, error), "ok"); + }); + it("should be loading until the subscription has synced", function() { + assert.equal(getResourceStatus(false, false, false, null), "loading"); + }); + it("should be loading while resyncing a resource that was seen", function() { + assert.equal(getResourceStatus(false, true, false, null), "loading"); + }); + it("should be missing when synced without having seen the resource", function() { + assert.equal(getResourceStatus(false, false, true, null), "missing"); + }); + it("should be deleted when synced after having seen the resource", function() { + assert.equal(getResourceStatus(false, true, true, null), "deleted"); + }); + it("should be error when the subscription failed", function() { + assert.equal(getResourceStatus(false, false, false, error), "error"); + assert.equal(getResourceStatus(false, true, false, error), "error"); + }); + it("should ignore the error of an earlier attempt once synced", function() { + assert.equal(getResourceStatus(false, false, true, error), "missing"); + assert.equal(getResourceStatus(false, true, true, error), "deleted"); + }); + }); +});