Address review of host pairing

Revoking a host now unassigns its instances instead of being refused
while it has any, and removes its system metrics.

Approving and revoking no longer force a save. Hosts are saved by
autosave and on exit like everything else, which also removes the
approving state from pairing requests.

The approval code and link are logged as warnings so they show up in
the systemd service, which only prints warnings and above. The pairing
limits are now the controller.host_pairing_timeout and
controller.host_pairing_max_pending config values, 0 removes the limit.

Subscribers take an optional permitted function, used for the pairing
requests instead of overrides in a subclass.
This commit is contained in:
Danielv123 committed 2026-10-31 16:31:45 +01:00
1 parent e5701a8dae
commit 49a0b27d29
29 files changed
+356 -418

No files matched your search

+13 -14
View File
@@ -255,26 +255,25 @@ export default class ControlConnection extends BaseConnection {
throw new lib.NotFoundError(`Unknown host id (${request.hostId})`);
}
const assigned = [...this._controller.instances.values()].filter(
instance => instance.config.get("instance.assigned_host") === request.hostId
);
if (assigned.length) {
const names = assigned.map(instance => instance.config.get("instance.name")).join(", ");
throw new lib.ConflictError(
`Cannot revoke host ${host.name} while instances are assigned to it: ${names}`
);
}
this._controller.hosts.delete(host);
this._controller.deleteNote("host", request.hostId, this.user.name);
const system = this._controller.systems.getMutable(request.hostId);
if (system) {
this._controller.systems.delete(system);
}
// Disconnect before saving so the host is cut off even if the save fails.
// 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();
}
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})`);
await this._controller.hosts.save();
}
async handleHostListRequest(): Promise<lib.HostDetails[]> {
@@ -283,11 +282,11 @@ export default class ControlConnection extends BaseConnection {
async handleHostPairingListRequest(): Promise<lib.HostPairingDetails[]> {
this._controller.hostPairing.prune();
return [...this._controller.hostPairing.requests.values()];
return [...this._controller.hostPairing.records.values()];
}
async handleHostPairingApproveRequest(request: lib.HostPairingApproveRequest) {
return await this._controller.hostPairing.approve(request.code, request.name, this.user.name);
return this._controller.hostPairing.approve(request.code, request.name, this.user.name);
}
async handleHostPairingRejectRequest(request: lib.HostPairingRejectRequest) {
+3 -3
View File
@@ -323,7 +323,7 @@ export default class Controller {
// Handle updates for datastores
this.systems.on("update", this.systemsUpdated.bind(this));
this.hosts.on("update", this.hostsUpdated.bind(this));
this.hostPairing.requests.on("update", this.hostPairingRequestsUpdated.bind(this));
this.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));
@@ -373,7 +373,6 @@ export default class Controller {
async _startInternal(args: ControllerArgs) {
this.logDirectory = args.logDirectory;
this.hostPairing.start();
this.clusterLogIndex = await lib.LogIndex.load(path.join(this.logDirectory, "cluster"));
this.clusterLogBuildInterval = setInterval(() => {
@@ -496,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();
@@ -1062,7 +1062,7 @@ export default class Controller {
if (request.action === "unsubscribe") {
return null;
}
const requests = [...this.hostPairing.requests.values()].filter(
const requests = [...this.hostPairing.records.values()].filter(
pairing => pairing.updatedAtMs > request.lastRequestTimeMs,
);
return requests.length ? new lib.HostPairingUpdatesEvent(requests) : null;
+23 -48
View File
@@ -14,10 +14,6 @@ const codeLength = 6;
/** Time a request is kept after the last poll from the host */
export const pollTimeoutMs = 30e3;
/** Maximum time a request can stay pending */
export const maxPendingMs = 60 * 60e3;
/** Maximum number of pending requests in total */
export const maxPending = 50;
/** Maximum number of pending requests from one address */
export const maxPendingPerAddress = 3;
/** Maximum length of a host name */
@@ -44,16 +40,16 @@ export class HostPairingError extends Error {
}
}
interface PairingRequest {
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" | "approving" | "approved" | "rejected",
result?: HostPairingResult,
}
} & (
{ state: "pending" | "rejected" } | { state: "approved", result: HostPairingResult }
);
/**
* Strips the IPv4 mapped prefix and groups IPv6 addresses by their /64
@@ -105,7 +101,7 @@ function generateCode() {
*/
export default class HostPairingManager {
/** Pending requests by code, broadcast to subscribed control links */
requests = new lib.SubscribableDatastore<lib.HostPairingDetails>();
records = new lib.SubscribableDatastore<lib.HostPairingDetails>();
private _bySecret = new Map<string, PairingRequest>();
private _byCode = new Map<string, PairingRequest>();
private _pruneInterval?: ReturnType<typeof setInterval>;
@@ -148,28 +144,19 @@ export default class HostPairingManager {
/**
* Create an approved host with a new id and token
*
* The host record is saved to disk before this returns.
*
* @param name - Name of the host.
* @returns the id, token and name of the new host.
*/
async createHost(name: string): Promise<HostPairingResult> {
createHost(name: string): HostPairingResult {
const hosts = this._controller.hosts;
let hostId;
do {
hostId = crypto.randomInt(1, 2 ** 31);
} while (hosts.has(hostId));
const record = new HostRecord(
hosts.set(new HostRecord(
hostId, name, "", new Map(), false, "", "", Math.floor(Date.now() / 1000),
);
hosts.set(record);
try {
await hosts.save();
} catch (err) {
hosts.delete(record);
throw err;
}
));
return { hostId, token: this._controller.generateHostToken(hostId), name };
}
@@ -191,7 +178,8 @@ export default class HostPairingManager {
if (pendingFromAddress >= maxPendingPerAddress) {
throw new HostPairingError("Too many pending requests from this address", 429, 30);
}
if (this.requests.size >= maxPending) {
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);
}
@@ -209,7 +197,7 @@ export default class HostPairingManager {
};
this._bySecret.set(request.secret, request);
this._byCode.set(code, request);
this.requests.set(request.details);
this.records.set(request.details);
logger.verbose(`Host pairing request ${code} for "${name}" from ${remoteAddress}`);
return { requestId: request.secret, code };
}
@@ -229,7 +217,7 @@ export default class HostPairingManager {
request.lastPollMs = Date.now();
if (request.state === "approved") {
this._remove(request);
return request.result!;
return request.result;
}
if (request.state === "rejected") {
this._remove(request);
@@ -268,7 +256,7 @@ export default class HostPairingManager {
* @param approvedBy - Name of the user approving it, for logging.
* @returns the id of the new host.
*/
async approve(code: string, name: string | undefined, approvedBy: string) {
approve(code: string, name: string | undefined, approvedBy: string) {
const request = this._pending(code);
let hostName;
try {
@@ -277,18 +265,9 @@ export default class HostPairingManager {
throw new lib.ValidationError(err.message);
}
request.state = "approving";
let result;
try {
result = await this.createHost(hostName);
} catch (err) {
request.state = "pending";
throw err;
}
request.state = "approved";
request.result = result;
this.requests.delete(request.details);
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}`
@@ -305,7 +284,7 @@ export default class HostPairingManager {
reject(code: string, rejectedBy: string) {
const request = this._pending(code);
request.state = "rejected";
this.requests.delete(request.details);
this.records.delete(request.details);
logger.audit(
`User ${rejectedBy} rejected host ${request.details.name} with code ` +
`${request.details.code} from ${request.details.remoteAddress}`
@@ -315,26 +294,22 @@ export default class HostPairingManager {
private _remove(request: PairingRequest) {
this._bySecret.delete(request.secret);
this._byCode.delete(request.details.code);
if (this.requests.has(request.details.code)) {
this.requests.delete(request.details);
}
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()) {
if (request.state === "approving") {
continue;
}
const expired = now - request.lastPollMs > pollTimeoutMs
|| (request.state === "pending" && now - request.details.createdAtMs > maxPendingMs);
if (!expired) {
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 ` +
`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"
);
}
+6 -6
View File
@@ -256,7 +256,7 @@ function checkHostPairingRequest(req: Request, res: Response, needsRequestId: bo
}
// Request from a host for a host to join the cluster.
async function createHostPairing(req: Request, res: Response) {
function createHostPairing(req: Request, res: Response) {
if (!checkHostPairingRequest(req, res, false)) {
return;
}
@@ -279,10 +279,13 @@ async function createHostPairing(req: Request, res: Response) {
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 = await controller.hostPairing.createHost(name);
const result = controller.hostPairing.createHost(name);
logger.audit(
`User ${user.name} approved host ${result.name} (${result.hostId}) from ${remoteAddress} ` +
"with their token"
@@ -783,10 +786,7 @@ export function addRouteHandlers(app: Application) {
next();
};
const pairingJson = express.json({ limit: "4kb" });
app.post("/api/host-pairing",
noStore, pairingJson,
(req:Request, res:Response, next:any) => createHostPairing(req, res).catch(next)
);
app.post("/api/host-pairing", 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) => {
+11 -9
View File
@@ -20,7 +20,6 @@ The installer runs without prompts when all the questions for the mode are answe
## Modes
- `standalone`: controller and host on this computer. The host is approved like any other host the first time it starts.
The host is added to the controller directly and does not need to be approved.
- `controller`: controller only.
- `host`: host only, joins the cluster of an existing controller, see [Setting up a host](#setting-up-a-host).
- `ctl`: the clusterioctl command line interface only.
@@ -33,21 +32,24 @@ The installer runs without prompts when all the questions for the mode are answe
| Option | Modes | Description |
| --- | --- | --- |
| `--mode <mode>` | all | Operating mode to install. |
| `--admin <name>` | standalone, controller | Name of the admin account to create. |
| `--http-port <port>` | standalone, controller | Port the controller web interface listens on, defaults to 8080. |
| `--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>` | standalone, host | DNS name or IP address players connect to this computer with. |
| `--factorio-dir <path>` | standalone, host | Path to the Factorio installation. |
| `--self-signed-cert <path>` | standalone, host | Certificate to trust for a controller using a self-signed certificate. It is added to the run scripts. |
| `--remote-npm`, `--no-remote-npm` | standalone, controller, host | Allow or deny remote updates, plugin updates and plugin installs from the web interface. |
| `--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
@@ -84,8 +86,8 @@ 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>` and set `host.controller_token` back to `enter token here`.
The host then requests to join that controller the next time it starts.
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
+12 -11
View File
@@ -161,6 +161,9 @@ async function execCtl(args) {
return await execFile(path.join("node_modules", ".bin", `clusterioctl${scriptExt}`), args);
}
// Same characters as the controller refuses in host names.
const hostNameControlCharacters = /[\p{Cc}\u202a-\u202e\u2066-\u2069]/u;
function validateHostName(input) {
if (!input || !input.trim()) {
return "Host name may not be empty";
@@ -174,9 +177,6 @@ function validateHostName(input) {
return true;
}
// Same characters as the controller refuses in host names.
const hostNameControlCharacters = /[\p{Cc}\u202a-\u202e\u2066-\u2069]/u;
function validateControllerUrl(input) {
let url;
try {
@@ -594,6 +594,14 @@ async function inquirerMissingArgs(args) {
], 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; }
if (args.controllerUrl) { answers.controllerUrl = args.controllerUrl; }
@@ -783,7 +791,7 @@ 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",
@@ -869,7 +877,6 @@ async function main() {
if (answers.mode === "standalone") {
// Default to localhost on correct port for host in standalone mode
answers.hostName = "local";
answers.controllerUrl = `http://localhost:${answers.httpPort}/`;
}
@@ -895,12 +902,6 @@ async function main() {
/* eslint-disable no-console */
console.log(`Successfully installed ${answers.mode}`);
if (["standalone", "host"].includes(answers.mode)) {
console.log(
`Start the host with run-host${process.platform === "win32" ? ".cmd" : ".sh"}, then approve it on the ` +
`Hosts page of ${answers.controllerUrl}`
);
}
if (adminToken) {
console.log(`Admin authentication token: ${adminToken}`);
}
+3 -2
View File
@@ -132,8 +132,9 @@ Lists up all configuration entries with their currently configured values.
### `run`
Runs the host.
The host has to be approved on the controller before it can connect, which is done by running the installer in the host directory, see Setting up remote hosts in the readme of the main repository.
If the controller rejects the token of the host when it starts, for example because the host was revoked, it exits with code 8 and the run scripts created by the installer do not restart it.
A host that 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.
+26 -15
View File
@@ -111,10 +111,14 @@ function retryDelay(response: Response, defaultMs: number) {
*
* @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">> & PairHostOptions) {
let failing = false;
async function poll(
requestId: string,
options: Required<Pick<PairHostOptions, "pollIntervalMs" | "retryDelayMs">> & PairHostOptions,
) {
let delayMs = options.pollIntervalMs;
while (true) {
await sleep(options.pollIntervalMs, undefined, { signal: options.signal });
await sleep(delayMs, undefined, { signal: options.signal });
delayMs = options.pollIntervalMs;
let response;
try {
response = await request(options.controllerUrl, "api/host-pairing/poll", {
@@ -125,20 +129,22 @@ async function poll(requestId: string, options: Required<Pick<PairHostOptions, "
throw err;
}
// Keep polling through network errors, the request is made again if it expired meanwhile.
if (!failing) {
options.onRetry?.(err, options.pollIntervalMs);
failing = true;
}
delayMs = options.retryDelayMs;
options.onRetry?.(err, delayMs);
continue;
}
failing = false;
if (response.status === 200) {
return pairingResult(response);
}
if (response.status === 404) {
return null;
}
if (response.status !== 202 && !isTemporary(response.status)) {
if (isTemporary(response.status)) {
delayMs = retryDelay(response, options.retryDelayMs);
options.onRetry?.(responseError(response), delayMs);
continue;
}
if (response.status !== 202) {
throw responseError(response);
}
}
@@ -221,11 +227,12 @@ export async function pairHost(options: PairHostOptions): Promise<PairingResult>
*
* @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) {
const response = await request(controllerUrl, "api/host-pairing/check", { token });
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;
}
@@ -254,8 +261,11 @@ export async function ensurePaired(
if (token && token !== unpairedToken) {
let valid;
try {
valid = await checkHostToken(controllerUrl, token);
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;
@@ -276,10 +286,11 @@ export async function ensurePaired(
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.info(`Waiting for approval of "${name}" with code ${code}, open this link to approve it:`);
logger.info(approveUrl);
logger.info(`Or run: npx clusterioctl host approve ${code}`);
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`);
+16
View File
@@ -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.",
+2 -2
View File
@@ -183,7 +183,7 @@ export abstract class Datastore<
// Save the datastore to the provider
async save() {
// Saves run one at a time so an older snapshot can't be written after a newer one.
const save = this.saving.then(async () => {
const save = this.saving.catch(() => {}).then(async () => {
if (!this.dirty) {
return;
}
@@ -196,7 +196,7 @@ export abstract class Datastore<
throw err;
}
});
this.saving = save.catch(() => {});
this.saving = save;
await save;
}
+3 -1
View File
@@ -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;
}
@@ -104,16 +104,11 @@ function RevokeHostButton({ host, instances }: RevokeHostButtonProps) {
const navigate = useNavigate();
const assigned = [...instances.values()].map(instance => instance.name);
if (assigned.length) {
return <Tooltip title={`Unassign or delete the instances on this host first: ${assigned.join(", ")}`}>
<Button danger disabled>Revoke host access</Button>
</Tooltip>;
}
return <Popconfirm
title={`Revoke access for ${host.name}?`}
description={<>
The host is removed from the cluster and disconnected.<br />
{assigned.length > 0 && <>Its instances become unassigned: {assigned.join(", ")}<br /></>}
To add it back, start the host again and approve it.
</>}
placement="bottomRight"
+2 -8
View File
@@ -1,6 +1,5 @@
import { useCallback, useContext, useSyncExternalStore } from "react";
import ControlContext from "../components/ControlContext";
import { useAccount } from "./account";
export function useHost(id?: number) {
const [hosts, synced] = useHosts();
@@ -13,14 +12,9 @@ export function useHosts() {
return useSyncExternalStore(subscribe, () => control.hosts.getSnapshot());
}
/** Requests from host installers waiting to be approved, empty if the account may not approve hosts */
/** Requests from hosts waiting to be approved, empty if the account may not approve hosts */
export function useHostPairings() {
const control = useContext(ControlContext);
const account = useAccount();
const permitted = Boolean(account.hasPermission("core.host.approve"));
const subscribe = useCallback(
(callback: () => void) => (permitted ? control.hostPairings.subscribe(callback) : () => {}),
[control, permitted],
);
const subscribe = useCallback((callback: () => void) => control.hostPairings.subscribe(callback), [control]);
return useSyncExternalStore(subscribe, () => control.hostPairings.getSnapshot());
}
+5 -35
View File
@@ -1,19 +1,13 @@
import * as lib from "@clusterio/lib";
/**
* Subscriber for the requests from host installers waiting to be approved
* Subscriber for the requests from hosts waiting to be approved
*
* Only accounts that may approve hosts can subscribe to the requests, so
* this does not resubscribe on connect or account changes for other
* accounts, which would fail with a permission error. The requests only
* live in the controller's memory and it does not tell a new session about
* requests removed before it started, so the requests are cleared when a
* new session starts and fetched again. The same applies to requests removed
* while nothing was subscribed, so they are also cleared when subscribing
* again after the last handler unsubscribed.
* 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 _permitted: () => boolean;
private _handlers = 0;
/**
@@ -21,31 +15,7 @@ export class HostPairingSubscriber extends lib.MapSubscriber<lib.HostPairingUpda
* @param permitted - Returns true if the account may approve hosts.
*/
constructor(control: lib.Link, permitted: () => boolean) {
super(lib.HostPairingUpdatesEvent, control);
this._permitted = permitted;
}
override handleConnectionEvent(event: "connect" | "drop" | "resume" | "close") {
if (event === "connect") {
this.values.clear();
this.lastUpdatedMs = -1;
}
if (event === "connect" || event === "resume") {
// The account of a new session is reported after the connect event.
queueMicrotask(() => {
if (this._permitted()) {
super.handleConnectionEvent(event);
}
});
return;
}
super.handleConnectionEvent(event);
}
override handleAccountEvent() {
if (this._permitted()) {
super.handleAccountEvent();
}
super(lib.HostPairingUpdatesEvent, control, undefined, permitted);
}
override subscribe(handler: lib.EventSubscriberCallback<lib.HostPairingUpdatesEvent>) {