Replace host tokens with host pairing

Hosts join the cluster by running the installer, which shows a code and
waits until the request is approved under Hosts > Add host in the web
interface or with clusterioctl host approve. An admin can pass their
user token to the installer to approve the host right away. The token
is only used for that and is not saved.

The controller only accepts hosts that have a record, and only
approving a host creates one. Revoking a host deletes its record, so
its token can no longer be used to reconnect. Hosts that have connected
before keep working.

Removes host generate-token, revoke-token and create-config from
clusterioctl, bootstrap generate-host-token, the host token messages and
the core.host.generate_token, revoke_token and create_config
permissions, which are also stripped from stored roles. Adds
clusterioctl host pending, approve, reject and revoke, and the
core.host.approve and core.host.revoke permissions.

Standalone installs add the host to the controller database directly,
since the controller is not running during the install.
This commit is contained in:
Danielv123 committed 2026-10-30 06:11:32 +01:00
1 parent fa2883d74e
commit 87d4f5c64e
49 files changed
+4855 -473

No files matched your search

+116
View File
@@ -4,3 +4,119 @@ 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 added to the controller directly and does not need to be approved.
- `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 <mode>` | all | Operating mode to install. |
| `--admin <name>` | standalone, controller | Name of the admin account to create. |
| `--http-port <port>` | standalone, controller | Port the controller web interface listens on, defaults to 8080. |
| `--host-name <name>` | host | Name to request for the host, defaults to the name of the computer. |
| `--controller-url <url>` | host, ctl | URL of the controller, the same as for its web interface. |
| `--controller-token <token>` | host, ctl | ctl: authentication token saved for clusterioctl. host: authentication token of a user that approves the host without waiting, it is not saved. |
| `--no-pair` | host | Install the host without pairing it with the controller. |
| `--public-address <address>` | standalone, host | DNS name or IP address players connect to this computer with. |
| `--factorio-dir <path>` | standalone, host | Path to the Factorio installation. |
| `--self-signed-cert <path>` | standalone, host | Certificate to trust for a controller using a self-signed certificate. It is used for pairing and added to the run scripts. |
| `--remote-npm`, `--no-remote-npm` | standalone, controller, host | Allow or deny remote updates, plugin updates and plugin installs from the web interface. |
| `--plugins <package...>` | all | Plugins to install, pass `--plugins` without packages to install none. |
| `--plugin-template <template...>`, `--plugin-name <name>` | plugin-template | Templates to use and name of the new plugin. |
| `--log-level <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. |
## 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. Once it has installed everything it prints a code and waits for the host to be approved:
Waiting for approval. Approve "my-host" with code ABC-DEF on the Hosts page of https://example.com/, or run: npx clusterioctl host approve ABC-DEF
3. Approve the request by clicking Add host on the Hosts page of the web interface, or run `npx clusterioctl host approve ABC-DEF`.
Only approve a request if its code matches the one shown by the installer.
Approving requires the `core.host.approve` permission.
4. The installer saves `host.id`, `host.name`, `host.controller_url` and `host.controller_token` to `config-host.json` and exits.
Start the host with `run-host.cmd`, `run-host.sh` or the systemd service in the `systemd` folder.
Press Ctrl+C while the installer waits to cancel the request.
A request that is not approved within an hour expires.
Pass `--controller-token <token>` with 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 <path>`, see [setting up TLS](https://github.com/clusterio/clusterio/blob/master/docs/setting-up-tls.md#creating-and-using-a-self-signed-certificate).
When a host is revoked in the web interface or with `npx clusterioctl host revoke <host>` its token stops working and a running host shuts down.
Starting it again fails with exit code 8, which the run scripts do not restart on.
## Running the installer again
Running the installer with the host mode in a directory with `config-host.json` in it does not install anything, it only pairs the host again if needed:
- If the controller accepts the saved token it prints "Host is already set up" and exits with code 0.
- If it does not, for example because the host was revoked or never approved, it asks for the host name and controller URL, defaulting to the saved ones, and pairs the host again.
The host gets a new id, other settings in `config-host.json` are kept.
- If the controller cannot be reached it prints a warning, keeps the saved config and exits with code 0.
The token is only checked with the controller in `config-host.json`.
Passing a different `--controller-url` pairs the host with that controller instead, without sending it the saved token, and the host gets a new id.
If the same controller only moved to a new address, change the address with `npx clusteriohost config set host.controller_url <url>` instead, which keeps the host.
## Docker
To run a host in a container install it when building the image with all answers given as options and `--no-pair`.
Then run the installer again with the host mode when the container starts, it pairs the host on the first start and exits straight away on later 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 --no-pair --public-address factorio.example.com \
--factorio-dir /opt/factorio --no-remote-npm --plugins
VOLUME /clusterio
CMD npm init "@clusterio" -- --mode host --controller-url "$CONTROLLER_URL" --host-name "$HOST_NAME" \
${CONTROLLER_TOKEN:+--controller-token "$CONTROLLER_TOKEN"} && exec ./run-host.sh
```
docker run -d --name my-host -v my-host:/clusterio -p 34100-34199:34100-34199/udp \
-e CONTROLLER_URL=https://example.com/ -e HOST_NAME=my-host my-host-image
docker logs my-host
- The volume holds `config-host.json`, without it every new container pairs 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 `CONTROLLER_TOKEN` to approve the host without waiting.
- Stop the container after revoking its host, otherwise a restart runs the installer again and the host asks to join again.
+255 -48
View File
@@ -10,6 +10,7 @@ import util from "node:util";
import yargs from "yargs";
import { levels, logger, setLogLevel } from "./logging.js";
import { checkHostToken, createLocalHost, pairHost, PairingError } from "./pair.js";
import { copyPluginTemplates } from "./template.js";
let dev = false;
const scriptExt = process.platform === "win32" ? ".cmd" : "";
@@ -161,22 +162,193 @@ 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");
function validateHostName(input) {
if (!input || !input.trim()) {
return "Host name may not be empty";
}
if (input.trim().length > 100) {
return "Host name may be at most 100 characters";
}
if (hostNameControlCharacters.test(input)) {
return "Host name may not contain control characters";
}
return true;
}
let parsed;
// Same characters as the controller refuses in host names.
const hostNameControlCharacters = /[\p{Cc}\u202a-\u202e\u2066-\u2069]/u;
function validateControllerUrl(input) {
let url;
try {
parsed = JSON.parse(Buffer.from(parts[1], "base64"));
url = new URL(input);
} 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;
}
// The host requires the controller URL to end with a slash.
function normaliseControllerUrl(input) {
const url = new URL(input);
if (!url.pathname.endsWith("/")) {
url.pathname += "/";
}
return url.href;
}
async function readSelfSignedCert(args) {
if (!args.selfSignedCert) {
return undefined;
}
try {
return await fs.readFile(args.selfSignedCert);
} catch (err) {
throw new InstallError(`Failed to read --self-signed-cert ${args.selfSignedCert}: ${err.message}`);
}
}
async function installerVersion() {
return JSON.parse(await fs.readFile(path.join(import.meta.dirname, "package.json"))).version;
}
// 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]);
}
}
// Turn an error from pairing into a message for the user.
function pairingFailed(err) {
const retry = "Run the installer again with --mode host in this directory to retry.";
if (err.name === "AbortError") {
return new InstallError(`Pairing cancelled. ${retry}`);
}
if (err instanceof PairingError) {
return new InstallError(`Pairing failed: ${err.message}. ${retry}`);
}
if (typeof err.code === "string") {
const hint = /CERT|SELF_SIGNED|UNABLE_TO_VERIFY/.test(err.code)
? " Pass the certificate with --self-signed-cert if the controller uses a self-signed one."
: "";
return new InstallError(`Failed to connect to the controller: ${err.message}.${hint} ${retry}`);
}
return err;
}
// Request to join the cluster and save the id and token of the host once approved.
async function pairWithController(args, { hostName, controllerUrl }) {
const ca = await readSelfSignedCert(args);
await execHost(["config", "set", "host.name", hostName]);
await execHost(["config", "set", "host.controller_url", controllerUrl]);
// Ctrl-C may arrive twice under npm init, as npm forwards it to the installer, so keep
// listening until the request has been cancelled.
const abort = new AbortController();
const onSigint = () => { abort.abort(); };
process.on("SIGINT", onSigint);
// The close patch for inquirer on Windows leaves the console in raw mode, where Ctrl-C is
// read as input instead of raising SIGINT. No prompts follow, so it can be turned off.
if (process.platform === "win32" && process.stdin.isTTY && process.stdin.isRaw) {
process.stdin.setRawMode(false);
}
let result;
try {
logger.info(`Requesting to join the cluster at ${controllerUrl}`);
result = await pairHost({
controllerUrl,
name: hostName,
version: await installerVersion(),
token: args.controllerToken,
ca,
signal: abort.signal,
onPending: ({ code }) => {
// eslint-disable-next-line no-console
console.log(
`Waiting for approval. Approve "${hostName}" with code ${code} on the Hosts page of ` +
`${controllerUrl}, or run: npx clusterioctl host approve ${code}`
);
},
});
} catch (err) {
throw pairingFailed(err);
} finally {
process.off("SIGINT", onSigint);
}
if (parsed.aud !== "host" || !Number.isInteger(parsed.host)) {
throw new InstallError("Invalid token");
logger.info(`Host approved as "${result.name}" with id ${result.hostId}`);
await execHost(["config", "set", "host.id", result.hostId]);
if (result.name !== hostName) {
await execHost(["config", "set", "host.name", result.name]);
}
// Saved last so that an interrupted install is paired again when the installer is run again.
await execHost(["config", "set", "host.controller_token", result.token]);
}
// Pair a host that is already installed again, unless the controller still accepts it.
async function rerunHost(args) {
let config;
try {
config = JSON.parse(await fs.readFile("config-host.json"));
} catch (err) {
throw new InstallError(`Failed to read config-host.json: ${err.message}`);
}
// Let a rerun fix run scripts written before the certificate was passed.
if (!dev && args.selfSignedCert) {
logger.info("Writing run scripts");
await writeScripts("host", args.selfSignedCert);
}
if (!args.pair) {
// eslint-disable-next-line no-console
console.log("Host is already installed");
return;
}
const token = config["host.controller_token"];
const controllerUrl = config["host.controller_url"];
let otherController = false;
if (args.controllerUrl !== undefined) {
const result = validateControllerUrl(args.controllerUrl);
if (result !== true) {
throw new InstallError(result);
}
const savedUrl = validateControllerUrl(controllerUrl) === true ? normaliseControllerUrl(controllerUrl) : "";
otherController = normaliseControllerUrl(args.controllerUrl) !== savedUrl;
}
// The token is never sent to another controller, it would give that controller access to this cluster.
if (otherController) {
logger.info(`Pairing with ${args.controllerUrl} instead of the controller in config-host.json`);
} else if (token && token !== "enter token here") {
let valid;
try {
valid = await checkHostToken({ controllerUrl, token, ca: await readSelfSignedCert(args) });
} catch (err) {
if (err instanceof InstallError) {
throw err;
}
logger.warn(`Could not check if ${controllerUrl} accepts this host: ${err.message}`);
logger.warn("Keeping the existing host config, pass --controller-url to pair with another controller");
return;
}
if (valid) {
// eslint-disable-next-line no-console
console.log("Host is already set up");
return;
}
logger.info("The controller no longer accepts this host, pairing it again");
}
const answers = await inquirerPairingArgs(args, {
hostName: config["host.name"],
controllerUrl: config["host.controller_url"],
});
await pairWithController(args, answers);
// eslint-disable-next-line no-console
console.log("Successfully set up host");
}
async function validateInstallDir() {
@@ -509,6 +681,37 @@ WantedBy=multi-user.target
}
}
async function inquirerPairingArgs(args, defaults = {}) {
let answers = {};
if (args.hostName) { answers.hostName = args.hostName; }
if (args.controllerUrl) { answers.controllerUrl = args.controllerUrl; }
answers = await inquirer.prompt([
{
type: "input",
name: "hostName",
message: "Name of host",
default: defaults.hostName ?? os.hostname(),
validate: validateHostName,
},
{
type: "input",
name: "controllerUrl",
message: "Controller URL",
default: defaults.controllerUrl,
validate: validateControllerUrl,
},
], answers);
// Inquirer does 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);
return answers;
}
// eslint-disable-next-line complexity
async function inquirerMissingArgs(args) {
let answers = {};
@@ -568,17 +771,16 @@ async function inquirerMissingArgs(args) {
}
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 (await pathExists("config-host.json")) {
// An installed host is only paired again, see rerunHost
return { mode: "host", rerun: true };
}
if (args.pair) {
answers = { ...answers, ...await inquirerPairingArgs(args) };
}
}
if (["host", "ctl"].includes(answers.mode)) {
if (answers.mode === "ctl") {
if (args.controllerUrl) { answers.controllerUrl = args.controllerUrl; }
answers = await inquirer.prompt([
{
@@ -598,10 +800,6 @@ async function inquirerMissingArgs(args) {
], answers);
}
if (answers.mode === "host") {
validateHostToken(answers.controllerToken);
}
if (["standalone", "host"].includes(answers.mode)) {
let myIp = "localhost";
if (args.publicAddress) {
@@ -663,7 +861,7 @@ async function inquirerMissingArgs(args) {
{
type: "confirm",
name: "remoteNpm",
message: "Allow remote updates via npm?",
message: "Allow remote updates and plugin installs from the web interface?",
default: true,
},
], answers);
@@ -749,7 +947,12 @@ async function main() {
nargs: 1, describe: "Controller URL [host/ctl]", type: "string",
})
.option("controller-token", {
nargs: 1, describe: "Controller authentication token [host/ctl]", type: "string",
nargs: 1, type: "string", describe:
"User token for ctl, or of a user that approves the host without waiting (not saved) [host/ctl]",
})
.option("pair", {
describe: "Pair the host with the controller, use --no-pair to only install it [host]",
default: true, type: "boolean",
})
.option("public-address", {
nargs: 1, describe: "DNS/IP Address to connect to this server [standalone/host]", type: "string",
@@ -761,7 +964,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",
@@ -801,6 +1005,11 @@ async function main() {
let answers = await inquirerMissingArgs(args);
logger.verbose(JSON.stringify(answers));
if (answers.rerun) {
await rerunHost(args);
return;
}
if (answers.pluginTemplate) {
await copyPluginTemplates(answers.pluginName, answers.pluginTemplate);
return;
@@ -816,46 +1025,36 @@ 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"]);
}
if (answers.mode === "standalone") {
// The controller is not running, so the host is added to its database directly. The id
// from the host config is kept so running the installer again reuses the same host.
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];
let host = await createLocalHost({ name: "local", id: Number.isInteger(hostId) ? hostId : undefined });
await execHost(["config", "set", "host.id", host.hostId]);
await execHost(["config", "set", "host.name", host.name]);
// 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]);
await execHost(["config", "set", "host.controller_token", host.token]);
}
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]);
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]);
if (["standalone", "host"].includes(answers.mode)) {
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);
}
// Written before pairing as running the installer again on an installed host only pairs it.
if (!dev && ["standalone", "controller", "host"].includes(answers.mode)) {
logger.info("Writing run scripts");
await writeScripts(answers.mode, args.selfSignedCert);
@@ -867,6 +1066,14 @@ async function main() {
await execCtl(["config", "set", "ctl.controller_token", answers.controllerToken]);
}
if (answers.mode === "host") {
if (args.pair) {
await pairWithController(args, answers);
} else {
logger.info("Run the installer again with --mode host in this directory to pair the host");
}
}
/* eslint-disable no-console */
console.log(`Successfully installed ${answers.mode}`);
if (adminToken) {
+275
View File
@@ -0,0 +1,275 @@
// Pairing of hosts with the controller, used by the installer.
// Only uses Node.js builtins as it runs before or without Clusterio being installed.
import crypto from "node:crypto";
import fs from "node:fs/promises";
import http from "node:http";
import https from "node:https";
import path from "node:path";
import { setTimeout as sleep } from "node:timers/promises";
/** Time to keep polling through network errors, the controller drops requests not polled for 30 seconds */
const pollRetryMs = 30e3;
/** Time to wait for a response from the controller */
const requestTimeoutMs = 30e3;
/** Largest response accepted from the controller */
const maxResponseSize = 64 * 1024;
/** Error responded by the controller, or for an invalid controller URL */
export class PairingError extends Error {
/**
* @param {string} message - Description of the error.
* @param {number=} status - HTTP status the controller responded with.
*/
constructor(message, status) {
super(message);
this.name = "PairingError";
/** @type {number | undefined} */
this.status = status;
}
}
function apiUrl(controllerUrl, route) {
let url;
try {
url = new URL(route, controllerUrl.endsWith("/") ? controllerUrl : `${controllerUrl}/`);
} catch (err) {
throw new PairingError(`Invalid controller URL ${controllerUrl}`);
}
if (!["http:", "https:"].includes(url.protocol)) {
throw new PairingError(`Controller URL ${controllerUrl} must start with http:// or https://`);
}
return url;
}
function request(url, { method = "POST", body, token, ca, signal, timeoutMs = requestTimeoutMs }) {
return new Promise((resolve, reject) => {
const data = body === undefined ? undefined : JSON.stringify(body);
const headers = { "Accept": "application/json" };
if (data !== undefined) {
headers["Content-Type"] = "application/json";
headers["Content-Length"] = Buffer.byteLength(data);
}
if (token) {
headers["Authorization"] = `Bearer ${token}`;
}
const options = { method, headers, signal, timeout: timeoutMs };
if (url.protocol === "https:" && ca) {
options.ca = ca;
}
const req = (url.protocol === "https:" ? https : http).request(url, options, res => {
const chunks = [];
let size = 0;
res.on("data", chunk => {
size += chunk.length;
if (size > maxResponseSize) {
req.destroy(new PairingError("Response from controller is too large", res.statusCode));
return;
}
chunks.push(chunk);
});
res.on("error", reject);
res.on("end", () => {
let json;
try {
json = JSON.parse(Buffer.concat(chunks).toString());
} catch (err) {
json = undefined;
}
resolve({ status: res.statusCode, headers: res.headers, json });
});
});
req.on("timeout", () => {
const err = new Error(`Request to ${url} timed out`);
err.code = "ETIMEDOUT";
req.destroy(err);
});
req.on("error", reject);
req.end(data);
});
}
function responseError(response) {
let message = typeof response.json?.error === "string"
? response.json.error
: `Unexpected response from controller: ${response.status} ${http.STATUS_CODES[response.status] ?? ""}`.trim();
const retryAfter = response.headers["retry-after"];
if (response.status === 429 && retryAfter) {
message += `, try again in ${retryAfter} seconds`;
}
return new PairingError(message, response.status);
}
function pairingResult(response) {
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 };
}
async function pollUntilDone(controllerUrl, requestId, ca, pollIntervalMs, signal) {
const url = apiUrl(controllerUrl, "api/host-pairing/poll");
let lastResponseMs = Date.now();
while (true) {
await sleep(pollIntervalMs, undefined, { signal });
let response;
try {
response = await request(url, { body: { requestId }, ca, signal });
} catch (err) {
if (signal?.aborted || Date.now() - lastResponseMs > pollRetryMs) {
throw err;
}
continue;
}
lastResponseMs = Date.now();
if (response.status === 200) {
return pairingResult(response);
}
if (response.status !== 202) {
throw responseError(response);
}
}
}
/**
* Request to join the cluster and wait until the request is approved
*
* @param {object} options - Pairing options.
* @param {string} options.controllerUrl - URL of the controller, with or without a trailing slash.
* @param {string} options.name - Name to request for the host.
* @param {string=} options.version - Version of the installer, shown with the request.
* @param {string=} options.token -
* Token of a user allowed to approve hosts, approves the host without waiting.
* @param {(string|Buffer)=} options.ca - Certificate to trust for a controller using a self-signed certificate.
* @param {number=} options.pollIntervalMs - Interval to poll for the result at.
* @param {function({ code: string }): void=} options.onPending -
* Called once with the code to approve the request with if it has to wait for approval.
* @param {AbortSignal=} options.signal - Signal to cancel the request with.
* @returns {Promise<{ hostId: number, token: string, name: string }>} 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({
controllerUrl, name, version = "", token, ca, pollIntervalMs = 2000, onPending, signal,
}) {
let requestId;
try {
signal?.throwIfAborted();
const response = await request(apiUrl(controllerUrl, "api/host-pairing"), {
body: { name, version }, token, ca, signal,
});
if (response.status === 200) {
return pairingResult(response);
}
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;
onPending?.({ code: response.json.code });
return await pollUntilDone(controllerUrl, requestId, ca, pollIntervalMs, signal);
} catch (err) {
if (!signal?.aborted) {
throw err;
}
if (requestId !== undefined) {
await request(apiUrl(controllerUrl, "api/host-pairing/cancel"), {
body: { requestId }, ca, timeoutMs: 5e3,
}).catch(() => {});
}
throw new DOMException("Pairing was cancelled", "AbortError");
}
}
/**
* Check if the controller accepts a host token
*
* @param {object} options - Check options.
* @param {string} options.controllerUrl - URL of the controller, with or without a trailing slash.
* @param {string} options.token - Host token to check.
* @param {(string|Buffer)=} options.ca - Certificate to trust for a controller using a self-signed certificate.
* @returns {Promise<boolean>} 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, token, ca }) {
const response = await request(apiUrl(controllerUrl, "api/host-pairing/check"), {
method: "GET", token, ca,
});
if (response.status === 200) {
return true;
}
if (response.status === 401) {
return false;
}
throw responseError(response);
}
function signHostToken(payload, secret) {
const encode = value => Buffer.from(JSON.stringify(value)).toString("base64url");
const unsigned = `${encode({ alg: "HS256", typ: "JWT" })}.${encode(payload)}`;
const signature = crypto.createHmac("sha256", secret).update(unsigned).digest("base64url");
return `${unsigned}.${signature}`;
}
/**
* Add a host to the database of a controller installed in the same directory
*
* The controller must not be running, as it would overwrite the database with
* what it has in memory.
*
* @param {object} options - Host options.
* @param {string=} options.directory - Directory with config-controller.json in it.
* @param {string} options.name - Name of the host.
* @param {number=} options.id -
* Id to give the host, picks a random unused id if not given. If a host with
* this id exists, a new token is signed for it and its name is kept.
* @param {string=} options.version - Version to record for the host.
* @returns {Promise<{ hostId: number, token: string, name: string }>} id, token and name of the host.
*/
export async function createLocalHost({ directory = ".", name, id, version = "" }) {
const configPath = path.join(directory, "config-controller.json");
const config = JSON.parse(await fs.readFile(configPath, "utf8"));
const secret = config["controller.auth_secret"];
if (typeof secret !== "string" || !secret) {
throw new Error(`${configPath} has no controller.auth_secret`);
}
const databaseDirectory = path.resolve(directory, config["controller.database_directory"] ?? "database");
const hostsPath = path.join(databaseDirectory, "hosts.json");
let hosts = [];
try {
hosts = JSON.parse(await fs.readFile(hostsPath, "utf8"));
} catch (err) {
if (err.code !== "ENOENT") {
throw err;
}
}
const now = Math.floor(Date.now() / 1000);
const existing = id === undefined ? undefined : hosts.find(host => host.id === id);
let hostId = id;
if (existing) {
// Running the installer again signs a new token for the same host.
name = existing.name;
} else {
const ids = new Set(hosts.map(host => host.id));
while (hostId === undefined || ids.has(hostId)) {
hostId = crypto.randomInt(1, 2 ** 31);
}
hosts.push({ id: hostId, name, version, plugins: {}, token_valid_after: now });
await fs.mkdir(databaseDirectory, { recursive: true });
const temporary = path.join(databaseDirectory, "hosts.tmp.json");
await fs.writeFile(temporary, JSON.stringify(hosts, null, "\t"), { flush: true });
await fs.rename(temporary, hostsPath);
}
const token = signHostToken({ aud: "host", host: hostId, iat: now }, Buffer.from(secret, "base64"));
return { hostId, token, name };
}