diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 6c74dbc028..31dbc48fba 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -20,6 +20,32 @@ jobs: with: node-version: 20.16.0 cache: "pnpm" + + - name: Install Nixpacks + if: matrix.job == 'test' + run: | + export NIXPACKS_VERSION=1.39.0 + curl -sSL https://nixpacks.com/install.sh | bash + echo "Nixpacks installed $NIXPACKS_VERSION" + + - name: Install Railpack + if: matrix.job == 'test' + run: | + export RAILPACK_VERSION=0.15.0 + curl -sSL https://railpack.com/install.sh | bash + echo "Railpack installed $RAILPACK_VERSION" + + - name: Add build tools to PATH + if: matrix.job == 'test' + run: echo "$HOME/.local/bin" >> $GITHUB_PATH + + - name: Initialize Docker Swarm + if: matrix.job == 'test' + run: | + docker swarm init + docker network create --driver overlay dokploy-network || true + echo "✅ Docker Swarm initialized" + - run: pnpm install --frozen-lockfile - run: pnpm server:build - run: pnpm ${{ matrix.job }} diff --git a/.github/workflows/sync-openapi-docs.yml b/.github/workflows/sync-openapi-docs.yml new file mode 100644 index 0000000000..ddc51355a2 --- /dev/null +++ b/.github/workflows/sync-openapi-docs.yml @@ -0,0 +1,70 @@ +name: Generate and Sync OpenAPI + +on: + push: + branches: + - canary + - main + paths: + - 'apps/dokploy/server/api/routers/**' + - 'packages/server/src/services/**' + - 'packages/server/src/db/schema/**' + + workflow_dispatch: + +jobs: + generate-and-commit: + name: Generate OpenAPI and commit to Dokploy repo + runs-on: ubuntu-latest + steps: + - name: Checkout Dokploy repository + uses: actions/checkout@v4 + with: + token: ${{ secrets.GITHUB_TOKEN }} + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20.16.0 + cache: "pnpm" + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Generate OpenAPI specification + run: | + pnpm generate:openapi + + # Verifica que se generó correctamente + if [ ! -f openapi.json ]; then + echo "❌ openapi.json not found" + exit 1 + fi + + echo "✅ OpenAPI specification generated successfully" + + - name: Sync to website repository + run: | + # Clona el repositorio de website + git clone https://x-access-token:${{ secrets.DOCS_SYNC_TOKEN }}@github.com/dokploy/website.git website-repo + + cd website-repo + + # Copia el openapi.json al website (sobrescribe) + mkdir -p apps/docs/public + cp -f ../openapi.json apps/docs/public/openapi.json + + # Configura git + git config user.name "Dokploy Bot" + git config user.email "bot@dokploy.com" + + # Agrega y commitea siempre + git add apps/docs/public/openapi.json + git commit -m "chore: sync OpenAPI specification [skip ci]" \ + -m "Source: ${{ github.repository }}@${{ github.sha }}" \ + -m "Updated: $(date -u +'%Y-%m-%d %H:%M:%S UTC')" \ + --allow-empty + + git push + + echo "✅ OpenAPI synced to website successfully" + diff --git a/.gitignore b/.gitignore index 5e6e4eb3c5..d531bab015 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,8 @@ node_modules .env.test.local .env.production.local +openapi.json + # Testing coverage diff --git a/Dockerfile.cloud b/Dockerfile.cloud index 8e4bac2159..ee42cd2bd2 100644 --- a/Dockerfile.cloud +++ b/Dockerfile.cloud @@ -16,11 +16,11 @@ RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm --filter=@dokploy/server # Deploy only the dokploy app -ARG NEXT_PUBLIC_UMAMI_HOST -ENV NEXT_PUBLIC_UMAMI_HOST=$NEXT_PUBLIC_UMAMI_HOST +# ARG NEXT_PUBLIC_UMAMI_HOST +# ENV NEXT_PUBLIC_UMAMI_HOST=$NEXT_PUBLIC_UMAMI_HOST -ARG NEXT_PUBLIC_UMAMI_WEBSITE_ID -ENV NEXT_PUBLIC_UMAMI_WEBSITE_ID=$NEXT_PUBLIC_UMAMI_WEBSITE_ID +# ARG NEXT_PUBLIC_UMAMI_WEBSITE_ID +# ENV NEXT_PUBLIC_UMAMI_WEBSITE_ID=$NEXT_PUBLIC_UMAMI_WEBSITE_ID ARG NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ENV NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=$NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY diff --git a/apps/dokploy/__test__/compose/domain/host-rule-format.test.ts b/apps/dokploy/__test__/compose/domain/host-rule-format.test.ts new file mode 100644 index 0000000000..27e696b207 --- /dev/null +++ b/apps/dokploy/__test__/compose/domain/host-rule-format.test.ts @@ -0,0 +1,215 @@ +import type { Domain } from "@dokploy/server"; +import { createDomainLabels } from "@dokploy/server"; +import { parse, stringify } from "yaml"; +import { describe, expect, it } from "vitest"; + +/** + * Regression tests for Traefik Host rule label format. + * + * These tests verify that the Host rule is generated with the correct format: + * - Host(`domain.com`) - with opening and closing parentheses + * - Host(`domain.com`) && PathPrefix(`/path`) - for path-based routing + * + * Issue: https://github.com/Dokploy/dokploy/issues/3161 + * The bug caused Host rules to be malformed as Host`domain.com`) + * (missing opening parenthesis) which broke all domain routing. + */ +describe("Host rule format regression tests", () => { + const baseDomain: Domain = { + host: "example.com", + port: 8080, + https: false, + uniqueConfigKey: 1, + customCertResolver: null, + certificateType: "none", + applicationId: "", + composeId: "", + domainType: "compose", + serviceName: "test-app", + domainId: "", + path: "/", + createdAt: "", + previewDeploymentId: "", + internalPath: "/", + stripPath: false, + }; + + describe("Host rule format validation", () => { + it("should generate Host rule with correct parentheses format", async () => { + const labels = await createDomainLabels("test-app", baseDomain, "web"); + const ruleLabel = labels.find((l) => l.includes(".rule=")); + + expect(ruleLabel).toBeDefined(); + // Verify exact format: Host(`domain`) + expect(ruleLabel).toMatch(/Host\(`[^`]+`\)/); + // Ensure opening parenthesis is present after Host + expect(ruleLabel).toContain("Host(`example.com`)"); + // Ensure it does NOT have the malformed format + expect(ruleLabel).not.toMatch(/Host`[^`]+`\)/); + }); + + it("should generate PathPrefix with correct parentheses format", async () => { + const labels = await createDomainLabels( + "test-app", + { ...baseDomain, path: "/api" }, + "web", + ); + const ruleLabel = labels.find((l) => l.includes(".rule=")); + + expect(ruleLabel).toBeDefined(); + // Verify PathPrefix format + expect(ruleLabel).toMatch(/PathPrefix\(`[^`]+`\)/); + expect(ruleLabel).toContain("PathPrefix(`/api`)"); + // Ensure opening parenthesis is present + expect(ruleLabel).not.toMatch(/PathPrefix`[^`]+`\)/); + }); + + it("should generate combined Host and PathPrefix with correct format", async () => { + const labels = await createDomainLabels( + "test-app", + { ...baseDomain, path: "/api/v1" }, + "websecure", + ); + const ruleLabel = labels.find((l) => l.includes(".rule=")); + + expect(ruleLabel).toBeDefined(); + expect(ruleLabel).toBe( + "traefik.http.routers.test-app-1-websecure.rule=Host(`example.com`) && PathPrefix(`/api/v1`)", + ); + }); + }); + + describe("YAML serialization preserves Host rule format", () => { + it("should preserve Host rule format through YAML stringify/parse", async () => { + const labels = await createDomainLabels("test-app", baseDomain, "web"); + const ruleLabel = labels.find((l) => l.includes(".rule=")); + + // Simulate compose file structure + const composeSpec = { + services: { + myapp: { + image: "nginx", + labels: labels, + }, + }, + }; + + // Stringify to YAML + const yamlOutput = stringify(composeSpec, { lineWidth: 1000 }); + + // Parse back + const parsed = parse(yamlOutput) as typeof composeSpec; + const parsedRuleLabel = parsed.services.myapp.labels.find((l: string) => + l.includes(".rule="), + ); + + // Verify format is preserved + expect(parsedRuleLabel).toBe(ruleLabel); + expect(parsedRuleLabel).toContain("Host(`example.com`)"); + expect(parsedRuleLabel).not.toMatch(/Host`[^`]+`\)/); + }); + + it("should preserve complex rule format through YAML serialization", async () => { + const labels = await createDomainLabels( + "test-app", + { ...baseDomain, path: "/api", https: true }, + "websecure", + ); + + const composeSpec = { + services: { + myapp: { + labels: labels, + }, + }, + }; + + const yamlOutput = stringify(composeSpec, { lineWidth: 1000 }); + const parsed = parse(yamlOutput) as typeof composeSpec; + const parsedRuleLabel = parsed.services.myapp.labels.find((l: string) => + l.includes(".rule="), + ); + + expect(parsedRuleLabel).toContain( + "Host(`example.com`) && PathPrefix(`/api`)", + ); + }); + }); + + describe("Edge cases for domain names", () => { + const domainCases = [ + { name: "simple domain", host: "example.com" }, + { name: "subdomain", host: "app.example.com" }, + { name: "deep subdomain", host: "api.v1.app.example.com" }, + { name: "numeric domain", host: "123.example.com" }, + { name: "hyphenated domain", host: "my-app.example-host.com" }, + { name: "localhost", host: "localhost" }, + { name: "IP address style", host: "192.168.1.100" }, + ]; + + for (const { name, host } of domainCases) { + it(`should generate correct Host rule for ${name}: ${host}`, async () => { + const labels = await createDomainLabels( + "test-app", + { ...baseDomain, host }, + "web", + ); + const ruleLabel = labels.find((l) => l.includes(".rule=")); + + expect(ruleLabel).toBeDefined(); + expect(ruleLabel).toContain(`Host(\`${host}\`)`); + // Verify parenthesis is present + expect(ruleLabel).toMatch( + new RegExp(`Host\\(\\\`${host.replace(/\./g, "\\.")}\\\`\\)`), + ); + }); + } + }); + + describe("Multiple domains scenario", () => { + it("should generate correct format for both web and websecure entrypoints", async () => { + const webLabels = await createDomainLabels("test-app", baseDomain, "web"); + const websecureLabels = await createDomainLabels( + "test-app", + baseDomain, + "websecure", + ); + + const webRule = webLabels.find((l) => l.includes(".rule=")); + const websecureRule = websecureLabels.find((l) => l.includes(".rule=")); + + // Both should have correct format + expect(webRule).toContain("Host(`example.com`)"); + expect(websecureRule).toContain("Host(`example.com`)"); + + // Neither should have malformed format + expect(webRule).not.toMatch(/Host`[^`]+`\)/); + expect(websecureRule).not.toMatch(/Host`[^`]+`\)/); + }); + }); + + describe("Special characters in paths", () => { + const pathCases = [ + { name: "simple path", path: "/api" }, + { name: "nested path", path: "/api/v1/users" }, + { name: "path with hyphen", path: "/api-v1" }, + { name: "path with underscore", path: "/api_v1" }, + ]; + + for (const { name, path } of pathCases) { + it(`should generate correct PathPrefix for ${name}: ${path}`, async () => { + const labels = await createDomainLabels( + "test-app", + { ...baseDomain, path }, + "web", + ); + const ruleLabel = labels.find((l) => l.includes(".rule=")); + + expect(ruleLabel).toBeDefined(); + expect(ruleLabel).toContain(`PathPrefix(\`${path}\`)`); + // Verify parenthesis is present + expect(ruleLabel).not.toMatch(/PathPrefix`[^`]+`\)/); + }); + } + }); +}); diff --git a/apps/dokploy/__test__/deploy/application.command.test.ts b/apps/dokploy/__test__/deploy/application.command.test.ts new file mode 100644 index 0000000000..be29748eb9 --- /dev/null +++ b/apps/dokploy/__test__/deploy/application.command.test.ts @@ -0,0 +1,276 @@ +import * as adminService from "@dokploy/server/services/admin"; +import * as applicationService from "@dokploy/server/services/application"; +import { deployApplication } from "@dokploy/server/services/application"; +import * as deploymentService from "@dokploy/server/services/deployment"; +import * as builders from "@dokploy/server/utils/builders"; +import * as notifications from "@dokploy/server/utils/notifications/build-success"; +import * as execProcess from "@dokploy/server/utils/process/execAsync"; +import * as gitProvider from "@dokploy/server/utils/providers/git"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("@dokploy/server/db", () => { + const createChainableMock = (): any => { + const chain = { + set: vi.fn(() => chain), + where: vi.fn(() => chain), + returning: vi.fn().mockResolvedValue([{}] as any), + } as any; + return chain; + }; + + return { + db: { + select: vi.fn(), + insert: vi.fn(), + update: vi.fn(() => createChainableMock()), + delete: vi.fn(), + query: { + applications: { + findFirst: vi.fn(), + }, + }, + }, + }; +}); + +vi.mock("@dokploy/server/services/application", async () => { + const actual = await vi.importActual< + typeof import("@dokploy/server/services/application") + >("@dokploy/server/services/application"); + return { + ...actual, + findApplicationById: vi.fn(), + updateApplicationStatus: vi.fn(), + }; +}); + +vi.mock("@dokploy/server/services/admin", () => ({ + getDokployUrl: vi.fn(), +})); + +vi.mock("@dokploy/server/services/deployment", () => ({ + createDeployment: vi.fn(), + updateDeploymentStatus: vi.fn(), + updateDeployment: vi.fn(), +})); + +vi.mock("@dokploy/server/utils/providers/git", async () => { + const actual = await vi.importActual< + typeof import("@dokploy/server/utils/providers/git") + >("@dokploy/server/utils/providers/git"); + return { + ...actual, + getGitCommitInfo: vi.fn(), + }; +}); + +vi.mock("@dokploy/server/utils/process/execAsync", () => ({ + execAsync: vi.fn(), + ExecError: class ExecError extends Error {}, +})); + +vi.mock("@dokploy/server/utils/builders", async () => { + const actual = await vi.importActual< + typeof import("@dokploy/server/utils/builders") + >("@dokploy/server/utils/builders"); + return { + ...actual, + mechanizeDockerContainer: vi.fn(), + getBuildCommand: vi.fn(), + }; +}); + +vi.mock("@dokploy/server/utils/notifications/build-success", () => ({ + sendBuildSuccessNotifications: vi.fn(), +})); + +vi.mock("@dokploy/server/utils/notifications/build-error", () => ({ + sendBuildErrorNotifications: vi.fn(), +})); + +vi.mock("@dokploy/server/services/rollbacks", () => ({ + createRollback: vi.fn(), +})); + +import { db } from "@dokploy/server/db"; +import { cloneGitRepository } from "@dokploy/server/utils/providers/git"; + +const createMockApplication = (overrides = {}) => ({ + applicationId: "test-app-id", + name: "Test App", + appName: "test-app", + sourceType: "git" as const, + customGitUrl: "https://github.com/Dokploy/examples.git", + customGitBranch: "main", + customGitSSHKeyId: null, + buildType: "nixpacks" as const, + buildPath: "/astro", + env: "NODE_ENV=production", + serverId: null, + rollbackActive: false, + enableSubmodules: false, + environmentId: "env-id", + environment: { + projectId: "project-id", + env: "", + name: "production", + project: { + name: "Test Project", + organizationId: "org-id", + env: "", + }, + }, + domains: [], + ...overrides, +}); + +const createMockDeployment = () => ({ + deploymentId: "deployment-id", + logPath: "/tmp/test-deployment.log", +}); + +describe("deployApplication - Command Generation Tests", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(db.query.applications.findFirst).mockResolvedValue( + createMockApplication() as any, + ); + vi.mocked(applicationService.findApplicationById).mockResolvedValue( + createMockApplication() as any, + ); + vi.mocked(adminService.getDokployUrl).mockResolvedValue( + "http://localhost:3000", + ); + vi.mocked(deploymentService.createDeployment).mockResolvedValue( + createMockDeployment() as any, + ); + vi.mocked(execProcess.execAsync).mockResolvedValue({ + stdout: "", + stderr: "", + } as any); + vi.mocked(builders.mechanizeDockerContainer).mockResolvedValue( + undefined as any, + ); + vi.mocked(deploymentService.updateDeploymentStatus).mockResolvedValue( + undefined as any, + ); + vi.mocked(applicationService.updateApplicationStatus).mockResolvedValue( + {} as any, + ); + vi.mocked(notifications.sendBuildSuccessNotifications).mockResolvedValue( + undefined as any, + ); + vi.mocked(gitProvider.getGitCommitInfo).mockResolvedValue({ + message: "test commit", + hash: "abc123", + }); + vi.mocked(deploymentService.updateDeployment).mockResolvedValue({} as any); + }); + + it("should generate correct git clone command for astro example", async () => { + const app = createMockApplication(); + const command = await cloneGitRepository(app); + console.log(command); + + expect(command).toContain("https://github.com/Dokploy/examples.git"); + expect(command).not.toContain("--recurse-submodules"); + expect(command).toContain("--branch main"); + expect(command).toContain("--depth 1"); + expect(command).toContain("git clone"); + }); + + it("should generate git clone with submodules when enabled", async () => { + const app = createMockApplication({ enableSubmodules: true }); + const command = await cloneGitRepository(app); + + expect(command).toContain("--recurse-submodules"); + expect(command).toContain("https://github.com/Dokploy/examples.git"); + }); + + it("should verify nixpacks command is called with correct app", async () => { + const mockNixpacksCommand = "nixpacks build /path/to/app --name test-app"; + vi.mocked(builders.getBuildCommand).mockResolvedValue(mockNixpacksCommand); + + await deployApplication({ + applicationId: "test-app-id", + titleLog: "Test deployment", + descriptionLog: "", + }); + + expect(builders.getBuildCommand).toHaveBeenCalledWith( + expect.objectContaining({ + buildType: "nixpacks", + customGitUrl: "https://github.com/Dokploy/examples.git", + buildPath: "/astro", + }), + ); + + expect(execProcess.execAsync).toHaveBeenCalledWith( + expect.stringContaining("nixpacks build"), + ); + }); + + it("should verify railpack command includes correct parameters", async () => { + const mockApp = createMockApplication({ buildType: "railpack" }); + vi.mocked(db.query.applications.findFirst).mockResolvedValue( + mockApp as any, + ); + vi.mocked(applicationService.findApplicationById).mockResolvedValue( + mockApp as any, + ); + + const mockRailpackCommand = "railpack prepare /path/to/app"; + vi.mocked(builders.getBuildCommand).mockResolvedValue(mockRailpackCommand); + + await deployApplication({ + applicationId: "test-app-id", + titleLog: "Railpack test", + descriptionLog: "", + }); + + expect(builders.getBuildCommand).toHaveBeenCalledWith( + expect.objectContaining({ + buildType: "railpack", + }), + ); + + expect(execProcess.execAsync).toHaveBeenCalledWith( + expect.stringContaining("railpack prepare"), + ); + }); + + it("should execute commands in correct order", async () => { + const mockNixpacksCommand = "nixpacks build"; + vi.mocked(builders.getBuildCommand).mockResolvedValue(mockNixpacksCommand); + + await deployApplication({ + applicationId: "test-app-id", + titleLog: "Test", + descriptionLog: "", + }); + + const execCalls = vi.mocked(execProcess.execAsync).mock.calls; + expect(execCalls.length).toBeGreaterThan(0); + + const fullCommand = execCalls[0]?.[0]; + expect(fullCommand).toContain("set -e"); + expect(fullCommand).toContain("git clone"); + expect(fullCommand).toContain("nixpacks build"); + }); + + it("should include log redirection in command", async () => { + const mockCommand = "nixpacks build"; + vi.mocked(builders.getBuildCommand).mockResolvedValue(mockCommand); + + await deployApplication({ + applicationId: "test-app-id", + titleLog: "Test", + descriptionLog: "", + }); + + const execCalls = vi.mocked(execProcess.execAsync).mock.calls; + const fullCommand = execCalls[0]?.[0]; + + expect(fullCommand).toContain(">> /tmp/test-deployment.log 2>&1"); + }); +}); diff --git a/apps/dokploy/__test__/deploy/application.real.test.ts b/apps/dokploy/__test__/deploy/application.real.test.ts new file mode 100644 index 0000000000..43ff078362 --- /dev/null +++ b/apps/dokploy/__test__/deploy/application.real.test.ts @@ -0,0 +1,479 @@ +import { existsSync } from "node:fs"; +import path from "node:path"; +import type { ApplicationNested } from "@dokploy/server"; +import { paths } from "@dokploy/server/constants"; +import { execAsync } from "@dokploy/server/utils/process/execAsync"; +import { format } from "date-fns"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const REAL_TEST_TIMEOUT = 180000; // 3 minutes + +// Mock ONLY database and notifications +vi.mock("@dokploy/server/db", () => { + const createChainableMock = (): any => { + const chain: any = { + set: vi.fn(() => chain), + where: vi.fn(() => chain), + returning: vi.fn().mockResolvedValue([{}]), + }; + return chain; + }; + + return { + db: { + select: vi.fn(), + insert: vi.fn(), + update: vi.fn(() => createChainableMock()), + delete: vi.fn(), + query: { + applications: { + findFirst: vi.fn(), + }, + }, + }, + }; +}); + +vi.mock("@dokploy/server/services/application", async () => { + const actual = await vi.importActual< + typeof import("@dokploy/server/services/application") + >("@dokploy/server/services/application"); + return { + ...actual, + findApplicationById: vi.fn(), + updateApplicationStatus: vi.fn(), + }; +}); + +vi.mock("@dokploy/server/services/admin", () => ({ + getDokployUrl: vi.fn().mockResolvedValue("http://localhost:3000"), +})); + +vi.mock("@dokploy/server/services/deployment", () => ({ + createDeployment: vi.fn(), + updateDeploymentStatus: vi.fn(), + updateDeployment: vi.fn(), +})); + +vi.mock("@dokploy/server/utils/notifications/build-success", () => ({ + sendBuildSuccessNotifications: vi.fn(), +})); + +vi.mock("@dokploy/server/utils/notifications/build-error", () => ({ + sendBuildErrorNotifications: vi.fn(), +})); + +vi.mock("@dokploy/server/services/rollbacks", () => ({ + createRollback: vi.fn(), +})); + +// NOT mocked (executed for real): +// - execAsync +// - cloneGitRepository +// - getBuildCommand +// - mechanizeDockerContainer (requires Docker Swarm) + +import { db } from "@dokploy/server/db"; +import * as adminService from "@dokploy/server/services/admin"; +import * as applicationService from "@dokploy/server/services/application"; +import { deployApplication } from "@dokploy/server/services/application"; +import * as deploymentService from "@dokploy/server/services/deployment"; + +const createMockApplication = ( + overrides: Partial = {}, +): ApplicationNested => + ({ + applicationId: "test-app-id", + name: "Real Test App", + appName: `real-test-${Date.now()}`, + sourceType: "git" as const, + customGitUrl: "https://github.com/Dokploy/examples.git", + customGitBranch: "main", + customGitSSHKeyId: null, + customGitBuildPath: "/astro", + buildType: "nixpacks" as const, + env: "NODE_ENV=production", + serverId: null, + rollbackActive: false, + enableSubmodules: false, + environmentId: "env-id", + environment: { + projectId: "project-id", + env: "", + name: "production", + project: { + name: "Test Project", + organizationId: "org-id", + env: "", + }, + }, + domains: [], + mounts: [], + security: [], + redirects: [], + ports: [], + registry: null, + ...overrides, + }) as ApplicationNested; + +const createMockDeployment = async (appName: string) => { + const { LOGS_PATH } = paths(false); // false = local, no remote server + const formattedDateTime = format(new Date(), "yyyy-MM-dd:HH:mm:ss"); + const fileName = `${appName}-${formattedDateTime}.log`; + const logFilePath = path.join(LOGS_PATH, appName, fileName); + + // Actually create the log directory + await execAsync(`mkdir -p ${path.dirname(logFilePath)}`); + await execAsync(`echo "Initializing deployment" > ${logFilePath}`); + + return { + deploymentId: "deployment-id", + logPath: logFilePath, + }; +}; + +async function cleanupDocker(appName: string) { + try { + await execAsync(`docker stop ${appName} 2>/dev/null || true`); + await execAsync(`docker rm ${appName} 2>/dev/null || true`); + await execAsync(`docker rmi ${appName} 2>/dev/null || true`); + } catch (error) { + console.log("Docker cleanup completed"); + } +} + +async function cleanupFiles(appName: string) { + try { + const { LOGS_PATH, APPLICATIONS_PATH } = paths(false); + + // Clean cloned code directories + const appPath = path.join(APPLICATIONS_PATH, appName); + await execAsync(`rm -rf ${appPath} 2>/dev/null || true`); + + // Clean logs for appName - removes entire folder + const logPath = path.join(LOGS_PATH, appName); + await execAsync(`rm -rf ${logPath} 2>/dev/null || true`); + + console.log(`✅ Cleaned up files and logs for ${appName}`); + } catch (error) { + console.error(`⚠️ Error during cleanup for ${appName}:`, error); + } +} + +describe( + "deployApplication - REAL Execution Tests", + () => { + let currentAppName: string; + let currentDeployment: any; + const allTestAppNames: string[] = []; + + beforeEach(async () => { + vi.clearAllMocks(); + currentAppName = `real-test-${Date.now()}`; + currentDeployment = await createMockDeployment(currentAppName); + allTestAppNames.push(currentAppName); + + const mockApp = createMockApplication({ appName: currentAppName }); + + vi.mocked(db.query.applications.findFirst).mockResolvedValue( + mockApp as any, + ); + vi.mocked(applicationService.findApplicationById).mockResolvedValue( + mockApp as any, + ); + vi.mocked(adminService.getDokployUrl).mockResolvedValue( + "http://localhost:3000", + ); + vi.mocked(deploymentService.createDeployment).mockResolvedValue( + currentDeployment as any, + ); + vi.mocked(deploymentService.updateDeploymentStatus).mockResolvedValue( + undefined as any, + ); + vi.mocked(applicationService.updateApplicationStatus).mockResolvedValue( + {} as any, + ); + vi.mocked(deploymentService.updateDeployment).mockResolvedValue( + {} as any, + ); + }); + + afterEach(async () => { + // ALWAYS cleanup, even if test failed or passed + console.log(`\n🧹 Cleaning up test: ${currentAppName}`); + + // Clean current appName + try { + await cleanupDocker(currentAppName); + await cleanupFiles(currentAppName); + } catch (error) { + console.error("⚠️ Error cleaning current app:", error); + } + + // Clean ALL test folders just in case + try { + const { LOGS_PATH, APPLICATIONS_PATH } = paths(false); + await execAsync(`rm -rf ${LOGS_PATH}/real-* 2>/dev/null || true`); + await execAsync( + `rm -rf ${APPLICATIONS_PATH}/real-* 2>/dev/null || true`, + ); + console.log("✅ Cleaned up all test artifacts"); + } catch (error) { + console.error("⚠️ Error cleaning all artifacts:", error); + } + + console.log("✅ Cleanup completed\n"); + }); + + it( + "should REALLY clone git repo and build with nixpacks", + async () => { + console.log(`\n🚀 Testing real deployment with app: ${currentAppName}`); + + const result = await deployApplication({ + applicationId: "test-app-id", + titleLog: "Real Nixpacks Test", + descriptionLog: "Testing real execution", + }); + + expect(result).toBe(true); + + // Verify that Docker image was actually created + const { stdout: dockerImages } = await execAsync( + `docker images ${currentAppName} --format "{{.Repository}}"`, + ); + console.log("dockerImages", dockerImages); + expect(dockerImages.trim()).toBe(currentAppName); + console.log(`✅ Docker image created: ${currentAppName}`); + + // Verify log exists and has content + expect(existsSync(currentDeployment.logPath)).toBe(true); + const { stdout: logContent } = await execAsync( + `cat ${currentDeployment.logPath}`, + ); + expect(logContent).toContain("Cloning"); + expect(logContent).toContain("nixpacks"); + console.log(`✅ Build log created with ${logContent.length} chars`); + + // Verify update functions were called + expect(deploymentService.updateDeploymentStatus).toHaveBeenCalledWith( + "deployment-id", + "done", + ); + }, + REAL_TEST_TIMEOUT, + ); + + it.skip( + "should REALLY build with railpack (SKIPPED: requires special permissions)", + async () => { + const railpackAppName = `real-railpack-${Date.now()}`; + const railpackApp = createMockApplication({ + appName: railpackAppName, + buildType: "railpack", + railpackVersion: "3", + }); + currentAppName = railpackAppName; + allTestAppNames.push(railpackAppName); + + vi.mocked(db.query.applications.findFirst).mockResolvedValue( + railpackApp as any, + ); + vi.mocked(applicationService.findApplicationById).mockResolvedValue( + railpackApp as any, + ); + + console.log(`\n🚀 Testing real railpack deployment: ${currentAppName}`); + + const result = await deployApplication({ + applicationId: "test-app-id", + titleLog: "Real Railpack Test", + descriptionLog: "", + }); + + expect(result).toBe(true); + + const { stdout: dockerImages } = await execAsync( + `docker images ${currentAppName} --format "{{.Repository}}"`, + ); + expect(dockerImages.trim()).toBe(currentAppName); + console.log(`✅ Railpack image created: ${currentAppName}`); + + const { stdout: logContent } = await execAsync( + `cat ${currentDeployment.logPath}`, + ); + expect(logContent).toContain("railpack"); + console.log("✅ Railpack build completed"); + }, + REAL_TEST_TIMEOUT, + ); + + it( + "should handle REAL git clone errors", + async () => { + const errorAppName = `real-error-${Date.now()}`; + const errorApp = createMockApplication({ + appName: errorAppName, + customGitUrl: + "https://github.com/invalid/nonexistent-repo-123456.git", + }); + currentAppName = errorAppName; + allTestAppNames.push(errorAppName); + + vi.mocked(db.query.applications.findFirst).mockResolvedValue( + errorApp as any, + ); + vi.mocked(applicationService.findApplicationById).mockResolvedValue( + errorApp as any, + ); + + console.log(`\n🚀 Testing real error handling: ${currentAppName}`); + + await expect( + deployApplication({ + applicationId: "test-app-id", + titleLog: "Real Error Test", + descriptionLog: "", + }), + ).rejects.toThrow(); + + // Verify error status was called + expect(deploymentService.updateDeploymentStatus).toHaveBeenCalledWith( + "deployment-id", + "error", + ); + + // Verify log contains error + const { stdout: logContent } = await execAsync( + `cat ${currentDeployment.logPath}`, + ); + expect(logContent.toLowerCase()).toContain("error"); + console.log("✅ Error handling verified"); + }, + REAL_TEST_TIMEOUT, + ); + + it( + "should REALLY clone with submodules when enabled", + async () => { + const submodulesAppName = `real-submodules-${Date.now()}`; + const submodulesApp = createMockApplication({ + appName: submodulesAppName, + enableSubmodules: true, + }); + currentAppName = submodulesAppName; + allTestAppNames.push(submodulesAppName); + + vi.mocked(db.query.applications.findFirst).mockResolvedValue( + submodulesApp as any, + ); + vi.mocked(applicationService.findApplicationById).mockResolvedValue( + submodulesApp as any, + ); + + console.log(`\n🚀 Testing real submodules support: ${currentAppName}`); + + const result = await deployApplication({ + applicationId: "test-app-id", + titleLog: "Real Submodules Test", + descriptionLog: "", + }); + + expect(result).toBe(true); + + // Verify deployment completed successfully + const { stdout: logContent } = await execAsync( + `cat ${currentDeployment.logPath}`, + ); + expect(logContent).toContain("Cloning"); + expect(logContent.length).toBeGreaterThan(100); + console.log("✅ Submodules deployment completed"); + + // Verify image + const { stdout: dockerImages } = await execAsync( + `docker images ${currentAppName} --format "{{.Repository}}"`, + ); + expect(dockerImages.trim()).toBe(currentAppName); + }, + REAL_TEST_TIMEOUT, + ); + + it( + "should verify REAL commit info extraction", + async () => { + console.log(`\n🚀 Testing real commit info: ${currentAppName}`); + + await deployApplication({ + applicationId: "test-app-id", + titleLog: "Real Commit Test", + descriptionLog: "", + }); + + // Verify updateDeployment was called with commit info + expect(deploymentService.updateDeployment).toHaveBeenCalled(); + const updateCall = vi.mocked(deploymentService.updateDeployment).mock + .calls[0]; + + // Real commit info should have title and hash + expect(updateCall?.[1]).toHaveProperty("title"); + expect(updateCall?.[1]).toHaveProperty("description"); + expect(updateCall?.[1]?.description).toContain("Commit:"); + + console.log( + `✅ Real commit extracted: ${updateCall?.[1]?.title?.substring(0, 50)}...`, + ); + }, + REAL_TEST_TIMEOUT, + ); + + it( + "should REALLY build with Dockerfile", + async () => { + const dockerfileAppName = `real-dockerfile-${Date.now()}`; + const dockerfileApp = createMockApplication({ + appName: dockerfileAppName, + buildType: "dockerfile", + customGitBuildPath: "/deno", + dockerfile: "Dockerfile", + }); + currentAppName = dockerfileAppName; + allTestAppNames.push(dockerfileAppName); + + vi.mocked(db.query.applications.findFirst).mockResolvedValue( + dockerfileApp as any, + ); + vi.mocked(applicationService.findApplicationById).mockResolvedValue( + dockerfileApp as any, + ); + + console.log(`\n🚀 Testing real Dockerfile build: ${currentAppName}`); + + const result = await deployApplication({ + applicationId: "test-app-id", + titleLog: "Real Dockerfile Test", + descriptionLog: "", + }); + + expect(result).toBe(true); + + // Verify log + const { stdout: logContent } = await execAsync( + `cat ${currentDeployment.logPath}`, + ); + expect(logContent).toContain("Building"); + expect(logContent).toContain(dockerfileAppName); + console.log("✅ Dockerfile build log verified"); + + // Verify image + const { stdout: dockerImages } = await execAsync( + `docker images ${currentAppName} --format "{{.Repository}}"`, + ); + console.log("dockerImages", dockerImages); + expect(dockerImages.trim()).toBe(currentAppName); + console.log(`✅ Docker image created: ${currentAppName}`); + }, + REAL_TEST_TIMEOUT, + ); + }, + REAL_TEST_TIMEOUT, +); diff --git a/apps/dokploy/__test__/drop/drop.test.ts b/apps/dokploy/__test__/drop/drop.test.ts index 112a4b25ee..cabc77d876 100644 --- a/apps/dokploy/__test__/drop/drop.test.ts +++ b/apps/dokploy/__test__/drop/drop.test.ts @@ -30,6 +30,10 @@ const baseApp: ApplicationNested = { previewLabels: [], herokuVersion: "", giteaBranch: "", + buildServerId: "", + buildRegistryId: "", + buildRegistry: null, + args: [], giteaBuildPath: "", previewRequireCollaboratorPermissions: false, giteaId: "", @@ -37,6 +41,9 @@ const baseApp: ApplicationNested = { giteaRepository: "", cleanCache: false, watchPaths: [], + rollbackRegistryId: "", + rollbackRegistry: null, + deployments: [], enableSubmodules: false, applicationStatus: "done", triggerType: "push", diff --git a/apps/dokploy/__test__/server/mechanizeDockerContainer.test.ts b/apps/dokploy/__test__/server/mechanizeDockerContainer.test.ts index 6eb5d18318..c12a272bc8 100644 --- a/apps/dokploy/__test__/server/mechanizeDockerContainer.test.ts +++ b/apps/dokploy/__test__/server/mechanizeDockerContainer.test.ts @@ -1,10 +1,13 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; - import type { ApplicationNested } from "@dokploy/server/utils/builders"; import { mechanizeDockerContainer } from "@dokploy/server/utils/builders"; +import { beforeEach, describe, expect, it, vi } from "vitest"; type MockCreateServiceOptions = { - StopGracePeriod?: number; + TaskTemplate?: { + ContainerSpec?: { + StopGracePeriod?: number; + }; + }; [key: string]: unknown; }; @@ -82,8 +85,10 @@ describe("mechanizeDockerContainer", () => { throw new Error("createServiceMock should have been called once"); } const [settings] = call; - expect(settings.StopGracePeriod).toBe(0); - expect(typeof settings.StopGracePeriod).toBe("number"); + expect(settings.TaskTemplate?.ContainerSpec?.StopGracePeriod).toBe(0); + expect(typeof settings.TaskTemplate?.ContainerSpec?.StopGracePeriod).toBe( + "number", + ); }); it("omits StopGracePeriod when stopGracePeriodSwarm is null", async () => { @@ -97,6 +102,8 @@ describe("mechanizeDockerContainer", () => { throw new Error("createServiceMock should have been called once"); } const [settings] = call; - expect(settings).not.toHaveProperty("StopGracePeriod"); + expect(settings.TaskTemplate?.ContainerSpec).not.toHaveProperty( + "StopGracePeriod", + ); }); }); diff --git a/apps/dokploy/__test__/traefik/server/update-server-config.test.ts b/apps/dokploy/__test__/traefik/server/update-server-config.test.ts index 6858f0f005..f35e8132cc 100644 --- a/apps/dokploy/__test__/traefik/server/update-server-config.test.ts +++ b/apps/dokploy/__test__/traefik/server/update-server-config.test.ts @@ -18,6 +18,8 @@ const baseAdmin: User = { enablePaidFeatures: false, allowImpersonation: false, role: "user", + firstName: "", + lastName: "", metricsConfig: { containers: { refreshRate: 20, @@ -61,7 +63,6 @@ const baseAdmin: User = { expirationDate: "", id: "", isRegistered: false, - name: "", createdAt2: new Date().toISOString(), emailVerified: false, image: "", diff --git a/apps/dokploy/__test__/traefik/traefik.test.ts b/apps/dokploy/__test__/traefik/traefik.test.ts index 5b48b12487..279e74fa58 100644 --- a/apps/dokploy/__test__/traefik/traefik.test.ts +++ b/apps/dokploy/__test__/traefik/traefik.test.ts @@ -11,8 +11,15 @@ const baseApp: ApplicationNested = { giteaRepository: "", giteaOwner: "", giteaBranch: "", + buildServerId: "", + buildRegistryId: "", + buildRegistry: null, giteaBuildPath: "", giteaId: "", + args: [], + rollbackRegistryId: "", + rollbackRegistry: null, + deployments: [], cleanCache: false, applicationStatus: "done", endpointSpecSwarm: null, diff --git a/apps/dokploy/__test__/vitest.config.ts b/apps/dokploy/__test__/vitest.config.ts index ddc84d6ac3..7270b828a7 100644 --- a/apps/dokploy/__test__/vitest.config.ts +++ b/apps/dokploy/__test__/vitest.config.ts @@ -13,7 +13,11 @@ export default defineConfig({ NODE: "test", }, }, - plugins: [tsconfigPaths()], + plugins: [ + tsconfigPaths({ + projects: [path.resolve(__dirname, "../tsconfig.json")], + }), + ], resolve: { alias: { "@dokploy/server": path.resolve( diff --git a/apps/dokploy/components/dashboard/application/advanced/general/add-command.tsx b/apps/dokploy/components/dashboard/application/advanced/general/add-command.tsx index 1bf69394ad..a7c5f72880 100644 --- a/apps/dokploy/components/dashboard/application/advanced/general/add-command.tsx +++ b/apps/dokploy/components/dashboard/application/advanced/general/add-command.tsx @@ -1,6 +1,7 @@ import { zodResolver } from "@hookform/resolvers/zod"; +import { Plus, Trash2 } from "lucide-react"; import { useEffect } from "react"; -import { useForm } from "react-hook-form"; +import { useFieldArray, useForm } from "react-hook-form"; import { toast } from "sonner"; import { z } from "zod"; import { Button } from "@/components/ui/button"; @@ -28,6 +29,13 @@ interface Props { const AddRedirectSchema = z.object({ command: z.string(), + args: z + .array( + z.object({ + value: z.string().min(1, "Argument cannot be empty"), + }), + ) + .optional(), }); type AddCommand = z.infer; @@ -47,22 +55,30 @@ export const AddCommand = ({ applicationId }: Props) => { const form = useForm({ defaultValues: { command: "", + args: [], }, resolver: zodResolver(AddRedirectSchema), }); + const { fields, append, remove } = useFieldArray({ + control: form.control, + name: "args", + }); + useEffect(() => { - if (data?.command) { + if (data) { form.reset({ command: data?.command || "", + args: data?.args?.map((arg) => ({ value: arg })) || [], }); } - }, [form, form.reset, form.formState.isSubmitSuccessful, data?.command]); + }, [data, form]); const onSubmit = async (data: AddCommand) => { await mutateAsync({ applicationId, command: data?.command, + args: data?.args?.map((arg) => arg.value).filter(Boolean), }) .then(async () => { toast.success("Command Updated"); @@ -100,13 +116,65 @@ export const AddCommand = ({ applicationId }: Props) => { Command - + )} /> + +
+
+ Arguments (Args) + +
+ + {fields.length === 0 && ( +

+ No arguments added yet. Click "Add Argument" to add one. +

+ )} + + {fields.map((field, index) => ( + ( + +
+ + + + +
+ +
+ )} + /> + ))} +
+
+ + + + + ); +}; diff --git a/apps/dokploy/components/dashboard/application/deployments/show-deployments.tsx b/apps/dokploy/components/dashboard/application/deployments/show-deployments.tsx index 7f3bc82b43..ca7a93518e 100644 --- a/apps/dokploy/components/dashboard/application/deployments/show-deployments.tsx +++ b/apps/dokploy/components/dashboard/application/deployments/show-deployments.tsx @@ -143,7 +143,7 @@ export const ShowDeployments = ({ See the last 10 deployments for this {type} -
+
{(type === "application" || type === "compose") && ( )} @@ -373,7 +373,19 @@ export const ShowDeployments = ({ type === "application" && ( +

+ Are you sure you want to rollback to this + deployment? +

+ + Please wait a few seconds while the image is + pulled from the registry. Your application + should be running shortly. + +
+ } type="default" onClick={async () => { await rollback({ @@ -407,7 +419,7 @@ export const ShowDeployments = ({
)} setActiveLog(null)} logPath={activeLog?.logPath || ""} diff --git a/apps/dokploy/components/dashboard/application/domains/handle-domain.tsx b/apps/dokploy/components/dashboard/application/domains/handle-domain.tsx index 9d7a074f98..bb5366c339 100644 --- a/apps/dokploy/components/dashboard/application/domains/handle-domain.tsx +++ b/apps/dokploy/components/dashboard/application/domains/handle-domain.tsx @@ -46,7 +46,13 @@ export type CacheType = "fetch" | "cache"; export const domain = z .object({ - host: z.string().min(1, { message: "Add a hostname" }), + host: z + .string() + .min(1, { message: "Add a hostname" }) + .refine((val) => val === val.trim(), { + message: "Domain name cannot have leading or trailing spaces", + }) + .transform((val) => val.trim()), path: z.string().min(1).optional(), internalPath: z.string().optional(), stripPath: z.boolean().optional(), @@ -299,6 +305,13 @@ export const AddDomain = ({ id, type, domainId = "", children }: Props) => { {isError && {error?.message}} + {type === "compose" && ( + + Whenever you make changes to domains, remember to redeploy your + compose to apply the changes. + + )} +
{ + if ( + values.rollbackActive && + (!values.rollbackRegistryId || values.rollbackRegistryId === "none") + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ["rollbackRegistryId"], + message: "Registry is required when rollbacks are enabled", + }); + } + }); type FormValues = z.infer; @@ -49,17 +74,33 @@ export const ShowRollbackSettings = ({ applicationId, children }: Props) => { const { mutateAsync: updateApplication, isLoading } = api.application.update.useMutation(); + const { data: registries } = api.registry.all.useQuery(); + const form = useForm({ resolver: zodResolver(formSchema), defaultValues: { rollbackActive: application?.rollbackActive ?? false, + rollbackRegistryId: application?.rollbackRegistryId || "", }, }); + useEffect(() => { + if (application) { + form.reset({ + rollbackActive: application.rollbackActive ?? false, + rollbackRegistryId: application.rollbackRegistryId || "", + }); + } + }, [application, form]); + const onSubmit = async (data: FormValues) => { await updateApplication({ applicationId, rollbackActive: data.rollbackActive, + rollbackRegistryId: + data.rollbackRegistryId === "none" || !data.rollbackRegistryId + ? null + : data.rollbackRegistryId, }) .then(() => { toast.success("Rollback settings updated"); @@ -112,6 +153,65 @@ export const ShowRollbackSettings = ({ applicationId, children }: Props) => { )} /> + {form.watch("rollbackActive") && ( + ( + + Rollback Registry + + {!registries || registries.length === 0 ? ( + + No registries available. Please{" "} + + configure a registry + {" "} + first to enable rollbacks. + + ) : ( + + Select a registry where rollback images will be stored. + + )} + + + )} + /> + )} + diff --git a/apps/dokploy/components/dashboard/application/schedules/handle-schedules.tsx b/apps/dokploy/components/dashboard/application/schedules/handle-schedules.tsx index 8273d0e2be..1cb3d34af0 100644 --- a/apps/dokploy/components/dashboard/application/schedules/handle-schedules.tsx +++ b/apps/dokploy/components/dashboard/application/schedules/handle-schedules.tsx @@ -60,6 +60,30 @@ export const commonCronExpressions = [ { label: "Custom", value: "custom" }, ]; +export const commonTimezones = [ + { label: "UTC (Coordinated Universal Time)", value: "UTC" }, + { label: "America/New_York (Eastern Time)", value: "America/New_York" }, + { label: "America/Chicago (Central Time)", value: "America/Chicago" }, + { label: "America/Denver (Mountain Time)", value: "America/Denver" }, + { label: "America/Los_Angeles (Pacific Time)", value: "America/Los_Angeles" }, + { + label: "America/Mexico_City (Central Mexico)", + value: "America/Mexico_City", + }, + { label: "America/Sao_Paulo (Brasilia Time)", value: "America/Sao_Paulo" }, + { label: "Europe/London (Greenwich Mean Time)", value: "Europe/London" }, + { label: "Europe/Paris (Central European Time)", value: "Europe/Paris" }, + { label: "Europe/Berlin (Central European Time)", value: "Europe/Berlin" }, + { label: "Asia/Tokyo (Japan Standard Time)", value: "Asia/Tokyo" }, + { label: "Asia/Shanghai (China Standard Time)", value: "Asia/Shanghai" }, + { label: "Asia/Dubai (Gulf Standard Time)", value: "Asia/Dubai" }, + { label: "Asia/Kolkata (India Standard Time)", value: "Asia/Kolkata" }, + { + label: "Australia/Sydney (Australian Eastern Time)", + value: "Australia/Sydney", + }, +]; + const formSchema = z .object({ name: z.string().min(1, "Name is required"), @@ -75,6 +99,7 @@ const formSchema = z "dokploy-server", ]), script: z.string(), + timezone: z.string().optional(), }) .superRefine((data, ctx) => { if (data.scheduleType === "compose" && !data.serviceName) { @@ -213,6 +238,7 @@ export const HandleSchedules = ({ id, scheduleId, scheduleType }: Props) => { serviceName: "", scheduleType: scheduleType || "application", script: "", + timezone: undefined, }, }); @@ -251,6 +277,7 @@ export const HandleSchedules = ({ id, scheduleId, scheduleType }: Props) => { serviceName: schedule.serviceName || "", scheduleType: schedule.scheduleType, script: schedule.script || "", + timezone: schedule.timezone || undefined, }); } }, [form, schedule, scheduleId]); @@ -464,6 +491,54 @@ export const HandleSchedules = ({ id, scheduleId, scheduleType }: Props) => { formControl={form.control} /> + ( + + + Timezone + + + + + + +

+ Select a timezone for the schedule. If not + specified, UTC will be used. +

+
+
+
+
+ + + Optional: Choose a timezone for the schedule execution time + + +
+ )} + /> + {(scheduleTypeForm === "application" || scheduleTypeForm === "compose") && ( <> diff --git a/apps/dokploy/components/dashboard/docker/logs/utils.ts b/apps/dokploy/components/dashboard/docker/logs/utils.ts index 5e97edfe25..fc0b50928e 100644 --- a/apps/dokploy/components/dashboard/docker/logs/utils.ts +++ b/apps/dokploy/components/dashboard/docker/logs/utils.ts @@ -49,7 +49,7 @@ export function parseLogs(logString: string): LogLine[] { // { timestamp: new Date("2024-12-10T10:00:00.000Z"), // message: "The server is running on port 8080" } const logRegex = - /^(?:(\d+)\s+)?(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z|\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3} UTC)?\s*(.*)$/; + /^(?:(?\d+)\s+)?(?(?:\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z|\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3} UTC))?\s*(?[\s\S]*)$/; return logString .split("\n") @@ -59,7 +59,7 @@ export function parseLogs(logString: string): LogLine[] { const match = line.match(logRegex); if (!match) return null; - const [, , timestamp, message] = match; + const { timestamp, message } = match.groups ?? {}; if (!message?.trim()) return null; diff --git a/apps/dokploy/components/dashboard/impersonation/impersonation-bar.tsx b/apps/dokploy/components/dashboard/impersonation/impersonation-bar.tsx index b96b7c8664..f779839967 100644 --- a/apps/dokploy/components/dashboard/impersonation/impersonation-bar.tsx +++ b/apps/dokploy/components/dashboard/impersonation/impersonation-bar.tsx @@ -103,7 +103,7 @@ export const ImpersonationBar = () => { setOpen(false); toast.success("Successfully impersonating user", { - description: `You are now viewing as ${selectedUser.name || selectedUser.email}`, + description: `You are now viewing as ${`${selectedUser.name} ${selectedUser.lastName}`.trim() || selectedUser.email}`, }); window.location.reload(); } catch (error) { @@ -195,7 +195,8 @@ export const ImpersonationBar = () => { - {selectedUser.name || ""} + {`${selectedUser.name} ${selectedUser.lastName}`.trim() || + ""} {selectedUser.email} @@ -242,7 +243,8 @@ export const ImpersonationBar = () => { - {user.name || ""} + {`${user.name} ${user.lastName}`.trim() || + ""} {user.email} • {user.role} @@ -283,10 +285,14 @@ export const ImpersonationBar = () => { - {data?.user?.name?.slice(0, 2).toUpperCase() || "U"} + {`${data?.user?.firstName?.[0] || ""}${data?.user?.lastName?.[0] || ""}`.toUpperCase() || + "U"}
@@ -299,7 +305,8 @@ export const ImpersonationBar = () => { Impersonating - {data?.user?.name || ""} + {`${data?.user?.firstName} ${data?.user?.lastName}`.trim() || + ""}
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 b28c4d9b67..1dd41e7224 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 @@ -10,7 +10,7 @@ import { DockerNetworkChart } from "./docker-network-chart"; const defaultData = { cpu: { - value: 0, + value: "0%", time: "", }, memory: { @@ -46,7 +46,7 @@ interface Props { } export interface DockerStats { cpu: { - value: number; + value: string; time: string; }; memory: { @@ -220,7 +220,13 @@ export const ContainerFreeMonitoring = ({ Used: {currentData.cpu.value} - +
diff --git a/apps/dokploy/components/dashboard/postgres/advanced/show-custom-command.tsx b/apps/dokploy/components/dashboard/postgres/advanced/show-custom-command.tsx index febaa86447..5a543b477d 100644 --- a/apps/dokploy/components/dashboard/postgres/advanced/show-custom-command.tsx +++ b/apps/dokploy/components/dashboard/postgres/advanced/show-custom-command.tsx @@ -1,6 +1,7 @@ import { zodResolver } from "@hookform/resolvers/zod"; +import { Plus, Trash2 } from "lucide-react"; import { useEffect } from "react"; -import { useForm } from "react-hook-form"; +import { useFieldArray, useForm } from "react-hook-form"; import { toast } from "sonner"; import { z } from "zod"; import { Button } from "@/components/ui/button"; @@ -20,6 +21,13 @@ import type { ServiceType } from "../../application/advanced/show-resources"; const addDockerImage = z.object({ dockerImage: z.string().min(1, "Docker image is required"), command: z.string(), + args: z + .array( + z.object({ + value: z.string().min(1, "Argument cannot be empty"), + }), + ) + .optional(), }); interface Props { @@ -61,18 +69,25 @@ export const ShowCustomCommand = ({ id, type }: Props) => { defaultValues: { dockerImage: "", command: "", + args: [], }, resolver: zodResolver(addDockerImage), }); + const { fields, append, remove } = useFieldArray({ + control: form.control, + name: "args", + }); + useEffect(() => { if (data) { form.reset({ dockerImage: data.dockerImage, command: data.command || "", + args: data.args?.map((arg) => ({ value: arg })) || [], }); } - }, [data, form, form.reset]); + }, [data, form]); const onSubmit = async (formData: AddDockerImage) => { await mutateAsync({ @@ -83,6 +98,7 @@ export const ShowCustomCommand = ({ id, type }: Props) => { mariadbId: id || "", dockerImage: formData?.dockerImage, command: formData?.command, + args: formData?.args?.map((arg) => arg.value).filter(Boolean), }) .then(async () => { toast.success("Custom Command Updated"); @@ -128,13 +144,68 @@ export const ShowCustomCommand = ({ id, type }: Props) => { Command - + )} /> + +
+
+ Arguments (Args) + +
+ + {fields.length === 0 && ( +

+ No arguments added yet. Click "Add Argument" to add one. +

+ )} + + {fields.map((field, index) => ( + ( + +
+ + + + +
+ +
+ )} + /> + ))} +
+
- - {/* Action buttons for non-production environments */} - {/* - - */} {environment.name !== "production" && (
- )} + + + + + + + + No models found. + {displayModels.map((model) => { + const isSelected = field.value === model.id; + return ( + { + field.onChange(model.id); + setModelPopoverOpen(false); + setModelSearch(""); + }} + > + + {model.id} + + ); + })} + + + + + + Select an AI model to use + + + + ); + }} /> )} diff --git a/apps/dokploy/components/dashboard/settings/notifications/handle-notifications.tsx b/apps/dokploy/components/dashboard/settings/notifications/handle-notifications.tsx index 337cdfd2ba..0a513ef23c 100644 --- a/apps/dokploy/components/dashboard/settings/notifications/handle-notifications.tsx +++ b/apps/dokploy/components/dashboard/settings/notifications/handle-notifications.tsx @@ -1,5 +1,11 @@ import { zodResolver } from "@hookform/resolvers/zod"; -import { AlertTriangle, Mail, PenBoxIcon, PlusIcon } from "lucide-react"; +import { + AlertTriangle, + Mail, + PenBoxIcon, + PlusIcon, + Trash2, +} from "lucide-react"; import { useEffect, useState } from "react"; import { useFieldArray, useForm } from "react-hook-form"; import { toast } from "sonner"; @@ -44,6 +50,7 @@ const notificationBaseSchema = z.object({ appDeploy: z.boolean().default(false), appBuildError: z.boolean().default(false), databaseBackup: z.boolean().default(false), + volumeBackup: z.boolean().default(false), dokployRestart: z.boolean().default(false), dockerCleanup: z.boolean().default(false), serverThreshold: z.boolean().default(false), @@ -103,10 +110,25 @@ export const notificationSchema = z.discriminatedUnion("type", [ type: z.literal("ntfy"), serverUrl: z.string().min(1, { message: "Server URL is required" }), topic: z.string().min(1, { message: "Topic is required" }), - accessToken: z.string().min(1, { message: "Access Token is required" }), + accessToken: z.string().optional(), priority: z.number().min(1).max(5).default(3), }) .merge(notificationBaseSchema), + z + .object({ + type: z.literal("custom"), + endpoint: z.string().min(1, { message: "Endpoint URL is required" }), + headers: z + .array( + z.object({ + key: z.string(), + value: z.string(), + }), + ) + .optional() + .default([]), + }) + .merge(notificationBaseSchema), z .object({ type: z.literal("lark"), @@ -144,6 +166,10 @@ export const notificationsMap = { icon: , label: "ntfy", }, + custom: { + icon: , + label: "Custom", + }, }; export type NotificationSchema = z.infer; @@ -179,6 +205,13 @@ export const HandleNotifications = ({ notificationId }: Props) => { api.notification.testNtfyConnection.useMutation(); const { mutateAsync: testLarkConnection, isLoading: isLoadingLark } = api.notification.testLarkConnection.useMutation(); + + const { mutateAsync: testCustomConnection, isLoading: isLoadingCustom } = + api.notification.testCustomConnection.useMutation(); + + const customMutation = notificationId + ? api.notification.updateCustom.useMutation() + : api.notification.createCustom.useMutation(); const slackMutation = notificationId ? api.notification.updateSlack.useMutation() : api.notification.createSlack.useMutation(); @@ -217,6 +250,15 @@ export const HandleNotifications = ({ notificationId }: Props) => { name: "toAddresses" as never, }); + const { + fields: headerFields, + append: appendHeader, + remove: removeHeader, + } = useFieldArray({ + control: form.control, + name: "headers" as never, + }); + useEffect(() => { if (type === "email" && fields.length === 0) { append(""); @@ -231,6 +273,7 @@ export const HandleNotifications = ({ notificationId }: Props) => { appDeploy: notification.appDeploy, dokployRestart: notification.dokployRestart, databaseBackup: notification.databaseBackup, + volumeBackup: notification.volumeBackup, dockerCleanup: notification.dockerCleanup, webhookUrl: notification.slack?.webhookUrl, channel: notification.slack?.channel || "", @@ -244,6 +287,7 @@ export const HandleNotifications = ({ notificationId }: Props) => { appDeploy: notification.appDeploy, dokployRestart: notification.dokployRestart, databaseBackup: notification.databaseBackup, + volumeBackup: notification.volumeBackup, botToken: notification.telegram?.botToken, messageThreadId: notification.telegram?.messageThreadId || "", chatId: notification.telegram?.chatId, @@ -258,6 +302,7 @@ export const HandleNotifications = ({ notificationId }: Props) => { appDeploy: notification.appDeploy, dokployRestart: notification.dokployRestart, databaseBackup: notification.databaseBackup, + volumeBackup: notification.volumeBackup, type: notification.notificationType, webhookUrl: notification.discord?.webhookUrl, decoration: notification.discord?.decoration || undefined, @@ -271,6 +316,7 @@ export const HandleNotifications = ({ notificationId }: Props) => { appDeploy: notification.appDeploy, dokployRestart: notification.dokployRestart, databaseBackup: notification.databaseBackup, + volumeBackup: notification.volumeBackup, type: notification.notificationType, smtpServer: notification.email?.smtpServer, smtpPort: notification.email?.smtpPort, @@ -288,6 +334,7 @@ export const HandleNotifications = ({ notificationId }: Props) => { appDeploy: notification.appDeploy, dokployRestart: notification.dokployRestart, databaseBackup: notification.databaseBackup, + volumeBackup: notification.volumeBackup, type: notification.notificationType, appToken: notification.gotify?.appToken, decoration: notification.gotify?.decoration || undefined, @@ -302,8 +349,9 @@ export const HandleNotifications = ({ notificationId }: Props) => { appDeploy: notification.appDeploy, dokployRestart: notification.dokployRestart, databaseBackup: notification.databaseBackup, + volumeBackup: notification.volumeBackup, type: notification.notificationType, - accessToken: notification.ntfy?.accessToken, + accessToken: notification.ntfy?.accessToken || "", topic: notification.ntfy?.topic, priority: notification.ntfy?.priority, serverUrl: notification.ntfy?.serverUrl, @@ -323,6 +371,26 @@ export const HandleNotifications = ({ notificationId }: Props) => { dockerCleanup: notification.dockerCleanup, serverThreshold: notification.serverThreshold, }); + } else if (notification.notificationType === "custom") { + form.reset({ + appBuildError: notification.appBuildError, + appDeploy: notification.appDeploy, + dokployRestart: notification.dokployRestart, + databaseBackup: notification.databaseBackup, + type: notification.notificationType, + endpoint: notification.custom?.endpoint || "", + headers: notification.custom?.headers + ? Object.entries(notification.custom.headers).map( + ([key, value]) => ({ + key, + value, + }), + ) + : [], + name: notification.name, + dockerCleanup: notification.dockerCleanup, + serverThreshold: notification.serverThreshold, + }); } } else { form.reset(); @@ -337,6 +405,7 @@ export const HandleNotifications = ({ notificationId }: Props) => { gotify: gotifyMutation, ntfy: ntfyMutation, lark: larkMutation, + custom: customMutation, }; const onSubmit = async (data: NotificationSchema) => { @@ -345,6 +414,7 @@ export const HandleNotifications = ({ notificationId }: Props) => { appDeploy, dokployRestart, databaseBackup, + volumeBackup, dockerCleanup, serverThreshold, } = data; @@ -355,6 +425,7 @@ export const HandleNotifications = ({ notificationId }: Props) => { appDeploy: appDeploy, dokployRestart: dokployRestart, databaseBackup: databaseBackup, + volumeBackup: volumeBackup, webhookUrl: data.webhookUrl, channel: data.channel, name: data.name, @@ -369,6 +440,7 @@ export const HandleNotifications = ({ notificationId }: Props) => { appDeploy: appDeploy, dokployRestart: dokployRestart, databaseBackup: databaseBackup, + volumeBackup: volumeBackup, botToken: data.botToken, messageThreadId: data.messageThreadId || "", chatId: data.chatId, @@ -384,6 +456,7 @@ export const HandleNotifications = ({ notificationId }: Props) => { appDeploy: appDeploy, dokployRestart: dokployRestart, databaseBackup: databaseBackup, + volumeBackup: volumeBackup, webhookUrl: data.webhookUrl, decoration: data.decoration, name: data.name, @@ -398,6 +471,7 @@ export const HandleNotifications = ({ notificationId }: Props) => { appDeploy: appDeploy, dokployRestart: dokployRestart, databaseBackup: databaseBackup, + volumeBackup: volumeBackup, smtpServer: data.smtpServer, smtpPort: data.smtpPort, username: data.username, @@ -416,6 +490,7 @@ export const HandleNotifications = ({ notificationId }: Props) => { appDeploy: appDeploy, dokployRestart: dokployRestart, databaseBackup: databaseBackup, + volumeBackup: volumeBackup, serverUrl: data.serverUrl, appToken: data.appToken, priority: data.priority, @@ -431,8 +506,9 @@ export const HandleNotifications = ({ notificationId }: Props) => { appDeploy: appDeploy, dokployRestart: dokployRestart, databaseBackup: databaseBackup, + volumeBackup: volumeBackup, serverUrl: data.serverUrl, - accessToken: data.accessToken, + accessToken: data.accessToken || "", topic: data.topic, priority: data.priority, name: data.name, @@ -453,6 +529,32 @@ export const HandleNotifications = ({ notificationId }: Props) => { larkId: notification?.larkId || "", serverThreshold: serverThreshold, }); + } else if (data.type === "custom") { + // Convert headers array to object + const headersRecord = + data.headers && data.headers.length > 0 + ? data.headers.reduce( + (acc, { key, value }) => { + if (key.trim()) acc[key] = value; + return acc; + }, + {} as Record, + ) + : undefined; + + promise = customMutation.mutateAsync({ + appBuildError: appBuildError, + appDeploy: appDeploy, + dokployRestart: dokployRestart, + databaseBackup: databaseBackup, + endpoint: data.endpoint, + headers: headersRecord, + name: data.name, + dockerCleanup: dockerCleanup, + serverThreshold: serverThreshold, + notificationId: notificationId || "", + customId: notification?.customId || "", + }); } if (promise) { @@ -1001,8 +1103,12 @@ export const HandleNotifications = ({ notificationId }: Props) => { + + Optional. Leave blank for public topics. + )} @@ -1039,7 +1145,92 @@ export const HandleNotifications = ({ notificationId }: Props) => { /> )} + {type === "custom" && ( +
+ ( + + Webhook URL + + + + + The URL where POST requests will be sent with + notification data. + + + + )} + /> +
+
+ Headers + + Optional. Custom headers for your POST request (e.g., + Authorization, Content-Type). + +
+ +
+ {headerFields.map((field, index) => ( +
+ ( + + + + + + )} + /> + ( + + + + + + )} + /> + +
+ ))} +
+ + +
+
+ )} {type === "lark" && ( <> { )} /> + ( + +
+ Volume Backup + + Trigger the action when a volume backup is created. + +
+ + + +
+ )} + /> + { isLoadingEmail || isLoadingGotify || isLoadingNtfy || - isLoadingLark + isLoadingLark || + isLoadingCustom } variant="secondary" + type="button" onClick={async () => { + const isValid = await form.trigger(); + if (!isValid) return; + + const data = form.getValues(); + try { - if (type === "slack") { + if (data.type === "slack") { await testSlackConnection({ - webhookUrl: form.getValues("webhookUrl"), - channel: form.getValues("channel"), + webhookUrl: data.webhookUrl, + channel: data.channel, }); - } else if (type === "telegram") { + } else if (data.type === "telegram") { await testTelegramConnection({ - botToken: form.getValues("botToken"), - chatId: form.getValues("chatId"), - messageThreadId: form.getValues("messageThreadId") || "", + botToken: data.botToken, + chatId: data.chatId, + messageThreadId: data.messageThreadId || "", }); - } else if (type === "discord") { + } else if (data.type === "discord") { await testDiscordConnection({ - webhookUrl: form.getValues("webhookUrl"), - decoration: form.getValues("decoration"), + webhookUrl: data.webhookUrl, + decoration: data.decoration, }); - } else if (type === "email") { + } else if (data.type === "email") { await testEmailConnection({ - smtpServer: form.getValues("smtpServer"), - smtpPort: form.getValues("smtpPort"), - username: form.getValues("username"), - password: form.getValues("password"), - toAddresses: form.getValues("toAddresses"), - fromAddress: form.getValues("fromAddress"), + smtpServer: data.smtpServer, + smtpPort: data.smtpPort, + username: data.username, + password: data.password, + fromAddress: data.fromAddress, + toAddresses: data.toAddresses, }); - } else if (type === "gotify") { + } else if (data.type === "gotify") { await testGotifyConnection({ - serverUrl: form.getValues("serverUrl"), - appToken: form.getValues("appToken"), - priority: form.getValues("priority"), - decoration: form.getValues("decoration"), + serverUrl: data.serverUrl, + appToken: data.appToken, + priority: data.priority, + decoration: data.decoration, }); - } else if (type === "ntfy") { + } else if (data.type === "ntfy") { await testNtfyConnection({ - serverUrl: form.getValues("serverUrl"), - topic: form.getValues("topic"), - accessToken: form.getValues("accessToken"), - priority: form.getValues("priority"), + serverUrl: data.serverUrl, + topic: data.topic, + accessToken: data.accessToken || "", + priority: data.priority, }); - } else if (type === "lark") { + } else if (data.type === "lark") { await testLarkConnection({ - webhookUrl: form.getValues("webhookUrl"), + webhookUrl: data.webhookUrl, + }); + } else if (data.type === "custom") { + const headersRecord = + data.headers && data.headers.length > 0 + ? data.headers.reduce( + (acc, { key, value }) => { + if (key.trim()) acc[key] = value; + return acc; + }, + {} as Record, + ) + : undefined; + await testCustomConnection({ + endpoint: data.endpoint, + headers: headersRecord, }); } toast.success("Connection Success"); } catch (error) { toast.error( - `Error testing the provider ${error instanceof Error ? error.message : "Unknown error"}`, + `Error testing the provider: ${error instanceof Error ? error.message : "Unknown error"}`, ); } }} diff --git a/apps/dokploy/components/dashboard/settings/notifications/show-notifications.tsx b/apps/dokploy/components/dashboard/settings/notifications/show-notifications.tsx index 5b7a2220ed..06ffd91e42 100644 --- a/apps/dokploy/components/dashboard/settings/notifications/show-notifications.tsx +++ b/apps/dokploy/components/dashboard/settings/notifications/show-notifications.tsx @@ -1,4 +1,4 @@ -import { Bell, Loader2, Mail, Trash2 } from "lucide-react"; +import { Bell, Loader2, Mail, PenBoxIcon, Trash2 } from "lucide-react"; import { toast } from "sonner"; import { DiscordIcon, @@ -96,6 +96,11 @@ export const ShowNotifications = () => {
)} + {notification.notificationType === "custom" && ( +
+ +
+ )} {notification.notificationType === "lark" && (
diff --git a/apps/dokploy/components/dashboard/settings/profile/profile-form.tsx b/apps/dokploy/components/dashboard/settings/profile/profile-form.tsx index 583f3fefe7..47219620f8 100644 --- a/apps/dokploy/components/dashboard/settings/profile/profile-form.tsx +++ b/apps/dokploy/components/dashboard/settings/profile/profile-form.tsx @@ -41,6 +41,7 @@ const profileSchema = z.object({ currentPassword: z.string().nullable(), image: z.string().optional(), name: z.string().optional(), + lastName: z.string().optional(), allowImpersonation: z.boolean().optional().default(false), }); @@ -88,7 +89,8 @@ export const ProfileForm = () => { image: data?.user?.image || "", currentPassword: "", allowImpersonation: data?.user?.allowImpersonation || false, - name: data?.user?.name || "", + name: data?.user?.firstName || "", + lastName: data?.user?.lastName || "", }, resolver: zodResolver(profileSchema), }); @@ -102,7 +104,8 @@ export const ProfileForm = () => { image: data?.user?.image || "", currentPassword: form.getValues("currentPassword") || "", allowImpersonation: data?.user?.allowImpersonation, - name: data?.user?.name || "", + name: data?.user?.firstName || "", + lastName: data?.user?.lastName || "", }, { keepValues: true, @@ -127,6 +130,7 @@ export const ProfileForm = () => { currentPassword: values.currentPassword || undefined, allowImpersonation: values.allowImpersonation, name: values.name || undefined, + lastName: values.lastName || undefined, }); await refetch(); toast.success("Profile Updated"); @@ -136,6 +140,7 @@ export const ProfileForm = () => { image: values.image, currentPassword: "", name: values.name || "", + lastName: values.lastName || "", }); } catch (error) { toast.error("Error updating the profile"); @@ -180,9 +185,22 @@ export const ProfileForm = () => { name="name" render={({ field }) => ( - Name + First Name - + + + + + )} + /> + ( + + Last Name + + @@ -280,7 +298,7 @@ export const ProfileForm = () => { {getFallbackAvatarInitials( - data?.user?.name, + `${data?.user?.firstName} ${data?.user?.lastName}`.trim(), )} diff --git a/apps/dokploy/components/dashboard/settings/servers/actions/show-traefik-actions.tsx b/apps/dokploy/components/dashboard/settings/servers/actions/show-traefik-actions.tsx index d9573ca744..aebba88771 100644 --- a/apps/dokploy/components/dashboard/settings/servers/actions/show-traefik-actions.tsx +++ b/apps/dokploy/components/dashboard/settings/servers/actions/show-traefik-actions.tsx @@ -1,5 +1,7 @@ import { useTranslation } from "next-i18next"; import { toast } from "sonner"; +import { AlertBlock } from "@/components/shared/alert-block"; +import { DialogAction } from "@/components/shared/dialog-action"; import { Button } from "@/components/ui/button"; import { DropdownMenu, @@ -85,7 +87,26 @@ export const ShowTraefikActions = ({ serverId }: Props) => { - + + The Traefik container will be recreated from scratch. This + means the container will be deleted and created again, which + may cause downtime in your applications. + +

+ Are you sure you want to{" "} + {haveTraefikDashboardPortEnabled ? "disable" : "enable"} the + Traefik dashboard? +

+
+ } onClick={async () => { await toggleDashboard({ enableDashboard: !haveTraefikDashboardPortEnabled, @@ -97,14 +118,26 @@ export const ShowTraefikActions = ({ serverId }: Props) => { ); refetchDashboard(); }) - .catch(() => {}); + .catch((error) => { + const errorMessage = + error?.message || + "Failed to toggle dashboard. Please check if port 8080 is available."; + toast.error(errorMessage); + }); }} - className="w-full cursor-pointer space-x-3" + disabled={toggleDashboardIsLoading} + type="default" > - - {haveTraefikDashboardPortEnabled ? "Disable" : "Enable"} Dashboard - - + e.preventDefault()} + className="w-full cursor-pointer space-x-3" + > + + {haveTraefikDashboardPortEnabled ? "Disable" : "Enable"}{" "} + Dashboard + + + e.preventDefault()} diff --git a/apps/dokploy/components/dashboard/settings/servers/handle-servers.tsx b/apps/dokploy/components/dashboard/settings/servers/handle-servers.tsx index cdbe8a95b3..b36aec7c43 100644 --- a/apps/dokploy/components/dashboard/settings/servers/handle-servers.tsx +++ b/apps/dokploy/components/dashboard/settings/servers/handle-servers.tsx @@ -52,6 +52,7 @@ const Schema = z.object({ sshKeyId: z.string().min(1, { message: "SSH Key is required", }), + serverType: z.enum(["deploy", "build"]).default("deploy"), }); type Schema = z.infer; @@ -89,6 +90,7 @@ export const HandleServers = ({ serverId }: Props) => { port: 22, username: "root", sshKeyId: "", + serverType: "deploy", }, resolver: zodResolver(Schema), }); @@ -101,6 +103,7 @@ export const HandleServers = ({ serverId }: Props) => { port: data?.port || 22, username: data?.username || "root", sshKeyId: data?.sshKeyId || "", + serverType: data?.serverType || "deploy", }); }, [form, form.reset, form.formState.isSubmitSuccessful, data]); @@ -116,6 +119,7 @@ export const HandleServers = ({ serverId }: Props) => { port: data.port || 22, username: data.username || "root", sshKeyId: data.sshKeyId || "", + serverType: data.serverType || "deploy", serverId: serverId || "", }) .then(async (_data) => { @@ -266,6 +270,50 @@ export const HandleServers = ({ serverId }: Props) => { )} /> + { + const serverTypeValue = form.watch("serverType"); + return ( + + 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. + + )} + + ); + }} + /> { const [activeLog, setActiveLog] = useState(null); const { data: isCloud } = api.settings.isCloud.useQuery(); + const isBuildServer = server?.serverType === "build"; const [isDrawerOpen, setIsDrawerOpen] = useState(false); const [filteredLogs, setFilteredLogs] = useState([]); const [isDeploying, setIsDeploying] = useState(false); @@ -117,17 +118,26 @@ export const SetupServer = ({ serverId }: Props) => { SSH Keys Deployments Validate - Security - {isCloud && ( - Monitoring + + {!isBuildServer && ( + <> + Security + {isCloud && ( + Monitoring + )} + GPU Setup + )} - GPU Setup { - -
- -
-
- -
-
- -
-
-
- -
- -
-
+ {!isBuildServer && ( + <> + +
+ +
+
+ +
+
+ +
+
+
+ +
+ +
+
+ + )} )} diff --git a/apps/dokploy/components/dashboard/settings/servers/show-servers.tsx b/apps/dokploy/components/dashboard/settings/servers/show-servers.tsx index 191aab9ced..2f8ac24e27 100644 --- a/apps/dokploy/components/dashboard/settings/servers/show-servers.tsx +++ b/apps/dokploy/components/dashboard/settings/servers/show-servers.tsx @@ -129,6 +129,9 @@ export const ShowServers = () => { Status )} + + Type + IP Address @@ -153,6 +156,8 @@ export const ShowServers = () => { {data?.map((server) => { const canDelete = server.totalSum === 0; const isActive = server.serverStatus === "active"; + const isBuildServer = + server.serverType === "build"; return ( @@ -171,6 +176,15 @@ export const ShowServers = () => { )} + + + {server.serverType} + + {server.ipAddress} @@ -233,11 +247,12 @@ export const ShowServers = () => { serverId={server.serverId} /> - {server.sshKeyId && ( - - )} + {server.sshKeyId && + !isBuildServer && ( + + )} )} @@ -286,41 +301,43 @@ export const ShowServers = () => {
- {isActive && server.sshKeyId && ( - <> - - - Extra - + {isActive && + server.sshKeyId && + !isBuildServer && ( + <> + + + Extra + - - - {isCloud && ( - - )} + + {isCloud && ( + + )} - - + + - - - )} + + + )} diff --git a/apps/dokploy/components/dashboard/settings/servers/validate-server.tsx b/apps/dokploy/components/dashboard/settings/servers/validate-server.tsx index c09753f3e7..5aaf154fda 100644 --- a/apps/dokploy/components/dashboard/settings/servers/validate-server.tsx +++ b/apps/dokploy/components/dashboard/settings/servers/validate-server.tsx @@ -25,6 +25,13 @@ export const ValidateServer = ({ serverId }: Props) => { enabled: !!serverId, }, ); + const { data: server } = api.server.one.useQuery( + { serverId }, + { + enabled: !!serverId, + }, + ); + const isBuildServer = server?.serverType === "build"; const _utils = api.useUtils(); return ( @@ -73,7 +80,9 @@ export const ValidateServer = ({ serverId }: Props) => {

Status

- Shows the server configuration status + {isBuildServer + ? "Shows the build server configuration status" + : "Shows the server configuration status"}

{ : undefined } /> - + {!isBuildServer && ( + + )} { } /> - + {!isBuildServer && ( + <> + + + + )} { : "Not Created" } /> -
diff --git a/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/create-server.tsx b/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/create-server.tsx index 0141aca08c..1f463a18fb 100644 --- a/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/create-server.tsx +++ b/apps/dokploy/components/dashboard/settings/servers/welcome-stripe/create-server.tsx @@ -95,6 +95,7 @@ export const CreateServer = ({ stepper }: Props) => { port: data.port || 22, username: data.username || "root", sshKeyId: data.sshKeyId || "", + serverType: "deploy", }) .then(async (_data) => { toast.success("Server Created"); diff --git a/apps/dokploy/components/dashboard/settings/users/add-invitation.tsx b/apps/dokploy/components/dashboard/settings/users/add-invitation.tsx index 6e03845549..e778f2e96f 100644 --- a/apps/dokploy/components/dashboard/settings/users/add-invitation.tsx +++ b/apps/dokploy/components/dashboard/settings/users/add-invitation.tsx @@ -158,6 +158,7 @@ export const AddInvitation = () => { Member + Admin diff --git a/apps/dokploy/components/dashboard/settings/users/change-role.tsx b/apps/dokploy/components/dashboard/settings/users/change-role.tsx new file mode 100644 index 0000000000..93dc4dfc04 --- /dev/null +++ b/apps/dokploy/components/dashboard/settings/users/change-role.tsx @@ -0,0 +1,159 @@ +import { zodResolver } from "@hookform/resolvers/zod"; +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 { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, +} from "@/components/ui/dialog"; +import { DropdownMenuItem } from "@/components/ui/dropdown-menu"; +import { + Form, + FormControl, + FormDescription, + FormField, + FormItem, + FormLabel, + FormMessage, +} from "@/components/ui/form"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { api } from "@/utils/api"; + +const changeRoleSchema = z.object({ + role: z.enum(["admin", "member"]), +}); + +type ChangeRoleSchema = z.infer; + +interface Props { + memberId: string; + currentRole: "admin" | "member"; + userEmail: string; +} + +export const ChangeRole = ({ memberId, currentRole, userEmail }: Props) => { + const [isOpen, setIsOpen] = useState(false); + const utils = api.useUtils(); + + const { mutateAsync, isError, error, isLoading } = + api.organization.updateMemberRole.useMutation(); + + const form = useForm({ + defaultValues: { + role: currentRole, + }, + resolver: zodResolver(changeRoleSchema), + }); + + useEffect(() => { + if (isOpen) { + form.reset({ + role: currentRole, + }); + } + }, [form, currentRole, isOpen]); + + const onSubmit = async (data: ChangeRoleSchema) => { + await mutateAsync({ + memberId, + role: data.role, + }) + .then(async () => { + toast.success("Role updated successfully"); + await utils.user.all.invalidate(); + setIsOpen(false); + }) + .catch((error) => { + toast.error(error?.message || "Error updating role"); + }); + }; + + return ( + + + e.preventDefault()} + > + Change Role + + + + + Change User Role + + Change the role for {userEmail} + + + {isError && {error?.message}} + + + + ( + + Role + + + Admin: Can manage users and settings. +
+ Member: Limited permissions, can be + customized. +
+ + Note: Owner role is intransferible. + +
+ +
+ )} + /> + + + + + + +
+
+ ); +}; diff --git a/apps/dokploy/components/dashboard/settings/users/show-users.tsx b/apps/dokploy/components/dashboard/settings/users/show-users.tsx index 06c94416b0..a52cfda6dd 100644 --- a/apps/dokploy/components/dashboard/settings/users/show-users.tsx +++ b/apps/dokploy/components/dashboard/settings/users/show-users.tsx @@ -29,12 +29,15 @@ import { import { authClient } from "@/lib/auth-client"; import { api } from "@/utils/api"; import { AddUserPermissions } from "./add-permissions"; +import { ChangeRole } from "./change-role"; export const ShowUsers = () => { const { data: isCloud } = api.settings.isCloud.useQuery(); const { data, isLoading, refetch } = api.user.all.useQuery(); const { mutateAsync } = api.user.remove.useMutation(); + const utils = api.useUtils(); + const { data: session } = authClient.useSession(); return (
@@ -81,6 +84,52 @@ export const ShowUsers = () => { {data?.map((member) => { + const currentUserRole = data?.find( + (m) => m.user.id === session?.user?.id, + )?.role; + + // Owner never has "Edit Permissions" (they're absolute owner) + // Other users can edit permissions if target is not themselves and target is a member + const canEditPermissions = + member.role !== "owner" && + member.role === "member" && + member.user.id !== session?.user?.id; + + // Can change role based on hierarchy: + // - Owner: Can change anyone's role (except themselves and other owners) + // - Admin: Can only change member roles (not other admins or owners) + // - Owner role is intransferible + const canChangeRole = + member.role !== "owner" && + member.user.id !== session?.user?.id && + (currentUserRole === "owner" || + (currentUserRole === "admin" && + member.role === "member")); + + // Delete/Unlink follow same hierarchy as role changes + // - Owner: Can delete/unlink anyone (except themselves and owner can't be deleted) + // - Admin: Can only delete/unlink members (not other admins or owner) + const canDelete = + member.role !== "owner" && + !isCloud && + member.user.id !== session?.user?.id && + (currentUserRole === "owner" || + (currentUserRole === "admin" && + member.role === "member")); + + const canUnlink = + member.role !== "owner" && + member.user.id !== session?.user?.id && + (currentUserRole === "owner" || + (currentUserRole === "admin" && + member.role === "member")); + + const hasAnyAction = + canEditPermissions || + canChangeRole || + canDelete || + canUnlink; + return ( @@ -109,7 +158,7 @@ export const ShowUsers = () => { - {member.role !== "owner" && ( + {hasAnyAction ? ( )} diff --git a/apps/dokploy/components/dashboard/settings/web-domain.tsx b/apps/dokploy/components/dashboard/settings/web-domain.tsx index 51cb7af3ef..c889708c3d 100644 --- a/apps/dokploy/components/dashboard/settings/web-domain.tsx +++ b/apps/dokploy/components/dashboard/settings/web-domain.tsx @@ -36,7 +36,7 @@ import { api } from "@/utils/api"; const addServerDomain = z .object({ - domain: z.string(), + domain: z.string().trim().toLowerCase(), letsEncryptEmail: z.string(), https: z.boolean().optional(), certificateType: z.enum(["letsencrypt", "none", "custom"]), @@ -49,7 +49,11 @@ const addServerDomain = z message: "Required", }); } - if (data.certificateType === "letsencrypt" && !data.letsEncryptEmail) { + if ( + data.https && + data.certificateType === "letsencrypt" && + !data.letsEncryptEmail + ) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: diff --git a/apps/dokploy/components/dashboard/settings/web-server/manage-traefik-ports.tsx b/apps/dokploy/components/dashboard/settings/web-server/manage-traefik-ports.tsx index 282f1fddd3..3ce95aa1f4 100644 --- a/apps/dokploy/components/dashboard/settings/web-server/manage-traefik-ports.tsx +++ b/apps/dokploy/components/dashboard/settings/web-server/manage-traefik-ports.tsx @@ -105,7 +105,9 @@ export const ManageTraefikPorts = ({ children, serverId }: Props) => { }); toast.success(t("settings.server.webServer.traefik.portsUpdated")); setOpen(false); - } catch {} + } catch (error) { + toast.error((error as Error).message || "Error updating Traefik ports"); + } }; return ( @@ -156,11 +158,11 @@ export const ManageTraefikPorts = ({ children, serverId }: Props) => {

) : ( - +
{fields.map((field, index) => ( - + {
)} + + + The Traefik container will be recreated from scratch. This + means the container will be deleted and created again, which + may cause downtime in your applications. +