diff --git a/CLAUDE.md b/CLAUDE.md
index 6a556dae182..1b847911db3 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -20,7 +20,7 @@ Build commands in `services/application.ts` and `services/compose.ts` go through
## Deployment logs
-A deployment's log stays where it was written. Reads and single removals find that place through `getDeploymentLogServerId` (`packages/server/src/utils/deployments/log-server.ts`): the row's build server, otherwise the owning service's server, otherwise the panel. `deployment.serverId` is the exception: it marks a server's setup or hardening run, whose log the panel keeps on its own disk, so nothing connects to that server for it and `getAccessibleServerIds` is the only organization check on reading it. Deleting an application cascades to its deployment rows before `removeDeployments` runs, so past build servers come from the rows loaded with the application. `removeDeployment` keeps the row when the log could not be removed, so the removal can be repeated. The rotation of old deployments drops the row anyway and opens one connection per server, so a dead server neither stops a new deployment nor delays later ones again.
+A deployment's log stays where it was written. Reads and single removals find that place through `getDeploymentLogServerId` (`packages/server/src/utils/deployments/log-server.ts`): the row's build server, otherwise the owning service's server, otherwise the panel. `deployment.serverId` is the exception: it marks a server's setup or hardening run, whose log the panel keeps on its own disk, so nothing connects to that server for it. Reading, killing or removing a deployment that belongs to no service (such a run, or a run of a host schedule) needs an owner or admin, besides `getAccessibleServerIds` (taken from upstream v0.31.1). Deleting an application cascades to its deployment rows before `removeDeployments` runs, so past build servers come from the rows loaded with the application. `removeDeployment` keeps the row when the log could not be removed, so the removal can be repeated. The rotation of old deployments drops the row anyway and opens one connection per server, so a dead server neither stops a new deployment nor delays later ones again.
## libSQL replicas
@@ -48,6 +48,8 @@ The panel's password change (`changeRedisPassword`, `utils/databases/redis-passw
The Server Security dialog (`routers/server-security.ts`, `services/server-security.ts`) runs root commands over SSH on remote servers, and its writes need `server:create`; the fork's Apply hardening button lives in that dialog now. `banFail2banIp` refuses the panel's address only when `webServerSettings.serverIp` is set and matches, so a panel that reaches the server from another address can still ban itself. `togglePanelPort` publishes or removes port 3000 on the panel's service, and the fork's update path has not been checked against a removed port. PostHog code stays, but `getPostHogKey` returns null unless `IS_CLOUD`, so a self-hosted panel contacts nobody. Upstream's Bitbucket watch paths are reachable only with a service Deploy Webhook Secret: `isProviderDeployWebhookAuthenticated` refuses every Bitbucket webhook without one, so upstream's `bitbucket-watch-paths.test.ts` is left out. Upstream's 3 s task loop in `mechanizeDockerContainer` is left out too, because `waitForApplicationRollout` covers it with a limit on each read.
+Two features came with v0.31.2. Project export and import (`routers/project-export-import.ts`, `services/project-export-import/`) is open to owners and admins; the bundle holds every secret of the project, encrypted with a passphrase the caller picks, so `api-key-output-guard.ts` refuses `projectExportImport.export` to API keys like the reveal procedures, or a key's holder could decrypt the bundle offline. Connecting a server by one command (`services/server-connect.ts`, `pages/api/connect/[token].ts`) hands out `curl .../api/connect/ | sudo bash`: the token is an HMAC keyed with the SSH key's private key and lives one hour, and the script adds the panel's public key to root's `authorized_keys` and registers the address the request came from. A panel behind an IP allowlist answers the new server only if that server's address is allowed.
+
Deploy webhooks (`pages/api/deploy/[refreshToken].ts`, `compose/[refreshToken].ts`) turn Next's body parser off and read the body themselves (`readDeployWebhookBody`), so a signature is checked against the bytes the provider signed: Gitea marshals its JSON in Go, and `JSON.stringify` of the parsed body is a different text. A request with a provider event header must carry that provider's proof: GitHub `X-Hub-Signature-256` with the GitHub App's webhook secret, GitLab `X-Gitlab-Token` equal to the provider's Deploy Webhook Secret (`webhookSecret`; the OAuth `secret` is accepted only while no webhook secret is set, as before), Gitea `X-Gitea-Signature` (HMAC-SHA256 hex of the raw body) with the new Deploy Webhook Secret of the Gitea provider (`gitea.webhook_secret`, migration 0217, set in the provider dialog and the Secret field of the Gitea webhook). Applications and composes of source type Custom Git have no provider row, and Bitbucket and Soft Serve have no panel-side credentials, so they use the service's own Deploy Webhook Secret (`webhookSecret` on `application` and `compose`, `encryptedText`, migration 0218, generated in the Deployments tab next to the webhook URL): without one their provider-header requests stay refused with 401, which was a deliberate part of the hardening (a token holder could otherwise forge a branch with headers). With one, `isServiceSecretValid` checks the proof of the provider the event header names: Bitbucket Cloud and Data Center `X-Hub-Signature` = `sha256=` (Data Center event `repo:refs_changed`, branch from `changes[].ref.displayId`; Cloud `repo:push`, `push.changes[].new.name`), Soft Serve `X-SoftServe-Signature` = `sha256=` (header and algorithm read from soft-serve's `pkg/webhook`), and for Custom Git also GitHub-style `X-Hub-Signature-256`, GitLab-style `X-Gitlab-Token` equal to the secret, Gitea/Forgejo `X-Gitea-Signature` (or their GitHub-compatible `X-Hub-Signature-256`), so mirrors on self-hosted GitHub/GitLab/Gitea/Forgejo work. A source of type Bitbucket uses the service secret as well; GitHub, GitLab and Gitea sources keep their provider secrets. The secret is read like the webhook token: `application.revealWebhookSecret` / `compose.revealWebhookSecret` (browser session only, `deployment: create`, audit `reveal`), `regenerateWebhookSecret` (browser session, `service: create`, returns the new value once) and `removeWebhookSecret`; `application.one` / `compose.one` answer it redacted, update schemas omit it and duplicating a project does not copy it. `__test__/deploy/service-webhook-secret.test.ts` covers it. A real Soft Serve (`ghcr.io/charmbracelet/soft-serve`, same image as `charmbracelet/soft-serve`) pushing to the real handler under Bun was checked on 2026-11-08: `ssh repo webhook create -e push -s `; Soft Serve refuses webhook URLs on private, loopback and TEST-NET addresses (`pkg/ssrf`), so a local test needs a public-range address assigned to the test box's `lo`. Bitbucket has only been checked with payloads and signatures built per Atlassian's docs. Gitea and Forgejo also send `X-GitHub-Event` and `X-Hub-Signature-256` for GitHub compatibility, so `getProviderByHeader` checks GitHub's header last; with it first, every real Gitea push was read as GitHub and refused with 401 (found with a real Gitea 1.24 on 2026-11-08). A request with no provider header skips the check as before, and for Git sources it ends in 301 "Branch Not Match: the request has no Git provider event header", since the branch is read from the header. `__test__/deploy/gitea-webhook-signature.test.ts` covers it.
`application.one` and `compose.one` return `refreshToken` as `__DOKPLOY_REDACTED_SECRET__`, so the Deployments tab showed and copied `/api/deploy/__DOKPLOY_REDACTED_SECRET__` (found 2026-11-08). It now shows the URL with dots and, on the first click (copy), calls `application.revealWebhookToken` or `compose.revealWebhookToken`: browser session only (`api-key-output-guard.ts` refuses API keys), the `deployment: create` permission on that service, and a `reveal` audit entry. Regenerating the token forgets the answer. `__test__/components/webhook-url-reveal.test.ts` guards it.
diff --git a/README.md b/README.md
index b58e7b58a38..e933db27243 100644
--- a/README.md
+++ b/README.md
@@ -263,7 +263,7 @@ Dokploy includes multiple features to make your life easier.
- **Backups**: Automate backups for databases to an external storage destination.
- **Docker Compose**: Native support for Docker Compose to manage complex applications.
- **Multi Node**: Scale applications to multiple nodes using Docker Swarm to manage the cluster.
-- **Templates**: Deploy open-source templates (Plausible, Pocketbase, Calcom, etc.) with a single click.
+- **Templates**: Deploy open-source templates (Plausible, Pocketbase, Calcom, etc.) with a single click +600 Templates.
- **Traefik Integration**: Automatically integrates with Traefik for routing and load balancing.
- **Real-time Monitoring**: Monitor CPU, memory, storage, and network usage for every resource.
- **Logs & Metrics**: Ship container logs and host/container metrics to Grafana (Loki, Prometheus/Mimir), Datadog, New Relic, InfluxDB, VictoriaMetrics, Better Stack, Elasticsearch/OpenSearch, Splunk, or AWS CloudWatch, tagged by project/environment/application.
diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts
index cc865dcbdcd..227ec5edef0 100644
--- a/apps/api/src/auth.ts
+++ b/apps/api/src/auth.ts
@@ -1,3 +1,5 @@
+import { timingSafeEqual } from "node:crypto";
+
export const isValidApiKey = (
configuredKey: string | undefined,
authHeader: string | undefined,
@@ -6,6 +8,13 @@ export const isValidApiKey = (
typeof configuredKey === "string" && configuredKey.trim().length > 0;
const hasAuthHeader =
typeof authHeader === "string" && authHeader.trim().length > 0;
+ if (!hasConfiguredKey || !hasAuthHeader) {
+ return false;
+ }
- return hasConfiguredKey && hasAuthHeader && configuredKey === authHeader;
+ const expected = Buffer.from(configuredKey);
+ const received = Buffer.from(authHeader);
+ return (
+ expected.length === received.length && timingSafeEqual(expected, received)
+ );
};
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index d78c7a554ca..c0945f3c790 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -108,6 +108,12 @@ export const deploymentFunction = inngest.createFunction(
},
);
+if (!process.env.API_KEY) {
+ console.error(
+ "API_KEY is not set; all authenticated routes will be rejected",
+ );
+}
+
app.use(async (c, next) => {
if (c.req.path === "/health" || c.req.path === "/api/inngest") {
return next();
diff --git a/apps/dokploy/__test__/application/provider-status.test.ts b/apps/dokploy/__test__/application/provider-status.test.ts
index bdaae9e5c9f..2bdf8e049e9 100644
--- a/apps/dokploy/__test__/application/provider-status.test.ts
+++ b/apps/dokploy/__test__/application/provider-status.test.ts
@@ -15,6 +15,7 @@ vi.mock("@dokploy/server/index", async (importOriginal) => {
IS_CLOUD: true,
hasValidLicense: vi.fn(async () => false),
updateApplication: mockUpdateApplication,
+ assertServiceCredentialAccess: vi.fn(async () => {}),
findApplicationById: vi.fn(async () => ({
applicationId: "app-1",
appName: "example-app",
diff --git a/apps/dokploy/__test__/auth/api-key-session.test.ts b/apps/dokploy/__test__/auth/api-key-session.test.ts
index 33cfdb85f27..a251fb66f3a 100644
--- a/apps/dokploy/__test__/auth/api-key-session.test.ts
+++ b/apps/dokploy/__test__/auth/api-key-session.test.ts
@@ -121,11 +121,14 @@ const { organization } = await import("better-auth/plugins");
const drizzleAdapterOptions = vi.mocked(drizzleAdapter).mock.calls[0]?.[1];
const organizationOptions = vi.mocked(organization).mock.calls[0]?.[0];
-const apiKeyRequest = {
- headers: {
- "x-api-key": "dokploy-test-key",
- },
-} as unknown as IncomingMessage;
+// validateRequest keeps its answer per request object, so every case needs
+// its own request.
+const apiKeyRequest = () =>
+ ({
+ headers: {
+ "x-api-key": "dokploy-test-key",
+ },
+ }) as unknown as IncomingMessage;
const userRecord = {
id: "user-1",
@@ -180,7 +183,7 @@ describe("validateRequest API key sessions", () => {
});
mocks.checkPermission.mockRejectedValue(new Error("Permission denied"));
- await expect(validateRequest(apiKeyRequest)).resolves.toEqual({
+ await expect(validateRequest(apiKeyRequest())).resolves.toEqual({
session: null,
user: null,
});
@@ -189,7 +192,7 @@ describe("validateRequest API key sessions", () => {
it("rejects API key metadata for an organization the key owner is not a member of", async () => {
mocks.memberFindFirst.mockResolvedValue(undefined);
- await expect(validateRequest(apiKeyRequest)).resolves.toEqual({
+ await expect(validateRequest(apiKeyRequest())).resolves.toEqual({
session: null,
user: null,
});
@@ -203,7 +206,7 @@ describe("validateRequest API key sessions", () => {
},
});
- await expect(validateRequest(apiKeyRequest)).resolves.toMatchObject({
+ await expect(validateRequest(apiKeyRequest())).resolves.toMatchObject({
session: {
userId: "user-1",
activeOrganizationId: "org-1",
@@ -222,12 +225,35 @@ describe("validateRequest API key sessions", () => {
{ api: ["read"] },
);
});
+
+ it("verifies the API key once when the same request is validated twice", async () => {
+ mocks.memberFindFirst.mockResolvedValue({
+ role: "owner",
+ organization: {
+ ownerId: "user-1",
+ },
+ });
+ const request = apiKeyRequest();
+
+ const first = await validateRequest(request);
+ const second = await validateRequest(request);
+
+ expect(second).toBe(first);
+ expect(first).toMatchObject({
+ session: { userId: "user-1", activeOrganizationId: "org-1" },
+ });
+ expect(mocks.verifyApiKey).toHaveBeenCalledTimes(1);
+
+ await validateRequest(apiKeyRequest());
+ expect(mocks.verifyApiKey).toHaveBeenCalledTimes(2);
+ });
});
describe("validateRequest cookie sessions", () => {
- const cookieRequest = {
- headers: { cookie: "better-auth.session_token=token" },
- } as unknown as IncomingMessage;
+ const cookieRequest = () =>
+ ({
+ headers: { cookie: "better-auth.session_token=token" },
+ }) as unknown as IncomingMessage;
beforeEach(() => {
vi.clearAllMocks();
@@ -248,7 +274,7 @@ describe("validateRequest cookie sessions", () => {
user: { enableEnterpriseFeatures: true, isValidEnterpriseLicense: true },
});
- await expect(validateRequest(cookieRequest)).resolves.toMatchObject({
+ await expect(validateRequest(cookieRequest())).resolves.toMatchObject({
session: { id: "session-1", activeOrganizationId: "org-1" },
user: {
id: "user-1",
@@ -263,7 +289,7 @@ describe("validateRequest cookie sessions", () => {
it("falls back to the user itself when there is no membership", async () => {
mocks.memberFindFirst.mockResolvedValue(undefined);
- await expect(validateRequest(cookieRequest)).resolves.toMatchObject({
+ await expect(validateRequest(cookieRequest())).resolves.toMatchObject({
session: { activeOrganizationId: "" },
user: {
id: "user-1",
diff --git a/apps/dokploy/__test__/backups/backup-destination-organization.test.ts b/apps/dokploy/__test__/backups/backup-destination-organization.test.ts
index e5a2f369ea4..14804c89231 100644
--- a/apps/dokploy/__test__/backups/backup-destination-organization.test.ts
+++ b/apps/dokploy/__test__/backups/backup-destination-organization.test.ts
@@ -80,6 +80,12 @@ const caller = backupRouter.createCaller({
user: { id: "user-1", email: "user@example.com", role: "owner" },
} as Parameters[0]);
+const callerAs = (role: string) =>
+ backupRouter.createCaller({
+ session: { activeOrganizationId: "org-a" },
+ user: { id: "user-1", email: "user@example.com", role },
+ } as Parameters[0]);
+
const ownDestination = { destinationId: "dest-a", organizationId: "org-a" };
const foreignDestination = { destinationId: "dest-b", organizationId: "org-b" };
@@ -113,6 +119,13 @@ const restoreInput = {
backupFile: "app/2024.sql.gz",
};
+const postgresSchedule = {
+ appName: "app",
+ prefix: "/",
+ postgres: { appName: "app" },
+};
+const webServerSchedule = { appName: "panel", prefix: "/" };
+
const drain = async (stream: unknown) => {
for await (const _ of stream as AsyncIterable) {
}
@@ -130,11 +143,12 @@ describe("backup endpoints scope destinations to the active organization", () =>
databaseType: "postgres",
backupType: "database",
});
- mocks.findPostgresById.mockResolvedValue({ postgresId: "pg-1" });
+ mocks.findPostgresById.mockResolvedValue({
+ postgresId: "pg-1",
+ appName: "app",
+ });
// The fork only restores objects under a schedule of the same database.
- mocks.findRestoreBackups.mockResolvedValue([
- { appName: "app", prefix: "/", postgres: { appName: "app" } },
- ]);
+ mocks.findRestoreBackups.mockResolvedValue([postgresSchedule]);
});
it("rejects creating a backup on a destination from another organization", async () => {
@@ -193,9 +207,7 @@ describe("backup endpoints scope destinations to the active organization", () =>
expect(mocks.restorePostgresBackup).toHaveBeenCalledTimes(1);
});
- // Upstream leaves service-less web-server schedules unscoped; the fork
- // scopes their destination like every other schedule.
- it("rejects web-server schedules on a destination from another organization", async () => {
+ it("rejects a service-less web-server schedule on a foreign destination", async () => {
mocks.findDestinationRow.mockResolvedValue(foreignDestination);
await expect(
@@ -211,3 +223,74 @@ describe("backup endpoints scope destinations to the active organization", () =>
expect(mocks.createBackup).not.toHaveBeenCalled();
});
});
+
+describe("restore access by role", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.findPostgresById.mockResolvedValue({
+ postgresId: "pg-1",
+ appName: "app",
+ });
+ });
+
+ // Web-server backups live under the schedule's appName folder, and the fork
+ // restores only objects under a schedule on that destination.
+ const webServerRestore = {
+ databaseId: "",
+ databaseType: "web-server" as const,
+ backupType: "database" as const,
+ databaseName: "panel",
+ backupFile: "panel/panel.zip",
+ destinationId: "dest-a",
+ };
+
+ for (const role of ["owner", "admin"]) {
+ it(`${role} can run a web-server restore`, async () => {
+ mocks.findDestinationRow.mockResolvedValue(ownDestination);
+ mocks.findRestoreBackups.mockResolvedValue([webServerSchedule]);
+ const stream =
+ await callerAs(role).restoreBackupWithLogs(webServerRestore);
+ await drain(stream);
+ expect(mocks.restoreWebServerBackup).toHaveBeenCalledTimes(1);
+ });
+ }
+
+ it("a member cannot run a web-server restore (panel wipe)", async () => {
+ mocks.findDestinationRow.mockResolvedValue(ownDestination);
+ mocks.findRestoreBackups.mockResolvedValue([webServerSchedule]);
+ const stream =
+ await callerAs("member").restoreBackupWithLogs(webServerRestore);
+ await expect(drain(stream)).rejects.toMatchObject({ code: "UNAUTHORIZED" });
+ expect(mocks.restoreWebServerBackup).not.toHaveBeenCalled();
+ });
+
+ it("a member with service access can still restore its own database", async () => {
+ mocks.findDestinationRow.mockResolvedValue(ownDestination);
+ mocks.findRestoreBackups.mockResolvedValue([postgresSchedule]);
+ const stream = await callerAs("member").restoreBackupWithLogs({
+ ...restoreInput,
+ destinationId: "dest-a",
+ });
+ await drain(stream);
+ expect(mocks.restorePostgresBackup).toHaveBeenCalledTimes(1);
+ });
+
+ it("refuses a backup file outside the target service's folder", async () => {
+ mocks.findDestinationRow.mockResolvedValue(ownDestination);
+ mocks.findRestoreBackups.mockResolvedValue([postgresSchedule]);
+ mocks.findPostgresById.mockResolvedValue({
+ postgresId: "pg-1",
+ appName: "other",
+ });
+ const stream = await callerAs("member").restoreBackupWithLogs({
+ ...restoreInput,
+ destinationId: "dest-a",
+ });
+ await expect(drain(stream)).rejects.toMatchObject({
+ message: expect.stringContaining(
+ "Backup file does not belong to this service",
+ ),
+ });
+ expect(mocks.restorePostgresBackup).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/dokploy/__test__/backups/volume-backup-destination-organization.test.ts b/apps/dokploy/__test__/backups/volume-backup-destination-organization.test.ts
index ce97e6a3ec9..8583cc96323 100644
--- a/apps/dokploy/__test__/backups/volume-backup-destination-organization.test.ts
+++ b/apps/dokploy/__test__/backups/volume-backup-destination-organization.test.ts
@@ -44,6 +44,7 @@ vi.mock("@dokploy/server", async (importOriginal) => ({
removeVolumeBackup: vi.fn(),
restoreVolume: vi.fn(),
runVolumeBackup: vi.fn(),
+ assertVolumeBelongsToService: vi.fn(async () => {}),
}));
vi.mock("@dokploy/server/lib/auth", () => ({
diff --git a/apps/dokploy/__test__/certificate/certificate-router-assigned-server.test.ts b/apps/dokploy/__test__/certificate/certificate-router-assigned-server.test.ts
index 1b32f369dc1..1370e048701 100644
--- a/apps/dokploy/__test__/certificate/certificate-router-assigned-server.test.ts
+++ b/apps/dokploy/__test__/certificate/certificate-router-assigned-server.test.ts
@@ -1,7 +1,9 @@
import { REDACTED_SECRET_VALUE } from "@dokploy/server/utils/security/redaction";
+import { TRPCError } from "@trpc/server";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
+ assertServerAccess: vi.fn(),
audit: vi.fn(),
certificateFindMany: vi.fn(),
checkPermission: vi.fn(),
@@ -14,6 +16,7 @@ const mocks = vi.hoisted(() => ({
vi.mock("@dokploy/server", () => ({
IS_CLOUD: true,
+ assertServerAccess: mocks.assertServerAccess,
createCertificate: mocks.createCertificate,
findCertificateById: mocks.findCertificateById,
getAccessibleServerIds: mocks.getAccessibleServerIds,
@@ -71,6 +74,17 @@ const createCaller = () =>
describe("certificate router assigned-server boundary", () => {
beforeEach(() => {
vi.clearAllMocks();
+ // The rule of the real helper on the cloud, over the mocked server list.
+ mocks.assertServerAccess.mockImplementation(
+ async (session: unknown, serverId?: string | null) => {
+ const accessible = serverId
+ ? await mocks.getAccessibleServerIds(session)
+ : null;
+ if (!accessible?.has(serverId)) {
+ throw new TRPCError({ code: "UNAUTHORIZED" });
+ }
+ },
+ );
mocks.checkPermission.mockResolvedValue(undefined);
mocks.createCertificate.mockResolvedValue({
certificateId: "certificate-1",
@@ -197,6 +211,18 @@ describe("certificate router assigned-server boundary", () => {
{ code: "UNAUTHORIZED" },
);
+ expect(mocks.assertServerAccess).toHaveBeenCalledWith(
+ expect.objectContaining({ userId: "user-1" }),
+ "server-1",
+ );
+ expect(mocks.createCertificate).not.toHaveBeenCalled();
+ });
+
+ it("denies cloud certificate creation without a server before file writes", async () => {
+ await expect(
+ createCaller().create({ ...certificateInput, serverId: undefined }),
+ ).rejects.toMatchObject({ code: "UNAUTHORIZED" });
+
expect(mocks.createCertificate).not.toHaveBeenCalled();
});
diff --git a/apps/dokploy/__test__/deployment/deployment-router-assigned-server.test.ts b/apps/dokploy/__test__/deployment/deployment-router-assigned-server.test.ts
index e88040c9929..8eb581bda92 100644
--- a/apps/dokploy/__test__/deployment/deployment-router-assigned-server.test.ts
+++ b/apps/dokploy/__test__/deployment/deployment-router-assigned-server.test.ts
@@ -131,7 +131,7 @@ const { deploymentRouter } = await import(
"../../server/api/routers/deployment"
);
-const createCaller = () =>
+const createCaller = (role = "member") =>
deploymentRouter.createCaller({
db: {},
req: {},
@@ -142,7 +142,7 @@ const createCaller = () =>
},
user: {
id: "user-1",
- role: "member",
+ role,
},
} as never);
@@ -434,11 +434,37 @@ describe("deployment router assigned-server boundary", () => {
expect(mocks.findAllDeploymentsByServerId).not.toHaveBeenCalled();
});
- it("filters cloud deployment queue jobs to accessible servers", async () => {
+ it.each(["owner", "admin"])(
+ "filters cloud deployment queue jobs to accessible servers for an %s",
+ async (role) => {
+ mocks.getAccessibleServerIds.mockResolvedValue(new Set(["server-1"]));
+
+ await expect(createCaller(role).queueList()).resolves.toEqual([
+ { id: "server-1-job", serverId: "server-1", servicePath: undefined },
+ ]);
+
+ expect(mocks.fetchDeployApiJobs).toHaveBeenCalledTimes(1);
+ expect(mocks.fetchDeployApiJobs).toHaveBeenCalledWith("server-1");
+ },
+ );
+
+ it("shows a member only cloud queue jobs of services shared with them", async () => {
mocks.getAccessibleServerIds.mockResolvedValue(new Set(["server-1"]));
+ mocks.fetchDeployApiJobs.mockImplementation((serverId: string) =>
+ Promise.resolve([
+ { id: "shared-job", serverId, data: { applicationId: "app-1" } },
+ { id: "other-job", serverId, data: { composeId: "compose-9" } },
+ { id: "setup-job", serverId, data: { serverId } },
+ ]),
+ );
await expect(createCaller().queueList()).resolves.toEqual([
- { id: "server-1-job", serverId: "server-1", servicePath: undefined },
+ {
+ id: "shared-job",
+ serverId: "server-1",
+ data: { applicationId: "app-1" },
+ servicePath: undefined,
+ },
]);
expect(mocks.fetchDeployApiJobs).toHaveBeenCalledTimes(1);
@@ -837,7 +863,35 @@ describe("deployment router assigned-server boundary", () => {
expect(mocks.execAsyncRemote).not.toHaveBeenCalled();
});
- it("reads a server setup log on the panel, after checking access to that server", async () => {
+ it.each(["owner", "admin"])(
+ "reads a server setup log on the panel for an %s, after checking access to that server",
+ async (role) => {
+ mocks.isCloud = false;
+ mocks.findMemberByUserId.mockResolvedValue({ role });
+ mocks.execAsync.mockResolvedValue({ stdout: "setup logs" });
+ mocks.getAccessibleServerIds.mockResolvedValue(new Set(["server-1"]));
+ mocks.findDeploymentById.mockResolvedValue({
+ deploymentId: "deployment-1",
+ logPath: "/tmp/deployment.log",
+ serverId: "server-1",
+ });
+
+ await expect(
+ createCaller(role).readLogs({
+ deploymentId: "deployment-1",
+ tail: 100,
+ }),
+ ).resolves.toBe("setup logs");
+
+ expect(mocks.assertTargetServerAccess).toHaveBeenCalledWith(
+ expect.anything(),
+ "server-1",
+ );
+ expect(mocks.execAsyncRemote).not.toHaveBeenCalled();
+ },
+ );
+
+ it("keeps a server setup log away from a member with access to that server", async () => {
mocks.isCloud = false;
mocks.execAsync.mockResolvedValue({ stdout: "setup logs" });
mocks.getAccessibleServerIds.mockResolvedValue(new Set(["server-1"]));
@@ -849,12 +903,9 @@ describe("deployment router assigned-server boundary", () => {
await expect(
createCaller().readLogs({ deploymentId: "deployment-1", tail: 100 }),
- ).resolves.toBe("setup logs");
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
- expect(mocks.assertTargetServerAccess).toHaveBeenCalledWith(
- expect.anything(),
- "server-1",
- );
+ expect(mocks.execAsync).not.toHaveBeenCalled();
expect(mocks.execAsyncRemote).not.toHaveBeenCalled();
});
@@ -952,10 +1003,6 @@ describe("deployment router assigned-server boundary", () => {
},
},
},
- {
- owner: "server schedule",
- deployment: { schedule: { serverId: "server-1" } },
- },
])(
"reads the $owner deployment log from the server that holds it",
async ({ deployment }) => {
@@ -977,6 +1024,50 @@ describe("deployment router assigned-server boundary", () => {
},
);
+ it.each(["owner", "admin"])(
+ "reads the server schedule deployment log from the server that holds it for an %s",
+ async (role) => {
+ mocks.findMemberByUserId.mockResolvedValue({ role });
+ mocks.findDeploymentById.mockResolvedValue({
+ deploymentId: "deployment-1",
+ logPath: "/tmp/deployment.log",
+ schedule: { serverId: "server-1" },
+ });
+
+ await expect(
+ createCaller(role).readLogs({
+ deploymentId: "deployment-1",
+ tail: 100,
+ }),
+ ).resolves.toBe("logs");
+
+ expect(mocks.assertTargetServerAccess).toHaveBeenCalledWith(
+ expect.anything(),
+ "server-1",
+ );
+ expect(mocks.execAsyncRemote).toHaveBeenCalledWith(
+ "server-1",
+ expect.stringContaining('tail -n 100 "/tmp/deployment.log"'),
+ );
+ expect(mocks.execAsync).not.toHaveBeenCalled();
+ },
+ );
+
+ it("keeps a server schedule deployment log away from a member with access to that server", async () => {
+ mocks.findDeploymentById.mockResolvedValue({
+ deploymentId: "deployment-1",
+ logPath: "/tmp/deployment.log",
+ schedule: { scheduleType: "server", serverId: "server-1" },
+ });
+
+ await expect(
+ createCaller().readLogs({ deploymentId: "deployment-1", tail: 100 }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+
+ expect(mocks.execAsyncRemote).not.toHaveBeenCalled();
+ expect(mocks.execAsync).not.toHaveBeenCalled();
+ });
+
it("reads a deployment log locally when the service runs on the panel", async () => {
mocks.isCloud = false;
mocks.execAsync.mockResolvedValue({ stdout: "local logs" });
@@ -1315,23 +1406,40 @@ describe("deployment router assigned-server boundary", () => {
});
describe("server schedule", () => {
- it("kills a run on the schedule's server", async () => {
+ it.each(["owner", "admin"])(
+ "lets an %s kill a run on the schedule's server",
+ async (role) => {
+ mocks.findMemberByUserId.mockResolvedValue({ role });
+ mocks.findDeploymentById.mockResolvedValue(
+ scheduleRun(serverSchedule),
+ );
+
+ await killRun();
+
+ expect(mocks.checkPermission).toHaveBeenCalledWith(
+ expect.anything(),
+ { deployment: ["cancel"] },
+ );
+ expect(mocks.assertTargetServerAccess).toHaveBeenCalledWith(
+ expect.anything(),
+ "server-1",
+ );
+ expect(mocks.execAsyncRemote).toHaveBeenCalledWith(
+ "server-1",
+ KILL_RUN,
+ );
+ expect(mocks.execAsync).not.toHaveBeenCalled();
+ },
+ );
+
+ it("refuses both actions for a member with access to the schedule's server", async () => {
mocks.findDeploymentById.mockResolvedValue(scheduleRun(serverSchedule));
- await killRun();
+ await expect(killRun()).rejects.toMatchObject({ code: "FORBIDDEN" });
+ await expect(removeRun()).rejects.toMatchObject({ code: "FORBIDDEN" });
- expect(mocks.checkPermission).toHaveBeenCalledWith(expect.anything(), {
- deployment: ["cancel"],
- });
- expect(mocks.assertTargetServerAccess).toHaveBeenCalledWith(
- expect.anything(),
- "server-1",
- );
- expect(mocks.execAsyncRemote).toHaveBeenCalledWith(
- "server-1",
- KILL_RUN,
- );
- expect(mocks.execAsync).not.toHaveBeenCalled();
+ expectNoProcessSideEffects();
+ expect(mocks.removeDeployment).not.toHaveBeenCalled();
});
it("does not let a service left on the row replace the server check", async () => {
@@ -1382,7 +1490,26 @@ describe("deployment router assigned-server boundary", () => {
);
});
- it("kills a server-bound run on its server, never on the panel", async () => {
+ it.each(["owner", "admin"])(
+ "kills a server-bound run on its server for an %s, never on the panel",
+ async (role) => {
+ mocks.isCloud = false;
+ mocks.findMemberByUserId.mockResolvedValue({ role });
+ mocks.findDeploymentById.mockResolvedValue({
+ deploymentId: "deployment-1",
+ pid: "1234",
+ serverId: "server-1",
+ status: "running",
+ });
+
+ await createCaller(role).killProcess({ deploymentId: "deployment-1" });
+
+ expect(mocks.execAsyncRemote).toHaveBeenCalledWith("server-1", KILL_RUN);
+ expect(mocks.execAsync).not.toHaveBeenCalled();
+ },
+ );
+
+ it("refuses to kill or remove a server-bound run for a member with access to that server", async () => {
mocks.isCloud = false;
mocks.findDeploymentById.mockResolvedValue({
deploymentId: "deployment-1",
@@ -1391,10 +1518,17 @@ describe("deployment router assigned-server boundary", () => {
status: "running",
});
- await createCaller().killProcess({ deploymentId: "deployment-1" });
+ await expect(
+ createCaller().killProcess({ deploymentId: "deployment-1" }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ await expect(
+ createCaller().removeDeployment({ deploymentId: "deployment-1" }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
- expect(mocks.execAsyncRemote).toHaveBeenCalledWith("server-1", KILL_RUN);
expect(mocks.execAsync).not.toHaveBeenCalled();
+ expect(mocks.execAsyncRemote).not.toHaveBeenCalled();
+ expect(mocks.updateDeploymentStatus).not.toHaveBeenCalled();
+ expect(mocks.removeDeployment).not.toHaveBeenCalled();
});
it("denies backup deployment logs through the owning backup service before log reads", async () => {
diff --git a/apps/dokploy/__test__/domain/domain-create-authz.test.ts b/apps/dokploy/__test__/domain/domain-create-authz.test.ts
new file mode 100644
index 00000000000..9de0a0171cf
--- /dev/null
+++ b/apps/dokploy/__test__/domain/domain-create-authz.test.ts
@@ -0,0 +1,98 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ createDomain: vi.fn(),
+ findPreviewDeploymentById: vi.fn(),
+ checkServiceAccess: vi.fn(),
+}));
+
+vi.mock("@dokploy/server", async (importOriginal) => ({
+ ...(await importOriginal()),
+ createDomain: mocks.createDomain,
+ findPreviewDeploymentById: mocks.findPreviewDeploymentById,
+}));
+vi.mock("@dokploy/server/services/permission", () => ({
+ checkServicePermissionAndAccess: mocks.checkServiceAccess,
+ checkPermission: vi.fn(async () => undefined),
+}));
+vi.mock("@/server/api/utils/audit", () => ({
+ audit: vi.fn(async () => undefined),
+}));
+
+const { domainRouter } = await import("@/server/api/routers/domain");
+
+const callerAs = (role: string) =>
+ domainRouter.createCaller({
+ user: { id: "u1", role },
+ session: { activeOrganizationId: "org-a" },
+ } as never);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.createDomain.mockResolvedValue({
+ domainId: "d1",
+ host: "x.example.com",
+ });
+ mocks.findPreviewDeploymentById.mockResolvedValue({ applicationId: "app-1" });
+});
+
+describe("domain.create — authorized users still create domains", () => {
+ for (const role of ["owner", "admin", "member"]) {
+ it(`${role} with access creates an application domain`, async () => {
+ mocks.checkServiceAccess.mockResolvedValue(undefined);
+ await callerAs(role).create({
+ host: "x.example.com",
+ applicationId: "app-1",
+ domainType: "application",
+ customCertResolver: "",
+ } as never);
+ expect(mocks.checkServiceAccess).toHaveBeenCalledWith(
+ expect.anything(),
+ "app-1",
+ { domain: ["create"] },
+ );
+ expect(mocks.createDomain).toHaveBeenCalledTimes(1);
+ });
+ }
+
+ it("still authorizes and creates when domainType is omitted", async () => {
+ mocks.checkServiceAccess.mockResolvedValue(undefined);
+ await callerAs("member").create({
+ host: "x.example.com",
+ applicationId: "app-1",
+ customCertResolver: "",
+ } as never);
+ expect(mocks.checkServiceAccess).toHaveBeenCalledWith(
+ expect.anything(),
+ "app-1",
+ { domain: ["create"] },
+ );
+ expect(mocks.createDomain).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("domain.create — unauthorized is blocked", () => {
+ it("rejects when the caller lacks access to the service (even with omitted domainType)", async () => {
+ mocks.checkServiceAccess.mockRejectedValue(
+ Object.assign(new Error("UNAUTHORIZED"), { code: "UNAUTHORIZED" }),
+ );
+ await expect(
+ callerAs("member").create({
+ host: "x.example.com",
+ applicationId: "victim-app",
+ customCertResolver: "",
+ } as never),
+ ).rejects.toBeTruthy();
+ expect(mocks.createDomain).not.toHaveBeenCalled();
+ });
+
+ it("rejects when no service id is provided", async () => {
+ await expect(
+ callerAs("owner").create({
+ host: "x.example.com",
+ customCertResolver: "",
+ } as never),
+ ).rejects.toBeTruthy();
+ expect(mocks.createDomain).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/dokploy/__test__/drop/drop-zip-slip-within-basepath.test.ts b/apps/dokploy/__test__/drop/drop-zip-slip-within-basepath.test.ts
new file mode 100644
index 00000000000..ba171e40808
--- /dev/null
+++ b/apps/dokploy/__test__/drop/drop-zip-slip-within-basepath.test.ts
@@ -0,0 +1,73 @@
+import { File as NodeFile } from "node:buffer";
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { unzipDrop } from "@dokploy/server";
+import AdmZip from "adm-zip";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+// Production layout: BASE_PATH is the PARENT of APPLICATIONS_PATH
+// (/etc/dokploy vs /etc/dokploy/applications). The existing GHSA-66v7 test
+// collapses them to the same dir, so it only catches escapes that leave
+// BASE_PATH entirely. This reproduces the in-BASE_PATH escape instead.
+const TMP = path.join(os.tmpdir(), `dokploy-zipslip-${process.pid}`);
+const BASE_PATH = path.join(TMP, "base");
+const APPLICATIONS_PATH = path.join(BASE_PATH, "applications");
+
+vi.mock("@dokploy/server/constants", async (importOriginal) => {
+ const actual = (await importOriginal()) as any;
+ return {
+ ...actual,
+ paths: () => ({ ...actual.paths(), BASE_PATH, APPLICATIONS_PATH }),
+ };
+});
+
+if (typeof window === "undefined") {
+ globalThis.File = NodeFile as unknown as typeof globalThis.File;
+ globalThis.FileList = class FileList {} as typeof globalThis.FileList;
+}
+
+const app = { appName: "attacker", serverId: null, buildServerId: null } as any;
+
+describe("zip-slip within BASE_PATH (cross-service write)", () => {
+ beforeAll(async () => {
+ await fs.rm(TMP, { recursive: true, force: true });
+ await fs.mkdir(path.join(APPLICATIONS_PATH, "attacker", "code"), {
+ recursive: true,
+ });
+ });
+ afterAll(async () => {
+ await fs.rm(TMP, { recursive: true, force: true });
+ });
+
+ it("rejects an entry that escapes the app dir but stays under BASE_PATH", async () => {
+ const traversalEntry = "../../victim/code/pwned.txt";
+ const placeholder = "x".repeat(traversalEntry.length);
+ const zip = new AdmZip();
+ zip.addFile("package.json", Buffer.from('{"name":"a","version":"1.0.0"}'));
+ zip.addFile(placeholder, Buffer.from("PWNED"));
+ let buf = Buffer.from(zip.toBuffer());
+ buf = Buffer.from(
+ buf.toString("binary").split(placeholder).join(traversalEntry),
+ "binary",
+ );
+ const file = new File([buf as unknown as ArrayBuffer], "exploit.zip");
+
+ await expect(unzipDrop(file, app)).rejects.toThrow(
+ /resolved path escapes output directory/,
+ );
+
+ const victimFile = path.join(
+ APPLICATIONS_PATH,
+ "victim",
+ "code",
+ "pwned.txt",
+ );
+ const written = await fs
+ .readFile(victimFile, "utf8")
+ .then((c) => c)
+ .catch(() => null);
+
+ expect(written).toBeNull();
+ });
+});
diff --git a/apps/dokploy/__test__/env/vault-provider-secret-binding.test.ts b/apps/dokploy/__test__/env/vault-provider-secret-binding.test.ts
index d2273624b16..489764a3370 100644
--- a/apps/dokploy/__test__/env/vault-provider-secret-binding.test.ts
+++ b/apps/dokploy/__test__/env/vault-provider-secret-binding.test.ts
@@ -89,18 +89,56 @@ describe("vault provider stored secret binding", () => {
message: "Re-enter the vault provider credentials to change url",
}),
);
+ });
- expect(
+ it("rejects reading another HashiCorp mount with a kept token", () => {
+ expect(() =>
mergeVaultProviderConfig(
{ ...storedHashicorp, token: VAULT_SECRET_MASK, mount: "kv" },
storedHashicorp,
),
- ).toEqual({ ...storedHashicorp, mount: "kv" });
+ ).toThrow(
+ expect.objectContaining({
+ code: "BAD_REQUEST",
+ message: "Re-enter the vault provider credentials to change mount",
+ }),
+ );
+ });
+
+ it("names every changed HashiCorp field when a kept token would follow them", () => {
+ expect(() =>
+ mergeVaultProviderConfig(
+ {
+ ...storedHashicorp,
+ url: "https://collector.example.net",
+ token: VAULT_SECRET_MASK,
+ mount: "kv",
+ },
+ storedHashicorp,
+ ),
+ ).toThrow(
+ expect.objectContaining({
+ code: "BAD_REQUEST",
+ message: "Re-enter the vault provider credentials to change url, mount",
+ }),
+ );
+ });
+
+ it("keeps the stored HashiCorp token when nothing else changes", () => {
+ expect(
+ mergeVaultProviderConfig(
+ { ...storedHashicorp, token: VAULT_SECRET_MASK },
+ storedHashicorp,
+ ),
+ ).toEqual(storedHashicorp);
+ });
+ it("accepts a new HashiCorp URL and mount with a re-entered token", () => {
const reentered = {
...storedHashicorp,
url: "https://vault-new.example.com",
token: "new-token",
+ mount: "kv",
};
expect(mergeVaultProviderConfig(reentered, storedHashicorp)).toEqual(
reentered,
diff --git a/apps/dokploy/__test__/export-import/export-import.test.ts b/apps/dokploy/__test__/export-import/export-import.test.ts
new file mode 100644
index 00000000000..3c193d3f737
--- /dev/null
+++ b/apps/dokploy/__test__/export-import/export-import.test.ts
@@ -0,0 +1,494 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@dokploy/server/db", () => ({ db: {} }));
+vi.mock("@dokploy/server/services/mount", () => ({
+ createFileMount: vi.fn(async () => {}),
+}));
+vi.mock("@dokploy/server/services/application", () => ({
+ findApplicationById: vi.fn(async (applicationId: string) => ({
+ applicationId,
+ domains: [{ domainId: "d" }],
+ security: [{ securityId: "s" }],
+ redirects: [{ redirectId: "r" }],
+ })),
+}));
+vi.mock("@dokploy/server/utils/traefik/domain", () => ({
+ manageDomain: vi.fn(async () => {}),
+}));
+vi.mock("@dokploy/server/utils/traefik/security", () => ({
+ createSecurityMiddleware: vi.fn(async () => {}),
+}));
+vi.mock("@dokploy/server/utils/traefik/redirect", () => ({
+ createRedirectMiddleware: vi.fn(async () => {}),
+}));
+
+import {
+ applications,
+ compose,
+ domains,
+ environments,
+ libsql,
+ mounts,
+ ports,
+ postgres,
+ projects,
+} from "@dokploy/server/db/schema";
+import {
+ BundleCryptoError,
+ BundleFormatError,
+ encryptPayload,
+ exportProject,
+ importBundle,
+ readBundle,
+ replaceAppNames,
+} from "@dokploy/server/services/project-export-import";
+import { createRedirectMiddleware } from "@dokploy/server/utils/traefik/redirect";
+import { createSecurityMiddleware } from "@dokploy/server/utils/traefik/security";
+
+const PASSPHRASE = "correct horse battery";
+
+const sourceTree = () => ({
+ projectId: "p1",
+ name: "Shop",
+ description: null,
+ organizationId: "org-source",
+ env: "DB_URL=postgres://user@shop-db-abc123:5432/app",
+ createdAt: "2026-01-01",
+ projectTags: [{ tag: { name: "prod", color: "#f00" } }],
+ environments: [
+ {
+ environmentId: "e1",
+ name: "production",
+ isDefault: true,
+ env: "",
+ projectId: "p1",
+ createdAt: "2026-01-01",
+ applications: [
+ {
+ applicationId: "a1",
+ name: "web",
+ appName: "shop-web-xyz789",
+ environmentId: "e1",
+ env: "DATABASE_URL=postgres://shop-db-abc123:5432/app",
+ sourceType: "github",
+ githubId: "gh-1",
+ registryId: "reg-1",
+ serverId: "srv-1",
+ networkIds: [],
+ applicationStatus: "done",
+ domains: [
+ {
+ domainId: "d1",
+ host: "shop.example.com",
+ path: "/",
+ enabled: true,
+ uniqueConfigKey: 7,
+ applicationId: "a1",
+ },
+ ],
+ mounts: [
+ {
+ mountId: "m1",
+ type: "file",
+ filePath: "config/app.json",
+ content: "{}",
+ applicationId: "a1",
+ },
+ ],
+ redirects: [],
+ security: [],
+ ports: [{ portId: "po1", publishedPort: 8080, targetPort: 80 }],
+ },
+ ],
+ compose: [],
+ postgres: [
+ {
+ postgresId: "pg1",
+ name: "db",
+ appName: "shop-db-abc123",
+ environmentId: "e1",
+ databasePassword: "secret",
+ externalPort: 5432,
+ serverId: "srv-1",
+ applicationStatus: "done",
+ mounts: [],
+ },
+ ],
+ mysql: [],
+ mariadb: [],
+ mongo: [],
+ redis: [],
+ libsql: [],
+ },
+ ],
+});
+
+const exportDb = (tree = sourceTree()) => {
+ const applications = tree.environments.flatMap((env) => env.applications);
+ return {
+ query: {
+ projects: {
+ findFirst: vi.fn(async () => ({
+ ...tree,
+ environments: tree.environments.map(
+ ({ applications: _applications, ...env }) => env,
+ ),
+ })),
+ },
+ applications: { findMany: vi.fn(async () => applications) },
+ },
+ } as never;
+};
+
+const fakeImportDb = (existing: {
+ projectNames?: string[];
+ appPorts?: number[];
+ dbPorts?: number[];
+ libsqlPorts?: Record[];
+ domains?: { host: string; path: string }[];
+ appNames?: string[];
+}) => {
+ const inserts: { table: unknown; values: Record }[] = [];
+ let id = 0;
+ const tx = {
+ query: { tags: { findFirst: vi.fn(async () => undefined) } },
+ insert: (table: unknown) => ({
+ values: (values: Record) => {
+ id += 1;
+ const row = {
+ ...values,
+ projectId: values.projectId ?? `new-project-${id}`,
+ environmentId: values.environmentId ?? `new-env-${id}`,
+ applicationId: `new-app-${id}`,
+ postgresId: `new-pg-${id}`,
+ libsqlId: `new-libsql-${id}`,
+ composeId: `new-compose-${id}`,
+ mountId: `new-mount-${id}`,
+ tagId: `new-tag-${id}`,
+ };
+ inserts.push({ table, values });
+ const result = Promise.resolve(undefined);
+ return Object.assign(result, {
+ returning: async () => [row],
+ });
+ },
+ }),
+ update: () => ({ set: () => ({ where: async () => {} }) }),
+ };
+ const appNameRows = (existing.appNames ?? []).map((appName) => ({ appName }));
+ const table = (rows: () => unknown[]) => ({
+ findMany: vi.fn(async (args?: { columns?: { appName?: boolean } }) =>
+ args?.columns?.appName ? appNameRows : rows(),
+ ),
+ });
+ const db = {
+ query: {
+ projects: {
+ findFirst: vi.fn(async () =>
+ existing.projectNames?.length ? { projectId: "existing" } : undefined,
+ ),
+ },
+ applications: table(() => [
+ {
+ applicationId: "other",
+ ports: (existing.appPorts ?? []).map((publishedPort) => ({
+ publishedPort,
+ })),
+ },
+ ]),
+ compose: table(() => []),
+ postgres: table(() =>
+ (existing.dbPorts ?? []).map((externalPort) => ({ externalPort })),
+ ),
+ mysql: table(() => []),
+ mariadb: table(() => []),
+ mongo: table(() => []),
+ redis: table(() => []),
+ libsql: table(() => existing.libsqlPorts ?? []),
+ domains: { findMany: vi.fn(async () => existing.domains ?? []) },
+ },
+ transaction: async (fn: (t: typeof tx) => unknown) => fn(tx),
+ };
+ const insertsInto = (table: unknown) =>
+ inserts.filter((insert) => insert.table === table).map((i) => i.values);
+ return { db: db as never, insertsInto };
+};
+
+const exportedPayload = async (serviceIds?: string[]) => {
+ const { content } = await exportProject(exportDb(), {
+ projectId: "p1",
+ serviceIds,
+ passphrase: PASSPHRASE,
+ });
+ return (await readBundle(content, PASSPHRASE)).payload;
+};
+
+describe("bundle encryption", () => {
+ it("round-trips the payload and names the file after the project", async () => {
+ const { filename, content } = await exportProject(exportDb(), {
+ projectId: "p1",
+ passphrase: PASSPHRASE,
+ });
+ expect(filename).toMatch(/^shop-\d{4}-\d{2}-\d{2}\.dokploy$/);
+ expect(content).not.toContain("secret");
+ const { payload } = await readBundle(content, PASSPHRASE);
+ expect(payload.project.name).toBe("Shop");
+ });
+
+ it("rejects a wrong passphrase", async () => {
+ const { content } = await exportProject(exportDb(), {
+ projectId: "p1",
+ passphrase: PASSPHRASE,
+ });
+ await expect(
+ readBundle(content, "a different passphrase"),
+ ).rejects.toBeInstanceOf(BundleCryptoError);
+ });
+
+ it("rejects a tampered bundle", async () => {
+ const { content } = await exportProject(exportDb(), {
+ projectId: "p1",
+ passphrase: PASSPHRASE,
+ });
+ const envelope = JSON.parse(content);
+ const data = Buffer.from(envelope.data, "base64");
+ data[0] = (data[0] ?? 0) ^ 1;
+ envelope.data = data.toString("base64");
+ await expect(
+ readBundle(JSON.stringify(envelope), PASSPHRASE),
+ ).rejects.toBeInstanceOf(BundleCryptoError);
+ });
+
+ it("rejects files that are not bundles and bundles from a newer format", async () => {
+ await expect(readBundle("not json", PASSPHRASE)).rejects.toBeInstanceOf(
+ BundleFormatError,
+ );
+ const { content } = await exportProject(exportDb(), {
+ projectId: "p1",
+ passphrase: PASSPHRASE,
+ });
+ const newer = { ...JSON.parse(content), formatVersion: 99 };
+ await expect(readBundle(JSON.stringify(newer), PASSPHRASE)).rejects.toThrow(
+ /newer version/,
+ );
+ });
+
+ const bundleWithAppName = async (appName: string) => {
+ const { content } = await exportProject(exportDb(), {
+ projectId: "p1",
+ passphrase: PASSPHRASE,
+ });
+ const { payload } = await readBundle(content, PASSPHRASE);
+ payload.services[0]!.appName = appName;
+ return JSON.stringify({
+ ...JSON.parse(content),
+ ...(await encryptPayload(JSON.stringify(payload), PASSPHRASE)),
+ });
+ };
+
+ it.each(["unused/../victim", "..", "."])(
+ "rejects a bundle with the app name %j",
+ async (appName) => {
+ await expect(
+ readBundle(await bundleWithAppName(appName), PASSPHRASE),
+ ).rejects.toBeInstanceOf(BundleFormatError);
+ },
+ );
+
+ it("accepts generated app names longer than 63 characters", async () => {
+ const appName = `${"a".repeat(63)}-abc123`;
+ const { payload } = await readBundle(
+ await bundleWithAppName(appName),
+ PASSPHRASE,
+ );
+ expect(payload.services[0]?.appName).toBe(appName);
+ });
+});
+
+describe("exportProject", () => {
+ it("drops references to resources that live outside the project", async () => {
+ const payload = await exportedPayload();
+ const app = payload.services.find((s) => s.kind === "application");
+ expect(app).toBeDefined();
+ expect(app).not.toHaveProperty("githubId");
+ expect(app).not.toHaveProperty("registryId");
+ expect(app).not.toHaveProperty("serverId");
+ expect(payload.project).not.toHaveProperty("organizationId");
+ expect(app?.domains).toHaveLength(1);
+ expect(payload.tags).toEqual([{ name: "prod", color: "#f00" }]);
+ });
+
+ it("warns about git providers and registries that must be reconnected", async () => {
+ const payload = await exportedPayload();
+ expect(payload.warnings.join("\n")).toMatch(
+ /"web" uses a connected git provider/,
+ );
+ expect(payload.warnings.join("\n")).toMatch(/"web" uses a registry/);
+ });
+
+ it("only includes the selected services", async () => {
+ const payload = await exportedPayload(["pg1"]);
+ expect(payload.services.map((s) => s.kind)).toEqual(["postgres"]);
+ });
+});
+
+describe("replaceAppNames", () => {
+ it("replaces whole app names only", () => {
+ const map = { "db-abc": "db-new" };
+ expect(replaceAppNames("host=db-abc;other=mydb-abc", map)).toBe(
+ "host=db-new;other=mydb-abc",
+ );
+ });
+});
+
+describe("importBundle", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it("creates the project on the chosen server keeping the app names", async () => {
+ const payload = await exportedPayload();
+ const { db, insertsInto } = fakeImportDb({});
+ const result = await importBundle(db, payload, {
+ organizationId: "org-target",
+ serverId: "srv-target",
+ });
+
+ expect(result.projectName).toBe("Shop");
+ const [project] = insertsInto(projects);
+ expect(project?.organizationId).toBe("org-target");
+ const [pg] = insertsInto(postgres);
+ const [app] = insertsInto(applications);
+ expect(pg?.appName).toBe("shop-db-abc123");
+ expect(app?.appName).toBe("shop-web-xyz789");
+ expect(pg?.serverId).toBe("srv-target");
+ expect(pg?.applicationStatus).toBe("idle");
+ expect(app?.githubId).toBeUndefined();
+ expect(app?.env).toBe("DATABASE_URL=postgres://shop-db-abc123:5432/app");
+ expect(result.warnings.join("\n")).not.toMatch(/already exists/);
+ expect(insertsInto(environments)).toHaveLength(1);
+ const [domain] = insertsInto(domains);
+ expect(domain).not.toHaveProperty("uniqueConfigKey");
+ expect(domain?.enabled).toBe(true);
+ expect(insertsInto(mounts)).toHaveLength(1);
+ expect(createSecurityMiddleware).toHaveBeenCalledTimes(1);
+ expect(createRedirectMiddleware).toHaveBeenCalledTimes(1);
+ });
+
+ it("imports forward-auth domains disabled and flags domains generated for the source IP", async () => {
+ const payload = await exportedPayload();
+ const app = payload.services.find((s) => s.kind === "application");
+ const [domain] = app?.domains as Record[];
+ domain!.host = "shop-web-1-2-3-4.sslip.io";
+ domain!.forwardAuthEnabled = true;
+ const { db, insertsInto } = fakeImportDb({});
+ const result = await importBundle(db, payload, {
+ organizationId: "org",
+ serverId: null,
+ });
+ expect(insertsInto(domains)[0]).toMatchObject({
+ forwardAuthEnabled: false,
+ enabled: false,
+ });
+ expect(result.warnings.join("\n")).toMatch(/used forward auth/);
+ expect(result.warnings.join("\n")).toMatch(/source server's IP/);
+ });
+
+ it("drops libsql gRPC and admin ports that are already published", async () => {
+ const payload = await exportedPayload();
+ payload.services.push({
+ kind: "libsql",
+ environmentId: "e1",
+ appName: "shop-libsql-aaa111",
+ name: "libsql",
+ externalGRPCPort: 5001,
+ externalAdminPort: 5002,
+ mounts: [],
+ });
+ const { db, insertsInto } = fakeImportDb({
+ libsqlPorts: [{ externalGRPCPort: 5001 }],
+ });
+ await importBundle(db, payload, { organizationId: "org", serverId: null });
+ const [row] = insertsInto(libsql);
+ expect(row?.externalGRPCPort).toBeNull();
+ expect(row?.externalAdminPort).toBe(5002);
+ });
+
+ it("renames only services whose app name is taken and rewrites references", async () => {
+ const payload = await exportedPayload();
+ const { db, insertsInto } = fakeImportDb({ appNames: ["shop-db-abc123"] });
+ const result = await importBundle(db, payload, {
+ organizationId: "org",
+ serverId: null,
+ });
+ const [pg] = insertsInto(postgres);
+ const [project] = insertsInto(projects);
+ expect(pg?.appName).not.toBe("shop-db-abc123");
+ expect(insertsInto(applications)[0]?.appName).toBe("shop-web-xyz789");
+ expect(insertsInto(applications)[0]?.env).toBe(
+ `DATABASE_URL=postgres://${pg?.appName}:5432/app`,
+ );
+ expect(project?.env).toBe(`DB_URL=postgres://user@${pg?.appName}:5432/app`);
+ expect(result.warnings.join("\n")).toMatch(/shop-db-abc123 already exists/);
+ });
+
+ it("resolves name, domain and port conflicts automatically", async () => {
+ const payload = await exportedPayload();
+ const { db, insertsInto } = fakeImportDb({
+ projectNames: ["Shop"],
+ appPorts: [8080],
+ dbPorts: [5432],
+ domains: [{ host: "shop.example.com", path: "/" }],
+ });
+ const result = await importBundle(db, payload, {
+ organizationId: "org-target",
+ serverId: null,
+ });
+
+ expect(result.projectName).toBe("imported-Shop");
+ expect(insertsInto(ports)).toHaveLength(0);
+ expect(insertsInto(postgres)[0]?.externalPort).toBeNull();
+ expect(insertsInto(domains)[0]?.enabled).toBe(false);
+ expect(result.warnings.join("\n")).toMatch(/shop\.example\.com/);
+ expect(result.warnings.join("\n")).toMatch(/Port 8080/);
+ expect(result.warnings.join("\n")).toMatch(/Port 5432/);
+ });
+
+ it("keeps the compose suffix so saved service names still match", async () => {
+ const payload = await exportedPayload();
+ payload.services.push({
+ kind: "compose",
+ environmentId: "e1",
+ appName: "shop-stack-ccc333",
+ name: "stack",
+ randomize: true,
+ suffix: "abc123",
+ domains: [
+ {
+ domainId: "cd1",
+ host: "stack.example.com",
+ serviceName: "web-abc123",
+ },
+ ],
+ mounts: [],
+ });
+ const { db, insertsInto } = fakeImportDb({});
+ await importBundle(db, payload, { organizationId: "org", serverId: null });
+ expect(insertsInto(compose)[0]?.suffix).toBe("abc123");
+ expect(
+ insertsInto(domains).find((d) => d.host === "stack.example.com")
+ ?.serviceName,
+ ).toBe("web-abc123");
+ });
+
+ it.each(["../../etc/passwd", ".", ""])(
+ "rejects the file mount path %j",
+ async (filePath) => {
+ const payload = await exportedPayload();
+ const app = payload.services.find((s) => s.kind === "application");
+ (app?.mounts as { filePath: string }[])[0]!.filePath = filePath;
+ const { db } = fakeImportDb({});
+ await expect(
+ importBundle(db, payload, { organizationId: "org", serverId: null }),
+ ).rejects.toBeInstanceOf(BundleFormatError);
+ },
+ );
+});
diff --git a/apps/dokploy/__test__/git-provider/github-update-authz.test.ts b/apps/dokploy/__test__/git-provider/github-update-authz.test.ts
new file mode 100644
index 00000000000..5ecde7cd12a
--- /dev/null
+++ b/apps/dokploy/__test__/git-provider/github-update-authz.test.ts
@@ -0,0 +1,69 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ findGithubById: vi.fn(),
+ assertGitProviderAccess: vi.fn(),
+ updateGitProvider: vi.fn(),
+ updateGithub: vi.fn(),
+}));
+
+vi.mock("@dokploy/server", () => ({
+ findGithubById: mocks.findGithubById,
+ assertGitProviderAccess: mocks.assertGitProviderAccess,
+ updateGitProvider: mocks.updateGitProvider,
+ updateGithub: mocks.updateGithub,
+ canViewGitProviderSecrets: vi.fn(async () => true),
+ getAccessibleGitProviderIds: vi.fn(async () => new Set()),
+}));
+vi.mock("@dokploy/server/services/permission", () => ({
+ checkPermission: vi.fn(async () => undefined),
+}));
+vi.mock("@/server/api/utils/audit", () => ({
+ audit: vi.fn(async () => undefined),
+}));
+
+const { githubRouter } = await import("@/server/api/routers/github");
+
+const callerAs = (role: string) =>
+ githubRouter.createCaller({
+ user: { id: "u1", role },
+ session: { activeOrganizationId: "org-a" },
+ } as never);
+
+const input = {
+ githubId: "gh-1",
+ gitProviderId: "gp-1",
+ name: "my-provider",
+ githubAppName: "app",
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.findGithubById.mockResolvedValue({
+ githubId: "gh-1",
+ gitProvider: { gitProviderId: "gp-1", organizationId: "org-a" },
+ });
+});
+
+describe("github.update — owner/admin update their own provider", () => {
+ for (const role of ["owner", "admin"]) {
+ it(`${role} can update a provider in their org`, async () => {
+ mocks.assertGitProviderAccess.mockResolvedValue(undefined);
+ await callerAs(role).update(input as never);
+ expect(mocks.assertGitProviderAccess).toHaveBeenCalledTimes(1);
+ expect(mocks.updateGitProvider).toHaveBeenCalledTimes(1);
+ expect(mocks.updateGithub).toHaveBeenCalledTimes(1);
+ });
+ }
+});
+
+describe("github.update — cross-org takeover is blocked", () => {
+ it("rejects and does not mutate when the provider is not in the caller's org", async () => {
+ mocks.assertGitProviderAccess.mockRejectedValue(
+ Object.assign(new Error("not found"), { code: "NOT_FOUND" }),
+ );
+ await expect(callerAs("owner").update(input as never)).rejects.toBeTruthy();
+ expect(mocks.updateGitProvider).not.toHaveBeenCalled();
+ expect(mocks.updateGithub).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/dokploy/__test__/mounts/update-file-mount-conflict.test.ts b/apps/dokploy/__test__/mounts/update-file-mount-conflict.test.ts
index acacdec5b24..ce73b65be08 100644
--- a/apps/dokploy/__test__/mounts/update-file-mount-conflict.test.ts
+++ b/apps/dokploy/__test__/mounts/update-file-mount-conflict.test.ts
@@ -7,6 +7,9 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("@dokploy/server", () => ({
+ assertCanUseBindMount: vi.fn(async () => {}),
+ assertCanUseVolumeMount: vi.fn(async () => {}),
+ getServiceOrganizationId: vi.fn(),
createMount: vi.fn(),
deleteMount: vi.fn(),
findApplicationById: vi.fn(),
diff --git a/apps/dokploy/__test__/patch/read-repo-file-traversal.test.ts b/apps/dokploy/__test__/patch/read-repo-file-traversal.test.ts
new file mode 100644
index 00000000000..2d7db15b03c
--- /dev/null
+++ b/apps/dokploy/__test__/patch/read-repo-file-traversal.test.ts
@@ -0,0 +1,57 @@
+import { join } from "node:path";
+import { paths } from "@dokploy/server/constants";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const execMocks = vi.hoisted(() => ({
+ execAsync: vi.fn((_command: string) =>
+ Promise.resolve({ stdout: "ROOT:x:0:0", stderr: "" }),
+ ),
+ execAsyncRemote: vi.fn((_serverId: string, _command: string) =>
+ Promise.resolve({ stdout: "", stderr: "" }),
+ ),
+}));
+vi.mock("@dokploy/server/utils/process/execAsync", () => execMocks);
+
+vi.mock("@dokploy/server/services/application", () => ({
+ findApplicationById: vi.fn(() =>
+ Promise.resolve({ appName: "app1", serverId: null, buildServerId: null }),
+ ),
+}));
+vi.mock("@dokploy/server/services/compose", () => ({
+ findComposeById: vi.fn(() =>
+ Promise.resolve({ appName: "c1", serverId: null }),
+ ),
+}));
+
+const { readPatchRepoFile } = await import(
+ "@dokploy/server/services/patch-repo"
+);
+
+beforeEach(() => vi.clearAllMocks());
+
+describe("patch.readRepoFile path traversal", () => {
+ it("rejects a filePath that escapes the patch-repos directory with ../", async () => {
+ await expect(
+ readPatchRepoFile(
+ "a",
+ "application",
+ "../../../../../../../../../../etc/passwd",
+ ),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+
+ // No shell command is built when the path is rejected.
+ expect(execMocks.execAsync).not.toHaveBeenCalled();
+ });
+
+ it("still reads a normal file inside the repo", async () => {
+ const out = await readPatchRepoFile("a", "application", "Dockerfile");
+ expect(execMocks.execAsync).toHaveBeenCalledTimes(1);
+ const command = execMocks.execAsync.mock.calls[0]?.[0] ?? "";
+ const { PATCH_REPOS_PATH } = paths(false);
+ expect(command).toContain(join(PATCH_REPOS_PATH, "application", "app1"));
+ // `git cat-file --filters` could run the repo's filters (LFS and others) on the host.
+ expect(command).toMatch(/git show HEAD\\?:Dockerfile/);
+ expect(command).not.toContain("--filters");
+ expect(out).toBe("ROOT:x:0:0");
+ });
+});
diff --git a/apps/dokploy/__test__/permissions/assert-server-access.test.ts b/apps/dokploy/__test__/permissions/assert-server-access.test.ts
new file mode 100644
index 00000000000..ec0ac52d495
--- /dev/null
+++ b/apps/dokploy/__test__/permissions/assert-server-access.test.ts
@@ -0,0 +1,122 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mockDb = vi.hoisted(() => ({
+ query: {
+ server: { findMany: vi.fn() },
+ member: { findFirst: vi.fn() },
+ },
+}));
+vi.mock("@dokploy/server/db", () => ({ db: mockDb }));
+
+const mockHasValidLicense = vi.hoisted(() => vi.fn());
+vi.mock("@dokploy/server/services/proprietary/license-key", () => ({
+ hasValidLicense: mockHasValidLicense,
+}));
+
+vi.mock("@dokploy/server/constants", async (importOriginal) => ({
+ ...(await importOriginal()),
+ IS_CLOUD: false,
+}));
+
+const { assertServerAccess } = await import("@dokploy/server/services/server");
+
+const session = { userId: "user-1", activeOrganizationId: "org-a" };
+
+// org-a owns srv-a and srv-c; srv-b belongs to another org.
+const orgServers = [{ serverId: "srv-a" }, { serverId: "srv-c" }];
+
+const setMember = (
+ role: string,
+ accessedServers: string[],
+ licensed: boolean,
+) => {
+ mockDb.query.member.findFirst.mockResolvedValue({ role, accessedServers });
+ mockHasValidLicense.mockResolvedValue(licensed);
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockDb.query.server.findMany.mockResolvedValue(orgServers);
+});
+
+const allow = (p: Promise) => expect(p).resolves.toBeUndefined();
+const deny = (p: Promise) =>
+ expect(p).rejects.toMatchObject({ code: "UNAUTHORIZED" });
+
+describe("assertServerAccess — legitimate access is preserved per role", () => {
+ it("owner reaches any server in the org (ignores accessedServers)", async () => {
+ setMember("owner", [], true);
+ await allow(assertServerAccess(session, "srv-a"));
+ await allow(assertServerAccess(session, "srv-c"));
+ });
+
+ it("admin reaches any server in the org", async () => {
+ setMember("admin", [], true);
+ await allow(assertServerAccess(session, "srv-a"));
+ await allow(assertServerAccess(session, "srv-c"));
+ });
+
+ it("member in an UNLICENSED org reaches any server in the org", async () => {
+ setMember("member", [], false);
+ await allow(assertServerAccess(session, "srv-a"));
+ await allow(assertServerAccess(session, "srv-c"));
+ });
+
+ it("licensed member reaches a server in its accessedServers", async () => {
+ setMember("member", ["srv-a"], true);
+ await allow(assertServerAccess(session, "srv-a"));
+ });
+
+ it("custom role reaches a server in its accessedServers", async () => {
+ setMember("deployer", ["srv-c"], true);
+ await allow(assertServerAccess(session, "srv-c"));
+ });
+
+ it("any role may act on the local host (no serverId) on self-hosted", async () => {
+ setMember("member", [], true);
+ await allow(assertServerAccess(session, null));
+ });
+});
+
+describe("assertServerAccess — unauthorized access is blocked", () => {
+ it("rejects a server of another organization for everyone", async () => {
+ for (const role of ["owner", "admin", "member"]) {
+ setMember(role, ["srv-a"], true);
+ await deny(assertServerAccess(session, "srv-b"));
+ }
+ });
+
+ it("rejects a server the licensed member was not granted", async () => {
+ setMember("member", ["srv-a"], true);
+ await deny(assertServerAccess(session, "srv-c"));
+ });
+
+ it("rejects a custom role for a server outside its grant", async () => {
+ setMember("deployer", ["srv-a"], true);
+ await deny(assertServerAccess(session, "srv-c"));
+ });
+});
+
+describe("assertServerAccess on Cloud", () => {
+ it("rejects the local control-plane host (no serverId) when IS_CLOUD", async () => {
+ vi.resetModules();
+ vi.doMock("@dokploy/server/constants", async (importOriginal) => ({
+ ...(await importOriginal()),
+ IS_CLOUD: true,
+ }));
+ vi.doMock("@dokploy/server/db", () => ({ db: mockDb }));
+ vi.doMock("@dokploy/server/services/proprietary/license-key", () => ({
+ hasValidLicense: mockHasValidLicense,
+ }));
+ const { assertServerAccess: cloudAssert } = await import(
+ "@dokploy/server/services/server"
+ );
+ setMember("owner", [], true);
+ await expect(cloudAssert(session, null)).rejects.toMatchObject({
+ code: "UNAUTHORIZED",
+ });
+ // A real owned server is still reachable on Cloud.
+ await expect(cloudAssert(session, "srv-a")).resolves.toBeUndefined();
+ vi.doUnmock("@dokploy/server/constants");
+ });
+});
diff --git a/apps/dokploy/__test__/permissions/member-role-ceiling.test.ts b/apps/dokploy/__test__/permissions/member-role-ceiling.test.ts
new file mode 100644
index 00000000000..d5107287a89
--- /dev/null
+++ b/apps/dokploy/__test__/permissions/member-role-ceiling.test.ts
@@ -0,0 +1,294 @@
+import type { SQL } from "drizzle-orm";
+import { PgDialect } from "drizzle-orm/pg-core";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+type MemberRow = {
+ id: string;
+ role: string;
+ organizationId: string;
+ userId: string;
+ user: { email: string };
+};
+
+const mocks = vi.hoisted(() => ({
+ members: [] as MemberRow[],
+ customRoles: {} as Record>,
+ memberFindFirst: vi.fn(),
+ userFindFirst: vi.fn(),
+ invitationFindFirst: vi.fn(),
+ orgRoleFindFirst: vi.fn(),
+ orgRoleFindMany: vi.fn(),
+ updateSet: vi.fn(),
+ insertValues: vi.fn(),
+}));
+
+vi.mock("@dokploy/server/db", () => ({
+ db: {
+ query: {
+ member: { findFirst: mocks.memberFindFirst },
+ user: { findFirst: mocks.userFindFirst },
+ invitation: { findFirst: mocks.invitationFindFirst },
+ organizationRole: {
+ findFirst: mocks.orgRoleFindFirst,
+ findMany: mocks.orgRoleFindMany,
+ },
+ },
+ update: vi.fn(() => ({
+ set: (...args: unknown[]) => {
+ mocks.updateSet(...args);
+ return { where: () => Promise.resolve() };
+ },
+ })),
+ insert: vi.fn(() => ({
+ values: (...args: unknown[]) => {
+ mocks.insertValues(...args);
+ return { returning: () => Promise.resolve([{ id: "invite-1" }]) };
+ },
+ })),
+ },
+}));
+
+vi.mock("@dokploy/server/index", () => ({ IS_CLOUD: false }));
+
+// The real assertRoleAssignmentAllowed runs against the tables above; only the
+// procedure's own permission gate is stubbed.
+vi.mock("@dokploy/server/services/permission", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@dokploy/server/services/permission")
+ >()),
+ checkPermission: vi.fn(async () => undefined),
+}));
+
+vi.mock(
+ "@dokploy/server/services/proprietary/license-key",
+ async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@dokploy/server/services/proprietary/license-key")
+ >()),
+ hasValidLicense: vi.fn(async () => true),
+ }),
+);
+
+vi.mock("@/server/api/utils/audit", () => ({
+ audit: vi.fn(async () => undefined),
+}));
+vi.mock("@/server/api/utils/plan-limits", () => ({
+ assertMemberLimit: vi.fn(async () => undefined),
+}));
+
+const { organizationRouter } = await import(
+ "@/server/api/routers/organization"
+);
+
+const render = (where: SQL) => new PgDialect().sqlToQuery(where);
+
+const findMember = ({ where }: { where: SQL }) => {
+ const { sql, params } = render(where);
+ if (sql === '"member"."id" = $1') {
+ return Promise.resolve(mocks.members.find((row) => row.id === params[0]));
+ }
+ if (sql === '("member"."user_id" = $1 and "member"."organization_id" = $2)') {
+ return Promise.resolve(
+ mocks.members.find(
+ (row) => row.userId === params[0] && row.organizationId === params[1],
+ ),
+ );
+ }
+ throw new Error(`Unexpected member query: ${sql}`);
+};
+
+const findCustomRoles = ({ where }: { where: SQL }) => {
+ const { sql, params } = render(where);
+ expect(sql).toBe(
+ '("organization_role"."organization_id" = $1 and "organization_role"."role" = $2)',
+ );
+ const permission = mocks.customRoles[params[1] as string];
+ return Promise.resolve(
+ params[0] === "org-a" && permission
+ ? [{ role: params[1], permission: JSON.stringify(permission) }]
+ : [],
+ );
+};
+
+const callerAs = (role: string, userId = "caller-1") => {
+ mocks.members.push({
+ id: "member-1",
+ role,
+ organizationId: "org-a",
+ userId,
+ user: { email: "caller@example.com" },
+ });
+ return organizationRouter.createCaller({
+ user: { id: userId, role },
+ session: { activeOrganizationId: "org-a" },
+ } as never);
+};
+
+const targetMember = (role: string) => {
+ mocks.members.push({
+ id: "member-2",
+ role,
+ organizationId: "org-a",
+ userId: "victim-1",
+ user: { email: "victim@example.com" },
+ });
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.members = [];
+ mocks.customRoles = {
+ deployer: { deployment: ["read", "create"] },
+ "user-manager": {
+ member: ["read", "update", "create"],
+ deployment: ["read", "create"],
+ },
+ "server-operator": {
+ deployment: ["read", "create"],
+ server: ["read", "execute"],
+ },
+ };
+ mocks.memberFindFirst.mockImplementation(findMember);
+ mocks.orgRoleFindMany.mockImplementation(findCustomRoles);
+ mocks.orgRoleFindFirst.mockResolvedValue({ role: "deployer" });
+ mocks.userFindFirst.mockResolvedValue(undefined);
+ mocks.invitationFindFirst.mockResolvedValue(undefined);
+});
+
+describe("updateMemberRole — privileged roles keep working", () => {
+ it("owner can promote a member to admin", async () => {
+ targetMember("member");
+ await expect(
+ callerAs("owner").updateMemberRole({
+ memberId: "member-2",
+ role: "admin",
+ }),
+ ).resolves.toBe(true);
+ expect(mocks.updateSet).toHaveBeenCalledWith({ role: "admin" });
+ });
+
+ it("admin can assign a custom role to a member", async () => {
+ targetMember("member");
+ await expect(
+ callerAs("admin").updateMemberRole({
+ memberId: "member-2",
+ role: "deployer",
+ }),
+ ).resolves.toBe(true);
+ expect(mocks.updateSet).toHaveBeenCalledWith({ role: "deployer" });
+ });
+
+ it("a custom role with member:update can still assign a non-admin custom role", async () => {
+ targetMember("member");
+ await expect(
+ callerAs("user-manager").updateMemberRole({
+ memberId: "member-2",
+ role: "deployer",
+ }),
+ ).resolves.toBe(true);
+ expect(mocks.updateSet).toHaveBeenCalledWith({ role: "deployer" });
+ });
+});
+
+describe("updateMemberRole — privilege escalation is blocked", () => {
+ it("an admin cannot promote a member to admin: only the owner grants it", async () => {
+ targetMember("member");
+ await expect(
+ callerAs("admin").updateMemberRole({
+ memberId: "member-2",
+ role: "admin",
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ expect(mocks.updateSet).not.toHaveBeenCalled();
+ });
+
+ it("a custom role cannot promote a member to admin", async () => {
+ targetMember("member");
+ await expect(
+ callerAs("user-manager").updateMemberRole({
+ memberId: "member-2",
+ role: "admin",
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ expect(mocks.updateSet).not.toHaveBeenCalled();
+ });
+
+ it("a custom role cannot demote an existing admin", async () => {
+ targetMember("admin");
+ await expect(
+ callerAs("user-manager").updateMemberRole({
+ memberId: "member-2",
+ role: "member",
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ expect(mocks.updateSet).not.toHaveBeenCalled();
+ });
+
+ it("an admin cannot change another admin's role (pre-existing rule)", async () => {
+ targetMember("admin");
+ await expect(
+ callerAs("admin").updateMemberRole({
+ memberId: "member-2",
+ role: "member",
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ expect(mocks.updateSet).not.toHaveBeenCalled();
+ });
+
+ it("a custom role cannot hand out permissions it does not have", async () => {
+ targetMember("member");
+ await expect(
+ callerAs("user-manager").updateMemberRole({
+ memberId: "member-2",
+ role: "server-operator",
+ }),
+ ).rejects.toMatchObject({
+ code: "FORBIDDEN",
+ message: "Cannot assign a role with permissions you do not have",
+ });
+ expect(mocks.updateSet).not.toHaveBeenCalled();
+ });
+
+ it("a role that does not exist in the organization cannot be assigned", async () => {
+ targetMember("member");
+ await expect(
+ callerAs("admin").updateMemberRole({
+ memberId: "member-2",
+ role: "ghost",
+ }),
+ ).rejects.toMatchObject({ code: "NOT_FOUND" });
+ expect(mocks.updateSet).not.toHaveBeenCalled();
+ });
+});
+
+describe("inviteMember — admin ceiling", () => {
+ it("a custom role cannot invite an admin", async () => {
+ await expect(
+ callerAs("user-manager").inviteMember({
+ email: "new@example.com",
+ role: "admin",
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ expect(mocks.insertValues).not.toHaveBeenCalled();
+ });
+
+ it("an admin cannot invite an admin", async () => {
+ await expect(
+ callerAs("admin").inviteMember({
+ email: "new@example.com",
+ role: "admin",
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ expect(mocks.insertValues).not.toHaveBeenCalled();
+ });
+
+ it("a custom role cannot invite with a role above its own permissions", async () => {
+ await expect(
+ callerAs("user-manager").inviteMember({
+ email: "new@example.com",
+ role: "server-operator",
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ expect(mocks.insertValues).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/dokploy/__test__/schedule/schedule-read-redaction.test.ts b/apps/dokploy/__test__/schedule/schedule-read-redaction.test.ts
index c5d38481dc9..1de22f9b326 100644
--- a/apps/dokploy/__test__/schedule/schedule-read-redaction.test.ts
+++ b/apps/dokploy/__test__/schedule/schedule-read-redaction.test.ts
@@ -7,6 +7,7 @@ const mocks = vi.hoisted(() => ({
findMemberByUserId: vi.fn(),
findScheduleById: vi.fn(),
schedulesFindMany: vi.fn(),
+ serverFindFirst: vi.fn(),
}));
vi.mock("@dokploy/server", () => ({
@@ -21,6 +22,9 @@ vi.mock("@dokploy/server/db", () => ({
schedules: {
findMany: mocks.schedulesFindMany,
},
+ server: {
+ findFirst: mocks.serverFindFirst,
+ },
},
},
}));
@@ -111,6 +115,7 @@ describe("schedule read redaction", () => {
mocks.checkPermission.mockResolvedValue(undefined);
mocks.checkServicePermissionAndAccess.mockResolvedValue(undefined);
mocks.findMemberByUserId.mockResolvedValue({ role: "admin" });
+ mocks.serverFindFirst.mockResolvedValue(remoteServer);
});
it("redacts the bound compose service and shared env in one", async () => {
diff --git a/apps/dokploy/__test__/security/api-key-output-guard.test.ts b/apps/dokploy/__test__/security/api-key-output-guard.test.ts
index d718a6e90bc..909f6b84b30 100644
--- a/apps/dokploy/__test__/security/api-key-output-guard.test.ts
+++ b/apps/dokploy/__test__/security/api-key-output-guard.test.ts
@@ -138,6 +138,7 @@ const testRouter = createTRPCRouter({
}),
dockerVolume: createTRPCRouter({ readVolumeFile: secretReader }),
notification: createTRPCRouter({ revealSecret: secretReader }),
+ projectExportImport: createTRPCRouter({ export: secretReader }),
settings: createTRPCRouter({
readTraefikEnv: secretReader,
getOpenApiDocument: protectedProcedure.query(() => ({
@@ -267,6 +268,7 @@ describe("procedures that return raw secrets", () => {
() => apiKey().dockerVolume.readVolumeFile(),
],
["notification.revealSecret", () => apiKey().notification.revealSecret()],
+ ["projectExportImport.export", () => apiKey().projectExportImport.export()],
["settings.readTraefikEnv", () => apiKey().settings.readTraefikEnv()],
["user.revealApiKey", () => apiKey().user.revealApiKey()],
])("%s is refused before it runs", async (_path, call) => {
diff --git a/apps/dokploy/__test__/server/connect-server-register.test.ts b/apps/dokploy/__test__/server/connect-server-register.test.ts
new file mode 100644
index 00000000000..9f5d60a4bae
--- /dev/null
+++ b/apps/dokploy/__test__/server/connect-server-register.test.ts
@@ -0,0 +1,232 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ isCloud: false,
+ sshKey: null as null | Record,
+ claimed: true,
+ released: vi.fn(),
+ org: { ownerId: "owner-1" } as null | { ownerId: string },
+ owner: { id: "owner-1", serversQuantity: 1 },
+ ownerServers: [] as unknown[],
+ findMember: vi.fn(),
+ checkPermission: vi.fn(),
+ createServer: vi.fn(),
+ applyDockerCleanupSchedule: vi.fn(),
+ audit: vi.fn(),
+ captureEvent: vi.fn(),
+}));
+
+vi.mock("@dokploy/server", async () => {
+ const connect = await import("@dokploy/server/services/server-connect");
+ return {
+ ...connect,
+ get IS_CLOUD() {
+ return mocks.isCloud;
+ },
+ captureEvent: mocks.captureEvent,
+ createServer: mocks.createServer,
+ findUserById: async () => mocks.owner,
+ findServersByUserId: async () => mocks.ownerServers,
+ };
+});
+
+vi.mock("@dokploy/server/db", () => ({
+ db: {
+ update: () => ({
+ set: (values: { lastUsedAt: string | null }) => ({
+ where: () => {
+ if (values.lastUsedAt === null) {
+ mocks.released();
+ return Promise.resolve();
+ }
+ return {
+ returning: async () =>
+ mocks.claimed ? [{ sshKeyId: "key-1" }] : [],
+ };
+ },
+ }),
+ }),
+ query: {
+ sshKeys: { findFirst: async () => mocks.sshKey },
+ organization: { findFirst: async () => mocks.org },
+ },
+ },
+}));
+
+vi.mock("@dokploy/server/services/permission", () => ({
+ findMemberByUserId: mocks.findMember,
+ checkPermission: mocks.checkPermission,
+}));
+
+vi.mock("@/server/api/utils/audit", () => ({ audit: mocks.audit }));
+
+vi.mock("@/server/utils/docker-cleanup", () => ({
+ applyDockerCleanupSchedule: mocks.applyDockerCleanupSchedule,
+}));
+
+const { createConnectToken } = await import(
+ "@dokploy/server/services/server-connect"
+);
+const { registerConnectedServer } = await import(
+ "@/server/utils/connect-server"
+);
+
+const PRIVATE_KEY = "private-key";
+const makeToken = (overrides = {}) =>
+ createConnectToken(
+ {
+ sshKeyId: "key-1",
+ userId: "user-1",
+ serverType: "build",
+ enableDockerCleanup: false,
+ expiresAt: Math.floor(Date.now() / 1000) + 3600,
+ ...overrides,
+ },
+ PRIVATE_KEY,
+ );
+
+describe("registerConnectedServer", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.isCloud = false;
+ mocks.sshKey = {
+ sshKeyId: "key-1",
+ organizationId: "org-1",
+ privateKey: PRIVATE_KEY,
+ name: "Web",
+ description: "Runs the web app",
+ };
+ mocks.claimed = true;
+ mocks.org = { ownerId: "owner-1" };
+ mocks.ownerServers = [];
+ mocks.findMember.mockResolvedValue({
+ role: "admin",
+ user: { id: "user-1", email: "u@example.com" },
+ });
+ mocks.checkPermission.mockResolvedValue(undefined);
+ mocks.createServer.mockImplementation(async (input) => ({
+ ...input,
+ serverId: "srv-1",
+ }));
+ });
+
+ it("creates the server from the SSH key's name and the token's settings", async () => {
+ const result = await registerConnectedServer({
+ token: makeToken(),
+ ipAddress: "203.0.113.5",
+ });
+
+ expect(result).toMatchObject({ status: 200, serverId: "srv-1" });
+ expect(mocks.createServer).toHaveBeenCalledWith(
+ {
+ name: "Web",
+ description: "Runs the web app",
+ ipAddress: "203.0.113.5",
+ port: 22,
+ username: "root",
+ sshKeyId: "key-1",
+ serverType: "build",
+ enableDockerCleanup: false,
+ },
+ "org-1",
+ );
+ expect(mocks.applyDockerCleanupSchedule).toHaveBeenCalledWith(
+ "srv-1",
+ "org-1",
+ false,
+ );
+ expect(mocks.audit).toHaveBeenCalledWith(
+ {
+ user: { id: "user-1", email: "u@example.com", role: "admin" },
+ session: { activeOrganizationId: "org-1" },
+ },
+ expect.objectContaining({ action: "create", resourceType: "server" }),
+ );
+ });
+
+ it("rejects invalid, unknown-key and expired tokens", async () => {
+ expect(
+ (await registerConnectedServer({ token: "nope", ipAddress: "1.1.1.1" }))
+ .status,
+ ).toBe(400);
+
+ const known = mocks.sshKey;
+ mocks.sshKey = null;
+ expect(
+ (
+ await registerConnectedServer({
+ token: makeToken(),
+ ipAddress: "1.1.1.1",
+ })
+ ).status,
+ ).toBe(400);
+
+ mocks.sshKey = known;
+ expect(
+ (
+ await registerConnectedServer({
+ token: makeToken({ userId: "user-2" }).replace("user-2", "user-1"),
+ ipAddress: "1.1.1.1",
+ })
+ ).status,
+ ).toBe(400);
+
+ expect(
+ (
+ await registerConnectedServer({
+ token: makeToken({ expiresAt: 1 }),
+ ipAddress: "1.1.1.1",
+ })
+ ).status,
+ ).toBe(410);
+ expect(mocks.createServer).not.toHaveBeenCalled();
+ });
+
+ it("rejects when the IP cannot be detected", async () => {
+ const result = await registerConnectedServer({
+ token: makeToken(),
+ ipAddress: null,
+ });
+ expect(result.status).toBe(400);
+ expect(mocks.createServer).not.toHaveBeenCalled();
+ });
+
+ it("rejects when the user lost access", async () => {
+ mocks.checkPermission.mockRejectedValue(new Error("denied"));
+ const result = await registerConnectedServer({
+ token: makeToken(),
+ ipAddress: "1.1.1.1",
+ });
+ expect(result.status).toBe(403);
+ expect(mocks.createServer).not.toHaveBeenCalled();
+ });
+
+ it("rejects a command that was already used", async () => {
+ mocks.claimed = false;
+ const result = await registerConnectedServer({
+ token: makeToken(),
+ ipAddress: "1.1.1.1",
+ });
+ expect(result.status).toBe(409);
+ expect(mocks.createServer).not.toHaveBeenCalled();
+ });
+
+ it("releases the claim when creating the server fails", async () => {
+ mocks.createServer.mockRejectedValue(new Error("db down"));
+ await expect(
+ registerConnectedServer({ token: makeToken(), ipAddress: "1.1.1.1" }),
+ ).rejects.toThrow("db down");
+ expect(mocks.released).toHaveBeenCalled();
+ });
+
+ it("enforces the cloud server quota", async () => {
+ mocks.isCloud = true;
+ mocks.ownerServers = [{}];
+ const result = await registerConnectedServer({
+ token: makeToken(),
+ ipAddress: "1.1.1.1",
+ });
+ expect(result.status).toBe(403);
+ expect(mocks.createServer).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/dokploy/__test__/server/server-connect.test.ts b/apps/dokploy/__test__/server/server-connect.test.ts
new file mode 100644
index 00000000000..6f8515082b5
--- /dev/null
+++ b/apps/dokploy/__test__/server/server-connect.test.ts
@@ -0,0 +1,162 @@
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import {
+ buildConnectErrorScript,
+ buildConnectScript,
+ type ConnectTokenPayload,
+ createConnectToken,
+ decodeConnectToken,
+ getConnectClientIp,
+ verifyConnectToken,
+} from "@dokploy/server/services/server-connect";
+import { describe, expect, it } from "vitest";
+
+const NOW = 1_800_000_000_000;
+const payload: ConnectTokenPayload = {
+ sshKeyId: "Ab3_kX9-qL2mN8pR4sT6v",
+ userId: "DTnRRRQ5dmjSQHSLchvagLhmKpTD9VNh",
+ expiresAt: NOW / 1000 + 3600,
+ serverType: "deploy",
+ enableDockerCleanup: true,
+};
+const privateKey = "-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n-----END";
+
+describe("connect token", () => {
+ it("round-trips", () => {
+ const token = createConnectToken(payload, privateKey);
+ expect(token).toMatch(/^[A-Za-z0-9_.-]+$/);
+ expect(token.length).toBeLessThanOrEqual(100);
+ expect(decodeConnectToken(token)).toEqual(payload);
+ expect(verifyConnectToken(token, privateKey, NOW)).toBe("valid");
+ const build = {
+ ...payload,
+ serverType: "build",
+ enableDockerCleanup: false,
+ } as const;
+ expect(decodeConnectToken(createConnectToken(build, privateKey))).toEqual(
+ build,
+ );
+ });
+
+ it("rejects a token signed with another key", () => {
+ const token = createConnectToken(payload, privateKey);
+ expect(verifyConnectToken(token, "other-key", NOW)).toBe("invalid");
+ });
+
+ it("rejects a tampered payload", () => {
+ const token = createConnectToken(payload, privateKey);
+ const forged = token.replace(".d1.", ".b1.");
+ expect(forged).not.toBe(token);
+ expect(verifyConnectToken(forged, privateKey, NOW)).toBe("invalid");
+ });
+
+ it("rejects tampered or truncated signatures and garbage", () => {
+ const token = createConnectToken(payload, privateKey);
+ expect(verifyConnectToken(`${token}x`, privateKey, NOW)).toBe("invalid");
+ expect(verifyConnectToken(token.slice(0, -4), privateKey, NOW)).toBe(
+ "invalid",
+ );
+ expect(verifyConnectToken("garbage", privateKey, NOW)).toBe("invalid");
+ expect(verifyConnectToken(`${token}.extra`, privateKey, NOW)).toBe(
+ "invalid",
+ );
+ expect(decodeConnectToken("a.b.zz.x9.sig")).toBeNull();
+ });
+
+ it("reports expired tokens", () => {
+ const token = createConnectToken(
+ { ...payload, expiresAt: NOW / 1000 - 1 },
+ privateKey,
+ );
+ expect(verifyConnectToken(token, privateKey, NOW)).toBe("expired");
+ });
+});
+
+describe("connect script", () => {
+ const publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExample dokploy";
+ const registerUrl = "https://app.dokploy.com/api/connect/abc.def";
+
+ it("includes the key and register URL inside main", () => {
+ const script = buildConnectScript({ publicKey, registerUrl });
+ expect(script).toContain(`grep -qxF '${publicKey}'`);
+ expect(script).toContain(`'${registerUrl}'`);
+ expect(script.trim().endsWith('main "$@"')).toBe(true);
+ });
+
+ it("rejects unsafe register URLs and keys", () => {
+ expect(() =>
+ buildConnectScript({
+ publicKey,
+ registerUrl: "https://x.com/api/connect/a';rm -rf /;'",
+ }),
+ ).toThrow();
+ expect(() =>
+ buildConnectScript({ publicKey: "ssh-ed25519 a'b", registerUrl }),
+ ).toThrow();
+ });
+
+ it("falls back to any IP family when IPv4 fails", () => {
+ const script = buildConnectScript({ publicKey, registerUrl });
+ expect(script).toMatch(/curl -4 [^\n]*\|\|\n\s*code=\$\(curl -sS/);
+ });
+
+ it("is valid bash", () => {
+ const dir = mkdtempSync(join(tmpdir(), "connect-"));
+ const file = join(dir, "s.sh");
+ writeFileSync(file, buildConnectScript({ publicKey, registerUrl }));
+ execFileSync("bash", ["-n", file]);
+ writeFileSync(file, buildConnectErrorScript("It's not valid"));
+ execFileSync("bash", ["-n", file]);
+ });
+
+ it("appends the key on a new line when authorized_keys lacks a trailing newline", () => {
+ const dir = mkdtempSync(join(tmpdir(), "connect-"));
+ const keys = join(dir, "authorized_keys");
+ writeFileSync(keys, "ssh-rsa EXISTING user@host");
+ const snippet = buildConnectScript({ publicKey, registerUrl })
+ .split("\n")
+ .filter((line) => line.includes('"$keys"') && !line.includes("chmod"))
+ .join("\n");
+ execFileSync("bash", ["-c", `keys='${keys}'\n${snippet}\n${snippet}`]);
+ expect(readFileSync(keys, "utf8")).toBe(
+ `ssh-rsa EXISTING user@host\n${publicKey}\n`,
+ );
+ });
+});
+
+describe("getConnectClientIp", () => {
+ it("prefers cf-connecting-ip over x-forwarded-for", () => {
+ expect(
+ getConnectClientIp(
+ {
+ "cf-connecting-ip": "203.0.113.9",
+ "x-forwarded-for": "104.16.0.1",
+ },
+ "172.18.0.3",
+ ),
+ ).toBe("203.0.113.9");
+ });
+
+ it("prefers the first x-forwarded-for entry", () => {
+ expect(
+ getConnectClientIp(
+ { "x-forwarded-for": "203.0.113.5, 10.0.0.2" },
+ "10.0.0.2",
+ ),
+ ).toBe("203.0.113.5");
+ });
+
+ it("falls back to the socket address and strips IPv4-mapped prefixes", () => {
+ expect(getConnectClientIp({}, "::ffff:198.51.100.7")).toBe("198.51.100.7");
+ expect(getConnectClientIp({}, "2001:db8::1")).toBe("2001:db8::1");
+ });
+
+ it("returns null for anything that is not an IP", () => {
+ expect(getConnectClientIp({ "x-forwarded-for": "evil.com" }, "")).toBe(
+ null,
+ );
+ expect(getConnectClientIp({}, undefined)).toBe(null);
+ });
+});
diff --git a/apps/dokploy/__test__/server/traefik-setup.test.ts b/apps/dokploy/__test__/server/traefik-setup.test.ts
index b3d07d4e41b..3575bfd4ee4 100644
--- a/apps/dokploy/__test__/server/traefik-setup.test.ts
+++ b/apps/dokploy/__test__/server/traefik-setup.test.ts
@@ -40,10 +40,13 @@ const createStandaloneContainer = async (
additionalPorts: TraefikOptions["additionalPorts"],
) => {
const created = {
- start: vi.fn().mockResolvedValue(undefined),
+ id: "created-traefik",
inspect: vi.fn().mockResolvedValue({
State: { Running: true, StartedAt: "2026-10-26T00:00:00Z" },
}),
+ remove: vi.fn().mockResolvedValue(undefined),
+ rename: vi.fn().mockResolvedValue(undefined),
+ start: vi.fn().mockResolvedValue(undefined),
};
const createContainer = vi.fn().mockResolvedValue(created);
mocks.getRemoteDocker.mockResolvedValue({
@@ -58,6 +61,13 @@ const createStandaloneContainer = async (
await vi.runAllTimersAsync();
await started;
+ // A first start that fails is only logged, so make sure these settings are
+ // the ones that became dokploy-traefik and kept running.
+ expect(createContainer).toHaveBeenCalledTimes(1);
+ expect(created.rename).toHaveBeenCalledWith({ name: "dokploy-traefik" });
+ expect(created.start).toHaveBeenCalledTimes(1);
+ expect(created.remove).not.toHaveBeenCalled();
+
return createContainer.mock.calls[0]?.[0];
};
@@ -93,6 +103,9 @@ describe("initializeStandaloneTraefik", () => {
expect(settings.HostConfig.PortBindings["443/udp"]).toEqual([
{ HostPort: "443" },
]);
+ expect(Object.keys(settings.ExposedPorts)).toEqual(
+ expect.arrayContaining(["443/tcp", "443/udp"]),
+ );
});
});
diff --git a/apps/dokploy/__test__/settings/docker-server-boundary.test.ts b/apps/dokploy/__test__/settings/docker-server-boundary.test.ts
index cbc03eff5db..d67e8346e32 100644
--- a/apps/dokploy/__test__/settings/docker-server-boundary.test.ts
+++ b/apps/dokploy/__test__/settings/docker-server-boundary.test.ts
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
+import packageInfo from "../../package.json";
const mocks = vi.hoisted(() => ({
assertNoTraefikDeletion: vi.fn(),
@@ -527,7 +528,7 @@ describe("settings Docker server boundary", () => {
await expect(createCaller().updateServer()).resolves.toBe(true);
expect(mocks.getAgentHitsUpdateCommand).toHaveBeenCalledWith(
- "v0.31.0",
+ packageInfo.version,
"off_v0.29.8/Fork_159+next",
"v0.30.0",
undefined,
@@ -587,7 +588,7 @@ describe("settings Docker server boundary", () => {
expect(mocks.reloadDockerResource).toHaveBeenCalledWith(
"dokploy",
undefined,
- "v0.31.0",
+ packageInfo.version,
);
log.mockRestore();
});
@@ -606,7 +607,7 @@ describe("settings Docker server boundary", () => {
);
expect(mocks.getAgentHitsUpdateCommand).toHaveBeenCalledWith(
- "v0.31.0",
+ packageInfo.version,
"off_v0.29.8/Fork_159+next",
"v0.30.0",
4,
diff --git a/apps/dokploy/__test__/setup/monitoring-setup.real.test.ts b/apps/dokploy/__test__/setup/monitoring-setup.real.test.ts
index 03c01b0ab4b..88a1a17991e 100644
--- a/apps/dokploy/__test__/setup/monitoring-setup.real.test.ts
+++ b/apps/dokploy/__test__/setup/monitoring-setup.real.test.ts
@@ -13,7 +13,6 @@ vi.mock("@dokploy/server/services/server", () => ({
findServerById: vi.fn().mockResolvedValue({
serverId: "test-server",
serverType: "deploy",
- sshKeyId: null, // -> getRemoteDocker returns the local docker instance
metricsConfig: {
server: {
type: "Remote",
@@ -30,6 +29,11 @@ vi.mock("@dokploy/server/services/server", () => ({
}),
}));
+vi.mock("@dokploy/server/utils/servers/remote-docker", async () => {
+ const { docker } = await import("@dokploy/server/constants");
+ return { getRemoteDocker: vi.fn(async () => docker) };
+});
+
vi.mock("@dokploy/server/services/settings", () => ({
getDokployImageTag: vi.fn(() => "latest"),
}));
diff --git a/apps/dokploy/__test__/ssh-key/ssh-key-secret-redaction.test.ts b/apps/dokploy/__test__/ssh-key/ssh-key-secret-redaction.test.ts
index bab40c5f570..9f2b4a5cd47 100644
--- a/apps/dokploy/__test__/ssh-key/ssh-key-secret-redaction.test.ts
+++ b/apps/dokploy/__test__/ssh-key/ssh-key-secret-redaction.test.ts
@@ -88,7 +88,10 @@ describe("ssh key router secret redaction", () => {
});
const [result] = await createCaller().all();
- expect(result?.privateKey).toBe(REDACTED_SECRET_VALUE);
+ expect(mocks.sshKeyFindMany).toHaveBeenCalledWith(
+ expect.objectContaining({ columns: { privateKey: false } }),
+ );
+ expect(JSON.stringify(result)).not.toContain("private-key");
expect(result?.name).toBe("deploy");
});
diff --git a/apps/dokploy/__test__/traefik/reconnect-services.test.ts b/apps/dokploy/__test__/traefik/reconnect-services.test.ts
index a60b0504b12..22608518522 100644
--- a/apps/dokploy/__test__/traefik/reconnect-services.test.ts
+++ b/apps/dokploy/__test__/traefik/reconnect-services.test.ts
@@ -50,8 +50,8 @@ describe("reconnectServicesToTraefik", () => {
expect(mocks.execAsync).toHaveBeenCalledOnce();
expect(mocks.execAsync).toHaveBeenCalledWith(
- 'docker network connect first-compose $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1\n' +
- 'docker network connect second-compose $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1\n',
+ 'docker network connect first-compose $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1 || true\n' +
+ 'docker network connect second-compose $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1 || true\n',
);
expect(mocks.execAsyncRemote).not.toHaveBeenCalled();
});
@@ -64,7 +64,7 @@ describe("reconnectServicesToTraefik", () => {
expect(mocks.execAsyncRemote).toHaveBeenCalledOnce();
expect(mocks.execAsyncRemote).toHaveBeenCalledWith(
"server-id",
- 'docker network connect remote-compose $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1\n',
+ 'docker network connect remote-compose $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1 || true\n',
);
expect(mocks.execAsync).not.toHaveBeenCalled();
});
diff --git a/apps/dokploy/__test__/traefik/standalone-traefik-recreate.test.ts b/apps/dokploy/__test__/traefik/standalone-traefik-recreate.test.ts
index 18fa2da70b4..70fd667de83 100644
--- a/apps/dokploy/__test__/traefik/standalone-traefik-recreate.test.ts
+++ b/apps/dokploy/__test__/traefik/standalone-traefik-recreate.test.ts
@@ -29,24 +29,40 @@ const CRASH_LOG = frame(
interface FakeOptions {
oldRunning?: boolean | null;
staleBackup?: boolean;
+ staleBackupRunning?: boolean;
imagePresent?: boolean;
pullEvents?: { error?: string }[];
startError?: Error;
crashLoop?: boolean;
restoreError?: Error;
+ backupRenameError?: Error;
+ oldNetworks?: Record;
+ connectError?: Error;
+ // Holds the rename with this log entry until `until` settles.
+ holdRename?: { entry: string; until: Promise };
}
const fakeDocker = ({
oldRunning = true,
staleBackup = false,
+ staleBackupRunning = false,
imagePresent = true,
pullEvents = [],
startError,
crashLoop = false,
restoreError,
+ backupRenameError,
+ oldNetworks = {},
+ connectError,
+ holdRename,
}: FakeOptions = {}) => {
const log: string[] = [];
const containers: { id: string; name: string; running: boolean }[] = [];
+ const networks: Record<
+ string,
+ Record
+ > = { old: { ...oldNetworks } };
+ const neverStarted = new Set();
if (oldRunning !== null) {
containers.push({
id: "old",
@@ -58,7 +74,7 @@ const fakeDocker = ({
containers.push({
id: "stale",
name: "dokploy-traefik-previous",
- running: false,
+ running: staleBackupRunning,
});
}
let hasImage = imagePresent;
@@ -73,17 +89,48 @@ const fakeDocker = ({
};
const container = (ref: string) => ({
+ id: ref,
inspect: async () => {
const c = find(ref);
const startedAt =
c.id === "new" && crashLoop ? `crash-${++restarts}` : "steady";
- return { Id: c.id, State: { Running: c.running, StartedAt: startedAt } };
+ return {
+ Id: c.id,
+ State: {
+ Running: c.running,
+ Status: c.running
+ ? "running"
+ : neverStarted.has(c.id)
+ ? "created"
+ : "exited",
+ StartedAt: startedAt,
+ },
+ NetworkSettings: { Networks: networks[c.id] ?? {} },
+ };
},
rename: async ({ name }: { name: string }) => {
+ if (holdRename?.entry === `rename ${ref} -> ${name}`) {
+ await holdRename.until;
+ }
const c = find(ref);
- if (restoreError && c.id === "old" && name === "dokploy-traefik") {
+ if (containers.some((other) => other !== c && other.name === name)) {
+ throw new Error(`Conflict: ${name} is already in use`);
+ }
+ if (c.running) {
+ throw new Error(
+ `could not add service state for endpoint ${name} to cluster on UpdateDNSNames: cannot create entry in table endpoint_table, already exists`,
+ );
+ }
+ if (
+ restoreError &&
+ name === "dokploy-traefik" &&
+ !c.id.startsWith("new")
+ ) {
throw restoreError;
}
+ if (backupRenameError && name === "dokploy-traefik-previous") {
+ throw backupRenameError;
+ }
log.push(`rename ${c.id} -> ${name}`);
c.name = name;
},
@@ -96,6 +143,7 @@ const fakeDocker = ({
const c = find(ref);
log.push(`start ${c.id}`);
if (startError && c.id === "new") throw startError;
+ neverStarted.delete(c.id);
c.running = true;
},
remove: async () => {
@@ -127,6 +175,22 @@ const fakeDocker = ({
},
},
getContainer: (ref: string) => container(ref),
+ getNetwork: (networkId: string) => ({
+ connect: async ({
+ Container,
+ EndpointConfig,
+ }: {
+ Container: string;
+ EndpointConfig: { Aliases?: string[] };
+ }) => {
+ if (connectError) throw connectError;
+ log.push(`connect ${Container} -> ${networkId}`);
+ networks[Container] = {
+ ...networks[Container],
+ [networkId]: { NetworkID: networkId, ...EndpointConfig },
+ };
+ },
+ }),
createContainer: async (settings: Record) => {
const name = settings.name as string;
if (containers.some((c) => c.name === name)) {
@@ -136,6 +200,7 @@ const fakeDocker = ({
created += 1;
const id = created === 1 ? "new" : `new${created}`;
containers.push({ id, name, running: false });
+ neverStarted.add(id);
log.push(`create ${id}`);
return container(id);
},
@@ -145,6 +210,7 @@ const fakeDocker = ({
docker,
log,
containers,
+ networks,
createdWith: () => createdWith,
};
};
@@ -182,13 +248,20 @@ describe("initializeStandaloneTraefik", () => {
await vi.advanceTimersByTimeAsync(0);
expect(fake.log).toEqual([
- "rename old -> dokploy-traefik-previous",
- "stop old",
"create new",
+ "stop old",
+ "rename old -> dokploy-traefik-previous",
+ "rename new -> dokploy-traefik",
"start new",
]);
+ expect(fake.containers).toContainEqual({
+ id: "old",
+ name: "dokploy-traefik-previous",
+ running: false,
+ });
await vi.runAllTimersAsync();
await result;
+ expect(fake.log.at(-1)).toBe("remove old");
});
it("keeps the old container until the new one stays up, then removes it", async () => {
@@ -202,9 +275,10 @@ describe("initializeStandaloneTraefik", () => {
expect(error).toBeNull();
expect(fake.log).toEqual([
- "rename old -> dokploy-traefik-previous",
- "stop old",
"create new",
+ "stop old",
+ "rename old -> dokploy-traefik-previous",
+ "rename new -> dokploy-traefik",
"start new",
"remove old",
]);
@@ -212,7 +286,7 @@ describe("initializeStandaloneTraefik", () => {
{ id: "new", name: "dokploy-traefik", running: true },
]);
expect(fake.createdWith()).toMatchObject({
- name: "dokploy-traefik",
+ name: "dokploy-traefik-next",
Image: `traefik:v${TRAEFIK_VERSION}`,
HostConfig: { PortBindings: { "8080/tcp": [{ HostPort: "8080" }] } },
});
@@ -254,9 +328,10 @@ describe("initializeStandaloneTraefik", () => {
"port is already allocated. The previous Traefik was restored.",
);
expect(fake.log).toEqual([
- "rename old -> dokploy-traefik-previous",
- "stop old",
"create new",
+ "stop old",
+ "rename old -> dokploy-traefik-previous",
+ "rename new -> dokploy-traefik",
"start new",
"remove new",
"rename old -> dokploy-traefik",
@@ -301,12 +376,57 @@ describe("initializeStandaloneTraefik", () => {
const error = await recreate(fake);
expect(error).toBeNull();
- expect(fake.log.slice(0, 2)).toEqual([
+ expect(fake.log.slice(0, 4)).toEqual([
+ "create new",
"remove stale",
+ "stop old",
"rename old -> dokploy-traefik-previous",
]);
});
+ it("joins the new container to every other network the old one was on, before starting it", async () => {
+ const fake = fakeDocker({
+ oldNetworks: {
+ "dokploy-network": { NetworkID: "dokploy-network-id" },
+ "my-compose": { NetworkID: "my-compose-id" },
+ "manual-net": { NetworkID: "manual-net-id", Aliases: ["proxy"] },
+ },
+ });
+
+ const error = await recreate(fake);
+
+ expect(error).toBeNull();
+ expect(fake.log).toEqual([
+ "create new",
+ "connect new -> my-compose-id",
+ "connect new -> manual-net-id",
+ "stop old",
+ "rename old -> dokploy-traefik-previous",
+ "rename new -> dokploy-traefik",
+ "start new",
+ "remove old",
+ ]);
+ expect(fake.networks.new).toEqual({
+ "my-compose-id": { NetworkID: "my-compose-id" },
+ "manual-net-id": { NetworkID: "manual-net-id", Aliases: ["proxy"] },
+ });
+ });
+
+ it("keeps the old container running when the new one cannot join a network", async () => {
+ const fake = fakeDocker({
+ oldNetworks: { "manual-net": { NetworkID: "manual-net-id" } },
+ connectError: new Error("network manual-net-id not found"),
+ });
+
+ const error = await recreate(fake);
+
+ expect(error?.message).toBe("network manual-net-id not found");
+ expect(fake.log).toEqual(["create new", "remove new"]);
+ expect(fake.containers).toEqual([
+ { id: "old", name: "dokploy-traefik", running: true },
+ ]);
+ });
+
it("says so when putting the old container back also fails", async () => {
const fake = fakeDocker({
startError: new Error("port is already allocated"),
@@ -320,6 +440,25 @@ describe("initializeStandaloneTraefik", () => {
);
});
+ it("starts the old container again when it cannot be moved aside", async () => {
+ const fake = fakeDocker({
+ backupRenameError: new Error("name already in use"),
+ });
+
+ const error = await recreate(fake);
+
+ expect(error?.message).toBe("name already in use");
+ expect(fake.log).toEqual([
+ "create new",
+ "stop old",
+ "start old",
+ "remove new",
+ ]);
+ expect(fake.containers).toEqual([
+ { id: "old", name: "dokploy-traefik", running: true },
+ ]);
+ });
+
it("runs overlapping recreates of the same server one after another", async () => {
const fake = fakeDocker();
mocks.getRemoteDocker.mockResolvedValue(fake.docker);
@@ -335,14 +474,16 @@ describe("initializeStandaloneTraefik", () => {
await expect(first).resolves.toBeUndefined();
await expect(second).resolves.toBeUndefined();
expect(fake.log).toEqual([
- "rename old -> dokploy-traefik-previous",
- "stop old",
"create new",
+ "stop old",
+ "rename old -> dokploy-traefik-previous",
+ "rename new -> dokploy-traefik",
"start new",
"remove old",
- "rename new -> dokploy-traefik-previous",
- "stop new",
"create new2",
+ "stop new",
+ "rename new -> dokploy-traefik-previous",
+ "rename new2 -> dokploy-traefik",
"start new2",
"remove new",
]);
@@ -382,7 +523,11 @@ describe("initializeStandaloneTraefik", () => {
const error = await recreate(fake);
expect(error).toBeNull();
- expect(fake.log).toEqual(["create new", "start new"]);
+ expect(fake.log).toEqual([
+ "create new",
+ "rename new -> dokploy-traefik",
+ "start new",
+ ]);
});
it("keeps the old behaviour on a fresh setup that fails: logs instead of throwing", async () => {
@@ -394,7 +539,12 @@ describe("initializeStandaloneTraefik", () => {
const error = await recreate(fake);
expect(error).toBeNull();
- expect(fake.log).toEqual(["create new", "start new"]);
+ expect(fake.log).toEqual([
+ "create new",
+ "rename new -> dokploy-traefik",
+ "start new",
+ "remove new",
+ ]);
});
});
@@ -425,6 +575,172 @@ describe("restoreInterruptedTraefik", () => {
]);
});
+ it("starts the backup again even when renaming it back fails", async () => {
+ const fake = fakeDocker({
+ oldRunning: null,
+ staleBackup: true,
+ staleBackupRunning: true,
+ restoreError: new Error("name already in use"),
+ });
+ mocks.getRemoteDocker.mockResolvedValue(fake.docker);
+
+ await expect(restoreInterruptedTraefik()).rejects.toThrow(
+ "name already in use",
+ );
+
+ expect(fake.containers).toEqual([
+ { id: "stale", name: "dokploy-traefik-previous", running: true },
+ ]);
+ });
+
+ it("stops a running backup before renaming it back", async () => {
+ const fake = fakeDocker({
+ oldRunning: null,
+ staleBackup: true,
+ staleBackupRunning: true,
+ });
+ mocks.getRemoteDocker.mockResolvedValue(fake.docker);
+
+ await restoreInterruptedTraefik();
+
+ expect(fake.log).toEqual([
+ "stop stale",
+ "rename stale -> dokploy-traefik",
+ "start stale",
+ ]);
+ expect(fake.containers).toEqual([
+ { id: "stale", name: "dokploy-traefik", running: true },
+ ]);
+ });
+
+ it("clears a new container that never started and brings back the backup", async () => {
+ const fake = fakeDocker({ oldRunning: null, staleBackup: true });
+ mocks.getRemoteDocker.mockResolvedValue(fake.docker);
+ await fake.docker.createContainer({ name: "dokploy-traefik" });
+
+ await restoreInterruptedTraefik();
+
+ expect(fake.log).toEqual([
+ "create new",
+ "remove new",
+ "rename stale -> dokploy-traefik",
+ "start stale",
+ ]);
+ expect(fake.containers).toEqual([
+ { id: "stale", name: "dokploy-traefik", running: true },
+ ]);
+ });
+
+ it("starts Traefik again when Dokploy restarted right after an update stopped it", async () => {
+ const fake = fakeDocker({ oldRunning: false });
+ mocks.getRemoteDocker.mockResolvedValue(fake.docker);
+ await fake.docker.createContainer({ name: "dokploy-traefik-next" });
+
+ await restoreInterruptedTraefik();
+
+ expect(fake.log).toEqual(["create new", "start old", "remove new"]);
+ expect(fake.containers).toEqual([
+ { id: "old", name: "dokploy-traefik", running: true },
+ ]);
+ });
+
+ it("only clears the new container when Dokploy restarted before the update stopped Traefik", async () => {
+ const fake = fakeDocker();
+ mocks.getRemoteDocker.mockResolvedValue(fake.docker);
+ await fake.docker.createContainer({ name: "dokploy-traefik-next" });
+
+ await restoreInterruptedTraefik();
+
+ expect(fake.log).toEqual(["create new", "remove new"]);
+ expect(fake.containers).toEqual([
+ { id: "old", name: "dokploy-traefik", running: true },
+ ]);
+ });
+
+ it("brings back the backup when Dokploy restarted mid-swap", async () => {
+ const fake = fakeDocker({ oldRunning: null, staleBackup: true });
+ mocks.getRemoteDocker.mockResolvedValue(fake.docker);
+ await fake.docker.createContainer({ name: "dokploy-traefik-next" });
+
+ await restoreInterruptedTraefik();
+
+ expect(fake.log).toEqual([
+ "create new",
+ "rename stale -> dokploy-traefik",
+ "start stale",
+ "remove new",
+ ]);
+ expect(fake.containers).toEqual([
+ { id: "stale", name: "dokploy-traefik", running: true },
+ ]);
+ });
+
+ it("leaves a stopped Traefik alone when no update was interrupted", async () => {
+ const fake = fakeDocker({ oldRunning: false });
+ mocks.getRemoteDocker.mockResolvedValue(fake.docker);
+
+ await restoreInterruptedTraefik();
+
+ expect(fake.log).toEqual([]);
+ });
+
+ it("leaves a stopped Traefik alone even when a backup exists", async () => {
+ const fake = fakeDocker({ oldRunning: false, staleBackup: true });
+ mocks.getRemoteDocker.mockResolvedValue(fake.docker);
+
+ await restoreInterruptedTraefik();
+
+ expect(fake.log).toEqual([]);
+ });
+
+ it("waits for a running update instead of restoring its backup mid-way", async () => {
+ let resume!: () => void;
+ const fake = fakeDocker({
+ holdRename: {
+ entry: "rename new -> dokploy-traefik",
+ until: new Promise((resolve) => {
+ resume = resolve;
+ }),
+ },
+ });
+ mocks.getRemoteDocker.mockResolvedValue(fake.docker);
+
+ const update = initializeStandaloneTraefik().then(
+ () => null,
+ (error: Error) => error,
+ );
+ await vi.advanceTimersByTimeAsync(0);
+ // What a restore after a Dokploy restart would undo: a backup, a new
+ // container and no dokploy-traefik.
+ expect(fake.containers.map((c) => c.name)).toEqual([
+ "dokploy-traefik-previous",
+ "dokploy-traefik-next",
+ ]);
+ const restore = restoreInterruptedTraefik();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(fake.log).toEqual([
+ "create new",
+ "stop old",
+ "rename old -> dokploy-traefik-previous",
+ ]);
+ resume();
+ await vi.runAllTimersAsync();
+
+ expect(await update).toBeNull();
+ await expect(restore).resolves.toBeUndefined();
+ expect(fake.log).toEqual([
+ "create new",
+ "stop old",
+ "rename old -> dokploy-traefik-previous",
+ "rename new -> dokploy-traefik",
+ "start new",
+ "remove old",
+ ]);
+ expect(fake.containers).toEqual([
+ { id: "new", name: "dokploy-traefik", running: true },
+ ]);
+ });
+
it("leaves things alone when Traefik exists", async () => {
const fake = fakeDocker({ staleBackup: true });
mocks.getRemoteDocker.mockResolvedValue(fake.docker);
@@ -452,9 +768,10 @@ describe("restoreInterruptedTraefik", () => {
expect(fake.log).toEqual([
"rename stale -> dokploy-traefik",
"start stale",
- "rename stale -> dokploy-traefik-previous",
- "stop stale",
"create new",
+ "stop stale",
+ "rename stale -> dokploy-traefik-previous",
+ "rename new -> dokploy-traefik",
"start new",
"remove stale",
]);
diff --git a/apps/dokploy/__test__/traefik/update-traefik-cloud.test.ts b/apps/dokploy/__test__/traefik/update-traefik-cloud.test.ts
index e0cb63e68a3..0960c92715b 100644
--- a/apps/dokploy/__test__/traefik/update-traefik-cloud.test.ts
+++ b/apps/dokploy/__test__/traefik/update-traefik-cloud.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
findServerById: vi.fn(),
+ getAccessibleServerIds: vi.fn(),
getTraefikOverview: vi.fn(),
pullTraefikImage: vi.fn(),
readEnvironmentVariableList: vi.fn(),
@@ -46,6 +47,7 @@ describe("Traefik update endpoints on cloud", () => {
serverId,
organizationId: serverId === "server-b" ? "org-b" : "org-a",
}));
+ mocks.getAccessibleServerIds.mockResolvedValue(new Set(["server-a"]));
mocks.getTraefikOverview.mockResolvedValue({
state: "running",
startedAt: "2026-10-23T03:00:00Z",
diff --git a/apps/dokploy/__test__/traefik/update-traefik-router.test.ts b/apps/dokploy/__test__/traefik/update-traefik-router.test.ts
index ab3682f3b37..03fd86dade3 100644
--- a/apps/dokploy/__test__/traefik/update-traefik-router.test.ts
+++ b/apps/dokploy/__test__/traefik/update-traefik-router.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
findServerById: vi.fn(),
+ getAccessibleServerIds: vi.fn(),
getTraefikOverview: vi.fn(),
pullTraefikImage: vi.fn(),
readEnvironmentVariableList: vi.fn(),
@@ -62,6 +63,9 @@ describe("Traefik update endpoints", () => {
serverId,
organizationId: serverId === "server-b" ? "org-b" : "org-a",
}));
+ mocks.getAccessibleServerIds.mockResolvedValue(
+ new Set(["server-a", "server-c"]),
+ );
mocks.getTraefikOverview.mockResolvedValue(overview("outdated"));
mocks.pullTraefikImage.mockResolvedValue(undefined);
mocks.readEnvironmentVariableList.mockResolvedValue(TRAEFIK_ENV);
diff --git a/apps/dokploy/__test__/users/container-metrics-boundary.test.ts b/apps/dokploy/__test__/users/container-metrics-boundary.test.ts
index 26058d5b0db..1089e03e30f 100644
--- a/apps/dokploy/__test__/users/container-metrics-boundary.test.ts
+++ b/apps/dokploy/__test__/users/container-metrics-boundary.test.ts
@@ -106,8 +106,8 @@ vi.mock("@/server/api/utils/monitoring-access", () => ({
mocks.assertContainerMetricsServiceAccess,
}));
-vi.mock("@dokploy/server/utils/url/network", () => ({
- fetchWithPublicEgress: mocks.fetch,
+vi.mock("@dokploy/server/services/logs-and-metrics/provider-fetch", () => ({
+ providerFetch: mocks.fetch,
}));
const { userRouter } = await import("../../server/api/routers/user");
@@ -198,10 +198,6 @@ describe("user.getContainerMetrics target boundary", () => {
Authorization: "Bearer stored-remote-token",
},
},
- {
- allowPrivateNetwork: true,
- fieldName: "Monitoring metrics URL",
- },
);
expect(mocks.assertContainerMetricsServiceAccess).toHaveBeenCalledWith(
expect.anything(),
@@ -257,10 +253,6 @@ describe("user.getContainerMetrics target boundary", () => {
Authorization: "Bearer stored-local-token",
},
},
- {
- allowPrivateNetwork: true,
- fieldName: "Monitoring metrics URL",
- },
);
});
diff --git a/apps/dokploy/__test__/users/user-service-email-boundary.test.ts b/apps/dokploy/__test__/users/user-service-email-boundary.test.ts
index f1ec8992ec8..5cd78391fff 100644
--- a/apps/dokploy/__test__/users/user-service-email-boundary.test.ts
+++ b/apps/dokploy/__test__/users/user-service-email-boundary.test.ts
@@ -1,15 +1,26 @@
+import type { SQL } from "drizzle-orm";
+import { PgDialect } from "drizzle-orm/pg-core";
import { beforeEach, describe, expect, it, vi } from "vitest";
+type InvitationRow = { email: string; status: string; expiresAt: Date };
+
const mocks = vi.hoisted(() => ({
dbUpdate: vi.fn(),
updateReturning: vi.fn(),
updateSet: vi.fn(),
updateWhere: vi.fn(),
+ findUser: vi.fn(),
+ findInvitation: vi.fn(),
+ invitations: [] as InvitationRow[],
}));
vi.mock("@dokploy/server/db", () => ({
db: {
update: mocks.dbUpdate,
+ query: {
+ user: { findFirst: mocks.findUser },
+ invitation: { findFirst: mocks.findInvitation },
+ },
},
}));
@@ -19,9 +30,31 @@ vi.mock("@dokploy/server/lib/auth", () => ({
const { updateUser } = await import("@dokploy/server/services/user");
+// The mock answers like the database would, so the case for an expired
+// invitation depends on the query's own expiry condition.
+const findPendingInvitation = ({ where }: { where: SQL }) => {
+ const { sql, params } = new PgDialect().sqlToQuery(where);
+ expect(sql).toBe(
+ '(lower("invitation"."email") = $1 and "invitation"."status" = $2 and "invitation"."expires_at" > $3)',
+ );
+ const [email, status, now] = params as [string, string, string | Date];
+ const nowTime = new Date(now).getTime();
+ return Promise.resolve(
+ mocks.invitations.find(
+ (row) =>
+ row.email.toLowerCase() === email &&
+ row.status === status &&
+ row.expiresAt.getTime() > nowTime,
+ ),
+ );
+};
+
describe("updateUser email verification boundary", () => {
beforeEach(() => {
vi.clearAllMocks();
+ mocks.invitations = [];
+ mocks.findUser.mockResolvedValue({ email: "old@example.com" });
+ mocks.findInvitation.mockImplementation(findPendingInvitation);
mocks.dbUpdate.mockReturnValue({
set: mocks.updateSet,
});
@@ -40,6 +73,7 @@ describe("updateUser email verification boundary", () => {
firstName: "Ada",
});
+ expect(mocks.findInvitation).toHaveBeenCalledTimes(1);
expect(mocks.updateSet).toHaveBeenCalledWith({
email: "new@example.com",
firstName: "Ada",
@@ -47,12 +81,49 @@ describe("updateUser email verification boundary", () => {
});
});
+ it("refuses an email that has a pending, unexpired invitation", async () => {
+ mocks.invitations = [
+ {
+ email: "invitee@example.com",
+ status: "pending",
+ expiresAt: new Date(Date.now() + 60 * 60 * 1000),
+ },
+ ];
+
+ await expect(
+ updateUser("user-1", { email: "Invitee@Example.com" }),
+ ).rejects.toThrow("This email address can't be used");
+
+ expect(mocks.dbUpdate).not.toHaveBeenCalled();
+ expect(mocks.updateSet).not.toHaveBeenCalled();
+ });
+
+ it("lets an email through when its pending invitation has expired", async () => {
+ mocks.invitations = [
+ {
+ email: "invitee@example.com",
+ status: "pending",
+ expiresAt: new Date(Date.now() - 60 * 1000),
+ },
+ ];
+
+ await updateUser("user-1", { email: "invitee@example.com" });
+
+ expect(mocks.findInvitation).toHaveBeenCalledTimes(1);
+ expect(mocks.updateSet).toHaveBeenCalledWith({
+ email: "invitee@example.com",
+ emailVerified: false,
+ });
+ });
+
it("does not change emailVerified for profile updates without email", async () => {
await updateUser("user-1", {
firstName: "Ada",
lastName: "Lovelace",
});
+ expect(mocks.findUser).not.toHaveBeenCalled();
+ expect(mocks.findInvitation).not.toHaveBeenCalled();
expect(mocks.updateSet).toHaveBeenCalledWith({
firstName: "Ada",
lastName: "Lovelace",
diff --git a/apps/dokploy/__test__/utils/docker-cleanup-traefik.test.ts b/apps/dokploy/__test__/utils/docker-cleanup-traefik.test.ts
index 630d5fb264c..187d28c064b 100644
--- a/apps/dokploy/__test__/utils/docker-cleanup-traefik.test.ts
+++ b/apps/dokploy/__test__/utils/docker-cleanup-traefik.test.ts
@@ -81,6 +81,9 @@ describe("docker cleanup keeps a stopped dokploy-traefik", () => {
expect(
runWithFakeDocker(script!, { "dokploy-traefik-previous": "false" }),
).toEqual([]);
+ expect(
+ runWithFakeDocker(script!, { "dokploy-traefik-next": "false" }),
+ ).toEqual([]);
expect(runWithFakeDocker(script!, { "dokploy-traefik": "true" })).toEqual([
prune,
]);
diff --git a/apps/dokploy/__test__/wss/terminal-ssh-lifecycle.test.ts b/apps/dokploy/__test__/wss/terminal-ssh-lifecycle.test.ts
new file mode 100644
index 00000000000..ff42d69b264
--- /dev/null
+++ b/apps/dokploy/__test__/wss/terminal-ssh-lifecycle.test.ts
@@ -0,0 +1,261 @@
+import { EventEmitter } from "node:events";
+import http from "node:http";
+import type { AddressInfo } from "node:net";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { WebSocket } from "ws";
+
+interface FakeClient extends EventEmitter {
+ connect: ReturnType;
+ destroy: ReturnType;
+ end: ReturnType;
+ shell: ReturnType;
+ exec: ReturnType;
+}
+
+const mocks = vi.hoisted(() => ({
+ clients: [] as FakeClient[],
+ findServerById: vi.fn(),
+ resolveServerDestinationHost: vi.fn(),
+ validateRequest: vi.fn(),
+}));
+
+// The test opens the channels itself, through the callbacks the handlers pass.
+vi.mock("ssh2", async () => {
+ const { EventEmitter } = await import("node:events");
+ class Client extends EventEmitter {
+ connect = vi.fn(() => this);
+ destroy = vi.fn(() => this);
+ end = vi.fn(() => this);
+ shell = vi.fn();
+ // As ssh2 does once the connection has ended.
+ exec = vi.fn(() => {
+ if (this.end.mock.calls.length > 0) {
+ throw new Error("Not connected");
+ }
+ return this;
+ });
+ constructor() {
+ super();
+ mocks.clients.push(this as unknown as FakeClient);
+ }
+ }
+ return { Client };
+});
+vi.mock("node-pty", () => ({ spawn: vi.fn() }));
+vi.mock("public-ip", () => ({ publicIpv4: vi.fn(), publicIpv6: vi.fn() }));
+vi.mock("@dokploy/server", () => ({
+ IS_CLOUD: false,
+ execAsync: vi.fn(),
+ findServerById: mocks.findServerById,
+ resolveTrustedOriginsForAuthRequest: vi.fn(async () => []),
+ validateRequest: mocks.validateRequest,
+}));
+vi.mock("@dokploy/server/utils/servers/destination", () => ({
+ resolveServerDestinationHost: mocks.resolveServerDestinationHost,
+}));
+vi.mock("../../server/utils/docker", () => ({
+ getDockerHost: vi.fn(),
+}));
+vi.mock("../../server/wss/authorize", () => ({
+ canAccessTerminalOverWss: vi.fn(async () => true),
+ canAccessDockerOverWss: vi.fn(async () => true),
+}));
+vi.mock("../../server/wss/server-permission", () => ({
+ canAccessServerTerminalWebSocket: vi.fn(async () => true),
+}));
+vi.mock("../../server/wss/docker-permission", () => ({
+ canAccessDockerTerminalWebSocket: vi.fn(async () => true),
+}));
+vi.mock("../../server/wss/container-ownership", () => ({
+ containerBelongsToService: vi.fn(async () => true),
+}));
+
+const { setupDockerContainerTerminalWebSocketServer } = await import(
+ "../../server/wss/docker-container-terminal"
+);
+const { HANGUP_SCAN_DELAYS_MS } = await import("../../server/wss/hangup-scans");
+const { setupTerminalWebSocketServer } = await import(
+ "../../server/wss/terminal"
+);
+
+const terminals = {
+ server: {
+ path: "/terminal?serverId=server-1",
+ openChannel: (c: FakeClient) => c.shell,
+ },
+ container: {
+ path: "/docker-container-terminal?containerId=abc123def456&serverId=server-1",
+ openChannel: (c: FakeClient) => c.exec,
+ },
+} as const;
+
+let server: http.Server;
+let base: string;
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ mocks.clients.length = 0;
+ mocks.validateRequest.mockResolvedValue({
+ user: { id: "user-1" },
+ session: {
+ id: "session-1",
+ activeOrganizationId: "org-1",
+ authMethod: "session",
+ },
+ });
+ mocks.findServerById.mockResolvedValue({
+ organizationId: "org-1",
+ port: 22,
+ username: "root",
+ sshKeyId: "key-1",
+ sshKey: { privateKey: "key" },
+ });
+ mocks.resolveServerDestinationHost.mockResolvedValue("203.0.113.10");
+ server = http.createServer();
+ setupTerminalWebSocketServer(server);
+ setupDockerContainerTerminalWebSocketServer(server);
+ await new Promise((r) => server.listen(0, "127.0.0.1", r));
+ base = `ws://127.0.0.1:${(server.address() as AddressInfo).port}`;
+});
+
+afterEach(async () => {
+ vi.useRealTimers();
+ await new Promise((r) => server.close(r));
+});
+
+const connect = async (path: string) => {
+ const ws = new WebSocket(`${base}${path}`);
+ ws.on("error", () => {});
+ await new Promise((r) => ws.once("open", r));
+ return ws;
+};
+
+const connecting = async () => {
+ await vi.waitFor(() => expect(mocks.clients[0]?.connect).toHaveBeenCalled());
+ return mocks.clients[0] as FakeClient;
+};
+
+const closeClient = async (ws: WebSocket) => {
+ const closed = new Promise((r) => ws.once("close", r));
+ ws.close();
+ await closed;
+};
+
+// vi.waitFor would move the fake clock on every retry.
+const until = async (condition: () => boolean) => {
+ const deadline = Date.now() + 2_000;
+ while (!condition() && Date.now() < deadline) {
+ await new Promise((r) => setImmediate(r));
+ }
+ expect(condition()).toBe(true);
+};
+
+const fakeStream = () =>
+ Object.assign(new EventEmitter(), {
+ stderr: Object.assign(new EventEmitter(), { resume: vi.fn() }),
+ end: vi.fn(),
+ resume: vi.fn(),
+ setWindow: vi.fn(),
+ write: vi.fn(),
+ });
+
+const openShell = async (
+ t: (typeof terminals)[keyof typeof terminals],
+ error?: Error,
+) => {
+ const ws = await connect(t.path);
+ const client = await connecting();
+ client.emit("ready");
+ await vi.waitFor(() => expect(t.openChannel(client)).toHaveBeenCalled());
+ const stream = fakeStream();
+ t.openChannel(client).mock.calls[0]?.at(-1)(
+ error,
+ error ? undefined : stream,
+ );
+ return { ws, client, stream };
+};
+
+describe.each(Object.entries(terminals))("%s terminal over SSH", (_, t) => {
+ it("closes the socket and the connection when the remote shell exits", async () => {
+ const { ws, client, stream } = await openShell(t);
+
+ stream.emit("close", 0);
+
+ await vi.waitFor(() => expect(ws.readyState).toBe(WebSocket.CLOSED));
+ expect(client.end).toHaveBeenCalled();
+ });
+
+ it("closes the socket and the connection when the shell cannot be opened", async () => {
+ const { ws, client } = await openShell(
+ t,
+ new Error("channel open failure"),
+ );
+
+ await vi.waitFor(() => expect(ws.readyState).toBe(WebSocket.CLOSED));
+ expect(client.end).toHaveBeenCalled();
+ });
+});
+
+describe("server terminal when the browser leaves", () => {
+ it("ends a connection still being made at once and destroys it 3 s later", async () => {
+ const ws = await connect(terminals.server.path);
+ const client = await connecting();
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+
+ await closeClient(ws);
+ await until(() => client.end.mock.calls.length > 0);
+ vi.advanceTimersByTime(2_999);
+ expect(client.destroy).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(1);
+
+ expect(client.destroy).toHaveBeenCalledTimes(1);
+ expect(client.shell).not.toHaveBeenCalled();
+ });
+
+ it("ends the shell and the connection of an open shell, and destroys a connection still open 3 s later", async () => {
+ const { ws, client, stream } = await openShell(terminals.server);
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+
+ await closeClient(ws);
+ await until(() => client.end.mock.calls.length > 0);
+ expect(stream.end).toHaveBeenCalled();
+ expect(client.destroy).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(3_000);
+
+ expect(client.destroy).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not destroy a connection that closed within 3 s", async () => {
+ const { ws, client } = await openShell(terminals.server);
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+
+ await closeClient(ws);
+ await until(() => client.end.mock.calls.length > 0);
+ client.emit("close");
+ vi.advanceTimersByTime(3_000);
+
+ expect(client.destroy).not.toHaveBeenCalled();
+ });
+});
+
+describe("container terminal when the browser leaves", () => {
+ it("keeps the connection for every hangup scan and ends it after the last one", async () => {
+ const { ws, client, stream } = await openShell(terminals.container);
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+
+ await closeClient(ws);
+ for (const [scan, delay] of [0, ...HANGUP_SCAN_DELAYS_MS].entries()) {
+ await vi.advanceTimersByTimeAsync(delay);
+ await until(() => client.exec.mock.calls.length === scan + 2);
+ expect(client.end).not.toHaveBeenCalled();
+ const hangup = fakeStream();
+ client.exec.mock.calls[scan + 1]?.at(-1)(undefined, hangup);
+ hangup.emit("close", 0);
+ }
+
+ await until(() => client.end.mock.calls.length > 0);
+ expect(stream.end).toHaveBeenCalled();
+ expect(client.exec).toHaveBeenCalledTimes(HANGUP_SCAN_DELAYS_MS.length + 2);
+ expect(client.destroy).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/dokploy/components/dashboard/docker/terminal/docker-terminal.tsx b/apps/dokploy/components/dashboard/docker/terminal/docker-terminal.tsx
index 333cad6ac94..1e2a658dd8c 100644
--- a/apps/dokploy/components/dashboard/docker/terminal/docker-terminal.tsx
+++ b/apps/dokploy/components/dashboard/docker/terminal/docker-terminal.tsx
@@ -93,9 +93,7 @@ export const DockerTerminal: React.FC = ({
cancelled = true;
cancelAnimationFrame(frame);
resizeObserver?.disconnect();
- if (ws && ws.readyState === WebSocket.OPEN) {
- ws.close();
- }
+ ws?.close();
term?.dispose();
};
}, [containerId, activeWay, id]);
diff --git a/apps/dokploy/components/dashboard/monitoring/free/container/show-free-container-monitoring.tsx b/apps/dokploy/components/dashboard/monitoring/free/container/show-free-container-monitoring.tsx
index 0d63fe99c6f..0e097ceb5f0 100644
--- a/apps/dokploy/components/dashboard/monitoring/free/container/show-free-container-monitoring.tsx
+++ b/apps/dokploy/components/dashboard/monitoring/free/container/show-free-container-monitoring.tsx
@@ -151,7 +151,7 @@ export const ContainerFreeMonitoring = ({
serviceId,
}: Props) => {
const { data } = api.application.readAppMonitoring.useQuery(
- { appName },
+ { appName, serviceId },
{
refetchOnWindowFocus: false,
},
diff --git a/apps/dokploy/components/dashboard/onboarding/steps/plan-step.tsx b/apps/dokploy/components/dashboard/onboarding/steps/plan-step.tsx
index 4127baf4202..996b3cb8da2 100644
--- a/apps/dokploy/components/dashboard/onboarding/steps/plan-step.tsx
+++ b/apps/dokploy/components/dashboard/onboarding/steps/plan-step.tsx
@@ -58,6 +58,7 @@ export const PlanStep = ({ onNext }: Props) => {
`${"trial" | "checkout"}:${Tier}` | null
>(null);
const { data } = api.stripe.getProducts.useQuery();
+ const { data: status } = api.project.onboardingStatus.useQuery();
const { mutateAsync: createCheckoutSession } =
api.stripe.createCheckoutSession.useMutation();
const { mutateAsync: startFreeTrial } =
@@ -118,6 +119,28 @@ export const PlanStep = ({ onNext }: Props) => {
+ {status?.hasActiveAccess && (
+
+
+
+ {status.isOnTrial
+ ? `Your ${status.plan ? `${status.plan[0]!.toUpperCase()}${status.plan.slice(1)} ` : ""}trial is active`
+ : "You already have an active plan"}
+
+ {status.isOnTrial && status.trialDaysRemaining !== null && (
+
+ {status.trialDaysRemaining}{" "}
+ {status.trialDaysRemaining === 1 ? "day" : "days"} remaining
+
+ )}
+
+
+ Continue
+
+
+
+ )}
+
{PLANS.map((plan) => {
const productId =
@@ -158,24 +181,28 @@ export const PlanStep = ({ onNext }: Props) => {
))}
-
-
handleTrial(plan.tier)}
- >
- Start 7-day free trial
-
-
-
handleCheckout(plan.tier)}
- >
- Subscribe now
-
-
+ {!status?.hasActiveAccess && (
+
+ {!status?.hasUsedTrial && (
+
handleTrial(plan.tier)}
+ >
+ Start 7-day free trial
+
+
+ )}
+
handleCheckout(plan.tier)}
+ >
+ Subscribe now
+
+
+ )}
);
})}
diff --git a/apps/dokploy/components/dashboard/project/export-import/export-project.tsx b/apps/dokploy/components/dashboard/project/export-import/export-project.tsx
new file mode 100644
index 00000000000..7e1f1d6fea5
--- /dev/null
+++ b/apps/dokploy/components/dashboard/project/export-import/export-project.tsx
@@ -0,0 +1,218 @@
+import { Download } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import { Checkbox } from "@/components/ui/checkbox";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import { Label } from "@/components/ui/label";
+import { api } from "@/utils/api";
+import { isPassphraseValid, PassphraseFields } from "./passphrase-fields";
+
+type ServiceRow = { name: string } & Record;
+
+export type ProjectEnvironment = {
+ environmentId: string;
+ name: string;
+ applications: ServiceRow[];
+ compose: ServiceRow[];
+ postgres: ServiceRow[];
+ mysql: ServiceRow[];
+ mariadb: ServiceRow[];
+ mongo: ServiceRow[];
+ redis: ServiceRow[];
+ libsql: ServiceRow[];
+};
+
+const SERVICE_KINDS = [
+ ["applications", "applicationId", "application"],
+ ["compose", "composeId", "compose"],
+ ["postgres", "postgresId", "postgres"],
+ ["mysql", "mysqlId", "mysql"],
+ ["mariadb", "mariadbId", "mariadb"],
+ ["mongo", "mongoId", "mongo"],
+ ["redis", "redisId", "redis"],
+ ["libsql", "libsqlId", "libsql"],
+] as const;
+
+const servicesOf = (env: ProjectEnvironment) =>
+ SERVICE_KINDS.flatMap(([key, idField, label]) =>
+ env[key].map((service) => ({
+ id: service[idField] as string,
+ name: service.name,
+ label,
+ })),
+ ).sort((a, b) => a.name.localeCompare(b.name));
+
+const downloadFile = (filename: string, content: string) => {
+ const url = URL.createObjectURL(
+ new Blob([content], { type: "application/json" }),
+ );
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = filename;
+ link.click();
+ URL.revokeObjectURL(url);
+};
+
+interface ExportProjectProps {
+ projectId: string;
+ environments: ProjectEnvironment[];
+}
+
+export const ExportProject = ({
+ projectId,
+ environments,
+}: ExportProjectProps) => {
+ const [open, setOpen] = useState(false);
+ const [selected, setSelected] = useState>(new Set());
+ const [passphrase, setPassphrase] = useState("");
+ const [passphraseConfirm, setPassphraseConfirm] = useState("");
+ const { mutateAsync, isPending } =
+ api.projectExportImport.export.useMutation();
+
+ const allIds = environments.flatMap((env) =>
+ servicesOf(env).map((service) => service.id),
+ );
+
+ const handleOpenChange = (next: boolean) => {
+ setOpen(next);
+ if (next) {
+ setSelected(new Set(allIds));
+ setPassphrase("");
+ setPassphraseConfirm("");
+ }
+ };
+
+ const toggle = (ids: string[], checked: boolean) => {
+ const next = new Set(selected);
+ for (const id of ids) {
+ if (checked) next.add(id);
+ else next.delete(id);
+ }
+ setSelected(next);
+ };
+
+ const handleExport = async () => {
+ try {
+ const { filename, content } = await mutateAsync({
+ projectId,
+ serviceIds: [...selected],
+ passphrase,
+ });
+ downloadFile(filename, content);
+ toast.success("Project exported");
+ setOpen(false);
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : "Export failed");
+ }
+ };
+
+ return (
+
+
+ e.preventDefault()}
+ >
+
+ Export project
+
+
+
+
+ Export project
+
+ Download the configuration of the selected services as an encrypted
+ file you can import into another Dokploy instance.
+
+
+
+
+ {environments.map((env) => {
+ const services = servicesOf(env);
+ const ids = services.map((service) => service.id);
+ return (
+
+
+ 0 && ids.every((id) => selected.has(id))
+ }
+ onCheckedChange={(checked) => toggle(ids, checked === true)}
+ />
+
+ {env.name}
+
+
+ {services.map((service) => (
+
+
+ toggle([service.id], checked === true)
+ }
+ />
+
+ {service.name}
+
+ ({service.label})
+
+
+
+ ))}
+
+ );
+ })}
+
+
+
+ Environment variables and credentials are included, encrypted with the
+ passphrase. Data in volumes and databases, backups, deployments, and
+ resources shared across projects (servers, registries, git providers,
+ destinations) are not.
+
+
+
+
+
+
+ Export
+
+
+
+
+ );
+};
diff --git a/apps/dokploy/components/dashboard/project/export-import/import-project.tsx b/apps/dokploy/components/dashboard/project/export-import/import-project.tsx
new file mode 100644
index 00000000000..8d18f6e500a
--- /dev/null
+++ b/apps/dokploy/components/dashboard/project/export-import/import-project.tsx
@@ -0,0 +1,207 @@
+import { Upload } from "lucide-react";
+import { useState } from "react";
+import { toast } from "sonner";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { api, type RouterOutputs } from "@/utils/api";
+import {
+ AutofillDecoy,
+ MIN_PASSPHRASE_LENGTH,
+ PassphraseField,
+} from "./passphrase-fields";
+
+type Preview = RouterOutputs["projectExportImport"]["importPreview"];
+
+const LOCAL_SERVER = "local";
+
+export const ImportProject = () => {
+ const utils = api.useUtils();
+ const [open, setOpen] = useState(false);
+ const [bundle, setBundle] = useState(null);
+ const [passphrase, setPassphrase] = useState("");
+ const [preview, setPreview] = useState(null);
+ const [serverId, setServerId] = useState("");
+ const { data: isCloud } = api.settings.isCloud.useQuery();
+ const { data: servers } = api.server.withSSHKey.useQuery(undefined, {
+ enabled: open,
+ });
+ const previewMutation = api.projectExportImport.importPreview.useMutation();
+ const importMutation = api.projectExportImport.import.useMutation();
+
+ const reset = () => {
+ setBundle(null);
+ setPassphrase("");
+ setPreview(null);
+ setServerId(isCloud ? "" : LOCAL_SERVER);
+ };
+
+ const handleOpenChange = (next: boolean) => {
+ if (importMutation.isPending) return;
+ setOpen(next);
+ if (next) reset();
+ };
+
+ const handleFile = async (file: File | undefined) => {
+ setPreview(null);
+ setBundle(file ? await file.text() : null);
+ };
+
+ const handlePreview = async () => {
+ if (!bundle) return;
+ try {
+ const result = await previewMutation.mutateAsync({ bundle, passphrase });
+ setPreview(result);
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : "Invalid bundle");
+ }
+ };
+
+ const handleImport = async () => {
+ if (!bundle) return;
+ try {
+ const result = await importMutation.mutateAsync({
+ bundle,
+ passphrase,
+ serverId: serverId === LOCAL_SERVER ? undefined : serverId,
+ });
+ await utils.project.all.invalidate();
+ toast.success(`Imported as "${result.projectName}"`);
+ setOpen(false);
+ for (const warning of result.warnings) toast.warning(warning);
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : "Import failed");
+ }
+ };
+
+ return (
+
+
+
+
+ Import project
+
+
+
+
+ Import project
+
+ Create a new project from a file exported from another Dokploy
+ instance. Services are created but not deployed.
+
+
+
+ {!preview ? (
+
+
+ Export file
+ void handleFile(e.target.files?.[0])}
+ />
+
+
+
+
+ ) : (
+
+
+ Server
+
+
+
+
+
+ {!isCloud && (
+ Dokploy server
+ )}
+ {servers?.map((server) => (
+
+ {server.name}
+
+ ))}
+
+
+
+
+ {preview.environments.map((env) => (
+
+
{env.name}
+
+ {env.services.map((service) => (
+
+ {service.name} ({service.type})
+
+ ))}
+
+
+ ))}
+
+ {preview.warnings.length > 0 && (
+
+
+ {preview.warnings.map((warning) => (
+ {warning}
+ ))}
+
+
+ )}
+
+ )}
+
+
+ {!preview ? (
+
+ Continue
+
+ ) : (
+ <>
+ setPreview(null)}
+ >
+ Back
+
+
+ Import
+
+ >
+ )}
+
+
+
+ );
+};
diff --git a/apps/dokploy/components/dashboard/project/export-import/passphrase-fields.tsx b/apps/dokploy/components/dashboard/project/export-import/passphrase-fields.tsx
new file mode 100644
index 00000000000..ec2d5a986de
--- /dev/null
+++ b/apps/dokploy/components/dashboard/project/export-import/passphrase-fields.tsx
@@ -0,0 +1,117 @@
+import { Wand2 } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { generateRandomPassword } from "@/lib/password-utils";
+
+export const MIN_PASSPHRASE_LENGTH = 12;
+
+interface PassphraseFieldProps {
+ id: string;
+ label: string;
+ value: string;
+ onChange: (value: string) => void;
+ errorMessage?: string;
+ copyable?: boolean;
+ action?: React.ReactNode;
+}
+
+export const PassphraseField = ({
+ id,
+ label,
+ value,
+ onChange,
+ errorMessage,
+ copyable,
+ action,
+}: PassphraseFieldProps) => (
+
+
+ {label}
+ {action}
+
+
onChange(e.target.value)}
+ errorMessage={errorMessage}
+ />
+
+);
+
+interface PassphraseFieldsProps {
+ value: string;
+ confirm: string;
+ onValueChange: (value: string) => void;
+ onConfirmChange: (value: string) => void;
+}
+
+export const isPassphraseValid = (value: string, confirm: string) =>
+ value.length >= MIN_PASSPHRASE_LENGTH && value === confirm;
+
+export const PassphraseFields = ({
+ value,
+ confirm,
+ onValueChange,
+ onConfirmChange,
+}: PassphraseFieldsProps) => (
+ <>
+
+ 0 && value.length < MIN_PASSPHRASE_LENGTH
+ ? `Passphrase must be at least ${MIN_PASSPHRASE_LENGTH} characters`
+ : undefined
+ }
+ action={
+ {
+ const generated = generateRandomPassword(24);
+ onValueChange(generated);
+ onConfirmChange(generated);
+ }}
+ >
+
+ Generate
+
+ }
+ />
+ 0 && confirm !== value
+ ? "Passphrases don't match"
+ : undefined
+ }
+ />
+ >
+);
+
+export const AutofillDecoy = () => (
+
+);
diff --git a/apps/dokploy/components/dashboard/projects/show.tsx b/apps/dokploy/components/dashboard/projects/show.tsx
index bbc9e0ef0d2..a191b32c2e1 100644
--- a/apps/dokploy/components/dashboard/projects/show.tsx
+++ b/apps/dokploy/components/dashboard/projects/show.tsx
@@ -53,6 +53,8 @@ import {
} from "@/components/ui/select";
import { api } from "@/utils/api";
import { useDebounce } from "@/utils/hooks/use-debounce";
+import { ExportProject } from "../project/export-import/export-project";
+import { ImportProject } from "../project/export-import/import-project";
import { HandleProject } from "./handle-project";
import { ProjectEnvironment } from "./project-environment";
@@ -62,6 +64,7 @@ export const ShowProjects = () => {
const { data: isCloud } = api.settings.isCloud.useQuery();
const { data, isPending } = api.project.all.useQuery();
const { data: auth } = api.user.get.useQuery();
+ const canTransfer = auth?.role === "owner" || auth?.role === "admin";
const { data: permissions } = api.user.getPermissions.useQuery();
const { mutateAsync } = api.project.remove.useMutation();
const { data: availableTags } = api.tag.all.useQuery();
@@ -217,7 +220,8 @@ export const ShowProjects = () => {
{permissions?.project.create && (
-
+
+ {canTransfer && }
)}
@@ -237,6 +241,7 @@ export const ShowProjects = () => {
placeholder="Filter projects..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
+ autoComplete="off"
className="pr-10"
/>
@@ -414,6 +419,18 @@ export const ShowProjects = () => {
projectId={project.projectId}
/>
+ e.stopPropagation()}
+ >
+ {canTransfer && (
+
+ )}
+
e.stopPropagation()}
diff --git a/apps/dokploy/components/dashboard/settings/api/add-api-key.tsx b/apps/dokploy/components/dashboard/settings/api/add-api-key.tsx
index 9a894d13988..45f15b1691c 100644
--- a/apps/dokploy/components/dashboard/settings/api/add-api-key.tsx
+++ b/apps/dokploy/components/dashboard/settings/api/add-api-key.tsx
@@ -117,6 +117,7 @@ export const AddApiKey = () => {
});
const rateLimitEnabled = form.watch("rateLimitEnabled");
+ const { data: isCloud } = api.settings.isCloud.useQuery();
const onSubmit = async (values: FormValues) => {
createApiKey.mutate({
@@ -241,97 +242,106 @@ export const AddApiKey = () => {
/>
{/* Rate Limiting Section */}
-
-
Rate Limiting
-
(
-
-
- Enable Rate Limiting
-
- Limit the number of requests within a time window
-
-
-
-
-
-
- )}
- />
-
- {rateLimitEnabled && (
- <>
- (
-
- Time Window
-
- field.onChange(Number.parseInt(value, 10))
- }
- >
-
-
-
-
-
-
- {TIME_WINDOW_OPTIONS.map((option) => (
-
- {option.label}
-
- ))}
-
-
+ {isCloud ? (
+
+
Rate Limiting
+
+ API keys are limited to 300 requests per minute.
+
+
+ ) : (
+
+
Rate Limiting
+
(
+
+
+ Enable Rate Limiting
- The duration in which requests are counted
+ Limit the number of requests within a time window
-
-
- )}
- />
- (
-
- Maximum Requests
-
-
- field.onChange(
- e.target.value
- ? Number.parseInt(e.target.value, 10)
- : null,
- )
+
+
+
+
+
+ )}
+ />
+
+ {rateLimitEnabled && (
+ <>
+ (
+
+ Time Window
+
+ field.onChange(Number.parseInt(value, 10))
}
- />
-
-
- Maximum number of requests allowed within the time
- window
-
-
-
- )}
- />
- >
- )}
-
+ >
+
+
+
+
+
+
+ {TIME_WINDOW_OPTIONS.map((option) => (
+
+ {option.label}
+
+ ))}
+
+
+
+ The duration in which requests are counted
+
+
+
+ )}
+ />
+ (
+
+ Maximum Requests
+
+
+ field.onChange(
+ e.target.value
+ ? Number.parseInt(e.target.value, 10)
+ : null,
+ )
+ }
+ />
+
+
+ Maximum number of requests allowed within the time
+ window
+
+
+
+ )}
+ />
+ >
+ )}
+
+ )}
{/* Request Limiting Section */}
diff --git a/apps/dokploy/components/dashboard/settings/git/gitea/add-gitea-provider.tsx b/apps/dokploy/components/dashboard/settings/git/gitea/add-gitea-provider.tsx
index b61cdbe6d3f..0f89e3af3de 100644
--- a/apps/dokploy/components/dashboard/settings/git/gitea/add-gitea-provider.tsx
+++ b/apps/dokploy/components/dashboard/settings/git/gitea/add-gitea-provider.tsx
@@ -116,22 +116,7 @@ export const AddGiteaProvider = () => {
return;
}
- // Generate OAuth URL using the shared utility
- const authUrl = getGiteaOAuthUrl(
- result.giteaId,
- data.clientId,
- data.giteaUrl,
- baseUrl,
- );
-
- // Open the Gitea OAuth URL
- if (authUrl !== "#") {
- window.open(authUrl, "_blank");
- } else {
- toast.error("Configuration Incomplete", {
- description: "Please fill in Client ID and Gitea URL first.",
- });
- }
+ window.open(getGiteaOAuthUrl(result.giteaId), "_blank");
toast.success("Gitea provider created successfully");
setIsOpen(false);
diff --git a/apps/dokploy/components/dashboard/settings/git/gitea/edit-gitea-provider.tsx b/apps/dokploy/components/dashboard/settings/git/gitea/edit-gitea-provider.tsx
index bc3f38ed986..b09f0b094a4 100644
--- a/apps/dokploy/components/dashboard/settings/git/gitea/edit-gitea-provider.tsx
+++ b/apps/dokploy/components/dashboard/settings/git/gitea/edit-gitea-provider.tsx
@@ -149,26 +149,15 @@ export const EditGiteaProvider = ({ giteaId }: Props) => {
description: result,
});
} catch (error: any) {
- const formValues = form.getValues();
- const authUrl =
- error.authorizationUrl ||
- getGiteaOAuthUrl(
- giteaId,
- formValues.clientId,
- formValues.giteaUrl,
- typeof url === "string" ? url : (url as any).url || "",
- );
+ const authUrl = getGiteaOAuthUrl(giteaId);
toast.error("Gitea Not Connected", {
description:
error.message || "Please complete the OAuth authorization process.",
- action:
- authUrl && authUrl !== "#"
- ? {
- label: "Authorize Now",
- onClick: () => window.open(authUrl, "_blank"),
- }
- : undefined,
+ action: {
+ label: "Authorize Now",
+ onClick: () => window.open(authUrl, "_blank"),
+ },
});
}
};
@@ -323,18 +312,7 @@ export const EditGiteaProvider = ({ giteaId }: Props) => {
{
- const formValues = form.getValues();
- const authUrl = getGiteaOAuthUrl(
- giteaId,
- formValues.clientId,
- formValues.giteaUrl,
- typeof url === "string" ? url : (url as any).url || "",
- );
- if (authUrl !== "#") {
- window.open(authUrl, "_blank");
- }
- }}
+ onClick={() => window.open(getGiteaOAuthUrl(giteaId), "_blank")}
>
Connect to Gitea
diff --git a/apps/dokploy/components/dashboard/settings/git/show-git-providers.tsx b/apps/dokploy/components/dashboard/settings/git/show-git-providers.tsx
index 0798731edf7..48033f0c023 100644
--- a/apps/dokploy/components/dashboard/settings/git/show-git-providers.tsx
+++ b/apps/dokploy/components/dashboard/settings/git/show-git-providers.tsx
@@ -34,7 +34,6 @@ import {
} from "@/components/ui/tooltip";
import { api } from "@/utils/api";
import { DEFAULT_GITHUB_URL } from "@/utils/github-utils";
-import { useUrl } from "@/utils/hooks/use-url";
import { AddBitbucketProvider } from "./bitbucket/add-bitbucket-provider";
import { EditBitbucketProvider } from "./bitbucket/edit-bitbucket-provider";
import { AddGiteaProvider } from "./gitea/add-gitea-provider";
@@ -96,12 +95,11 @@ export const ShowGitProviders = () => {
api.gitProvider.toggleShare.useMutation();
const { data: currentMember } = api.user.get.useQuery();
const { data: permissions } = api.user.getPermissions.useQuery();
- const url = useUrl();
const isOrgAdmin =
currentMember?.role === "owner" || currentMember?.role === "admin";
const getGitlabUrl = (gitlabId: string) =>
- `${url}/api/providers/gitlab/authorize?gitlabId=${encodeURIComponent(gitlabId)}`;
+ `/api/providers/gitlab/authorize?gitlabId=${encodeURIComponent(gitlabId)}`;
return (
diff --git a/apps/dokploy/components/dashboard/settings/profile/profile-form.tsx b/apps/dokploy/components/dashboard/settings/profile/profile-form.tsx
index 1bcfbdd3e9d..7b3d5005df5 100644
--- a/apps/dokploy/components/dashboard/settings/profile/profile-form.tsx
+++ b/apps/dokploy/components/dashboard/settings/profile/profile-form.tsx
@@ -44,7 +44,12 @@ const profileSchema = z.object({
.trim()
.email("Please enter a valid email address")
.min(1, "Email is required"),
- password: z.string().nullable(),
+ password: z
+ .string()
+ .nullable()
+ .refine((val) => !val || val.length >= 8, {
+ message: "Password must be at least 8 characters",
+ }),
currentPassword: z.string().nullable(),
image: z.string().optional(),
firstName: z.string().optional(),
diff --git a/apps/dokploy/components/dashboard/settings/servers/connect-server.tsx b/apps/dokploy/components/dashboard/settings/servers/connect-server.tsx
new file mode 100644
index 00000000000..3691ce50656
--- /dev/null
+++ b/apps/dokploy/components/dashboard/settings/servers/connect-server.tsx
@@ -0,0 +1,315 @@
+import { standardSchemaResolver as zodResolver } from "@hookform/resolvers/standard-schema";
+import copy from "copy-to-clipboard";
+import { CheckCircle2, CopyIcon, Loader2, Settings } from "lucide-react";
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { useForm } from "react-hook-form";
+import { toast } from "sonner";
+import { z } from "zod";
+import { AlertBlock } from "@/components/shared/alert-block";
+import { Button } from "@/components/ui/button";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Switch } from "@/components/ui/switch";
+import { Textarea } from "@/components/ui/textarea";
+import { api } from "@/utils/api";
+
+const Schema = z.object({
+ name: z.string().trim().min(1, { message: "Name is required" }).max(100),
+ description: z.string().max(200).optional(),
+ serverType: z.enum(["deploy", "build"]).default("deploy"),
+ enableDockerCleanup: z.boolean().default(true),
+});
+
+type Schema = z.infer
;
+
+type PendingCommand = { sshKeyId: string; command: string; expiresAt: number };
+
+const isExpired = (pending: PendingCommand | null) =>
+ !!pending && Date.now() > pending.expiresAt * 1000;
+
+// Lives in HandleServers, not in the dialog, so closing the dialog while the
+// command runs keeps polling and keeps the command.
+export const useConnectServer = () => {
+ const utils = api.useUtils();
+ const [pending, setPending] = useState(null);
+ const { data: connected } = api.server.connectStatus.useQuery(
+ { sshKeyId: pending?.sshKeyId ?? "" },
+ {
+ enabled: !!pending,
+ refetchInterval: (query) =>
+ query.state.data || isExpired(pending) ? false : 3000,
+ },
+ );
+
+ useEffect(() => {
+ if (connected) {
+ toast.success("Server connected");
+ utils.server.all.invalidate();
+ utils.stripe.canCreateMoreServers.invalidate();
+ utils.sshKey.all.invalidate();
+ }
+ }, [connected, utils]);
+
+ return { pending, setPending, connected };
+};
+
+interface Props {
+ session: ReturnType;
+ onCompleteSetup: (serverId: string) => void;
+ onClose: () => void;
+}
+
+export const ConnectServer = ({ session, onCompleteSetup, onClose }: Props) => {
+ const { pending, setPending, connected } = session;
+ const { data: canCreateMoreServers } =
+ api.stripe.canCreateMoreServers.useQuery();
+ const { mutateAsync, isPending, error, isError } =
+ api.server.generateConnectCommand.useMutation();
+
+ const form = useForm({
+ defaultValues: {
+ name: "",
+ description: "",
+ serverType: "deploy",
+ enableDockerCleanup: true,
+ },
+ resolver: zodResolver(Schema),
+ });
+
+ const onSubmit = async (data: Schema) => {
+ const result = await mutateAsync({
+ name: data.name,
+ description: data.description || undefined,
+ serverType: data.serverType,
+ enableDockerCleanup: data.enableDockerCleanup,
+ }).catch(() => null);
+ if (!result) return;
+ setPending({
+ sshKeyId: result.sshKeyId,
+ expiresAt: result.expiresAt,
+ command: `curl -fsSL ${window.location.origin}/api/connect/${result.token} | sudo bash`,
+ });
+ };
+
+ if (pending && connected) {
+ return (
+
+
+
+
+
+ {connected.name} is connected ({connected.ipAddress})
+
+
+ Complete the setup to install Docker, Traefik and the rest of the
+ server requirements. If the IP address is not right, fix it with
+ Edit Server first.
+
+
+
+
+ {
+ setPending(null);
+ onClose();
+ }}
+ >
+ Close
+
+ {
+ setPending(null);
+ onCompleteSetup(connected.serverId);
+ }}
+ >
+ Complete setup
+
+
+
+ );
+ }
+
+ if (pending) {
+ return (
+
+
+
+ Run this command on your server as root. It adds Dokploy's SSH
+ key and registers the server. It works once and expires in 1 hour.
+
+
+ {pending.command}
+ {
+ copy(pending.command);
+ toast.success("Copied to clipboard");
+ }}
+ >
+
+
+
+
+ {isExpired(pending) ? (
+
+ This command expired. Start over to generate a new one.
+
+ ) : (
+
+
+
+ Waiting for your server…
+
+ This updates by itself when the command runs.
+
+
+
+ )}
+
setPending(null)}
+ >
+ Start over
+
+
+ );
+ }
+
+ return (
+
+
+ );
+};
diff --git a/apps/dokploy/components/dashboard/settings/servers/handle-servers.tsx b/apps/dokploy/components/dashboard/settings/servers/handle-servers.tsx
index 10518fc5606..4b5098f282f 100644
--- a/apps/dokploy/components/dashboard/settings/servers/handle-servers.tsx
+++ b/apps/dokploy/components/dashboard/settings/servers/handle-servers.tsx
@@ -37,8 +37,11 @@ import {
SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { api } from "@/utils/api";
+import { ConnectServer, useConnectServer } from "./connect-server";
+import { SetupServer } from "./setup-server";
const Schema = z.object({
name: z.string().min(1, {
@@ -67,6 +70,8 @@ interface Props {
export const HandleServers = ({ serverId, children }: Props) => {
const utils = api.useUtils();
const [isOpen, setIsOpen] = useState(false);
+ const [setupServerId, setSetupServerId] = useState(null);
+ const connectSession = useConnectServer();
const { data: canCreateMoreServers, refetch } =
api.stripe.canCreateMoreServers.useQuery();
@@ -139,323 +144,367 @@ export const HandleServers = ({ serverId, children }: Props) => {
});
};
- return (
-
- {children ? (
- {children}
- ) : serverId ? (
-
- {
- e.preventDefault();
- }}
- >
- Edit Server
-
-
- ) : (
-
-
-
- Create Server
-
-
+ const manualForm = (
+ <>
+ {!canCreateMoreServers && (
+
+ You cannot create more servers,{" "}
+
+ Please upgrade your plan
+
+
)}
- e.preventDefault()}
- >
-
- {serverId ? "Edit" : "Create"} Server
-
- {serverId ? "Edit" : "Create"} a server to deploy your applications
- remotely.
-
-
-
-
- You may need to purchase or rent a Virtual Private Server (VPS) to
- proceed. We recommend using one of these heavily tested providers:
-
-
-
- You are free to use whatever provider, but we recommend to use one
- of the above, to avoid issues.
-
-
- {!canCreateMoreServers && (
-
- You cannot create more servers,{" "}
-
- Please upgrade your plan
-
-
- )}
- {isError && {error?.message} }
-
-
-
- (
-
- Name
-
-
-
-
-
-
- )}
- />
-
+ {isError && {error?.message} }
+
+
+
+ (
+
+ Description
+
+
+
+
+
+
+ )}
+ />
+ {
+ const serverTypeValue = form.watch("serverType");
+ return (
- Select a SSH Key
+ Server Type
-
+
- {sshKeys?.map((sshKey) => (
-
- {sshKey.name}
-
- ))}
-
- Registries ({sshKeys?.length})
-
+ Deploy Server
+ Build Server
+ Server Type
+ {serverTypeValue === "deploy" && (
+
+ Deploy servers are used to run your applications,
+ databases, and services. They handle the deployment and
+ execution of your projects.
+
+ )}
+ {serverTypeValue === "build" && (
+
+ Build servers are dedicated to building your applications.
+ They handle the compilation and build process, offloading
+ this work from your deployment servers. Build servers
+ won't appear in deployment options.
+
+ )}
- )}
- />
-
- (
-
- IP Address
-
-
-
-
-
-
- )}
- />
- (
-
- Port
-
- {
- const value = e.target.value;
- if (value === "") {
- field.onChange(0);
- } else {
- const number = Number.parseInt(value, 10);
- if (!Number.isNaN(number)) {
- field.onChange(number);
- }
- }
- }}
- />
-
-
-
-
- )}
- />
-
-
+ );
+ }}
+ />
+ (
+
+ Select a SSH Key
+
+
+
+
+
+
+ {sshKeys?.map((sshKey) => (
+
+ {sshKey.name}
+
+ ))}
+ Registries ({sshKeys?.length})
+
+
+
+
+
+ )}
+ />
+
-
- (
+
+ Username
+
+
+
+
+ Use "root" or a non-root user with passwordless sudo
+ access.
+
+
+
+ )}
+ />
+ (
+
+
+ Enable Docker Cleanup
+
+ Automatically prune unused Docker images daily. Keeps disk
+ usage in check on this remote server.
+
+
+
+
+
+
+ )}
+ />
+
+
+
+
+ {serverId ? "Update" : "Create"}
+
+
+
+ >
+ );
+
+ return (
+ <>
+
+ {children ? (
+ {children}
+ ) : serverId ? (
+
+ {
+ e.preventDefault();
+ }}
>
- {serverId ? "Update" : "Create"}
+ Edit Server
+
+
+ ) : (
+
+
+
+ Create Server
-
-
-
-
+
+ )}
+ e.preventDefault()}
+ >
+
+ {serverId ? "Edit" : "Create"} Server
+
+ {serverId ? "Edit" : "Create"} a server to deploy your
+ applications remotely.
+
+
+
+
+ You may need to purchase or rent a Virtual Private Server (VPS) to
+ proceed. We recommend using one of these heavily tested providers:
+
+
+
+ You are free to use whatever provider, but we recommend to use one
+ of the above, to avoid issues.
+
+
+ {serverId ? (
+ manualForm
+ ) : (
+
+
+ Run a command
+ Manual (SSH)
+
+
+ setIsOpen(false)}
+ onCompleteSetup={(id) => {
+ setIsOpen(false);
+ setSetupServerId(id);
+ }}
+ />
+
+
+ {manualForm}
+
+
+ )}
+
+
+ {setupServerId && (
+ {
+ if (!open) {
+ setSetupServerId(null);
+ utils.server.all.invalidate();
+ }
+ }}
+ />
+ )}
+ >
);
};
diff --git a/apps/dokploy/components/dashboard/settings/servers/setup-server.tsx b/apps/dokploy/components/dashboard/settings/servers/setup-server.tsx
index 4576b9db9b0..027459f1046 100644
--- a/apps/dokploy/components/dashboard/settings/servers/setup-server.tsx
+++ b/apps/dokploy/components/dashboard/settings/servers/setup-server.tsx
@@ -39,10 +39,21 @@ import { ValidateServer } from "./validate-server";
interface Props {
serverId: string;
children?: React.ReactNode;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
+ defaultTab?: string;
}
-export const SetupServer = ({ serverId, children }: Props) => {
- const [isOpen, setIsOpen] = useState(false);
+export const SetupServer = ({
+ serverId,
+ children,
+ open,
+ onOpenChange,
+ defaultTab = "ssh-keys",
+}: Props) => {
+ const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
+ const isOpen = open ?? uncontrolledOpen;
+ const setIsOpen = onOpenChange ?? setUncontrolledOpen;
const { data: server } = api.server.one.useQuery(
{
serverId,
@@ -92,7 +103,7 @@ export const SetupServer = ({ serverId, children }: Props) => {
return (
- {children ? (
+ {open !== undefined ? null : children ? (
{children}
) : (
@@ -130,7 +141,7 @@ export const SetupServer = ({ serverId, children }: Props) => {
configured.
-
+
{
const router = useRouter();
const query = router.query;
const { data, refetch, isPending } = api.server.all.useQuery();
- const { data: sshKeys } = api.sshKey.all.useQuery();
const { data: isCloud } = api.settings.isCloud.useQuery();
const { data: canCreateMoreServers } =
api.stripe.canCreateMoreServers.useQuery();
@@ -138,349 +136,322 @@ export const ShowServers = () => {
) : (
- <>
- {sshKeys?.length === 0 && data?.length === 0 ? (
-
-
+
+ {data?.length === 0 ? (
+ <>
+
- No SSH Keys found. Add a SSH Key to start adding servers.{" "}
-
- Add SSH Key
-
+ Start adding servers to deploy your applications remotely.
-
+ >
) : (
- <>
- {data?.length === 0 ? (
-
-
-
- Start adding servers to deploy your applications
- remotely.
-
- {permissions?.server.create && }
-
- ) : (
-
-
- {data?.map((server) => {
- const isActive = server.serverStatus === "active";
- const isBuildServer = server.serverType === "build";
- return (
-
-
-
-
-
-
- {server.name}
-
-
-
-
-
-
- {isCloud && (
- <>
- {server.serverStatus === "active" ? (
-
+
+ {data?.map((server) => {
+ const isActive = server.serverStatus === "active";
+ const isBuildServer = server.serverType === "build";
+ return (
+
+
+
+
+
+
+ {server.name}
+
+
+
+
+
+
+ {isCloud && (
+ <>
+ {server.serverStatus === "active" ? (
+
+ {server.serverStatus}
+
+ ) : (
+
+
+
+
{server.serverStatus}
- ) : (
-
-
-
-
- {server.serverStatus}
-
-
-
-
-
- This server is deactivated due
- to lack of payment. Please pay
- your invoice to reactivate it.
- If you think this is an error,
- please contact support.
-
-
-
- )}
- >
- )}
-
- {server.serverType}
-
-
-
-
-
-
-
-
- IP:
-
-
- {server.ipAddress}
-
-
- Port:
-
-
- {server.port}
-
-
-
-
-
- User:
-
-
- {server.username}
-
-
-
-
-
- SSH Key:
-
-
- {server.sshKeyId ? "Yes" : "No"}
-
-
-
-
-
- Created{" "}
- {format(
- new Date(server.createdAt),
- "PPp",
- )}
-
-
-
- {/* Compact Actions */}
- {isActive && (
-
-
-
-
-
-
- Setup Server{" "}
-
-
-
-
-
-
-
- Setup Server
-
-
- Configure and initialize your
- server with Docker, Traefik, and
- other essential services
-
-
-
-
-
+
+
+
+
+ This server is deactivated due to
+ lack of payment. Please pay your
+ invoice to reactivate it. If you
+ think this is an error, please
+ contact support.
+
+
+
+ )}
+ >
+ )}
+
+ {server.serverType}
+
+
+
+
+
+
+
+ IP:
+
+ {server.ipAddress}
+
+
+ Port:
+
+ {server.port}
+
+
+
+
+ User:
+
+
+ {server.username}
+
+
+
+
+
+ SSH Key:
+
+
+ {server.sshKeyId ? "Yes" : "No"}
+
+
+
+
+
+ Created{" "}
+ {format(new Date(server.createdAt), "PPp")}
+
+
-
-
+ {/* Compact Actions */}
+ {isActive && (
+
+
+
+
+
+
+ Setup Server{" "}
+
+
+
+
+
+
+
+ Setup Server
+
+
+ Configure and initialize your server
+ with Docker, Traefik, and other
+ essential services
+
+
+
+
-
- {server.sshKeyId &&
- permissions?.server.terminal && (
-
-
-
-
-
-
-
-
-
- Terminal
-
-
- )}
-
- {server.sshKeyId &&
- permissions?.server.read && (
-
-
-
-
-
-
-
-
-
- Security
-
-
- )}
+
+
+
- {permissions?.server.update && (
-
-
+ {server.sshKeyId &&
+ permissions?.server.terminal && (
+
+
+
+
-
-
-
-
-
-
-
- Edit Server
-
-
- )}
+
+
+
+
+
+ Terminal
+
+
+ )}
- {server.sshKeyId && !isBuildServer && (
-
-
+
+
+
-
-
-
-
-
-
-
- Web Server Actions
-
-
- )}
+
+
+
+
+
+ Security
+
+
+ )}
- {isCloud &&
- server.sshKeyId &&
- !isBuildServer && (
-
-
-
-
-
-
-
-
-
- Monitoring
-
-
- )}
+ {permissions?.server.update && (
+
+
+
+
+
+
+
+
+
+ Edit Server
+
+
+ )}
-
+ {server.sshKeyId && !isBuildServer && (
+
+
+
+
+
+
+
+
+
+ Web Server Actions
+
+
+ )}
- {permissions?.server.delete && (
-
-
+
+
+
-
-
-
-
-
-
-
- Delete Server
-
-
- )}
-
-
- )}
-
-
- );
- })}
-
+
+
+
+
+
+ Monitoring
+
+
+ )}
- {permissions?.server.create && (
-
- {data && data?.length > 0 && (
-
-
+
+
+ {permissions?.server.delete && (
+
+
+
+
+
+
+
+
+
+ Delete Server
+
+
+ )}
+
)}
-
- )}
-
- )}
- >
+
+
+ );
+ })}
+
)}
- >
+ {/* Same tree position in both states so the open dialog survives the first server appearing. */}
+ {permissions?.server.create && (
+
+
+
+ )}
+
)}
diff --git a/apps/dokploy/components/dashboard/settings/ssh-keys/handle-ssh-keys.tsx b/apps/dokploy/components/dashboard/settings/ssh-keys/handle-ssh-keys.tsx
index 68e7d764ee1..849086cb24f 100644
--- a/apps/dokploy/components/dashboard/settings/ssh-keys/handle-ssh-keys.tsx
+++ b/apps/dokploy/components/dashboard/settings/ssh-keys/handle-ssh-keys.tsx
@@ -25,7 +25,11 @@ import {
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
-import { sshKeyCreate, type sshKeyType } from "@/server/db/validations";
+import {
+ sshKeyCreate,
+ type sshKeyType,
+ sshKeyUpdate,
+} from "@/server/db/validations";
import { api } from "@/utils/api";
type SSHKey = z.infer
;
@@ -55,7 +59,9 @@ export const HandleSSHKeys = ({ sshKeyId }: Props) => {
const generateMutation = api.sshKey.generate.useMutation();
const form = useForm({
- resolver: zodResolver(sshKeyCreate),
+ resolver: zodResolver(
+ (sshKeyId ? sshKeyUpdate : sshKeyCreate) as typeof sshKeyCreate,
+ ),
defaultValues: {
name: "",
description: "",
diff --git a/apps/dokploy/components/dashboard/settings/web-server/terminal.tsx b/apps/dokploy/components/dashboard/settings/web-server/terminal.tsx
index 429066cf688..8ddcd0b4500 100644
--- a/apps/dokploy/components/dashboard/settings/web-server/terminal.tsx
+++ b/apps/dokploy/components/dashboard/settings/web-server/terminal.tsx
@@ -16,74 +16,79 @@ interface Props {
export const Terminal: React.FC = ({ id, serverId }) => {
const termRef = useRef(null);
- const initialized = useRef(false);
const { resolvedTheme } = useTheme();
useEffect(() => {
- if (initialized.current) {
- // Required in strict mode to avoid issues due to double wss connection
- return;
- }
+ let cancelled = false;
+ let term: XTerm | null = null;
+ let ws: WebSocket | null = null;
+ let resizeObserver: ResizeObserver | null = null;
- initialized.current = true;
- const container = document.getElementById(id);
- if (container) {
- container.innerHTML = "";
- }
- const term = new XTerm({
- cursorBlink: true,
- lineHeight: 1.4,
- convertEol: true,
- theme: {
- cursor: resolvedTheme === "light" ? "#000000" : "transparent",
- background: "rgba(0, 0, 0, 0)",
- foreground: "currentColor",
- },
- });
+ const frame = requestAnimationFrame(() => {
+ if (cancelled) return;
- const addonFit = new FitAddon();
- const clipboardAddon = new ClipboardAddon();
- term.loadAddon(clipboardAddon);
- attachTerminalKeyHandlers(term);
+ const container = document.getElementById(id);
+ if (container) {
+ container.innerHTML = "";
+ }
+ term = new XTerm({
+ cursorBlink: true,
+ lineHeight: 1.4,
+ convertEol: true,
+ theme: {
+ cursor: resolvedTheme === "light" ? "#000000" : "transparent",
+ background: "rgba(0, 0, 0, 0)",
+ foreground: "currentColor",
+ },
+ });
- // @ts-expect-error
- term.open(termRef.current);
- term.loadAddon(addonFit);
- addonFit.fit();
+ const addonFit = new FitAddon();
+ const clipboardAddon = new ClipboardAddon();
+ term.loadAddon(clipboardAddon);
+ attachTerminalKeyHandlers(term);
- const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
+ // @ts-expect-error
+ term.open(termRef.current);
+ term.loadAddon(addonFit);
+ addonFit.fit();
- const urlParams = new URLSearchParams();
- urlParams.set("serverId", serverId);
- urlParams.set("cols", term.cols.toString());
- urlParams.set("rows", term.rows.toString());
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
- if (serverId === "local") {
- const { port, username } = getLocalServerData();
- urlParams.set("port", port.toString());
- urlParams.set("username", username);
- }
+ const urlParams = new URLSearchParams();
+ urlParams.set("serverId", serverId);
+ urlParams.set("cols", term.cols.toString());
+ urlParams.set("rows", term.rows.toString());
- const wsUrl = `${protocol}//${window.location.host}/terminal?${urlParams}`;
+ if (serverId === "local") {
+ const { port, username } = getLocalServerData();
+ urlParams.set("port", port.toString());
+ urlParams.set("username", username);
+ }
- const ws = new WebSocket(wsUrl);
- const addonAttach = new AttachAddon(ws);
- term.loadAddon(addonAttach);
+ const wsUrl = `${protocol}//${window.location.host}/terminal?${urlParams}`;
- const sendResize = (cols: number, rows: number) => {
- if (ws.readyState === WebSocket.OPEN) {
- ws.send(JSON.stringify({ type: "resize", cols, rows }));
- }
- };
- term.onResize(({ cols, rows }) => sendResize(cols, rows));
+ ws = new WebSocket(wsUrl);
+ const addonAttach = new AttachAddon(ws);
+ term.loadAddon(addonAttach);
+
+ const sendResize = (cols: number, rows: number) => {
+ if (ws && ws.readyState === WebSocket.OPEN) {
+ ws.send(JSON.stringify({ type: "resize", cols, rows }));
+ }
+ };
+ term.onResize(({ cols, rows }) => sendResize(cols, rows));
- const resizeObserver = new ResizeObserver(() => addonFit.fit());
- if (termRef.current) {
- resizeObserver.observe(termRef.current);
- }
+ resizeObserver = new ResizeObserver(() => addonFit.fit());
+ if (termRef.current) {
+ resizeObserver.observe(termRef.current);
+ }
+ });
return () => {
- resizeObserver.disconnect();
- ws.readyState === WebSocket.OPEN && ws.close();
+ cancelled = true;
+ cancelAnimationFrame(frame);
+ resizeObserver?.disconnect();
+ ws?.close();
+ term?.dispose();
};
}, [id, serverId]);
diff --git a/apps/dokploy/package.json b/apps/dokploy/package.json
index 47642594e9b..cf79db58a5b 100644
--- a/apps/dokploy/package.json
+++ b/apps/dokploy/package.json
@@ -1,6 +1,6 @@
{
"name": "dokploy",
- "version": "v0.31.0",
+ "version": "v0.31.2",
"private": true,
"license": "Apache-2.0",
"type": "module",
diff --git a/apps/dokploy/pages/_document.tsx b/apps/dokploy/pages/_document.tsx
index 5e6b6948be3..096070fb804 100644
--- a/apps/dokploy/pages/_document.tsx
+++ b/apps/dokploy/pages/_document.tsx
@@ -127,9 +127,9 @@ Document.getInitialProps = async (
appName = config.appName;
appDescription = config.appDescription;
ogImageUrl = config.ogImageUrl;
- // Remove any tags to prevent XSS breakout
+ // A raw "<" could close the