mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-19 07:33:12 +09:00
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:
49 files changed
+4855
-473
No files matched your search
+255
-48
@@ -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) {
|
||||
|
||||
Reference in new issue
Block a user