mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-19 23:33:13 +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
@@ -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
|
||||
import * as lib from "@clusterio/lib";
|
||||
@@ -186,14 +185,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) {
|
||||
@@ -322,9 +313,6 @@ async function initialize(): Promise<InitializeParameters> {
|
||||
.command("generate-user-token <name>", "Generate authentication token for the given user", yargs => {
|
||||
yargs.positional("name", { describe: "Name of the user", type: "string" });
|
||||
})
|
||||
.command("generate-host-token <id>", "Generate authentication token for the given host", yargs => {
|
||||
yargs.positional("id", { describe: "ID of the host", type: "number" });
|
||||
})
|
||||
.command("create-ctl-config <name>", "Create clusterioctl config for the given user", yargs => {
|
||||
yargs.option("output", {
|
||||
describe: "Path to output config (- for stdout)", type: "string",
|
||||
|
||||
@@ -6,6 +6,7 @@ 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 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";
|
||||
|
||||
@@ -81,10 +81,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));
|
||||
@@ -248,49 +249,49 @@ export default class ControlConnection extends BaseConnection {
|
||||
this._controller.config.setProp(field as keyof lib.ControllerConfigFields, prop, value, "control");
|
||||
}
|
||||
|
||||
async handleHostRevokeTokensRequest(request: lib.HostRevokeTokensRequest) {
|
||||
async handleHostRevokeRequest(request: lib.HostRevokeRequest) {
|
||||
const host = this._controller.hosts.getMutable(request.hostId);
|
||||
if (!host) {
|
||||
throw new Error(`Unknown host id (${request.hostId})`);
|
||||
throw new lib.NotFoundError(`Unknown host id (${request.hostId})`);
|
||||
}
|
||||
|
||||
host.tokenValidAfter = Math.floor(Date.now() / 1000);
|
||||
const assigned = [...this._controller.instances.values()].filter(
|
||||
instance => instance.config.get("instance.assigned_host") === request.hostId
|
||||
);
|
||||
if (assigned.length) {
|
||||
const names = assigned.map(instance => instance.config.get("instance.name")).join(", ");
|
||||
throw new lib.ConflictError(
|
||||
`Cannot revoke host ${host.name} while instances are assigned to it: ${names}`
|
||||
);
|
||||
}
|
||||
|
||||
this._controller.hosts.delete(host);
|
||||
this._controller.deleteNote("host", request.hostId, this.user.name);
|
||||
|
||||
// Disconnect before saving so the host is cut off even if the save fails.
|
||||
const hostConnection = this._controller.wsServer.hostConnections.get(request.hostId);
|
||||
if (hostConnection) {
|
||||
hostConnection.connector.terminate();
|
||||
}
|
||||
|
||||
this._controller.hosts.set(host);
|
||||
logger.audit(`User ${this.user.name} revoked host ${host.name} (${host.id})`);
|
||||
await this._controller.hosts.save();
|
||||
}
|
||||
|
||||
async handleHostListRequest(): Promise<lib.HostDetails[]> {
|
||||
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<lib.HostPairingDetails[]> {
|
||||
this._controller.hostPairing.prune();
|
||||
return [...this._controller.hostPairing.requests.values()];
|
||||
}
|
||||
|
||||
async handleHostConfigCreateRequest(request: lib.HostConfigCreateRequest) {
|
||||
const hostConfig = new lib.HostConfig("host");
|
||||
async handleHostPairingApproveRequest(request: lib.HostPairingApproveRequest) {
|
||||
return await 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) {
|
||||
|
||||
@@ -29,6 +29,7 @@ import UserRecord from "./UserRecord.js";
|
||||
import UserManager from "./UserManager.js";
|
||||
import WsServer from "./WsServer.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";
|
||||
@@ -91,6 +92,8 @@ export default class Controller {
|
||||
users: UserManager;
|
||||
/** Instance manager for the cluster, also contains access to the user records */
|
||||
instances: InstanceManager;
|
||||
/** Pending requests from host installers to join the cluster */
|
||||
hostPairing: HostPairingManager;
|
||||
|
||||
// Possible states are new, starting, running, stopping, stopped
|
||||
private _state: string = "new";
|
||||
@@ -296,6 +299,7 @@ export default class Controller {
|
||||
|
||||
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 +309,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)
|
||||
@@ -318,6 +323,7 @@ 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.hostPairing.requests.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));
|
||||
@@ -367,6 +373,7 @@ export default class Controller {
|
||||
|
||||
async _startInternal(args: ControllerArgs) {
|
||||
this.logDirectory = args.logDirectory;
|
||||
this.hostPairing.start();
|
||||
this.clusterLogIndex = await lib.LogIndex.load(path.join(this.logDirectory, "cluster"));
|
||||
|
||||
this.clusterLogBuildInterval = setInterval(() => {
|
||||
@@ -582,6 +589,8 @@ export default class Controller {
|
||||
this.autosaveInterval = undefined;
|
||||
}
|
||||
|
||||
this.hostPairing.stop();
|
||||
|
||||
if (this.clusterLogIndex) {
|
||||
await this.clusterLogIndex.save();
|
||||
}
|
||||
@@ -869,6 +878,10 @@ export default class Controller {
|
||||
|
||||
static migrateRoles(rawJson: unknown[]): Static<typeof lib.Role.jsonSchema>[] {
|
||||
const serialized = rawJson as Static<typeof lib.Role.jsonSchema>[];
|
||||
// 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 +889,7 @@ export default class Controller {
|
||||
return "core.instance.save.subscribe";
|
||||
}
|
||||
return permission;
|
||||
});
|
||||
}).filter(permission => !removedPermissions.has(permission));
|
||||
return lib.Role.pluginMigrations.reduce(json);
|
||||
});
|
||||
}
|
||||
@@ -1017,6 +1030,20 @@ export default class Controller {
|
||||
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.requests.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;
|
||||
|
||||
@@ -34,19 +34,16 @@ 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,
|
||||
);
|
||||
// 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.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._saveInfo();
|
||||
});
|
||||
|
||||
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 */
|
||||
private _saveInfo() {
|
||||
if (this._controller.hosts.getMutable(this.id) === this.info) {
|
||||
this._controller.hosts.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._saveInfo();
|
||||
}
|
||||
|
||||
async handleInstanceStatusChangedEvent(request: lib.InstanceStatusChangedEvent) {
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
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";
|
||||
|
||||
import HostRecord from "./HostRecord.js";
|
||||
|
||||
/** 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 installer */
|
||||
export const pollTimeoutMs = 30e3;
|
||||
/** Maximum time a request can stay pending */
|
||||
export const maxPendingMs = 60 * 60e3;
|
||||
/** Maximum number of pending requests in total */
|
||||
export const maxPending = 50;
|
||||
/** Maximum number of pending requests from one address */
|
||||
export const maxPendingPerAddress = 3;
|
||||
/** Maximum number of requests created from one address per minute */
|
||||
export const maxCreatesPerMinute = 10;
|
||||
/** 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 installer */
|
||||
export interface HostPairingResult {
|
||||
hostId: number,
|
||||
token: string,
|
||||
name: string,
|
||||
}
|
||||
|
||||
/** Error with an HTTP status code to respond to the installer 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);
|
||||
}
|
||||
}
|
||||
|
||||
interface PairingRequest {
|
||||
/** Secret the installer 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" | "approving" | "approved" | "rejected",
|
||||
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 installer.
|
||||
*/
|
||||
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 host installers to join the cluster
|
||||
*
|
||||
* Requests only live in memory, and only while the installer keeps polling
|
||||
* for the result.
|
||||
*/
|
||||
export default class HostPairingManager {
|
||||
/** Pending requests by code, broadcast to subscribed control links */
|
||||
requests = new lib.SubscribableDatastore<lib.HostPairingDetails>();
|
||||
private _bySecret = new Map<string, PairingRequest>();
|
||||
private _byCode = new Map<string, PairingRequest>();
|
||||
/** Creation times of recent requests by address key */
|
||||
private _recentCreates = new Map<string, number[]>();
|
||||
private _pruneInterval?: ReturnType<typeof setInterval>;
|
||||
|
||||
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 an installer 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 an approved host with a new id and token
|
||||
*
|
||||
* The host record is saved to disk before this returns.
|
||||
*
|
||||
* @param name - Name of the host.
|
||||
* @returns the id, token and name of the new host.
|
||||
*/
|
||||
async createHost(name: string): Promise<HostPairingResult> {
|
||||
const hosts = this._controller.hosts;
|
||||
let hostId;
|
||||
do {
|
||||
hostId = crypto.randomInt(1, 2 ** 31);
|
||||
} while (hosts.has(hostId));
|
||||
|
||||
const record = new HostRecord(
|
||||
hostId, name, "", new Map(), false, "", "", Math.floor(Date.now() / 1000),
|
||||
);
|
||||
hosts.set(record);
|
||||
try {
|
||||
await hosts.save();
|
||||
} catch (err) {
|
||||
hosts.delete(record);
|
||||
throw err;
|
||||
}
|
||||
return { hostId, token: this._controller.generateHostToken(hostId), name };
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a pending request
|
||||
*
|
||||
* @param name - Name the installer asked for.
|
||||
* @param version - Version of the installer.
|
||||
* @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 recent = (this._recentCreates.get(key) ?? []).filter(ms => ms > now - 60e3);
|
||||
if (recent.length >= maxCreatesPerMinute) {
|
||||
throw new HostPairingError(
|
||||
"Too many requests from this address", 429, Math.ceil((recent[0] + 60e3 - now) / 1000),
|
||||
);
|
||||
}
|
||||
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);
|
||||
}
|
||||
if (this.requests.size >= maxPending) {
|
||||
throw new HostPairingError("Too many pending requests", 429, 30);
|
||||
}
|
||||
recent.push(now);
|
||||
this._recentCreates.set(key, recent);
|
||||
|
||||
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.requests.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 installer`);
|
||||
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.
|
||||
*/
|
||||
async 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);
|
||||
}
|
||||
|
||||
request.state = "approving";
|
||||
let result;
|
||||
try {
|
||||
result = await this.createHost(hostName);
|
||||
} catch (err) {
|
||||
request.state = "pending";
|
||||
throw err;
|
||||
}
|
||||
|
||||
request.state = "approved";
|
||||
request.result = result;
|
||||
this.requests.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.requests.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);
|
||||
if (this.requests.has(request.details.code)) {
|
||||
this.requests.delete(request.details);
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove requests the installer stopped polling for or that waited too long */
|
||||
prune() {
|
||||
const now = Date.now();
|
||||
for (const request of this._bySecret.values()) {
|
||||
if (request.state === "approving") {
|
||||
continue;
|
||||
}
|
||||
const expired = now - request.lastPollMs > pollTimeoutMs
|
||||
|| (request.state === "pending" && now - request.details.createdAtMs > maxPendingMs);
|
||||
if (!expired) {
|
||||
continue;
|
||||
}
|
||||
if (request.state === "approved") {
|
||||
logger.warn(
|
||||
`Approved host ${request.result!.name} (${request.result!.hostId}) was never picked up ` +
|
||||
"by its installer, revoke it on the hosts page if it is not needed"
|
||||
);
|
||||
}
|
||||
this._remove(request);
|
||||
}
|
||||
for (const [key, times] of this._recentCreates) {
|
||||
if (!times.some(ms => ms > now - 60e3)) {
|
||||
this._recentCreates.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -264,7 +264,10 @@ ${err.stack}`
|
||||
}
|
||||
|
||||
let host = this.controller.hosts.get(data.id);
|
||||
if (!tokenPayload.iat || tokenPayload.iat < (host?.tokenValidAfter ?? 0)) {
|
||||
if (!host) {
|
||||
throw new Error("host is not registered, run the installer again in the host directory");
|
||||
}
|
||||
if (!tokenPayload.iat || tokenPayload.iat < host.tokenValidAfter) {
|
||||
throw new Error("invalid token");
|
||||
}
|
||||
} catch (err: any) {
|
||||
@@ -303,6 +306,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
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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";
|
||||
@@ -215,19 +216,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 = userFromToken(req.app.locals.controller, token);
|
||||
} catch (err) {
|
||||
res.sendStatus(401);
|
||||
return;
|
||||
@@ -236,6 +225,118 @@ function validateUserToken(req: Request, res: Response, next: any) {
|
||||
next();
|
||||
}
|
||||
|
||||
function userFromToken(controller: Controller, token: string) {
|
||||
const tokenPayload = jwt.verify(token, controller.authSecret, { audience: "user" });
|
||||
if (typeof tokenPayload === "string") {
|
||||
throw new Error("unexpected JsonWebToken type");
|
||||
}
|
||||
let user = controller.users.getByName(tokenPayload.user);
|
||||
if (!user) {
|
||||
throw new Error("invalid user");
|
||||
}
|
||||
if (!tokenPayload.iat || tokenPayload.iat < user.tokenValidAfter) {
|
||||
throw new Error("invalid token");
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
// 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 an installer for a host to join the cluster.
|
||||
async 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 = userFromToken(controller, token);
|
||||
} catch (err) {
|
||||
res.status(401).json({ error: "Invalid user token" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
user.checkPermission("core.host.approve");
|
||||
} catch (err) {
|
||||
res.status(403).json({ error: `User ${user.name} is not allowed to approve hosts` });
|
||||
return;
|
||||
}
|
||||
const result = await controller.hostPairing.createHost(name);
|
||||
logger.audit(
|
||||
`User ${user.name} approved host ${result.name} (${result.hostId}) from ${remoteAddress} ` +
|
||||
"with their token"
|
||||
);
|
||||
res.status(200).json(result);
|
||||
return;
|
||||
}
|
||||
|
||||
res.status(202).json(controller.hostPairing.create(name, version, remoteAddress));
|
||||
} catch (err) {
|
||||
if (!sendHostPairingError(res, err)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Poll from an installer 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 an installer 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") {
|
||||
@@ -686,6 +787,21 @@ 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,
|
||||
(req:Request, res:Response, next:any) => createHostPairing(req, res).catch(next)
|
||||
);
|
||||
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)
|
||||
|
||||
@@ -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
@@ -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) {
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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 <host>", "Revoke all tokens for a host", (yargs) => {
|
||||
yargs.positional("host", { describe: "Host to revoke tokens for", type: "string" });
|
||||
definition: ["approve <code>", "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 <code>", "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 <host>", "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 <host>", "Update the host", (yargs) => {
|
||||
yargs.positional("host", { describe: "Host to update", type: "string" });
|
||||
|
||||
@@ -132,6 +132,9 @@ Lists up all configuration entries with their currently configured values.
|
||||
### `run`
|
||||
|
||||
Runs the host.
|
||||
The host has to be approved on the controller before it can connect, which is done by running the installer in the host directory, see Setting up remote hosts in the readme of the main repository.
|
||||
If the controller rejects the token of the host when it starts, for example because the host was revoked, 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
|
||||
|
||||
@@ -216,10 +216,9 @@ async function startHost() {
|
||||
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 <token>. You can generate an\n"+
|
||||
"auth token using npx clusterioctl generate-host-token."
|
||||
"This host has not been set up to connect to a controller. Run the installer\n"+
|
||||
"again in this directory with npm init @clusterio and approve the host in the\n"+
|
||||
"web interface."
|
||||
);
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Type, Static } from "@sinclair/typebox";
|
||||
|
||||
/**
|
||||
* A pending request from a host installer to join the cluster
|
||||
*
|
||||
* Requests are kept in memory on the controller only while the installer
|
||||
* waits for them to be approved or rejected.
|
||||
*/
|
||||
export default class HostPairingDetails {
|
||||
constructor(
|
||||
/** Code shown by the installer, used to identify the request. */
|
||||
public code: string,
|
||||
/** Name the installer asked for the host to have. */
|
||||
public name: string,
|
||||
/** Address the request was made from. */
|
||||
public remoteAddress: string,
|
||||
/** Version of the installer 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<typeof this.jsonSchema>) {
|
||||
return new this(
|
||||
json.code,
|
||||
json.name,
|
||||
json.remoteAddress,
|
||||
json.version,
|
||||
json.createdAtMs,
|
||||
json.updatedAtMs,
|
||||
json.isDeleted,
|
||||
);
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
const json: Static<typeof HostPairingDetails.jsonSchema> = {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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";
|
||||
|
||||
@@ -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<typeof this.jsonSchema>) {
|
||||
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<typeof this.jsonSchema>) {
|
||||
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<typeof this.jsonSchema>) {
|
||||
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<typeof this.jsonSchema>) {
|
||||
return new this(json.code);
|
||||
}
|
||||
}
|
||||
|
||||
export class GetFactorioCredentialsRequest {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -29,8 +29,10 @@ export const dataClasses: (RequestClass<unknown, unknown> | EventClass<unknown>)
|
||||
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<unknown, unknown> | EventClass<unknown>)
|
||||
host.ControllerConnectionEvent,
|
||||
host.PrepareControllerDisconnectRequest,
|
||||
host.SyncUserListsEvent,
|
||||
host.HostRevokeTokensRequest,
|
||||
host.HostRevokeRequest,
|
||||
|
||||
instance.InstanceDetailsGetRequest,
|
||||
instance.InstanceDetailsListRequest,
|
||||
|
||||
@@ -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 host installers to join the cluster, and approve hosts " +
|
||||
"directly by passing a token to the installer. 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.",
|
||||
},
|
||||
|
||||
{
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useContext, useState } from "react";
|
||||
import { Descriptions, Spin, Typography, Button, Space, Popconfirm, Flex, Tooltip } from "antd";
|
||||
import { ExclamationCircleOutlined } from "@ant-design/icons";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
import notify, { notifyErrorHandler } from "../util/notify";
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
MetricCpuRatio, MetricCpuUsed, MetricMemoryRatio, MetricMemoryUsed,
|
||||
MetricDiskUsed, MetricDiskRatio, MetricRelativeDate,
|
||||
} from "./system_metrics";
|
||||
import { formatTimestamp } from "../util/time_format";
|
||||
import { useSystems } from "../model/system";
|
||||
import { hasNpmButtonPermission, NpmButton } from "./NpmButton";
|
||||
import VariableDropdownButton, { VariableDropdownButtonProps } from "./VariableDropdownButton";
|
||||
@@ -98,10 +97,42 @@ function HostControlButton({ hostId, canRestart, restartRequired }: HostControlB
|
||||
return <VariableDropdownButton actions={actions} />;
|
||||
}
|
||||
|
||||
type RevokeHostButtonProps = { host: lib.HostDetails, instances: ReadonlyMap<number, lib.InstanceDetails> };
|
||||
|
||||
function RevokeHostButton({ host, instances }: RevokeHostButtonProps) {
|
||||
const control = useContext(ControlContext);
|
||||
const navigate = useNavigate();
|
||||
const assigned = [...instances.values()].map(instance => instance.name);
|
||||
|
||||
if (assigned.length) {
|
||||
return <Tooltip title={`Unassign or delete the instances on this host first: ${assigned.join(", ")}`}>
|
||||
<Button danger disabled>Revoke host access</Button>
|
||||
</Tooltip>;
|
||||
}
|
||||
|
||||
return <Popconfirm
|
||||
title={`Revoke access for ${host.name}?`}
|
||||
description={<>
|
||||
The host is removed from the cluster and disconnected.<br />
|
||||
To add it back, run the installer again in its directory.
|
||||
</>}
|
||||
placement="bottomRight"
|
||||
okText="Revoke"
|
||||
okButtonProps={{ danger: true }}
|
||||
onConfirm={() => control.send(
|
||||
new lib.HostRevokeRequest(host.id)
|
||||
).then(() => {
|
||||
notify(`Revoked access for host ${host.name}`, "success");
|
||||
navigate("/hosts");
|
||||
}).catch(notifyErrorHandler(`Error revoking access for host ${host.name}`))}
|
||||
>
|
||||
<Button danger>Revoke host access</Button>
|
||||
</Popconfirm>;
|
||||
}
|
||||
|
||||
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();
|
||||
@@ -125,24 +156,7 @@ export default function HostViewPage() {
|
||||
|
||||
let hostButtons = <Space wrap>
|
||||
<HostControlButton hostId={hostId} canRestart={system?.canRestart} restartRequired={system?.restartRequired}/>
|
||||
{
|
||||
account.hasPermission("core.host.revoke_token")
|
||||
&& <Popconfirm
|
||||
title={`Revoke tokens of ${host.name}?`}
|
||||
placement="bottomRight"
|
||||
okText="Revoke Tokens"
|
||||
okButtonProps={{ danger: true }}
|
||||
onConfirm={() => {
|
||||
control.send(new lib.HostRevokeTokensRequest(host.id!))
|
||||
.then(() => notify("Host tokens revoked"))
|
||||
.catch(notifyErrorHandler(`Error revoking tokens for host id:${host.id}`));
|
||||
}}
|
||||
>
|
||||
<Button danger>
|
||||
Revoke tokens
|
||||
</Button>
|
||||
</Popconfirm>
|
||||
}
|
||||
{account.hasPermission("core.host.revoke") && <RevokeHostButton host={host} instances={hostInstances} />}
|
||||
{canShowNpm && (
|
||||
<NpmButton target={{ hostId }} canRestart={system?.canRestart} disabled={!host["connected"]}/>
|
||||
)}
|
||||
@@ -175,13 +189,6 @@ export default function HostViewPage() {
|
||||
<Descriptions.Item label="Disk Usage"><MetricDiskRatio system={system} /></Descriptions.Item>
|
||||
<Descriptions.Item label="Disk"><MetricDiskUsed system={system} /></Descriptions.Item>
|
||||
<Descriptions.Item label="Public Address">{host.publicAddress}</Descriptions.Item>
|
||||
{
|
||||
host.tokenValidAfter
|
||||
? <Descriptions.Item label="Tokens valid after:">
|
||||
{formatTimestamp(host.tokenValidAfter*1000)}
|
||||
</Descriptions.Item>
|
||||
: null
|
||||
}
|
||||
</Descriptions>
|
||||
<ResourceNotes resourceType="host" resourceId={hostId} />
|
||||
{account.hasPermission("core.instance.list") && <>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
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 { Badge, Button, Flex, Input, Modal, Space, Switch, Table, Tooltip, Typography } from "antd";
|
||||
import { ExclamationCircleOutlined, CopyOutlined, PlusOutlined } from "@ant-design/icons";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
@@ -16,9 +16,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 +28,186 @@ 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<string|null>(null);
|
||||
let [hostId, setHostId] = useState<number|null>(null);
|
||||
let [form] = Form.useForm();
|
||||
let [pluginList, setPluginList] = useState<lib.PluginWebApi[]>([]);
|
||||
/** 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 control = useContext(ControlContext);
|
||||
const [requests, synced] = useHostPairings();
|
||||
const [names, setNames] = useState<ReadonlyMap<string, string>>(new Map());
|
||||
const [busyCodes, setBusyCodes] = useState<ReadonlySet<string>>(new Set());
|
||||
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 setName(code: string, name?: string) {
|
||||
setNames(current => {
|
||||
const next = new Map(current);
|
||||
if (name === undefined) {
|
||||
next.delete(code);
|
||||
} else {
|
||||
next.set(code, name);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
// Generate a new random
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
generateToken().catch(notifyErrorHandler("Error generating token"));
|
||||
}
|
||||
}, [open]);
|
||||
function setBusy(code: string, busy: boolean) {
|
||||
setBusyCodes(current => {
|
||||
const next = new Set(current);
|
||||
if (busy) {
|
||||
next.add(code);
|
||||
} else {
|
||||
next.delete(code);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
const pluginString = pluginList.filter(p => p.npmPackage).map(p => `"${p.npmPackage}"`).join(" ");
|
||||
function nameOf(request: Readonly<lib.HostPairingDetails>) {
|
||||
return (names.get(request.code) ?? request.name).trim();
|
||||
}
|
||||
|
||||
function approve(request: Readonly<lib.HostPairingDetails>) {
|
||||
const name = nameOf(request);
|
||||
setBusy(request.code, true);
|
||||
control.send(
|
||||
new lib.HostPairingApproveRequest(request.code, name !== request.name ? name : undefined)
|
||||
).then(() => {
|
||||
setName(request.code);
|
||||
notify(`Approved host ${name}`, "success");
|
||||
}).catch(
|
||||
notifyErrorHandler(`Error approving host ${request.name}`)
|
||||
).finally(() => {
|
||||
setBusy(request.code, false);
|
||||
});
|
||||
}
|
||||
|
||||
function reject(request: Readonly<lib.HostPairingDetails>) {
|
||||
setBusy(request.code, true);
|
||||
control.send(
|
||||
new lib.HostPairingRejectRequest(request.code)
|
||||
).then(() => {
|
||||
setName(request.code);
|
||||
}).catch(
|
||||
notifyErrorHandler(`Error rejecting host ${request.name}`)
|
||||
).finally(() => {
|
||||
setBusy(request.code, false);
|
||||
});
|
||||
}
|
||||
|
||||
return <Modal
|
||||
title="Add Host"
|
||||
open={props.open}
|
||||
footer={null}
|
||||
onCancel={props.onClose}
|
||||
width="800px"
|
||||
>
|
||||
<Typography.Paragraph>
|
||||
Run the installer in an empty directory on the machine the host will run on.
|
||||
It asks for a name for the host, then shows a code and waits for the request to be approved here.
|
||||
</Typography.Paragraph>
|
||||
<div className="codeblock">
|
||||
<CopyButton
|
||||
message="Copied host setup commands to clipboard"
|
||||
text={["mkdir clusterio", "cd clusterio", installCommand].join("\n")}
|
||||
/>
|
||||
<p>> mkdir clusterio</p>
|
||||
<p>> cd clusterio</p>
|
||||
<p>
|
||||
> npm init "@clusterio" -- --mode host
|
||||
--controller-url <span className="highlight">{controllerUrl}</span>
|
||||
</p>
|
||||
</div>
|
||||
<Typography.Paragraph>
|
||||
Once approved the installer saves the connection details of the host and exits.
|
||||
The host can then be started with the run-host script in that directory.
|
||||
</Typography.Paragraph>
|
||||
<Typography.Title level={5}>Waiting for approval</Typography.Title>
|
||||
<Typography.Paragraph type="secondary">
|
||||
Only approve a request if its code matches the code shown by the installer.
|
||||
An approved host has full access to the cluster.
|
||||
</Typography.Paragraph>
|
||||
<Table
|
||||
size="small"
|
||||
pagination={false}
|
||||
loading={!synced}
|
||||
rowKey="code"
|
||||
dataSource={[...requests.values()].sort((a, b) => a.createdAtMs - b.createdAtMs)}
|
||||
locale={{ emptyText: "No hosts are waiting for approval" }}
|
||||
columns={[
|
||||
{
|
||||
title: "Name",
|
||||
key: "name",
|
||||
render: (_, request) => <Input
|
||||
size="small"
|
||||
aria-label={`Name for host with code ${request.code}`}
|
||||
value={names.get(request.code) ?? request.name}
|
||||
onChange={event => { setName(request.code, event.target.value); }}
|
||||
/>,
|
||||
},
|
||||
{
|
||||
title: "Code",
|
||||
dataIndex: "code",
|
||||
render: (_, request) => <Typography.Text code strong>{request.code}</Typography.Text>,
|
||||
},
|
||||
{
|
||||
title: "Address",
|
||||
dataIndex: "remoteAddress",
|
||||
},
|
||||
{
|
||||
title: "Age",
|
||||
key: "age",
|
||||
render: (_, request) => <Tooltip title={new Date(request.createdAtMs).toLocaleString()}>
|
||||
<span>{formatDuration(Math.max(0, now - request.createdAtMs))}</span>
|
||||
</Tooltip>,
|
||||
},
|
||||
{
|
||||
key: "action",
|
||||
align: "right",
|
||||
render: (_, request) => {
|
||||
const busy = busyCodes.has(request.code);
|
||||
return <Space>
|
||||
<Button
|
||||
type="primary"
|
||||
size="small"
|
||||
disabled={busy || !nameOf(request)}
|
||||
onClick={() => { approve(request); }}
|
||||
>Approve</Button>
|
||||
<Button
|
||||
danger
|
||||
size="small"
|
||||
disabled={busy}
|
||||
onClick={() => { reject(request); }}
|
||||
>Reject</Button>
|
||||
</Space>;
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</Modal>;
|
||||
}
|
||||
|
||||
function AddHostButton() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [requests] = useHostPairings();
|
||||
return <>
|
||||
<Button
|
||||
onClick={() => { setOpen(true); }}
|
||||
>Generate Token</Button>
|
||||
<Modal
|
||||
title="Generate Host Token"
|
||||
open={open}
|
||||
footer={null}
|
||||
onCancel={() => {
|
||||
setOpen(false);
|
||||
setToken(null);
|
||||
form.resetFields();
|
||||
}}
|
||||
width="700px"
|
||||
>
|
||||
<Form form={form} layout="vertical" requiredMark="optional">
|
||||
<Form.Item name="hostId" label="Host ID">
|
||||
<InputNumber onChange={() => {
|
||||
generateToken().catch(notifyErrorHandler("Error generating token"));
|
||||
}} />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
<Typography.Paragraph>
|
||||
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:
|
||||
</Typography.Paragraph>
|
||||
<div className="codeblock">
|
||||
<CopyButton
|
||||
message="Copied get host id to clipboard"
|
||||
text="npx clusteriohost config get host.id"
|
||||
/>
|
||||
npx clusteriohost config get host.id
|
||||
</div>
|
||||
{token !== null && <>
|
||||
<Typography.Paragraph>
|
||||
Host auth token:
|
||||
</Typography.Paragraph>
|
||||
<div className="codeblock">
|
||||
<CopyButton
|
||||
message="Copied host token to clipboard"
|
||||
text={token}
|
||||
/>
|
||||
{token}
|
||||
</div>
|
||||
<Typography.Paragraph>
|
||||
You can set the token on an existing host with the following command:
|
||||
</Typography.Paragraph>
|
||||
<div className="codeblock">
|
||||
<CopyButton
|
||||
message="Copied set host id to clipboard"
|
||||
text={`npx clusteriohost config set host.id ${token}`}
|
||||
/>
|
||||
npx clusteriohost config set host.id {token}
|
||||
</div>
|
||||
<Typography.Paragraph>
|
||||
A new host can be setup using the following commands:
|
||||
</Typography.Paragraph>
|
||||
<div className="codeblock">
|
||||
<CopyButton
|
||||
message={"Copied host setup commands to clipboard"}
|
||||
text={`\
|
||||
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}`
|
||||
}/>
|
||||
<p>> mkdir clusterio</p>
|
||||
<p>> cd clusterio</p>
|
||||
<p>
|
||||
> npm init "@clusterio" --
|
||||
--controller-token <span className="highlight">{token} </span>
|
||||
--mode "host"
|
||||
--download-headless
|
||||
--controller-url <span className="highlight">{document.location.origin}/ </span>
|
||||
--host-name <span className="highlight">{hostId ? `Host ${hostId}` : "Host"} </span>
|
||||
--public-address <span className="highlight">localhost </span>
|
||||
{pluginString.length ? "--plugins" : ""} <span className="highlight">{pluginString}</span>
|
||||
</p>
|
||||
<p>> ./run-host</p>
|
||||
</div>
|
||||
</>}
|
||||
</Modal>
|
||||
<Badge count={requests.size} title={`${requests.size} waiting for approval`}>
|
||||
<Button type="primary" icon={<PlusOutlined />} onClick={() => { setOpen(true); }}>Add host</Button>
|
||||
</Badge>
|
||||
<AddHostModal open={open} onClose={() => { setOpen(false); }} />
|
||||
</>;
|
||||
}
|
||||
|
||||
@@ -216,7 +270,7 @@ export default function HostsPage() {
|
||||
return <PageLayout nav={[{ name: "Hosts" }]}>
|
||||
<PageHeader
|
||||
title="Hosts"
|
||||
extra={account.hasPermission("core.host.generate_token") ? <GenerateHostTokenButton /> : undefined}
|
||||
extra={account.hasPermission("core.host.approve") ? <AddHostButton /> : undefined}
|
||||
/>
|
||||
<Table
|
||||
style={{ overflowX: "auto" }}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useContext, useSyncExternalStore } from "react";
|
||||
import ControlContext from "../components/ControlContext";
|
||||
import { useAccount } from "./account";
|
||||
|
||||
export function useHost(id?: number) {
|
||||
const [hosts, synced] = useHosts();
|
||||
@@ -11,3 +12,15 @@ export function useHosts() {
|
||||
const subscribe = useCallback((callback: () => void) => control.hosts.subscribe(callback), [control]);
|
||||
return useSyncExternalStore(subscribe, () => control.hosts.getSnapshot());
|
||||
}
|
||||
|
||||
/** Requests from host installers waiting to be approved, empty if the account may not approve hosts */
|
||||
export function useHostPairings() {
|
||||
const control = useContext(ControlContext);
|
||||
const account = useAccount();
|
||||
const permitted = Boolean(account.hasPermission("core.host.approve"));
|
||||
const subscribe = useCallback(
|
||||
(callback: () => void) => (permitted ? control.hostPairings.subscribe(callback) : () => {}),
|
||||
[control, permitted],
|
||||
);
|
||||
return useSyncExternalStore(subscribe, () => control.hostPairings.getSnapshot());
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
/**
|
||||
* Subscriber for the requests from host installers waiting to be approved
|
||||
*
|
||||
* Only accounts that may approve hosts can subscribe to the requests, so
|
||||
* this does not resubscribe on connect or account changes for other
|
||||
* accounts, which would fail with a permission error. The requests only
|
||||
* live in the controller's memory and it does not tell a new session about
|
||||
* requests removed before it started, so the requests are cleared when a
|
||||
* new session starts and fetched again. The same applies to requests removed
|
||||
* while nothing was subscribed, so they are also cleared when subscribing
|
||||
* again after the last handler unsubscribed.
|
||||
*/
|
||||
export class HostPairingSubscriber extends lib.MapSubscriber<lib.HostPairingUpdatesEvent> {
|
||||
private _permitted: () => boolean;
|
||||
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);
|
||||
this._permitted = permitted;
|
||||
}
|
||||
|
||||
override handleConnectionEvent(event: "connect" | "drop" | "resume" | "close") {
|
||||
if (event === "connect") {
|
||||
this.values.clear();
|
||||
this.lastUpdatedMs = -1;
|
||||
}
|
||||
if (event === "connect" || event === "resume") {
|
||||
// The account of a new session is reported after the connect event.
|
||||
queueMicrotask(() => {
|
||||
if (this._permitted()) {
|
||||
super.handleConnectionEvent(event);
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
super.handleConnectionEvent(event);
|
||||
}
|
||||
|
||||
override handleAccountEvent() {
|
||||
if (this._permitted()) {
|
||||
super.handleAccountEvent();
|
||||
}
|
||||
}
|
||||
|
||||
override subscribe(handler: lib.EventSubscriberCallback<lib.HostPairingUpdatesEvent>) {
|
||||
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;
|
||||
});
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user