Merge remote-tracking branch 'upstream/master' into refactor/plugin-hooks-v2

# Conflicts:
#	packages/lib/src/data/messages_plugin.ts
#	packages/web_ui/src/components/PluginViewPage.tsx
#	test/lib/plugin.js
This commit is contained in:
bbassie committed 2026-09-12 18:07:12 +00:00
commit db84455c34
37 files changed
+573 -60

No files matched your search

+1 -1
View File
@@ -206,7 +206,7 @@ async function handleBootstrapCommand(
console.log(content);
} else {
logger.info(`Writing ${args.output}`);
await lib.safeOutputFile(args.output, content);
await lib.safeOutputFile(args.output, content, { mode: 0o600 });
}
}
}
@@ -126,6 +126,7 @@ export default class ControlConnection extends BaseConnection {
this.handle(lib.PluginListRequest, this.handlePluginListRequest.bind(this));
this.handle(lib.PluginUpdateRequest, this.handlePluginUpdateRequest.bind(this));
this.handle(lib.PluginInstallRequest, this.handlePluginInstallRequest.bind(this));
this.handle(lib.UpdateAllRequest, this.handleUpdateAllRequest.bind(this));
this.handle(lib.DebugDumpWsRequest, this.handleDebugDumpWsRequest.bind(this));
}
@@ -1305,6 +1306,16 @@ export default class ControlConnection extends BaseConnection {
return await lib.handlePluginInstall(request.pluginPackage);
}
async handleUpdateAllRequest(request: lib.UpdateAllRequest) {
if (!this._controller.config.get("controller.allow_remote_updates")) {
throw new lib.RequestError("Remote updates are disabled on this machine");
}
if (!this._controller.config.get("controller.allow_plugin_updates")) {
throw new lib.RequestError("Plugin updates are disabled on this machine");
}
return await lib.handleUpdateAll("@clusterio/controller", this._controller.pluginInfos);
}
async handlePluginListRequest(request: lib.PluginListRequest) {
return this._controller.pluginInfos.map(pluginInfo => lib.PluginDetails.fromNodeEnvInfo(
pluginInfo,
+3 -1
View File
@@ -1135,7 +1135,9 @@ export default class Controller {
let manifestPath = path.posix.join(pluginInfo.requirePath, "dist", "web", "manifest.json");
pluginInfo.manifest = await Controller.loadJsonObject(import.meta.resolve(manifestPath), true);
} catch (err) {
logger.warn(`Unable to load dist/web/manifest.json for plugin ${pluginInfo.name}`);
if (lib.pluginNeedsWebBuild(pluginInfo)) {
logger.warn(`Unable to load dist/web/manifest.json for plugin ${pluginInfo.name}`);
}
}
if (!this.config.get(`${pluginInfo.name}.load_plugin`)) {
+4 -1
View File
@@ -106,6 +106,9 @@ export default class WsServerConnector extends lib.WebSocketBaseConnector {
this._state = "connected";
this._attachSocketHandlers();
this._dropSendBufferSeq(lastSeq);
logger.verbose(
`Connector | resuming session with ${this.dst}, resending ${this._sendBuffer.length} buffered messages`
);
for (let message of this._sendBuffer) {
this._socket.send(JSON.stringify(message));
}
@@ -113,7 +116,7 @@ export default class WsServerConnector extends lib.WebSocketBaseConnector {
}
_timedOut() {
logger.verbose("Connector | Connection timed out");
logger.verbose(`Connector | Connection to ${this.dst} timed out`);
this._close();
}
+1 -1
View File
@@ -132,7 +132,7 @@ function getPlugins(req: Request, res: Response) {
if (!web.main) {
web.error = `Missing ${pluginInfo.name}.js entry in manifest.json`;
}
} else {
} else if (lib.pluginNeedsWebBuild(pluginInfo)) {
web.error = "Missing dist/web/manifest.json";
}
if (web.main === "remoteEntry.js") {
+1 -1
View File
@@ -234,7 +234,7 @@ async function migrateRename(args) {
if (await pathExists(source) && !await pathExists(destination)) {
await safeOutputFile(destination, JSON.stringify(
renameConfig(JSON.parse(await fs.readFile(source))), null, "\t"
));
), { mode: 0o600 });
logger.info(`Migrated ${source} to ${destination}`);
}
}
+7 -2
View File
@@ -28,9 +28,14 @@ controllerCommands.add(new lib.Command({
controllerCommands.add(new lib.Command({
definition: ["update", "Update the controller", (yargs) => {
yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" });
yargs.option("all", { alias: "a", type: "boolean", description: "Also update all plugins" });
}],
handler: async function(args: { restart: boolean }, control: Control) {
await control.send(new lib.ControllerUpdateRequest());
handler: async function(args: { restart: boolean, all: boolean }, control: Control) {
if (args.all) {
await control.send(new lib.UpdateAllRequest());
} else {
await control.send(new lib.ControllerUpdateRequest());
}
if (args.restart) {
await control.send(new lib.ControllerRestartRequest());
} else {
+8 -3
View File
@@ -87,7 +87,7 @@ hostCommands.add(new lib.Command({
} else {
logger.info(`Writing ${args.output}`);
try {
await fs.writeFile(args.output, content, { flag: "wx" });
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`);
@@ -101,10 +101,15 @@ hostCommands.add(new lib.Command({
definition: ["update <host>", "Update the host", (yargs) => {
yargs.positional("host", { describe: "Host to update", type: "string" });
yargs.option("restart", { alias: "r", type: "boolean", description: "Restart after update" });
yargs.option("all", { alias: "a", type: "boolean", description: "Also update all plugins" });
}],
handler: async function(args: { host: string, restart: boolean }, control: Control) {
handler: async function(args: { host: string, restart: boolean, all: boolean }, control: Control) {
let hostId = await lib.resolveHost(control, args.host);
await control.sendTo({ hostId }, new lib.HostUpdateRequest());
if (args.all) {
await control.sendTo({ hostId }, new lib.UpdateAllRequest());
} else {
await control.sendTo({ hostId }, new lib.HostUpdateRequest());
}
if (args.restart) {
await control.sendTo({ hostId }, new lib.HostRestartRequest());
} else {
+11
View File
@@ -401,6 +401,7 @@ export default class Host extends lib.Link {
this.handle(lib.PluginListRequest, this.handlePluginListRequest.bind(this));
this.handle(lib.PluginUpdateRequest, this.handlePluginUpdateRequest.bind(this));
this.handle(lib.PluginInstallRequest, this.handlePluginInstallRequest.bind(this));
this.handle(lib.UpdateAllRequest, this.handleUpdateAllRequest.bind(this));
this.snoopEvent(lib.InstanceAdminlistUpdateEvent, this.handleAdminlistUpdateEvent.bind(this));
this.snoopEvent(lib.InstanceBanlistUpdateEvent, this.handleBanlistUpdateEvent.bind(this));
@@ -1145,6 +1146,16 @@ export default class Host extends lib.Link {
return await lib.handlePluginInstall(request.pluginPackage);
}
async handleUpdateAllRequest(request: lib.UpdateAllRequest) {
if (!this.config.get("host.allow_remote_updates")) {
throw new lib.RequestError("Remote updates are disabled on this machine");
}
if (!this.config.get("host.allow_plugin_updates")) {
throw new lib.RequestError("Plugin updates are disabled on this machine");
}
return await lib.handleUpdateAll("@clusterio/host", this.pluginInfos);
}
async handlePluginListRequest(request: lib.PluginListRequest) {
return this.pluginInfos.map(pluginInfo => lib.PluginDetails.fromNodeEnvInfo(
pluginInfo,
+20
View File
@@ -791,6 +791,7 @@ end`.replace(/\r?\n/g, " ");
} else {
modPack = await this.sendTo("controller", new lib.ModPackGetRequest(modPackId));
}
this.checkModPackVersion(modPack);
this.activeModPack = modPack;
const mods = await this._host.fetchMods(modPack.mods.values(), modPack.factorioVersion);
@@ -842,6 +843,25 @@ end`.replace(/\r?\n/g, " ");
await fs.writeFile(this.path("mods", "mod-settings.dat"), this.activeModPack.toModSettingsDat());
}
/**
* Check that the mod pack does not target a newer Factorio than the server
*
* The mod pack's Factorio version is written into mod-settings.dat and
* Factorio refuses to read it if it is newer than the game. It then
* loads default settings instead, which can corrupt the save.
*
* @throws {lib.RequestError} if the mod pack version is higher than the server version.
*/
checkModPackVersion(modPack: lib.ModPack) {
const serverVersion = this.server.version;
if (serverVersion && modPack.integerFactorioVersion > lib.integerFullVersion(serverVersion)) {
throw new lib.RequestError(
`Mod pack ${modPack.name} is for Factorio ${modPack.factorioVersion} ` +
`which is newer than the Factorio ${serverVersion} this instance runs`
);
}
}
/**
* Prepare instance for starting
*
+2 -1
View File
@@ -4,7 +4,8 @@ export type PluginWebApi = {
enabled: boolean;
loaded: boolean;
web: {
main: string;
/** Path to the web bundle, not present if the plugin has no web build. */
main?: string;
error?: string;
};
/**
+1 -1
View File
@@ -468,7 +468,7 @@ export class Config<
if (!this.filepath) {
throw new Error("Cannot save config which has no filepath");
}
await safeOutputFile(this.filepath, JSON.stringify(this, null, "\t"));
await safeOutputFile(this.filepath, JSON.stringify(this, null, "\t"), { mode: 0o600 });
this.dirty = false;
}
+13
View File
@@ -1,6 +1,8 @@
import { Type, Static } from "@sinclair/typebox";
import { jsonArray } from "./composites.js";
import type { PluginNodeEnvInfo } from "../plugin.js";
import { Address, MessageRequest } from "./messages_core.js";
import type { IUser } from "./UserDetails.js";
/* This is similar to other plugin definitions but with lots removed */
export class PluginDetails {
@@ -91,3 +93,14 @@ export class PluginInstallRequest {
return this.pluginPackage;
}
}
export class UpdateAllRequest {
declare ["constructor"]: typeof UpdateAllRequest;
static type = "request" as const;
static src = "control" as const;
static dst = ["controller", "host"] as const;
static permission(user: IUser, message: MessageRequest) {
user.checkPermission(message.dst.type === Address.host ? "core.host.update" : "core.controller.update");
user.checkPermission("core.plugin.update");
}
}
+4
View File
@@ -168,6 +168,10 @@ export async function safeOutputFile(
throw err;
}
}
if (options?.mode !== undefined) {
// writeFile only applies mode when creating, a leftover temporary keeps its old mode.
await fs.chmod(temporary, options.mode);
}
await fs.rename(temporary, file);
}
+3 -1
View File
@@ -713,12 +713,14 @@ export abstract class WebSocketClientConnector extends WebSocketBaseConnector<We
this.emit("connect", data);
} else if (type === "continue") {
logger.info("Connector | resuming existing session");
this._state = "connected";
this._heartbeatInterval = data.heartbeatInterval;
this._sessionTimeout = data.sessionTimeout;
this.startHeartbeat();
this._dropSendBufferSeq(data.lastSeq);
logger.info(
`Connector | resuming existing session, resending ${this._sendBuffer.length} buffered messages`
);
for (let bufferedMessage of this._sendBuffer) {
this._sendInternal(bufferedMessage);
}
+2 -2
View File
@@ -444,7 +444,7 @@ export class Link {
let pending = this._pendingRequests.get(message.dst.requestId!);
if (!pending) {
throw new libErrors.InvalidMessage(
`Received response ${message.dst.requestId} without a pending request`
`Received response ${message.dst.requestId} from ${message.src} without a pending request`
);
}
@@ -465,7 +465,7 @@ export class Link {
let pending = this._pendingRequests.get(message.dst.requestId!);
if (!pending) {
throw new libErrors.InvalidMessage(
`Received error response ${message.dst.requestId} without a pending request`
`Received error response ${message.dst.requestId} from ${message.src} without a pending request`
);
}
+1
View File
@@ -140,4 +140,5 @@ export const dataClasses: (RequestClass<unknown, unknown> | EventClass<unknown>)
plugin.PluginListRequest,
plugin.PluginUpdateRequest,
plugin.PluginInstallRequest,
plugin.UpdateAllRequest,
];
+17
View File
@@ -40,6 +40,23 @@ export type PluginDeclaration = {
routes?: string[];
}
/**
* Check if a plugin is expected to ship a web build.
*
* Mirrors the rule used by the create tool: a web build is generated when the
* plugin has a web or controller entrypoint or defines config fields.
*/
export function pluginNeedsWebBuild(info: PluginDeclaration) {
return Boolean(
info.webEntrypoint
|| info.controllerEntrypoint
|| info.controllerConfigFields
|| info.hostConfigFields
|| info.instanceConfigFields
|| info.controlConfigFields
);
}
export type PluginNodeEnvInfo = PluginDeclaration & {
/**
* Path to the folder with the static files that should be hosted on the web
+9 -2
View File
@@ -19,8 +19,8 @@ async function logExec(cmd: string) {
}
}
export async function updatePackage(name: string) {
return logExec(`npm update --save ${name}`);
export async function updatePackage(...names: string[]) {
return logExec(`npm update --save ${names.join(" ")}`);
}
export async function installPackage(name: string) {
@@ -35,6 +35,13 @@ export async function handlePluginUpdate(pluginName: string, pluginInfos: Plugin
return await updatePackage(pluginName);
}
export async function handleUpdateAll(corePackage: string, pluginInfos: PluginNodeEnvInfo[]) {
const pluginPackages = pluginInfos
.map(plugin => plugin.npmPackage)
.filter((name): name is string => name !== undefined);
return await updatePackage(corePackage, ...pluginPackages);
}
export async function handlePluginInstall(pluginName: string) {
if (pluginName.length > 214 || /[^a-zA-Z0-9\-_.+@\/]/.test(pluginName)) {
// https://docs.npmjs.com/cli/v11/configuring-npm/package-json#name
+3
View File
@@ -50,6 +50,9 @@ async function loadPluginInfos(): Promise<[lib.PluginWebpackEnvInfo[], string]>
logger.error(`Failed to load plugin ${meta.name}: ${meta.web.error}`);
continue;
}
if (!meta.web.main) {
continue;
}
try {
await loadScript(`${staticRoot}${meta.web.main}`);
let container: any = (window as { [key: string]: any })[`plugin_${meta.name}`];
+23 -1
View File
@@ -27,6 +27,17 @@ function NpmRemoteUpdate({ setApplyAction, form, target }: NpmActionProps) {
</>;
}
function NpmUpdateAll({ setApplyAction, form, target }: NpmActionProps) {
const control = useContext(ControlContext);
setApplyAction(async () => {
await control.sendTo(target, new lib.UpdateAllRequest());
});
return <>
</>;
}
function NpmPluginUpdate({ setApplyAction, form, target }: NpmActionProps) {
const control = useContext(ControlContext);
const [plugins, setPlugins] = useState<lib.PluginDetails[]>([]);
@@ -128,6 +139,8 @@ export function NpmButton(props: {
}
}, [hostId]);
const coreUpdatePermission = `core.${props.target === "controller" ? "controller" : "host"}.update` as const;
function onValuesChange({ action } : { action?: string }) {
if (action) {
setFormAction(action);
@@ -175,10 +188,17 @@ export function NpmButton(props: {
<Form form={form} onValuesChange={onValuesChange} clearOnDestroy>
<Form.Item label="Action" name="action">
<Radio.Group value={formAction}>
{account.hasPermission(`core.${props.target === "controller" ? "controller" : "host"}.update`)
{account.hasPermission(coreUpdatePermission)
? <Radio.Button value="remote_update" disabled={!allows.remoteUpdates}>
Update Clusterio
</Radio.Button>: undefined}
{account.hasPermission(coreUpdatePermission) && account.hasPermission("core.plugin.update")
? <Radio.Button
value="update_all"
disabled={!allows.remoteUpdates || !allows.pluginUpdates}
>
Update All
</Radio.Button> : undefined}
{account.hasPermission("core.plugin.update")
? <Radio.Button value="plugin_update" disabled={!allows.pluginUpdates}>
Update Plugin
@@ -198,6 +218,8 @@ export function NpmButton(props: {
}
{formAction === "remote_update"
? <NpmRemoteUpdate {...{setApplyAction, form, target: props.target}}/> : undefined}
{formAction === "update_all"
? <NpmUpdateAll {...{setApplyAction, form, target: props.target}}/> : undefined}
{formAction === "plugin_update"
? <NpmPluginUpdate {...{setApplyAction, form, target: props.target}}/> : undefined}
{formAction === "plugin_install"
@@ -46,11 +46,14 @@ export default function PluginViewPage() {
}
const pluginError = pluginMeta.web.error ?? pluginInfo?.error;
const hasWebModule = Boolean(pluginMeta.web.main || pluginMeta.web.error);
if (!loadedPlugin) {
return <PageLayout nav={nav}>
<Descriptions bordered size="small" title={pluginTitle}>
<Descriptions.Item label="Version">{pluginMeta.version}</Descriptions.Item>
<Descriptions.Item label="Loaded in Web UI" span={2}>No</Descriptions.Item>
<Descriptions.Item label="Loaded in Web UI" span={2}>
{hasWebModule ? "No" : "No web module"}
</Descriptions.Item>
<Descriptions.Item label="Loaded on controller">{pluginMeta.loaded ? "Yes" : "No"}</Descriptions.Item>
<Descriptions.Item label="Enabled on controller" span={2}>
{pluginMeta.enabled ? "Yes" : "No"}
+12 -1
View File
@@ -86,6 +86,9 @@ export default function PluginsPage() {
if (!plugin.meta.enabled) {
return <><InfoCircleFilled style={{ color: "#1668dc" }} /> Disabled on controller</>;
}
if (!plugin.meta.web.main && !plugin.meta.web.error) {
return plugin.meta.version;
}
if (!plugin.meta.web.error && !control.pluginInfos.has(plugin.meta.name)) {
return <><InfoCircleFilled style={{ color: "#1668dc" }} /> Reload page to load</>;
}
@@ -103,7 +106,15 @@ export default function PluginsPage() {
{
title: "Loaded",
key: "loaded",
render: (_, plugin) => (plugin.package ? "Yes" : null),
render: (_, plugin) => {
if (plugin.package) {
return "Yes";
}
if (!plugin.meta.web.main && !plugin.meta.web.error) {
return "No web module";
}
return null;
},
sorter: (a, b) => Number(Boolean(a.package)) - Number(Boolean(b.package)),
sortOrder: tableState.sortOrder("loaded"),
responsive: ["sm"],