feat: add a panel button to update the manager itself

The manager clones SELF_UPDATE_REPO_URL, builds a new image in the shared build queue and
hands over to a short-lived updater container (new image) that swaps the manager container,
health-checks it and rolls back on failure. Exposed as GET/POST /api/system behind requireAuth;
installation changes answer 409 while an update runs. Session cookie is now SameSite=Lax.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-10-19 05:45:25 +02:00
1 parent 5fb1d6b0b4
commit 4b3c8f213a
23 files changed
+705 -5

No files matched your search

+11
View File
@@ -21,9 +21,20 @@ import {
import { buildLogPath } from "../build/nixpacks.js";
import { generateBearerToken } from "../crypto/secrets.js";
import fs from "node:fs";
import { isSelfUpdateInProgress } from "../system/selfUpdate.js";
export const installationsRouter = Router();
// An update swaps the manager's own container; an installation build or start in flight would be
// killed by it, so changes wait until the update is over.
installationsRouter.use((req, res, next) => {
if (req.method !== "GET" && isSelfUpdateInProgress()) {
res.status(409).json({ error: "the manager is updating itself; try again in a minute" });
return;
}
next();
});
// Not masked: this API sits behind single-operator session auth (requireAuth), and the
// operator is the same person who owns these secrets — editing them requires seeing them.
function toPublicJson(installation: Installation) {
+17
View File
@@ -0,0 +1,17 @@
import { Router } from "express";
import { getSystemInfo, startSelfUpdate, SelfUpdateError } from "../system/selfUpdate.js";
export const systemRouter = Router();
systemRouter.get("/", async (_req, res) => {
res.json(await getSystemInfo());
});
systemRouter.post("/update", async (_req, res) => {
try {
await startSelfUpdate();
res.status(202).json({ ok: true });
} catch (err) {
res.status(err instanceof SelfUpdateError ? err.status : 500).json({ error: (err as Error).message });
}
});
+4
View File
@@ -25,4 +25,8 @@ export const config = {
// The manager exits (and the container restart policy brings it back) once its own
// heap + external memory exceeds this. 0 disables the guard.
memoryLimitMb: Number(process.env.MANAGER_MEMORY_LIMIT_MB ?? 512),
// Self-update: git repo/ref the manager rebuilds itself from. Operator-set only (never taken
// from a request); without a repo URL the panel's "Update manager" button is disabled.
selfUpdateRepoUrl: process.env.SELF_UPDATE_REPO_URL || undefined,
selfUpdateRef: process.env.SELF_UPDATE_REF || "master",
};
+8
View File
@@ -7,6 +7,8 @@ import { reconcileInterruptedInstallations } from "./db/installations.js";
import { getActiveProxyRequests, handleMcpProxyRequest } from "./proxy/mcpProxy.js";
import { authRouter } from "./api/auth.js";
import { installationsRouter } from "./api/installations.js";
import { systemRouter } from "./api/system.js";
import { collectSelfUpdateResult } from "./system/selfUpdate.js";
import { requireAuth } from "./middleware/requireAuth.js";
import { SqliteSessionStore } from "./session/sqliteStore.js";
import { startMemoryGuard } from "./service/memoryGuard.js";
@@ -28,6 +30,8 @@ app.use(
saveUninitialized: false,
cookie: {
httpOnly: true,
// Lax: a cross-site form POST must not carry the session (e.g. to trigger a manager update).
sameSite: "lax",
// "auto": secure only if the request actually arrived over HTTPS (checks req.secure,
// which respects "trust proxy" + X-Forwarded-Proto). A flat `NODE_ENV === "production"`
// check meant the cookie was never stored at all when the admin panel is reached over
@@ -60,6 +64,7 @@ app.all("/mcp/:slug", handleMcpProxyRequest);
app.use("/api", express.json());
app.use("/api/auth", authRouter);
app.use("/api/installations", requireAuth, installationsRouter);
app.use("/api/system", requireAuth, systemRouter);
const webDist = path.resolve(import.meta.dirname, "../../web/dist");
app.use(express.static(webDist));
@@ -73,6 +78,9 @@ const server = app.listen(config.port, () => {
console.log(`remote-mcp-manager listening on http://localhost:${config.port}`);
});
// If an updater container ran just before this boot, pick up its outcome for the panel.
void collectSelfUpdateResult();
function shutdown(code: number): void {
server.close(() => process.exit(code));
server.closeAllConnections();
+6
View File
@@ -0,0 +1,6 @@
import { createSerialQueue } from "../util/serialQueue.js";
// Builds are the heaviest thing the host does (nixpacks + docker build); running several at
// once on a small host is what pushes it into swap. Serialize them — including the manager's
// own self-update build.
export const enqueueBuild = createSerialQueue();
+1 -5
View File
@@ -20,11 +20,7 @@ import {
removeImageIfUnused,
} from "../docker/containers.js";
import { generateBearerToken } from "../crypto/secrets.js";
import { createSerialQueue } from "../util/serialQueue.js";
// Builds are the heaviest thing the host does (nixpacks + docker build); running several at
// once on a small host is what pushes it into swap. Serialize them.
const enqueueBuild = createSerialQueue();
import { enqueueBuild } from "./buildQueue.js";
export interface DraftResult {
installation: Installation;
@@ -0,0 +1,42 @@
import { describe, expect, it } from "vitest";
import type { ContainerInspectInfo } from "dockerode";
import { buildReplacementSpec } from "./containerSpec.js";
const old = {
Id: "0123456789abcdef0123",
Name: "/remote-mcp-manager-manager-1",
Config: {
Env: ["PATH=/usr/bin", "NODE_OPTIONS=--old", "ADMIN_PASSWORD=x", "PORT=3000"],
Labels: { "com.docker.compose.service": "manager" },
ExposedPorts: { "3000/tcp": {} },
User: "",
Hostname: "0123456789ab",
Cmd: ["node", "old.js"],
},
HostConfig: {
NetworkMode: "mcp-net",
Binds: ["/var/run/docker.sock:/var/run/docker.sock", "./data:/repo/data"],
RestartPolicy: { Name: "unless-stopped" },
},
NetworkSettings: { Networks: { "mcp-net": { Aliases: ["manager", "0123456789ab"] } } },
} as unknown as ContainerInspectInfo;
describe("buildReplacementSpec", () => {
const spec = buildReplacementSpec(old, ["PATH=/usr/bin", "NODE_OPTIONS=--old"], "mcpmgr-manager:new");
it("keeps the name, host config and operator-set env, and runs the new image", () => {
expect(spec.name).toBe("remote-mcp-manager-manager-1");
expect(spec.Image).toBe("mcpmgr-manager:new");
expect(spec.HostConfig).toBe(old.HostConfig);
expect(spec.Env).toEqual(["ADMIN_PASSWORD=x", "PORT=3000"]);
});
it("does not pin the old image's Cmd or hostname", () => {
expect(spec.Cmd).toBeUndefined();
expect(spec.Hostname).toBeUndefined();
});
it("keeps network aliases except the old container's own id", () => {
expect(spec.NetworkingConfig?.EndpointsConfig?.["mcp-net"]?.Aliases).toEqual(["manager"]);
});
});
+40
View File
@@ -0,0 +1,40 @@
import type { ContainerCreateOptions, ContainerInspectInfo } from "dockerode";
/**
* Builds the create options for a container that replaces `old` but runs `newImage`, keeping
* everything the operator configured (name, bind mounts, port bindings, network + aliases,
* restart policy, user-supplied env) and nothing the image itself defines.
*
* `oldImageEnv` is the env baked into the OLD image: those entries are dropped, otherwise a
* `docker inspect`'d container pins the old image's ENV and a changed ENV in the new image
* (e.g. NODE_OPTIONS) would silently never apply. Cmd/Entrypoint/Hostname are likewise left
* out so the new image's defaults and a fresh hostname (= its own container id) apply.
*/
export function buildReplacementSpec(
old: ContainerInspectInfo,
oldImageEnv: string[],
newImage: string,
): ContainerCreateOptions {
const networkMode = old.HostConfig.NetworkMode ?? "default";
const network = old.NetworkSettings.Networks[networkMode];
const shortId = old.Id.slice(0, 12);
return {
name: old.Name.replace(/^\//, ""),
Image: newImage,
Env: (old.Config.Env ?? []).filter((e) => !oldImageEnv.includes(e)),
Labels: old.Config.Labels ?? {},
ExposedPorts: old.Config.ExposedPorts,
User: old.Config.User || undefined,
HostConfig: old.HostConfig,
...(network
? {
NetworkingConfig: {
EndpointsConfig: {
[networkMode]: { Aliases: ((network.Aliases ?? []) as string[]).filter((a) => a !== shortId) },
},
},
}
: {}),
};
}
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it } from "vitest";
import { demuxLogs } from "./dockerLogs.js";
function frame(stream: number, text: string): Buffer {
const payload = Buffer.from(text);
const header = Buffer.alloc(8);
header[0] = stream;
header.writeUInt32BE(payload.length, 4);
return Buffer.concat([header, payload]);
}
describe("demuxLogs", () => {
it("joins stdout and stderr frames in order", () => {
const buf = Buffer.concat([frame(1, "hello "), frame(2, "world\n")]);
expect(demuxLogs(buf)).toBe("hello world\n");
});
it("returns an empty string for empty or header-only input", () => {
expect(demuxLogs(Buffer.alloc(0))).toBe("");
expect(demuxLogs(Buffer.alloc(4))).toBe("");
});
it("does not read past a truncated frame", () => {
const buf = frame(1, "abcdef").subarray(0, 8 + 3);
expect(demuxLogs(buf)).toBe("abc");
});
});
+11
View File
@@ -0,0 +1,11 @@
/** Demuxes Docker's non-tty log stream (8-byte frame headers) into plain text. */
export function demuxLogs(buf: Buffer): string {
const out: string[] = [];
let offset = 0;
while (offset + 8 <= buf.length) {
const size = buf.readUInt32BE(offset + 4);
out.push(buf.subarray(offset + 8, offset + 8 + size).toString("utf8"));
offset += 8 + size;
}
return out.join("");
}
+211
View File
@@ -0,0 +1,211 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawn } from "node:child_process";
import Docker from "dockerode";
import { config } from "../config/env.js";
import { listInstallations } from "../db/installations.js";
import { cloneOrUpdateRepo, repoDir } from "../build/git.js";
import { enqueueBuild } from "../service/buildQueue.js";
import { killGroupAfter } from "../util/processTimeout.js";
import { withTimeout } from "../util/withTimeout.js";
import { demuxLogs } from "./dockerLogs.js";
import { readVersion } from "./version.js";
const docker = new Docker({ socketPath: config.dockerSocketPath });
const HELPER_LABEL = "remote-mcp-manager.self-update-helper";
const BUILD_TIMEOUT_MS = 30 * 60 * 1000;
// Updater: up to 90 s of health checks plus stop/create/rollback; this is only a backstop.
const HANDOVER_TIMEOUT_MS = 5 * 60 * 1000;
// The checkout lives under a name no installation slug can take (slugify strips underscores).
const CHECKOUT_SLUG = "_manager";
const BUSY_STATUSES = new Set(["cloning", "building", "starting"]);
type Phase = "idle" | "cloning" | "building" | "handing-over";
const state: { phase: Phase; error?: string; logPath?: string } = { phase: "idle" };
let lastResult: { finishedAt: string; ok: boolean; log: string } | null = null;
/** The container this process runs in (Docker sets the hostname to the container id), if any. */
async function inspectSelf() {
try {
return await withTimeout(docker.getContainer(os.hostname()).inspect(), 10_000, "docker inspect self");
} catch {
return undefined;
}
}
function tailOfLog(maxLines = 200): string {
if (!state.logPath || !fs.existsSync(state.logPath)) return "";
return fs.readFileSync(state.logPath, "utf8").split("\n").slice(-maxLines).join("\n");
}
export async function getSystemInfo() {
// The updater is usually still running when the new manager boots, so its result can only be
// collected later; polling this endpoint is what picks it up.
if (!lastResult && state.phase === "idle") await collectSelfUpdateResult();
const self = await inspectSelf();
return {
version: readVersion(),
uptimeSec: Math.round(process.uptime()),
canSelfUpdate: Boolean(config.selfUpdateRepoUrl && self),
unavailableReason: !config.selfUpdateRepoUrl
? "SELF_UPDATE_REPO_URL is not set"
: !self
? "the manager is not running inside a container it can inspect"
: null,
ref: config.selfUpdateRef,
phase: state.phase,
error: state.error ?? null,
log: state.phase === "idle" && !state.error ? "" : tailOfLog(),
lastUpdate: lastResult,
};
}
function runDockerBuild(contextDir: string, image: string, logPath: string): Promise<boolean> {
return new Promise((resolve) => {
const logStream = fs.createWriteStream(logPath, { flags: "a" });
const child = spawn("docker", ["build", "-t", image, contextDir], { detached: true });
killGroupAfter(child, BUILD_TIMEOUT_MS);
child.stdout.pipe(logStream, { end: false });
child.stderr.pipe(logStream, { end: false });
child.on("close", (code) => {
logStream.end();
resolve(code === 0);
});
child.on("error", (err) => {
logStream.write(`\nfailed to spawn docker: ${err.message}\n`);
logStream.end();
resolve(false);
});
});
}
async function runUpdate(self: Docker.ContainerInspectInfo): Promise<void> {
const url = config.selfUpdateRepoUrl!;
const image = `mcpmgr-manager:update-${Date.now()}`;
const logDir = path.join(config.logsDir, CHECKOUT_SLUG);
fs.mkdirSync(logDir, { recursive: true });
state.logPath = path.join(logDir, `${Date.now()}.log`);
const note = (msg: string) => fs.appendFileSync(state.logPath!, `[self-update] ${msg}\n`);
try {
// Same queue as installation builds: never two heavy builds at once on a small host. The
// hand-over below also happens inside it, so no queued build can start while the manager is
// about to be swapped out.
await enqueueBuild(async () => {
state.phase = "cloning";
note(`cloning ${url} (${config.selfUpdateRef})`);
await cloneOrUpdateRepo(CHECKOUT_SLUG, url, config.selfUpdateRef);
state.phase = "building";
note(`building ${image}`);
if (!(await runDockerBuild(repoDir(CHECKOUT_SLUG), image, state.logPath!))) {
throw new Error(`image build failed, see ${state.logPath}`);
}
state.phase = "handing-over";
const socketBind = (self.HostConfig.Binds ?? []).find((b) => b.split(":")[1] === config.dockerSocketPath);
if (!socketBind) throw new Error(`no bind mount for ${config.dockerSocketPath} on the manager container`);
note("starting the updater container; the manager will restart shortly");
const helper = await docker.createContainer({
Image: image,
Cmd: ["node", "dist/system/selfUpdateHelper.js"],
Env: [
`OLD_CONTAINER_ID=${self.Id}`,
`NEW_IMAGE=${image}`,
`DOCKER_SOCKET_PATH=${config.dockerSocketPath}`,
],
Labels: { [HELPER_LABEL]: "1" },
HostConfig: {
Binds: [socketBind],
SecurityOpt: self.HostConfig.SecurityOpt ?? undefined,
NetworkMode: self.HostConfig.NetworkMode,
RestartPolicy: { Name: "no" },
},
});
await helper.start();
// A successful hand-over kills this process, so getting past this wait means the updater
// ended without replacing us (crashed early, rolled back before stopping us) or hung.
const exit = (await withTimeout(helper.wait(), HANDOVER_TIMEOUT_MS, "updater container")) as { StatusCode: number };
await collectSelfUpdateResult();
throw new Error(
exit.StatusCode === 0
? "the updater finished but this manager is still running"
: `the updater exited with code ${exit.StatusCode}${lastResult ? `:\n${lastResult.log.split("\n").slice(-15).join("\n")}` : ""}`,
);
});
} catch (err) {
state.phase = "idle";
state.error = (err as Error).message;
note(`failed: ${state.error}`);
}
}
/** True from the moment an update is requested until it fails; a successful one ends this process. */
export function isSelfUpdateInProgress(): boolean {
return state.phase !== "idle";
}
export class SelfUpdateError extends Error {
constructor(
message: string,
readonly status: number,
) {
super(message);
}
}
/** Validates preconditions and starts the update in the background. Throws SelfUpdateError if it can't. */
export async function startSelfUpdate(): Promise<void> {
if (!config.selfUpdateRepoUrl) throw new SelfUpdateError("SELF_UPDATE_REPO_URL is not set", 400);
if (state.phase !== "idle") throw new SelfUpdateError("an update is already in progress", 409);
if (listInstallations().some((i) => BUSY_STATUSES.has(i.status))) {
throw new SelfUpdateError("an installation is building or starting; wait for it to finish", 409);
}
// Claimed before the first await so two concurrent requests can't both start an update.
state.phase = "cloning";
state.error = undefined;
const self = await inspectSelf();
if (!self) {
state.phase = "idle";
throw new SelfUpdateError("the manager is not running inside a container it can inspect", 400);
}
void runUpdate(self);
}
/**
* Called once at boot: if an updater container left a result behind (this process is either the
* freshly updated manager or the one the updater rolled back to), record its log and clean it up.
*/
export async function collectSelfUpdateResult(): Promise<void> {
try {
const helpers = await withTimeout(
docker.listContainers({ all: true, filters: { label: [HELPER_LABEL] } }),
10_000,
"docker list updater",
);
for (const h of helpers) {
if (h.State === "running") continue;
const container = docker.getContainer(h.Id);
const info = await withTimeout(container.inspect(), 10_000, "docker inspect updater");
const logs = (await withTimeout(
container.logs({ stdout: true, stderr: true }),
10_000,
"docker logs updater",
)) as unknown as Buffer;
lastResult = {
finishedAt: info.State.FinishedAt,
ok: info.State.ExitCode === 0,
log: demuxLogs(Buffer.from(logs)),
};
await withTimeout(container.remove({ force: true }), 10_000, "docker rm updater");
}
} catch {
// Best effort: no Docker access (e.g. local dev) just means there is nothing to report.
}
}
+109
View File
@@ -0,0 +1,109 @@
// Entry point of the short-lived "updater" container (the NEW image run with this script).
// The manager can't replace itself — stopping its own container kills the code doing it — so it
// hands over to this process, which swaps the manager container for one running NEW_IMAGE and
// rolls back to the old container if the new one never becomes healthy.
// Standalone on purpose: it doesn't import the app's config/db modules.
import http from "node:http";
import Docker from "dockerode";
import { buildReplacementSpec } from "./containerSpec.js";
const socketPath = process.env.DOCKER_SOCKET_PATH ?? "/var/run/docker.sock";
const oldId = process.env.OLD_CONTAINER_ID;
const newImage = process.env.NEW_IMAGE;
const HEALTH_TIMEOUT_MS = 90_000;
const docker = new Docker({ socketPath });
const log = (msg: string) => console.log(`[self-update] ${msg}`);
function checkHealth(ip: string, port: number): Promise<boolean> {
return new Promise((resolve) => {
const req = http.get({ host: ip, port, path: "/health", timeout: 2_000 }, (res) => {
res.resume();
resolve(res.statusCode === 200);
});
req.on("error", () => resolve(false));
req.on("timeout", () => {
req.destroy();
resolve(false);
});
});
}
async function waitUntilHealthy(containerId: string, network: string, port: number): Promise<boolean> {
const deadline = Date.now() + HEALTH_TIMEOUT_MS;
while (Date.now() < deadline) {
const info = await docker.getContainer(containerId).inspect();
if (!info.State.Running && info.State.Status !== "restarting") return false;
const ip = info.NetworkSettings.Networks[network]?.IPAddress;
if (ip && (await checkHealth(ip, port))) return true;
await new Promise((r) => setTimeout(r, 2_000));
}
return false;
}
async function main(): Promise<number> {
if (!oldId || !newImage) throw new Error("OLD_CONTAINER_ID and NEW_IMAGE are required");
const oldContainer = docker.getContainer(oldId);
const old = await oldContainer.inspect();
const name = old.Name.replace(/^\//, "");
const oldImageEnv = (await docker.getImage(old.Image).inspect()).Config.Env ?? [];
const spec = buildReplacementSpec(old, oldImageEnv, newImage);
const network = old.HostConfig.NetworkMode ?? "default";
const port = Number(old.Config.Env?.find((e) => e.startsWith("PORT="))?.slice(5) ?? 3000);
// The old container holds the name and the published port, so it has to go first. It is only
// renamed and stopped (not removed) so it can be started again if the new one fails. Renaming
// comes first, while it is still running: if that fails, nothing has been touched yet.
const backupName = `${name}-pre-update`;
await docker.getContainer(backupName).remove({ force: true }).catch(() => {});
await oldContainer.rename({ name: backupName });
log(`stopping ${name} (${old.Id.slice(0, 12)})`);
try {
await oldContainer.stop({ t: 15 });
} catch (err) {
if ((err as { statusCode?: number }).statusCode !== 304) {
await oldContainer.rename({ name }).catch(() => {});
throw err;
}
}
let created: Docker.Container | undefined;
let healthy = false;
try {
log(`starting new container from ${newImage}`);
created = await docker.createContainer(spec);
await created.start();
healthy = await waitUntilHealthy(created.id, network, port);
if (!healthy) log(`new manager did not become healthy within ${HEALTH_TIMEOUT_MS / 1000}s`);
} catch (err) {
log(`failed to start the new container: ${(err as Error).message}`);
}
if (healthy) {
// The update has succeeded; failing to tidy up must not undo it.
log("new manager is healthy, removing the old container");
await oldContainer.remove({ force: true }).catch((err) => log(`could not remove the old container: ${err.message}`));
await docker.getImage(old.Image).remove({ force: false }).catch(() => {});
log("update complete");
return 0;
}
// Every rollback step is attempted on its own: the old container must be started again even if
// an earlier step failed.
log("rolling back to the previous manager");
if (created) await created.remove({ force: true }).catch((err) => log(`could not remove the new container: ${err.message}`));
await oldContainer.rename({ name }).catch((err) => log(`could not restore the name: ${err.message}`));
await oldContainer.start().catch((err) => log(`could not start the old container: ${err.message}`));
await docker.getImage(newImage).remove({ force: false }).catch(() => {});
log("rollback complete");
return 1;
}
main().then(
(code) => process.exit(code),
(err) => {
log(`fatal: ${(err as Error).stack ?? err}`);
process.exit(2);
},
);
+14
View File
@@ -0,0 +1,14 @@
import fs from "node:fs";
import path from "node:path";
// VERSION sits at the repo root, four levels above this file in both the image and a checkout:
// <root>/apps/server/{src,dist}/system/version.*
const versionFile = path.resolve(import.meta.dirname, "../../../../VERSION");
export function readVersion(): string {
try {
return fs.readFileSync(versionFile, "utf8").trim() || "unknown";
} catch {
return "unknown";
}
}