mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-18 07:33:12 +09:00
Merge remote-tracking branch 'origin/master' into fix/headless-export-icons
This commit is contained in:
114 files changed
+5338
-1165
No files matched your search
@@ -23,13 +23,14 @@ import util from "util";
|
||||
import winston from "winston";
|
||||
import DailyRotateFile from "winston-daily-rotate-file";
|
||||
|
||||
import jwt from "jsonwebtoken";
|
||||
|
||||
// homebrew modules
|
||||
// Reduce startup time by lazy compiling schemas.
|
||||
import "./src/set_lazy_schema_compilation.js";
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { ConsoleTransport, levels, logger } from "@clusterio/lib";
|
||||
|
||||
import Controller from "./src/Controller.js";
|
||||
import type Controller from "./src/Controller.js";
|
||||
import UserManager from "./src/UserManager.js";
|
||||
import UserRecord from "./src/UserRecord.js";
|
||||
import packageConfig from "@clusterio/controller/package.json" with { type: "json" };
|
||||
@@ -186,14 +187,6 @@ async function handleBootstrapCommand(
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(userManager.signUserToken(user));
|
||||
|
||||
} else if (subCommand === "generate-host-token") {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(jwt.sign(
|
||||
{ aud: "host", host: args.id },
|
||||
// Auth secret is never null after startup
|
||||
Buffer.from(controllerConfig.get("controller.auth_secret")!, "base64")
|
||||
));
|
||||
|
||||
} else if (subCommand === "create-ctl-config") {
|
||||
let admin = userManager.getByName(args.name);
|
||||
if (!admin) {
|
||||
@@ -203,6 +196,7 @@ async function handleBootstrapCommand(
|
||||
}
|
||||
let ctlConfig = new lib.CtlConfig("control");
|
||||
|
||||
const { default: Controller } = await import("./src/Controller.js");
|
||||
ctlConfig.set("ctl.controller_url", Controller.calculateControllerUrl(controllerConfig));
|
||||
ctlConfig.set(
|
||||
"ctl.controller_token",
|
||||
@@ -322,9 +316,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",
|
||||
@@ -475,6 +466,8 @@ async function startup() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Loaded here as the server is not needed by the other commands
|
||||
const { default: Controller } = await import("./src/Controller.js");
|
||||
controller = await Controller.fromConfig(
|
||||
controllerConfig,
|
||||
pluginInfos,
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
"clusteriocontroller": "./dist/node/controller.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
"node": "^22.18.0 || >=24.2.0"
|
||||
},
|
||||
|
||||
"dependencies": {
|
||||
|
||||
@@ -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,48 @@ 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);
|
||||
this._controller.hosts.delete(host);
|
||||
this._controller.deleteNote("host", request.hostId, this.user.name);
|
||||
const system = this._controller.systems.getMutable(request.hostId);
|
||||
if (system) {
|
||||
this._controller.systems.delete(system);
|
||||
}
|
||||
|
||||
// Disconnected first so unassigning the instances does not depend on the host responding.
|
||||
const hostConnection = this._controller.wsServer.hostConnections.get(request.hostId);
|
||||
if (hostConnection) {
|
||||
hostConnection.connector.terminate();
|
||||
}
|
||||
|
||||
this._controller.hosts.set(host);
|
||||
const assigned = [...this._controller.instances.values()].filter(
|
||||
instance => instance.config.get("instance.assigned_host") === request.hostId
|
||||
);
|
||||
for (const instance of assigned) {
|
||||
await this._controller.instances.unassignInstance(instance.id);
|
||||
}
|
||||
logger.audit(`User ${this.user.name} revoked host ${host.name} (${host.id})`);
|
||||
}
|
||||
|
||||
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.records.values()];
|
||||
}
|
||||
|
||||
async handleHostConfigCreateRequest(request: lib.HostConfigCreateRequest) {
|
||||
const hostConfig = new lib.HostConfig("host");
|
||||
async handleHostPairingApproveRequest(request: lib.HostPairingApproveRequest) {
|
||||
return this._controller.hostPairing.approve(request.code, request.name, this.user.name);
|
||||
}
|
||||
|
||||
hostConfig.set("host.controller_url", this._controller.getControllerUrl());
|
||||
if (request.id !== undefined) {
|
||||
hostConfig.set("host.id", request.id);
|
||||
}
|
||||
if (request.name !== undefined) {
|
||||
hostConfig.set("host.name", request.name);
|
||||
}
|
||||
if (request.generateToken) {
|
||||
this.user.checkPermission("core.host.generate_token");
|
||||
hostConfig.set("host.controller_token", this._controller.generateHostToken(hostConfig.get("host.id")));
|
||||
}
|
||||
return hostConfig.toJSON();
|
||||
async handleHostPairingRejectRequest(request: lib.HostPairingRejectRequest) {
|
||||
this._controller.hostPairing.reject(request.code, this.user.name);
|
||||
}
|
||||
|
||||
async handleInstanceDetailsGetRequest(request: lib.InstanceDetailsGetRequest) {
|
||||
|
||||
@@ -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 hosts 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.records.on("update", this.hostPairingRequestsUpdated.bind(this));
|
||||
this.instances.records.on("update", this.instanceUpdated.bind(this));
|
||||
this.saves.on("update", this.savesUpdated.bind(this));
|
||||
this.modPacks.on("update", this.modPacksUpdated.bind(this));
|
||||
@@ -420,7 +426,7 @@ export default class Controller {
|
||||
this.app.use(this.devServer.middlewares);
|
||||
}
|
||||
|
||||
if (!args.dev) {
|
||||
if (!this.devServer) {
|
||||
let manifestPath = path.join(import.meta.dirname, "..", "..", "web", "manifest.json");
|
||||
|
||||
let manifest = await Controller.loadJsonObject(manifestPath);
|
||||
@@ -489,6 +495,7 @@ export default class Controller {
|
||||
logger.info(`Listening for HTTPS on port ${(this.httpsServer.address() as AddressInfo).port}`);
|
||||
}
|
||||
|
||||
this.hostPairing.start();
|
||||
this.onAutosaveIntervalChanged();
|
||||
this.onSystemMetricsIntervalChanged();
|
||||
|
||||
@@ -527,14 +534,14 @@ export default class Controller {
|
||||
},
|
||||
plugins: [webUiVite.clusterioDevPlugins(pluginDirs)],
|
||||
});
|
||||
if (args.dev) {
|
||||
this.app.locals.webBundle = {
|
||||
main: this.devServer.config.plugins.find(p => p.name === "clusterio:app")!.api.entry,
|
||||
imports: Object.fromEntries(webUiVite.sharedModules.map(
|
||||
name => [name, webUiVite.devSharedUrl(name)]
|
||||
)),
|
||||
};
|
||||
}
|
||||
// Plugins served from source import the shared modules from the development server, the web
|
||||
// interface has to use the same copies, so it is served from source as well with --dev-plugin.
|
||||
this.app.locals.webBundle = {
|
||||
main: this.devServer.config.plugins.find(p => p.name === "clusterio:app")!.api.entry,
|
||||
imports: Object.fromEntries(webUiVite.sharedModules.map(
|
||||
name => [name, webUiVite.devSharedUrl(name)]
|
||||
)),
|
||||
};
|
||||
this.app.locals.devServer = this.devServer;
|
||||
}
|
||||
|
||||
@@ -582,6 +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);
|
||||
});
|
||||
}
|
||||
@@ -1012,11 +1025,49 @@ export default class Controller {
|
||||
return jwt.sign({ aud: "host", host: hostId }, this.authSecret);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check a host token
|
||||
*
|
||||
* @param token - Host token to check.
|
||||
* @returns ID of the host the token was issued to.
|
||||
* @throws if the token is invalid, its host is not registered or it was issued before tokenValidAfter.
|
||||
*/
|
||||
verifyHostToken(token: string): number {
|
||||
// migrate: allow pre-rename tokens issued to hosts before alpha-14
|
||||
const payload = jwt.verify(token, this.authSecret, { audience: ["host", "slave"] });
|
||||
if (typeof payload === "string") {
|
||||
throw new Error("unexpected JsonWebToken type");
|
||||
}
|
||||
const hostId = payload.host !== undefined ? payload.host : payload.slave;
|
||||
const host = this.hosts.get(hostId);
|
||||
if (!host) {
|
||||
throw new Error("host is not registered, start the host again to request to join the cluster");
|
||||
}
|
||||
if (!payload.iat || payload.iat < host.tokenValidAfter) {
|
||||
throw new Error("invalid token");
|
||||
}
|
||||
return hostId;
|
||||
}
|
||||
|
||||
hostsUpdated(hosts: HostRecord[]) {
|
||||
let updates = hosts.map(host => host.toHostDetails());
|
||||
this.subscriptions.broadcast(new lib.HostUpdatesEvent(updates));
|
||||
}
|
||||
|
||||
hostPairingRequestsUpdated(requests: lib.HostPairingDetails[]) {
|
||||
this.subscriptions.broadcast(new lib.HostPairingUpdatesEvent(requests));
|
||||
}
|
||||
|
||||
async handleHostPairingSubscription(request: lib.SubscriptionRequest) {
|
||||
if (request.action === "unsubscribe") {
|
||||
return null;
|
||||
}
|
||||
const requests = [...this.hostPairing.records.values()].filter(
|
||||
pairing => pairing.updatedAtMs > request.lastRequestTimeMs,
|
||||
);
|
||||
return requests.length ? new lib.HostPairingUpdatesEvent(requests) : null;
|
||||
}
|
||||
|
||||
async handleHostSubscription(request: lib.SubscriptionRequest) {
|
||||
if (request.action === "unsubscribe") {
|
||||
return null;
|
||||
|
||||
@@ -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,319 @@
|
||||
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 host */
|
||||
export const pollTimeoutMs = 30e3;
|
||||
/** Maximum number of pending requests from one address */
|
||||
export const maxPendingPerAddress = 3;
|
||||
/** Maximum length of a host name */
|
||||
export const maxNameLength = 100;
|
||||
/** Control and bidirectional override characters refused in host names */
|
||||
const nameControlCharacters = /[\p{Cc}\u202a-\u202e\u2066-\u2069]/u;
|
||||
|
||||
/** Result of an approved request, sent to the host */
|
||||
export interface HostPairingResult {
|
||||
hostId: number,
|
||||
token: string,
|
||||
name: string,
|
||||
}
|
||||
|
||||
/** Error with an HTTP status code to respond to the host with */
|
||||
export class HostPairingError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
public status: number,
|
||||
/** Seconds to wait before trying again, for status 429 */
|
||||
public retryAfter?: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
type PairingRequest = {
|
||||
/** Secret the host polls with, never shown to users */
|
||||
secret: string,
|
||||
details: lib.HostPairingDetails,
|
||||
/** Address with IPv6 addresses grouped by /64, used for limits */
|
||||
addressKey: string,
|
||||
lastPollMs: number,
|
||||
} & (
|
||||
{ state: "pending" | "rejected" } | { state: "approved", result: HostPairingResult }
|
||||
);
|
||||
|
||||
/**
|
||||
* Strips the IPv4 mapped prefix and groups IPv6 addresses by their /64
|
||||
*
|
||||
* @param address - Address to make a key for
|
||||
* @returns key used to count requests from an address.
|
||||
*/
|
||||
export function addressKey(address: string) {
|
||||
if (address.startsWith("::ffff:") && net.isIPv4(address.slice(7))) {
|
||||
return address.slice(7);
|
||||
}
|
||||
if (!net.isIPv6(address)) {
|
||||
return address;
|
||||
}
|
||||
const [head, tail = ""] = address.split("::");
|
||||
const headParts = head ? head.split(":") : [];
|
||||
const tailParts = tail ? tail.split(":") : [];
|
||||
const missing = 8 - headParts.length - tailParts.length;
|
||||
const parts = address.includes("::")
|
||||
? [...headParts, ...new Array(missing).fill("0"), ...tailParts]
|
||||
: headParts;
|
||||
return `${parts.slice(0, 4).map(part => part.toLowerCase().replace(/^0+(?=.)/, "")).join(":")}::/64`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise a pairing code typed by a user
|
||||
*
|
||||
* @param code - Code as typed, may contain dashes and lower case letters.
|
||||
* @returns code formatted as shown by the host.
|
||||
*/
|
||||
export function normaliseCode(code: string) {
|
||||
const plain = code.toUpperCase().replace(/[^0-9A-Z]/g, "");
|
||||
return `${plain.slice(0, 3)}-${plain.slice(3)}`;
|
||||
}
|
||||
|
||||
function generateCode() {
|
||||
let code = "";
|
||||
for (let i = 0; i < codeLength; i++) {
|
||||
code += codeAlphabet[crypto.randomInt(codeAlphabet.length)];
|
||||
}
|
||||
return normaliseCode(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps track of requests from hosts to join the cluster
|
||||
*
|
||||
* Requests only live in memory, and only while the host keeps polling
|
||||
* for the result.
|
||||
*/
|
||||
export default class HostPairingManager {
|
||||
/** Pending requests by code, broadcast to subscribed control links */
|
||||
records = new lib.SubscribableDatastore<lib.HostPairingDetails>();
|
||||
private _bySecret = new Map<string, PairingRequest>();
|
||||
private _byCode = new Map<string, PairingRequest>();
|
||||
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 a host or a user
|
||||
*
|
||||
* @param name - Name to check.
|
||||
* @returns the trimmed name.
|
||||
*/
|
||||
static validateName(name: unknown) {
|
||||
if (typeof name !== "string" || !name.trim()) {
|
||||
throw new HostPairingError("Host name is required", 400);
|
||||
}
|
||||
const trimmed = name.trim();
|
||||
if (trimmed.length > maxNameLength) {
|
||||
throw new HostPairingError(`Host name must be at most ${maxNameLength} characters`, 400);
|
||||
}
|
||||
// Names come from unauthenticated requests and are printed to terminals and logs.
|
||||
if (nameControlCharacters.test(trimmed)) {
|
||||
throw new HostPairingError("Host name may not contain control characters", 400);
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an approved host with a new id and token
|
||||
*
|
||||
* @param name - Name of the host.
|
||||
* @returns the id, token and name of the new host.
|
||||
*/
|
||||
createHost(name: string): HostPairingResult {
|
||||
const hosts = this._controller.hosts;
|
||||
let hostId;
|
||||
do {
|
||||
hostId = crypto.randomInt(1, 2 ** 31);
|
||||
} while (hosts.has(hostId));
|
||||
|
||||
hosts.set(new HostRecord(
|
||||
hostId, name, "", new Map(), false, "", "", Math.floor(Date.now() / 1000),
|
||||
));
|
||||
return { hostId, token: this._controller.generateHostToken(hostId), name };
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a pending request
|
||||
*
|
||||
* @param name - Name the host asked for.
|
||||
* @param version - Version of the host.
|
||||
* @param remoteAddress - Address the request came from.
|
||||
* @returns the secret to poll with and the code to show the user.
|
||||
*/
|
||||
create(name: string, version: string, remoteAddress: string) {
|
||||
this.prune();
|
||||
const key = addressKey(remoteAddress);
|
||||
const now = Date.now();
|
||||
const pendingFromAddress = [...this._bySecret.values()].filter(
|
||||
request => request.addressKey === key && request.state === "pending"
|
||||
).length;
|
||||
if (pendingFromAddress >= maxPendingPerAddress) {
|
||||
throw new HostPairingError("Too many pending requests from this address", 429, 30);
|
||||
}
|
||||
const maxPending = this._controller.config.get("controller.host_pairing_max_pending");
|
||||
if (maxPending && this.records.size >= maxPending) {
|
||||
throw new HostPairingError("Too many pending requests", 429, 30);
|
||||
}
|
||||
|
||||
let code;
|
||||
do {
|
||||
code = generateCode();
|
||||
} while (this._byCode.has(code));
|
||||
|
||||
const request: PairingRequest = {
|
||||
secret: crypto.randomBytes(32).toString("base64url"),
|
||||
details: new lib.HostPairingDetails(code, name, remoteAddress, version, now),
|
||||
addressKey: key,
|
||||
lastPollMs: now,
|
||||
state: "pending",
|
||||
};
|
||||
this._bySecret.set(request.secret, request);
|
||||
this._byCode.set(code, request);
|
||||
this.records.set(request.details);
|
||||
logger.verbose(`Host pairing request ${code} for "${name}" from ${remoteAddress}`);
|
||||
return { requestId: request.secret, code };
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll for the result of a request
|
||||
*
|
||||
* @param secret - Request id returned when the request was created.
|
||||
* @returns the result if the request was approved, or null if still pending.
|
||||
*/
|
||||
poll(secret: string): HostPairingResult | null {
|
||||
this.prune();
|
||||
const request = this._bySecret.get(secret);
|
||||
if (!request) {
|
||||
throw new HostPairingError("Request not found", 404);
|
||||
}
|
||||
request.lastPollMs = Date.now();
|
||||
if (request.state === "approved") {
|
||||
this._remove(request);
|
||||
return request.result;
|
||||
}
|
||||
if (request.state === "rejected") {
|
||||
this._remove(request);
|
||||
throw new HostPairingError("Request was rejected", 403);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel a pending request
|
||||
*
|
||||
* @param secret - Request id returned when the request was created.
|
||||
*/
|
||||
cancel(secret: string) {
|
||||
const request = this._bySecret.get(secret);
|
||||
if (request && request.state === "pending") {
|
||||
logger.verbose(`Host pairing request ${request.details.code} cancelled by the host`);
|
||||
this._remove(request);
|
||||
}
|
||||
}
|
||||
|
||||
private _pending(code: string) {
|
||||
this.prune();
|
||||
const request = this._byCode.get(normaliseCode(code));
|
||||
if (!request || request.state !== "pending") {
|
||||
throw new lib.NotFoundError(`No pending host request with code ${code}`);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Approve a pending request, creating the host
|
||||
*
|
||||
* @param code - Code of the request.
|
||||
* @param name - Name to give the host, defaults to the requested name.
|
||||
* @param approvedBy - Name of the user approving it, for logging.
|
||||
* @returns the id of the new host.
|
||||
*/
|
||||
approve(code: string, name: string | undefined, approvedBy: string) {
|
||||
const request = this._pending(code);
|
||||
let hostName;
|
||||
try {
|
||||
hostName = name === undefined ? request.details.name : HostPairingManager.validateName(name);
|
||||
} catch (err: any) {
|
||||
throw new lib.ValidationError(err.message);
|
||||
}
|
||||
|
||||
const result = this.createHost(hostName);
|
||||
Object.assign(request, { state: "approved", result });
|
||||
this.records.delete(request.details);
|
||||
logger.audit(
|
||||
`User ${approvedBy} approved host ${result.name} (${result.hostId}) with code ` +
|
||||
`${request.details.code} from ${request.details.remoteAddress}`
|
||||
);
|
||||
return result.hostId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject a pending request
|
||||
*
|
||||
* @param code - Code of the request.
|
||||
* @param rejectedBy - Name of the user rejecting it, for logging.
|
||||
*/
|
||||
reject(code: string, rejectedBy: string) {
|
||||
const request = this._pending(code);
|
||||
request.state = "rejected";
|
||||
this.records.delete(request.details);
|
||||
logger.audit(
|
||||
`User ${rejectedBy} rejected host ${request.details.name} with code ` +
|
||||
`${request.details.code} from ${request.details.remoteAddress}`
|
||||
);
|
||||
}
|
||||
|
||||
private _remove(request: PairingRequest) {
|
||||
this._bySecret.delete(request.secret);
|
||||
this._byCode.delete(request.details.code);
|
||||
this.records.delete(request.details);
|
||||
}
|
||||
|
||||
/** Remove requests the host stopped polling for or that waited too long */
|
||||
prune() {
|
||||
const now = Date.now();
|
||||
const timeoutMs = this._controller.config.get("controller.host_pairing_timeout") * 1000;
|
||||
for (const request of this._bySecret.values()) {
|
||||
const timedOut = request.state === "pending" && timeoutMs > 0
|
||||
&& now - request.details.createdAtMs > timeoutMs;
|
||||
if (!timedOut && now - request.lastPollMs <= pollTimeoutMs) {
|
||||
continue;
|
||||
}
|
||||
if (request.state === "approved") {
|
||||
logger.warn(
|
||||
`Approved host ${request.result.name} (${request.result.hostId}) was never picked up ` +
|
||||
"by the host, revoke it on the hosts page if it is not needed"
|
||||
);
|
||||
}
|
||||
this._remove(request);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -252,21 +252,9 @@ ${err.stack}`
|
||||
}
|
||||
|
||||
try {
|
||||
// migrate: allow pre-rename tokens issued to hosts before alpha-14
|
||||
const tokenPayload = jwt.verify(data.token, this.controller.authSecret, { audience: ["host", "slave"] });
|
||||
if (typeof tokenPayload === "string") {
|
||||
throw new Error("unexpected JsonWebToken type");
|
||||
}
|
||||
|
||||
// migrate: allow pre-rename tokens issued to hosts before alpha-14
|
||||
if ((tokenPayload.host !== undefined ? tokenPayload.host : tokenPayload.slave) !== data.id) {
|
||||
if (this.controller.verifyHostToken(data.token) !== data.id) {
|
||||
throw new Error("missmatched host id");
|
||||
}
|
||||
|
||||
let host = this.controller.hosts.get(data.id);
|
||||
if (!tokenPayload.iat || tokenPayload.iat < (host?.tokenValidAfter ?? 0)) {
|
||||
throw new Error("invalid token");
|
||||
}
|
||||
} catch (err: any) {
|
||||
logger.verbose(`WsServer | authentication failed for ${this.remoteAddr(req)}`);
|
||||
wsRejectedConnectionsCounter.inc();
|
||||
@@ -303,6 +291,13 @@ ${err.stack}`
|
||||
);
|
||||
}
|
||||
|
||||
// The host may have been revoked while waiting for the old connection to close.
|
||||
if (!this.controller.hosts.has(data.id)) {
|
||||
wsRejectedConnectionsCounter.inc();
|
||||
socket.close(lib.ConnectionClosed.Unauthorized, "Authentication failed: host was revoked");
|
||||
return;
|
||||
}
|
||||
|
||||
let [connector, sessionToken] = this.createSession(new lib.Address(lib.Address.host, data.id));
|
||||
|
||||
// Handle close before HostConnection does. This avoids a host
|
||||
|
||||
@@ -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";
|
||||
@@ -188,17 +189,7 @@ function validateHostToken(req: Request, res: Response, next: any) {
|
||||
}
|
||||
|
||||
try {
|
||||
const tokenPayload = jwt.verify(token, req.app.locals.controller.authSecret, { audience: "host" });
|
||||
if (typeof tokenPayload === "string") {
|
||||
throw new Error("unexpected JsonWebToken type");
|
||||
}
|
||||
let host = req.app.locals.controller.hosts.get(tokenPayload.host);
|
||||
if (!host) {
|
||||
throw new Error("invalid host");
|
||||
}
|
||||
if (!tokenPayload.iat || tokenPayload.iat < (host.tokenValidAfter ?? 0)) {
|
||||
throw new Error("invalid token");
|
||||
}
|
||||
req.app.locals.controller.verifyHostToken(token);
|
||||
} catch (err) {
|
||||
res.sendStatus(401);
|
||||
return;
|
||||
@@ -215,19 +206,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 +215,121 @@ 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 a host for a host to join the cluster.
|
||||
function createHostPairing(req: Request, res: Response) {
|
||||
if (!checkHostPairingRequest(req, res, false)) {
|
||||
return;
|
||||
}
|
||||
const controller = req.app.locals.controller;
|
||||
const remoteAddress = controller.wsServer.remoteAddr(req);
|
||||
try {
|
||||
const name = HostPairingManager.validateName(req.body?.name);
|
||||
const version = typeof req.body?.version === "string" ? req.body.version.slice(0, 64) : "";
|
||||
|
||||
// A user allowed to approve hosts can skip the wait by passing their token.
|
||||
const token = getAccessToken(req);
|
||||
if (token !== undefined) {
|
||||
let user;
|
||||
try {
|
||||
user = userFromToken(controller, token);
|
||||
} catch (err) {
|
||||
res.status(401).json({ error: "Invalid user token" });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
user.checkPermission("core.host.approve");
|
||||
} catch (err) {
|
||||
logger.audit(
|
||||
`User ${user.name} tried to approve host ${name} from ${remoteAddress} without permission`
|
||||
);
|
||||
res.status(403).json({ error: `User ${user.name} is not allowed to approve hosts` });
|
||||
return;
|
||||
}
|
||||
const result = 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 a host for the result of its request.
|
||||
function pollHostPairing(req: Request, res: Response) {
|
||||
if (!checkHostPairingRequest(req, res, true)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = req.app.locals.controller.hostPairing.poll(req.body.requestId);
|
||||
if (result) {
|
||||
res.status(200).json(result);
|
||||
} else {
|
||||
res.status(202).json({ status: "pending" });
|
||||
}
|
||||
} catch (err) {
|
||||
if (!sendHostPairingError(res, err)) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Cancel from a host that stopped waiting.
|
||||
function cancelHostPairing(req: Request, res: Response) {
|
||||
if (!checkHostPairingRequest(req, res, true)) {
|
||||
return;
|
||||
}
|
||||
req.app.locals.controller.hostPairing.cancel(req.body.requestId);
|
||||
res.sendStatus(204);
|
||||
}
|
||||
|
||||
// Handle an uploaded export package.
|
||||
async function uploadExport(req: Request, res: Response) {
|
||||
if (req.get("Content-Type") !== "application/zip") {
|
||||
@@ -686,6 +780,18 @@ export function addRouteHandlers(app: Application) {
|
||||
);
|
||||
app.get("/api/plugins", getPlugins);
|
||||
app.get("/api/cluster-name", getClusterName);
|
||||
// Set before parsing so errors from the body parser and token check are not cached either.
|
||||
const noStore = (req: Request, res: Response, next: any) => {
|
||||
res.set("Cache-Control", "no-store");
|
||||
next();
|
||||
};
|
||||
const pairingJson = express.json({ limit: "4kb" });
|
||||
app.post("/api/host-pairing", noStore, pairingJson, createHostPairing);
|
||||
app.post("/api/host-pairing/poll", noStore, pairingJson, pollHostPairing);
|
||||
app.post("/api/host-pairing/cancel", noStore, pairingJson, cancelHostPairing);
|
||||
app.get("/api/host-pairing/check", noStore, validateHostToken, (req: Request, res: Response) => {
|
||||
res.json({ valid: true });
|
||||
});
|
||||
app.put("/api/upload-export",
|
||||
validateHostToken,
|
||||
(req:Request, res:Response, next:any) => uploadExport(req, res).catch(next)
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
// This needs to be a separate file due to ECMAScript Modules evaluating code in
|
||||
// imported modules before any code in the file that imports it.
|
||||
(global as any).lazySchemaCompilation = true;
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"entryPoints": ["index.ts"],
|
||||
"includeVersion": true
|
||||
}
|
||||
@@ -4,3 +4,113 @@ Installer for Clusterio.
|
||||
|
||||
Install the latest [Node.js LTS release](https://nodejs.org/en/download) before running the installer.
|
||||
See [the Clusterio installation guide](https://github.com/clusterio/clusterio#installation) for platform-specific instructions.
|
||||
|
||||
Run the installer in a new empty directory:
|
||||
|
||||
npm init "@clusterio"
|
||||
|
||||
It asks which components to install and how to set them up.
|
||||
Every question can be answered with an option instead, pass options to the installer after `--`:
|
||||
|
||||
npm init "@clusterio" -- --mode host --host-name my-host --controller-url https://example.com/
|
||||
|
||||
The installer runs without prompts when all the questions for the mode are answered with options.
|
||||
|
||||
|
||||
## Modes
|
||||
|
||||
- `standalone`: controller and host on this computer. The host is approved like any other host the first time it starts.
|
||||
- `controller`: controller only.
|
||||
- `host`: host only, joins the cluster of an existing controller, see [Setting up a host](#setting-up-a-host).
|
||||
- `ctl`: the clusterioctl command line interface only.
|
||||
- `plugins`: plugins only, for adding plugins to an existing installation.
|
||||
- `plugin-template`: files for writing a new plugin.
|
||||
|
||||
|
||||
## Options
|
||||
|
||||
| Option | Modes | Description |
|
||||
| --- | --- | --- |
|
||||
| `--mode <mode>` | all | Operating mode to install. |
|
||||
| `--admin <name>` | controller | Name of the admin account to create. |
|
||||
| `--http-port <port>` | 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>` | ctl | Authentication token saved for clusterioctl. |
|
||||
| `--public-address <address>` | host | DNS name or IP address players connect to this computer with. |
|
||||
| `--factorio-dir <path>` | host | Path to the Factorio installation. |
|
||||
| `--self-signed-cert <path>` | host | Certificate to trust for a controller using a self-signed certificate. It is added to the run scripts. |
|
||||
| `--remote-npm`, `--no-remote-npm` | controller, host | Allow or deny remote updates, plugin updates and plugin installs from the web interface. |
|
||||
| `--plugins <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. |
|
||||
|
||||
Options for the `controller` and `host` modes also work in the `standalone` mode, except for `--controller-url` as the host connects to the controller on the same computer.
|
||||
`--host-name` defaults to `local` in the `standalone` mode.
|
||||
|
||||
|
||||
## Setting up a host
|
||||
|
||||
A new host has to be approved before it can join the cluster:
|
||||
|
||||
1. Run the installer with the host mode on the computer for the host.
|
||||
It asks for a name for the host, the controller URL, the public address, the Factorio installation, whether to allow remote updates and which plugins to install.
|
||||
|
||||
2. Start the host with `run-host.cmd`, `run-host.sh` or the systemd service in the `systemd` folder.
|
||||
The first time it starts it prints a code and waits for the host to be approved:
|
||||
|
||||
Waiting for approval of "my-host" with code ABC-DEF, open this link to approve it:
|
||||
https://example.com/hosts?approve=ABC-DEF
|
||||
Or run: npx clusterioctl host approve ABC-DEF
|
||||
|
||||
3. Open the link to approve the request in the web interface, where its name can be changed first.
|
||||
It can also be approved under Add host on the Hosts page, or with `npx clusterioctl host approve ABC-DEF`.
|
||||
Only approve a request if its code matches the one shown by the host.
|
||||
Approving requires the `core.host.approve` permission.
|
||||
|
||||
4. The host saves `host.id`, `host.name` and `host.controller_token` to `config-host.json` and starts up.
|
||||
Later starts connect to the cluster straight away.
|
||||
|
||||
The host keeps waiting until the request is approved, also if the controller is restarted or can't be reached for a while.
|
||||
Press Ctrl+C to stop waiting.
|
||||
If the request is rejected the host exits with code 8, which the run scripts do not restart on.
|
||||
|
||||
Start the host with `npx clusteriohost run --user-token <token>` and the token of a user that has the `core.host.approve` permission to approve the host without waiting.
|
||||
The token is only used for approving the host and is not saved.
|
||||
|
||||
If the controller uses a self-signed certificate pass it with `--self-signed-cert <path>`, see [setting up TLS](https://github.com/clusterio/clusterio/blob/master/docs/setting-up-tls.md#creating-and-using-a-self-signed-certificate).
|
||||
The installer adds it to the run scripts.
|
||||
|
||||
When a host is revoked in the web interface or with `npx clusterioctl host revoke <host>` its token stops working and a running host shuts down.
|
||||
Starting it again requests to join the cluster again, and the host gets a new id once approved.
|
||||
|
||||
To move a host to another controller, change `host.controller_url` with `npx clusteriohost config set host.controller_url <url>`.
|
||||
The new controller does not accept the token of the host, so the host requests to join it the next time it starts.
|
||||
|
||||
|
||||
## Docker
|
||||
|
||||
To run a host in a container install it when building the image with all answers given as options.
|
||||
The host requests to join the cluster the first time the container starts.
|
||||
|
||||
```dockerfile
|
||||
FROM node:22
|
||||
# Install the Factorio headless server to /opt/factorio here
|
||||
RUN mkdir /clusterio && chown node:node /clusterio
|
||||
USER node
|
||||
WORKDIR /clusterio
|
||||
RUN npm init "@clusterio" -- --mode host --host-name my-host --controller-url https://example.com/ \
|
||||
--public-address factorio.example.com --factorio-dir /opt/factorio --no-remote-npm --plugins
|
||||
VOLUME /clusterio
|
||||
CMD exec ./node_modules/.bin/clusteriohost run ${USER_TOKEN:+--user-token "$USER_TOKEN"}
|
||||
```
|
||||
|
||||
docker run -d --name my-host -v my-host:/clusterio -p 34100-34199:34100-34199/udp my-host-image
|
||||
docker logs my-host
|
||||
|
||||
- The volume holds `config-host.json`, without it every new container requests to join as a new host.
|
||||
Docker copies the installation from the image into a new empty volume, later image updates do not change the installation in an existing volume.
|
||||
- The code to approve is printed to the container log, or set `USER_TOKEN` to approve the host without waiting.
|
||||
- Stop the container after revoking its host, otherwise a restart requests to join again.
|
||||
+167
-188
@@ -1,10 +1,14 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import checkbox from "@inquirer/checkbox";
|
||||
import confirm from "@inquirer/confirm";
|
||||
import input from "@inquirer/input";
|
||||
import select from "@inquirer/select";
|
||||
import child_process from "node:child_process";
|
||||
import fs from "node:fs/promises";
|
||||
import inquirer from "inquirer";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import readline from "node:readline";
|
||||
import stream from "node:stream";
|
||||
import util from "node:util";
|
||||
import yargs from "yargs";
|
||||
@@ -16,15 +20,13 @@ const scriptExt = process.platform === "win32" ? ".cmd" : "";
|
||||
import { escapeArg } from "./escape_arg.js";
|
||||
|
||||
// I hate this, there is a bug with rl.close on windows that was meant to have been fixed in Node14.4
|
||||
// See nodejs/node#21771 and nodejs/node#30701 for the apparent fix that was applied
|
||||
// One option is to not call rl.close: SBoudrias/Inquirer.js#767
|
||||
// But this comes with its own issues: SBoudrias/Inquirer.js#899
|
||||
// See nodejs/node#21771, nodejs/node#30701 and nodejs/node#31762
|
||||
// The solution below was adapted from aws-amplify/amplify-cli#12347
|
||||
if (process.platform === "win32") {
|
||||
const _inquirer_close = inquirer.ui.Prompt.prototype.close;
|
||||
inquirer.ui.Prompt.prototype.close = function() {
|
||||
this.rl.terminal = false;
|
||||
_inquirer_close.call(this);
|
||||
const close = readline.Interface.prototype.close;
|
||||
readline.Interface.prototype.close = function() {
|
||||
this.terminal = false;
|
||||
close.call(this);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -161,21 +163,48 @@ async function execCtl(args) {
|
||||
return await execFile(path.join("node_modules", ".bin", `clusterioctl${scriptExt}`), args);
|
||||
}
|
||||
|
||||
function validateHostToken(token) {
|
||||
let parts = token.split(".");
|
||||
if (parts.length !== 3) {
|
||||
throw new InstallError("Invalid token");
|
||||
}
|
||||
// Same characters as the controller refuses in host names.
|
||||
const hostNameControlCharacters = /[\p{Cc}\u202a-\u202e\u2066-\u2069]/u;
|
||||
|
||||
let parsed;
|
||||
function validateHostName(value) {
|
||||
if (!value || !value.trim()) {
|
||||
return "Host name may not be empty";
|
||||
}
|
||||
if (value.trim().length > 100) {
|
||||
return "Host name may be at most 100 characters";
|
||||
}
|
||||
if (hostNameControlCharacters.test(value)) {
|
||||
return "Host name may not contain control characters";
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function validateControllerUrl(value) {
|
||||
let url;
|
||||
try {
|
||||
parsed = JSON.parse(Buffer.from(parts[1], "base64"));
|
||||
url = new URL(value);
|
||||
} catch (err) {
|
||||
throw new InstallError("Invalid token");
|
||||
return "Controller URL must be a URL like https://example.com/";
|
||||
}
|
||||
if (!["http:", "https:"].includes(url.protocol)) {
|
||||
return "Controller URL must start with http:// or https://";
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (parsed.aud !== "host" || !Number.isInteger(parsed.host)) {
|
||||
throw new InstallError("Invalid token");
|
||||
// The host requires the controller URL to end with a slash.
|
||||
function normaliseControllerUrl(value) {
|
||||
const url = new URL(value);
|
||||
if (!url.pathname.endsWith("/")) {
|
||||
url.pathname += "/";
|
||||
}
|
||||
return url.href;
|
||||
}
|
||||
|
||||
// Remote updates, plugin updates and plugin installs are allowed or denied together.
|
||||
async function setRemoteUpdates(exec, component, allow) {
|
||||
for (let field of ["allow_remote_updates", "allow_plugin_updates", "allow_plugin_install"]) {
|
||||
await exec(["config", "set", `${component}.${field}`, allow]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -510,96 +539,87 @@ WantedBy=multi-user.target
|
||||
}
|
||||
|
||||
// eslint-disable-next-line complexity
|
||||
async function inquirerMissingArgs(args) {
|
||||
async function promptMissingArgs(args) {
|
||||
let answers = {};
|
||||
if (args.mode) { answers.mode = args.mode; }
|
||||
if (args["plugin-template"]) { answers.mode = "plugin-template"; }
|
||||
answers = await inquirer.prompt([
|
||||
{
|
||||
type: "list",
|
||||
name: "mode",
|
||||
message: "Operating mode to install",
|
||||
default: "standalone",
|
||||
choices: [
|
||||
{ name: "Standalone (install both controller and host on this computer)", value: "standalone" },
|
||||
{ name: "Controller only", value: "controller" },
|
||||
{ name: "Host only", value: "host" },
|
||||
{ name: "Ctl only", value: "ctl" },
|
||||
{ name: "Plugins only", value: "plugins" },
|
||||
{ name: "Plugin template", value: "plugin-template" },
|
||||
],
|
||||
},
|
||||
], answers);
|
||||
answers.mode ??= await select({
|
||||
message: "Operating mode to install",
|
||||
default: "standalone",
|
||||
choices: [
|
||||
{ name: "Standalone (install both controller and host on this computer)", value: "standalone" },
|
||||
{ name: "Controller only", value: "controller" },
|
||||
{ name: "Host only", value: "host" },
|
||||
{ name: "Ctl only", value: "ctl" },
|
||||
{ name: "Plugins only", value: "plugins" },
|
||||
{ name: "Plugin template", value: "plugin-template" },
|
||||
],
|
||||
});
|
||||
|
||||
if (["standalone", "controller"].includes(answers.mode)) {
|
||||
if (args.admin) { answers.admin = args.admin; }
|
||||
answers = await inquirer.prompt([
|
||||
{
|
||||
type: "input",
|
||||
name: "admin",
|
||||
message: "Admin account name",
|
||||
validate: input => {
|
||||
if (!input) {
|
||||
return "May not be empty";
|
||||
}
|
||||
return true;
|
||||
},
|
||||
answers.admin ??= await input({
|
||||
message: "Admin account name",
|
||||
validate: value => {
|
||||
if (!value) {
|
||||
return "May not be empty";
|
||||
}
|
||||
return true;
|
||||
},
|
||||
], answers);
|
||||
});
|
||||
|
||||
if (args.httpPort) { answers.httpPort = args.httpPort; }
|
||||
answers = await inquirer.prompt([
|
||||
{
|
||||
type: "input",
|
||||
name: "httpPort",
|
||||
message: "HTTP port to listen on",
|
||||
default: 8080,
|
||||
validate: input => {
|
||||
if (!input) {
|
||||
return "May not be empty";
|
||||
}
|
||||
if (!Number.isInteger(Number(input))) {
|
||||
return "Must be a number";
|
||||
}
|
||||
return true;
|
||||
},
|
||||
answers.httpPort ??= await input({
|
||||
message: "HTTP port to listen on",
|
||||
default: "8080",
|
||||
validate: value => {
|
||||
if (!value) {
|
||||
return "May not be empty";
|
||||
}
|
||||
if (!Number.isInteger(Number(value))) {
|
||||
return "Must be a number";
|
||||
}
|
||||
return true;
|
||||
},
|
||||
], answers);
|
||||
});
|
||||
}
|
||||
|
||||
if (answers.mode === "standalone") {
|
||||
answers.hostName = args.hostName ?? "local";
|
||||
const result = validateHostName(answers.hostName);
|
||||
if (result !== true) {
|
||||
throw new InstallError(result);
|
||||
}
|
||||
}
|
||||
|
||||
if (answers.mode === "host") {
|
||||
if (args.hostName) { answers.hostName = args.hostName; }
|
||||
answers = await inquirer.prompt([
|
||||
{
|
||||
type: "input",
|
||||
name: "hostName",
|
||||
message: "Name of host",
|
||||
},
|
||||
], answers);
|
||||
if (args.controllerUrl) { answers.controllerUrl = args.controllerUrl; }
|
||||
answers.hostName ??= await input({
|
||||
message: "Name of host",
|
||||
default: os.hostname(),
|
||||
validate: validateHostName,
|
||||
});
|
||||
answers.controllerUrl ??= await input({
|
||||
message: "Controller URL",
|
||||
validate: validateControllerUrl,
|
||||
});
|
||||
|
||||
// The prompts do not validate answers given as arguments
|
||||
for (let result of [validateHostName(answers.hostName), validateControllerUrl(answers.controllerUrl)]) {
|
||||
if (result !== true) {
|
||||
throw new InstallError(result);
|
||||
}
|
||||
}
|
||||
answers.controllerUrl = normaliseControllerUrl(answers.controllerUrl);
|
||||
}
|
||||
|
||||
if (["host", "ctl"].includes(answers.mode)) {
|
||||
if (answers.mode === "ctl") {
|
||||
if (args.controllerUrl) { answers.controllerUrl = args.controllerUrl; }
|
||||
answers = await inquirer.prompt([
|
||||
{
|
||||
type: "input",
|
||||
name: "controllerUrl",
|
||||
message: "Controller URL",
|
||||
},
|
||||
], answers);
|
||||
answers.controllerUrl ??= await input({ message: "Controller URL" });
|
||||
|
||||
if (args.controllerToken) { answers.controllerToken = args.controllerToken; }
|
||||
answers = await inquirer.prompt([
|
||||
{
|
||||
type: "input",
|
||||
name: "controllerToken",
|
||||
message: "Controller authentication Token",
|
||||
},
|
||||
], answers);
|
||||
}
|
||||
|
||||
if (answers.mode === "host") {
|
||||
validateHostToken(answers.controllerToken);
|
||||
answers.controllerToken ??= await input({ message: "Controller authentication Token" });
|
||||
}
|
||||
|
||||
if (["standalone", "host"].includes(answers.mode)) {
|
||||
@@ -612,14 +632,10 @@ async function inquirerMissingArgs(args) {
|
||||
myIp = await result.text();
|
||||
} catch (err) { /* ignore */ }
|
||||
}
|
||||
answers = await inquirer.prompt([
|
||||
{
|
||||
type: "input",
|
||||
name: "publicAddress",
|
||||
message: "Public DNS/IP address of this server",
|
||||
default: myIp,
|
||||
},
|
||||
], answers);
|
||||
answers.publicAddress ??= await input({
|
||||
message: "Public DNS/IP address of this server",
|
||||
default: myIp,
|
||||
});
|
||||
|
||||
if (args.factorioDir) { answers.factorioDir = args.factorioDir; }
|
||||
let locations = factorioLocations[process.platform] || [];
|
||||
@@ -630,28 +646,17 @@ async function inquirerMissingArgs(args) {
|
||||
}
|
||||
}
|
||||
|
||||
answers = await inquirer.prompt([
|
||||
{
|
||||
type: "list",
|
||||
name: "factorioDir",
|
||||
message: "Path to Factorio installation",
|
||||
choices: [
|
||||
...foundLocations.map(location => ({ name: `${location} (auto detected)`, value: location })),
|
||||
{ name: "Use local factorio directory, you must copy an installation to it", value: "factorio" },
|
||||
{ name: "Provide path manually", value: null },
|
||||
],
|
||||
},
|
||||
], answers);
|
||||
answers.factorioDir ??= await select({
|
||||
message: "Path to Factorio installation",
|
||||
choices: [
|
||||
...foundLocations.map(location => ({ name: `${location} (auto detected)`, value: location })),
|
||||
{ name: "Use local factorio directory, you must copy an installation to it", value: "factorio" },
|
||||
{ name: "Provide path manually", value: null },
|
||||
],
|
||||
});
|
||||
|
||||
if (answers.factorioDir === null) {
|
||||
answers = await inquirer.prompt([
|
||||
{
|
||||
type: "input",
|
||||
name: "factorioDir",
|
||||
message: "Path to Factorio installation",
|
||||
askAnswered: true,
|
||||
},
|
||||
], answers);
|
||||
answers.factorioDir = await input({ message: "Path to Factorio installation" });
|
||||
} else if (answers.factorioDir === "factorio") {
|
||||
await fs.mkdir("factorio", { recursive: true });
|
||||
}
|
||||
@@ -659,14 +664,10 @@ async function inquirerMissingArgs(args) {
|
||||
|
||||
if (["standalone", "controller", "host"].includes(answers.mode)) {
|
||||
if (args.hasOwnProperty("remoteNpm")) { answers.remoteNpm = args.remoteNpm; }
|
||||
answers = await inquirer.prompt([
|
||||
{
|
||||
type: "confirm",
|
||||
name: "remoteNpm",
|
||||
message: "Allow remote updates via npm?",
|
||||
default: true,
|
||||
},
|
||||
], answers);
|
||||
answers.remoteNpm ??= await confirm({
|
||||
message: "Allow remote updates and plugin installs from the web interface?",
|
||||
default: true,
|
||||
});
|
||||
}
|
||||
|
||||
if (answers.mode === "plugin-template") {
|
||||
@@ -677,29 +678,23 @@ async function inquirerMissingArgs(args) {
|
||||
answers.pluginName = args["plugin-name"];
|
||||
}
|
||||
answers.plugins = [];
|
||||
answers = await inquirer.prompt([
|
||||
{
|
||||
type: "checkbox",
|
||||
name: "pluginTemplate",
|
||||
message: "Plugin templates to use",
|
||||
choices: [
|
||||
{ name: "Controller", value: "controller" },
|
||||
{ name: "Host", value: "host" },
|
||||
{ name: "Instance", value: "instance" },
|
||||
{ name: "Lua Module", value: "module" },
|
||||
{ name: "Command Line", value: "ctl" },
|
||||
{ name: "Web UI", value: "web" },
|
||||
{ name: "No Typescript", value: "js" },
|
||||
{ name: "No Config", value: "no_config" },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: "input",
|
||||
name: "pluginName",
|
||||
message: "Name of your new plugin",
|
||||
default: path.basename(path.resolve()),
|
||||
},
|
||||
], answers);
|
||||
answers.pluginTemplate ??= await checkbox({
|
||||
message: "Plugin templates to use",
|
||||
choices: [
|
||||
{ name: "Controller", value: "controller" },
|
||||
{ name: "Host", value: "host" },
|
||||
{ name: "Instance", value: "instance" },
|
||||
{ name: "Lua Module", value: "module" },
|
||||
{ name: "Command Line", value: "ctl" },
|
||||
{ name: "Web UI", value: "web" },
|
||||
{ name: "No Typescript", value: "js" },
|
||||
{ name: "No Config", value: "no_config" },
|
||||
],
|
||||
});
|
||||
answers.pluginName ??= await input({
|
||||
message: "Name of your new plugin",
|
||||
default: path.basename(path.resolve()),
|
||||
});
|
||||
}
|
||||
|
||||
if (dev) {
|
||||
@@ -707,15 +702,11 @@ async function inquirerMissingArgs(args) {
|
||||
} else if (args.plugins) {
|
||||
answers.plugins = args.plugins;
|
||||
}
|
||||
answers = await inquirer.prompt([
|
||||
{
|
||||
type: "checkbox",
|
||||
name: "plugins",
|
||||
message: "Plugins to install",
|
||||
choices: availablePlugins,
|
||||
pageSize: 20,
|
||||
},
|
||||
], answers);
|
||||
answers.plugins ??= await checkbox({
|
||||
message: "Plugins to install",
|
||||
choices: availablePlugins,
|
||||
pageSize: 20,
|
||||
});
|
||||
|
||||
return answers;
|
||||
}
|
||||
@@ -743,13 +734,13 @@ async function main() {
|
||||
nargs: 1, describe: "HTTP port to listen on [standalone/controller]", type: "number",
|
||||
})
|
||||
.option("host-name", {
|
||||
nargs: 1, describe: "Host name [host]", type: "string",
|
||||
nargs: 1, describe: "Host name [standalone/host]", type: "string",
|
||||
})
|
||||
.option("controller-url", {
|
||||
nargs: 1, describe: "Controller URL [host/ctl]", type: "string",
|
||||
})
|
||||
.option("controller-token", {
|
||||
nargs: 1, describe: "Controller authentication token [host/ctl]", type: "string",
|
||||
nargs: 1, describe: "Controller authentication token [ctl]", type: "string",
|
||||
})
|
||||
.option("public-address", {
|
||||
nargs: 1, describe: "DNS/IP Address to connect to this server [standalone/host]", type: "string",
|
||||
@@ -761,7 +752,8 @@ async function main() {
|
||||
nargs: 1, describe: "Path to self-signed certificate of the controller [standalone/host]", type: "string",
|
||||
})
|
||||
.option("remote-npm", {
|
||||
nargs: 0, description: "Allow remote updates via npm [standalone/controller/host]", type: "boolean",
|
||||
nargs: 0, type: "boolean", description:
|
||||
"Allow remote updates and plugin installs from the web interface [standalone/controller/host]",
|
||||
})
|
||||
.option("plugins", {
|
||||
array: true, describe: "Plugins to install", type: "string",
|
||||
@@ -798,7 +790,7 @@ async function main() {
|
||||
return;
|
||||
}
|
||||
|
||||
let answers = await inquirerMissingArgs(args);
|
||||
let answers = await promptMissingArgs(args);
|
||||
logger.verbose(JSON.stringify(answers));
|
||||
|
||||
if (answers.pluginTemplate) {
|
||||
@@ -816,44 +808,28 @@ async function main() {
|
||||
await execController(["config", "create"]);
|
||||
await execController(["bootstrap", "create-admin", answers.admin]);
|
||||
await execController(["config", "set", "controller.http_port", answers.httpPort]);
|
||||
await execController(["config", "set", "controller.allow_remote_updates", answers.remoteNpm]);
|
||||
await execController(["config", "set", "controller.allow_plugin_updates", answers.remoteNpm]);
|
||||
await setRemoteUpdates(execController, "controller", answers.remoteNpm);
|
||||
let result = await execController(["bootstrap", "generate-user-token", answers.admin]);
|
||||
adminToken = result.stdout.split("\n").slice(-2)[0];
|
||||
}
|
||||
|
||||
if (answers.mode === "standalone") {
|
||||
if (["standalone", "host"].includes(answers.mode)) {
|
||||
logger.info("Setting up host");
|
||||
await execHost(["config", "create"]);
|
||||
await execHost(["config", "set", "host.name", "local"]);
|
||||
|
||||
let result = await execHost(["config", "show", "host.id"]);
|
||||
let hostId = Number.parseInt(result.stdout.split("\n").slice(-2)[0], 10);
|
||||
|
||||
result = await execController(["bootstrap", "generate-host-token", hostId]);
|
||||
let hostToken = result.stdout.split("\n").slice(-2)[0];
|
||||
|
||||
// Default to localhost on correct port for host in standalone mode
|
||||
await execHost(["config", "set", "host.controller_url", `http://localhost:${answers.httpPort}/`]);
|
||||
await execHost(["config", "set", "host.controller_token", hostToken]);
|
||||
await execHost(["config", "set", "host.public_address", answers.publicAddress]);
|
||||
await execHost(["config", "set", "host.factorio_directory", answers.factorioDir]);
|
||||
await execHost(["config", "set", "host.allow_remote_updates", answers.remoteNpm]);
|
||||
await execHost(["config", "set", "host.allow_plugin_updates", answers.remoteNpm]);
|
||||
}
|
||||
|
||||
if (answers.mode === "host") {
|
||||
logger.info("Setting up host");
|
||||
let hostId = JSON.parse(Buffer.from(answers.controllerToken.split(".")[1], "base64")).host;
|
||||
await execHost(["config", "create"]);
|
||||
await execHost(["config", "set", "host.id", hostId]);
|
||||
if (answers.mode === "standalone") {
|
||||
// Default to localhost on correct port for host in standalone mode
|
||||
answers.controllerUrl = `http://localhost:${answers.httpPort}/`;
|
||||
}
|
||||
|
||||
if (["standalone", "host"].includes(answers.mode)) {
|
||||
// The host requests to join the cluster when it is started.
|
||||
await execHost(["config", "set", "host.name", answers.hostName]);
|
||||
await execHost(["config", "set", "host.controller_url", answers.controllerUrl]);
|
||||
await execHost(["config", "set", "host.controller_token", answers.controllerToken]);
|
||||
await execHost(["config", "set", "host.public_address", answers.publicAddress]);
|
||||
await execHost(["config", "set", "host.factorio_directory", answers.factorioDir]);
|
||||
await execHost(["config", "set", "host.allow_remote_updates", answers.remoteNpm]);
|
||||
await execHost(["config", "set", "host.allow_plugin_updates", answers.remoteNpm]);
|
||||
await setRemoteUpdates(execHost, "host", answers.remoteNpm);
|
||||
}
|
||||
|
||||
if (!dev && ["standalone", "controller", "host"].includes(answers.mode)) {
|
||||
@@ -878,7 +854,10 @@ async function main() {
|
||||
if (import.meta.main) {
|
||||
main().catch(err => {
|
||||
process.exitCode = 1;
|
||||
if (err instanceof InstallError) {
|
||||
if (err.name === "ExitPromptError") {
|
||||
// Ctrl+C at a prompt
|
||||
process.exitCode = 130;
|
||||
} else if (err instanceof InstallError) {
|
||||
logger.error(err.message);
|
||||
} else {
|
||||
logger.fatal(`
|
||||
|
||||
@@ -28,12 +28,15 @@
|
||||
"clusteriocreate": "./create.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
"node": "^22.18.0 || >=24.2.0"
|
||||
},
|
||||
|
||||
"dependencies": {
|
||||
"@inquirer/checkbox": "^5.2.8",
|
||||
"@inquirer/confirm": "^6.3.5",
|
||||
"@inquirer/input": "^5.1.9",
|
||||
"@inquirer/select": "^5.2.8",
|
||||
"chalk": "catalog:",
|
||||
"inquirer": "^8.2.7",
|
||||
"yargs": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@
|
||||
"clusterioctl": "./dist/node/ctl.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
"node": "^22.18.0 || >=24.2.0"
|
||||
},
|
||||
|
||||
"dependencies": {
|
||||
|
||||
@@ -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" });
|
||||
@@ -271,7 +286,7 @@ hostPluginCommands.add(new lib.Command({
|
||||
let hostId = await lib.resolveHost(ctl, args.host);
|
||||
const plugins = await ctl.sendTo({ hostId }, new lib.PluginListRequest());
|
||||
print(asTable(plugins.map(p => ({
|
||||
title: p.title, version: p.version, loaded: p.loaded, enabled: p.enabled, npmPackage: p.npmPackage,
|
||||
title: p.title, version: p.version, state: p.state, npmPackage: p.npmPackage,
|
||||
}))));
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"entryPoints": ["index.ts"],
|
||||
"includeVersion": true
|
||||
}
|
||||
@@ -132,6 +132,10 @@ Lists up all configuration entries with their currently configured values.
|
||||
### `run`
|
||||
|
||||
Runs the host.
|
||||
A host that has not been approved prints a code and a link and waits for approval before it connects, see [Setting up a host](https://github.com/clusterio/clusterio/blob/master/packages/create/README.md#setting-up-a-host).
|
||||
If the controller no longer accepts the token of the host when it starts, for example because the host was revoked, it asks to be approved again.
|
||||
If its request is rejected it exits with code 8 and the run scripts created by the installer do not restart it.
|
||||
A host that is revoked while it runs shuts down.
|
||||
|
||||
|
||||
## See Also
|
||||
|
||||
+41
-14
@@ -20,11 +20,14 @@ import winston from "winston";
|
||||
import "winston-daily-rotate-file";
|
||||
|
||||
// internal libraries
|
||||
// Reduce startup time by lazy compiling schemas.
|
||||
import "./src/set_lazy_schema_compilation.js";
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { ConsoleTransport, levels, logger } from "@clusterio/lib";
|
||||
|
||||
import Host from "./src/Host.js";
|
||||
import type Host from "./src/Host.js";
|
||||
import { createScenarioCommand, handleCreateScenarioCommand } from "./src/create_scenario.js";
|
||||
import { PairingError, ensurePaired } from "./src/pairing.js";
|
||||
|
||||
let host: Host | undefined;
|
||||
|
||||
@@ -134,6 +137,10 @@ async function startHost() {
|
||||
type: "boolean", nargs: 0, default: false,
|
||||
describe: "Start the host in recovery mode with all plugins disabled and controller disconnected",
|
||||
});
|
||||
yargs.option("user-token", {
|
||||
type: "string", nargs: 1,
|
||||
describe: "Token of a user allowed to approve hosts, approves this host without waiting. Not saved",
|
||||
});
|
||||
})
|
||||
.demandCommand(1, "You need to specify a command to run")
|
||||
.strict()
|
||||
@@ -212,19 +219,6 @@ async function startHost() {
|
||||
// and as the process name in ps/top on linux.
|
||||
process.title = "clusteriohost";
|
||||
|
||||
// make sure we have the controller access token
|
||||
if (hostConfig.get("host.controller_token") === "enter token here") {
|
||||
logger.fatal("ERROR invalid config!");
|
||||
logger.fatal(
|
||||
"Controller requires an access token for socket operations. As clusterio\n"+
|
||||
"hosts depends upon this, please set your token using the command npx\n"+
|
||||
"clusteriohost config set host.controller_token <token>. You can generate an\n"+
|
||||
"auth token using npx clusterioctl generate-host-token."
|
||||
);
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
|
||||
// make sure url ends with /
|
||||
if (!hostConfig.get("host.controller_url").endsWith("/")) {
|
||||
logger.fatal("ERROR invalid config!");
|
||||
@@ -233,6 +227,39 @@ async function startHost() {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!args.recovery) {
|
||||
const abort = new AbortController();
|
||||
const onSignal = () => { abort.abort(); };
|
||||
process.on("SIGINT", onSignal);
|
||||
process.on("SIGTERM", onSignal);
|
||||
process.on("SIGHUP", onSignal);
|
||||
try {
|
||||
await ensurePaired(hostConfig, {
|
||||
version: packageConfig.version,
|
||||
userToken: args.userToken as string | undefined,
|
||||
signal: abort.signal,
|
||||
});
|
||||
} catch (err: any) {
|
||||
if (abort.signal.aborted) {
|
||||
logger.info("Stopped waiting for approval");
|
||||
return;
|
||||
}
|
||||
if (err instanceof PairingError) {
|
||||
logger.fatal(`Unable to join the cluster: ${err.message}`);
|
||||
// Exit code 8 stops the run scripts from restarting the host.
|
||||
process.exitCode = err.status === 403 ? 8 : 1;
|
||||
return;
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
process.off("SIGINT", onSignal);
|
||||
process.off("SIGTERM", onSignal);
|
||||
process.off("SIGHUP", onSignal);
|
||||
}
|
||||
}
|
||||
|
||||
// Loaded here as the server is not needed by the other commands
|
||||
const { default: Host } = await import("./src/Host.js");
|
||||
let hostConnector = new HostConnector(hostConfig, pluginInfos);
|
||||
host = await Host.fromConfig(
|
||||
hostConfig,
|
||||
|
||||
@@ -4,6 +4,7 @@ export { BaseInstancePlugin, InstanceHooks, type InstancePluginContext } from ".
|
||||
export { default as Host, HostRouter } from "./src/Host.js";
|
||||
export { default as Instance } from "./src/Instance.js";
|
||||
export { default as InstanceConnection } from "./src/InstanceConnection.js";
|
||||
export { PairingError, checkHostToken, pairHost } from "./src/pairing.js";
|
||||
|
||||
if (import.meta.main) {
|
||||
bootstrap();
|
||||
|
||||
@@ -33,13 +33,17 @@
|
||||
"clusteriohost": "./dist/node/host.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
"node": "^22.18.0 || >=24.2.0"
|
||||
},
|
||||
|
||||
"dependencies": {
|
||||
"@clusterio/lib": "workspace:^",
|
||||
"@jimp/core": "^1.6.1",
|
||||
"@jimp/js-png": "^1.6.1",
|
||||
"@jimp/plugin-crop": "^1.6.1",
|
||||
"@jimp/plugin-resize": "^1.6.1",
|
||||
"@jimp/types": "^1.6.1",
|
||||
"@sinclair/typebox": "catalog:",
|
||||
"jimp": "^1.6.1",
|
||||
"pidusage": "^4.1.0",
|
||||
"rcon-client": "^4.2.5",
|
||||
"semver": "catalog:",
|
||||
|
||||
@@ -1308,6 +1308,16 @@ end`.replace(/\r?\n/g, " ");
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop the instance once a start, stop or save in progress has finished */
|
||||
async _stopWhenSettled() {
|
||||
// Stopping concurrently with these races them and asserts on the server state.
|
||||
// Checked right before stop() as another waiter may have started stopping.
|
||||
while (transitoryStatuses.has(this._status)) {
|
||||
await this._waitForSettledStatus();
|
||||
}
|
||||
await this.stop();
|
||||
}
|
||||
|
||||
async kill() {
|
||||
if (this._status === "stopped") {
|
||||
return;
|
||||
@@ -1494,7 +1504,7 @@ end`.replace(/\r?\n/g, " ");
|
||||
}
|
||||
|
||||
async handleInstanceRestartRequest(request: lib.InstanceRestartRequest) {
|
||||
await this.stop();
|
||||
await this._stopWhenSettled();
|
||||
// Stopping invalidates this instance object, a new one must be created by the host
|
||||
// To do this we simulate a waking an instance and sending a start request
|
||||
const instanceConnection = await this._host._connectInstance(this.id);
|
||||
@@ -1502,7 +1512,7 @@ end`.replace(/\r?\n/g, " ");
|
||||
}
|
||||
|
||||
async handleInstanceStopRequest() {
|
||||
await this.stop();
|
||||
await this._stopWhenSettled();
|
||||
}
|
||||
|
||||
async handleInstanceKillRequest() {
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
// Export of item icons and locale
|
||||
import fs from "node:fs/promises";
|
||||
import path from "path";
|
||||
import { Jimp, JimpMime, type JimpInstance } from "jimp";
|
||||
import { createJimp } from "@jimp/core";
|
||||
import png from "@jimp/js-png";
|
||||
import * as crop from "@jimp/plugin-crop";
|
||||
import * as resize from "@jimp/plugin-resize";
|
||||
import type {} from "@jimp/types"; // needed to name jimp types in export.d.ts
|
||||
import yazl from "yazl";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
@@ -160,7 +164,9 @@ async function loadFile(
|
||||
return await modZip.zip.readFile(path.posix.join(modZip.root, filePath));
|
||||
}
|
||||
|
||||
type Image = JimpInstance;
|
||||
// Only the parts of jimp the export uses
|
||||
const Jimp = createJimp({ formats: [png], plugins: [crop.methods, resize.methods] });
|
||||
type Image = InstanceType<typeof Jimp>;
|
||||
type IconCache = Map<string, Image | null>;
|
||||
async function loadIcon(
|
||||
server: FactorioServer,
|
||||
@@ -423,7 +429,13 @@ async function exportIcons(
|
||||
state.metadata[baseName] ??= metadata;
|
||||
let count = 0;
|
||||
for (let prototype of prototypes) {
|
||||
const icon = await exportIcon(server, modVersions, files, state, prototype);
|
||||
let icon: lib.ExportMetadataEntry["icon"];
|
||||
try {
|
||||
icon = await exportIcon(server, modVersions, files, state, prototype);
|
||||
} catch (err: any) {
|
||||
// One broken icon should not stop the rest of the export
|
||||
server._logger.warn(`Skipping icon of ${prototype.type} ${prototype.name}: ${err.message}`);
|
||||
}
|
||||
if (icon) {
|
||||
count += 1;
|
||||
}
|
||||
@@ -494,6 +506,7 @@ async function exportLocale(
|
||||
modZip = await loadZip(server, modVersions, zipCache, mod);
|
||||
} catch (err: any) {
|
||||
if (err.code === "ENOENT") {
|
||||
server._logger.warn(`Skipping locale of ${mod}, its mod zip was not found`);
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
@@ -673,7 +686,7 @@ async function buildExport(server: FactorioServer, files: ExportFiles) {
|
||||
// Crop sheet to actual used height and write single spritesheet + metadata.
|
||||
const usedRows = Math.ceil(state.pos / (SHEET_WIDTH / SHEET_ICON_SIZE));
|
||||
state.sheet.crop({ x: 0, y: 0, w: SHEET_WIDTH, h: Math.max(usedRows * SHEET_ICON_SIZE, 1) });
|
||||
zip.addBuffer(await state.sheet.getBuffer(JimpMime.png), "export/spritesheet.png");
|
||||
zip.addBuffer(await state.sheet.getBuffer("image/png"), "export/spritesheet.png");
|
||||
addJson("export/metadata.json", state.metadata satisfies lib.ExportMetadata);
|
||||
zip.end();
|
||||
|
||||
@@ -684,6 +697,8 @@ async function buildExport(server: FactorioServer, files: ExportFiles) {
|
||||
|
||||
|
||||
// For testing only
|
||||
export const _createSheetState = createSheetState;
|
||||
export const _exportIcons = exportIcons;
|
||||
export const _exportLocale = exportLocale;
|
||||
export const _loadSimpleIcon = loadSimpleIcon;
|
||||
export const _loadLayeredIcon = loadLayeredIcon;
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
import { setTimeout as sleep } from "node:timers/promises";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
import { logger } from "@clusterio/lib";
|
||||
|
||||
/** Time to wait for a response from the controller */
|
||||
const requestTimeoutMs = 30e3;
|
||||
/** Placeholder token of a host that has not been paired */
|
||||
const unpairedToken = "enter token here";
|
||||
|
||||
/** Error responded by the controller */
|
||||
export class PairingError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
/** HTTP status the controller responded with */
|
||||
public status?: number,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "PairingError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface PairingResult {
|
||||
hostId: number;
|
||||
token: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface PairHostOptions {
|
||||
/** URL of the controller, ending with a slash */
|
||||
controllerUrl: string;
|
||||
/** Name to request for the host */
|
||||
name: string;
|
||||
/** Version of the host, shown with the request */
|
||||
version?: string;
|
||||
/** Token of a user allowed to approve hosts, approves the host without waiting */
|
||||
token?: string;
|
||||
/** Interval to poll for the result at */
|
||||
pollIntervalMs?: number;
|
||||
/** Delay before trying again when the controller can't be reached or is busy */
|
||||
retryDelayMs?: number;
|
||||
/** Called with the code to approve the request with each time a request is made */
|
||||
onPending?: (code: string) => void;
|
||||
/** Called when the controller can't be reached or is busy and the request is retried */
|
||||
onRetry?: (err: Error, delayMs: number) => void;
|
||||
/** Signal to cancel pairing with */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
interface Response {
|
||||
status: number;
|
||||
headers: Headers;
|
||||
json: any;
|
||||
}
|
||||
|
||||
async function request(
|
||||
controllerUrl: string,
|
||||
route: string,
|
||||
options: { body?: object, token?: string, signal?: AbortSignal, timeoutMs?: number },
|
||||
): Promise<Response> {
|
||||
const headers: Record<string, string> = { "Accept": "application/json" };
|
||||
if (options.body) {
|
||||
headers["Content-Type"] = "application/json";
|
||||
}
|
||||
if (options.token) {
|
||||
headers["Authorization"] = `Bearer ${options.token}`;
|
||||
}
|
||||
const timeout = AbortSignal.timeout(options.timeoutMs ?? requestTimeoutMs);
|
||||
const response = await fetch(new URL(route, controllerUrl), {
|
||||
method: options.body ? "POST" : "GET",
|
||||
headers,
|
||||
body: options.body ? JSON.stringify(options.body) : undefined,
|
||||
signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout,
|
||||
});
|
||||
let json;
|
||||
try {
|
||||
json = await response.json();
|
||||
} catch {
|
||||
json = undefined;
|
||||
}
|
||||
return { status: response.status, headers: response.headers, json };
|
||||
}
|
||||
|
||||
function responseError(response: Response) {
|
||||
const message = typeof response.json?.error === "string"
|
||||
? response.json.error
|
||||
: `Unexpected response from controller: ${response.status}`;
|
||||
return new PairingError(message, response.status);
|
||||
}
|
||||
|
||||
function pairingResult(response: Response): PairingResult {
|
||||
const { hostId, token, name } = response.json ?? {};
|
||||
if (!Number.isInteger(hostId) || typeof token !== "string" || typeof name !== "string") {
|
||||
throw new PairingError("Invalid response from controller", response.status);
|
||||
}
|
||||
return { hostId, token, name };
|
||||
}
|
||||
|
||||
/** Responses that are worth trying again later */
|
||||
function isTemporary(status: number) {
|
||||
return status === 429 || status >= 500;
|
||||
}
|
||||
|
||||
function retryDelay(response: Response, defaultMs: number) {
|
||||
const seconds = Number(response.headers.get("retry-after"));
|
||||
return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : defaultMs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll a request until it is approved, rejected or no longer known by the controller
|
||||
*
|
||||
* @returns the result if approved, or null if the controller no longer knows the request.
|
||||
*/
|
||||
async function poll(
|
||||
requestId: string,
|
||||
options: Required<Pick<PairHostOptions, "pollIntervalMs" | "retryDelayMs">> & PairHostOptions,
|
||||
) {
|
||||
let delayMs = options.pollIntervalMs;
|
||||
while (true) {
|
||||
await sleep(delayMs, undefined, { signal: options.signal });
|
||||
delayMs = options.pollIntervalMs;
|
||||
let response;
|
||||
try {
|
||||
response = await request(options.controllerUrl, "api/host-pairing/poll", {
|
||||
body: { requestId }, signal: options.signal,
|
||||
});
|
||||
} catch (err: any) {
|
||||
if (options.signal?.aborted) {
|
||||
throw err;
|
||||
}
|
||||
// Keep polling through network errors, the request is made again if it expired meanwhile.
|
||||
delayMs = options.retryDelayMs;
|
||||
options.onRetry?.(err, delayMs);
|
||||
continue;
|
||||
}
|
||||
if (response.status === 200) {
|
||||
return pairingResult(response);
|
||||
}
|
||||
if (response.status === 404) {
|
||||
return null;
|
||||
}
|
||||
if (isTemporary(response.status)) {
|
||||
delayMs = retryDelay(response, options.retryDelayMs);
|
||||
options.onRetry?.(responseError(response), delayMs);
|
||||
continue;
|
||||
}
|
||||
if (response.status !== 202) {
|
||||
throw responseError(response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Request to join the cluster and wait until the request is approved
|
||||
*
|
||||
* Waits through network errors and controller restarts, making a new request
|
||||
* if the controller no longer knows the previous one.
|
||||
*
|
||||
* @param options - Pairing options.
|
||||
* @returns id, token and approved name of the host.
|
||||
* @throws {PairingError} if the controller refuses or rejects the request.
|
||||
* @throws {DOMException} AbortError if the signal is aborted.
|
||||
*/
|
||||
export async function pairHost(options: PairHostOptions): Promise<PairingResult> {
|
||||
const opts = { pollIntervalMs: 2000, retryDelayMs: 10e3, version: "", ...options };
|
||||
let requestId: string | undefined;
|
||||
try {
|
||||
while (true) {
|
||||
opts.signal?.throwIfAborted();
|
||||
let response;
|
||||
try {
|
||||
response = await request(opts.controllerUrl, "api/host-pairing", {
|
||||
body: { name: opts.name, version: opts.version }, token: opts.token, signal: opts.signal,
|
||||
});
|
||||
} catch (err: any) {
|
||||
if (opts.signal?.aborted) {
|
||||
throw err;
|
||||
}
|
||||
opts.onRetry?.(err, opts.retryDelayMs);
|
||||
await sleep(opts.retryDelayMs, undefined, { signal: opts.signal });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (response.status === 200) {
|
||||
return pairingResult(response);
|
||||
}
|
||||
if (isTemporary(response.status)) {
|
||||
const delayMs = retryDelay(response, opts.retryDelayMs);
|
||||
opts.onRetry?.(responseError(response), delayMs);
|
||||
await sleep(delayMs, undefined, { signal: opts.signal });
|
||||
continue;
|
||||
}
|
||||
if (response.status === 404) {
|
||||
throw new PairingError("The controller must be updated to a version that supports host pairing", 404);
|
||||
}
|
||||
if (response.status !== 202) {
|
||||
throw responseError(response);
|
||||
}
|
||||
if (typeof response.json?.requestId !== "string" || typeof response.json.code !== "string") {
|
||||
throw new PairingError("Invalid response from controller", response.status);
|
||||
}
|
||||
|
||||
requestId = response.json.requestId as string;
|
||||
opts.onPending?.(response.json.code);
|
||||
const result = await poll(requestId, opts);
|
||||
requestId = undefined;
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
if (!opts.signal?.aborted) {
|
||||
throw err;
|
||||
}
|
||||
if (requestId !== undefined) {
|
||||
await request(opts.controllerUrl, "api/host-pairing/cancel", {
|
||||
body: { requestId }, timeoutMs: 5e3,
|
||||
}).catch(() => {});
|
||||
}
|
||||
throw new DOMException("Pairing was cancelled", "AbortError");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the controller accepts a host token
|
||||
*
|
||||
* @param controllerUrl - URL of the controller, ending with a slash.
|
||||
* @param token - Host token to check.
|
||||
* @param signal - Signal to cancel the check with.
|
||||
* @returns true if the token is valid and its host is registered.
|
||||
* @throws {PairingError} if the controller gives an unexpected response.
|
||||
*/
|
||||
export async function checkHostToken(controllerUrl: string, token: string, signal?: AbortSignal) {
|
||||
const response = await request(controllerUrl, "api/host-pairing/check", { token, signal });
|
||||
if (response.status === 200) {
|
||||
return true;
|
||||
}
|
||||
if (response.status === 401) {
|
||||
return false;
|
||||
}
|
||||
throw responseError(response);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pair the host with the controller if it has not been paired, or the controller no longer accepts it
|
||||
*
|
||||
* Waits until the request is approved and saves the id, name and token of the host to its config.
|
||||
*
|
||||
* @param config - Config of the host.
|
||||
* @param options - Pairing options.
|
||||
* @throws {PairingError} if the controller refuses or rejects the request.
|
||||
* @throws {DOMException} AbortError if the signal is aborted.
|
||||
*/
|
||||
export async function ensurePaired(
|
||||
config: lib.HostConfig,
|
||||
options: { version: string, userToken?: string, signal?: AbortSignal },
|
||||
) {
|
||||
const controllerUrl = config.get("host.controller_url");
|
||||
const token = config.get("host.controller_token");
|
||||
if (token && token !== unpairedToken) {
|
||||
let valid;
|
||||
try {
|
||||
valid = await checkHostToken(controllerUrl, token, options.signal);
|
||||
} catch (err: any) {
|
||||
if (options.signal?.aborted) {
|
||||
throw err;
|
||||
}
|
||||
// Connecting reports the problem, or authenticates if the controller predates pairing.
|
||||
logger.verbose(`Unable to check if the controller accepts this host: ${err.message}`);
|
||||
return;
|
||||
}
|
||||
if (valid) {
|
||||
return;
|
||||
}
|
||||
logger.warn("The controller no longer accepts this host, requesting to join again");
|
||||
}
|
||||
|
||||
const name = config.get("host.name");
|
||||
logger.info(`Requesting to join the cluster at ${controllerUrl} as "${name}"`);
|
||||
const result = await pairHost({
|
||||
controllerUrl,
|
||||
name,
|
||||
version: options.version,
|
||||
token: options.userToken,
|
||||
signal: options.signal,
|
||||
onPending: code => {
|
||||
const approveUrl = new URL(`hosts?approve=${code}`, controllerUrl).href;
|
||||
// Logged as warnings for the systemd service, which only prints warnings and above.
|
||||
// The link is logged on its own so terminals can make it clickable without it wrapping.
|
||||
logger.warn(`Waiting for approval of "${name}" with code ${code}, open this link to approve it:`);
|
||||
logger.warn(approveUrl);
|
||||
logger.warn(`Or run: npx clusterioctl host approve ${code}`);
|
||||
},
|
||||
onRetry: (err, delayMs) => {
|
||||
logger.warn(`Requesting to join failed: ${err.message}, trying again in ${Math.ceil(delayMs / 1000)}s`);
|
||||
},
|
||||
});
|
||||
|
||||
config.set("host.id", result.hostId);
|
||||
config.set("host.name", result.name);
|
||||
config.set("host.controller_token", result.token);
|
||||
await config.save();
|
||||
logger.info(`Host approved as "${result.name}" with id ${result.hostId}`);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
// This needs to be a separate file due to ECMAScript Modules evaluating code in
|
||||
// imported modules before any code in the file that imports it.
|
||||
(global as any).lazySchemaCompilation = true;
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"entryPoints": ["index.ts"],
|
||||
"includeVersion": true
|
||||
}
|
||||
@@ -46,7 +46,7 @@
|
||||
"compile_validator": "node scripts/compile_validator.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
"node": "^22.18.0 || >=24.2.0"
|
||||
},
|
||||
|
||||
"dependencies": {
|
||||
|
||||
@@ -37,6 +37,8 @@ export interface ControllerConfigFields {
|
||||
"controller.default_mod_pack_id": number | null;
|
||||
"controller.default_role_id": number | null;
|
||||
"controller.autosave_interval": number;
|
||||
"controller.host_pairing_timeout": number;
|
||||
"controller.host_pairing_max_pending": number;
|
||||
"controller.mod_portal_cache_duration_minutes": number;
|
||||
"controller.mod_portal_page_size": number;
|
||||
"controller.allow_remote_updates": boolean;
|
||||
@@ -98,6 +100,20 @@ export class ControllerConfig extends classes.Config<ControllerConfigFields> {
|
||||
initialValue: 60,
|
||||
validator: validators.greaterThanZero,
|
||||
},
|
||||
"controller.host_pairing_timeout": {
|
||||
title: "Host Pairing Timeout",
|
||||
description: "Time in seconds a host can wait for approval before it has to request again, 0 for no limit.",
|
||||
type: "number",
|
||||
initialValue: 3600,
|
||||
validator: validators.greaterThanEqualZero,
|
||||
},
|
||||
"controller.host_pairing_max_pending": {
|
||||
title: "Host Pairing Max Pending",
|
||||
description: "Maximum number of hosts that can wait for approval at the same time, 0 for no limit.",
|
||||
type: "number",
|
||||
initialValue: 50,
|
||||
validator: validators.all(validators.integer, validators.greaterThanEqualZero),
|
||||
},
|
||||
"controller.http_port": {
|
||||
title: "HTTP Port",
|
||||
description: "Port to listen for HTTP connections on, set to null to not listen for HTTP connections.",
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Type, Static } from "@sinclair/typebox";
|
||||
|
||||
/**
|
||||
* A pending request from a host to join the cluster
|
||||
*
|
||||
* Requests are kept in memory on the controller only while the host
|
||||
* waits for them to be approved or rejected.
|
||||
*/
|
||||
export default class HostPairingDetails {
|
||||
constructor(
|
||||
/** Code shown by the host, used to identify the request. */
|
||||
public code: string,
|
||||
/** Name the host asked to have. */
|
||||
public name: string,
|
||||
/** Address the request was made from. */
|
||||
public remoteAddress: string,
|
||||
/** Version of the host that made the request. */
|
||||
public version = "",
|
||||
/** Millisecond Unix timestamp the request was made at. */
|
||||
public createdAtMs = 0,
|
||||
/** Millisecond Unix timestamp this entry was last updated at. */
|
||||
public updatedAtMs = 0,
|
||||
/** True if this request is no longer pending. */
|
||||
public isDeleted = false,
|
||||
) { }
|
||||
|
||||
get id() {
|
||||
return this.code;
|
||||
}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
"code": Type.String(),
|
||||
"name": Type.String(),
|
||||
"remoteAddress": Type.String(),
|
||||
"version": Type.Optional(Type.String()),
|
||||
"createdAtMs": Type.Optional(Type.Number()),
|
||||
"updatedAtMs": Type.Optional(Type.Number()),
|
||||
"isDeleted": Type.Optional(Type.Boolean()),
|
||||
});
|
||||
|
||||
static fromJSON(json: Static<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,
|
||||
|
||||
@@ -4,57 +4,94 @@ import type { PluginNodeEnvInfo } from "../plugin.js";
|
||||
import { Address, MessageRequest } from "./messages_core.js";
|
||||
import type { IUser } from "./UserDetails.js";
|
||||
|
||||
export const pluginStateSchema = Type.Union([
|
||||
Type.Literal("loaded"),
|
||||
Type.Literal("disabled"),
|
||||
Type.Literal("unloadOnRestart"),
|
||||
Type.Literal("loadOnRestart"),
|
||||
Type.Literal("noEntrypoint"),
|
||||
Type.Literal("pendingInstall"),
|
||||
Type.Literal("removed"),
|
||||
Type.Literal("removedLoaded"),
|
||||
Type.Literal("nameTaken"),
|
||||
]);
|
||||
/**
|
||||
* State of a plugin on a machine
|
||||
*
|
||||
* - loaded: Running and loaded again on the next restart
|
||||
* - disabled: Not loaded as `<plugin>.load_plugin` is false
|
||||
* - unloadOnRestart: Running, but disabled since startup
|
||||
* - loadOnRestart: Not running, enabled since startup or skipped by recovery mode
|
||||
* - noEntrypoint: Has no entrypoint for this machine, so it is never loaded here
|
||||
* - pendingInstall: Installed since startup, loaded on the next restart
|
||||
* - removed: Uninstalled since startup while not running
|
||||
* - removedLoaded: Uninstalled since startup, running until the next restart
|
||||
* - nameTaken: Not loaded as another package provides a plugin with the same name
|
||||
*/
|
||||
export type PluginState = Static<typeof pluginStateSchema>;
|
||||
|
||||
/* This is similar to other plugin definitions but with lots removed */
|
||||
export class PluginDetails {
|
||||
constructor(
|
||||
public name: string,
|
||||
public title: string,
|
||||
public version: string,
|
||||
public loaded: boolean,
|
||||
public enabled: boolean,
|
||||
public state: PluginState,
|
||||
public description?: string,
|
||||
public npmPackage?: string,
|
||||
/** Version installed on disk, differs from version when an update is waiting for a restart */
|
||||
public installedVersion?: string,
|
||||
/** Installed after the machine started, will be loaded on the next restart */
|
||||
public pendingInstall?: boolean,
|
||||
/** Uninstalled after the machine started, will not be loaded on the next restart */
|
||||
public removed?: boolean,
|
||||
/** Name in the root package.json dependencies, differs from npmPackage for aliases */
|
||||
public dependencyName?: string,
|
||||
/** Has no entrypoint for this machine, so it is never loaded here */
|
||||
public noEntrypoint?: boolean,
|
||||
/** Not loaded as another package provides a plugin with the same name */
|
||||
public nameTaken?: boolean,
|
||||
) {}
|
||||
|
||||
static jsonSchema = Type.Object({
|
||||
name: Type.String(),
|
||||
title: Type.String(),
|
||||
version: Type.String(),
|
||||
// Missing from 2.0.3 and older, which require loaded and enabled instead
|
||||
state: Type.Optional(pluginStateSchema),
|
||||
loaded: Type.Boolean(),
|
||||
enabled: Type.Boolean(),
|
||||
description: Type.Optional(Type.String()),
|
||||
npmPackage: Type.Optional(Type.String()),
|
||||
installedVersion: Type.Optional(Type.String()),
|
||||
pendingInstall: Type.Optional(Type.Boolean()),
|
||||
removed: Type.Optional(Type.Boolean()),
|
||||
dependencyName: Type.Optional(Type.String()),
|
||||
noEntrypoint: Type.Optional(Type.Boolean()),
|
||||
nameTaken: Type.Optional(Type.Boolean()),
|
||||
});
|
||||
|
||||
static fromJSON(json: Static<typeof this.jsonSchema>) {
|
||||
return new this(
|
||||
json.name, json.title, json.version, json.loaded, json.enabled,
|
||||
json.description, json.npmPackage, json.installedVersion, json.pendingInstall, json.removed,
|
||||
json.dependencyName, json.noEntrypoint, json.nameTaken,
|
||||
json.name, json.title, json.version, json.state ?? this.loadState(json.loaded, json.enabled),
|
||||
json.description, json.npmPackage, json.installedVersion, json.dependencyName,
|
||||
);
|
||||
}
|
||||
|
||||
static fromNodeEnvInfo(pluginInfo: PluginNodeEnvInfo, loaded: boolean, enabled: boolean) {
|
||||
toJSON(): Static<typeof PluginDetails.jsonSchema> {
|
||||
return {
|
||||
name: this.name,
|
||||
title: this.title,
|
||||
version: this.version,
|
||||
state: this.state,
|
||||
loaded: this.loaded,
|
||||
enabled: this.loadsOnRestart,
|
||||
description: this.description,
|
||||
npmPackage: this.npmPackage,
|
||||
installedVersion: this.installedVersion,
|
||||
dependencyName: this.dependencyName,
|
||||
};
|
||||
}
|
||||
|
||||
/** State of a plugin known since startup */
|
||||
static loadState(loaded: boolean, enabled: boolean): PluginState {
|
||||
if (loaded) {
|
||||
return enabled ? "loaded" : "unloadOnRestart";
|
||||
}
|
||||
return enabled ? "loadOnRestart" : "disabled";
|
||||
}
|
||||
|
||||
static fromNodeEnvInfo(pluginInfo: PluginNodeEnvInfo, state: PluginState) {
|
||||
return new this(
|
||||
pluginInfo.name, pluginInfo.title, pluginInfo.version, loaded, enabled,
|
||||
pluginInfo.name, pluginInfo.title, pluginInfo.version, state,
|
||||
pluginInfo.description, pluginInfo.npmPackage,
|
||||
);
|
||||
}
|
||||
@@ -63,10 +100,25 @@ export class PluginDetails {
|
||||
static fromPackageJson(packageName: string, packageJson: any, npmPackage?: string, dependencyName?: string) {
|
||||
const description = typeof packageJson.description === "string" ? packageJson.description : undefined;
|
||||
return new this(
|
||||
packageName, packageName, packageJson.version, false, false,
|
||||
description, npmPackage, packageJson.version, true, undefined, dependencyName,
|
||||
packageName, packageName, packageJson.version, "pendingInstall",
|
||||
description, npmPackage, packageJson.version, dependencyName,
|
||||
);
|
||||
}
|
||||
|
||||
/** Running on the machine now */
|
||||
get loaded() {
|
||||
return ["loaded", "unloadOnRestart", "removedLoaded"].includes(this.state);
|
||||
}
|
||||
|
||||
/** Running on the machine after the next restart */
|
||||
get loadsOnRestart() {
|
||||
return ["loaded", "loadOnRestart", "pendingInstall"].includes(this.state);
|
||||
}
|
||||
|
||||
/** Uninstalled since startup */
|
||||
get removed() {
|
||||
return this.state === "removed" || this.state === "removedLoaded";
|
||||
}
|
||||
}
|
||||
|
||||
export class PluginListRequest {
|
||||
|
||||
@@ -166,6 +166,7 @@ export abstract class Datastore<
|
||||
"update": [ updates: U[] ],
|
||||
}> {
|
||||
private dirty = false;
|
||||
private saving: Promise<void> = Promise.resolve();
|
||||
|
||||
constructor(
|
||||
private provider: DatastoreProvider<K, V> = new MemoryDatastoreProvider(),
|
||||
@@ -181,10 +182,22 @@ export abstract class Datastore<
|
||||
|
||||
// Save the datastore to the provider
|
||||
async save() {
|
||||
if (this.dirty) {
|
||||
await this.provider.save(this.data);
|
||||
// Saves run one at a time so an older snapshot can't be written after a newer one.
|
||||
const save = this.saving.catch(() => {}).then(async () => {
|
||||
if (!this.dirty) {
|
||||
return;
|
||||
}
|
||||
// Cleared before writing so changes made while saving are saved by the next save.
|
||||
this.dirty = false;
|
||||
}
|
||||
try {
|
||||
await this.provider.save(this.data);
|
||||
} catch (err) {
|
||||
this.dirty = true;
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
this.saving = save;
|
||||
await save;
|
||||
}
|
||||
|
||||
// Load the datastore from the provider
|
||||
|
||||
@@ -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 hosts to join the cluster, and approve hosts " +
|
||||
"directly by starting them with a user token. Approving gives the new host full access to the cluster.",
|
||||
},
|
||||
{
|
||||
name: "core.host.revoke_token",
|
||||
title: "Revoke host token",
|
||||
description: "Revoke access token and terminate existing connection for hosts.",
|
||||
},
|
||||
{
|
||||
name: "core.host.create_config",
|
||||
title: "Create host config",
|
||||
description: "Create host configs via the controller.",
|
||||
name: "core.host.revoke",
|
||||
title: "Revoke hosts",
|
||||
description: "Remove hosts from the cluster, disconnecting them and making their access tokens invalid.",
|
||||
},
|
||||
|
||||
{
|
||||
|
||||
@@ -128,14 +128,12 @@ export async function listPluginDetails(
|
||||
for (const pluginInfo of pluginInfos) {
|
||||
const dir = await realDir(path.dirname(pluginInfo.packagePath));
|
||||
knownDirs.add(dir);
|
||||
const loaded = isLoaded(pluginInfo);
|
||||
// Without an entrypoint for this machine the plugin has no load_plugin field here
|
||||
const loadable = hasEntrypoint(pluginInfo);
|
||||
const plugin = PluginDetails.fromNodeEnvInfo(
|
||||
pluginInfo, isLoaded(pluginInfo), loadable && isEnabled(pluginInfo),
|
||||
pluginInfo,
|
||||
hasEntrypoint(pluginInfo) ? PluginDetails.loadState(loaded, isEnabled(pluginInfo)) : "noEntrypoint",
|
||||
);
|
||||
if (!loadable) {
|
||||
plugin.noEntrypoint = true;
|
||||
}
|
||||
if (Object.hasOwn(dependencies, pluginInfo.requirePath)) {
|
||||
plugin.dependencyName = pluginInfo.requirePath;
|
||||
}
|
||||
@@ -147,7 +145,7 @@ export async function listPluginDetails(
|
||||
packageJson = await readPackageJson(path.dirname(pluginInfo.packagePath), false);
|
||||
if (packageJson === undefined) {
|
||||
// Uninstalled since startup, it won't be found on the next restart
|
||||
plugin.removed = true;
|
||||
plugin.state = loaded ? "removedLoaded" : "removed";
|
||||
}
|
||||
} catch {
|
||||
// Ignored: npm is still writing it
|
||||
@@ -185,8 +183,7 @@ export async function listPluginDetails(
|
||||
const plugin = PluginDetails.fromPackageJson(packageName, packageJson, npmPackage, dependencyName);
|
||||
if (takenDirs.has(dir)) {
|
||||
// Skipped on startup as its plugin name is taken, will be again
|
||||
plugin.pendingInstall = undefined;
|
||||
plugin.nameTaken = true;
|
||||
plugin.state = "nameTaken";
|
||||
}
|
||||
plugins.push(plugin);
|
||||
}
|
||||
|
||||
@@ -480,6 +480,8 @@ export class EventSubscriber<E, S = null> {
|
||||
protected Event: EventClass<E>,
|
||||
public control: Link,
|
||||
protected filteredHandler?: EventSubscriberCallback<E>,
|
||||
/** Nothing is sent to the controller while this returns false, for accounts without permission */
|
||||
protected permitted: () => boolean = () => true,
|
||||
) {
|
||||
control.handle(Event, this._handleEvent.bind(this));
|
||||
// The events below exist only on websocket connectors, we can't early return because of test mocking
|
||||
@@ -670,7 +672,7 @@ export class EventSubscriber<E, S = null> {
|
||||
* Update the subscription with the controller based on current handler counts
|
||||
*/
|
||||
private async _sendRequest(action: SubscriptionAction, filters: SubscriptionFilters) {
|
||||
if (!this.control.connector.valid) {
|
||||
if (!this.control.connector.valid || !this.permitted()) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -725,6 +727,16 @@ export class MapSubscriber<
|
||||
/** Current value of the subscribed resource */
|
||||
values = new Map<K, V>();
|
||||
|
||||
override handleConnectionEvent(event: "connect" | "drop" | "resume" | "close") {
|
||||
if (event === "connect") {
|
||||
// A new session is only sent values that exist, not ones removed while disconnected,
|
||||
// so everything is fetched again.
|
||||
this.values.clear();
|
||||
this.lastUpdatedMs = -1;
|
||||
}
|
||||
super.handleConnectionEvent(event);
|
||||
}
|
||||
|
||||
protected override getLastUpdatedTimeMs(event: E) {
|
||||
let maxTime = this.lastUpdatedMs;
|
||||
for (const update of event.updates) {
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"entryPoints": ["index.ts"],
|
||||
"includeVersion": true
|
||||
}
|
||||
@@ -29,7 +29,7 @@
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
"node": "^22.18.0 || >=24.2.0"
|
||||
},
|
||||
|
||||
"dependencies": {
|
||||
@@ -45,7 +45,6 @@
|
||||
"os-browserify": "^0.3.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
"process": "^0.11.10",
|
||||
"rc-field-form": "^1.44.0",
|
||||
"react": "catalog:",
|
||||
"react-dom": "catalog:",
|
||||
"react-markdown": "catalog:",
|
||||
@@ -53,7 +52,6 @@
|
||||
"react-router-dom": "catalog:",
|
||||
"semver": "catalog:",
|
||||
"stream-browserify": "^3.0.0",
|
||||
"typescript": "catalog:",
|
||||
"util": "^0.12.5",
|
||||
"vite": "catalog:"
|
||||
},
|
||||
@@ -61,6 +59,7 @@
|
||||
"@types/node": "catalog:",
|
||||
"@types/react": "catalog:",
|
||||
"@types/react-dom": "^18.3.7",
|
||||
"@types/semver": "catalog:"
|
||||
"@types/semver": "catalog:",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useContext, useState } from "react";
|
||||
import { Descriptions, Spin, Typography, Button, Space, Popconfirm, Flex, Tooltip } from "antd";
|
||||
import { Descriptions, 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";
|
||||
@@ -17,12 +17,13 @@ import PageHeader from "./PageHeader";
|
||||
import PageLayout from "./PageLayout";
|
||||
import PluginExtra from "./PluginExtra";
|
||||
import ResourceNotes from "./ResourceNotes";
|
||||
import ResourceState from "./ResourceState";
|
||||
import {
|
||||
MetricCpuRatio, MetricCpuUsed, MetricMemoryRatio, MetricMemoryUsed,
|
||||
MetricDiskUsed, MetricDiskRatio, MetricRelativeDate,
|
||||
} from "./system_metrics";
|
||||
import { formatTimestamp } from "../util/time_format";
|
||||
import { useSystems } from "../model/system";
|
||||
import useResourceState from "../util/useResourceState";
|
||||
import { hasNpmButtonPermission, NpmButton } from "./NpmButton";
|
||||
import VariableDropdownButton, { VariableDropdownButtonProps } from "./VariableDropdownButton";
|
||||
|
||||
@@ -98,51 +99,55 @@ 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);
|
||||
|
||||
return <Popconfirm
|
||||
title={`Revoke access for ${host.name}?`}
|
||||
description={<>
|
||||
The host is removed from the cluster and disconnected.<br />
|
||||
{assigned.length > 0 && <>Its instances become unassigned: {assigned.join(", ")}<br /></>}
|
||||
To add it back, start the host again and approve it.
|
||||
</>}
|
||||
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();
|
||||
const system = systems.get(hostId);
|
||||
const [host, synced] = useHost(hostId);
|
||||
const [host, synced, error] = useHost(hostId);
|
||||
const state = useResourceState(host, synced, error, hostId);
|
||||
const [maxLevel, setMaxLevel] = useState<keyof typeof lib.levels>("info");
|
||||
const canShowNpm = hasNpmButtonPermission(false);
|
||||
const hostInstances = new Map([...instances].filter(([_id, instance]) => instance.assignedHost === hostId));
|
||||
|
||||
let nav = [{ name: "Hosts", path: "/hosts" }, { name: host?.name ?? String(hostId) }];
|
||||
if (!host) {
|
||||
if (!synced) {
|
||||
return <PageLayout nav={nav}><Spin size="large" /></PageLayout>;
|
||||
}
|
||||
|
||||
return <PageLayout nav={nav}>
|
||||
<PageHeader title={String(hostId)} />
|
||||
<p>Host with id {hostId} was not found on the controller.</p>
|
||||
</PageLayout>;
|
||||
return <ResourceState state={state} type="Host" id={hostId} nav={nav} listPath="/hosts" error={error} />;
|
||||
}
|
||||
|
||||
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 +180,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,9 @@
|
||||
import React, { useContext, useRef, useState, useEffect } from "react";
|
||||
import { Button, Flex, Form, InputNumber, Modal, Space, Switch, Table, Tooltip, Typography } from "antd";
|
||||
import { ExclamationCircleOutlined, CopyOutlined } from "@ant-design/icons";
|
||||
import React, { useContext, useState, useEffect } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import {
|
||||
Badge, Button, Descriptions, Flex, Input, Modal, Result, Space, Spin, Switch, Table, Tooltip, Typography,
|
||||
} from "antd";
|
||||
import { ExclamationCircleOutlined, CopyOutlined, PlusOutlined } from "@ant-design/icons";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
@@ -16,9 +19,10 @@ import {
|
||||
MetricDiskUsed, MetricDiskRatio,
|
||||
RestartRequired,
|
||||
} from "./system_metrics";
|
||||
import { useHosts } from "../model/host";
|
||||
import { useHostPairings, useHosts } from "../model/host";
|
||||
import { useSystems } from "../model/system";
|
||||
import notify, { notifyErrorHandler } from "../util/notify";
|
||||
import { formatDuration } from "../util/time_format";
|
||||
import useTableQueryState from "../util/useTableQueryState";
|
||||
import useColumnSearch from "../util/useColumnSearch";
|
||||
import useRowNavigation from "../util/useRowNavigation";
|
||||
@@ -27,133 +31,228 @@ import Link from "./Link";
|
||||
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
|
||||
|
||||
|
||||
function GenerateHostTokenButton() {
|
||||
let control = useContext(ControlContext);
|
||||
let [open, setOpen] = useState(false);
|
||||
let [token, setToken] = useState<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 [requests, synced] = useHostPairings();
|
||||
const [, setParams] = useSearchParams();
|
||||
const now = useNow(props.open);
|
||||
|
||||
const controllerUrl = new URL(webRoot, document.location.href).href;
|
||||
const installCommand = `npm init "@clusterio" -- --mode host --controller-url ${controllerUrl}`;
|
||||
|
||||
function review(code: string) {
|
||||
setParams(current => {
|
||||
const next = new URLSearchParams(current);
|
||||
next.set("approve", code);
|
||||
return next;
|
||||
}, { replace: true });
|
||||
}
|
||||
|
||||
// Generate a new random
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
generateToken().catch(notifyErrorHandler("Error generating token"));
|
||||
}
|
||||
}, [open]);
|
||||
return <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, then start the host
|
||||
with the run-host script. It 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 host saves its connection details and starts up.
|
||||
Later starts connect to the cluster straight away.
|
||||
</Typography.Paragraph>
|
||||
<Typography.Title level={5}>Waiting for approval</Typography.Title>
|
||||
<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",
|
||||
dataIndex: "name",
|
||||
},
|
||||
{
|
||||
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) => <Button
|
||||
type="primary"
|
||||
size="small"
|
||||
onClick={() => { review(request.code); }}
|
||||
>Review</Button>,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</Modal>;
|
||||
}
|
||||
|
||||
const pluginString = pluginList.filter(p => p.npmPackage).map(p => `"${p.npmPackage}"`).join(" ");
|
||||
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>
|
||||
/** Format a code like the controller does, matching any case and without the dash */
|
||||
function normaliseCode(code: string) {
|
||||
const plain = code.toUpperCase().replace(/[^0-9A-Z]/g, "");
|
||||
return `${plain.slice(0, 3)}-${plain.slice(3)}`;
|
||||
}
|
||||
|
||||
/** Dialog opened by the link a waiting host prints, for approving that host */
|
||||
function ApproveHostModal(props: { code: string, onClose: () => void }) {
|
||||
const control = useContext(ControlContext);
|
||||
const account = useAccount();
|
||||
const [requests, synced] = useHostPairings();
|
||||
const code = normaliseCode(props.code);
|
||||
const request = requests.get(code);
|
||||
const [name, setName] = useState<string>();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const now = useNow(true);
|
||||
const permitted = account.hasPermission("core.host.approve");
|
||||
const hostName = (name ?? request?.name ?? "").trim();
|
||||
|
||||
function approve() {
|
||||
if (!request) {
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
control.send(
|
||||
new lib.HostPairingApproveRequest(request.code, hostName !== request.name ? hostName : undefined)
|
||||
).then(() => {
|
||||
notify(`Approved host ${hostName}`, "success");
|
||||
props.onClose();
|
||||
}).catch(
|
||||
notifyErrorHandler(`Error approving host ${request.name}`)
|
||||
).finally(() => {
|
||||
setBusy(false);
|
||||
});
|
||||
}
|
||||
|
||||
function reject() {
|
||||
if (!request) {
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
control.send(new lib.HostPairingRejectRequest(request.code)).then(() => {
|
||||
notify(`Rejected host ${request.name}`);
|
||||
props.onClose();
|
||||
}).catch(
|
||||
notifyErrorHandler(`Error rejecting host ${request.name}`)
|
||||
).finally(() => {
|
||||
setBusy(false);
|
||||
});
|
||||
}
|
||||
|
||||
let content;
|
||||
if (!permitted) {
|
||||
content = <Result
|
||||
status="403"
|
||||
title="You are not allowed to approve hosts"
|
||||
subTitle="Ask someone with the Approve hosts permission to open this link."
|
||||
/>;
|
||||
} else if (!request && !synced) {
|
||||
content = <Flex justify="center" style={{ padding: 48 }}><Spin size="large" /></Flex>;
|
||||
} else if (!request) {
|
||||
content = <Result
|
||||
status="warning"
|
||||
title={<>No host is waiting with code <span style={{ whiteSpace: "nowrap" }}>{code}</span></>}
|
||||
subTitle={
|
||||
"It may have been approved or rejected already, or stopped waiting. " +
|
||||
"A host that is still waiting shows a new code."
|
||||
}
|
||||
/>;
|
||||
} else {
|
||||
content = <>
|
||||
<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:
|
||||
A host is asking to join the cluster.
|
||||
Only approve it if the code below matches the code shown by the host,
|
||||
an approved host has full access to the cluster.
|
||||
</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>
|
||||
<Flex justify="center" style={{ margin: "24px 0" }}>
|
||||
<Typography.Text code strong style={{ fontSize: 32, letterSpacing: 4 }}>{request.code}</Typography.Text>
|
||||
</Flex>
|
||||
<Descriptions size="small" column={1} bordered style={{ marginBottom: 16 }}>
|
||||
<Descriptions.Item label="Address">{request.remoteAddress}</Descriptions.Item>
|
||||
{request.version && <Descriptions.Item label="Version">{request.version}</Descriptions.Item>}
|
||||
<Descriptions.Item label="Waiting for">
|
||||
{formatDuration(Math.max(0, now - request.createdAtMs))}
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
<Typography.Text strong>Name</Typography.Text>
|
||||
<Input
|
||||
size="large"
|
||||
aria-label="Host name"
|
||||
value={name ?? request.name}
|
||||
onChange={event => { setName(event.target.value); }}
|
||||
onPressEnter={approve}
|
||||
style={{ margin: "4px 0 24px" }}
|
||||
/>
|
||||
<Button
|
||||
type="primary"
|
||||
size="large"
|
||||
block
|
||||
disabled={busy || !hostName}
|
||||
loading={busy}
|
||||
onClick={approve}
|
||||
>Approve</Button>
|
||||
<Flex justify="center" style={{ marginTop: 12 }}>
|
||||
<Button type="link" danger disabled={busy} onClick={reject}>Reject</Button>
|
||||
</Flex>
|
||||
</>;
|
||||
}
|
||||
|
||||
return <Modal title="Approve host" open footer={null} onCancel={props.onClose} width="520px">
|
||||
{content}
|
||||
</Modal>;
|
||||
}
|
||||
|
||||
function AddHostButton() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [requests] = useHostPairings();
|
||||
return <>
|
||||
<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); }} />
|
||||
</>;
|
||||
}
|
||||
|
||||
@@ -212,11 +311,22 @@ export default function HostsPage() {
|
||||
});
|
||||
const nameSearch = useColumnSearch<lib.HostDetails>(tableState, "name", host => host.name, "Search hosts");
|
||||
const rowNav = useRowNavigation();
|
||||
const [params, setParams] = useSearchParams();
|
||||
const approveCode = params.get("approve");
|
||||
|
||||
function closeApprove() {
|
||||
setParams(current => {
|
||||
const next = new URLSearchParams(current);
|
||||
next.delete("approve");
|
||||
return next;
|
||||
}, { replace: true });
|
||||
}
|
||||
|
||||
return <PageLayout nav={[{ name: "Hosts" }]}>
|
||||
{approveCode !== null && <ApproveHostModal code={approveCode} onClose={closeApprove} />}
|
||||
<PageHeader
|
||||
title="Hosts"
|
||||
extra={account.hasPermission("core.host.generate_token") ? <GenerateHostTokenButton /> : undefined}
|
||||
extra={account.hasPermission("core.host.approve") ? <AddHostButton /> : undefined}
|
||||
/>
|
||||
<Table
|
||||
style={{ overflowX: "auto" }}
|
||||
|
||||
@@ -8,6 +8,8 @@ import FactorioIcon from "./FactorioIcon";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { useModPack } from "../model/mod_pack";
|
||||
import { PrototypeMetadataEntry } from "../store/export_prototype_metadata_store";
|
||||
import useResourceState from "../util/useResourceState";
|
||||
import ResourceState from "./ResourceState";
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
@@ -39,7 +41,8 @@ export default function IconReferencePage() {
|
||||
|
||||
const [filter, setFilter] = useState("");
|
||||
const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());
|
||||
const [modPack] = useModPack(modPackId);
|
||||
const [modPack, synced, error] = useModPack(modPackId);
|
||||
const state = useResourceState(modPack, synced, error, modPackId);
|
||||
const manifest = modPack?.exportManifest;
|
||||
const prototypes = useExportPrototypeMetadata(modPack);
|
||||
const filtered = useMemo(() => filterPrototypes(prototypes, filter), [prototypes, filter]);
|
||||
@@ -100,6 +103,10 @@ export default function IconReferencePage() {
|
||||
{ name: modPack?.name ?? String(modPackId), path: `/mods/mod-packs/${modPackId}/view` },
|
||||
{ name: "Icon Reference" },
|
||||
];
|
||||
if (!modPack) {
|
||||
return <ResourceState state={state} type="Mod pack" id={modPackId} nav={nav} listPath="/mods" error={error} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<PageLayout nav={nav}>
|
||||
<PageHeader title="Icon Reference" />
|
||||
|
||||
@@ -25,8 +25,10 @@ export default function InstanceControlButton(props: InstanceControlButtonProps)
|
||||
|
||||
const instanceId = props.instance.id;
|
||||
const instanceStatus = props.instance.status;
|
||||
const showStart = ["stopped", "stopping"].includes(instanceStatus);
|
||||
const showStop = ["running", "starting"].includes(instanceStatus);
|
||||
// While starting or stopping the button shows the action in progress as loading.
|
||||
const showStart = ["stopped", "starting"].includes(instanceStatus);
|
||||
const showStop = ["running", "stopping"].includes(instanceStatus);
|
||||
const transitioning = ["starting", "stopping"].includes(instanceStatus);
|
||||
|
||||
function actionFinish() {
|
||||
setSwitching(false);
|
||||
@@ -37,7 +39,7 @@ export default function InstanceControlButton(props: InstanceControlButtonProps)
|
||||
|
||||
const actions: VariableDropdownButtonProps["actions"] = [];
|
||||
|
||||
if (account.hasPermission("core.instance.start") && showStart !== switching) {
|
||||
if (account.hasPermission("core.instance.start") && showStart) {
|
||||
actions.push({
|
||||
key: "start",
|
||||
label: "Start",
|
||||
@@ -101,7 +103,7 @@ export default function InstanceControlButton(props: InstanceControlButtonProps)
|
||||
{...props}
|
||||
type="primary"
|
||||
actions={actions}
|
||||
loading={switching}
|
||||
loading={switching || transitioning}
|
||||
disabled={!(showStart || showStop)}
|
||||
/>
|
||||
<Popconfirm
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useContext, useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import {
|
||||
Alert, Button, Descriptions, Dropdown, Flex, MenuProps, Modal, Segmented, Space, Spin, Tooltip, Typography,
|
||||
Button, Descriptions, Dropdown, Flex, MenuProps, Modal, Segmented, Space, Tooltip, Typography,
|
||||
message,
|
||||
} from "antd";
|
||||
import CopyOutlined from "@ant-design/icons/CopyOutlined";
|
||||
@@ -16,6 +16,7 @@ import PageHeader from "./PageHeader";
|
||||
import PageLayout from "./PageLayout";
|
||||
import PluginExtra from "./PluginExtra";
|
||||
import ResourceNotes from "./ResourceNotes";
|
||||
import ResourceState from "./ResourceState";
|
||||
import InstanceConfigTree from "./InstanceConfigTree";
|
||||
import LogConsole, { SelectMaxLogLevel } from "./LogConsole";
|
||||
import InstanceRcon from "./InstanceRcon";
|
||||
@@ -31,6 +32,7 @@ import InstanceStatusTag from "./InstanceStatusTag";
|
||||
import Link from "./Link";
|
||||
import { instancePublicAddress } from "../util/instance";
|
||||
import useLocalStorage from "../util/useLocalStorage";
|
||||
import useResourceState from "../util/useResourceState";
|
||||
import { MetricRelativeDate } from "./system_metrics";
|
||||
|
||||
type MenuItem = Required<MenuProps>["items"][number];
|
||||
@@ -208,26 +210,15 @@ export default function InstanceViewPage() {
|
||||
let navigate = useNavigate();
|
||||
|
||||
let account = useAccount();
|
||||
let [instance, synced] = useInstance(instanceId);
|
||||
let [instance, synced, error] = useInstance(instanceId);
|
||||
const state = useResourceState(instance, synced, error, instanceId);
|
||||
let [host] = useHost(instance?.assignedHost);
|
||||
|
||||
let nav = [{ name: "Instances", path: "/instances" }, { name: instance?.name ?? String(instanceId) }];
|
||||
if (!instance) {
|
||||
if (!synced) {
|
||||
return <PageLayout nav={nav}><Spin size="large" /></PageLayout>;
|
||||
}
|
||||
|
||||
return <PageLayout nav={nav}>
|
||||
<Alert
|
||||
message={"Instance not found"}
|
||||
showIcon
|
||||
description={<>Instance with id {instanceId} was not found on the controller.</>}
|
||||
type="warning"
|
||||
action={
|
||||
<Link to="/instances">Go back to instances list</Link>
|
||||
}
|
||||
/>
|
||||
</PageLayout>;
|
||||
return <ResourceState
|
||||
state={state} type="Instance" id={instanceId} nav={nav} listPath="/instances" error={error}
|
||||
/>;
|
||||
}
|
||||
|
||||
return <PageLayout nav={nav}>
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import React, { Fragment, memo, useCallback, useEffect, useContext, useRef, useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { FieldData } from "rc-field-form/lib/interface";
|
||||
|
||||
import {
|
||||
Button, Card, ColorPicker, Checkbox, Col, ConfigProvider, Descriptions, Form, Input, Pagination,
|
||||
Popconfirm, Row, Table, Tag, Typography, Select, Skeleton, Space, Spin, Switch, Modal, Tooltip,
|
||||
TablePaginationConfig, Alert, notification,
|
||||
Popconfirm, Row, Table, Tag, Typography, Select, Skeleton, Space, Switch, Modal, Tooltip,
|
||||
TablePaginationConfig, Alert, notification, FormProps,
|
||||
} from "antd";
|
||||
|
||||
import {
|
||||
@@ -23,10 +22,12 @@ import { useModPack } from "../model/mod_pack";
|
||||
import { useMods } from "../model/mods";
|
||||
import { useClipboard } from "../util/clipboard";
|
||||
import notify, { notifyErrorHandler } from "../util/notify";
|
||||
import useResourceState from "../util/useResourceState";
|
||||
import PageHeader from "./PageHeader";
|
||||
import PageLayout from "./PageLayout";
|
||||
import SectionHeader from "./SectionHeader";
|
||||
import ResourceNotes from "./ResourceNotes";
|
||||
import ResourceState from "./ResourceState";
|
||||
import ModDetails from "./ModDetails";
|
||||
import { InputPartialVersion } from "./InputVersion";
|
||||
import Link from "./Link";
|
||||
@@ -35,6 +36,8 @@ const { logger } = lib;
|
||||
const { Text } = Typography;
|
||||
const strcmp = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare;
|
||||
|
||||
type FieldData = NonNullable<FormProps["fields"]>[number];
|
||||
|
||||
type ModChange =
|
||||
{
|
||||
type: "name" | "description"
|
||||
@@ -1182,7 +1185,8 @@ export default function ModPackViewPage() {
|
||||
let modPackId = Number(params.id);
|
||||
|
||||
const [form] = Form.useForm();
|
||||
const [modPack, synced] = useModPack(modPackId);
|
||||
const [modPack, synced, error] = useModPack(modPackId);
|
||||
const state = useResourceState(modPack, synced, error, modPackId);
|
||||
let prototypes: any = useExportedAsset(modPack, "settings");
|
||||
let locale: Map<any, any> = useExportedAsset(modPack, "locale");
|
||||
let [changes, setChanges] = useState<ModChange[]>([]);
|
||||
@@ -1252,17 +1256,7 @@ export default function ModPackViewPage() {
|
||||
|
||||
let nav = [{ name: "Mods", path: "/mods" }, { name: "Mod Packs" }, { name: modPack?.name ?? String(modPackId) }];
|
||||
if (!modifiedModPack || !modPack) {
|
||||
if (!synced) {
|
||||
return <PageLayout nav={nav}>
|
||||
<PageHeader title={String(modPackId)} />
|
||||
<Spin size="large" />
|
||||
</PageLayout>;
|
||||
}
|
||||
|
||||
return <PageLayout nav={nav}>
|
||||
<PageHeader title="Mod Pack Not Found" />
|
||||
<p>Mod pack with id {modPackId} was not found on the controller.</p>
|
||||
</PageLayout>;
|
||||
return <ResourceState state={state} type="Mod pack" id={modPackId} nav={nav} listPath="/mods" error={error} />;
|
||||
}
|
||||
|
||||
return <PageLayout nav={nav}>
|
||||
|
||||
@@ -35,6 +35,8 @@ type MachinePluginsState = {
|
||||
unknown: Machine[],
|
||||
/** Fetch the plugin lists of connected machines now, instead of waiting for the next system metrics */
|
||||
refresh: (addresses?: lib.AddressShorthand[]) => Promise<void>,
|
||||
/** Why machines is not available, if it's not just still loading */
|
||||
error: Error | null,
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -44,7 +46,7 @@ type MachinePluginsState = {
|
||||
export function useMachinePlugins(): MachinePluginsState {
|
||||
const control = useContext(ControlContext);
|
||||
const account = useAccount();
|
||||
const [hosts, hostsSynced] = useHosts();
|
||||
const [hosts, hostsSynced, hostsError] = useHosts();
|
||||
const [systems, systemsSynced] = useSystems();
|
||||
// Lists fetched directly, used until the system metrics of the machine update
|
||||
const [listed, setListed] = useState(new Map<string, ListedPlugins>());
|
||||
@@ -88,8 +90,12 @@ export function useMachinePlugins(): MachinePluginsState {
|
||||
}
|
||||
}, [canList, hostsSynced, connectedKey]);
|
||||
|
||||
if (!canList || !hostsSynced || (!systemsSynced && !listed.size)) {
|
||||
return { machines: undefined, unknown: [], refresh };
|
||||
if (!canList) {
|
||||
const error = new lib.PermissionError("Missing permission core.plugin.list");
|
||||
return { machines: undefined, unknown: [], refresh, error };
|
||||
}
|
||||
if (!hostsSynced || (!systemsSynced && !listed.size)) {
|
||||
return { machines: undefined, unknown: [], refresh, error: hostsError };
|
||||
}
|
||||
const machines: MachinePlugins[] = [];
|
||||
const unknown: Machine[] = [];
|
||||
@@ -105,7 +111,7 @@ export function useMachinePlugins(): MachinePluginsState {
|
||||
unknown.push(machine);
|
||||
}
|
||||
}
|
||||
return { machines, unknown, refresh };
|
||||
return { machines, unknown, refresh, error: null };
|
||||
}
|
||||
|
||||
/** Latest version published on npm of each package */
|
||||
@@ -160,7 +166,7 @@ export function PluginVersions(props: { status: PluginStatus, latest?: string })
|
||||
.sort(compareVersions)
|
||||
.reverse();
|
||||
const count = (filter: (machine: MachinePlugin) => boolean) => machines.filter(filter).length;
|
||||
const missing = count(machine => (!machine.plugin || Boolean(machine.plugin.removed)) && !machine.nameTaken);
|
||||
const missing = count(machine => machine.state === "missing" || machine.state === "dependencyTaken");
|
||||
|
||||
return <>
|
||||
{versions.map(version => {
|
||||
@@ -175,14 +181,14 @@ export function PluginVersions(props: { status: PluginStatus, latest?: string })
|
||||
</div>;
|
||||
})}
|
||||
{count(isPending) > 0 && <CountLine label="Restart pending on" count={count(isPending)} />}
|
||||
{count(machine => machine.disabled) > 0 && <CountLine
|
||||
label="Disabled on" count={count(machine => machine.disabled)} type="secondary"
|
||||
{count(machine => machine.state === "disabled") > 0 && <CountLine
|
||||
label="Disabled on" count={count(machine => machine.state === "disabled")} type="secondary"
|
||||
/>}
|
||||
{count(machine => machine.noEntrypoint) > 0 && <CountLine
|
||||
label="No entrypoint on" count={count(machine => machine.noEntrypoint)} type="secondary"
|
||||
{count(machine => machine.state === "noEntrypoint") > 0 && <CountLine
|
||||
label="No entrypoint on" count={count(machine => machine.state === "noEntrypoint")} type="secondary"
|
||||
/>}
|
||||
{count(machine => machine.nameTaken) > 0 && <CountLine
|
||||
label="From another package on" count={count(machine => machine.nameTaken)} type="secondary"
|
||||
{count(machine => machine.state === "nameTaken") > 0 && <CountLine
|
||||
label="From another package on" count={count(machine => machine.state === "nameTaken")} type="secondary"
|
||||
/>}
|
||||
{missing > 0 && <CountLine label="Not installed on" count={missing} type="warning" />}
|
||||
{unknown.length > 0 && <CountLine label="Plugins not reported by" count={unknown.length} type="warning" />}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import React, { useEffect, useContext, useState } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import { Alert, Descriptions, Spin } from "antd";
|
||||
import { Alert, Descriptions } from "antd";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
import type { PluginWebApi } from "@clusterio/lib";
|
||||
|
||||
import ControlContext from "./ControlContext";
|
||||
import PageLayout from "./PageLayout";
|
||||
import PageHeader from "./PageHeader";
|
||||
import ResourceState from "./ResourceState";
|
||||
import SectionHeader from "./SectionHeader";
|
||||
import notify from "../util/notify";
|
||||
import useResourceState from "../util/useResourceState";
|
||||
import { usePluginInstaller } from "./PluginInstall";
|
||||
import { PluginMachinesTable, PluginUpdateButton, useLatestVersions, useMachinePlugins } from "./PluginClusterStatus";
|
||||
import { PluginStatus, computePluginStatuses, pluginStatusKey } from "../util/plugin_status";
|
||||
@@ -89,18 +89,18 @@ export default function PluginViewPage() {
|
||||
let params = useParams();
|
||||
const control = useContext(ControlContext);
|
||||
let [pluginList, setPluginList] = useState<PluginWebApi[]>();
|
||||
const [pluginListError, setPluginListError] = useState<Error | null>(null);
|
||||
let pluginName = String(params.name);
|
||||
const { machines, unknown, refresh } = useMachinePlugins();
|
||||
const { machines, unknown, refresh, error: machinesError } = useMachinePlugins();
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
let response = await fetch(`${webRoot}api/plugins`);
|
||||
if (response.ok) {
|
||||
setPluginList(await response.json());
|
||||
} else {
|
||||
notify("Failed to load plugin list");
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to load plugin list: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
})();
|
||||
setPluginList(await response.json());
|
||||
})().catch(setPluginListError);
|
||||
}, []);
|
||||
|
||||
const pluginMeta = pluginList?.find(p => p.name === pluginName);
|
||||
@@ -110,19 +110,16 @@ export default function PluginViewPage() {
|
||||
: undefined;
|
||||
const pluginInfo = control.pluginInfos.get(pluginName);
|
||||
const pluginTitle = pluginInfo?.title ?? status?.title ?? pluginName;
|
||||
// Machines are only needed for plugins not on the controller, which isn't known until the list has loaded
|
||||
const error = pluginListError ?? (pluginList ? machinesError : null);
|
||||
const state = useResourceState(
|
||||
pluginList && (pluginMeta ?? status), Boolean(pluginList && machines), error, pluginName
|
||||
);
|
||||
let nav = [{ name: "Plugins", path: "/plugins" }, { name: pluginTitle }];
|
||||
if (!pluginList || (!pluginMeta && !machines)) {
|
||||
return <PageLayout nav={nav}>
|
||||
<Descriptions bordered size="small" title={pluginTitle} />
|
||||
<Spin size="large" />
|
||||
</PageLayout>;
|
||||
}
|
||||
|
||||
if (!pluginMeta && !status) {
|
||||
return <PageLayout nav={nav}>
|
||||
<PageHeader title="Plugin not found" />
|
||||
<p>Plugin with name {pluginName} was not found on the controller or any host.</p>
|
||||
</PageLayout>;
|
||||
if (state !== "ok") {
|
||||
return <ResourceState
|
||||
state={state} type="Plugin" id={pluginTitle} nav={nav} listPath="/plugins" error={error}
|
||||
/>;
|
||||
}
|
||||
|
||||
return <PageLayout nav={nav}>
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import React from "react";
|
||||
import { Result, ResultProps, Spin } from "antd";
|
||||
|
||||
import Link from "./Link";
|
||||
import PageHeader from "./PageHeader";
|
||||
import PageLayout from "./PageLayout";
|
||||
import type { ResourceStatus } from "../util/useResourceState";
|
||||
|
||||
type ResourceStateProps = {
|
||||
/** Status from useResourceState */
|
||||
state: ResourceStatus;
|
||||
/** Capitalised name of the kind of resource, e.g. "Mod pack" */
|
||||
type: string;
|
||||
/** Id or name of the resource */
|
||||
id: number | string;
|
||||
nav: React.ComponentProps<typeof PageLayout>["nav"];
|
||||
/** Page listing this kind of resource */
|
||||
listPath: string;
|
||||
/** Error from the subscription */
|
||||
error: Error | null;
|
||||
};
|
||||
|
||||
/** Whole page to render in place of a view page when its resource can't be shown */
|
||||
export default function ResourceState(props: ResourceStateProps) {
|
||||
const { state, type, id, nav } = props;
|
||||
if (state === "ok") {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (state === "loading") {
|
||||
return <PageLayout nav={nav}>
|
||||
<PageHeader title={String(id)} />
|
||||
<Spin size="large" />
|
||||
</PageLayout>;
|
||||
}
|
||||
|
||||
const results: Record<typeof state, ResultProps> = {
|
||||
missing: { status: "warning", title: `${type} not found`, subTitle: `${type} ${id} was not found.` },
|
||||
deleted: { status: "warning", title: `${type} ${id} has been deleted` },
|
||||
error: { status: "error", title: `Could not load ${type.toLowerCase()}`, subTitle: props.error?.message },
|
||||
};
|
||||
|
||||
return <PageLayout nav={nav}>
|
||||
<Result
|
||||
{...results[state]}
|
||||
extra={<Link to={props.listPath}>Back to {type.toLowerCase()} list</Link>}
|
||||
/>
|
||||
</PageLayout>;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useEffect, useContext, useState, useMemo } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { Button, Checkbox, Col, Grid, Input, Popconfirm, Row, Space, Spin, Tooltip } from "antd";
|
||||
import { Button, Checkbox, Col, Grid, Input, Popconfirm, Row, Space, Tooltip } from "antd";
|
||||
import { ExclamationCircleOutlined, StarOutlined, DeleteOutlined} from "@ant-design/icons";
|
||||
|
||||
import * as lib from "@clusterio/lib";
|
||||
@@ -12,7 +12,9 @@ import PageHeader from "./PageHeader";
|
||||
import PageLayout from "./PageLayout";
|
||||
import PluginExtra from "./PluginExtra";
|
||||
import ResourceNotes from "./ResourceNotes";
|
||||
import ResourceState from "./ResourceState";
|
||||
import { notifyErrorHandler } from "../util/notify";
|
||||
import useResourceState from "../util/useResourceState";
|
||||
|
||||
|
||||
/** Splits a permission name into parts, removing the last part */
|
||||
@@ -88,7 +90,7 @@ function PermissionItem({
|
||||
|
||||
/** A group of permissions; includes a title, clear and select all buttons, and the permission items */
|
||||
function PermissionGroup({
|
||||
groupName, permissions, canUpdate, baselineState, permissionState, setPermissionState,
|
||||
groupName, permissions, canUpdate, baselineState, permissionState, setPermissions,
|
||||
}: {
|
||||
groupName: string;
|
||||
permissions: lib.Permission[];
|
||||
@@ -96,17 +98,10 @@ function PermissionGroup({
|
||||
|
||||
baselineState: Record<string, boolean>;
|
||||
permissionState: Record<string, boolean>;
|
||||
setPermissionState: React.Dispatch<React.SetStateAction<Record<string, boolean>>>;
|
||||
setEdited?: (value: boolean) => void;
|
||||
setPermissions: (names: string[], value: boolean) => void;
|
||||
}) {
|
||||
function setGroup(value: boolean) {
|
||||
setPermissionState((prev: any) => {
|
||||
const next = { ...prev };
|
||||
for (let p of permissions) {
|
||||
next[p.name] = value;
|
||||
}
|
||||
return next;
|
||||
});
|
||||
setPermissions(permissions.map(p => p.name), value);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -129,7 +124,7 @@ function PermissionGroup({
|
||||
checked={permissionState[p.name]}
|
||||
baseline={baselineState[p.name]}
|
||||
disabled={!canUpdate}
|
||||
onChange={v => setPermissionState((prev: any) => ({ ...prev, [p.name]: v }))}
|
||||
onChange={v => setPermissions([p.name], v)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -169,12 +164,13 @@ export default function RoleViewPage() {
|
||||
const navigate = useNavigate();
|
||||
const account = useAccount();
|
||||
const control = useContext(ControlContext);
|
||||
const [role, synced] = useRole(roleId);
|
||||
const [role, synced, error] = useRole(roleId);
|
||||
const state = useResourceState(role, synced, error, roleId);
|
||||
|
||||
const [name, setName] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [permissionState, setPermissionState] = useState<Record<string, boolean>>({});
|
||||
const [baselineState, setBaselineState] = useState<Record<string, boolean>>({});
|
||||
// Local edits on top of the live role
|
||||
const [nameEdit, setNameEdit] = useState<string>();
|
||||
const [descriptionEdit, setDescriptionEdit] = useState<string>();
|
||||
const [permissionEdits, setPermissionEdits] = useState<Record<string, boolean>>({});
|
||||
const [search, setSearch] = useState("");
|
||||
// Hidden below lg, where the site sider leaves too little room; undefined until measured
|
||||
const screens = Grid.useBreakpoint();
|
||||
@@ -183,38 +179,41 @@ export default function RoleViewPage() {
|
||||
const allPermissions = useMemo(() => [...lib.permissions.values()], []);
|
||||
const canUpdate = Boolean(account.hasPermission("core.role.update"));
|
||||
|
||||
const baselineState = useMemo(() => Object.fromEntries(
|
||||
allPermissions.map(p => [p.name, Boolean(role?.permissions.has(p.name))])
|
||||
), [role, allPermissions]);
|
||||
|
||||
// Drop edits that now match the role, and all edits if we can no longer apply them
|
||||
useEffect(() => {
|
||||
if (!role) {
|
||||
if (!role || !canUpdate) {
|
||||
setNameEdit(undefined);
|
||||
setDescriptionEdit(undefined);
|
||||
setPermissionEdits(prev => (Object.keys(prev).length ? {} : prev));
|
||||
return;
|
||||
}
|
||||
setNameEdit(prev => (prev === role.name ? undefined : prev));
|
||||
setDescriptionEdit(prev => (prev === role.description ? undefined : prev));
|
||||
setPermissionEdits(prev => {
|
||||
const next = Object.fromEntries(Object.entries(prev).filter(([k, v]) => v !== baselineState[k]));
|
||||
return Object.keys(next).length === Object.keys(prev).length ? prev : next;
|
||||
});
|
||||
}, [role, canUpdate, baselineState]);
|
||||
|
||||
const base = Object.fromEntries(
|
||||
allPermissions.map(p => [p.name, role.permissions.has(p.name)])
|
||||
);
|
||||
useEffect(() => {
|
||||
setNameEdit(undefined);
|
||||
setDescriptionEdit(undefined);
|
||||
setPermissionEdits({});
|
||||
}, [roleId]);
|
||||
|
||||
setName(role.name);
|
||||
setDescription(role.description);
|
||||
setPermissionState(base);
|
||||
setBaselineState(base);
|
||||
}, [role, allPermissions]);
|
||||
|
||||
// If no role then display either the loading screen or the not found screen
|
||||
if (!role) {
|
||||
const nav = [{ name: "Roles", path: "/roles" }, { name: String(roleId) }];
|
||||
|
||||
if (!synced) {
|
||||
return <PageLayout nav={nav}>
|
||||
<PageHeader title={String(roleId)} />
|
||||
<Spin size="large" />
|
||||
</PageLayout>;
|
||||
}
|
||||
|
||||
return <PageLayout nav={nav}>
|
||||
<PageHeader title="Role not found" />
|
||||
<p>Role with id {roleId} was not found on the controller.</p>
|
||||
</PageLayout>;
|
||||
return <ResourceState state={state} type="Role" id={roleId} nav={nav} listPath="/roles" error={error} />;
|
||||
}
|
||||
|
||||
const name = nameEdit ?? role.name;
|
||||
const description = descriptionEdit ?? role.description;
|
||||
const permissionState = { ...baselineState, ...permissionEdits };
|
||||
|
||||
// Apply the filter by searching all permission fields
|
||||
const filtered = allPermissions.filter(p => {
|
||||
const q = search.toLowerCase();
|
||||
@@ -243,27 +242,33 @@ export default function RoleViewPage() {
|
||||
const grantedGroups = new Set(allPermissions.filter(p => permissionState[p.name]).map(p => getGroupName(p.name)));
|
||||
|
||||
// Check if any changes have been made to the permissions or role metadata
|
||||
const permissionChanged = Object.keys(permissionState).some(k => permissionState[k] !== baselineState[k]);
|
||||
const permissionChanged = Object.keys(permissionEdits).some(k => permissionEdits[k] !== baselineState[k]);
|
||||
const metaChanged = name !== role.name || description !== role.description;
|
||||
const edited = permissionChanged || metaChanged;
|
||||
|
||||
/** Applies all pending changes */
|
||||
function applyChanges() {
|
||||
const newPermissions = Object.entries(permissionState).filter(([, v]) => v).map(([k]) => k);
|
||||
control.send(new lib.RoleUpdateRequest(roleId, name || "", description || "", newPermissions))
|
||||
.then(() => {
|
||||
setBaselineState(permissionState);
|
||||
})
|
||||
.catch(notifyErrorHandler("Error applying changes"));
|
||||
function setPermissions(names: string[], value: boolean) {
|
||||
setPermissionEdits(prev => {
|
||||
const next = { ...prev };
|
||||
for (let permissionName of names) {
|
||||
next[permissionName] = value;
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
/** Revert any pending changes */
|
||||
function revertChanges() {
|
||||
setPermissionState(baselineState);
|
||||
if (role) {
|
||||
setName(role.name);
|
||||
setDescription(role.description);
|
||||
}
|
||||
setNameEdit(undefined);
|
||||
setDescriptionEdit(undefined);
|
||||
setPermissionEdits({});
|
||||
}
|
||||
|
||||
/** Applies all pending changes */
|
||||
function applyChanges() {
|
||||
const newPermissions = Object.entries(permissionState).filter(([, v]) => v).map(([k]) => k);
|
||||
control.send(new lib.RoleUpdateRequest(roleId, name, description, newPermissions))
|
||||
.then(revertChanges)
|
||||
.catch(notifyErrorHandler("Error applying changes"));
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -320,12 +325,12 @@ export default function RoleViewPage() {
|
||||
|
||||
<div style={{ marginBottom: 16, display: "flex", alignItems: "center", gap: 12 }}>
|
||||
<label style={{ width: 110, flexShrink: 0 }}>Name</label>
|
||||
<Input value={name} disabled={!canUpdate} onChange={e => setName(e.target.value)} />
|
||||
<Input value={name} disabled={!canUpdate} onChange={e => setNameEdit(e.target.value)} />
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: 16, display: "flex", alignItems: "center", gap: 12 }}>
|
||||
<label style={{ width: 110, flexShrink: 0 }}>Description</label>
|
||||
<Input value={description} disabled={!canUpdate} onChange={e => setDescription(e.target.value)} />
|
||||
<Input value={description} disabled={!canUpdate} onChange={e => setDescriptionEdit(e.target.value)} />
|
||||
</div>
|
||||
|
||||
<ResourceNotes resourceType="role" resourceId={roleId} />
|
||||
@@ -363,7 +368,7 @@ export default function RoleViewPage() {
|
||||
permissions={permissions}
|
||||
permissionState={permissionState}
|
||||
baselineState={baselineState}
|
||||
setPermissionState={setPermissionState}
|
||||
setPermissions={setPermissions}
|
||||
canUpdate={canUpdate}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -2,7 +2,7 @@ import React, { useEffect, useContext, useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import {
|
||||
Button, Col, Descriptions, Form, Input, Popconfirm,
|
||||
Row, Table, Tag, Select, Space, Spin, Switch,
|
||||
Row, Table, Tag, Select, Space, Switch,
|
||||
} from "antd";
|
||||
import DeleteOutlined from "@ant-design/icons/DeleteOutlined";
|
||||
|
||||
@@ -18,7 +18,9 @@ import PageLayout from "./PageLayout";
|
||||
import PluginExtra from "./PluginExtra";
|
||||
import SectionHeader from "./SectionHeader";
|
||||
import ResourceNotes from "./ResourceNotes";
|
||||
import ResourceState from "./ResourceState";
|
||||
import useRowNavigation from "../util/useRowNavigation";
|
||||
import useResourceState from "../util/useResourceState";
|
||||
import Link from "./Link";
|
||||
import notify, { notifyErrorHandler } from "../util/notify";
|
||||
import { formatDuration } from "../util/time_format";
|
||||
@@ -40,8 +42,9 @@ export default function UserViewPage() {
|
||||
let account = useAccount();
|
||||
let control = useContext(ControlContext);
|
||||
let [instances] = useInstances();
|
||||
const [user, synced] = useUser(userName);
|
||||
let [roles] = useRoles();
|
||||
const [user, synced, error] = useUser(userName);
|
||||
const state = useResourceState(user, synced, error, userName);
|
||||
let [roles, rolesSynced] = useRoles();
|
||||
let [form] = Form.useForm();
|
||||
const statsTable = useTableQueryState<[number, lib.PlayerStats]>({
|
||||
namespace: "stats", defaultSortKey: "instance",
|
||||
@@ -62,22 +65,25 @@ export default function UserViewPage() {
|
||||
}
|
||||
}, [account, form, user, banReasonDirty]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user || !account.hasPermission("core.user.update_roles")) {
|
||||
return;
|
||||
}
|
||||
const current: number[] = form.getFieldValue("roles") ?? [];
|
||||
// Keep local edits, but drop roles deleted since
|
||||
const next = rolesDirty
|
||||
? current.filter(id => !rolesSynced || roles.has(id))
|
||||
: [...user.roleIds];
|
||||
if (next.length !== current.length || next.some((id, i) => id !== current[i])) {
|
||||
form.setFieldsValue({ "roles": next });
|
||||
}
|
||||
}, [account, form, user, roles, rolesSynced, rolesDirty]);
|
||||
|
||||
let nav = [{ name: "Users", path: "/users" }, { name: userName }];
|
||||
if (!user) {
|
||||
if (!synced) {
|
||||
return <PageLayout nav={nav}>
|
||||
<PageHeader title={userName} />
|
||||
<Spin size="large" />
|
||||
</PageLayout>;
|
||||
}
|
||||
|
||||
return <PageLayout nav={nav}>
|
||||
<PageHeader title="User not found" />
|
||||
<p>User with name {userName} was not found on the controller.</p>
|
||||
</PageLayout>;
|
||||
return <ResourceState state={state} type="User" id={userName} nav={nav} listPath="/users" error={error} />;
|
||||
}
|
||||
|
||||
// TODO: Update displayed roles when user roles change and have not been edited locally
|
||||
let roleSelector = <Form.Item
|
||||
noStyle
|
||||
name="roles"
|
||||
|
||||
@@ -40,6 +40,7 @@ export { default as PageLayout } from "./components/PageLayout";
|
||||
export { default as SavesList } from "./components/SavesList";
|
||||
export { default as SectionHeader } from "./components/SectionHeader";
|
||||
export { default as ResourceNotes } from "./components/ResourceNotes";
|
||||
export { default as ResourceState } from "./components/ResourceState";
|
||||
|
||||
export { default as Link } from "./components/Link";
|
||||
|
||||
@@ -48,3 +49,4 @@ export { default as FactorioIcon } from "./components/FactorioIcon";
|
||||
export { default as useTableQueryState } from "./util/useTableQueryState";
|
||||
export { default as useColumnSearch } from "./util/useColumnSearch";
|
||||
export { default as useRowNavigation } from "./util/useRowNavigation";
|
||||
export { default as useResourceState, type ResourceStatus } from "./util/useResourceState";
|
||||
@@ -2,8 +2,8 @@ import { useCallback, useContext, useSyncExternalStore } from "react";
|
||||
import ControlContext from "../components/ControlContext";
|
||||
|
||||
export function useHost(id?: number) {
|
||||
const [hosts, synced] = useHosts();
|
||||
return [id !== undefined ? hosts.get(id) : undefined, synced] as const;
|
||||
const [hosts, synced, error] = useHosts();
|
||||
return [id !== undefined ? hosts.get(id) : undefined, synced, error] as const;
|
||||
}
|
||||
|
||||
export function useHosts() {
|
||||
@@ -11,3 +11,10 @@ export function useHosts() {
|
||||
const subscribe = useCallback((callback: () => void) => control.hosts.subscribe(callback), [control]);
|
||||
return useSyncExternalStore(subscribe, () => control.hosts.getSnapshot());
|
||||
}
|
||||
|
||||
/** Requests from hosts waiting to be approved, empty if the account may not approve hosts */
|
||||
export function useHostPairings() {
|
||||
const control = useContext(ControlContext);
|
||||
const subscribe = useCallback((callback: () => void) => control.hostPairings.subscribe(callback), [control]);
|
||||
return useSyncExternalStore(subscribe, () => control.hostPairings.getSnapshot());
|
||||
}
|
||||
@@ -4,8 +4,8 @@ import { Config, InstanceConfigGetRequest } from "@clusterio/lib";
|
||||
import ControlContext from "../components/ControlContext";
|
||||
|
||||
export function useInstance(id?: number) {
|
||||
const [instances, synced] = useInstances();
|
||||
return [id !== undefined ? instances.get(id) : undefined, synced] as const;
|
||||
const [instances, synced, error] = useInstances();
|
||||
return [id !== undefined ? instances.get(id) : undefined, synced, error] as const;
|
||||
}
|
||||
|
||||
export function useInstances() {
|
||||
|
||||
@@ -4,8 +4,8 @@ import { defaultModPackStore } from "../store/default_mod_pack_store";
|
||||
|
||||
|
||||
export function useModPack(id?: number) {
|
||||
const [modPacks, synced] = useModPacks();
|
||||
return [id !== undefined ? modPacks.get(id) : undefined, synced] as const;
|
||||
const [modPacks, synced, error] = useModPacks();
|
||||
return [id !== undefined ? modPacks.get(id) : undefined, synced, error] as const;
|
||||
}
|
||||
|
||||
export function useModPacks() {
|
||||
|
||||
@@ -12,8 +12,8 @@ export function useRolesOfUser(user?: lib.UserDetails) {
|
||||
}
|
||||
|
||||
export function useRole(id?: number) {
|
||||
const [roles, synced] = useRoles();
|
||||
return [id !== undefined ? roles.get(id) : undefined, synced] as const;
|
||||
const [roles, synced, error] = useRoles();
|
||||
return [id !== undefined ? roles.get(id) : undefined, synced, error] as const;
|
||||
}
|
||||
|
||||
export function useRoles() {
|
||||
|
||||
@@ -89,8 +89,8 @@ export function sortLastSeen(
|
||||
}
|
||||
|
||||
export function useUser(name?: string) {
|
||||
const [users, synced] = useUsers();
|
||||
return [name !== undefined ? users.get(name.toLowerCase()) : undefined, synced] as const;
|
||||
const [users, synced, error] = useUsers();
|
||||
return [name !== undefined ? users.get(name.toLowerCase()) : undefined, synced, error] as const;
|
||||
}
|
||||
|
||||
export function useUsers() {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import * as lib from "@clusterio/lib";
|
||||
|
||||
/**
|
||||
* Subscriber for the requests from hosts waiting to be approved
|
||||
*
|
||||
* The requests only live in the controller's memory and it does not tell
|
||||
* subscribers about requests removed while nothing was subscribed, so they
|
||||
* are cleared when subscribing again after the last handler unsubscribed.
|
||||
*/
|
||||
export class HostPairingSubscriber extends lib.MapSubscriber<lib.HostPairingUpdatesEvent> {
|
||||
private _handlers = 0;
|
||||
|
||||
/**
|
||||
* @param control - Link to the controller.
|
||||
* @param permitted - Returns true if the account may approve hosts.
|
||||
*/
|
||||
constructor(control: lib.Link, permitted: () => boolean) {
|
||||
super(lib.HostPairingUpdatesEvent, control, undefined, permitted);
|
||||
}
|
||||
|
||||
override subscribe(handler: lib.EventSubscriberCallback<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;
|
||||
});
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -16,18 +16,26 @@ export type Machine = {
|
||||
};
|
||||
export type MachinePlugins = Machine & { plugins: lib.PluginDetails[] };
|
||||
|
||||
/**
|
||||
* What happens with a plugin on one machine, in order of precedence
|
||||
*
|
||||
* - nameTaken: Another package here provides the plugin by the same name, startup skips this one
|
||||
* - dependencyTaken: Not installed, and the group's npm package name is a dependency here for
|
||||
* another plugin, such as an alias
|
||||
* - missing: Not installed
|
||||
* - noEntrypoint: Installed but never loaded on this machine as it has no entrypoint for it
|
||||
* - disabled: Installed but not loaded after the next restart
|
||||
* - enabled: Installed and loaded after the next restart
|
||||
*/
|
||||
export type MachinePluginState =
|
||||
"nameTaken" | "dependencyTaken" | "missing" | "noEntrypoint" | "disabled" | "enabled";
|
||||
|
||||
/** A plugin on one machine, with the version it runs now and the version it will run after a restart */
|
||||
export type MachinePlugin = Machine & {
|
||||
plugin?: lib.PluginDetails,
|
||||
state: MachinePluginState,
|
||||
running?: string,
|
||||
afterRestart?: string,
|
||||
disabled: boolean,
|
||||
/** Installed but never loaded on this machine as it has no entrypoint for it */
|
||||
noEntrypoint: boolean,
|
||||
/** The group's npm package name is a dependency here for another plugin, such as an alias */
|
||||
dependencyTaken: boolean,
|
||||
/** Another package here provides the plugin by the same name, startup skips this one */
|
||||
nameTaken: boolean,
|
||||
/** A host from before installedVersion was reported, it can't install a specific version */
|
||||
oldHost: boolean,
|
||||
};
|
||||
@@ -53,45 +61,51 @@ export function compareVersions(a: string, b: string) {
|
||||
return strcmp(a, b);
|
||||
}
|
||||
|
||||
/** Not uninstalled since startup and not skipped by name, so its plugin name is in use */
|
||||
function holdsName(plugin: lib.PluginDetails) {
|
||||
return !plugin.removed && plugin.state !== "pendingInstall" && plugin.state !== "nameTaken";
|
||||
}
|
||||
|
||||
function machinePluginState(
|
||||
plugins: lib.PluginDetails[], plugin: lib.PluginDetails | undefined, key: string, names: Set<string>,
|
||||
): MachinePluginState {
|
||||
if (plugin?.state === "nameTaken") {
|
||||
return "nameTaken";
|
||||
}
|
||||
const absent = !plugin || plugin.removed;
|
||||
if ((absent || plugin.state === "pendingInstall") && plugins.some(
|
||||
candidate => pluginStatusKey(candidate) !== key && names.has(candidate.name) && holdsName(candidate)
|
||||
)) {
|
||||
return "nameTaken";
|
||||
}
|
||||
if (absent) {
|
||||
return plugins.some(candidate => candidate.dependencyName === key && !candidate.removed)
|
||||
? "dependencyTaken" : "missing";
|
||||
}
|
||||
if (plugin.state === "noEntrypoint") {
|
||||
return "noEntrypoint";
|
||||
}
|
||||
return plugin.loadsOnRestart ? "enabled" : "disabled";
|
||||
}
|
||||
|
||||
/** The plugin with the given key on one machine, names are the plugin names known for that key */
|
||||
function machinePlugin(machine: MachinePlugins, key: string, names: Set<string>): MachinePlugin {
|
||||
const { plugins, ...rest } = machine;
|
||||
// A package removed and installed again is listed twice, the removed one may still be running
|
||||
const candidates = plugins.filter(candidate => pluginStatusKey(candidate) === key);
|
||||
const plugin = candidates.find(candidate => !candidate.removed) ?? candidates[0];
|
||||
const absent = !plugin || Boolean(plugin.removed);
|
||||
const dependencyTaken = absent && plugins.some(
|
||||
candidate => candidate.dependencyName === key && !candidate.removed
|
||||
);
|
||||
const nameTaken = Boolean(plugin?.nameTaken) || (absent || Boolean(plugin.pendingInstall)) && plugins.some(
|
||||
candidate => (
|
||||
pluginStatusKey(candidate) !== key && names.has(candidate.name)
|
||||
&& !candidate.removed && !candidate.pendingInstall && !candidate.nameTaken
|
||||
)
|
||||
);
|
||||
const noEntrypoint = Boolean(plugin?.noEntrypoint);
|
||||
const state = machinePluginState(plugins, plugin, key, names);
|
||||
const oldHost = !machine.isController && plugins.length > 0 && plugins.every(
|
||||
candidate => candidate.installedVersion === undefined && !candidate.removed
|
||||
);
|
||||
const entry: MachinePlugin = {
|
||||
...rest, plugin, disabled: false, noEntrypoint, dependencyTaken, nameTaken, oldHost,
|
||||
return {
|
||||
...rest,
|
||||
plugin,
|
||||
state,
|
||||
oldHost,
|
||||
running: candidates.find(candidate => candidate.loaded)?.version,
|
||||
afterRestart: state === "enabled" && plugin ? plugin.installedVersion ?? plugin.version : undefined,
|
||||
};
|
||||
// What runs now follows loaded, what runs after a restart follows enabled and what is on disk
|
||||
entry.running = candidates.find(candidate => candidate.loaded)?.version;
|
||||
if (nameTaken) {
|
||||
return entry;
|
||||
}
|
||||
if (plugin?.pendingInstall) {
|
||||
// Plugins load by default, so a new install runs after the next restart
|
||||
entry.afterRestart = plugin.installedVersion ?? plugin.version;
|
||||
} else if (plugin && !plugin.removed && !noEntrypoint) {
|
||||
if (plugin.enabled) {
|
||||
entry.afterRestart = plugin.installedVersion ?? plugin.version;
|
||||
} else {
|
||||
entry.disabled = true;
|
||||
}
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
/** Group the plugin lists of every machine by plugin */
|
||||
@@ -107,7 +121,7 @@ export function computePluginStatuses(
|
||||
if (!titles.has(key) || plugin.loaded) {
|
||||
titles.set(key, plugin.title);
|
||||
}
|
||||
if (!plugin.pendingInstall && !plugin.nameTaken) {
|
||||
if (plugin.state !== "pendingInstall" && plugin.state !== "nameTaken") {
|
||||
pluginNames.set(key, (pluginNames.get(key) ?? new Set()).add(plugin.name));
|
||||
}
|
||||
}
|
||||
@@ -154,15 +168,15 @@ export function planUpdate(
|
||||
if (installed && compareVersions(plugin.installedVersion ?? plugin.version, version) >= 0) {
|
||||
continue;
|
||||
}
|
||||
const kind = !installed || plugin.pendingInstall ? "install" : "update";
|
||||
const kind = !installed || plugin.state === "pendingInstall" ? "install" : "update";
|
||||
const skip = (reason: string, skipKind: PackageOperation["kind"] = kind) => {
|
||||
plan.skipped.push({ kind: skipKind, target, reason });
|
||||
};
|
||||
if (machine.offline) {
|
||||
skip("offline");
|
||||
} else if (machine.nameTaken) {
|
||||
} else if (machine.state === "nameTaken") {
|
||||
skip("another package provides this plugin", "install");
|
||||
} else if (machine.dependencyTaken) {
|
||||
} else if (machine.state === "dependencyTaken") {
|
||||
skip(`another package is installed as ${status.npmPackage}`, "install");
|
||||
} else if (installed && !plugin.npmPackage) {
|
||||
// An alias, private or local package, installing the group's npm package would replace it
|
||||
@@ -211,18 +225,20 @@ export function machineStatusLabels(machine: MachinePlugin) {
|
||||
if (machine.offline) {
|
||||
labels.push("Offline");
|
||||
}
|
||||
if (machine.nameTaken) {
|
||||
if (machine.state === "nameTaken") {
|
||||
labels.push("Another package provides this plugin");
|
||||
} else if (!machine.plugin || machine.plugin.removed) {
|
||||
labels.push(machine.dependencyTaken ? "Another package is installed by this name" : "Not installed");
|
||||
} else if (machine.state === "dependencyTaken") {
|
||||
labels.push("Another package is installed by this name");
|
||||
} else if (machine.state === "missing") {
|
||||
labels.push("Not installed");
|
||||
} else {
|
||||
if (!machine.plugin.npmPackage) {
|
||||
if (!machine.plugin?.npmPackage) {
|
||||
labels.push("Not installed from npm");
|
||||
}
|
||||
if (machine.noEntrypoint) {
|
||||
if (machine.state === "noEntrypoint") {
|
||||
labels.push("No entrypoint for this machine");
|
||||
}
|
||||
if (machine.disabled) {
|
||||
if (machine.state === "disabled") {
|
||||
labels.push("Disabled");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { useRef } from "react";
|
||||
|
||||
export type ResourceStatus = "loading" | "ok" | "missing" | "deleted" | "error";
|
||||
|
||||
export function getResourceStatus(
|
||||
exists: boolean,
|
||||
seen: boolean,
|
||||
synced: boolean,
|
||||
error: Error | null,
|
||||
): ResourceStatus {
|
||||
if (exists) {
|
||||
return "ok";
|
||||
}
|
||||
// A retry only clears the error when its response arrives, which can be after the update that synced it
|
||||
if (synced) {
|
||||
return seen ? "deleted" : "missing";
|
||||
}
|
||||
return error ? "error" : "loading";
|
||||
}
|
||||
|
||||
/**
|
||||
* Status of the resource shown on a view page, for use with the ResourceState component
|
||||
*
|
||||
* @param value - The resource, undefined or null if the subscription does not have it.
|
||||
* @param synced - The synced property from the subscription.
|
||||
* @param error - The error property from the subscription.
|
||||
* @param id - Identifies the resource shown, the router reuses the page when navigating between resources.
|
||||
* @returns "ok" if there is a value to show, otherwise why there isn't.
|
||||
*/
|
||||
export default function useResourceState(value: unknown, synced: boolean, error: Error | null, id: number | string) {
|
||||
const seenId = useRef<number | string>(undefined);
|
||||
const exists = value !== undefined && value !== null;
|
||||
if (exists) {
|
||||
seenId.current = id;
|
||||
}
|
||||
return getResourceStatus(exists, seenId.current === id, synced, error);
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"entryPoints": ["src/index.ts"],
|
||||
"includeVersion": true
|
||||
}
|
||||
Reference in new issue
Block a user