Pair hosts when they start instead of in the installer

The installer only writes the controller URL and host name. Running the
host requests to join the cluster if it has not been approved yet, or if
the controller no longer accepts its token, and waits until an admin
approves it. Once approved it saves its id and token and starts as
normal. A rejected host exits with code 8.

clusteriohost run --user-token approves the host right away with the
token of a user allowed to approve hosts. The token is not saved.

This moves the pairing client into the host package, where it uses the
same certificate setup as the host's connection to the controller, and
removes --no-pair and the rerun handling from the installer.
This commit is contained in:
Danielv123 committed 2026-10-30 21:13:14 +01:00
1 parent 37e79d9c41
commit 4a49a198f0
25 files changed
+948 -1131

No files matched your search

+24 -35
View File
@@ -37,11 +37,10 @@ The installer runs without prompts when all the questions for the mode are answe
| `--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. |
| `--controller-token <token>` | ctl | Authentication token saved for clusterioctl. |
| `--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. |
| `--self-signed-cert <path>` | standalone, host | Certificate to trust for a controller using a self-signed certificate. It is 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. |
@@ -57,47 +56,39 @@ 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:
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. 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.
Only approve a request if its code matches the one shown by the host.
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.
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.
Press Ctrl+C while the installer waits to cancel the request.
A request that is not approved within an hour expires.
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.
Pass `--controller-token <token>` with the token of a user that has the `core.host.approve` permission to approve the host without waiting.
Start the host with `npx clusteriohost run --user-token <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 <path>`, 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 <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.
Starting it again requests to join the cluster again, and the host gets a new id once approved.
## 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.
To move a host to another controller, change `host.controller_url` with `npx clusteriohost config set host.controller_url <url>` and set `host.controller_token` back to `enter token here`.
The host then requests to join that controller 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 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.
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
@@ -105,18 +96,16 @@ FROM node:22
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
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 npm init "@clusterio" -- --mode host --controller-url "$CONTROLLER_URL" --host-name "$HOST_NAME" \
${CONTROLLER_TOKEN:+--controller-token "$CONTROLLER_TOKEN"} && exec ./run-host.sh
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 \
-e CONTROLLER_URL=https://example.com/ -e HOST_NAME=my-host my-host-image
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 pairs as a new 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 `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.
- 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.
+38 -202
View File
@@ -10,7 +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 { createLocalHost } from "./local_host.js";
import { copyPluginTemplates } from "./template.js";
let dev = false;
const scriptExt = process.platform === "win32" ? ".cmd" : "";
@@ -200,21 +200,6 @@ function normaliseControllerUrl(input) {
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"]) {
@@ -222,135 +207,6 @@ async function setRemoteUpdates(exec, component, 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);
}
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() {
let entries = new Set(await fs.readdir("."));
if (entries.size) {
@@ -681,37 +537,6 @@ 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 = {};
@@ -771,13 +596,31 @@ async function inquirerMissingArgs(args) {
}
if (answers.mode === "host") {
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 (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: os.hostname(),
validate: validateHostName,
},
{
type: "input",
name: "controllerUrl",
message: "Controller URL",
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);
}
if (answers.mode === "ctl") {
@@ -947,12 +790,7 @@ async function main() {
nargs: 1, describe: "Controller URL [host/ctl]", type: "string",
})
.option("controller-token", {
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",
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",
@@ -1005,11 +843,6 @@ 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;
@@ -1048,13 +881,18 @@ async function main() {
await execHost(["config", "set", "host.controller_token", host.token]);
}
if (answers.mode === "host") {
// 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]);
}
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 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);
@@ -1066,16 +904,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 (answers.mode === "host") {
console.log(
`Start the host with run-host${process.platform === "win32" ? ".cmd" : ".sh"}, then approve it on the ` +
`Hosts page of ${answers.controllerUrl}`
);
}
if (adminToken) {
console.log(`Admin authentication token: ${adminToken}`);
}
+68
View File
@@ -0,0 +1,68 @@
// Adds the host of a standalone install to the controller database, used by the installer.
// Only uses Node.js builtins as it runs before Clusterio is installed.
import crypto from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
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 };
}
-275
View File
@@ -1,275 +0,0 @@
// 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 };
}