diff --git a/src/app/apps/page.tsx b/src/app/apps/page.tsx index e3492c1..758b69b 100644 --- a/src/app/apps/page.tsx +++ b/src/app/apps/page.tsx @@ -13,6 +13,7 @@ import { createPortal } from "react-dom"; import DashboardLayout from "@/components/DashboardLayout"; import SearchField from "@/components/SearchField"; import SearchableSelect from "@/components/SearchableSelect"; +import ToastViewport from "@/components/ToastViewport"; import { Boxes, Package, @@ -50,6 +51,8 @@ import { storeServerSelection, writeCachedPageData, } from "@/lib/page-state"; +import type { ToastInput } from "@/lib/use-toast-manager"; +import { useToastManager } from "@/lib/use-toast-manager"; type InstallMode = "template" | "custom"; @@ -551,12 +554,14 @@ function InstallModal({ serverList, onClose, onSuccess, + onToast, }: { template: AppTemplate | null; initialMode: InstallMode; serverList: Server[]; onClose: () => void; onSuccess: () => void; + onToast: (toast: ToastInput) => void; }) { const [mounted, setMounted] = useState(false); const [mode, setMode] = useState(initialMode); @@ -953,7 +958,14 @@ function InstallModal({ onSuccess(); onClose(); } catch (err: unknown) { - setError(err instanceof Error ? err.message : "Install failed"); + const message = err instanceof Error ? err.message : "Install failed"; + setError(message); + onToast({ + tone: "error", + title: "App Installer", + message, + showProgress: true, + }); } finally { setLoading(false); } @@ -1670,6 +1682,7 @@ function InstallModal({ } export default function AppsPage() { + const { toasts, pushToast, dismissToast } = useToastManager(); const [search, setSearch] = useState(""); const [cat, setCat] = useState("All"); const [templates, setTemplates] = useState([]); @@ -1820,12 +1833,18 @@ export default function AppsPage() { serverList={serverList} onClose={() => setInstallTarget(null)} onSuccess={load} + onToast={pushToast} /> )} +
void; onProcessOpen?: (state: ProcessLogsModalState) => void; onProcessUpdate?: (state: Partial) => void; + onToast?: (toast: ToastInput) => void; } type DeployChoice = Exclude | null; @@ -206,6 +208,7 @@ export default function DeployContainerModal({ onDeployed, onProcessOpen, onProcessUpdate, + onToast, }: DeployContainerModalProps) { const router = useRouter(); const [choice, setChoice] = useState(null); @@ -1056,6 +1059,12 @@ export default function DeployContainerModal({ } catch (err: unknown) { const message = err instanceof Error ? err.message : "Deploy failed"; setError(message); + onToast?.({ + tone: "error", + title: "Container Deploy", + message, + showProgress: true, + }); failDeployTimelineModal({ onProcessUpdate, name: form.name, diff --git a/src/app/containers/page.tsx b/src/app/containers/page.tsx index 42d1387..e3924ea 100644 --- a/src/app/containers/page.tsx +++ b/src/app/containers/page.tsx @@ -508,6 +508,7 @@ export default function ContainersPage() { onDeployed={load} onProcessOpen={openProcessLogs} onProcessUpdate={updateProcessLogs} + onToast={pushToast} /> ) : null} {logsFor ? ( diff --git a/src/app/projects/[projectId]/environments/[environmentId]/page.tsx b/src/app/projects/[projectId]/environments/[environmentId]/page.tsx index 411cd39..3c83a4d 100644 --- a/src/app/projects/[projectId]/environments/[environmentId]/page.tsx +++ b/src/app/projects/[projectId]/environments/[environmentId]/page.tsx @@ -255,6 +255,7 @@ export default function EnvironmentContainersPage() { onDeployed={load} onProcessOpen={openProcessLogs} onProcessUpdate={updateProcessLogs} + onToast={pushToast} /> ) : null} {showDeployDatabase && activeEnvironment ? ( diff --git a/src/server/routes/apps.ts b/src/server/routes/apps.ts index e158df7..e184917 100644 --- a/src/server/routes/apps.ts +++ b/src/server/routes/apps.ts @@ -1,6 +1,6 @@ import { FastifyInstance } from "fastify"; import { z } from "zod"; -import { $Enums } from "@prisma/client"; +import { $Enums, type Server } from "@prisma/client"; import prisma from "../lib/prisma"; import { authenticate, requireApiKeyPermission } from "../middleware/auth"; import { auditLog } from "../services/audit.service"; @@ -147,6 +147,43 @@ function parseCsvBindings(value: string): string[] { .filter(Boolean); } +function normalizeContainerNameForConflict(value: string) { + return value.trim().replace(/^\//, "").toLowerCase(); +} + +function extractHostPortFromPortMapping(value: string) { + const trimmed = value.trim().replace(/^['"]|['"]$/g, ""); + if (!trimmed) return null; + + const dockerPsMatch = trimmed.match(/(?:^|:)(\d+)->/); + if (dockerPsMatch?.[1]) return dockerPsMatch[1]; + + const mapping = trimmed.split("/")[0]?.trim() ?? trimmed; + const parts = mapping.split(":").filter(Boolean); + if (parts.length < 2) return null; + + const hostPort = parts[parts.length - 2] ?? ""; + return /^\d+$/.test(hostPort) ? hostPort : null; +} + +function extractHostPortsFromPortMappings(value?: string | null) { + return parseCsvBindings(value ?? "") + .map(extractHostPortFromPortMapping) + .filter((port): port is string => Boolean(port)); +} + +function extractHostPortsFromStoredPorts(value: unknown) { + const ports = Array.isArray(value) + ? value.filter((entry): entry is string => typeof entry === "string") + : typeof value === "string" + ? parseCsvBindings(value) + : []; + + return ports + .map(extractHostPortFromPortMapping) + .filter((port): port is string => Boolean(port)); +} + function parseEnvironmentVariables(env: string): string[] { return env .split("\n") @@ -249,6 +286,110 @@ async function upsertAppInstallerContainer(input: { }); } +async function assertAppInstallTargetAvailable(input: { + server: Server; + containerName: string; + ports: string; +}) { + const requestedName = normalizeContainerNameForConflict(input.containerName); + const requestedHostPorts = extractHostPortsFromPortMappings(input.ports); + + const seenHostPorts = new Set(); + const duplicateRequestedPort = requestedHostPorts.find((port) => { + if (seenHostPorts.has(port)) return true; + seenHostPorts.add(port); + return false; + }); + + if (duplicateRequestedPort) { + throw new Error( + `Host port ${duplicateRequestedPort} is mapped more than once in this install.`, + ); + } + + const runtimeContainers = await ssh.listDockerContainers(input.server); + for (const container of runtimeContainers) { + if ( + normalizeContainerNameForConflict(container.name) === requestedName + ) { + throw new Error( + `Container name "${input.containerName}" is already used on the selected server.`, + ); + } + + const conflictingPort = requestedHostPorts.find((port) => + extractHostPortsFromPortMappings(container.ports).includes(port), + ); + if (conflictingPort) { + throw new Error( + `Host port ${conflictingPort} is already used by container "${container.name}" on the selected server.`, + ); + } + } + + const containers = await prisma.container.findMany({ + where: { + serverId: input.server.id, + status: { not: "ERROR" }, + }, + select: { + name: true, + ports: true, + }, + }); + + for (const container of containers) { + if ( + normalizeContainerNameForConflict(container.name) === requestedName + ) { + throw new Error( + `Container name "${input.containerName}" is already used on the selected server.`, + ); + } + + const conflictingPort = requestedHostPorts.find((port) => + extractHostPortsFromStoredPorts(container.ports).includes(port), + ); + if (conflictingPort) { + throw new Error( + `Host port ${conflictingPort} is already used by container "${container.name}" on the selected server.`, + ); + } + } + + const activeInstalls = await prisma.appInstall.findMany({ + where: { + serverId: input.server.id, + status: { notIn: ["FAILED", "REMOVED"] }, + }, + select: { + appName: true, + containerName: true, + port: true, + }, + }); + + for (const install of activeInstalls) { + if ( + install.containerName && + normalizeContainerNameForConflict(install.containerName) === requestedName + ) { + throw new Error( + `Container name "${input.containerName}" is already used by app install "${install.appName}" on the selected server.`, + ); + } + + const conflictingPort = requestedHostPorts.find((port) => + extractHostPortsFromPortMappings(install.port ?? "").includes(port), + ); + if (conflictingPort) { + throw new Error( + `Host port ${conflictingPort} is already used by app install "${install.appName}" on the selected server.`, + ); + } + } +} + function classifyRuntimeError( message: string, ): "CONTAINER_NOT_FOUND" | "INSPECT_FAILED" | "RUNTIME_UNAVAILABLE" { @@ -888,6 +1029,22 @@ export async function appsRoutes(app: FastifyInstance) { finalVolumes; } + try { + await assertAppInstallTargetAvailable({ + server, + containerName, + ports: finalPorts, + }); + } catch (error) { + return reply.status(400).send({ + success: false, + error: + error instanceof Error + ? error.message + : "Failed to validate app install target", + }); + } + const install = await prisma.appInstall.create({ data: { appId: finalAppId, diff --git a/src/server/routes/containers.ts b/src/server/routes/containers.ts index 368ebfb..aa263d4 100644 --- a/src/server/routes/containers.ts +++ b/src/server/routes/containers.ts @@ -1,4 +1,5 @@ import { FastifyInstance, FastifyReply } from "fastify"; +import yaml from "js-yaml"; import { posix as pathPosix } from "path"; import { z } from "zod"; import prisma from "../lib/prisma"; @@ -430,6 +431,202 @@ function parseDockerPorts(ports: string): string[] { .filter(Boolean); } +function extractHostPortFromPortMapping( + value: string, + options: { allowSinglePortAsHost?: boolean } = {}, +) { + const trimmed = value.trim().replace(/^['"]|['"]$/g, ""); + if (!trimmed) return null; + + const dockerPsMatch = trimmed.match(/(?:^|:)(\d+)->/); + if (dockerPsMatch?.[1]) return dockerPsMatch[1]; + + const mapping = trimmed.split("/")[0]?.trim() ?? trimmed; + const parts = mapping.split(":").filter(Boolean); + + if (parts.length === 1) { + return options.allowSinglePortAsHost && /^\d+$/.test(parts[0]) + ? parts[0] + : null; + } + + const hostPort = parts[parts.length - 2] ?? ""; + return /^\d+$/.test(hostPort) ? hostPort : null; +} + +function extractHostPortsFromPortMappings( + ports: string, + options: { allowSinglePortAsHost?: boolean } = {}, +) { + return ports + .split(",") + .map((entry) => extractHostPortFromPortMapping(entry, options)) + .filter((port): port is string => Boolean(port)); +} + +function extractHostPortsFromStoredPorts(value: unknown) { + const ports = Array.isArray(value) + ? value.filter((entry): entry is string => typeof entry === "string") + : typeof value === "string" + ? parseDockerPorts(value) + : []; + + return ports + .map((entry) => extractHostPortFromPortMapping(entry)) + .filter((port): port is string => Boolean(port)); +} + +function extractComposePublishedHostPorts(composeContent?: string | null) { + const content = toOptionalValue(composeContent); + if (!content) return []; + + let parsed: unknown; + try { + parsed = yaml.load(content); + } catch { + return []; + } + + if (typeof parsed !== "object" || parsed === null || !("services" in parsed)) { + return []; + } + + const services = (parsed as { services?: unknown }).services; + if (typeof services !== "object" || services === null) { + return []; + } + + const hostPorts: string[] = []; + for (const service of Object.values(services)) { + if (typeof service !== "object" || service === null) continue; + + const ports = (service as { ports?: unknown }).ports; + if (!Array.isArray(ports)) continue; + + for (const entry of ports) { + if (typeof entry === "string") { + const hostPort = extractHostPortFromPortMapping(entry); + if (hostPort) hostPorts.push(hostPort); + continue; + } + + if (typeof entry !== "object" || entry === null) continue; + + const published = (entry as { published?: unknown }).published; + const hostPort = + typeof published === "number" || typeof published === "string" + ? String(published).trim() + : ""; + if (/^\d+$/.test(hostPort)) hostPorts.push(hostPort); + } + } + + return hostPorts; +} + +function collectRequestedHostPorts(input: z.infer) { + const hostPorts = [ + ...extractHostPortsFromPortMappings(input.ports), + ...extractHostPortsFromPortMappings(input.portOverride ?? "", { + allowSinglePortAsHost: true, + }), + ]; + + if (input.sourceType === "MANUAL" && input.deployMode === "COMPOSE") { + hostPorts.push(...extractComposePublishedHostPorts(input.composeContent)); + } + + return hostPorts; +} + +async function assertRequestedHostPortsAvailable(input: { + deployInput: z.infer; + serverId: string; +}) { + const requestedHostPorts = collectRequestedHostPorts(input.deployInput); + if (requestedHostPorts.length === 0) return; + + const seen = new Set(); + const duplicateRequestedPort = requestedHostPorts.find((port) => { + if (seen.has(port)) return true; + seen.add(port); + return false; + }); + + if (duplicateRequestedPort) { + throw new Error( + `Host port ${duplicateRequestedPort} is mapped more than once in this deployment.`, + ); + } + + const containers = await prisma.container.findMany({ + where: { + serverId: input.serverId, + status: { not: "ERROR" }, + }, + select: { + name: true, + ports: true, + }, + }); + + for (const container of containers) { + const usedHostPorts = extractHostPortsFromStoredPorts(container.ports); + const conflictingPort = requestedHostPorts.find((port) => + usedHostPorts.includes(port), + ); + + if (conflictingPort) { + throw new Error( + `Host port ${conflictingPort} is already used by container "${container.name}" on the selected server.`, + ); + } + } +} + +function shouldValidateRequestedContainerName( + input: z.infer, +) { + const gitBuildType = resolveGitBuildType(input); + return input.deployMode !== "COMPOSE" && gitBuildType !== "COMPOSE"; +} + +function normalizeContainerNameForConflict(value: string) { + return value.trim().replace(/^\//, "").toLowerCase(); +} + +async function assertRequestedContainerNameAvailable(input: { + deployInput: z.infer; + serverId: string; +}) { + if (!shouldValidateRequestedContainerName(input.deployInput)) return; + + const requestedName = normalizeContainerNameForConflict( + input.deployInput.name, + ); + if (!requestedName) return; + + const containers = await prisma.container.findMany({ + where: { + serverId: input.serverId, + status: { not: "ERROR" }, + }, + select: { + name: true, + }, + }); + const conflict = containers.find( + (container) => + normalizeContainerNameForConflict(container.name) === requestedName, + ); + + if (conflict) { + throw new Error( + `Container name "${input.deployInput.name}" is already used on the selected server.`, + ); + } +} + function parseEnvironmentVariables(env: string): string[] { return env .split("\n") @@ -2654,6 +2851,45 @@ export async function containerRoutes(app: FastifyInstance) { } } + const shouldValidateHostPorts = + collectRequestedHostPorts(body.data).length > 0; + const shouldValidateContainerName = + shouldValidateRequestedContainerName(body.data); + + if (shouldValidateHostPorts || shouldValidateContainerName) { + try { + await syncContainersForServers([server], req.userId, (event) => + recordDockerCommandTiming(app, event), + ); + + if (shouldValidateContainerName) { + await assertRequestedContainerNameAvailable({ + deployInput: body.data, + serverId, + }); + } + + if (shouldValidateHostPorts) { + await assertRequestedHostPortsAvailable({ + deployInput: body.data, + serverId, + }); + } + } catch (error) { + const errorMessage = redactSecret( + error instanceof Error + ? error.message + : "Failed to validate requested deployment target", + accessToken, + ); + + return reply.status(400).send({ + success: false, + error: errorMessage, + }); + } + } + if (sourceType === "MANUAL" && deployMode === "IMAGE") { const image = toOptionalValue(rest.image)!;