Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
fix(security): serialize managed-app lifecycle cross-process
Abdurrahman Fakhrule92a75f1be63
diff --git a/lib/managed-apps/jobs.test.ts b/lib/managed-apps/jobs.test.tsindex cdc3441e..7350e99c 100644--- a/lib/managed-apps/jobs.test.ts+++ b/lib/managed-apps/jobs.test.ts@@ -11,6 +11,7 @@ vi.mock("server-only", () => ({}));const { startManagedAppJob, readManagedAppJob, listManagedAppJobs } = await import("./jobs");const { MANAGED_APP_JOB_LOG_CAP, liveRecord } = await import("./job-runner");const { performManagedAppAction } = await import("./manager");+const { withManagedAppOperationLease } = await import("./lock");import type { ManagedAppJob } from "./types";let home: string;@@ -216,3 +217,18 @@ describe("what never reaches a shell, and what never spawns", () => {expect(latest).not.toHaveProperty("log"); // history rows carry no transcript});});+++describe("cross-process managed-app operation lease", () => {+ it("refuses a second contender while the durable lease is held", async () => {+ let entered!: () => void, release!: () => void;+ const inside = new Promise<void>((resolve) => { entered = resolve; });+ const hold = new Promise<void>((resolve) => { release = resolve; });+ const first = withManagedAppOperationLease("hermes", async () => { entered(); await hold; });+ await inside;+ await expect(withManagedAppOperationLease("hermes", async () => undefined)).rejects.toThrow("another operation is already running");+ release();+ await first;+ await expect(withManagedAppOperationLease("hermes", async () => "ok")).resolves.toBe("ok");+ });+});diff --git a/lib/managed-apps/jobs.ts b/lib/managed-apps/jobs.tsindex 8153c81f..30663d9c 100644--- a/lib/managed-apps/jobs.ts+++ b/lib/managed-apps/jobs.ts@@ -3,7 +3,7 @@ import { randomBytes } from "node:crypto";import { isManagedAppId } from "./catalog";import { cancelJob, launchJob, liveRecord, liveRecords } from "./job-runner";import { isManagedAppJobId, listJobRecords, readJobRecord } from "./job-store";-import { acquireOperation } from "./lock";+import { acquireOperation, releaseOperation, withManagedAppOperationLease } from "./lock";import { MANAGED_APP_JOB_KINDS } from "./types";import type { ManagedAppId, ManagedAppJob, ManagedAppJobSummary, StartManagedAppJobOptions } from "./types";@@ -69,33 +69,34 @@ export async function startManagedAppJob(options: StartManagedAppJobOptions): Prif (!isManagedAppId(applicationId)) throw new Error("unknown managed application");if (!(MANAGED_APP_JOB_KINDS as readonly string[]).includes(kind)) throw new Error("unsupported managed application job");const argv = normaliseArgv(options.argv);- // Durable half of the lock. A second mso process on the same $HOME (a dev- // server on :3000) has its own in-memory Map and would happily start a second- // `hermes update` on the same git checkout; only the records are shared.- // Jobs whose owner is gone were already reconciled away by listJobRecords().- if ((await listJobRecords(applicationId)).some(blocking)) throw new Error("another operation is already running");- // In-process half: the SAME lock manager.ts takes for start/stop/restart/- // backup, so a job and a lifecycle action can never overlap either.- if (!acquireOperation(applicationId, kind)) throw new Error("another operation is already running");- const now = new Date().toISOString();- const record: ManagedAppJob = {- id: randomBytes(12).toString("hex"),- applicationId,- kind,- argv,- status: "queued",- startedAt: now,- endedAt: null,- exitCode: null,- error: null,- log: "",- logOffset: 0,- runnerId: RUNNER_ID,- serverPid: process.pid,- updatedAt: now,- };- await launchJob(record, options); // resolves once the id is durable- return snapshot(record, 0);+ return withManagedAppOperationLease(applicationId, async () => {+ if ((await listJobRecords(applicationId)).some(blocking)) throw new Error("another operation is already running");+ if (!acquireOperation(applicationId, kind)) throw new Error("another operation is already running");+ const now = new Date().toISOString();+ const record: ManagedAppJob = {+ id: randomBytes(12).toString("hex"),+ applicationId,+ kind,+ argv,+ status: "queued",+ startedAt: now,+ endedAt: null,+ exitCode: null,+ error: null,+ log: "",+ logOffset: 0,+ runnerId: RUNNER_ID,+ serverPid: process.pid,+ updatedAt: now,+ };+ try {+ await launchJob(record, options); // return only after the cross-process claim is durable+ } catch (error) {+ releaseOperation(applicationId);+ throw error;+ }+ return snapshot(record, 0);+ });}/** Poll read. `since` = the previous reply's `logOffset`, so `log` holds onlydiff --git a/lib/managed-apps/lock.ts b/lib/managed-apps/lock.tsindex b1db496a..36aca7ac 100644--- a/lib/managed-apps/lock.ts+++ b/lib/managed-apps/lock.ts@@ -1,4 +1,7 @@import "server-only";+import os from "node:os";+import path from "node:path";+import { withSecurityStoreLock } from "@/lib/security-store-lock";import type { ManagedAppId } from "./types";// THE per-app operation lock — the one manager.ts has always taken around@@ -42,3 +45,23 @@ export function releaseOperation(id: ManagedAppId): void {export function activeOperation(id: ManagedAppId): string | undefined {return active.get(id);}+++function durableOperationPath(id: ManagedAppId): string {+ return path.join(os.homedir(), ".mso", "managed-app-operations", `${id}.operation`);+}++/** Serialize the cross-process decision to start an app operation. Direct+ * lifecycle calls hold this lease for the operation; background jobs hold it+ * until their durable queued/running record exists, then that record becomes+ * the cross-process claim. */+export async function withManagedAppOperationLease<T>(id: ManagedAppId, fn: () => Promise<T>): Promise<T> {+ try {+ return await withSecurityStoreLock(durableOperationPath(id), fn, { busyTimeoutMs: 250 });+ } catch (error) {+ if (error instanceof Error && /security store is busy/.test(error.message)) {+ throw new Error("another operation is already running");+ }+ throw error;+ }+}diff --git a/lib/managed-apps/manager.ts b/lib/managed-apps/manager.tsindex 70f53563..ccfd74aa 100644--- a/lib/managed-apps/manager.ts+++ b/lib/managed-apps/manager.ts@@ -3,8 +3,9 @@ import os from "node:os";import { createBackup } from "./backups";import { getManagedAppDefinition, listManagedAppDefinitions } from "./catalog";import { dockerUsable, requireDocker, runDocker } from "./docker";-import { acquireOperation, activeOperation, releaseOperation } from "./lock";+import { acquireOperation, activeOperation, releaseOperation, withManagedAppOperationLease } from "./lock";import { redact } from "./redact";+import { listJobRecords } from "./job-store";import { commandExists, resolveCommand, runProgram } from "./runner";import { userBusEnv, userBusUnavailable } from "./user-bus";import type { ManagedAppAction, ManagedAppDefinition, ManagedAppId, ManagedAppLogs, ManagedAppView } from "./types";@@ -209,21 +210,22 @@ async function runLifecycle(installation: Installation, action: "start" | "stop"}export async function performManagedAppAction(id: ManagedAppId, action: ManagedAppAction): Promise<ManagedAppView> {- // Taken before detection now, and shared with the job layer (lock.ts), so a- // 30-minute update and a `restart` can never interleave on the same app.- if (!acquireOperation(id, action)) throw new Error("another operation is already running");- try {- const definition = getManagedAppDefinition(id);- const installation = await detect(definition);- if (!actionsFor(installation).includes(action)) throw new Error("operation unsupported for detected installation type");- if (action === "backup") await createBackup(definition, "manual");- else await runLifecycle(installation, action);- } finally {- releaseOperation(id);- // The action may have installed/upgraded the binary — drop the cached version- // so the view returned below reports the new one, not a stale ≤60 s reading.- versionCache.delete(id);- }+ await withManagedAppOperationLease(id, async () => {+ if ((await listJobRecords(id)).some((job) => job.status === "queued" || job.status === "running")) {+ throw new Error("another operation is already running");+ }+ if (!acquireOperation(id, action)) throw new Error("another operation is already running");+ try {+ const definition = getManagedAppDefinition(id);+ const installation = await detect(definition);+ if (!actionsFor(installation).includes(action)) throw new Error("operation unsupported for detected installation type");+ if (action === "backup") await createBackup(definition, "manual");+ else await runLifecycle(installation, action);+ } finally {+ releaseOperation(id);+ versionCache.delete(id);+ }+ });return getManagedApp(id);}