mirror of
https://github.com/Dokploy/dokploy.git
synced 2026-07-22 14:25:24 +02:00
Merge branch 'canary' into feat/add-network-management
This commit is contained in:
@@ -22,6 +22,9 @@ export const user = pgTable("user", {
|
||||
.notNull(),
|
||||
twoFactorEnabled: boolean("two_factor_enabled").default(false),
|
||||
role: text("role"),
|
||||
banned: boolean("banned").default(false),
|
||||
banReason: text("ban_reason"),
|
||||
banExpires: timestamp("ban_expires"),
|
||||
ownerId: text("owner_id"),
|
||||
allowImpersonation: boolean("allow_impersonation").default(false),
|
||||
lastName: text("last_name").default(""),
|
||||
@@ -45,6 +48,7 @@ export const session = pgTable(
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
activeOrganizationId: text("active_organization_id"),
|
||||
impersonatedBy: text("impersonated_by"),
|
||||
},
|
||||
(table) => [index("session_userId_idx").on(table.userId)],
|
||||
);
|
||||
@@ -142,6 +146,9 @@ export const twoFactor = pgTable(
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
verified: boolean("verified").default(true),
|
||||
failedVerificationCount: integer("failed_verification_count").default(0),
|
||||
lockedUntil: timestamp("locked_until"),
|
||||
},
|
||||
(table) => [
|
||||
index("twoFactor_secret_idx").on(table.secret),
|
||||
@@ -223,6 +230,13 @@ export const invitation = pgTable(
|
||||
],
|
||||
);
|
||||
|
||||
export const scimProvider = pgTable("scim_provider", {
|
||||
id: text("id").primaryKey(),
|
||||
providerId: text("provider_id").notNull().unique(),
|
||||
scimToken: text("scim_token").notNull().unique(),
|
||||
organizationId: text("organization_id"),
|
||||
});
|
||||
|
||||
export const userRelations = relations(user, ({ many }) => ({
|
||||
sessions: many(session),
|
||||
accounts: many(account),
|
||||
|
||||
@@ -37,35 +37,35 @@
|
||||
"@ai-sdk/mistral": "^3.0.20",
|
||||
"@ai-sdk/openai": "^3.0.29",
|
||||
"@ai-sdk/openai-compatible": "^2.0.30",
|
||||
"@better-auth/api-key": "1.5.4",
|
||||
"@better-auth/sso": "1.5.4",
|
||||
"@better-auth/utils": "0.3.1",
|
||||
"@better-auth/api-key": "1.6.23",
|
||||
"@better-auth/scim": "1.6.23",
|
||||
"@better-auth/sso": "1.6.23",
|
||||
"@better-auth/utils": "0.4.2",
|
||||
"@faker-js/faker": "^8.4.1",
|
||||
"@octokit/auth-app": "^6.1.3",
|
||||
"@octokit/rest": "^20.1.2",
|
||||
"@oslojs/crypto": "1.0.1",
|
||||
"@oslojs/encoding": "1.1.0",
|
||||
"@react-email/components": "^0.0.21",
|
||||
"@react-email/components": "^1.0.12",
|
||||
"@trpc/server": "11.10.0",
|
||||
"adm-zip": "^0.5.16",
|
||||
"ai": "^6.0.86",
|
||||
"ai-sdk-ollama": "^3.7.0",
|
||||
"bcrypt": "5.1.1",
|
||||
"better-auth": "1.5.4",
|
||||
"better-call": "2.0.2",
|
||||
"better-auth": "1.6.23",
|
||||
"bl": "6.0.11",
|
||||
"boxen": "^7.1.1",
|
||||
"date-fns": "3.6.0",
|
||||
"dockerode": "4.0.2",
|
||||
"dotenv": "16.4.5",
|
||||
"drizzle-dbml-generator": "0.10.0",
|
||||
"drizzle-orm": "0.45.1",
|
||||
"drizzle-orm": "0.45.2",
|
||||
"drizzle-zod": "0.5.1",
|
||||
"lodash": "4.17.21",
|
||||
"micromatch": "4.0.8",
|
||||
"nanoid": "3.3.11",
|
||||
"node-os-utils": "2.0.1",
|
||||
"node-pty": "1.0.0",
|
||||
"node-pty": "1.1.0",
|
||||
"node-schedule": "2.1.1",
|
||||
"nodemailer": "6.9.14",
|
||||
"octokit": "3.1.2",
|
||||
@@ -74,20 +74,19 @@
|
||||
"postgres": "3.4.4",
|
||||
"public-ip": "6.0.2",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "18.2.0",
|
||||
"react-dom": "18.2.0",
|
||||
"react": "19.2.7",
|
||||
"react-dom": "19.2.7",
|
||||
"resend": "^6.0.2",
|
||||
"semver": "7.7.3",
|
||||
"shell-quote": "^1.8.1",
|
||||
"slugify": "^1.6.6",
|
||||
"ssh2": "1.15.0",
|
||||
"ssh2": "~1.16.0",
|
||||
"toml": "3.0.0",
|
||||
"ws": "8.16.0",
|
||||
"yaml": "2.8.1",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@better-auth/cli": "1.4.21",
|
||||
"@types/adm-zip": "^0.5.7",
|
||||
"@types/bcrypt": "5.0.2",
|
||||
"@types/dockerode": "3.3.23",
|
||||
@@ -97,8 +96,8 @@
|
||||
"@types/node-schedule": "2.1.6",
|
||||
"@types/nodemailer": "^6.4.17",
|
||||
"@types/qrcode": "^1.5.5",
|
||||
"@types/react": "^18.3.5",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"@types/react": "^19.2.0",
|
||||
"@types/react-dom": "^19.2.0",
|
||||
"@types/semver": "7.7.1",
|
||||
"@types/shell-quote": "^1.7.5",
|
||||
"@types/ssh2": "1.15.1",
|
||||
@@ -110,7 +109,7 @@
|
||||
"rimraf": "6.1.3",
|
||||
"tailwindcss": "^3.4.17",
|
||||
"tsc-alias": "1.8.10",
|
||||
"tsx": "^4.16.2",
|
||||
"tsx": "^4.22.4",
|
||||
"typescript": "^5.8.3"
|
||||
},
|
||||
"packageManager": "pnpm@10.22.0",
|
||||
|
||||
@@ -81,12 +81,17 @@ const getDockerConfig = (): Docker => {
|
||||
return new Docker({ ...versionOption });
|
||||
};
|
||||
|
||||
export const docker = getDockerConfig();
|
||||
// Igual que db: el módulo se evalúa una vez por copia bundleada, el cache
|
||||
// evita crear un cliente (y loguear la detección del socket) por cada una.
|
||||
const globalForDocker = globalThis as unknown as {
|
||||
docker?: Docker;
|
||||
};
|
||||
|
||||
// When not set, use the legacy default so 2FA remains working for users who
|
||||
// enabled it before BETTER_AUTH_SECRET was introduced.
|
||||
export const BETTER_AUTH_SECRET =
|
||||
process.env.BETTER_AUTH_SECRET || "better-auth-secret-123456789";
|
||||
if (!globalForDocker.docker) {
|
||||
globalForDocker.docker = getDockerConfig();
|
||||
}
|
||||
|
||||
export const docker = globalForDocker.docker;
|
||||
|
||||
export const paths = (isServer = false) => {
|
||||
const BASE_PATH =
|
||||
|
||||
@@ -9,7 +9,7 @@ export const {
|
||||
POSTGRES_PORT = "5432",
|
||||
} = process.env;
|
||||
|
||||
function readSecret(path: string): string {
|
||||
export function readSecret(path: string): string {
|
||||
try {
|
||||
return fs.readFileSync(path, "utf8").trim();
|
||||
} catch {
|
||||
|
||||
@@ -9,32 +9,19 @@ export * from "./schema";
|
||||
|
||||
type Database = PostgresJsDatabase<typeof schema>;
|
||||
|
||||
/**
|
||||
* Evita problemas de redeclaración global en monorepos.
|
||||
* No usamos `declare global`.
|
||||
*/
|
||||
// Este módulo se evalúa varias veces por proceso (copias duplicadas por
|
||||
// esbuild y los chunks de Next); el cache en globalThis garantiza un solo
|
||||
// pool de conexiones por proceso.
|
||||
const globalForDb = globalThis as unknown as {
|
||||
db?: Database;
|
||||
};
|
||||
|
||||
let dbConnection: Database;
|
||||
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
// En producción no usamos global cache
|
||||
dbConnection = drizzle(postgres(dbUrl), {
|
||||
if (!globalForDb.db) {
|
||||
globalForDb.db = drizzle(postgres(dbUrl), {
|
||||
schema,
|
||||
});
|
||||
} else {
|
||||
// En desarrollo reutilizamos conexión para evitar múltiples conexiones
|
||||
if (!globalForDb.db) {
|
||||
globalForDb.db = drizzle(postgres(dbUrl), {
|
||||
schema,
|
||||
});
|
||||
}
|
||||
|
||||
dbConnection = globalForDb.db;
|
||||
}
|
||||
|
||||
export const db: Database = dbConnection;
|
||||
export const db: Database = globalForDb.db;
|
||||
|
||||
export { dbUrl };
|
||||
|
||||
@@ -216,6 +216,11 @@ export const twoFactor = pgTable("two_factor", {
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => user.id, { onDelete: "cascade" }),
|
||||
verified: boolean("verified").notNull().default(true),
|
||||
failedVerificationCount: integer("failed_verification_count")
|
||||
.notNull()
|
||||
.default(0),
|
||||
lockedUntil: timestamp("locked_until"),
|
||||
});
|
||||
|
||||
export const apikey = pgTable("apikey", {
|
||||
|
||||
@@ -54,6 +54,15 @@ export const apiUpdateAi = createSchema
|
||||
})
|
||||
.omit({ organizationId: true });
|
||||
|
||||
export const aiCustomProviderSchema = z.object({
|
||||
name: z.string().min(1, { message: "Name is required" }),
|
||||
apiUrl: z.string().url({ message: "Please enter a valid URL" }),
|
||||
});
|
||||
|
||||
export const apiSaveAiCustomProviders = z.object({
|
||||
providers: z.array(aiCustomProviderSchema),
|
||||
});
|
||||
|
||||
export const deploySuggestionSchema = z.object({
|
||||
environmentId: z.string().min(1),
|
||||
id: z.string().min(1),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { VALID_BRANCH_REGEX } from "@dokploy/server/utils/git-branch-validation";
|
||||
import { relations } from "drizzle-orm";
|
||||
import {
|
||||
bigint,
|
||||
@@ -50,7 +51,12 @@ import {
|
||||
UpdateConfigSwarmSchema,
|
||||
} from "./shared";
|
||||
import { sshKeys } from "./ssh-key";
|
||||
import { APP_NAME_MESSAGE, APP_NAME_REGEX, generateAppName } from "./utils";
|
||||
import {
|
||||
APP_NAME_MESSAGE,
|
||||
APP_NAME_REGEX,
|
||||
encryptedText,
|
||||
generateAppName,
|
||||
} from "./utils";
|
||||
export const sourceType = pgEnum("sourceType", [
|
||||
"docker",
|
||||
"git",
|
||||
@@ -81,11 +87,11 @@ export const applications = pgTable("application", {
|
||||
.$defaultFn(() => generateAppName("app"))
|
||||
.unique(),
|
||||
description: text("description"),
|
||||
env: text("env"),
|
||||
previewEnv: text("previewEnv"),
|
||||
env: encryptedText("env"),
|
||||
previewEnv: encryptedText("previewEnv"),
|
||||
watchPaths: text("watchPaths").array(),
|
||||
previewBuildArgs: text("previewBuildArgs"),
|
||||
previewBuildSecrets: text("previewBuildSecrets"),
|
||||
previewBuildArgs: encryptedText("previewBuildArgs"),
|
||||
previewBuildSecrets: encryptedText("previewBuildSecrets"),
|
||||
previewLabels: text("previewLabels").array(),
|
||||
previewWildcard: text("previewWildcard"),
|
||||
previewPort: integer("previewPort").default(3000),
|
||||
@@ -104,8 +110,8 @@ export const applications = pgTable("application", {
|
||||
"previewRequireCollaboratorPermissions",
|
||||
).default(true),
|
||||
rollbackActive: boolean("rollbackActive").default(false),
|
||||
buildArgs: text("buildArgs"),
|
||||
buildSecrets: text("buildSecrets"),
|
||||
buildArgs: encryptedText("buildArgs"),
|
||||
buildSecrets: encryptedText("buildSecrets"),
|
||||
memoryReservation: text("memoryReservation"),
|
||||
memoryLimit: text("memoryLimit"),
|
||||
cpuReservation: text("cpuReservation"),
|
||||
@@ -434,17 +440,22 @@ export const apiSaveBuildType = createSchema
|
||||
.required()
|
||||
.merge(createSchema.pick({ publishDirectory: true, isStaticSpa: true }));
|
||||
|
||||
const branchField = z
|
||||
.string()
|
||||
.min(1)
|
||||
.regex(VALID_BRANCH_REGEX, "Invalid branch name");
|
||||
|
||||
export const apiSaveGithubProvider = createSchema
|
||||
.pick({
|
||||
applicationId: true,
|
||||
repository: true,
|
||||
branch: true,
|
||||
owner: true,
|
||||
buildPath: true,
|
||||
githubId: true,
|
||||
})
|
||||
.required()
|
||||
.extend({
|
||||
branch: branchField,
|
||||
triggerType: z.enum(["push", "tag"]).default("push"),
|
||||
})
|
||||
.required()
|
||||
@@ -453,7 +464,6 @@ export const apiSaveGithubProvider = createSchema
|
||||
export const apiSaveGitlabProvider = createSchema
|
||||
.pick({
|
||||
applicationId: true,
|
||||
gitlabBranch: true,
|
||||
gitlabBuildPath: true,
|
||||
gitlabOwner: true,
|
||||
gitlabRepository: true,
|
||||
@@ -462,11 +472,11 @@ export const apiSaveGitlabProvider = createSchema
|
||||
gitlabPathNamespace: true,
|
||||
})
|
||||
.required()
|
||||
.extend({ gitlabBranch: branchField })
|
||||
.merge(createSchema.pick({ enableSubmodules: true, watchPaths: true }));
|
||||
|
||||
export const apiSaveBitbucketProvider = createSchema
|
||||
.pick({
|
||||
bitbucketBranch: true,
|
||||
bitbucketBuildPath: true,
|
||||
bitbucketOwner: true,
|
||||
bitbucketRepository: true,
|
||||
@@ -475,18 +485,19 @@ export const apiSaveBitbucketProvider = createSchema
|
||||
applicationId: true,
|
||||
})
|
||||
.required()
|
||||
.extend({ bitbucketBranch: branchField })
|
||||
.merge(createSchema.pick({ enableSubmodules: true, watchPaths: true }));
|
||||
|
||||
export const apiSaveGiteaProvider = createSchema
|
||||
.pick({
|
||||
applicationId: true,
|
||||
giteaBranch: true,
|
||||
giteaBuildPath: true,
|
||||
giteaOwner: true,
|
||||
giteaRepository: true,
|
||||
giteaId: true,
|
||||
})
|
||||
.required()
|
||||
.extend({ giteaBranch: branchField })
|
||||
.merge(createSchema.pick({ enableSubmodules: true, watchPaths: true }));
|
||||
|
||||
export const apiSaveDockerProvider = createSchema
|
||||
@@ -501,7 +512,6 @@ export const apiSaveDockerProvider = createSchema
|
||||
|
||||
export const apiSaveGitProvider = createSchema
|
||||
.pick({
|
||||
customGitBranch: true,
|
||||
applicationId: true,
|
||||
customGitBuildPath: true,
|
||||
customGitUrl: true,
|
||||
@@ -509,6 +519,7 @@ export const apiSaveGitProvider = createSchema
|
||||
enableSubmodules: true,
|
||||
})
|
||||
.required()
|
||||
.extend({ customGitBranch: branchField })
|
||||
.merge(
|
||||
createSchema.pick({
|
||||
customGitSSHKeyId: true,
|
||||
|
||||
@@ -50,6 +50,7 @@ export const backups = pgTable("backup", {
|
||||
.notNull()
|
||||
.references(() => destinations.destinationId, { onDelete: "cascade" }),
|
||||
keepLatestCount: integer("keepLatestCount"),
|
||||
includeEncryptionKey: boolean("includeEncryptionKey").notNull().default(true),
|
||||
backupType: backupType("backupType").notNull().default("database"),
|
||||
databaseType: databaseType("databaseType").notNull(),
|
||||
composeId: text("composeId").references(
|
||||
@@ -160,6 +161,7 @@ const createSchema = createInsertSchema(backups, {
|
||||
mongoId: z.string().optional(),
|
||||
libsqlId: z.string().optional(),
|
||||
userId: z.string().optional(),
|
||||
includeEncryptionKey: z.boolean().optional(),
|
||||
metadata: z.any().optional(),
|
||||
});
|
||||
|
||||
@@ -180,6 +182,7 @@ export const apiCreateBackup = createSchema.pick({
|
||||
backupType: true,
|
||||
composeId: true,
|
||||
serviceName: true,
|
||||
includeEncryptionKey: true,
|
||||
metadata: true,
|
||||
});
|
||||
|
||||
@@ -206,7 +209,10 @@ export const apiUpdateBackup = createSchema
|
||||
metadata: true,
|
||||
databaseType: true,
|
||||
})
|
||||
.required();
|
||||
.required()
|
||||
.extend({
|
||||
includeEncryptionKey: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const apiRestoreBackup = z.object({
|
||||
databaseId: z.string(),
|
||||
|
||||
@@ -17,7 +17,12 @@ import { schedules } from "./schedule";
|
||||
import { server } from "./server";
|
||||
import { applicationStatus, triggerType } from "./shared";
|
||||
import { sshKeys } from "./ssh-key";
|
||||
import { APP_NAME_MESSAGE, APP_NAME_REGEX, generateAppName } from "./utils";
|
||||
import {
|
||||
APP_NAME_MESSAGE,
|
||||
APP_NAME_REGEX,
|
||||
encryptedText,
|
||||
generateAppName,
|
||||
} from "./utils";
|
||||
export const sourceTypeCompose = pgEnum("sourceTypeCompose", [
|
||||
"git",
|
||||
"github",
|
||||
@@ -39,7 +44,7 @@ export const compose = pgTable("compose", {
|
||||
.notNull()
|
||||
.$defaultFn(() => generateAppName("compose")),
|
||||
description: text("description"),
|
||||
env: text("env"),
|
||||
env: encryptedText("env"),
|
||||
composeFile: text("composeFile").notNull().default(""),
|
||||
refreshToken: text("refreshToken").$defaultFn(() => nanoid()),
|
||||
sourceType: sourceTypeCompose("sourceType").notNull().default("github"),
|
||||
|
||||
@@ -55,6 +55,7 @@ export const domains = pgTable("domain", {
|
||||
internalPath: text("internalPath").default("/"),
|
||||
stripPath: boolean("stripPath").notNull().default(false),
|
||||
middlewares: text("middlewares").array().default(sql`ARRAY[]::text[]`),
|
||||
forwardAuthEnabled: boolean("forwardAuthEnabled").notNull().default(false),
|
||||
});
|
||||
|
||||
export const domainsRelations = relations(domains, ({ one }) => ({
|
||||
@@ -94,6 +95,7 @@ export const apiCreateDomain = createSchema.pick({
|
||||
internalPath: true,
|
||||
stripPath: true,
|
||||
middlewares: true,
|
||||
forwardAuthEnabled: true,
|
||||
});
|
||||
|
||||
export const apiFindDomain = z.object({
|
||||
@@ -126,5 +128,6 @@ export const apiUpdateDomain = createSchema
|
||||
internalPath: true,
|
||||
stripPath: true,
|
||||
middlewares: true,
|
||||
forwardAuthEnabled: true,
|
||||
})
|
||||
.merge(createSchema.pick({ domainId: true }).required());
|
||||
|
||||
@@ -11,6 +11,7 @@ import { mysql } from "./mysql";
|
||||
import { postgres } from "./postgres";
|
||||
import { projects } from "./project";
|
||||
import { redis } from "./redis";
|
||||
import { encryptedText } from "./utils";
|
||||
|
||||
export const environments = pgTable("environment", {
|
||||
environmentId: text("environmentId")
|
||||
@@ -22,7 +23,7 @@ export const environments = pgTable("environment", {
|
||||
createdAt: text("createdAt")
|
||||
.notNull()
|
||||
.$defaultFn(() => new Date().toISOString()),
|
||||
env: text("env").notNull().default(""),
|
||||
env: encryptedText("env").notNull().default(""),
|
||||
projectId: text("projectId")
|
||||
.notNull()
|
||||
.references(() => projects.projectId, { onDelete: "cascade" }),
|
||||
|
||||
75
packages/server/src/db/schema/forward-auth.ts
Normal file
75
packages/server/src/db/schema/forward-auth.ts
Normal file
@@ -0,0 +1,75 @@
|
||||
import { relations } from "drizzle-orm";
|
||||
import { boolean, pgTable, text } from "drizzle-orm/pg-core";
|
||||
import { nanoid } from "nanoid";
|
||||
import { z } from "zod";
|
||||
import { server } from "./server";
|
||||
import { certificateType } from "./shared";
|
||||
import { ssoProvider } from "./sso";
|
||||
|
||||
export const forwardAuthSettings = pgTable("forward_auth_settings", {
|
||||
forwardAuthSettingsId: text("forwardAuthSettingsId")
|
||||
.notNull()
|
||||
.primaryKey()
|
||||
.$defaultFn(() => nanoid()),
|
||||
authDomain: text("authDomain").notNull(),
|
||||
baseDomain: text("baseDomain").notNull(),
|
||||
https: boolean("https").notNull().default(true),
|
||||
certificateType: certificateType("certificateType")
|
||||
.notNull()
|
||||
.default("letsencrypt"),
|
||||
customCertResolver: text("customCertResolver"),
|
||||
providerId: text("providerId").references(() => ssoProvider.providerId, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
serverId: text("serverId")
|
||||
.unique()
|
||||
.references(() => server.serverId, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
createdAt: text("createdAt")
|
||||
.notNull()
|
||||
.$defaultFn(() => new Date().toISOString()),
|
||||
});
|
||||
|
||||
export const forwardAuthSettingsRelations = relations(
|
||||
forwardAuthSettings,
|
||||
({ one }) => ({
|
||||
server: one(server, {
|
||||
fields: [forwardAuthSettings.serverId],
|
||||
references: [server.serverId],
|
||||
}),
|
||||
provider: one(ssoProvider, {
|
||||
fields: [forwardAuthSettings.providerId],
|
||||
references: [ssoProvider.providerId],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
const domainRegex = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/;
|
||||
|
||||
export const apiForwardAuthServerTarget = z.object({
|
||||
serverId: z.string().nullable(),
|
||||
});
|
||||
|
||||
export const apiForwardAuthDomainTarget = z.object({
|
||||
domainId: z.string().min(1),
|
||||
});
|
||||
|
||||
export const apiSetForwardAuthSettings = z.object({
|
||||
serverId: z.string().nullable(),
|
||||
authDomain: z
|
||||
.string()
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.refine((v) => domainRegex.test(v), { message: "Invalid auth domain" }),
|
||||
https: z.boolean().default(true),
|
||||
certificateType: z
|
||||
.enum(["none", "letsencrypt", "custom"])
|
||||
.default("letsencrypt"),
|
||||
customCertResolver: z.string().optional(),
|
||||
});
|
||||
|
||||
export const apiDeployForwardAuthOnServer = z.object({
|
||||
serverId: z.string().nullable(),
|
||||
providerId: z.string().min(1),
|
||||
});
|
||||
@@ -10,6 +10,7 @@ export * from "./deployment";
|
||||
export * from "./destination";
|
||||
export * from "./domain";
|
||||
export * from "./environment";
|
||||
export * from "./forward-auth";
|
||||
export * from "./git-provider";
|
||||
export * from "./gitea";
|
||||
export * from "./github";
|
||||
@@ -31,6 +32,7 @@ export * from "./redis";
|
||||
export * from "./registry";
|
||||
export * from "./rollbacks";
|
||||
export * from "./schedule";
|
||||
export * from "./scim";
|
||||
export * from "./security";
|
||||
export * from "./server";
|
||||
export * from "./session";
|
||||
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
import {
|
||||
DATABASE_PASSWORD_MESSAGE,
|
||||
DATABASE_PASSWORD_REGEX,
|
||||
encryptedText,
|
||||
generateAppName,
|
||||
} from "./utils";
|
||||
|
||||
@@ -58,7 +59,7 @@ export const libsql = pgTable("libsql", {
|
||||
enableNamespaces: boolean("enableNamespaces").notNull().default(false),
|
||||
dockerImage: text("dockerImage").notNull(),
|
||||
command: text("command"),
|
||||
env: text("env"),
|
||||
env: encryptedText("env"),
|
||||
// RESOURCES
|
||||
memoryReservation: text("memoryReservation"),
|
||||
memoryLimit: text("memoryLimit"),
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
APP_NAME_REGEX,
|
||||
DATABASE_PASSWORD_MESSAGE,
|
||||
DATABASE_PASSWORD_REGEX,
|
||||
encryptedText,
|
||||
generateAppName,
|
||||
} from "./utils";
|
||||
|
||||
@@ -54,7 +55,7 @@ export const mariadb = pgTable("mariadb", {
|
||||
dockerImage: text("dockerImage").notNull(),
|
||||
command: text("command"),
|
||||
args: text("args").array(),
|
||||
env: text("env"),
|
||||
env: encryptedText("env"),
|
||||
// RESOURCES
|
||||
memoryReservation: text("memoryReservation"),
|
||||
memoryLimit: text("memoryLimit"),
|
||||
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
APP_NAME_REGEX,
|
||||
DATABASE_PASSWORD_MESSAGE,
|
||||
DATABASE_PASSWORD_REGEX,
|
||||
encryptedText,
|
||||
generateAppName,
|
||||
} from "./utils";
|
||||
|
||||
@@ -59,7 +60,7 @@ export const mongo = pgTable("mongo", {
|
||||
dockerImage: text("dockerImage").notNull().default("mongo:8"),
|
||||
command: text("command"),
|
||||
args: text("args").array(),
|
||||
env: text("env"),
|
||||
env: encryptedText("env"),
|
||||
memoryReservation: text("memoryReservation"),
|
||||
memoryLimit: text("memoryLimit"),
|
||||
cpuReservation: text("cpuReservation"),
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
APP_NAME_REGEX,
|
||||
DATABASE_PASSWORD_MESSAGE,
|
||||
DATABASE_PASSWORD_REGEX,
|
||||
encryptedText,
|
||||
generateAppName,
|
||||
} from "./utils";
|
||||
|
||||
@@ -54,7 +55,7 @@ export const mysql = pgTable("mysql", {
|
||||
dockerImage: text("dockerImage").notNull(),
|
||||
command: text("command"),
|
||||
args: text("args").array(),
|
||||
env: text("env"),
|
||||
env: encryptedText("env"),
|
||||
memoryReservation: text("memoryReservation"),
|
||||
memoryLimit: text("memoryLimit"),
|
||||
cpuReservation: text("cpuReservation"),
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
APP_NAME_REGEX,
|
||||
DATABASE_PASSWORD_MESSAGE,
|
||||
DATABASE_PASSWORD_REGEX,
|
||||
encryptedText,
|
||||
generateAppName,
|
||||
} from "./utils";
|
||||
|
||||
@@ -53,7 +54,7 @@ export const postgres = pgTable("postgres", {
|
||||
dockerImage: text("dockerImage").notNull(),
|
||||
command: text("command"),
|
||||
args: text("args").array(),
|
||||
env: text("env"),
|
||||
env: encryptedText("env"),
|
||||
memoryReservation: text("memoryReservation"),
|
||||
externalPort: integer("externalPort"),
|
||||
memoryLimit: text("memoryLimit"),
|
||||
|
||||
@@ -6,6 +6,7 @@ import { z } from "zod";
|
||||
import { organization } from "./account";
|
||||
import { environments } from "./environment";
|
||||
import { projectTags } from "./tag";
|
||||
import { encryptedText } from "./utils";
|
||||
|
||||
export const projects = pgTable("project", {
|
||||
projectId: text("projectId")
|
||||
@@ -21,7 +22,7 @@ export const projects = pgTable("project", {
|
||||
organizationId: text("organizationId")
|
||||
.notNull()
|
||||
.references(() => organization.id, { onDelete: "cascade" }),
|
||||
env: text("env").notNull().default(""),
|
||||
env: encryptedText("env").notNull().default(""),
|
||||
});
|
||||
|
||||
export const projectRelations = relations(projects, ({ many, one }) => ({
|
||||
@@ -37,6 +38,7 @@ const createSchema = createInsertSchema(projects, {
|
||||
projectId: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
description: z.string().optional(),
|
||||
env: z.string().optional(),
|
||||
});
|
||||
|
||||
export const apiCreateProject = createSchema.pick({
|
||||
|
||||
@@ -27,7 +27,12 @@ import {
|
||||
type UpdateConfigSwarm,
|
||||
UpdateConfigSwarmSchema,
|
||||
} from "./shared";
|
||||
import { APP_NAME_MESSAGE, APP_NAME_REGEX, generateAppName } from "./utils";
|
||||
import {
|
||||
APP_NAME_MESSAGE,
|
||||
APP_NAME_REGEX,
|
||||
encryptedText,
|
||||
generateAppName,
|
||||
} from "./utils";
|
||||
|
||||
export const redis = pgTable("redis", {
|
||||
redisId: text("redisId")
|
||||
@@ -44,7 +49,7 @@ export const redis = pgTable("redis", {
|
||||
dockerImage: text("dockerImage").notNull(),
|
||||
command: text("command"),
|
||||
args: text("args").array(),
|
||||
env: text("env"),
|
||||
env: encryptedText("env"),
|
||||
memoryReservation: text("memoryReservation"),
|
||||
memoryLimit: text("memoryLimit"),
|
||||
cpuReservation: text("cpuReservation"),
|
||||
|
||||
@@ -44,11 +44,28 @@ export const registryRelations = relations(registry, ({ many }) => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
// Registry usernames should NOT be lowercased.
|
||||
// Some registries (e.g. AWS ECR) require a specific case: the username must be
|
||||
// exactly "AWS" (uppercase) for ECR authentication. Docker Hub usernames are
|
||||
// case-insensitive for login, so preserving case is safe for all providers.
|
||||
const registryUsernameSchema = z.string().trim().min(1);
|
||||
|
||||
// Registry URLs must be hostname[:port] only — no shell metacharacters
|
||||
// Empty string is allowed (means default/Docker Hub registry)
|
||||
const registryUrlSchema = z
|
||||
.string()
|
||||
.refine(
|
||||
(val) =>
|
||||
val === "" ||
|
||||
/^[a-zA-Z0-9]([a-zA-Z0-9._-]*[a-zA-Z0-9])?(:\d{1,5})?$/.test(val),
|
||||
"Registry URL must be a valid hostname or hostname:port (e.g. registry.example.com or localhost:5000)",
|
||||
);
|
||||
|
||||
const createSchema = createInsertSchema(registry, {
|
||||
registryName: z.string().min(1),
|
||||
username: z.string().min(1),
|
||||
username: registryUsernameSchema,
|
||||
password: z.string().min(1),
|
||||
registryUrl: z.string(),
|
||||
registryUrl: registryUrlSchema,
|
||||
organizationId: z.string().min(1),
|
||||
registryId: z.string().min(1),
|
||||
registryType: z.enum(["cloud"]),
|
||||
@@ -59,9 +76,9 @@ export const apiCreateRegistry = createSchema
|
||||
.pick({})
|
||||
.extend({
|
||||
registryName: z.string().min(1),
|
||||
username: z.string().min(1),
|
||||
username: registryUsernameSchema,
|
||||
password: z.string().min(1),
|
||||
registryUrl: z.string(),
|
||||
registryUrl: registryUrlSchema,
|
||||
registryType: z.enum(["cloud"]),
|
||||
imagePrefix: z.string().nullable().optional(),
|
||||
})
|
||||
@@ -72,9 +89,9 @@ export const apiCreateRegistry = createSchema
|
||||
|
||||
export const apiTestRegistry = createSchema.pick({}).extend({
|
||||
registryName: z.string().optional(),
|
||||
username: z.string().min(1),
|
||||
username: registryUsernameSchema,
|
||||
password: z.string().min(1),
|
||||
registryUrl: z.string(),
|
||||
registryUrl: registryUrlSchema,
|
||||
registryType: z.enum(["cloud"]),
|
||||
imagePrefix: z.string().nullable().optional(),
|
||||
serverId: z.string().optional(),
|
||||
|
||||
@@ -3,11 +3,11 @@ import { boolean, pgEnum, pgTable, text } from "drizzle-orm/pg-core";
|
||||
import { createInsertSchema } from "drizzle-zod";
|
||||
import { nanoid } from "nanoid";
|
||||
import { z } from "zod";
|
||||
import { organization } from "./account";
|
||||
import { applications } from "./application";
|
||||
import { compose } from "./compose";
|
||||
import { deployments } from "./deployment";
|
||||
import { server } from "./server";
|
||||
import { user } from "./user";
|
||||
import { generateAppName } from "./utils";
|
||||
export const shellTypes = pgEnum("shellType", ["bash", "sh"]);
|
||||
|
||||
@@ -24,6 +24,7 @@ export const schedules = pgTable("schedule", {
|
||||
.primaryKey()
|
||||
.$defaultFn(() => nanoid()),
|
||||
name: text("name").notNull(),
|
||||
description: text("description"),
|
||||
cronExpression: text("cronExpression").notNull(),
|
||||
appName: text("appName")
|
||||
.notNull()
|
||||
@@ -45,7 +46,7 @@ export const schedules = pgTable("schedule", {
|
||||
serverId: text("serverId").references(() => server.serverId, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
userId: text("userId").references(() => user.id, {
|
||||
organizationId: text("organizationId").references(() => organization.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
enabled: boolean("enabled").notNull().default(true),
|
||||
@@ -56,6 +57,7 @@ export const schedules = pgTable("schedule", {
|
||||
});
|
||||
|
||||
export type Schedule = typeof schedules.$inferSelect;
|
||||
export type ScheduleType = Schedule["scheduleType"];
|
||||
|
||||
export const schedulesRelations = relations(schedules, ({ one, many }) => ({
|
||||
application: one(applications, {
|
||||
@@ -70,14 +72,16 @@ export const schedulesRelations = relations(schedules, ({ one, many }) => ({
|
||||
fields: [schedules.serverId],
|
||||
references: [server.serverId],
|
||||
}),
|
||||
user: one(user, {
|
||||
fields: [schedules.userId],
|
||||
references: [user.id],
|
||||
organization: one(organization, {
|
||||
fields: [schedules.organizationId],
|
||||
references: [organization.id],
|
||||
}),
|
||||
deployments: many(deployments),
|
||||
}));
|
||||
|
||||
export const createScheduleSchema = createInsertSchema(schedules);
|
||||
export const createScheduleSchema = createInsertSchema(schedules, {
|
||||
scheduleType: z.enum(["application", "compose", "server", "dokploy-server"]),
|
||||
});
|
||||
|
||||
export const updateScheduleSchema = createScheduleSchema.extend({
|
||||
scheduleId: z.string().min(1),
|
||||
|
||||
22
packages/server/src/db/schema/scim.ts
Normal file
22
packages/server/src/db/schema/scim.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { relations } from "drizzle-orm";
|
||||
import { pgTable, text } from "drizzle-orm/pg-core";
|
||||
import { nanoid } from "nanoid";
|
||||
import { organization } from "./account";
|
||||
|
||||
export const scimProvider = pgTable("scim_provider", {
|
||||
id: text("id")
|
||||
.primaryKey()
|
||||
.$defaultFn(() => nanoid()),
|
||||
providerId: text("provider_id").notNull().unique(),
|
||||
scimToken: text("scim_token").notNull().unique(),
|
||||
organizationId: text("organization_id").references(() => organization.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
});
|
||||
|
||||
export const scimProviderRelations = relations(scimProvider, ({ one }) => ({
|
||||
organization: one(organization, {
|
||||
fields: [scimProvider.organizationId],
|
||||
references: [organization.id],
|
||||
}),
|
||||
}));
|
||||
@@ -42,6 +42,7 @@ export const server = pgTable("server", {
|
||||
.notNull()
|
||||
.$defaultFn(() => generateAppName("server")),
|
||||
enableDockerCleanup: boolean("enableDockerCleanup").notNull().default(false),
|
||||
buildsConcurrency: integer("buildsConcurrency").notNull().default(1),
|
||||
createdAt: text("createdAt").notNull(),
|
||||
organizationId: text("organizationId")
|
||||
.notNull()
|
||||
@@ -149,8 +150,12 @@ export const apiCreateServer = createSchema
|
||||
username: true,
|
||||
sshKeyId: true,
|
||||
serverType: true,
|
||||
enableDockerCleanup: true,
|
||||
})
|
||||
.required();
|
||||
.required()
|
||||
.extend({
|
||||
enableDockerCleanup: z.boolean().default(true),
|
||||
});
|
||||
|
||||
export const apiFindOneServer = z.object({
|
||||
serverId: z.string().min(1),
|
||||
@@ -172,12 +177,19 @@ export const apiUpdateServer = createSchema
|
||||
username: true,
|
||||
sshKeyId: true,
|
||||
serverType: true,
|
||||
enableDockerCleanup: true,
|
||||
})
|
||||
.required()
|
||||
.extend({
|
||||
command: z.string().optional(),
|
||||
enableDockerCleanup: z.boolean().default(true),
|
||||
});
|
||||
|
||||
export const apiUpdateServerBuildsConcurrency = z.object({
|
||||
serverId: z.string().min(1),
|
||||
buildsConcurrency: z.number().int().min(1).max(100),
|
||||
});
|
||||
|
||||
export const apiUpdateServerMonitoring = createSchema
|
||||
.pick({
|
||||
serverId: true,
|
||||
|
||||
@@ -10,7 +10,7 @@ export const ssoProvider = pgTable("sso_provider", {
|
||||
oidcConfig: text("oidc_config"),
|
||||
samlConfig: text("saml_config"),
|
||||
providerId: text("provider_id").notNull().unique(),
|
||||
userId: text("user_id").references(() => user.id, { onDelete: "cascade" }),
|
||||
userId: text("user_id").references(() => user.id, { onDelete: "set null" }),
|
||||
organizationId: text("organization_id").references(() => organization.id, {
|
||||
onDelete: "cascade",
|
||||
}),
|
||||
|
||||
@@ -1,7 +1,36 @@
|
||||
import { decryptValue, encryptValue } from "@dokploy/server/lib/encryption";
|
||||
import { generatePassword } from "@dokploy/server/templates";
|
||||
import { faker } from "@faker-js/faker";
|
||||
import { customType } from "drizzle-orm/pg-core";
|
||||
import { customAlphabet } from "nanoid";
|
||||
|
||||
/**
|
||||
* Text column encrypted at rest (AES-256-GCM, key derived from
|
||||
* BETTER_AUTH_SECRET). Legacy plaintext values are passed through on read
|
||||
* and get encrypted the next time they are written.
|
||||
*/
|
||||
export const encryptedText = customType<{ data: string; driverData: string }>({
|
||||
dataType() {
|
||||
return "text";
|
||||
},
|
||||
toDriver(value) {
|
||||
return encryptValue(value);
|
||||
},
|
||||
fromDriver(value) {
|
||||
try {
|
||||
return decryptValue(value);
|
||||
} catch {
|
||||
// Fail open so a key mismatch (e.g. restoring a backup under a
|
||||
// different BETTER_AUTH_SECRET) degrades to showing ciphertext
|
||||
// instead of breaking every query that touches the row.
|
||||
console.error(
|
||||
"Failed to decrypt an encrypted column; returning the raw value. This usually means BETTER_AUTH_SECRET changed after the value was encrypted.",
|
||||
);
|
||||
return value;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const alphabet = "abcdefghijklmnopqrstuvwxyz123456789";
|
||||
|
||||
const customNanoid = customAlphabet(alphabet, 6);
|
||||
@@ -12,6 +41,12 @@ export const APP_NAME_REGEX = /^[a-zA-Z0-9._-]+$/;
|
||||
export const APP_NAME_MESSAGE =
|
||||
"App name can only contain letters, numbers, dots, underscores and hyphens";
|
||||
|
||||
/** Docker volume name: must start alphanumeric, then letters/numbers/._- only. Safe for shell. */
|
||||
export const VOLUME_NAME_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/;
|
||||
|
||||
export const VOLUME_NAME_MESSAGE =
|
||||
"Volume name must start with a letter or number and contain only letters, numbers, dots, underscores and hyphens";
|
||||
|
||||
/** Database password: blocks shell-dangerous characters like $ ! ' " \ / and spaces. */
|
||||
export const DATABASE_PASSWORD_REGEX =
|
||||
/^[a-zA-Z0-9@#%^&*()_+\-=[\]{}|;:,.<>?~`]*$/;
|
||||
|
||||
@@ -14,7 +14,11 @@ import { serviceType } from "./mount";
|
||||
import { mysql } from "./mysql";
|
||||
import { postgres } from "./postgres";
|
||||
import { redis } from "./redis";
|
||||
import { generateAppName } from "./utils";
|
||||
import {
|
||||
generateAppName,
|
||||
VOLUME_NAME_MESSAGE,
|
||||
VOLUME_NAME_REGEX,
|
||||
} from "./utils";
|
||||
|
||||
export const volumeBackups = pgTable("volume_backup", {
|
||||
volumeBackupId: text("volumeBackupId")
|
||||
@@ -113,7 +117,9 @@ export const volumeBackupsRelations = relations(
|
||||
}),
|
||||
);
|
||||
|
||||
export const createVolumeBackupSchema = createInsertSchema(volumeBackups).omit({
|
||||
export const createVolumeBackupSchema = createInsertSchema(volumeBackups, {
|
||||
volumeName: z.string().regex(VOLUME_NAME_REGEX, VOLUME_NAME_MESSAGE),
|
||||
}).omit({
|
||||
volumeBackupId: true,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import { relations } from "drizzle-orm";
|
||||
import { boolean, jsonb, pgTable, text, timestamp } from "drizzle-orm/pg-core";
|
||||
import {
|
||||
boolean,
|
||||
integer,
|
||||
jsonb,
|
||||
pgTable,
|
||||
text,
|
||||
timestamp,
|
||||
} from "drizzle-orm/pg-core";
|
||||
import { createInsertSchema } from "drizzle-zod";
|
||||
import { nanoid } from "nanoid";
|
||||
import { z } from "zod";
|
||||
@@ -96,6 +103,12 @@ export const webServerSettings = pgTable("webServerSettings", {
|
||||
metaTitle: null,
|
||||
footerText: null,
|
||||
}),
|
||||
// Deployment Configuration (self-hosted only)
|
||||
remoteServersOnly: boolean("remoteServersOnly").notNull().default(false),
|
||||
// Concurrent builds on the local web server
|
||||
buildsConcurrency: integer("buildsConcurrency").notNull().default(1),
|
||||
// Auth Configuration (self-hosted only)
|
||||
enforceSSO: boolean("enforceSSO").notNull().default(false),
|
||||
// Cache Cleanup Configuration
|
||||
cleanupCacheApplications: boolean("cleanupCacheApplications")
|
||||
.notNull()
|
||||
@@ -155,6 +168,13 @@ export const apiUpdateWebServerSettings = createSchema.partial().extend({
|
||||
cleanupCacheApplications: z.boolean().optional(),
|
||||
cleanupCacheOnPreviews: z.boolean().optional(),
|
||||
cleanupCacheOnCompose: z.boolean().optional(),
|
||||
remoteServersOnly: z.boolean().optional(),
|
||||
enforceSSO: z.boolean().optional(),
|
||||
buildsConcurrency: z.number().int().min(1).max(100).optional(),
|
||||
});
|
||||
|
||||
export const apiUpdateWebServerBuildsConcurrency = z.object({
|
||||
buildsConcurrency: z.number().int().min(1).max(100),
|
||||
});
|
||||
|
||||
export const apiAssignDomain = z
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
INVALID_HOSTNAME_MESSAGE,
|
||||
VALID_HOSTNAME_REGEX,
|
||||
} from "../../utils/hostname-validation";
|
||||
|
||||
export const domain = z
|
||||
.object({
|
||||
@@ -8,7 +12,10 @@ export const domain = z
|
||||
.refine((val) => val === val.trim(), {
|
||||
message: "Domain name cannot have leading or trailing spaces",
|
||||
})
|
||||
.transform((val) => val.trim()),
|
||||
.transform((val) => val.trim())
|
||||
.refine((val) => VALID_HOSTNAME_REGEX.test(val), {
|
||||
message: INVALID_HOSTNAME_MESSAGE,
|
||||
}),
|
||||
path: z.string().min(1).optional(),
|
||||
internalPath: z.string().optional(),
|
||||
stripPath: z.boolean().optional(),
|
||||
@@ -71,7 +78,10 @@ export const domainCompose = z
|
||||
.refine((val) => val === val.trim(), {
|
||||
message: "Domain name cannot have leading or trailing spaces",
|
||||
})
|
||||
.transform((val) => val.trim()),
|
||||
.transform((val) => val.trim())
|
||||
.refine((val) => VALID_HOSTNAME_REGEX.test(val), {
|
||||
message: INVALID_HOSTNAME_MESSAGE,
|
||||
}),
|
||||
path: z.string().min(1).optional(),
|
||||
internalPath: z.string().optional(),
|
||||
stripPath: z.boolean().optional(),
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
Tailwind,
|
||||
Text,
|
||||
} from "@react-email/components";
|
||||
import { emailTailwindConfig } from "../tailwind-config";
|
||||
|
||||
export type TemplateProps = {
|
||||
projectName: string;
|
||||
@@ -35,17 +36,7 @@ export const BuildFailedEmail = ({
|
||||
<Html>
|
||||
<Head />
|
||||
<Preview>{previewText}</Preview>
|
||||
<Tailwind
|
||||
config={{
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
brand: "#007291",
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Tailwind config={emailTailwindConfig}>
|
||||
<Body className="bg-white my-auto mx-auto font-sans px-2">
|
||||
<Container className="border border-solid border-[#eaeaea] rounded-lg my-[40px] mx-auto p-[20px] max-w-[465px]">
|
||||
<Section className="mt-[32px]">
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
Tailwind,
|
||||
Text,
|
||||
} from "@react-email/components";
|
||||
import { emailTailwindConfig } from "../tailwind-config";
|
||||
|
||||
export type TemplateProps = {
|
||||
projectName: string;
|
||||
@@ -35,17 +36,7 @@ export const BuildSuccessEmail = ({
|
||||
<Html>
|
||||
<Head />
|
||||
<Preview>{previewText}</Preview>
|
||||
<Tailwind
|
||||
config={{
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
brand: "#007291",
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Tailwind config={emailTailwindConfig}>
|
||||
<Body className="bg-white my-auto mx-auto font-sans px-2">
|
||||
<Container className="border border-solid border-[#eaeaea] rounded-lg my-[40px] mx-auto p-[20px] max-w-[465px]">
|
||||
<Section className="mt-[32px]">
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
Tailwind,
|
||||
Text,
|
||||
} from "@react-email/components";
|
||||
import { emailTailwindConfig } from "../tailwind-config";
|
||||
|
||||
export type TemplateProps = {
|
||||
projectName: string;
|
||||
@@ -32,17 +33,7 @@ export const DatabaseBackupEmail = ({
|
||||
return (
|
||||
<Html>
|
||||
<Preview>{previewText}</Preview>
|
||||
<Tailwind
|
||||
config={{
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
brand: "#007291",
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Tailwind config={emailTailwindConfig}>
|
||||
<Head />
|
||||
|
||||
<Body className="bg-white my-auto mx-auto font-sans px-2">
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
Tailwind,
|
||||
Text,
|
||||
} from "@react-email/components";
|
||||
import { emailTailwindConfig } from "../tailwind-config";
|
||||
|
||||
export type TemplateProps = {
|
||||
message: string;
|
||||
@@ -24,17 +25,7 @@ export const DockerCleanupEmail = ({
|
||||
return (
|
||||
<Html>
|
||||
<Preview>{previewText}</Preview>
|
||||
<Tailwind
|
||||
config={{
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
brand: "#007291",
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Tailwind config={emailTailwindConfig}>
|
||||
<Head />
|
||||
|
||||
<Body className="bg-white my-auto mx-auto font-sans px-2">
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
Tailwind,
|
||||
Text,
|
||||
} from "@react-email/components";
|
||||
import { emailTailwindConfig } from "../tailwind-config";
|
||||
|
||||
export type TemplateProps = {
|
||||
type: "error" | "success";
|
||||
@@ -29,17 +30,7 @@ export const DokployBackupEmail = ({
|
||||
return (
|
||||
<Html>
|
||||
<Preview>{previewText}</Preview>
|
||||
<Tailwind
|
||||
config={{
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
brand: "#007291",
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Tailwind config={emailTailwindConfig}>
|
||||
<Head />
|
||||
<Body className="bg-white my-auto mx-auto font-sans px-2">
|
||||
<Container className="border border-solid border-[#eaeaea] rounded-lg my-[40px] mx-auto p-[20px] max-w-[465px]">
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
Tailwind,
|
||||
Text,
|
||||
} from "@react-email/components";
|
||||
import { emailTailwindConfig } from "../tailwind-config";
|
||||
|
||||
export type TemplateProps = {
|
||||
date: string;
|
||||
@@ -22,17 +23,7 @@ export const DokployRestartEmail = ({
|
||||
return (
|
||||
<Html>
|
||||
<Preview>{previewText}</Preview>
|
||||
<Tailwind
|
||||
config={{
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
brand: "#007291",
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Tailwind config={emailTailwindConfig}>
|
||||
<Head />
|
||||
|
||||
<Body className="bg-white my-auto mx-auto font-sans px-2">
|
||||
|
||||
@@ -13,81 +13,86 @@ import {
|
||||
Tailwind,
|
||||
Text,
|
||||
} from "@react-email/components";
|
||||
import { emailTailwindConfig } from "../tailwind-config";
|
||||
|
||||
export type TemplateProps = {
|
||||
email: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
interface VercelInviteUserEmailProps {
|
||||
interface InvitationEmailProps {
|
||||
inviteLink: string;
|
||||
toEmail: string;
|
||||
organizationName: string;
|
||||
}
|
||||
|
||||
export const InvitationEmail = ({
|
||||
inviteLink,
|
||||
toEmail,
|
||||
}: VercelInviteUserEmailProps) => {
|
||||
const previewText = "Join to Dokploy";
|
||||
organizationName = "an organization",
|
||||
}: InvitationEmailProps) => {
|
||||
const previewText = `You've been invited to join ${organizationName} on Dokploy`;
|
||||
return (
|
||||
<Html>
|
||||
<Head />
|
||||
<Preview>{previewText}</Preview>
|
||||
<Tailwind
|
||||
config={{
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
brand: "#007291",
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Body className="bg-white my-auto mx-auto font-sans px-2">
|
||||
<Container className="border border-solid border-[#eaeaea] rounded-lg my-[40px] mx-auto p-[20px] max-w-[465px]">
|
||||
<Section className="mt-[32px]">
|
||||
<Tailwind config={emailTailwindConfig}>
|
||||
<Body className="bg-[#f4f4f5] my-auto mx-auto font-sans">
|
||||
<Container className="my-[40px] mx-auto max-w-[520px]">
|
||||
{/* Header */}
|
||||
<Section className="bg-[#09090b] rounded-t-xl px-[40px] py-[32px] text-center">
|
||||
<Img
|
||||
src={
|
||||
"https://raw.githubusercontent.com/Dokploy/dokploy/refs/heads/canary/apps/dokploy/logo.png"
|
||||
}
|
||||
width="100"
|
||||
height="50"
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/refs/heads/main/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
width="190"
|
||||
height="120"
|
||||
alt="Dokploy"
|
||||
className="my-0 mx-auto"
|
||||
/>
|
||||
</Section>
|
||||
<Heading className="text-black text-[24px] font-normal text-center p-0 my-[30px] mx-0">
|
||||
Join to <strong>Dokploy</strong>
|
||||
</Heading>
|
||||
<Text className="text-black text-[14px] leading-[24px]">
|
||||
Hello,
|
||||
</Text>
|
||||
<Text className="text-black text-[14px] leading-[24px]">
|
||||
You have been invited to join <strong>Dokploy</strong>, a platform
|
||||
that helps for deploying your apps to the cloud.
|
||||
</Text>
|
||||
<Section className="text-center mt-[32px] mb-[32px]">
|
||||
<Button
|
||||
href={inviteLink}
|
||||
className="bg-[#000000] rounded text-white text-[12px] font-semibold no-underline text-center px-5 py-3"
|
||||
>
|
||||
Join the team 🚀
|
||||
</Button>
|
||||
|
||||
{/* Body */}
|
||||
<Section className="bg-white px-[40px] py-[32px]">
|
||||
<Heading className="text-[#09090b] text-[22px] font-semibold m-0 mb-[8px]">
|
||||
You've been invited to join {organizationName}
|
||||
</Heading>
|
||||
<Text className="text-[#71717a] text-[14px] leading-[22px] m-0 mb-[24px]">
|
||||
You have been invited to join{" "}
|
||||
<strong className="text-[#09090b]">{organizationName}</strong>{" "}
|
||||
on Dokploy, the platform for deploying your apps to the cloud.
|
||||
Click the button below to accept the invitation.
|
||||
</Text>
|
||||
|
||||
{/* CTA Button */}
|
||||
<Section className="text-center mb-[24px]">
|
||||
<Button
|
||||
href={inviteLink}
|
||||
className="bg-[#09090b] rounded-lg text-white text-[14px] font-semibold no-underline text-center px-[24px] py-[12px]"
|
||||
>
|
||||
Accept Invitation
|
||||
</Button>
|
||||
</Section>
|
||||
|
||||
<Text className="text-[#a1a1aa] text-[13px] leading-[20px] m-0 text-center mb-[16px]">
|
||||
If the button above doesn't work, copy and paste the following
|
||||
link into your browser:
|
||||
</Text>
|
||||
<Text className="text-[#71717a] text-[12px] leading-[18px] m-0 text-center break-all">
|
||||
{inviteLink}
|
||||
</Text>
|
||||
</Section>
|
||||
|
||||
{/* Footer */}
|
||||
<Section className="bg-[#fafafa] rounded-b-xl px-[40px] py-[24px] text-center border-t border-solid border-[#e4e4e7]">
|
||||
<Hr className="border border-solid border-[#e4e4e7] my-0 mb-[16px] mx-0 w-full" />
|
||||
<Text className="text-[#a1a1aa] text-[12px] leading-[18px] m-0">
|
||||
This invitation was intended for{" "}
|
||||
<span className="text-[#71717a]">{toEmail}</span>. This invite
|
||||
was sent from{" "}
|
||||
<Link
|
||||
href="https://dokploy.com"
|
||||
className="text-[#71717a] underline"
|
||||
>
|
||||
Dokploy Cloud
|
||||
</Link>
|
||||
. If you were not expecting this invitation, you can safely
|
||||
ignore this email.
|
||||
</Text>
|
||||
</Section>
|
||||
<Text className="text-black text-[14px] leading-[24px]">
|
||||
or copy and paste this URL into your browser:{" "}
|
||||
<Link href={inviteLink} className="text-blue-600 no-underline">
|
||||
https://dokploy.com
|
||||
</Link>
|
||||
</Text>
|
||||
<Hr className="border border-solid border-[#eaeaea] my-[26px] mx-0 w-full" />
|
||||
<Text className="text-[#666666] text-[12px] leading-[24px]">
|
||||
This invitation was intended for {toEmail}. This invite was sent
|
||||
from <strong className="text-black">dokploy.com</strong>. If you
|
||||
were not expecting this invitation, you can ignore this email. If
|
||||
you are concerned about your account's safety, please reply to
|
||||
</Text>
|
||||
</Container>
|
||||
</Body>
|
||||
</Tailwind>
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
Tailwind,
|
||||
Text,
|
||||
} from "@react-email/components";
|
||||
import { emailTailwindConfig } from "../tailwind-config";
|
||||
|
||||
export type TemplateProps = {
|
||||
userName: string;
|
||||
@@ -38,17 +39,7 @@ export const InvoiceNotificationEmail = ({
|
||||
<Html>
|
||||
<Head />
|
||||
<Preview>{previewText}</Preview>
|
||||
<Tailwind
|
||||
config={{
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
brand: "#007291",
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Tailwind config={emailTailwindConfig}>
|
||||
<Body className="bg-[#f4f4f5] my-auto mx-auto font-sans">
|
||||
<Container className="my-[40px] mx-auto max-w-[520px]">
|
||||
{/* Header */}
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
Tailwind,
|
||||
Text,
|
||||
} from "@react-email/components";
|
||||
import { emailTailwindConfig } from "../tailwind-config";
|
||||
|
||||
export type TemplateProps = {
|
||||
userName: string;
|
||||
@@ -38,17 +39,7 @@ export const PaymentFailedEmail = ({
|
||||
<Html>
|
||||
<Head />
|
||||
<Preview>{previewText}</Preview>
|
||||
<Tailwind
|
||||
config={{
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
brand: "#007291",
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Tailwind config={emailTailwindConfig}>
|
||||
<Body className="bg-[#f4f4f5] my-auto mx-auto font-sans">
|
||||
<Container className="my-[40px] mx-auto max-w-[520px]">
|
||||
{/* Header */}
|
||||
|
||||
95
packages/server/src/emails/emails/verify-email.tsx
Normal file
95
packages/server/src/emails/emails/verify-email.tsx
Normal file
@@ -0,0 +1,95 @@
|
||||
import {
|
||||
Body,
|
||||
Button,
|
||||
Container,
|
||||
Head,
|
||||
Heading,
|
||||
Html,
|
||||
Img,
|
||||
Link,
|
||||
Preview,
|
||||
Section,
|
||||
Tailwind,
|
||||
Text,
|
||||
} from "@react-email/components";
|
||||
import { emailTailwindConfig } from "../tailwind-config";
|
||||
|
||||
export type TemplateProps = {
|
||||
userName: string;
|
||||
verificationUrl: string;
|
||||
};
|
||||
|
||||
export const VerifyEmailTemplate = ({
|
||||
userName = "User",
|
||||
verificationUrl = "https://app.dokploy.com/verify",
|
||||
}: TemplateProps) => {
|
||||
const previewText = "Verify your email address to get started with Dokploy";
|
||||
return (
|
||||
<Html>
|
||||
<Head />
|
||||
<Preview>{previewText}</Preview>
|
||||
<Tailwind config={emailTailwindConfig}>
|
||||
<Body className="bg-[#f4f4f5] my-auto mx-auto font-sans">
|
||||
<Container className="my-[40px] mx-auto max-w-[520px]">
|
||||
{/* Header */}
|
||||
<Section className="bg-[#09090b] rounded-t-xl px-[40px] py-[32px] text-center">
|
||||
<Img
|
||||
src="https://raw.githubusercontent.com/Dokploy/website/refs/heads/main/apps/docs/public/logo-dokploy-blackpng.png"
|
||||
width="190"
|
||||
height="120"
|
||||
alt="Dokploy"
|
||||
className="my-0 mx-auto"
|
||||
/>
|
||||
</Section>
|
||||
|
||||
{/* Body */}
|
||||
<Section className="bg-white px-[40px] py-[32px]">
|
||||
<Heading className="text-[#09090b] text-[22px] font-semibold m-0 mb-[8px]">
|
||||
Verify Your Email
|
||||
</Heading>
|
||||
<Text className="text-[#71717a] text-[14px] leading-[22px] m-0 mb-[24px]">
|
||||
Hello {userName}, thank you for signing up for Dokploy. Please
|
||||
verify your email address to activate your account.
|
||||
</Text>
|
||||
|
||||
{/* CTA Button */}
|
||||
<Section className="text-center mb-[24px]">
|
||||
<Button
|
||||
href={verificationUrl}
|
||||
className="bg-[#09090b] rounded-lg text-white text-[14px] font-semibold no-underline text-center px-[24px] py-[12px]"
|
||||
>
|
||||
Verify Email Address
|
||||
</Button>
|
||||
</Section>
|
||||
|
||||
<Text className="text-[#a1a1aa] text-[13px] leading-[20px] m-0 text-center mb-[16px]">
|
||||
If the button above doesn't work, copy and paste the following
|
||||
link into your browser:
|
||||
</Text>
|
||||
<Text className="text-[#71717a] text-[12px] leading-[18px] m-0 text-center break-all">
|
||||
{verificationUrl}
|
||||
</Text>
|
||||
</Section>
|
||||
|
||||
{/* Footer */}
|
||||
<Section className="bg-[#fafafa] rounded-b-xl px-[40px] py-[24px] text-center border-t border-solid border-[#e4e4e7]">
|
||||
<Text className="text-[#a1a1aa] text-[12px] leading-[18px] m-0">
|
||||
This is an automated email from{" "}
|
||||
<Link
|
||||
href="https://dokploy.com"
|
||||
className="text-[#71717a] underline"
|
||||
>
|
||||
Dokploy Cloud
|
||||
</Link>
|
||||
. If you didn't create an account, you can safely ignore this
|
||||
email.
|
||||
</Text>
|
||||
</Section>
|
||||
</Container>
|
||||
</Body>
|
||||
</Tailwind>
|
||||
</Html>
|
||||
);
|
||||
};
|
||||
|
||||
export default VerifyEmailTemplate;
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
Tailwind,
|
||||
Text,
|
||||
} from "@react-email/components";
|
||||
import { emailTailwindConfig } from "../tailwind-config";
|
||||
|
||||
export type TemplateProps = {
|
||||
projectName: string;
|
||||
@@ -44,17 +45,7 @@ export const VolumeBackupEmail = ({
|
||||
return (
|
||||
<Html>
|
||||
<Preview>{previewText}</Preview>
|
||||
<Tailwind
|
||||
config={{
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
brand: "#007291",
|
||||
},
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Tailwind config={emailTailwindConfig}>
|
||||
<Head />
|
||||
|
||||
<Body className="bg-white my-auto mx-auto font-sans px-2">
|
||||
|
||||
@@ -9,12 +9,13 @@
|
||||
"export": "email export"
|
||||
},
|
||||
"dependencies": {
|
||||
"@react-email/components": "0.0.21",
|
||||
"react-email": "2.1.5",
|
||||
"react": "^18.2.0"
|
||||
"@react-email/components": "^1.0.12",
|
||||
"react-email": "^6.6.5",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "18.2.33",
|
||||
"@types/react-dom": "18.2.14"
|
||||
"@types/react": "^19.2.0",
|
||||
"@types/react-dom": "^19.2.0"
|
||||
}
|
||||
}
|
||||
|
||||
14
packages/server/src/emails/tailwind-config.ts
Normal file
14
packages/server/src/emails/tailwind-config.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import type { Tailwind } from "@react-email/components";
|
||||
import type { ComponentProps } from "react";
|
||||
|
||||
type TailwindConfig = NonNullable<ComponentProps<typeof Tailwind>["config"]>;
|
||||
|
||||
export const emailTailwindConfig: TailwindConfig = {
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
brand: "#007291",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -36,8 +36,10 @@ export * from "./services/port";
|
||||
export * from "./services/postgres";
|
||||
export * from "./services/preview-deployment";
|
||||
export * from "./services/project";
|
||||
export * from "./services/proprietary/forward-auth";
|
||||
export * from "./services/proprietary/license-key";
|
||||
export * from "./services/proprietary/sso";
|
||||
export * from "./services/proprietary/whitelabeling";
|
||||
export * from "./services/redirect";
|
||||
export * from "./services/redis";
|
||||
export * from "./services/registry";
|
||||
@@ -51,6 +53,7 @@ export * from "./services/user";
|
||||
export * from "./services/volume-backups";
|
||||
export * from "./services/web-server-settings";
|
||||
export * from "./setup/config-paths";
|
||||
export * from "./setup/forward-auth-setup";
|
||||
export * from "./setup/monitoring-setup";
|
||||
export * from "./setup/postgres-setup";
|
||||
export * from "./setup/redis-setup";
|
||||
@@ -101,7 +104,9 @@ export * from "./utils/docker/types";
|
||||
export * from "./utils/docker/utils";
|
||||
export * from "./utils/filesystem/directory";
|
||||
export * from "./utils/filesystem/ssh";
|
||||
export * from "./utils/git-branch-validation";
|
||||
export * from "./utils/gpu-setup";
|
||||
export * from "./utils/hostname-validation";
|
||||
export * from "./utils/notifications/build-error";
|
||||
export * from "./utils/notifications/build-success";
|
||||
export * from "./utils/notifications/database-backup";
|
||||
@@ -127,6 +132,7 @@ export * from "./utils/tracking/hubspot";
|
||||
export * from "./utils/traefik/application";
|
||||
export * from "./utils/traefik/domain";
|
||||
export * from "./utils/traefik/file-types";
|
||||
export * from "./utils/traefik/forward-auth";
|
||||
export * from "./utils/traefik/middleware";
|
||||
export * from "./utils/traefik/redirect";
|
||||
export * from "./utils/traefik/security";
|
||||
@@ -134,4 +140,5 @@ export * from "./utils/traefik/types";
|
||||
export * from "./utils/traefik/web-server";
|
||||
export * from "./utils/volume-backups/index";
|
||||
export * from "./utils/watch-paths/should-deploy";
|
||||
export * from "./verification/send-verification-email";
|
||||
export * from "./wss/utils";
|
||||
|
||||
47
packages/server/src/lib/auth-cli.ts
Normal file
47
packages/server/src/lib/auth-cli.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { apiKey } from "@better-auth/api-key";
|
||||
import { scim } from "@better-auth/scim";
|
||||
import { sso } from "@better-auth/sso";
|
||||
import { betterAuth } from "better-auth";
|
||||
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
||||
import { admin, organization, twoFactor } from "better-auth/plugins";
|
||||
import { db } from "../db";
|
||||
import * as schema from "../db/schema";
|
||||
import { ac, adminRole, memberRole, ownerRole } from "./access-control";
|
||||
|
||||
// CLI-only config for `@better-auth/cli generate` — must mirror the plugin set
|
||||
// in auth.ts. Never import this from runtime code.
|
||||
export const auth = betterAuth({
|
||||
database: drizzleAdapter(db, {
|
||||
provider: "pg",
|
||||
schema,
|
||||
}),
|
||||
user: {
|
||||
modelName: "user",
|
||||
fields: {
|
||||
name: "firstName",
|
||||
},
|
||||
additionalFields: {
|
||||
role: { type: "string", input: false },
|
||||
ownerId: { type: "string", input: false },
|
||||
allowImpersonation: { type: "boolean", defaultValue: false },
|
||||
lastName: { type: "string", required: false, defaultValue: "" },
|
||||
enableEnterpriseFeatures: { type: "boolean", required: false },
|
||||
isValidEnterpriseLicense: { type: "boolean", required: false },
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
apiKey({ enableMetadata: true, references: "user" }),
|
||||
sso(),
|
||||
twoFactor(),
|
||||
organization({
|
||||
ac,
|
||||
roles: { owner: ownerRole, admin: adminRole, member: memberRole },
|
||||
dynamicAccessControl: {
|
||||
enabled: true,
|
||||
maximumRolesPerOrganization: 10,
|
||||
},
|
||||
}),
|
||||
scim(),
|
||||
admin(),
|
||||
],
|
||||
});
|
||||
28
packages/server/src/lib/auth-secret.ts
Normal file
28
packages/server/src/lib/auth-secret.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { readSecret } from "../db/constants";
|
||||
|
||||
const HARDCODED_LEGACY_SECRET = "better-auth-secret-123456789";
|
||||
|
||||
const { BETTER_AUTH_SECRET, BETTER_AUTH_SECRET_FILE } = process.env;
|
||||
|
||||
function resolveBetterAuthSecret(): string {
|
||||
if (BETTER_AUTH_SECRET) {
|
||||
return BETTER_AUTH_SECRET;
|
||||
}
|
||||
if (BETTER_AUTH_SECRET_FILE) {
|
||||
return readSecret(BETTER_AUTH_SECRET_FILE);
|
||||
}
|
||||
if (process.env.NODE_ENV !== "test") {
|
||||
console.warn(`
|
||||
⚠️ [DEPRECATED AUTH CONFIG]
|
||||
BETTER_AUTH_SECRET is not set via environment variable or Docker secret.
|
||||
Falling back to the insecure hardcoded default — this is a CRITICAL SECURITY RISK.
|
||||
This mode WILL BE REMOVED in a future release.
|
||||
|
||||
Please migrate to Docker Secrets:
|
||||
curl -sSL https://dokploy.com/security/0.29.3.sh | bash
|
||||
`);
|
||||
}
|
||||
return HARDCODED_LEGACY_SECRET;
|
||||
}
|
||||
|
||||
export const betterAuthSecret = resolveBetterAuthSecret();
|
||||
@@ -1,13 +1,14 @@
|
||||
import type { IncomingMessage } from "node:http";
|
||||
import { apiKey } from "@better-auth/api-key";
|
||||
import { scim } from "@better-auth/scim";
|
||||
import { sso } from "@better-auth/sso";
|
||||
import * as bcrypt from "bcrypt";
|
||||
import { betterAuth } from "better-auth";
|
||||
import { drizzleAdapter } from "better-auth/adapters/drizzle";
|
||||
import { APIError } from "better-auth/api";
|
||||
import { APIError, createAuthMiddleware } from "better-auth/api";
|
||||
import { admin, organization, twoFactor } from "better-auth/plugins";
|
||||
import { and, desc, eq } from "drizzle-orm";
|
||||
import { BETTER_AUTH_SECRET, IS_CLOUD } from "../constants";
|
||||
import { IS_CLOUD } from "../constants";
|
||||
import { db } from "../db";
|
||||
import * as schema from "../db/schema";
|
||||
import {
|
||||
@@ -21,425 +22,462 @@ import {
|
||||
updateWebServerSettings,
|
||||
} from "../services/web-server-settings";
|
||||
import { getHubSpotUTK, submitToHubSpot } from "../utils/tracking/hubspot";
|
||||
import { sendEmail } from "../verification/send-verification-email";
|
||||
import {
|
||||
sendEmail,
|
||||
sendVerificationEmail,
|
||||
} from "../verification/send-verification-email";
|
||||
import { getPublicIpWithFallback } from "../wss/utils";
|
||||
import { ac, adminRole, memberRole, ownerRole } from "./access-control";
|
||||
import { betterAuthSecret } from "./auth-secret";
|
||||
|
||||
const { handler, api } = betterAuth({
|
||||
database: drizzleAdapter(db, {
|
||||
provider: "pg",
|
||||
schema: schema,
|
||||
}),
|
||||
disabledPaths: [
|
||||
"/sso/register",
|
||||
"/organization/create",
|
||||
"/organization/update",
|
||||
"/organization/delete",
|
||||
],
|
||||
secret: BETTER_AUTH_SECRET,
|
||||
...(!IS_CLOUD
|
||||
? {
|
||||
advanced: {
|
||||
useSecureCookies: false,
|
||||
defaultCookieAttributes: {
|
||||
sameSite: "lax",
|
||||
secure: false,
|
||||
httpOnly: true,
|
||||
path: "/",
|
||||
},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
|
||||
account: {
|
||||
accountLinking: {
|
||||
enabled: true,
|
||||
async trustedProviders() {
|
||||
const fromDb = await getTrustedProviders();
|
||||
return ["github", "google", ...fromDb];
|
||||
},
|
||||
allowDifferentEmails: true,
|
||||
},
|
||||
},
|
||||
appName: "Dokploy",
|
||||
socialProviders: {
|
||||
github: {
|
||||
clientId: process.env.GITHUB_CLIENT_ID as string,
|
||||
clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
|
||||
},
|
||||
google: {
|
||||
clientId: process.env.GOOGLE_CLIENT_ID as string,
|
||||
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
disabled: process.env.NODE_ENV === "production",
|
||||
},
|
||||
async trustedOrigins() {
|
||||
try {
|
||||
if (IS_CLOUD) {
|
||||
return await getTrustedOrigins();
|
||||
}
|
||||
const [trustedOrigins, settings] = await Promise.all([
|
||||
getTrustedOrigins(),
|
||||
getWebServerSettings(),
|
||||
]);
|
||||
if (!settings) return [];
|
||||
const devOrigins =
|
||||
process.env.NODE_ENV === "development"
|
||||
? [
|
||||
"http://localhost:3000",
|
||||
"https://absolutely-handy-falcon.ngrok-free.app",
|
||||
]
|
||||
: [];
|
||||
return [
|
||||
...(settings?.serverIp ? [`http://${settings?.serverIp}:3000`] : []),
|
||||
...(settings?.host ? [`https://${settings?.host}`] : []),
|
||||
...devOrigins,
|
||||
...trustedOrigins,
|
||||
];
|
||||
} catch (error) {
|
||||
console.error("Failed to resolve trusted origins:", error);
|
||||
return [];
|
||||
const resolveTrustedOrigins = async () => {
|
||||
try {
|
||||
if (IS_CLOUD) {
|
||||
return await getTrustedOrigins();
|
||||
}
|
||||
},
|
||||
emailVerification: {
|
||||
sendOnSignUp: true,
|
||||
autoSignInAfterVerification: true,
|
||||
sendVerificationEmail: async ({ user, url }) => {
|
||||
if (IS_CLOUD) {
|
||||
const [trustedOrigins, settings] = await Promise.all([
|
||||
getTrustedOrigins(),
|
||||
getWebServerSettings(),
|
||||
]);
|
||||
|
||||
if (!settings) return [];
|
||||
|
||||
const devOrigins =
|
||||
process.env.NODE_ENV === "development"
|
||||
? [
|
||||
"http://localhost:3000",
|
||||
"https://absolutely-handy-falcon.ngrok-free.app",
|
||||
]
|
||||
: [];
|
||||
return [
|
||||
...(settings?.serverIp ? [`http://${settings?.serverIp}:3000`] : []),
|
||||
...(settings?.host ? [`https://${settings?.host}`] : []),
|
||||
...devOrigins,
|
||||
...trustedOrigins,
|
||||
];
|
||||
} catch (error) {
|
||||
console.error("Failed to resolve trusted origins:", error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
const createBetterAuth = () =>
|
||||
betterAuth({
|
||||
database: drizzleAdapter(db, {
|
||||
provider: "pg",
|
||||
schema: schema,
|
||||
}),
|
||||
disabledPaths: [
|
||||
"/sso/register",
|
||||
"/organization/create",
|
||||
"/organization/update",
|
||||
"/organization/delete",
|
||||
...(!IS_CLOUD ? ["/verify-email"] : []),
|
||||
],
|
||||
secret: betterAuthSecret,
|
||||
...(!IS_CLOUD
|
||||
? {
|
||||
advanced: {
|
||||
useSecureCookies: false,
|
||||
defaultCookieAttributes: {
|
||||
sameSite: "lax",
|
||||
secure: false,
|
||||
httpOnly: true,
|
||||
path: "/",
|
||||
},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
|
||||
account: {
|
||||
accountLinking: {
|
||||
enabled: true,
|
||||
async trustedProviders() {
|
||||
const fromDb = await getTrustedProviders();
|
||||
return ["github", "google", ...fromDb];
|
||||
},
|
||||
allowDifferentEmails: true,
|
||||
},
|
||||
},
|
||||
appName: "Dokploy",
|
||||
socialProviders: {
|
||||
github: {
|
||||
clientId: process.env.GITHUB_CLIENT_ID as string,
|
||||
clientSecret: process.env.GITHUB_CLIENT_SECRET as string,
|
||||
},
|
||||
google: {
|
||||
clientId: process.env.GOOGLE_CLIENT_ID as string,
|
||||
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
disabled: process.env.NODE_ENV === "production",
|
||||
},
|
||||
trustedOrigins: resolveTrustedOrigins,
|
||||
hooks: {
|
||||
before: createAuthMiddleware(async (ctx) => {
|
||||
ctx.context.trustedOrigins = [
|
||||
...(ctx.context.baseURL ? [new URL(ctx.context.baseURL).origin] : []),
|
||||
...(await resolveTrustedOrigins()),
|
||||
].filter(Boolean);
|
||||
}),
|
||||
},
|
||||
emailVerification: {
|
||||
sendOnSignUp: true,
|
||||
autoSignInAfterVerification: true,
|
||||
sendOnSignIn: true,
|
||||
sendVerificationEmail: async ({ user, url }) => {
|
||||
if (IS_CLOUD) {
|
||||
await sendVerificationEmail({
|
||||
userName: user.name || "User",
|
||||
email: user.email,
|
||||
verificationUrl: url,
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
autoSignIn: !IS_CLOUD,
|
||||
requireEmailVerification:
|
||||
IS_CLOUD && process.env.NODE_ENV === "production",
|
||||
password: {
|
||||
async hash(password) {
|
||||
return bcrypt.hashSync(password, 10);
|
||||
},
|
||||
async verify({ hash, password }) {
|
||||
return bcrypt.compareSync(password, hash);
|
||||
},
|
||||
},
|
||||
sendResetPassword: async ({ user, url }) => {
|
||||
await sendEmail({
|
||||
email: user.email,
|
||||
subject: "Verify your email",
|
||||
subject: "Reset your password",
|
||||
text: `
|
||||
<p>Click the link to verify your email: <a href="${url}">Verify Email</a></p>
|
||||
`,
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
autoSignIn: !IS_CLOUD,
|
||||
requireEmailVerification: IS_CLOUD && process.env.NODE_ENV === "production",
|
||||
password: {
|
||||
async hash(password) {
|
||||
return bcrypt.hashSync(password, 10);
|
||||
},
|
||||
async verify({ hash, password }) {
|
||||
return bcrypt.compareSync(password, hash);
|
||||
},
|
||||
},
|
||||
sendResetPassword: async ({ user, url }) => {
|
||||
await sendEmail({
|
||||
email: user.email,
|
||||
subject: "Reset your password",
|
||||
text: `
|
||||
<p>Click the link to reset your password: <a href="${url}">Reset Password</a></p>
|
||||
`,
|
||||
});
|
||||
});
|
||||
},
|
||||
},
|
||||
},
|
||||
databaseHooks: {
|
||||
user: {
|
||||
create: {
|
||||
before: async (_user, context) => {
|
||||
if (!IS_CLOUD) {
|
||||
const xDokployToken =
|
||||
context?.request?.headers?.get("x-dokploy-token");
|
||||
if (xDokployToken) {
|
||||
let invitation: Awaited<ReturnType<typeof getUserByToken>>;
|
||||
databaseHooks: {
|
||||
user: {
|
||||
create: {
|
||||
before: async (_user, context) => {
|
||||
if (!IS_CLOUD) {
|
||||
const xDokployToken =
|
||||
context?.request?.headers?.get("x-dokploy-token");
|
||||
if (xDokployToken) {
|
||||
let invitation: Awaited<ReturnType<typeof getUserByToken>>;
|
||||
try {
|
||||
invitation = await getUserByToken(xDokployToken);
|
||||
} catch {
|
||||
throw new APIError("BAD_REQUEST", {
|
||||
message: "Invalid invitation token",
|
||||
});
|
||||
}
|
||||
if (invitation.isExpired) {
|
||||
throw new APIError("BAD_REQUEST", {
|
||||
message: "Invitation has expired",
|
||||
});
|
||||
}
|
||||
if (invitation.status !== "pending") {
|
||||
throw new APIError("BAD_REQUEST", {
|
||||
message: "Invitation has already been used",
|
||||
});
|
||||
}
|
||||
if (
|
||||
_user.email.toLowerCase().trim() !==
|
||||
invitation.email.toLowerCase().trim()
|
||||
) {
|
||||
throw new APIError("BAD_REQUEST", {
|
||||
message: "Email does not match invitation",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const isSSORequest = context?.path.includes("/sso");
|
||||
const isSCIMRequest = context?.path.includes("/scim");
|
||||
if (isSSORequest || isSCIMRequest) {
|
||||
return;
|
||||
}
|
||||
const isAdminPresent = await db.query.member.findFirst({
|
||||
where: eq(schema.member.role, "owner"),
|
||||
});
|
||||
if (isAdminPresent) {
|
||||
throw new APIError("BAD_REQUEST", {
|
||||
message: "Admin is already created",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
after: async (user, context) => {
|
||||
const isSSORequest = context?.path.includes("/sso");
|
||||
const isSCIMRequest = context?.path.includes("/scim");
|
||||
const isAdminPresent = await db.query.member.findFirst({
|
||||
where: eq(schema.member.role, "owner"),
|
||||
});
|
||||
|
||||
if (!IS_CLOUD && !isAdminPresent) {
|
||||
await updateWebServerSettings({
|
||||
serverIp: await getPublicIpWithFallback(),
|
||||
});
|
||||
}
|
||||
|
||||
if (IS_CLOUD) {
|
||||
try {
|
||||
invitation = await getUserByToken(xDokployToken);
|
||||
} catch {
|
||||
throw new APIError("BAD_REQUEST", {
|
||||
message: "Invalid invitation token",
|
||||
});
|
||||
}
|
||||
if (invitation.isExpired) {
|
||||
throw new APIError("BAD_REQUEST", {
|
||||
message: "Invitation has expired",
|
||||
});
|
||||
}
|
||||
if (invitation.status !== "pending") {
|
||||
throw new APIError("BAD_REQUEST", {
|
||||
message: "Invitation has already been used",
|
||||
});
|
||||
}
|
||||
if (
|
||||
_user.email.toLowerCase().trim() !==
|
||||
invitation.email.toLowerCase().trim()
|
||||
) {
|
||||
throw new APIError("BAD_REQUEST", {
|
||||
message: "Email does not match invitation",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const isSSORequest = context?.path.includes("/sso");
|
||||
if (isSSORequest) {
|
||||
return;
|
||||
}
|
||||
const isAdminPresent = await db.query.member.findFirst({
|
||||
where: eq(schema.member.role, "owner"),
|
||||
});
|
||||
if (isAdminPresent) {
|
||||
throw new APIError("BAD_REQUEST", {
|
||||
message: "Admin is already created",
|
||||
});
|
||||
const hutk = getHubSpotUTK(
|
||||
context?.request?.headers?.get("cookie") || undefined,
|
||||
);
|
||||
// Cast to include additional fields
|
||||
const userWithFields = user as typeof user & {
|
||||
lastName?: string;
|
||||
};
|
||||
const hubspotSuccess = await submitToHubSpot(
|
||||
{
|
||||
email: user.email,
|
||||
firstName: user.name || "", // name is mapped to firstName column
|
||||
lastName: userWithFields.lastName || "",
|
||||
},
|
||||
hutk,
|
||||
);
|
||||
if (!hubspotSuccess) {
|
||||
console.error("Failed to submit to HubSpot");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error submitting to HubSpot", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
after: async (user, context) => {
|
||||
const isSSORequest = context?.path.includes("/sso");
|
||||
const isAdminPresent = await db.query.member.findFirst({
|
||||
where: eq(schema.member.role, "owner"),
|
||||
});
|
||||
|
||||
if (!IS_CLOUD) {
|
||||
await updateWebServerSettings({
|
||||
serverIp: await getPublicIpWithFallback(),
|
||||
});
|
||||
}
|
||||
|
||||
if (IS_CLOUD) {
|
||||
try {
|
||||
const hutk = getHubSpotUTK(
|
||||
context?.request?.headers?.get("cookie") || undefined,
|
||||
);
|
||||
// Cast to include additional fields
|
||||
const userWithFields = user as typeof user & {
|
||||
lastName?: string;
|
||||
};
|
||||
const hubspotSuccess = await submitToHubSpot(
|
||||
{
|
||||
email: user.email,
|
||||
firstName: user.name || "", // name is mapped to firstName column
|
||||
lastName: userWithFields.lastName || "",
|
||||
},
|
||||
hutk,
|
||||
);
|
||||
if (!hubspotSuccess) {
|
||||
console.error("Failed to submit to HubSpot");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error submitting to HubSpot", error);
|
||||
if (isSCIMRequest) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (IS_CLOUD || !isAdminPresent) {
|
||||
await db.transaction(async (tx) => {
|
||||
const organization = await tx
|
||||
.insert(schema.organization)
|
||||
.values({
|
||||
name: "My Organization",
|
||||
ownerId: user.id,
|
||||
if (IS_CLOUD || !isAdminPresent) {
|
||||
await db.transaction(async (tx) => {
|
||||
const organization = await tx
|
||||
.insert(schema.organization)
|
||||
.values({
|
||||
name: "My Organization",
|
||||
ownerId: user.id,
|
||||
createdAt: new Date(),
|
||||
})
|
||||
.returning()
|
||||
.then((res) => res[0]);
|
||||
|
||||
await tx.insert(schema.member).values({
|
||||
userId: user.id,
|
||||
organizationId: organization?.id || "",
|
||||
role: "owner",
|
||||
createdAt: new Date(),
|
||||
})
|
||||
.returning()
|
||||
.then((res) => res[0]);
|
||||
isDefault: true, // Mark first organization as default
|
||||
});
|
||||
});
|
||||
} else if (isSSORequest) {
|
||||
const providerId = context?.params?.providerId;
|
||||
if (!providerId) {
|
||||
throw new APIError("BAD_REQUEST", {
|
||||
message: "Provider ID is required",
|
||||
});
|
||||
}
|
||||
const provider = await db.query.ssoProvider.findFirst({
|
||||
where: eq(schema.ssoProvider.providerId, providerId),
|
||||
});
|
||||
|
||||
await tx.insert(schema.member).values({
|
||||
if (!provider) {
|
||||
throw new APIError("BAD_REQUEST", {
|
||||
message: "Provider not found",
|
||||
});
|
||||
}
|
||||
await db.insert(schema.member).values({
|
||||
userId: user.id,
|
||||
organizationId: organization?.id || "",
|
||||
role: "owner",
|
||||
organizationId: provider?.organizationId || "",
|
||||
role: "member",
|
||||
createdAt: new Date(),
|
||||
isDefault: true, // Mark first organization as default
|
||||
});
|
||||
});
|
||||
} else if (isSSORequest) {
|
||||
const providerId = context?.params?.providerId;
|
||||
if (!providerId) {
|
||||
throw new APIError("BAD_REQUEST", {
|
||||
message: "Provider ID is required",
|
||||
isDefault: true,
|
||||
});
|
||||
}
|
||||
const provider = await db.query.ssoProvider.findFirst({
|
||||
where: eq(schema.ssoProvider.providerId, providerId),
|
||||
},
|
||||
},
|
||||
},
|
||||
session: {
|
||||
create: {
|
||||
before: async (session) => {
|
||||
// Find the default organization for this user
|
||||
// Priority: 1) isDefault=true, 2) most recently created
|
||||
const member = await db.query.member.findFirst({
|
||||
where: eq(schema.member.userId, session.userId),
|
||||
orderBy: [
|
||||
desc(schema.member.isDefault),
|
||||
desc(schema.member.createdAt),
|
||||
],
|
||||
with: {
|
||||
organization: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!provider) {
|
||||
throw new APIError("BAD_REQUEST", {
|
||||
message: "Provider not found",
|
||||
});
|
||||
}
|
||||
await db.insert(schema.member).values({
|
||||
userId: user.id,
|
||||
organizationId: provider?.organizationId || "",
|
||||
role: "member",
|
||||
createdAt: new Date(),
|
||||
isDefault: true,
|
||||
return {
|
||||
data: {
|
||||
...session,
|
||||
activeOrganizationId: member?.organization.id,
|
||||
},
|
||||
};
|
||||
},
|
||||
after: async (session) => {
|
||||
const orgId = (
|
||||
session as typeof session & { activeOrganizationId?: string }
|
||||
).activeOrganizationId;
|
||||
if (!orgId) return;
|
||||
const memberRecord = await db.query.member.findFirst({
|
||||
where: and(
|
||||
eq(schema.member.userId, session.userId),
|
||||
eq(schema.member.organizationId, orgId),
|
||||
),
|
||||
with: { user: true },
|
||||
});
|
||||
}
|
||||
if (!memberRecord) return;
|
||||
await createAuditLog({
|
||||
organizationId: orgId,
|
||||
userId: session.userId,
|
||||
userEmail: memberRecord.user.email,
|
||||
userRole: memberRecord.role,
|
||||
action: "login",
|
||||
resourceType: "session",
|
||||
});
|
||||
},
|
||||
},
|
||||
delete: {
|
||||
after: async (session) => {
|
||||
const orgId = (
|
||||
session as typeof session & { activeOrganizationId?: string }
|
||||
).activeOrganizationId;
|
||||
if (!orgId) return;
|
||||
const memberRecord = await db.query.member.findFirst({
|
||||
where: and(
|
||||
eq(schema.member.userId, session.userId),
|
||||
eq(schema.member.organizationId, orgId),
|
||||
),
|
||||
with: { user: true },
|
||||
});
|
||||
if (!memberRecord) return;
|
||||
await createAuditLog({
|
||||
organizationId: orgId,
|
||||
userId: session.userId,
|
||||
userEmail: memberRecord.user.email,
|
||||
userRole: memberRecord.role,
|
||||
action: "logout",
|
||||
resourceType: "session",
|
||||
});
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
session: {
|
||||
create: {
|
||||
before: async (session) => {
|
||||
// Find the default organization for this user
|
||||
// Priority: 1) isDefault=true, 2) most recently created
|
||||
const member = await db.query.member.findFirst({
|
||||
where: eq(schema.member.userId, session.userId),
|
||||
orderBy: [
|
||||
desc(schema.member.isDefault),
|
||||
desc(schema.member.createdAt),
|
||||
],
|
||||
with: {
|
||||
organization: true,
|
||||
},
|
||||
expiresIn: 60 * 60 * 24 * 3,
|
||||
updateAge: 60 * 60 * 24,
|
||||
},
|
||||
user: {
|
||||
modelName: "user",
|
||||
fields: {
|
||||
name: "firstName", // Map better-auth's default 'name' field to 'firstName' column
|
||||
},
|
||||
additionalFields: {
|
||||
role: {
|
||||
type: "string",
|
||||
// required: true,
|
||||
input: false,
|
||||
},
|
||||
ownerId: {
|
||||
type: "string",
|
||||
// required: true,
|
||||
input: false,
|
||||
},
|
||||
allowImpersonation: {
|
||||
fieldName: "allowImpersonation",
|
||||
type: "boolean",
|
||||
defaultValue: false,
|
||||
},
|
||||
lastName: {
|
||||
type: "string",
|
||||
required: false,
|
||||
input: true,
|
||||
defaultValue: "",
|
||||
},
|
||||
enableEnterpriseFeatures: {
|
||||
type: "boolean",
|
||||
required: false,
|
||||
input: false,
|
||||
},
|
||||
isValidEnterpriseLicense: {
|
||||
type: "boolean",
|
||||
required: false,
|
||||
input: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
apiKey({
|
||||
enableMetadata: true,
|
||||
references: "user",
|
||||
}),
|
||||
sso({ trustEmailVerified: true }),
|
||||
scim({
|
||||
beforeSCIMTokenGenerated: async ({ user }) => {
|
||||
const dbUser = await db.query.user.findFirst({
|
||||
where: eq(schema.user.id, user.id),
|
||||
columns: { enableEnterpriseFeatures: true },
|
||||
});
|
||||
|
||||
return {
|
||||
data: {
|
||||
...session,
|
||||
activeOrganizationId: member?.organization.id,
|
||||
},
|
||||
};
|
||||
if (!dbUser?.enableEnterpriseFeatures) {
|
||||
throw new APIError("FORBIDDEN", {
|
||||
message: "SCIM provisioning requires an enterprise license",
|
||||
});
|
||||
}
|
||||
},
|
||||
after: async (session) => {
|
||||
const orgId = (
|
||||
session as typeof session & { activeOrganizationId?: string }
|
||||
).activeOrganizationId;
|
||||
if (!orgId) return;
|
||||
const memberRecord = await db.query.member.findFirst({
|
||||
where: and(
|
||||
eq(schema.member.userId, session.userId),
|
||||
eq(schema.member.organizationId, orgId),
|
||||
),
|
||||
with: { user: true },
|
||||
});
|
||||
if (!memberRecord) return;
|
||||
await createAuditLog({
|
||||
organizationId: orgId,
|
||||
userId: session.userId,
|
||||
userEmail: memberRecord.user.email,
|
||||
userRole: memberRecord.role,
|
||||
action: "login",
|
||||
resourceType: "session",
|
||||
});
|
||||
}),
|
||||
twoFactor(),
|
||||
organization({
|
||||
ac,
|
||||
roles: {
|
||||
owner: ownerRole,
|
||||
admin: adminRole,
|
||||
member: memberRole,
|
||||
},
|
||||
},
|
||||
delete: {
|
||||
after: async (session) => {
|
||||
const orgId = (
|
||||
session as typeof session & { activeOrganizationId?: string }
|
||||
).activeOrganizationId;
|
||||
if (!orgId) return;
|
||||
const memberRecord = await db.query.member.findFirst({
|
||||
where: and(
|
||||
eq(schema.member.userId, session.userId),
|
||||
eq(schema.member.organizationId, orgId),
|
||||
),
|
||||
with: { user: true },
|
||||
});
|
||||
if (!memberRecord) return;
|
||||
await createAuditLog({
|
||||
organizationId: orgId,
|
||||
userId: session.userId,
|
||||
userEmail: memberRecord.user.email,
|
||||
userRole: memberRecord.role,
|
||||
action: "logout",
|
||||
resourceType: "session",
|
||||
});
|
||||
dynamicAccessControl: {
|
||||
enabled: true,
|
||||
maximumRolesPerOrganization: 10,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
session: {
|
||||
expiresIn: 60 * 60 * 24 * 3,
|
||||
updateAge: 60 * 60 * 24,
|
||||
},
|
||||
user: {
|
||||
modelName: "user",
|
||||
fields: {
|
||||
name: "firstName", // Map better-auth's default 'name' field to 'firstName' column
|
||||
},
|
||||
additionalFields: {
|
||||
role: {
|
||||
type: "string",
|
||||
// required: true,
|
||||
input: false,
|
||||
},
|
||||
ownerId: {
|
||||
type: "string",
|
||||
// required: true,
|
||||
input: false,
|
||||
},
|
||||
allowImpersonation: {
|
||||
fieldName: "allowImpersonation",
|
||||
type: "boolean",
|
||||
defaultValue: false,
|
||||
},
|
||||
lastName: {
|
||||
type: "string",
|
||||
required: false,
|
||||
input: true,
|
||||
defaultValue: "",
|
||||
},
|
||||
enableEnterpriseFeatures: {
|
||||
type: "boolean",
|
||||
required: false,
|
||||
input: false,
|
||||
},
|
||||
isValidEnterpriseLicense: {
|
||||
type: "boolean",
|
||||
required: false,
|
||||
input: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
apiKey({
|
||||
enableMetadata: true,
|
||||
references: "user",
|
||||
}),
|
||||
sso(),
|
||||
twoFactor(),
|
||||
organization({
|
||||
ac,
|
||||
roles: {
|
||||
owner: ownerRole,
|
||||
admin: adminRole,
|
||||
member: memberRole,
|
||||
},
|
||||
dynamicAccessControl: {
|
||||
enabled: true,
|
||||
maximumRolesPerOrganization: 10,
|
||||
},
|
||||
async sendInvitationEmail(data, _request) {
|
||||
if (IS_CLOUD) {
|
||||
const host =
|
||||
process.env.NODE_ENV === "development"
|
||||
? "http://localhost:3000"
|
||||
: "https://app.dokploy.com";
|
||||
const inviteLink = `${host}/invitation?token=${data.id}`;
|
||||
}),
|
||||
// Self-hosted needs the admin plugin too: SCIM deactivation (active: false)
|
||||
// maps to the admin plugin's `banned` field and is rejected without it.
|
||||
// adminRoles: [] keeps every /admin/* endpoint locked on self-hosted.
|
||||
admin(
|
||||
IS_CLOUD
|
||||
? { adminUserIds: [process.env.USER_ADMIN_ID as string] }
|
||||
: { adminRoles: [] },
|
||||
),
|
||||
],
|
||||
});
|
||||
|
||||
await sendEmail({
|
||||
email: data.email,
|
||||
subject: "Invitation to join organization",
|
||||
text: `
|
||||
<p>You are invited to join ${data.organization.name} on Dokploy. Click the link to accept the invitation: <a href="${inviteLink}">Accept Invitation</a></p>
|
||||
`,
|
||||
});
|
||||
}
|
||||
},
|
||||
}),
|
||||
...(IS_CLOUD
|
||||
? [
|
||||
admin({
|
||||
adminUserIds: [process.env.USER_ADMIN_ID as string],
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
});
|
||||
// Una sola instancia de better-auth por proceso aunque el módulo esté
|
||||
// duplicado en varios bundles.
|
||||
const globalForAuth = globalThis as unknown as {
|
||||
betterAuthInstance?: ReturnType<typeof createBetterAuth>;
|
||||
};
|
||||
|
||||
if (!globalForAuth.betterAuthInstance) {
|
||||
globalForAuth.betterAuthInstance = createBetterAuth();
|
||||
}
|
||||
|
||||
const { handler, api } = globalForAuth.betterAuthInstance;
|
||||
|
||||
const _auth = {
|
||||
handler,
|
||||
createApiKey: api.createApiKey,
|
||||
registerSSOProvider: api.registerSSOProvider,
|
||||
updateSSOProvider: api.updateSSOProvider,
|
||||
generateSCIMToken: api.generateSCIMToken,
|
||||
listSCIMProviderConnections: api.listSCIMProviderConnections,
|
||||
deleteSCIMProviderConnection: api.deleteSCIMProviderConnection,
|
||||
};
|
||||
|
||||
export type AuthType = typeof _auth;
|
||||
@@ -479,8 +517,10 @@ export const validateRequest = async (request: IncomingMessage) => {
|
||||
};
|
||||
}
|
||||
|
||||
const organizationId = JSON.parse(
|
||||
apiKeyRecord.metadata || "{}",
|
||||
const organizationId = (
|
||||
JSON.parse(apiKeyRecord.metadata || "{}") as {
|
||||
organizationId?: string;
|
||||
}
|
||||
).organizationId;
|
||||
|
||||
if (!organizationId) {
|
||||
|
||||
15
packages/server/src/lib/encryption-secret.ts
Normal file
15
packages/server/src/lib/encryption-secret.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { readSecret } from "../db/constants";
|
||||
|
||||
const { ENCRYPTION_KEY, ENCRYPTION_KEY_FILE } = process.env;
|
||||
|
||||
function resolveEncryptionSecret(): string | undefined {
|
||||
if (ENCRYPTION_KEY) {
|
||||
return ENCRYPTION_KEY;
|
||||
}
|
||||
if (ENCRYPTION_KEY_FILE) {
|
||||
return readSecret(ENCRYPTION_KEY_FILE);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export const encryptionSecret = resolveEncryptionSecret();
|
||||
108
packages/server/src/lib/encryption.ts
Normal file
108
packages/server/src/lib/encryption.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import {
|
||||
createCipheriv,
|
||||
createDecipheriv,
|
||||
createHmac,
|
||||
randomBytes,
|
||||
} from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { paths } from "@dokploy/server/constants";
|
||||
import { betterAuthSecret } from "./auth-secret";
|
||||
import { encryptionSecret } from "./encryption-secret";
|
||||
|
||||
export const ENCRYPTION_KEY_BACKUP_FILE = "encryption.key";
|
||||
|
||||
const ENCRYPTION_PREFIX = "enc:v1:";
|
||||
const IV_LENGTH = 12;
|
||||
const AUTH_TAG_LENGTH = 16;
|
||||
|
||||
const deriveKey = (secret: string) =>
|
||||
createHmac("sha256", secret).update("dokploy:db-encryption:v1").digest();
|
||||
|
||||
const primaryKey = deriveKey(encryptionSecret ?? betterAuthSecret);
|
||||
|
||||
// Installs that adopt a dedicated ENCRYPTION_KEY still hold values encrypted
|
||||
// with the auth-secret-derived key; keep it as a decrypt fallback so they
|
||||
// lazily re-encrypt on the next write instead of becoming unreadable.
|
||||
const decryptionKeys = encryptionSecret
|
||||
? [primaryKey, deriveKey(betterAuthSecret)]
|
||||
: [primaryKey];
|
||||
|
||||
// Derived keys only — never the raw secrets. A leaked key can decrypt
|
||||
// stored values, but the raw BETTER_AUTH_SECRET could also forge sessions.
|
||||
export const exportEncryptionKeys = () =>
|
||||
decryptionKeys.map((key) => key.toString("hex")).join("\n");
|
||||
|
||||
let restoredKeys: Buffer[] | undefined;
|
||||
|
||||
// A backup created with "include encryption key" places the original
|
||||
// server's keys at BASE_PATH when restored; use them as a last-resort
|
||||
// decryption fallback so restored values keep working on the new server.
|
||||
const loadRestoredKeys = (): Buffer[] => {
|
||||
if (restoredKeys?.length) {
|
||||
return restoredKeys;
|
||||
}
|
||||
try {
|
||||
const { BASE_PATH } = paths();
|
||||
const keys = readFileSync(
|
||||
join(BASE_PATH, ENCRYPTION_KEY_BACKUP_FILE),
|
||||
"utf8",
|
||||
)
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter(Boolean)
|
||||
.map((hex) => Buffer.from(hex, "hex"))
|
||||
.filter(
|
||||
(key) =>
|
||||
key.length === 32 && !decryptionKeys.some((own) => own.equals(key)),
|
||||
);
|
||||
if (keys.length) {
|
||||
restoredKeys = keys;
|
||||
}
|
||||
} catch {
|
||||
// No restored key file present.
|
||||
}
|
||||
return restoredKeys ?? [];
|
||||
};
|
||||
|
||||
export const isEncrypted = (value: string) =>
|
||||
value.startsWith(ENCRYPTION_PREFIX);
|
||||
|
||||
export const encryptValue = (value: string): string => {
|
||||
if (!value || isEncrypted(value)) {
|
||||
return value;
|
||||
}
|
||||
const iv = randomBytes(IV_LENGTH);
|
||||
const cipher = createCipheriv("aes-256-gcm", primaryKey, iv);
|
||||
const encrypted = Buffer.concat([
|
||||
cipher.update(value, "utf8"),
|
||||
cipher.final(),
|
||||
]);
|
||||
return `${ENCRYPTION_PREFIX}${Buffer.concat([iv, cipher.getAuthTag(), encrypted]).toString("base64")}`;
|
||||
};
|
||||
|
||||
export const decryptValue = (value: string): string => {
|
||||
if (!value || !isEncrypted(value)) {
|
||||
return value;
|
||||
}
|
||||
const payload = Buffer.from(value.slice(ENCRYPTION_PREFIX.length), "base64");
|
||||
const iv = payload.subarray(0, IV_LENGTH);
|
||||
const authTag = payload.subarray(IV_LENGTH, IV_LENGTH + AUTH_TAG_LENGTH);
|
||||
const encrypted = payload.subarray(IV_LENGTH + AUTH_TAG_LENGTH);
|
||||
const keys = [...decryptionKeys, ...loadRestoredKeys()];
|
||||
for (const key of keys) {
|
||||
try {
|
||||
const decipher = createDecipheriv("aes-256-gcm", key, iv);
|
||||
decipher.setAuthTag(authTag);
|
||||
return Buffer.concat([
|
||||
decipher.update(encrypted),
|
||||
decipher.final(),
|
||||
]).toString("utf8");
|
||||
} catch {
|
||||
// GCM auth failed for this key; try the next one.
|
||||
}
|
||||
}
|
||||
throw new Error(
|
||||
"Failed to decrypt a stored secret. This usually means ENCRYPTION_KEY or BETTER_AUTH_SECRET changed after the value was encrypted.",
|
||||
);
|
||||
};
|
||||
@@ -120,6 +120,10 @@ export const getDokployUrl = async () => {
|
||||
const TRUSTED_ORIGINS_CACHE_TTL_MS = 30 * 60_000;
|
||||
let trustedOriginsCache: { data: string[]; expiresAt: number } | null = null;
|
||||
|
||||
export const invalidateTrustedOriginsCache = () => {
|
||||
trustedOriginsCache = null;
|
||||
};
|
||||
|
||||
export const getTrustedOrigins = async () => {
|
||||
const runQuery = async () => {
|
||||
const rows = await db
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { db } from "@dokploy/server/db";
|
||||
import { ai } from "@dokploy/server/db/schema";
|
||||
import { ai, organization } from "@dokploy/server/db/schema";
|
||||
import { aiCustomProviderSchema } from "@dokploy/server/db/schema/ai";
|
||||
import { selectAIProvider } from "@dokploy/server/utils/ai/select-ai-provider";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { generateText, Output } from "ai";
|
||||
@@ -24,7 +25,7 @@ interface DockerOutput {
|
||||
dockerCompose: string;
|
||||
envVariables: Array<{ name: string; value: string }>;
|
||||
domains: Array<{ host: string; port: number; serviceName: string }>;
|
||||
configFiles?: Array<{ content: string; filePath: string }>;
|
||||
configFiles?: Array<{ content: string; filePath: string }> | null;
|
||||
}
|
||||
|
||||
export const getAiSettingsByOrganizationId = async (organizationId: string) => {
|
||||
@@ -48,9 +49,74 @@ export const getAiSettingById = async (aiId: string) => {
|
||||
return aiSetting;
|
||||
};
|
||||
|
||||
type AiCustomProvider = z.infer<typeof aiCustomProviderSchema>;
|
||||
|
||||
const parseOrgMetadata = (metadata: string | null) => {
|
||||
try {
|
||||
const parsed = JSON.parse(metadata || "{}");
|
||||
return typeof parsed === "object" && parsed !== null
|
||||
? (parsed as Record<string, unknown>)
|
||||
: {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
export const getCustomAiProviders = async (organizationId: string) => {
|
||||
const org = await db.query.organization.findFirst({
|
||||
where: eq(organization.id, organizationId),
|
||||
});
|
||||
const metadata = parseOrgMetadata(org?.metadata ?? null);
|
||||
const result = z
|
||||
.array(aiCustomProviderSchema)
|
||||
.safeParse(metadata.aiProviders);
|
||||
return result.success ? result.data : [];
|
||||
};
|
||||
|
||||
export const saveCustomAiProviders = async (
|
||||
organizationId: string,
|
||||
providers: AiCustomProvider[],
|
||||
) => {
|
||||
const org = await db.query.organization.findFirst({
|
||||
where: eq(organization.id, organizationId),
|
||||
});
|
||||
if (!org) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Organization not found",
|
||||
});
|
||||
}
|
||||
const metadata = parseOrgMetadata(org.metadata);
|
||||
metadata.aiProviders = providers;
|
||||
await db
|
||||
.update(organization)
|
||||
.set({ metadata: JSON.stringify(metadata) })
|
||||
.where(eq(organization.id, organizationId));
|
||||
return providers;
|
||||
};
|
||||
|
||||
const normalizeApiUrl = (url: string) => url.trim().replace(/\/+$/, "");
|
||||
|
||||
export const saveAiSettings = async (organizationId: string, settings: any) => {
|
||||
const aiId = settings.aiId;
|
||||
|
||||
if (settings.apiUrl) {
|
||||
const customProviders = await getCustomAiProviders(organizationId);
|
||||
if (customProviders.length > 0) {
|
||||
const isAllowed = customProviders.some(
|
||||
(provider) =>
|
||||
normalizeApiUrl(provider.apiUrl) === normalizeApiUrl(settings.apiUrl),
|
||||
);
|
||||
if (!isAllowed) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message:
|
||||
"This API URL is not in your organization's allowed AI providers",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return db
|
||||
.insert(ai)
|
||||
.values({
|
||||
@@ -136,7 +202,7 @@ export const suggestVariants = async ({
|
||||
filePath: z.string(),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
.nullable(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
@@ -198,12 +264,12 @@ export const suggestVariants = async ({
|
||||
1. ALWAYS use 'image:' field, NEVER use 'build:' field
|
||||
2. NEVER use 'build: .' or any build directive - we don't have local Dockerfiles
|
||||
3. Use images from Docker Hub or other public registries (e.g., docker.io, ghcr.io, quay.io)
|
||||
4. For dependencies (databases, redis, etc.), use official images (e.g., postgres:16, redis:7, etc.)
|
||||
4. For dependencies (databases, redis, etc.), use official images (e.g., postgres:16, redis:8, etc.)
|
||||
5. Always specify image tags - avoid using 'latest' tag, use specific versions when possible
|
||||
6. Examples of correct image usage:
|
||||
- image: sendingtk/chatwoot:develop
|
||||
- image: postgres:16-alpine
|
||||
- image: redis:7-alpine
|
||||
- image: redis:8-alpine
|
||||
7. Examples of INCORRECT usage (DO NOT USE):
|
||||
- build: .
|
||||
- build: ./app
|
||||
@@ -229,7 +295,7 @@ export const suggestVariants = async ({
|
||||
|
||||
Domain Rules - For each service that needs to be exposed to the internet:
|
||||
1. Define a domain with:
|
||||
- host: {service-name}-{random-3-chars-hex}-${ip ? ip.replaceAll(".", "-") : ""}.traefik.me
|
||||
- host: {service-name}-{random-3-chars-hex}-${ip ? ip.replaceAll(".", "-") : ""}.sslip.io
|
||||
- port: the internal port the service runs on
|
||||
- serviceName: the name of the service in the docker-compose
|
||||
2. Make sure the service is properly configured to work with the specified port
|
||||
|
||||
@@ -95,27 +95,36 @@ export const findApplicationById = async (applicationId: string) => {
|
||||
const application = await db.query.applications.findFirst({
|
||||
where: eq(applications.applicationId, applicationId),
|
||||
with: {
|
||||
environment: {
|
||||
with: {
|
||||
project: true,
|
||||
},
|
||||
},
|
||||
|
||||
environment: { with: { project: true } },
|
||||
domains: true,
|
||||
deployments: true,
|
||||
mounts: true,
|
||||
redirects: true,
|
||||
security: true,
|
||||
ports: true,
|
||||
registry: true,
|
||||
gitlab: true,
|
||||
github: true,
|
||||
bitbucket: true,
|
||||
gitea: true,
|
||||
gitlab: {
|
||||
columns: { secret: false, accessToken: false, refreshToken: false },
|
||||
},
|
||||
github: {
|
||||
columns: {
|
||||
githubClientSecret: false,
|
||||
githubPrivateKey: false,
|
||||
githubWebhookSecret: false,
|
||||
},
|
||||
},
|
||||
bitbucket: { columns: { appPassword: false, apiToken: false } },
|
||||
gitea: {
|
||||
columns: {
|
||||
clientSecret: false,
|
||||
accessToken: false,
|
||||
refreshToken: false,
|
||||
},
|
||||
},
|
||||
server: true,
|
||||
previewDeployments: true,
|
||||
buildRegistry: true,
|
||||
rollbackRegistry: true,
|
||||
registry: { columns: { password: false } },
|
||||
buildRegistry: { columns: { password: false } },
|
||||
rollbackRegistry: { columns: { password: false } },
|
||||
},
|
||||
});
|
||||
if (!application) {
|
||||
|
||||
@@ -34,7 +34,12 @@ export const findBackupById = async (backupId: string) => {
|
||||
mariadb: true,
|
||||
mongo: true,
|
||||
libsql: true,
|
||||
destination: true,
|
||||
destination: {
|
||||
columns: {
|
||||
accessKey: false,
|
||||
secretAccessKey: false,
|
||||
},
|
||||
},
|
||||
compose: true,
|
||||
},
|
||||
});
|
||||
@@ -83,7 +88,12 @@ export const findBackupsByDbId = async (
|
||||
mariadb: true,
|
||||
mongo: true,
|
||||
libsql: true,
|
||||
destination: true,
|
||||
destination: {
|
||||
columns: {
|
||||
accessKey: false,
|
||||
secretAccessKey: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return result || [];
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
import { removeDirectoryIfExistsContent } from "@dokploy/server/utils/filesystem/directory";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { quote } from "shell-quote";
|
||||
import { stringify } from "yaml";
|
||||
import type { z } from "zod";
|
||||
import { encodeBase64 } from "../utils/docker/utils";
|
||||
@@ -63,7 +64,7 @@ export const removeCertificateById = async (certificateId: string) => {
|
||||
const certDir = path.join(CERTIFICATES_PATH, certificate.certificatePath);
|
||||
|
||||
if (certificate.serverId) {
|
||||
await execAsyncRemote(certificate.serverId, `rm -rf ${certDir}`);
|
||||
await execAsyncRemote(certificate.serverId, `rm -rf ${quote([certDir])}`);
|
||||
} else {
|
||||
await removeDirectoryIfExistsContent(certDir);
|
||||
}
|
||||
@@ -108,10 +109,10 @@ const createCertificateFiles = async (certificate: Certificate) => {
|
||||
const certificateData = encodeBase64(certificate.certificateData);
|
||||
const privateKey = encodeBase64(certificate.privateKey);
|
||||
const command = `
|
||||
mkdir -p ${certDir};
|
||||
echo "${certificateData}" | base64 -d > "${crtPath}";
|
||||
echo "${privateKey}" | base64 -d > "${keyPath}";
|
||||
echo "${yamlConfig}" > "${configFile}";
|
||||
mkdir -p ${quote([certDir])};
|
||||
echo "${certificateData}" | base64 -d > ${quote([crtPath])};
|
||||
echo "${privateKey}" | base64 -d > ${quote([keyPath])};
|
||||
echo "${yamlConfig}" > ${quote([configFile])};
|
||||
`;
|
||||
|
||||
await execAsyncRemote(certificate.serverId, command);
|
||||
|
||||
@@ -33,6 +33,7 @@ import { cloneGitlabRepository } from "@dokploy/server/utils/providers/gitlab";
|
||||
import { getCreateComposeFileCommand } from "@dokploy/server/utils/providers/raw";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { quote } from "shell-quote";
|
||||
import type { z } from "zod";
|
||||
import { encodeBase64 } from "../utils/docker/utils";
|
||||
import { getDokployUrl } from "./admin";
|
||||
@@ -131,7 +132,12 @@ export const findComposeById = async (composeId: string) => {
|
||||
server: true,
|
||||
backups: {
|
||||
with: {
|
||||
destination: true,
|
||||
destination: {
|
||||
columns: {
|
||||
accessKey: false,
|
||||
secretAccessKey: false,
|
||||
},
|
||||
},
|
||||
deployments: true,
|
||||
},
|
||||
},
|
||||
@@ -467,7 +473,7 @@ export const startCompose = async (composeId: string) => {
|
||||
const projectPath = join(COMPOSE_PATH, compose.appName, "code");
|
||||
const path =
|
||||
compose.sourceType === "raw" ? "docker-compose.yml" : compose.composePath;
|
||||
const baseCommand = `env -i PATH="$PATH" docker compose -p ${compose.appName} -f ${path} up -d`;
|
||||
const baseCommand = `env -i PATH="$PATH" docker compose -p ${quote([compose.appName])} -f ${quote([path])} up -d`;
|
||||
if (compose.composeType === "docker-compose") {
|
||||
if (compose.serverId) {
|
||||
await execAsyncRemote(
|
||||
|
||||
@@ -84,6 +84,7 @@ export const findDeploymentById = async (deploymentId: string) => {
|
||||
where: eq(deployments.deploymentId, deploymentId),
|
||||
with: {
|
||||
application: true,
|
||||
compose: true,
|
||||
schedule: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
execAsync,
|
||||
execAsyncRemote,
|
||||
} from "@dokploy/server/utils/process/execAsync";
|
||||
import { quote } from "shell-quote";
|
||||
|
||||
export const getContainers = async (serverId?: string | null) => {
|
||||
try {
|
||||
@@ -417,21 +418,58 @@ export const getContainerLogs = async (
|
||||
}
|
||||
};
|
||||
|
||||
export const containerRestart = async (containerId: string) => {
|
||||
try {
|
||||
const { stdout, stderr } = await execAsync(
|
||||
`docker container restart ${containerId}`,
|
||||
);
|
||||
export const containerRestart = async (
|
||||
containerId: string,
|
||||
serverId?: string,
|
||||
) => {
|
||||
const command = `docker container restart ${containerId}`;
|
||||
const { stderr } = serverId
|
||||
? await execAsyncRemote(serverId, command)
|
||||
: await execAsync(command);
|
||||
|
||||
if (stderr) {
|
||||
console.error(`Error: ${stderr}`);
|
||||
return;
|
||||
}
|
||||
if (stderr) {
|
||||
console.error(`Error: ${stderr}`);
|
||||
throw new Error(stderr);
|
||||
}
|
||||
};
|
||||
|
||||
const config = JSON.parse(stdout);
|
||||
export const containerStart = async (
|
||||
containerId: string,
|
||||
serverId?: string,
|
||||
) => {
|
||||
const command = `docker container start ${containerId}`;
|
||||
const { stderr } = serverId
|
||||
? await execAsyncRemote(serverId, command)
|
||||
: await execAsync(command);
|
||||
|
||||
return config;
|
||||
} catch {}
|
||||
if (stderr) {
|
||||
console.error(`Error: ${stderr}`);
|
||||
throw new Error(stderr);
|
||||
}
|
||||
};
|
||||
|
||||
export const containerStop = async (containerId: string, serverId?: string) => {
|
||||
const command = `docker container stop ${containerId}`;
|
||||
const { stderr } = serverId
|
||||
? await execAsyncRemote(serverId, command)
|
||||
: await execAsync(command);
|
||||
|
||||
if (stderr) {
|
||||
console.error(`Error: ${stderr}`);
|
||||
throw new Error(stderr);
|
||||
}
|
||||
};
|
||||
|
||||
export const containerKill = async (containerId: string, serverId?: string) => {
|
||||
const command = `docker container kill ${containerId}`;
|
||||
const { stderr } = serverId
|
||||
? await execAsyncRemote(serverId, command)
|
||||
: await execAsync(command);
|
||||
|
||||
if (stderr) {
|
||||
console.error(`Error: ${stderr}`);
|
||||
throw new Error(stderr);
|
||||
}
|
||||
};
|
||||
|
||||
export const containerRemove = async (
|
||||
@@ -482,7 +520,7 @@ export const getSwarmNodes = async (serverId?: string) => {
|
||||
|
||||
export const getNodeInfo = async (nodeId: string, serverId?: string) => {
|
||||
try {
|
||||
const command = `docker node inspect ${nodeId} --format '{{json .}}'`;
|
||||
const command = `docker node inspect ${quote([nodeId])} --format '{{json .}}'`;
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
if (serverId) {
|
||||
@@ -618,6 +656,8 @@ export const getAllContainerStats = async (serverId?: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
const destinationPathRegex = /^[a-zA-Z0-9.\-_/]+$/;
|
||||
|
||||
export const uploadFileToContainer = async (
|
||||
containerId: string,
|
||||
fileBuffer: Buffer,
|
||||
@@ -630,7 +670,12 @@ export const uploadFileToContainer = async (
|
||||
throw new Error("Invalid container ID");
|
||||
}
|
||||
|
||||
// Ensure destination path starts with /
|
||||
if (!destinationPathRegex.test(destinationPath)) {
|
||||
throw new Error(
|
||||
"Invalid destination path: shell metacharacters are not allowed",
|
||||
);
|
||||
}
|
||||
|
||||
const normalizedPath = destinationPath.startsWith("/")
|
||||
? destinationPath
|
||||
: `/${destinationPath}`;
|
||||
|
||||
@@ -308,6 +308,48 @@ export const duplicateEnvironment = async (
|
||||
return newEnvironment;
|
||||
};
|
||||
|
||||
interface EnvironmentWithServices {
|
||||
applications: { applicationId: string }[];
|
||||
compose: { composeId: string }[];
|
||||
libsql: { libsqlId: string }[];
|
||||
mariadb: { mariadbId: string }[];
|
||||
mongo: { mongoId: string }[];
|
||||
mysql: { mysqlId: string }[];
|
||||
postgres: { postgresId: string }[];
|
||||
redis: { redisId: string }[];
|
||||
}
|
||||
|
||||
export const filterEnvironmentServices = <T extends EnvironmentWithServices>(
|
||||
environment: T,
|
||||
accessedServices: string[],
|
||||
): T => ({
|
||||
...environment,
|
||||
applications: environment.applications.filter((app) =>
|
||||
accessedServices.includes(app.applicationId),
|
||||
),
|
||||
compose: environment.compose.filter((comp) =>
|
||||
accessedServices.includes(comp.composeId),
|
||||
),
|
||||
libsql: environment.libsql.filter((db) =>
|
||||
accessedServices.includes(db.libsqlId),
|
||||
),
|
||||
mariadb: environment.mariadb.filter((db) =>
|
||||
accessedServices.includes(db.mariadbId),
|
||||
),
|
||||
mongo: environment.mongo.filter((db) =>
|
||||
accessedServices.includes(db.mongoId),
|
||||
),
|
||||
mysql: environment.mysql.filter((db) =>
|
||||
accessedServices.includes(db.mysqlId),
|
||||
),
|
||||
postgres: environment.postgres.filter((db) =>
|
||||
accessedServices.includes(db.postgresId),
|
||||
),
|
||||
redis: environment.redis.filter((db) =>
|
||||
accessedServices.includes(db.redisId),
|
||||
),
|
||||
});
|
||||
|
||||
export const createProductionEnvironment = async (projectId: string) => {
|
||||
const newEnvironment = await db
|
||||
.insert(environments)
|
||||
|
||||
@@ -43,6 +43,38 @@ export const updateGitProvider = async (
|
||||
.then((response) => response[0]);
|
||||
};
|
||||
|
||||
// Returns true if the user can edit the git source configuration of an existing
|
||||
// deploy that is connected to the given provider.
|
||||
// Owner/admin: always yes.
|
||||
// Member: only if they own the provider or it's shared with the org.
|
||||
// Being in accessedGitProviders only grants permission to connect NEW deploys,
|
||||
// not to modify the git config of an existing deploy owned by someone else.
|
||||
export const canEditDeployGitSource = async (
|
||||
gitProviderId: string,
|
||||
session: { userId: string; activeOrganizationId: string },
|
||||
): Promise<boolean> => {
|
||||
const { userId, activeOrganizationId } = session;
|
||||
|
||||
const memberRecord = await db.query.member.findFirst({
|
||||
where: and(
|
||||
eq(member.userId, userId),
|
||||
eq(member.organizationId, activeOrganizationId),
|
||||
),
|
||||
columns: { role: true },
|
||||
});
|
||||
|
||||
if (memberRecord?.role === "owner") return true;
|
||||
|
||||
const provider = await db.query.gitProvider.findFirst({
|
||||
where: eq(gitProvider.gitProviderId, gitProviderId),
|
||||
columns: { userId: true, sharedWithOrganization: true },
|
||||
});
|
||||
|
||||
if (!provider) return false;
|
||||
|
||||
return provider.userId === userId || provider.sharedWithOrganization;
|
||||
};
|
||||
|
||||
export const getAccessibleGitProviderIds = async (session: {
|
||||
userId: string;
|
||||
activeOrganizationId: string;
|
||||
@@ -87,3 +119,30 @@ export const getAccessibleGitProviderIds = async (session: {
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Authorizes read access to a specific git provider for the current session.
|
||||
* Throws if the provider belongs to a different organization (cross-org IDOR)
|
||||
* or if the caller is not entitled to it within the active organization.
|
||||
* Must be called before returning any git-provider record that carries secrets
|
||||
* (OAuth tokens, app private keys, webhook secrets).
|
||||
*/
|
||||
export const assertGitProviderAccess = async (
|
||||
session: { userId: string; activeOrganizationId: string },
|
||||
provider: { gitProviderId: string; organizationId: string },
|
||||
) => {
|
||||
if (provider.organizationId !== session.activeOrganizationId) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Git provider not found",
|
||||
});
|
||||
}
|
||||
|
||||
const accessibleIds = await getAccessibleGitProviderIds(session);
|
||||
if (!accessibleIds.has(provider.gitProviderId)) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You don't have access to this git provider",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -11,6 +11,7 @@ import { pullImage } from "@dokploy/server/utils/docker/utils";
|
||||
import { execAsyncRemote } from "@dokploy/server/utils/process/execAsync";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq, getTableColumns } from "drizzle-orm";
|
||||
import { quote } from "shell-quote";
|
||||
import type { z } from "zod";
|
||||
import { validUniqueServerAppName } from "./project";
|
||||
|
||||
@@ -63,7 +64,12 @@ export const findLibsqlById = async (libsqlId: string) => {
|
||||
server: true,
|
||||
backups: {
|
||||
with: {
|
||||
destination: true,
|
||||
destination: {
|
||||
columns: {
|
||||
accessKey: false,
|
||||
secretAccessKey: false,
|
||||
},
|
||||
},
|
||||
deployments: true,
|
||||
},
|
||||
},
|
||||
@@ -135,7 +141,7 @@ export const deployLibsql = async (
|
||||
if (libsql.serverId) {
|
||||
await execAsyncRemote(
|
||||
libsql.serverId,
|
||||
`docker pull ${libsql.dockerImage}`,
|
||||
`docker pull ${quote([libsql.dockerImage])}`,
|
||||
onData,
|
||||
);
|
||||
} else {
|
||||
|
||||
@@ -11,6 +11,7 @@ import { pullImage } from "@dokploy/server/utils/docker/utils";
|
||||
import { execAsyncRemote } from "@dokploy/server/utils/process/execAsync";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq, getTableColumns } from "drizzle-orm";
|
||||
import { quote } from "shell-quote";
|
||||
import type { z } from "zod";
|
||||
import { validUniqueServerAppName } from "./project";
|
||||
|
||||
@@ -68,7 +69,12 @@ export const findMariadbById = async (mariadbId: string) => {
|
||||
server: true,
|
||||
backups: {
|
||||
with: {
|
||||
destination: true,
|
||||
destination: {
|
||||
columns: {
|
||||
accessKey: false,
|
||||
secretAccessKey: false,
|
||||
},
|
||||
},
|
||||
deployments: true,
|
||||
},
|
||||
},
|
||||
@@ -140,7 +146,7 @@ export const deployMariadb = async (
|
||||
if (mariadb.serverId) {
|
||||
await execAsyncRemote(
|
||||
mariadb.serverId,
|
||||
`docker pull ${mariadb.dockerImage}`,
|
||||
`docker pull ${quote([mariadb.dockerImage])}`,
|
||||
onData,
|
||||
);
|
||||
} else {
|
||||
|
||||
@@ -12,6 +12,7 @@ import { pullImage } from "@dokploy/server/utils/docker/utils";
|
||||
import { execAsyncRemote } from "@dokploy/server/utils/process/execAsync";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq, getTableColumns } from "drizzle-orm";
|
||||
import { quote } from "shell-quote";
|
||||
import type { z } from "zod";
|
||||
import { validUniqueServerAppName } from "./project";
|
||||
|
||||
@@ -63,7 +64,12 @@ export const findMongoById = async (mongoId: string) => {
|
||||
server: true,
|
||||
backups: {
|
||||
with: {
|
||||
destination: true,
|
||||
destination: {
|
||||
columns: {
|
||||
accessKey: false,
|
||||
secretAccessKey: false,
|
||||
},
|
||||
},
|
||||
deployments: true,
|
||||
},
|
||||
},
|
||||
@@ -155,7 +161,7 @@ export const deployMongo = async (
|
||||
if (mongo.serverId) {
|
||||
await execAsyncRemote(
|
||||
mongo.serverId,
|
||||
`docker pull ${mongo.dockerImage}`,
|
||||
`docker pull ${quote([mongo.dockerImage])}`,
|
||||
onData,
|
||||
);
|
||||
} else {
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
} from "@dokploy/server/utils/process/execAsync";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq, type SQL, sql } from "drizzle-orm";
|
||||
import { quote } from "shell-quote";
|
||||
import type { z } from "zod";
|
||||
|
||||
export type Mount = typeof mounts.$inferSelect;
|
||||
@@ -317,7 +318,7 @@ export const updateFileMount = async (mountId: string) => {
|
||||
try {
|
||||
const serverId = await getServerId(mount);
|
||||
const encodedContent = encodeBase64(mount.content || "");
|
||||
const command = `echo "${encodedContent}" | base64 -d > ${fullPath}`;
|
||||
const command = `echo "${encodedContent}" | base64 -d > ${quote([fullPath])}`;
|
||||
if (serverId) {
|
||||
await execAsyncRemote(serverId, command);
|
||||
} else {
|
||||
@@ -337,7 +338,7 @@ export const deleteFileMount = async (mountId: string) => {
|
||||
try {
|
||||
const serverId = await getServerId(mount);
|
||||
if (serverId) {
|
||||
const command = `rm -rf ${fullPath}`;
|
||||
const command = `rm -rf ${quote([fullPath])}`;
|
||||
await execAsyncRemote(serverId, command);
|
||||
} else {
|
||||
await removeFileOrDirectory(fullPath);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { pullImage } from "@dokploy/server/utils/docker/utils";
|
||||
import { execAsyncRemote } from "@dokploy/server/utils/process/execAsync";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq, getTableColumns } from "drizzle-orm";
|
||||
import { quote } from "shell-quote";
|
||||
import type { z } from "zod";
|
||||
import { validUniqueServerAppName } from "./project";
|
||||
|
||||
@@ -66,7 +67,12 @@ export const findMySqlById = async (mysqlId: string) => {
|
||||
server: true,
|
||||
backups: {
|
||||
with: {
|
||||
destination: true,
|
||||
destination: {
|
||||
columns: {
|
||||
accessKey: false,
|
||||
secretAccessKey: false,
|
||||
},
|
||||
},
|
||||
deployments: true,
|
||||
},
|
||||
},
|
||||
@@ -138,7 +144,7 @@ export const deployMySql = async (
|
||||
if (mysql.serverId) {
|
||||
await execAsyncRemote(
|
||||
mysql.serverId,
|
||||
`docker pull ${mysql.dockerImage}`,
|
||||
`docker pull ${quote([mysql.dockerImage])}`,
|
||||
onData,
|
||||
);
|
||||
} else {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { join } from "node:path";
|
||||
import { paths } from "@dokploy/server/constants";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { quote } from "shell-quote";
|
||||
import { execAsync, execAsyncRemote } from "../utils/process/execAsync";
|
||||
import { cloneBitbucketRepository } from "../utils/providers/bitbucket";
|
||||
import { cloneGitRepository } from "../utils/providers/git";
|
||||
@@ -85,7 +86,7 @@ export const readPatchRepoDirectory = async (
|
||||
serverId?: string | null,
|
||||
): Promise<DirectoryEntry[]> => {
|
||||
// Use git ls-tree to get tracked files only
|
||||
const command = `cd "${repoPath}" && git ls-tree -r --name-only HEAD`;
|
||||
const command = `cd ${quote([repoPath])} && git ls-tree -r --name-only HEAD`;
|
||||
|
||||
let stdout: string;
|
||||
try {
|
||||
@@ -168,7 +169,7 @@ export const readPatchRepoFile = async (
|
||||
const repoPath = join(PATCH_REPOS_PATH, type, application.appName);
|
||||
const fullPath = join(repoPath, filePath);
|
||||
|
||||
const command = `cat "${fullPath}"`;
|
||||
const command = `cat ${quote([fullPath])}`;
|
||||
|
||||
if (serverId) {
|
||||
const result = await execAsyncRemote(serverId, command);
|
||||
|
||||
@@ -80,9 +80,10 @@ export const checkPermission = async (
|
||||
const { id: userId } = ctx.user;
|
||||
const { activeOrganizationId: organizationId } = ctx.session;
|
||||
const memberRecord = await findMemberByUserId(userId, organizationId);
|
||||
const isStaticRole = memberRecord.role in staticRoles;
|
||||
|
||||
if (isStaticRole) {
|
||||
const isPrivilegedStaticRole =
|
||||
memberRecord.role === "owner" || memberRecord.role === "admin";
|
||||
if (isPrivilegedStaticRole) {
|
||||
const allEnterprise = Object.keys(permissions).every((r) =>
|
||||
enterpriseOnlyResources.has(r),
|
||||
);
|
||||
@@ -164,9 +165,13 @@ const getLegacyOverrides = (
|
||||
},
|
||||
sshKeys: {
|
||||
read: !!memberRecord.canAccessToSSHKeys,
|
||||
create: !!memberRecord.canAccessToSSHKeys,
|
||||
delete: !!memberRecord.canAccessToSSHKeys,
|
||||
},
|
||||
gitProviders: {
|
||||
read: !!memberRecord.canAccessToGitProviders,
|
||||
create: !!memberRecord.canAccessToGitProviders,
|
||||
delete: !!memberRecord.canAccessToGitProviders,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@@ -11,6 +11,7 @@ import { pullImage } from "@dokploy/server/utils/docker/utils";
|
||||
import { execAsyncRemote } from "@dokploy/server/utils/process/execAsync";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq, getTableColumns } from "drizzle-orm";
|
||||
import { quote } from "shell-quote";
|
||||
import type { z } from "zod";
|
||||
import { validUniqueServerAppName } from "./project";
|
||||
|
||||
@@ -76,7 +77,12 @@ export const findPostgresById = async (postgresId: string) => {
|
||||
server: true,
|
||||
backups: {
|
||||
with: {
|
||||
destination: true,
|
||||
destination: {
|
||||
columns: {
|
||||
accessKey: false,
|
||||
secretAccessKey: false,
|
||||
},
|
||||
},
|
||||
deployments: true,
|
||||
},
|
||||
},
|
||||
@@ -150,7 +156,7 @@ export const deployPostgres = async (
|
||||
if (postgres.serverId) {
|
||||
await execAsyncRemote(
|
||||
postgres.serverId,
|
||||
`docker pull ${postgres.dockerImage}`,
|
||||
`docker pull ${quote([postgres.dockerImage])}`,
|
||||
onData,
|
||||
);
|
||||
} else {
|
||||
|
||||
@@ -30,13 +30,9 @@ export const findPreviewDeploymentById = async (
|
||||
with: {
|
||||
domain: true,
|
||||
application: {
|
||||
with: {
|
||||
server: true,
|
||||
environment: {
|
||||
with: {
|
||||
project: true,
|
||||
},
|
||||
},
|
||||
columns: {
|
||||
applicationId: true,
|
||||
serverId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -140,7 +136,7 @@ export const createPreviewDeployment = async (
|
||||
where: eq(organization.id, application.environment.project.organizationId),
|
||||
});
|
||||
const generateDomain = await generateWildcardDomain(
|
||||
application.previewWildcard || "*.traefik.me",
|
||||
application.previewWildcard || "*.sslip.io",
|
||||
appName,
|
||||
application.server?.ipAddress || "",
|
||||
org?.ownerId || "",
|
||||
@@ -242,7 +238,7 @@ const generateWildcardDomain = async (
|
||||
throw new Error('The base domain must start with "*."');
|
||||
}
|
||||
const hash = `${appName}`;
|
||||
if (baseDomain.includes("traefik.me")) {
|
||||
if (baseDomain.includes("sslip.io")) {
|
||||
let ip = "";
|
||||
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
|
||||
382
packages/server/src/services/proprietary/forward-auth.ts
Normal file
382
packages/server/src/services/proprietary/forward-auth.ts
Normal file
@@ -0,0 +1,382 @@
|
||||
import { IS_CLOUD } from "@dokploy/server/constants";
|
||||
import { db } from "@dokploy/server/db";
|
||||
import {
|
||||
forwardAuthSettings,
|
||||
server,
|
||||
ssoProvider,
|
||||
} from "@dokploy/server/db/schema";
|
||||
import { checkServicePermissionAndAccess } from "@dokploy/server/services/permission";
|
||||
import {
|
||||
deriveBaseDomain,
|
||||
deriveCookieSecret,
|
||||
type ForwardAuthOidcConfig,
|
||||
forwardAuthCallbackUrl,
|
||||
isForwardAuthRunning,
|
||||
removeForwardAuth,
|
||||
setupForwardAuth,
|
||||
} from "@dokploy/server/setup/forward-auth-setup";
|
||||
import { manageDomain } from "@dokploy/server/utils/traefik/domain";
|
||||
import {
|
||||
manageForwardAuthDomain,
|
||||
removeForwardAuthDomain,
|
||||
removeForwardAuthMiddleware,
|
||||
} from "@dokploy/server/utils/traefik/forward-auth";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { and, asc, desc, eq, isNotNull, isNull } from "drizzle-orm";
|
||||
import { findApplicationById } from "../application";
|
||||
import { findDomainById, updateDomainById } from "../domain";
|
||||
|
||||
const resolveOidcConfig = (provider: {
|
||||
issuer: string;
|
||||
oidcConfig: string | null;
|
||||
}): ForwardAuthOidcConfig => {
|
||||
if (!provider.oidcConfig) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message:
|
||||
"Forward-auth requires an OIDC provider — SAML is not supported.",
|
||||
});
|
||||
}
|
||||
|
||||
let parsed: any;
|
||||
try {
|
||||
parsed = JSON.parse(provider.oidcConfig);
|
||||
} catch {
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to parse the SSO provider OIDC configuration",
|
||||
});
|
||||
}
|
||||
|
||||
if (!parsed?.clientId || !parsed?.clientSecret) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "SSO provider OIDC config is missing clientId/clientSecret",
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
clientId: parsed.clientId,
|
||||
clientSecret: parsed.clientSecret,
|
||||
issuer: provider.issuer,
|
||||
scopes: parsed.scopes,
|
||||
skipDiscovery: parsed.skipDiscovery,
|
||||
};
|
||||
};
|
||||
|
||||
const findProviderForOrg = async (
|
||||
providerId: string,
|
||||
organizationId: string,
|
||||
) => {
|
||||
const provider = await db.query.ssoProvider.findFirst({
|
||||
where: and(
|
||||
eq(ssoProvider.providerId, providerId),
|
||||
eq(ssoProvider.organizationId, organizationId),
|
||||
),
|
||||
columns: { providerId: true, issuer: true, oidcConfig: true },
|
||||
});
|
||||
if (!provider) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "SSO provider not found",
|
||||
});
|
||||
}
|
||||
return provider;
|
||||
};
|
||||
|
||||
export const listSsoProvidersForOrg = async (organizationId: string) => {
|
||||
return db.query.ssoProvider.findMany({
|
||||
where: and(
|
||||
eq(ssoProvider.organizationId, organizationId),
|
||||
isNotNull(ssoProvider.oidcConfig),
|
||||
),
|
||||
columns: { providerId: true, issuer: true, domain: true },
|
||||
orderBy: [asc(ssoProvider.createdAt)],
|
||||
});
|
||||
};
|
||||
|
||||
export const getDomainSsoStatus = async (
|
||||
ctx: { session: { activeOrganizationId: string } },
|
||||
domainId: string,
|
||||
) => {
|
||||
const domain = await findDomainById(domainId);
|
||||
if (domain.applicationId) {
|
||||
await checkServicePermissionAndAccess(ctx as any, domain.applicationId, {
|
||||
domain: ["read"],
|
||||
});
|
||||
}
|
||||
return { enabled: !!domain.forwardAuthEnabled };
|
||||
};
|
||||
|
||||
const settingsWhere = (serverId: string | null) =>
|
||||
serverId
|
||||
? eq(forwardAuthSettings.serverId, serverId)
|
||||
: isNull(forwardAuthSettings.serverId);
|
||||
|
||||
export const getForwardAuthSettings = async (serverId: string | null) => {
|
||||
return db.query.forwardAuthSettings.findFirst({
|
||||
where: settingsWhere(serverId),
|
||||
});
|
||||
};
|
||||
|
||||
export const setForwardAuthSettings = async (input: {
|
||||
organizationId: string;
|
||||
serverId: string | null;
|
||||
authDomain: string;
|
||||
https: boolean;
|
||||
certificateType: "none" | "letsencrypt" | "custom";
|
||||
customCertResolver?: string | null;
|
||||
}) => {
|
||||
const baseDomain = deriveBaseDomain(input.authDomain);
|
||||
const existing = await getForwardAuthSettings(input.serverId);
|
||||
|
||||
const values = {
|
||||
authDomain: input.authDomain,
|
||||
baseDomain,
|
||||
https: input.https,
|
||||
certificateType: input.certificateType,
|
||||
customCertResolver: input.customCertResolver ?? null,
|
||||
};
|
||||
|
||||
if (existing) {
|
||||
await db
|
||||
.update(forwardAuthSettings)
|
||||
.set(values)
|
||||
.where(settingsWhere(input.serverId));
|
||||
} else {
|
||||
await db.insert(forwardAuthSettings).values({
|
||||
...values,
|
||||
serverId: input.serverId,
|
||||
});
|
||||
}
|
||||
|
||||
await manageForwardAuthDomain(input.serverId, {
|
||||
authDomain: input.authDomain,
|
||||
https: input.https,
|
||||
certificateType: input.certificateType,
|
||||
customCertResolver: input.customCertResolver,
|
||||
});
|
||||
|
||||
if (existing?.providerId) {
|
||||
const proxyRunning = await isForwardAuthRunning(
|
||||
input.serverId ?? undefined,
|
||||
);
|
||||
if (proxyRunning) {
|
||||
await deployForwardAuthOnServer({
|
||||
serverId: input.serverId ?? undefined,
|
||||
providerId: existing.providerId,
|
||||
organizationId: input.organizationId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { callbackUrl: forwardAuthCallbackUrl(input.authDomain, input.https) };
|
||||
};
|
||||
|
||||
export const removeForwardAuthSettings = async (serverId: string | null) => {
|
||||
const existing = await getForwardAuthSettings(serverId);
|
||||
if (!existing) return { ok: true } as const;
|
||||
await removeForwardAuthDomain(serverId);
|
||||
await db.delete(forwardAuthSettings).where(settingsWhere(serverId));
|
||||
return { ok: true } as const;
|
||||
};
|
||||
|
||||
export const deployForwardAuthOnServer = async (input: {
|
||||
serverId?: string;
|
||||
providerId: string;
|
||||
organizationId: string;
|
||||
}) => {
|
||||
const settings = await getForwardAuthSettings(input.serverId ?? null);
|
||||
if (!settings) {
|
||||
throw new TRPCError({
|
||||
code: "PRECONDITION_FAILED",
|
||||
message:
|
||||
"Set the authentication domain for this server before deploying the proxy.",
|
||||
});
|
||||
}
|
||||
|
||||
const provider = await findProviderForOrg(
|
||||
input.providerId,
|
||||
input.organizationId,
|
||||
);
|
||||
const oidc = resolveOidcConfig(provider);
|
||||
|
||||
await setupForwardAuth({
|
||||
serverId: input.serverId,
|
||||
oidc,
|
||||
cookieSecret: deriveCookieSecret(
|
||||
`${input.serverId ?? "host"}:${settings.baseDomain}`,
|
||||
),
|
||||
authDomain: settings.authDomain,
|
||||
baseDomain: settings.baseDomain,
|
||||
authDomainHttps: settings.https,
|
||||
});
|
||||
|
||||
if (settings.providerId !== input.providerId) {
|
||||
await db
|
||||
.update(forwardAuthSettings)
|
||||
.set({ providerId: input.providerId })
|
||||
.where(settingsWhere(input.serverId ?? null));
|
||||
}
|
||||
|
||||
return { ok: true } as const;
|
||||
};
|
||||
|
||||
const FORWARD_AUTH_CHECK_TIMEOUT_MS = 4000;
|
||||
|
||||
const proxyStatus = async (
|
||||
serverId: string | null,
|
||||
): Promise<"running" | "stopped" | "unknown"> => {
|
||||
try {
|
||||
const running = await Promise.race([
|
||||
isForwardAuthRunning(serverId ?? undefined),
|
||||
new Promise<never>((_, reject) =>
|
||||
setTimeout(
|
||||
() => reject(new Error("timeout")),
|
||||
FORWARD_AUTH_CHECK_TIMEOUT_MS,
|
||||
),
|
||||
),
|
||||
]);
|
||||
return running ? "running" : "stopped";
|
||||
} catch {
|
||||
return "unknown";
|
||||
}
|
||||
};
|
||||
|
||||
export const getForwardAuthServerStatus = async (organizationId: string) => {
|
||||
const servers = await db.query.server.findMany({
|
||||
where: and(
|
||||
eq(server.organizationId, organizationId),
|
||||
isNotNull(server.sshKeyId),
|
||||
eq(server.serverType, "deploy"),
|
||||
),
|
||||
columns: { serverId: true, name: true, ipAddress: true },
|
||||
orderBy: [desc(server.createdAt)],
|
||||
});
|
||||
|
||||
const targets: {
|
||||
serverId: string | null;
|
||||
name: string;
|
||||
ipAddress: string | null;
|
||||
}[] = [
|
||||
...(IS_CLOUD
|
||||
? []
|
||||
: [
|
||||
{
|
||||
serverId: null,
|
||||
name: "Dokploy Server (local)",
|
||||
ipAddress: null,
|
||||
},
|
||||
]),
|
||||
...servers.map((s) => ({
|
||||
serverId: s.serverId,
|
||||
name: s.name,
|
||||
ipAddress: s.ipAddress,
|
||||
})),
|
||||
];
|
||||
|
||||
return Promise.all(
|
||||
targets.map(async (t) => {
|
||||
const settings = await getForwardAuthSettings(t.serverId);
|
||||
return {
|
||||
...t,
|
||||
status: await proxyStatus(t.serverId),
|
||||
authDomain: settings?.authDomain ?? null,
|
||||
https: settings?.https ?? true,
|
||||
certificateType: settings?.certificateType ?? "none",
|
||||
customCertResolver: settings?.customCertResolver ?? null,
|
||||
callbackUrl: settings
|
||||
? forwardAuthCallbackUrl(settings.authDomain, settings.https)
|
||||
: null,
|
||||
};
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
export const removeForwardAuthProxy = async (serverId: string | null) => {
|
||||
await removeForwardAuth(serverId ?? undefined);
|
||||
await db
|
||||
.update(forwardAuthSettings)
|
||||
.set({ providerId: null })
|
||||
.where(settingsWhere(serverId));
|
||||
return { ok: true } as const;
|
||||
};
|
||||
|
||||
const resolveApplicationDomain = async (domainId: string) => {
|
||||
const domain = await findDomainById(domainId);
|
||||
if (!domain.applicationId) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message:
|
||||
"SSO forward-auth is currently only supported on application domains",
|
||||
});
|
||||
}
|
||||
const application = await findApplicationById(domain.applicationId);
|
||||
return { domain, application };
|
||||
};
|
||||
|
||||
export const assertApplicationDomainAccess = async (
|
||||
ctx: { session: { activeOrganizationId: string } },
|
||||
domainId: string,
|
||||
action: "create" | "delete",
|
||||
) => {
|
||||
const domain = await findDomainById(domainId);
|
||||
if (!domain.applicationId) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message:
|
||||
"SSO forward-auth is currently only supported on application domains",
|
||||
});
|
||||
}
|
||||
await checkServicePermissionAndAccess(ctx as any, domain.applicationId, {
|
||||
domain: [action],
|
||||
});
|
||||
return domain;
|
||||
};
|
||||
|
||||
export const enableForwardAuthOnDomain = async (input: {
|
||||
domainId: string;
|
||||
}) => {
|
||||
const { application } = await resolveApplicationDomain(input.domainId);
|
||||
const serverId = application.serverId ?? undefined;
|
||||
|
||||
const settings = await getForwardAuthSettings(serverId ?? null);
|
||||
if (!settings?.providerId) {
|
||||
throw new TRPCError({
|
||||
code: "PRECONDITION_FAILED",
|
||||
message:
|
||||
"Deploy the authentication proxy for this server in SSO settings first.",
|
||||
});
|
||||
}
|
||||
|
||||
const proxyRunning = await isForwardAuthRunning(serverId);
|
||||
if (!proxyRunning) {
|
||||
throw new TRPCError({
|
||||
code: "PRECONDITION_FAILED",
|
||||
message:
|
||||
"The authentication proxy is not deployed on this server. Deploy it in SSO settings first.",
|
||||
});
|
||||
}
|
||||
|
||||
await updateDomainById(input.domainId, { forwardAuthEnabled: true });
|
||||
const domain = await findDomainById(input.domainId);
|
||||
await manageDomain(application, domain);
|
||||
|
||||
return { ok: true } as const;
|
||||
};
|
||||
|
||||
export const disableForwardAuthOnDomain = async (input: {
|
||||
domainId: string;
|
||||
}) => {
|
||||
const { application, domain } = await resolveApplicationDomain(
|
||||
input.domainId,
|
||||
);
|
||||
const uniqueConfigKey = domain.uniqueConfigKey;
|
||||
|
||||
await updateDomainById(input.domainId, { forwardAuthEnabled: false });
|
||||
const updated = await findDomainById(input.domainId);
|
||||
await manageDomain(application, updated);
|
||||
await removeForwardAuthMiddleware(application, uniqueConfigKey);
|
||||
|
||||
return { ok: true } as const;
|
||||
};
|
||||
58
packages/server/src/services/proprietary/whitelabeling.ts
Normal file
58
packages/server/src/services/proprietary/whitelabeling.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { IS_CLOUD } from "@dokploy/server/constants";
|
||||
import { db } from "@dokploy/server/db";
|
||||
import { hasValidLicense } from "@dokploy/server/services/proprietary/license-key";
|
||||
import { getWebServerSettings } from "@dokploy/server/services/web-server-settings";
|
||||
|
||||
export interface PublicWhitelabelingConfig {
|
||||
appName: string | null;
|
||||
appDescription: string | null;
|
||||
logoUrl: string | null;
|
||||
loginLogoUrl: string | null;
|
||||
faviconUrl: string | null;
|
||||
customCss: string | null;
|
||||
metaTitle: string | null;
|
||||
errorPageTitle: string | null;
|
||||
errorPageDescription: string | null;
|
||||
footerText: string | null;
|
||||
}
|
||||
|
||||
// Self-hosted is single-tenant; gate on the oldest organization's license,
|
||||
// mirroring resolveLocalConcurrency in server/queues/concurrency.ts. Used only
|
||||
// for unauthenticated requests (no active organization in session).
|
||||
const hasAnyValidLicense = async (): Promise<boolean> => {
|
||||
const org = await db.query.organization.findFirst({
|
||||
columns: { id: true },
|
||||
orderBy: (organization, { asc }) => [asc(organization.createdAt)],
|
||||
});
|
||||
return org ? await hasValidLicense(org.id) : false;
|
||||
};
|
||||
|
||||
/**
|
||||
* Public whitelabeling config for unauthenticated contexts (login page, SSR
|
||||
* document shell). No active organization/session is available here.
|
||||
*/
|
||||
export const getPublicWhitelabelingConfig =
|
||||
async (): Promise<PublicWhitelabelingConfig | null> => {
|
||||
if (IS_CLOUD) {
|
||||
return null;
|
||||
}
|
||||
if (!(await hasAnyValidLicense())) {
|
||||
return null;
|
||||
}
|
||||
const settings = await getWebServerSettings();
|
||||
const config = settings?.whitelabelingConfig;
|
||||
if (!config) return null;
|
||||
|
||||
return {
|
||||
appName: config.appName,
|
||||
appDescription: config.appDescription,
|
||||
logoUrl: config.logoUrl,
|
||||
loginLogoUrl: config.loginLogoUrl,
|
||||
faviconUrl: config.faviconUrl,
|
||||
customCss: config.customCss,
|
||||
metaTitle: config.metaTitle,
|
||||
errorPageTitle: config.errorPageTitle,
|
||||
errorPageDescription: config.errorPageDescription,
|
||||
footerText: config.footerText,
|
||||
};
|
||||
};
|
||||
@@ -10,6 +10,7 @@ import { pullImage } from "@dokploy/server/utils/docker/utils";
|
||||
import { execAsyncRemote } from "@dokploy/server/utils/process/execAsync";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { quote } from "shell-quote";
|
||||
import type { z } from "zod";
|
||||
import { validUniqueServerAppName } from "./project";
|
||||
|
||||
@@ -110,7 +111,7 @@ export const deployRedis = async (
|
||||
if (redis.serverId) {
|
||||
await execAsyncRemote(
|
||||
redis.serverId,
|
||||
`docker pull ${redis.dockerImage}`,
|
||||
`docker pull ${quote([redis.dockerImage])}`,
|
||||
onData,
|
||||
);
|
||||
} else {
|
||||
|
||||
@@ -27,6 +27,16 @@ export function safeDockerLoginCommand(
|
||||
return `printf %s ${escapedPassword} | docker login ${escapedRegistry} -u ${escapedUser} --password-stdin`;
|
||||
}
|
||||
|
||||
function sanitizeRegistryError(
|
||||
error: unknown,
|
||||
password: string | null | undefined,
|
||||
): string {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Error with registry login";
|
||||
if (!password) return message;
|
||||
return message.split(password).join("***");
|
||||
}
|
||||
|
||||
export const createRegistry = async (
|
||||
input: z.infer<typeof apiCreateRegistry>,
|
||||
organizationId: string,
|
||||
@@ -59,10 +69,15 @@ export const createRegistry = async (
|
||||
input.username,
|
||||
input.password,
|
||||
);
|
||||
if (input.serverId && input.serverId !== "none") {
|
||||
await execAsyncRemote(input.serverId, loginCommand);
|
||||
} else if (newRegistry.registryType === "cloud") {
|
||||
await execAsync(loginCommand);
|
||||
try {
|
||||
if (input.serverId && input.serverId !== "none") {
|
||||
await execAsyncRemote(input.serverId, loginCommand);
|
||||
} else if (newRegistry.registryType === "cloud") {
|
||||
await execAsync(loginCommand);
|
||||
}
|
||||
} catch (error) {
|
||||
const sanitized = sanitizeRegistryError(error, input.password);
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: sanitized });
|
||||
}
|
||||
|
||||
return newRegistry;
|
||||
@@ -85,7 +100,7 @@ export const removeRegistry = async (registryId: string) => {
|
||||
}
|
||||
|
||||
if (!IS_CLOUD) {
|
||||
await execAsync(`docker logout ${response.registryUrl}`);
|
||||
await execAsync(`docker logout ${shEscape(response.registryUrl)}`);
|
||||
}
|
||||
|
||||
return response;
|
||||
@@ -129,16 +144,24 @@ export const updateRegistry = async (
|
||||
});
|
||||
}
|
||||
|
||||
if (registryData?.serverId && registryData?.serverId !== "none") {
|
||||
await execAsyncRemote(registryData.serverId, loginCommand);
|
||||
} else if (response?.registryType === "cloud") {
|
||||
await execAsync(loginCommand);
|
||||
try {
|
||||
if (registryData?.serverId && registryData?.serverId !== "none") {
|
||||
await execAsyncRemote(registryData.serverId, loginCommand);
|
||||
} else if (response?.registryType === "cloud") {
|
||||
await execAsync(loginCommand);
|
||||
}
|
||||
} catch (execError) {
|
||||
throw new Error(sanitizeRegistryError(execError, response?.password));
|
||||
}
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Error updating this registry";
|
||||
error instanceof TRPCError
|
||||
? error.message
|
||||
: error instanceof Error
|
||||
? error.message
|
||||
: "Error updating this registry";
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message,
|
||||
@@ -162,6 +185,19 @@ export const findRegistryById = async (registryId: string) => {
|
||||
return registryResponse;
|
||||
};
|
||||
|
||||
export const findRegistryByIdWithCredentials = async (registryId: string) => {
|
||||
const registryResponse = await db.query.registry.findFirst({
|
||||
where: eq(registry.registryId, registryId),
|
||||
});
|
||||
if (!registryResponse) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Registry not found",
|
||||
});
|
||||
}
|
||||
return registryResponse;
|
||||
};
|
||||
|
||||
export const findAllRegistryByOrganizationId = async (
|
||||
organizationId: string,
|
||||
) => {
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
deployments as deploymentsSchema,
|
||||
rollbacks,
|
||||
} from "../db/schema";
|
||||
import type { ApplicationNested } from "../utils/builders";
|
||||
import { getRegistryTag } from "../utils/cluster/upload";
|
||||
import {
|
||||
calculateResources,
|
||||
@@ -23,7 +22,11 @@ import { findDeploymentById } from "./deployment";
|
||||
import type { Mount } from "./mount";
|
||||
import type { Port } from "./port";
|
||||
import type { Project } from "./project";
|
||||
import { type Registry, safeDockerLoginCommand } from "./registry";
|
||||
import {
|
||||
findRegistryByIdWithCredentials,
|
||||
type Registry,
|
||||
safeDockerLoginCommand,
|
||||
} from "./registry";
|
||||
|
||||
export const createRollback = async (
|
||||
input: z.infer<typeof createRollbackSchema>,
|
||||
@@ -56,11 +59,29 @@ export const createRollback = async (
|
||||
...rest
|
||||
} = await findApplicationById(deployment.applicationId);
|
||||
|
||||
const registry = rest.registryId
|
||||
? await findRegistryByIdWithCredentials(rest.registryId)
|
||||
: rest.registry;
|
||||
const buildRegistry = rest.buildRegistryId
|
||||
? await findRegistryByIdWithCredentials(rest.buildRegistryId)
|
||||
: rest.buildRegistry;
|
||||
const rollbackRegistry = rest.rollbackRegistryId
|
||||
? await findRegistryByIdWithCredentials(rest.rollbackRegistryId)
|
||||
: rest.rollbackRegistry;
|
||||
|
||||
const fullContextWithCredentials = {
|
||||
...rest,
|
||||
registry,
|
||||
buildRegistry,
|
||||
rollbackRegistry,
|
||||
};
|
||||
|
||||
await tx
|
||||
.update(rollbacks)
|
||||
.set({
|
||||
image: tagImage,
|
||||
fullContext: rest,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
fullContext: fullContextWithCredentials as any,
|
||||
})
|
||||
.where(eq(rollbacks.rollbackId, rollback.rollbackId));
|
||||
|
||||
@@ -162,7 +183,6 @@ export const rollback = async (rollbackId: string) => {
|
||||
if (!result.fullContext) {
|
||||
throw new Error("Rollback context not found");
|
||||
}
|
||||
// Use the full context for rollback
|
||||
await rollbackApplication(
|
||||
application.appName,
|
||||
result.image || "",
|
||||
@@ -198,24 +218,25 @@ const rollbackApplication = async (
|
||||
};
|
||||
mounts: Mount[];
|
||||
ports: Port[];
|
||||
rollbackRegistry?: Registry;
|
||||
rollbackRegistry?: Registry | null;
|
||||
},
|
||||
) => {
|
||||
if (!fullContext) {
|
||||
throw new Error("Full context is required for rollback");
|
||||
}
|
||||
|
||||
const rollbackRegistry = fullContext.rollbackRegistry ?? undefined;
|
||||
|
||||
// Ensure Docker daemon is authenticated with the rollback registry
|
||||
// before updating the swarm service. The authconfig in CreateServiceOptions
|
||||
// alone is not sufficient — Docker Swarm also relies on the daemon's
|
||||
// cached credentials (~/.docker/config.json) to distribute auth to nodes.
|
||||
if (fullContext.rollbackRegistry) {
|
||||
await dockerLoginForRegistry(fullContext.rollbackRegistry, serverId);
|
||||
if (rollbackRegistry) {
|
||||
await dockerLoginForRegistry(rollbackRegistry, serverId);
|
||||
}
|
||||
|
||||
const docker = await getRemoteDocker(serverId);
|
||||
|
||||
// Use the same configuration as mechanizeDockerContainer
|
||||
const {
|
||||
env,
|
||||
mounts,
|
||||
@@ -246,7 +267,9 @@ const rollbackApplication = async (
|
||||
UpdateConfig,
|
||||
Networks,
|
||||
Ulimits,
|
||||
} = generateConfigContainer(fullContext as ApplicationNested);
|
||||
} = generateConfigContainer(
|
||||
fullContext as Parameters<typeof generateConfigContainer>[0],
|
||||
);
|
||||
|
||||
const bindsMount = generateBindMounts(mounts);
|
||||
const envVariables = prepareEnvironmentVariables(
|
||||
@@ -254,18 +277,16 @@ const rollbackApplication = async (
|
||||
fullContext.environment.project.env,
|
||||
);
|
||||
|
||||
// Build the full registry image path if rollbackRegistry is available
|
||||
// e.g., "appName:v5" -> "siumauricio/appName:v5" or "registry.com/prefix/appName:v5"
|
||||
let rollbackImage = image;
|
||||
if (fullContext.rollbackRegistry) {
|
||||
rollbackImage = getRegistryTag(fullContext.rollbackRegistry, image);
|
||||
if (rollbackRegistry) {
|
||||
rollbackImage = getRegistryTag(rollbackRegistry, image);
|
||||
}
|
||||
|
||||
const settings: CreateServiceOptions = {
|
||||
authconfig: {
|
||||
password: fullContext.rollbackRegistry?.password || "",
|
||||
username: fullContext.rollbackRegistry?.username || "",
|
||||
serveraddress: fullContext.rollbackRegistry?.registryUrl || "",
|
||||
password: rollbackRegistry?.password || "",
|
||||
username: rollbackRegistry?.username || "",
|
||||
serveraddress: rollbackRegistry?.registryUrl || "",
|
||||
},
|
||||
Name: appName,
|
||||
TaskTemplate: {
|
||||
|
||||
@@ -2,7 +2,7 @@ import path from "node:path";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { z } from "zod";
|
||||
import { paths } from "../constants";
|
||||
import { IS_CLOUD, paths } from "../constants";
|
||||
import { db } from "../db";
|
||||
import type {
|
||||
createScheduleSchema,
|
||||
@@ -11,9 +11,51 @@ import type {
|
||||
import { type Schedule, schedules } from "../db/schema/schedule";
|
||||
import { encodeBase64 } from "../utils/docker/utils";
|
||||
import { execAsync, execAsyncRemote } from "../utils/process/execAsync";
|
||||
import { findMemberByUserId } from "./permission";
|
||||
import { findServerById } from "./server";
|
||||
|
||||
export type ScheduleExtended = Awaited<ReturnType<typeof findScheduleById>>;
|
||||
|
||||
// Host-level schedules (server / dokploy-server) run their script as root on the
|
||||
// host and must stay restricted to owners/admins, regardless of whether the
|
||||
// request is also tied to a service. Attaching an accessible applicationId must
|
||||
// not downgrade this to a service-access check.
|
||||
export const assertHostScheduleAccess = async (
|
||||
ctx: { user: { id: string }; session: { activeOrganizationId: string } },
|
||||
scheduleType: Schedule["scheduleType"] | null | undefined,
|
||||
serverId: string | null | undefined,
|
||||
) => {
|
||||
if (scheduleType !== "server" && scheduleType !== "dokploy-server") return;
|
||||
|
||||
if (scheduleType === "dokploy-server" && IS_CLOUD) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "Host-level schedules are not available in the cloud version.",
|
||||
});
|
||||
}
|
||||
|
||||
const member = await findMemberByUserId(
|
||||
ctx.user.id,
|
||||
ctx.session.activeOrganizationId,
|
||||
);
|
||||
if (member.role !== "owner" && member.role !== "admin") {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "Only owners and admins can manage server-level schedules.",
|
||||
});
|
||||
}
|
||||
|
||||
if (scheduleType === "server" && serverId) {
|
||||
const targetServer = await findServerById(serverId);
|
||||
if (targetServer.organizationId !== ctx.session.activeOrganizationId) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "You don't have access to this server.",
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const createSchedule = async (
|
||||
input: z.infer<typeof createScheduleSchema>,
|
||||
) => {
|
||||
@@ -85,6 +127,9 @@ export const findScheduleOrganizationId = async (scheduleId: string) => {
|
||||
if (schedule?.server) {
|
||||
return schedule?.server?.organization?.id;
|
||||
}
|
||||
if (schedule?.organizationId) {
|
||||
return schedule.organizationId;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
|
||||
@@ -53,6 +53,27 @@ export const findServerById = async (serverId: string) => {
|
||||
return currentServer;
|
||||
};
|
||||
|
||||
/**
|
||||
* Removes the SSH private key material from a server record before it is sent
|
||||
* to a client. `findServerById` eagerly loads the `sshKey` relation (needed for
|
||||
* server-side SSH operations), but the private key must never leave the server:
|
||||
* no client feature consumes it, and returning it exposed it to any member with
|
||||
* only `server:read`. Server-side callers keep using `findServerById` directly.
|
||||
*/
|
||||
export const redactServerSshKey = <
|
||||
T extends { sshKey?: { privateKey: string } | null },
|
||||
>(
|
||||
serverRecord: T,
|
||||
): T => {
|
||||
if (!serverRecord.sshKey) {
|
||||
return serverRecord;
|
||||
}
|
||||
return {
|
||||
...serverRecord,
|
||||
sshKey: { ...serverRecord.sshKey, privateKey: "" },
|
||||
};
|
||||
};
|
||||
|
||||
export const findServersByUserId = async (userId: string) => {
|
||||
const orgs = await db.query.organization.findMany({
|
||||
where: eq(organization.ownerId, userId),
|
||||
|
||||
@@ -430,7 +430,7 @@ export const createOrganizationUserWithCredentials = async ({
|
||||
.insert(user)
|
||||
.values({
|
||||
email: normalizedEmail,
|
||||
emailVerified: false,
|
||||
emailVerified: true,
|
||||
updatedAt: now,
|
||||
})
|
||||
.returning({
|
||||
|
||||
@@ -84,7 +84,12 @@ export const findVolumeBackupById = async (volumeBackupId: string) => {
|
||||
},
|
||||
},
|
||||
},
|
||||
destination: true,
|
||||
destination: {
|
||||
columns: {
|
||||
accessKey: false,
|
||||
secretAccessKey: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
158
packages/server/src/setup/forward-auth-setup.ts
Normal file
158
packages/server/src/setup/forward-auth-setup.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import { createHmac } from "node:crypto";
|
||||
import type { CreateServiceOptions } from "dockerode";
|
||||
import { betterAuthSecret } from "../lib/auth-secret";
|
||||
import { getRemoteDocker } from "../utils/servers/remote-docker";
|
||||
|
||||
export const FORWARD_AUTH_SERVICE_NAME = "dokploy-forward-auth";
|
||||
const FORWARD_AUTH_IMAGE = "quay.io/oauth2-proxy/oauth2-proxy:v7.6.0";
|
||||
|
||||
export const FORWARD_AUTH_PORT = 4180;
|
||||
|
||||
export interface ForwardAuthOidcConfig {
|
||||
clientId: string;
|
||||
clientSecret: string;
|
||||
issuer: string;
|
||||
scopes?: string[];
|
||||
skipDiscovery?: boolean;
|
||||
}
|
||||
|
||||
export interface SetupForwardAuthOptions {
|
||||
serverId?: string;
|
||||
oidc: ForwardAuthOidcConfig;
|
||||
cookieSecret: string;
|
||||
authDomain: string;
|
||||
baseDomain: string;
|
||||
authDomainHttps?: boolean;
|
||||
emailDomains?: string[];
|
||||
}
|
||||
|
||||
export const deriveBaseDomain = (authDomain: string): string => {
|
||||
const labels = authDomain.trim().toLowerCase().split(".").filter(Boolean);
|
||||
const base = labels.length > 2 ? labels.slice(1) : labels;
|
||||
return `.${base.join(".")}`;
|
||||
};
|
||||
|
||||
export const forwardAuthCallbackUrl = (
|
||||
authDomain: string,
|
||||
https: boolean,
|
||||
): string => `${https ? "https" : "http"}://${authDomain}/oauth2/callback`;
|
||||
|
||||
export const deriveCookieSecret = (salt: string): string => {
|
||||
// oauth2-proxy requires cookie_secret to be exactly 16, 24, or 32 bytes.
|
||||
// Take the first 32 hex chars (= 16 bytes) to satisfy that constraint.
|
||||
return createHmac("sha256", betterAuthSecret)
|
||||
.update(`forward-auth:${salt}`)
|
||||
.digest("hex")
|
||||
.slice(0, 32);
|
||||
};
|
||||
|
||||
export const buildForwardAuthEnv = (
|
||||
options: SetupForwardAuthOptions,
|
||||
): string[] => {
|
||||
const { oidc, cookieSecret, authDomain, baseDomain, authDomainHttps } =
|
||||
options;
|
||||
const scheme = authDomainHttps ? "https" : "http";
|
||||
const emailDomains =
|
||||
options.emailDomains && options.emailDomains.length > 0
|
||||
? options.emailDomains
|
||||
: ["*"];
|
||||
|
||||
const env: string[] = [
|
||||
"OAUTH2_PROXY_PROVIDER=oidc",
|
||||
`OAUTH2_PROXY_OIDC_ISSUER_URL=${oidc.issuer}`,
|
||||
`OAUTH2_PROXY_CLIENT_ID=${oidc.clientId}`,
|
||||
`OAUTH2_PROXY_CLIENT_SECRET=${oidc.clientSecret}`,
|
||||
`OAUTH2_PROXY_COOKIE_SECRET=${cookieSecret}`,
|
||||
`OAUTH2_PROXY_HTTP_ADDRESS=0.0.0.0:${FORWARD_AUTH_PORT}`,
|
||||
"OAUTH2_PROXY_REVERSE_PROXY=true",
|
||||
"OAUTH2_PROXY_SKIP_PROVIDER_BUTTON=true",
|
||||
"OAUTH2_PROXY_SET_XAUTHREQUEST=true",
|
||||
"OAUTH2_PROXY_UPSTREAMS=static://202",
|
||||
`OAUTH2_PROXY_REDIRECT_URL=${scheme}://${authDomain}/oauth2/callback`,
|
||||
`OAUTH2_PROXY_COOKIE_DOMAINS=${baseDomain}`,
|
||||
`OAUTH2_PROXY_WHITELIST_DOMAINS=${baseDomain}`,
|
||||
`OAUTH2_PROXY_COOKIE_SECURE=${authDomainHttps ? "true" : "false"}`,
|
||||
"OAUTH2_PROXY_INSECURE_OIDC_ALLOW_UNVERIFIED_EMAIL=true",
|
||||
`OAUTH2_PROXY_EMAIL_DOMAINS=${emailDomains.join(",")}`,
|
||||
];
|
||||
|
||||
const scopes = oidc.scopes?.length
|
||||
? oidc.scopes
|
||||
: ["openid", "email", "profile"];
|
||||
env.push(`OAUTH2_PROXY_SCOPE=${scopes.join(" ")}`);
|
||||
|
||||
if (oidc.skipDiscovery) {
|
||||
env.push("OAUTH2_PROXY_SKIP_OIDC_DISCOVERY=true");
|
||||
}
|
||||
|
||||
return env;
|
||||
};
|
||||
|
||||
export const setupForwardAuth = async (options: SetupForwardAuthOptions) => {
|
||||
const { serverId } = options;
|
||||
const docker = await getRemoteDocker(serverId);
|
||||
|
||||
const settings: CreateServiceOptions = {
|
||||
Name: FORWARD_AUTH_SERVICE_NAME,
|
||||
TaskTemplate: {
|
||||
ContainerSpec: {
|
||||
Image: FORWARD_AUTH_IMAGE,
|
||||
Env: buildForwardAuthEnv(options),
|
||||
},
|
||||
Networks: [{ Target: "dokploy-network" }],
|
||||
Placement: {
|
||||
Constraints: ["node.role==manager"],
|
||||
},
|
||||
},
|
||||
Mode: {
|
||||
Replicated: {
|
||||
Replicas: 1,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
const service = docker.getService(FORWARD_AUTH_SERVICE_NAME);
|
||||
const inspect = await service.inspect();
|
||||
await service.update({
|
||||
version: Number.parseInt(inspect.Version.Index),
|
||||
...settings,
|
||||
TaskTemplate: {
|
||||
...settings.TaskTemplate,
|
||||
ForceUpdate: inspect.Spec.TaskTemplate.ForceUpdate + 1,
|
||||
},
|
||||
});
|
||||
console.log("Forward Auth Updated ✅");
|
||||
} catch (_) {
|
||||
try {
|
||||
await docker.createService(settings);
|
||||
console.log("Forward Auth Started ✅");
|
||||
} catch (error: any) {
|
||||
if (error?.statusCode !== 409) {
|
||||
throw error;
|
||||
}
|
||||
console.log("Forward Auth service already exists, continuing...");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const removeForwardAuth = async (serverId?: string) => {
|
||||
const docker = await getRemoteDocker(serverId);
|
||||
try {
|
||||
const service = docker.getService(FORWARD_AUTH_SERVICE_NAME);
|
||||
await service.remove();
|
||||
console.log("Forward Auth Removed ✅");
|
||||
} catch {}
|
||||
};
|
||||
|
||||
export const isForwardAuthRunning = async (
|
||||
serverId?: string,
|
||||
): Promise<boolean> => {
|
||||
const docker = await getRemoteDocker(serverId);
|
||||
try {
|
||||
await docker.getService(FORWARD_AUTH_SERVICE_NAME).inspect();
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
@@ -3,7 +3,7 @@ import { docker } from "../constants";
|
||||
import { pullImage } from "../utils/docker/utils";
|
||||
|
||||
export const initializeRedis = async () => {
|
||||
const imageName = "redis:7";
|
||||
const imageName = "redis:8";
|
||||
const containerName = "dokploy-redis";
|
||||
|
||||
const settings: CreateServiceOptions = {
|
||||
|
||||
@@ -106,6 +106,21 @@ export const serverSetup = async (
|
||||
}
|
||||
};
|
||||
|
||||
export const reportDockerVersion = () => `
|
||||
if command -v docker >/dev/null 2>&1; then
|
||||
INSTALLED_DOCKER_VERSION=$(docker version --format '{{.Server.Version}}' 2>/dev/null || true)
|
||||
if [ -z "$INSTALLED_DOCKER_VERSION" ]; then
|
||||
INSTALLED_DOCKER_VERSION=$(docker --version 2>/dev/null | awk '{print $3}' | tr -d ',' || true)
|
||||
fi
|
||||
if [ -z "$INSTALLED_DOCKER_VERSION" ]; then
|
||||
INSTALLED_DOCKER_VERSION="unknown"
|
||||
fi
|
||||
DOCKER_VERSION_REPORT="$INSTALLED_DOCKER_VERSION (already installed)"
|
||||
else
|
||||
DOCKER_VERSION_REPORT="$DOCKER_VERSION (will be installed)"
|
||||
fi
|
||||
`;
|
||||
|
||||
export const defaultCommand = (isBuildServer = false) => {
|
||||
const bashCommand = `
|
||||
set -e;
|
||||
@@ -174,10 +189,11 @@ arch | ubuntu | debian | raspbian | centos | fedora | rhel | ol | rocky | sles |
|
||||
;;
|
||||
esac
|
||||
|
||||
${reportDockerVersion()}
|
||||
echo -e "---------------------------------------------"
|
||||
echo "| CPU Architecture | $SYS_ARCH"
|
||||
echo "| Operating System | $OS_TYPE $OS_VERSION"
|
||||
echo "| Docker | $DOCKER_VERSION"
|
||||
echo "| Docker | $DOCKER_VERSION_REPORT"
|
||||
${isBuildServer ? 'echo "| Server Type | Build Server"' : ""}
|
||||
echo -e "---------------------------------------------\n"
|
||||
echo -e "1. Installing required packages (curl, wget, git, jq, openssl). "
|
||||
|
||||
@@ -21,6 +21,7 @@ export interface CompleteTemplate {
|
||||
[key: string]: string;
|
||||
};
|
||||
config: {
|
||||
isolated?: boolean;
|
||||
domains: Array<{
|
||||
serviceName: string;
|
||||
port: number;
|
||||
@@ -55,25 +56,22 @@ interface TemplateMetadata {
|
||||
export async function fetchTemplatesList(
|
||||
baseUrl = "https://templates.dokploy.com",
|
||||
): Promise<TemplateMetadata[]> {
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}/meta.json`);
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch templates: ${response.statusText}`);
|
||||
}
|
||||
const templates = (await response.json()) as TemplateMetadata[];
|
||||
return templates.map((template) => ({
|
||||
id: template.id,
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
version: template.version,
|
||||
logo: template.logo,
|
||||
links: template.links,
|
||||
tags: template.tags,
|
||||
}));
|
||||
} catch (error) {
|
||||
console.error("Error fetching templates list:", error);
|
||||
throw error;
|
||||
const response = await fetch(`${baseUrl}/meta.json`, {
|
||||
signal: AbortSignal.timeout(10000),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch templates: ${response.statusText}`);
|
||||
}
|
||||
const templates = (await response.json()) as TemplateMetadata[];
|
||||
return templates.map((template) => ({
|
||||
id: template.id,
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
version: template.version,
|
||||
logo: template.logo,
|
||||
links: template.links,
|
||||
tags: template.tags,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -83,27 +81,26 @@ export async function fetchTemplateFiles(
|
||||
templateId: string,
|
||||
baseUrl = "https://templates.dokploy.com",
|
||||
): Promise<{ config: CompleteTemplate; dockerCompose: string }> {
|
||||
try {
|
||||
// Fetch both files in parallel
|
||||
const [templateYmlResponse, dockerComposeResponse] = await Promise.all([
|
||||
fetch(`${baseUrl}/blueprints/${templateId}/template.toml`),
|
||||
fetch(`${baseUrl}/blueprints/${templateId}/docker-compose.yml`),
|
||||
]);
|
||||
const timeout = AbortSignal.timeout(10000);
|
||||
const [templateYmlResponse, dockerComposeResponse] = await Promise.all([
|
||||
fetch(`${baseUrl}/blueprints/${templateId}/template.toml`, {
|
||||
signal: timeout,
|
||||
}),
|
||||
fetch(`${baseUrl}/blueprints/${templateId}/docker-compose.yml`, {
|
||||
signal: timeout,
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!templateYmlResponse.ok || !dockerComposeResponse.ok) {
|
||||
throw new Error("Template files not found");
|
||||
}
|
||||
|
||||
const [templateYml, dockerCompose] = await Promise.all([
|
||||
templateYmlResponse.text(),
|
||||
dockerComposeResponse.text(),
|
||||
]);
|
||||
|
||||
const config = parse(templateYml) as CompleteTemplate;
|
||||
|
||||
return { config, dockerCompose };
|
||||
} catch (error) {
|
||||
console.error(`Error fetching template ${templateId}:`, error);
|
||||
throw error;
|
||||
if (!templateYmlResponse.ok || !dockerComposeResponse.ok) {
|
||||
throw new Error("Template files not found");
|
||||
}
|
||||
|
||||
const [templateYml, dockerCompose] = await Promise.all([
|
||||
templateYmlResponse.text(),
|
||||
dockerComposeResponse.text(),
|
||||
]);
|
||||
|
||||
const config = parse(templateYml) as CompleteTemplate;
|
||||
|
||||
return { config, dockerCompose };
|
||||
}
|
||||
|
||||
@@ -38,15 +38,15 @@ export const generateRandomDomain = ({
|
||||
const slugIp = serverIp.replaceAll(".", "-").replaceAll(":", "-");
|
||||
|
||||
// Domain labels have a max length of 63 characters
|
||||
// Reserve space for: hash (6) + separators (1-2) + ip section + dot + traefik.me (10)
|
||||
// Approx: 6 + 2 + (variable ip length) + 11 = ~19-30 chars for other parts
|
||||
// Reserve space for: hash (6) + separators (1-2) + ip section + dot + sslip.io (8)
|
||||
// Approx: 6 + 2 + (variable ip length) + 9 = ~19-30 chars for other parts
|
||||
const maxProjectNameLength = 40;
|
||||
const truncatedProjectName =
|
||||
projectName.length > maxProjectNameLength
|
||||
? projectName.substring(0, maxProjectNameLength)
|
||||
: projectName;
|
||||
|
||||
return `${truncatedProjectName}-${hash}${slugIp === "" ? "" : `-${slugIp}`}.traefik.me`;
|
||||
return `${truncatedProjectName}-${hash}${slugIp === "" ? "" : `-${slugIp}`}.sslip.io`;
|
||||
};
|
||||
|
||||
export const generateHash = (length = 8): string => {
|
||||
|
||||
@@ -45,6 +45,7 @@ export interface CompleteTemplate {
|
||||
};
|
||||
variables: Record<string, string>;
|
||||
config: {
|
||||
isolated?: boolean;
|
||||
domains: DomainConfig[];
|
||||
env:
|
||||
| Record<string, string | boolean | number>
|
||||
|
||||
@@ -32,7 +32,19 @@ export const startLogCleanup = async (
|
||||
await execAsync(
|
||||
`tail -n 1000 ${accessLogPath} > ${accessLogPath}.tmp && mv ${accessLogPath}.tmp ${accessLogPath}`,
|
||||
);
|
||||
await execAsync("docker exec dokploy-traefik kill -USR1 1");
|
||||
|
||||
// Traefik can run as a standalone container ("dokploy-traefik") or a
|
||||
// swarm service task ("dokploy-traefik.1.<task-id>"), so resolve the
|
||||
// running container id dynamically instead of assuming the name.
|
||||
const { stdout: containerId } = await execAsync(
|
||||
'docker ps -q --filter "name=dokploy-traefik" --filter "status=running" | head -n 1',
|
||||
);
|
||||
const traefikContainerId = containerId.trim();
|
||||
if (!traefikContainerId) {
|
||||
console.error("Traefik container not found, skipping log reopen");
|
||||
return;
|
||||
}
|
||||
await execAsync(`docker exec ${traefikContainerId} kill -USR1 1`);
|
||||
} catch (error) {
|
||||
console.error("Error during log cleanup:", error);
|
||||
}
|
||||
|
||||
@@ -120,7 +120,7 @@ export function parseRawConfig(
|
||||
|
||||
if (search) {
|
||||
parsedLogs = parsedLogs.filter((log) =>
|
||||
log.RequestPath.toLowerCase().includes(search.toLowerCase()),
|
||||
log.RequestHost.toLowerCase().includes(search.toLowerCase()),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -74,8 +74,10 @@ export function selectAIProvider(config: { apiUrl: string; apiKey: string }) {
|
||||
});
|
||||
case "ollama":
|
||||
return createOllama({
|
||||
// optional settings, e.g.
|
||||
baseURL: config.apiUrl,
|
||||
headers: config.apiKey
|
||||
? { Authorization: `Bearer ${config.apiKey}` }
|
||||
: undefined,
|
||||
});
|
||||
case "deepinfra":
|
||||
return createDeepInfra({
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
createDeploymentBackup,
|
||||
updateDeploymentStatus,
|
||||
} from "@dokploy/server/services/deployment";
|
||||
import { findDestinationById } from "@dokploy/server/services/destination";
|
||||
import { findEnvironmentById } from "@dokploy/server/services/environment";
|
||||
import { findProjectById } from "@dokploy/server/services/project";
|
||||
import { sendDatabaseBackupNotifications } from "../notifications/database-backup";
|
||||
@@ -23,7 +24,7 @@ export const runComposeBackup = async (
|
||||
const environment = await findEnvironmentById(environmentId);
|
||||
const project = await findProjectById(environment.projectId);
|
||||
const { prefix, databaseType, serviceName } = backup;
|
||||
const destination = backup.destination;
|
||||
const destination = await findDestinationById(backup.destinationId);
|
||||
const backupFileName = `${getBackupTimestamp()}.${databaseType === "mongo" ? "bson" : "sql"}.gz`;
|
||||
const s3AppName = serviceName ? `${appName}_${serviceName}` : appName;
|
||||
const bucketDestination = `${s3AppName}/${normalizeS3Path(prefix)}${backupFileName}`;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { CLEANUP_CRON_JOB } from "@dokploy/server/constants";
|
||||
import { member } from "@dokploy/server/db/schema";
|
||||
import type { BackupSchedule } from "@dokploy/server/services/backup";
|
||||
import { findDestinationById } from "@dokploy/server/services/destination";
|
||||
import { getAllServers } from "@dokploy/server/services/server";
|
||||
import { getWebServerSettings } from "@dokploy/server/services/web-server-settings";
|
||||
import { eq } from "drizzle-orm";
|
||||
@@ -10,6 +11,7 @@ import { startLogCleanup } from "../access-log/handler";
|
||||
import { cleanupAll } from "../docker/utils";
|
||||
import { sendDockerCleanupNotifications } from "../notifications/docker-cleanup";
|
||||
import { execAsync, execAsyncRemote } from "../process/execAsync";
|
||||
import { redactRcloneCredentials } from "./redact";
|
||||
import { getS3Credentials, normalizeS3Path, scheduleBackup } from "./utils";
|
||||
|
||||
export const initCronJobs = async () => {
|
||||
@@ -131,9 +133,10 @@ export const keepLatestNBackups = async (
|
||||
if (!backup.keepLatestCount) return;
|
||||
|
||||
try {
|
||||
const rcloneFlags = getS3Credentials(backup.destination);
|
||||
const destination = await findDestinationById(backup.destinationId);
|
||||
const rcloneFlags = getS3Credentials(destination);
|
||||
const appName = getServiceAppName(backup);
|
||||
const backupFilesPath = `:s3:${backup.destination.bucket}/${appName}/${normalizeS3Path(backup.prefix)}`;
|
||||
const backupFilesPath = `:s3:${destination.bucket}/${appName}/${normalizeS3Path(backup.prefix)}`;
|
||||
|
||||
// --include "*.bson.gz" or "*.sql.gz" or "*.zip" ensures nothing else other than the dokploy backup files are touched by rclone
|
||||
const rcloneList = `rclone lsf ${rcloneFlags.join(" ")} --include "*${backup.databaseType === "web-server" ? ".zip" : ".{sql.gz,bson.gz}"}" ${backupFilesPath}`;
|
||||
@@ -151,6 +154,6 @@ export const keepLatestNBackups = async (
|
||||
await execAsync(rcloneCommand);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
console.error(redactRcloneCredentials(String(error)));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
createDeploymentBackup,
|
||||
updateDeploymentStatus,
|
||||
} from "@dokploy/server/services/deployment";
|
||||
import { findDestinationById } from "@dokploy/server/services/destination";
|
||||
import { findEnvironmentById } from "@dokploy/server/services/environment";
|
||||
import type { Libsql } from "@dokploy/server/services/libsql";
|
||||
import { findProjectById } from "@dokploy/server/services/project";
|
||||
@@ -29,7 +30,7 @@ export const runLibsqlBackup = async (
|
||||
description: "Initializing Backup",
|
||||
});
|
||||
const { prefix } = backup;
|
||||
const destination = backup.destination;
|
||||
const destination = await findDestinationById(backup.destinationId);
|
||||
const backupFileName = `${getBackupTimestamp()}.sql.gz`;
|
||||
const bucketDestination = `${appName}/${normalizeS3Path(prefix)}${backupFileName}`;
|
||||
try {
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
createDeploymentBackup,
|
||||
updateDeploymentStatus,
|
||||
} from "@dokploy/server/services/deployment";
|
||||
import { findDestinationById } from "@dokploy/server/services/destination";
|
||||
import { findEnvironmentById } from "@dokploy/server/services/environment";
|
||||
import type { Mariadb } from "@dokploy/server/services/mariadb";
|
||||
import { findProjectById } from "@dokploy/server/services/project";
|
||||
@@ -23,7 +24,7 @@ export const runMariadbBackup = async (
|
||||
const environment = await findEnvironmentById(environmentId);
|
||||
const project = await findProjectById(environment.projectId);
|
||||
const { prefix } = backup;
|
||||
const destination = backup.destination;
|
||||
const destination = await findDestinationById(backup.destinationId);
|
||||
const backupFileName = `${getBackupTimestamp()}.sql.gz`;
|
||||
const bucketDestination = `${appName}/${normalizeS3Path(prefix)}${backupFileName}`;
|
||||
const deployment = await createDeploymentBackup({
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
createDeploymentBackup,
|
||||
updateDeploymentStatus,
|
||||
} from "@dokploy/server/services/deployment";
|
||||
import { findDestinationById } from "@dokploy/server/services/destination";
|
||||
import { findEnvironmentById } from "@dokploy/server/services/environment";
|
||||
import type { Mongo } from "@dokploy/server/services/mongo";
|
||||
import { findProjectById } from "@dokploy/server/services/project";
|
||||
@@ -20,7 +21,7 @@ export const runMongoBackup = async (mongo: Mongo, backup: BackupSchedule) => {
|
||||
const environment = await findEnvironmentById(environmentId);
|
||||
const project = await findProjectById(environment.projectId);
|
||||
const { prefix } = backup;
|
||||
const destination = backup.destination;
|
||||
const destination = await findDestinationById(backup.destinationId);
|
||||
const backupFileName = `${getBackupTimestamp()}.bson.gz`;
|
||||
const bucketDestination = `${appName}/${normalizeS3Path(prefix)}${backupFileName}`;
|
||||
const deployment = await createDeploymentBackup({
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
createDeploymentBackup,
|
||||
updateDeploymentStatus,
|
||||
} from "@dokploy/server/services/deployment";
|
||||
import { findDestinationById } from "@dokploy/server/services/destination";
|
||||
import { findEnvironmentById } from "@dokploy/server/services/environment";
|
||||
import type { MySql } from "@dokploy/server/services/mysql";
|
||||
import { findProjectById } from "@dokploy/server/services/project";
|
||||
@@ -20,7 +21,7 @@ export const runMySqlBackup = async (mysql: MySql, backup: BackupSchedule) => {
|
||||
const environment = await findEnvironmentById(environmentId);
|
||||
const project = await findProjectById(environment.projectId);
|
||||
const { prefix } = backup;
|
||||
const destination = backup.destination;
|
||||
const destination = await findDestinationById(backup.destinationId);
|
||||
const backupFileName = `${getBackupTimestamp()}.sql.gz`;
|
||||
const bucketDestination = `${appName}/${normalizeS3Path(prefix)}${backupFileName}`;
|
||||
const deployment = await createDeploymentBackup({
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
createDeploymentBackup,
|
||||
updateDeploymentStatus,
|
||||
} from "@dokploy/server/services/deployment";
|
||||
import { findDestinationById } from "@dokploy/server/services/destination";
|
||||
import { findEnvironmentById } from "@dokploy/server/services/environment";
|
||||
import type { Postgres } from "@dokploy/server/services/postgres";
|
||||
import { findProjectById } from "@dokploy/server/services/project";
|
||||
@@ -29,7 +30,7 @@ export const runPostgresBackup = async (
|
||||
description: "Initializing Backup",
|
||||
});
|
||||
const { prefix } = backup;
|
||||
const destination = backup.destination;
|
||||
const destination = await findDestinationById(backup.destinationId);
|
||||
const backupFileName = `${getBackupTimestamp()}.sql.gz`;
|
||||
const bucketDestination = `${appName}/${normalizeS3Path(prefix)}${backupFileName}`;
|
||||
try {
|
||||
|
||||
12
packages/server/src/utils/backups/redact.ts
Normal file
12
packages/server/src/utils/backups/redact.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Redacts S3 credentials from rclone command strings.
|
||||
*
|
||||
* Used to prevent credential leakage in structured logs and error output.
|
||||
* Matches the flag format produced by `getS3Credentials()`:
|
||||
* --s3-access-key-id="VALUE" and --s3-secret-access-key="VALUE"
|
||||
*/
|
||||
export const redactRcloneCredentials = (command: string): string => {
|
||||
return command
|
||||
.replace(/(--s3-access-key-id=)"[^"]*"/g, '$1"[REDACTED]"')
|
||||
.replace(/(--s3-secret-access-key=)"[^"]*"/g, '$1"[REDACTED]"');
|
||||
};
|
||||
@@ -2,6 +2,7 @@ import { logger } from "@dokploy/server/lib/logger";
|
||||
import type { BackupSchedule } from "@dokploy/server/services/backup";
|
||||
import type { Destination } from "@dokploy/server/services/destination";
|
||||
import { scheduledJobs, scheduleJob } from "node-schedule";
|
||||
import { quote } from "shell-quote";
|
||||
import { keepLatestNBackups } from ".";
|
||||
import { runComposeBackup } from "./compose";
|
||||
import { runLibsqlBackup } from "./libsql";
|
||||
@@ -9,6 +10,7 @@ import { runMariadbBackup } from "./mariadb";
|
||||
import { runMongoBackup } from "./mongo";
|
||||
import { runMySqlBackup } from "./mysql";
|
||||
import { runPostgresBackup } from "./postgres";
|
||||
import { redactRcloneCredentials } from "./redact";
|
||||
import { runWebServerBackup } from "./web-server";
|
||||
|
||||
export const scheduleBackup = (backup: BackupSchedule) => {
|
||||
@@ -70,16 +72,16 @@ export const getS3Credentials = (destination: Destination) => {
|
||||
const { accessKey, secretAccessKey, region, endpoint, provider } =
|
||||
destination;
|
||||
const rcloneFlags = [
|
||||
`--s3-access-key-id="${accessKey}"`,
|
||||
`--s3-secret-access-key="${secretAccessKey}"`,
|
||||
`--s3-region="${region}"`,
|
||||
`--s3-endpoint="${endpoint}"`,
|
||||
`--s3-access-key-id=${quote([accessKey])}`,
|
||||
`--s3-secret-access-key=${quote([secretAccessKey])}`,
|
||||
`--s3-region=${quote([region])}`,
|
||||
`--s3-endpoint=${quote([endpoint])}`,
|
||||
"--s3-no-check-bucket",
|
||||
"--s3-force-path-style",
|
||||
];
|
||||
|
||||
if (provider) {
|
||||
rcloneFlags.unshift(`--s3-provider="${provider}"`);
|
||||
rcloneFlags.unshift(`--s3-provider=${quote([provider])}`);
|
||||
}
|
||||
|
||||
if (destination.additionalFlags?.length) {
|
||||
@@ -89,11 +91,16 @@ export const getS3Credentials = (destination: Destination) => {
|
||||
return rcloneFlags;
|
||||
};
|
||||
|
||||
// User-controlled values (database name, user, password) are passed to the
|
||||
// container as environment variables via `docker exec -e VAR=<escaped>` and
|
||||
// referenced as "$VAR" inside the inner shell, so they never appear in the
|
||||
// inner command text. The -e value is escaped for the outer shell with
|
||||
// shell-quote; the inner script is single-quoted and reads the env vars.
|
||||
export const getPostgresBackupCommand = (
|
||||
database: string,
|
||||
databaseUser: string,
|
||||
) => {
|
||||
return `docker exec -i $CONTAINER_ID bash -c "set -o pipefail; pg_dump -Fc --no-acl --no-owner -h localhost -U ${databaseUser} --no-password '${database}' | gzip"`;
|
||||
return `docker exec -e DB_NAME=${quote([database])} -e DB_USER=${quote([databaseUser])} -i $CONTAINER_ID bash -c 'set -o pipefail; pg_dump -Fc --no-acl --no-owner -h localhost -U "$DB_USER" --no-password "$DB_NAME" | gzip'`;
|
||||
};
|
||||
|
||||
export const getMariadbBackupCommand = (
|
||||
@@ -101,14 +108,14 @@ export const getMariadbBackupCommand = (
|
||||
databaseUser: string,
|
||||
databasePassword: string,
|
||||
) => {
|
||||
return `docker exec -i $CONTAINER_ID bash -c "set -o pipefail; mariadb-dump --user='${databaseUser}' --password='${databasePassword}' --single-transaction --quick --databases ${database} | gzip"`;
|
||||
return `docker exec -e DB_NAME=${quote([database])} -e DB_USER=${quote([databaseUser])} -e DB_PASS=${quote([databasePassword])} -i $CONTAINER_ID bash -c 'set -o pipefail; mariadb-dump --user="$DB_USER" --password="$DB_PASS" --single-transaction --quick --databases "$DB_NAME" | gzip'`;
|
||||
};
|
||||
|
||||
export const getMysqlBackupCommand = (
|
||||
database: string,
|
||||
databasePassword: string,
|
||||
) => {
|
||||
return `docker exec -i $CONTAINER_ID bash -c "set -o pipefail; mysqldump --default-character-set=utf8mb4 -u 'root' --password='${databasePassword}' --single-transaction --no-tablespaces --quick '${database}' | gzip"`;
|
||||
return `docker exec -e DB_NAME=${quote([database])} -e DB_PASS=${quote([databasePassword])} -i $CONTAINER_ID bash -c 'set -o pipefail; mysqldump --default-character-set=utf8mb4 -u root --password="$DB_PASS" --single-transaction --no-tablespaces --quick "$DB_NAME" | gzip'`;
|
||||
};
|
||||
|
||||
export const getMongoBackupCommand = (
|
||||
@@ -116,11 +123,11 @@ export const getMongoBackupCommand = (
|
||||
databaseUser: string,
|
||||
databasePassword: string,
|
||||
) => {
|
||||
return `docker exec -i $CONTAINER_ID bash -c "set -o pipefail; mongodump -d '${database}' -u '${databaseUser}' -p '${databasePassword}' --archive --authenticationDatabase admin --gzip"`;
|
||||
return `docker exec -e DB_NAME=${quote([database])} -e DB_USER=${quote([databaseUser])} -e DB_PASS=${quote([databasePassword])} -i $CONTAINER_ID bash -c 'set -o pipefail; mongodump -d "$DB_NAME" -u "$DB_USER" -p "$DB_PASS" --archive --authenticationDatabase admin --gzip'`;
|
||||
};
|
||||
|
||||
export const getLibsqlBackupCommand = (database: string) => {
|
||||
return `docker exec -i $CONTAINER_ID sh -c "tar cf - -C /var/lib/sqld ${database} | gzip"`;
|
||||
return `docker exec -e DB_NAME=${quote([database])} -i $CONTAINER_ID sh -c 'tar cf - -C /var/lib/sqld "$DB_NAME" | gzip'`;
|
||||
};
|
||||
|
||||
export const getServiceContainerCommand = (appName: string) => {
|
||||
@@ -262,7 +269,7 @@ export const getBackupCommand = (
|
||||
{
|
||||
containerSearch,
|
||||
backupCommand,
|
||||
rcloneCommand,
|
||||
rcloneCommand: redactRcloneCredentials(rcloneCommand),
|
||||
logPath,
|
||||
},
|
||||
`Executing backup command: ${backup.databaseType} ${backup.backupType}`,
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import { createWriteStream } from "node:fs";
|
||||
import { mkdtemp, rm, stat } from "node:fs/promises";
|
||||
import { mkdtemp, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { IS_CLOUD, paths } from "@dokploy/server/constants";
|
||||
import {
|
||||
ENCRYPTION_KEY_BACKUP_FILE,
|
||||
exportEncryptionKeys,
|
||||
} from "@dokploy/server/lib/encryption";
|
||||
import type { BackupSchedule } from "@dokploy/server/services/backup";
|
||||
import {
|
||||
createDeploymentBackup,
|
||||
@@ -11,6 +15,7 @@ import {
|
||||
import { findDestinationById } from "@dokploy/server/services/destination";
|
||||
import { sendDokployBackupNotifications } from "../notifications/dokploy-backup";
|
||||
import { execAsync } from "../process/execAsync";
|
||||
import { redactRcloneCredentials } from "./redact";
|
||||
import { getBackupTimestamp, getS3Credentials, normalizeS3Path } from "./utils";
|
||||
|
||||
function formatBytes(bytes?: number) {
|
||||
@@ -18,7 +23,7 @@ function formatBytes(bytes?: number) {
|
||||
if (bytes === 0) return "0 B";
|
||||
const sizes = ["B", "KB", "MB", "GB", "TB"];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(1024));
|
||||
const value = bytes / Math.pow(1024, i);
|
||||
const value = bytes / 1024 ** i;
|
||||
return `${value.toFixed(2)} ${sizes[i]} (${bytes} bytes)`;
|
||||
}
|
||||
|
||||
@@ -77,11 +82,22 @@ export const runWebServerBackup = async (backup: BackupSchedule) => {
|
||||
await execAsync(cleanupCommand);
|
||||
|
||||
await execAsync(
|
||||
`rsync -a --ignore-errors --no-specials --no-devices --exclude='volume-backups/' ${BASE_PATH}/ ${tempDir}/filesystem/`,
|
||||
`rsync -a --ignore-errors --no-specials --no-devices --exclude='volume-backups/' --exclude='${ENCRYPTION_KEY_BACKUP_FILE}' ${BASE_PATH}/ ${tempDir}/filesystem/`,
|
||||
);
|
||||
|
||||
writeStream.write("Copied filesystem to temp directory\n");
|
||||
|
||||
if (backup.includeEncryptionKey) {
|
||||
// Restoring the filesystem places this file at BASE_PATH, where
|
||||
// the encryption keyring picks it up as a decryption fallback.
|
||||
await writeFile(
|
||||
join(tempDir, "filesystem", ENCRYPTION_KEY_BACKUP_FILE),
|
||||
exportEncryptionKeys(),
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
writeStream.write("Included encryption key in backup\n");
|
||||
}
|
||||
|
||||
await execAsync(
|
||||
// Zip all .sql files since we created more than one
|
||||
`cd ${tempDir} && zip -r ${backupFileName} *.sql filesystem/ > /dev/null 2>&1`,
|
||||
@@ -113,20 +129,23 @@ export const runWebServerBackup = async (backup: BackupSchedule) => {
|
||||
try {
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
} catch (cleanupError) {
|
||||
console.error("Cleanup error:", cleanupError);
|
||||
console.error(
|
||||
"Cleanup error:",
|
||||
redactRcloneCredentials(String(cleanupError)),
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Backup error:", error);
|
||||
writeStream.write("Backup error❌\n");
|
||||
writeStream.write(
|
||||
error instanceof Error ? error.message : "Unknown error\n",
|
||||
const safeErrorMessage = redactRcloneCredentials(
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
console.error("Backup error:", redactRcloneCredentials(String(error)));
|
||||
writeStream.write("Backup error❌\n");
|
||||
writeStream.write(`${safeErrorMessage}\n`);
|
||||
writeStream.end();
|
||||
await sendDokployBackupNotifications({
|
||||
type: "error",
|
||||
// @ts-ignore
|
||||
errorMessage: error?.message || "Error message not provided",
|
||||
errorMessage: safeErrorMessage || "Error message not provided",
|
||||
backupSize: formatBytes(computedBackupSize),
|
||||
});
|
||||
await updateDeploymentStatus(deployment.deploymentId, "error");
|
||||
|
||||
@@ -54,7 +54,7 @@ Compose Type: ${composeType} ✅`;
|
||||
cd "${projectPath}";
|
||||
|
||||
${compose.isolatedDeployment ? `docker network inspect ${compose.appName} >/dev/null 2>&1 || docker network create ${compose.composeType === "stack" ? "--driver overlay" : ""} --attachable ${compose.appName}` : ""}
|
||||
env -i PATH="$PATH" ${exportEnvCommand} docker ${command.split(" ").join(" ")} 2>&1 || { echo "Error: ❌ Docker command failed"; exit 1; }
|
||||
env -i PATH="$PATH" HOME="$HOME" ${exportEnvCommand} docker ${command.split(" ").join(" ")} 2>&1 || { echo "Error: ❌ Docker command failed"; exit 1; }
|
||||
${compose.isolatedDeployment ? `docker network connect ${compose.appName} $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1` : ""}
|
||||
|
||||
echo "Docker Compose Deployed: ✅";
|
||||
@@ -67,9 +67,20 @@ Compose Type: ${composeType} ✅`;
|
||||
return bashCommand;
|
||||
};
|
||||
|
||||
// Shell control characters that must never appear in a user-provided compose
|
||||
// command: they would let it break out of the `docker ${command}` invocation
|
||||
// into arbitrary host commands. A normal docker compose CLI line never needs them.
|
||||
const UNSAFE_COMPOSE_COMMAND = /[;&|`$(){}<>\n\\]/;
|
||||
|
||||
const sanitizeCommand = (command: string) => {
|
||||
const sanitizedCommand = command.trim();
|
||||
|
||||
if (UNSAFE_COMPOSE_COMMAND.test(sanitizedCommand)) {
|
||||
throw new Error(
|
||||
"Invalid characters in compose command: shell control characters are not allowed",
|
||||
);
|
||||
}
|
||||
|
||||
const parts = sanitizedCommand.split(/\s+/);
|
||||
|
||||
const restCommand = parts.map((arg) => arg.replace(/^"(.*)"$/, "$1"));
|
||||
@@ -88,9 +99,9 @@ export const createCommand = (compose: ComposeNested) => {
|
||||
let command = "";
|
||||
|
||||
if (composeType === "docker-compose") {
|
||||
command = `compose -p ${appName} -f ${path} up -d --build --remove-orphans`;
|
||||
command = `compose -p ${quote([appName])} -f ${quote([path])} up -d --build --remove-orphans`;
|
||||
} else if (composeType === "stack") {
|
||||
command = `stack deploy -c ${path} ${appName} --prune --with-registry-auth`;
|
||||
command = `stack deploy -c ${quote([path])} ${quote([appName])} --prune --with-registry-auth`;
|
||||
}
|
||||
|
||||
return command;
|
||||
@@ -124,8 +135,8 @@ export const getCreateEnvFileCommand = (compose: ComposeNested) => {
|
||||
|
||||
const encodedContent = encodeBase64(envFileContent);
|
||||
return `
|
||||
touch ${envFilePath};
|
||||
echo "${encodedContent}" | base64 -d > "${envFilePath}";
|
||||
touch ${quote([envFilePath])};
|
||||
echo "${encodedContent}" | base64 -d > ${quote([envFilePath])};
|
||||
`;
|
||||
};
|
||||
|
||||
|
||||
@@ -85,9 +85,9 @@ export const getDockerCommand = (application: ApplicationNested) => {
|
||||
}
|
||||
|
||||
command += `
|
||||
echo "Building ${appName}" ;
|
||||
cd ${dockerContextPath} || {
|
||||
echo "❌ The path ${dockerContextPath} does not exist" ;
|
||||
echo ${quote([`Building ${appName}`])} ;
|
||||
cd ${quote([dockerContextPath])} || {
|
||||
echo ${quote([`❌ The path ${dockerContextPath} does not exist`])} ;
|
||||
exit 1;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { findRegistryByIdWithCredentials } from "@dokploy/server/services/registry";
|
||||
import type { InferResultType } from "@dokploy/server/types/with";
|
||||
import type { CreateServiceOptions } from "dockerode";
|
||||
import { getRegistryTag, uploadImageRemoteCommand } from "../cluster/upload";
|
||||
@@ -28,9 +29,9 @@ export type ApplicationNested = InferResultType<
|
||||
security: true;
|
||||
redirects: true;
|
||||
ports: true;
|
||||
registry: true;
|
||||
buildRegistry: true;
|
||||
rollbackRegistry: true;
|
||||
registry: { columns: { password: false } };
|
||||
buildRegistry: { columns: { password: false } };
|
||||
rollbackRegistry: { columns: { password: false } };
|
||||
deployments: true;
|
||||
environment: { with: { project: true } };
|
||||
}
|
||||
@@ -121,8 +122,8 @@ export const mechanizeDockerContainer = async (
|
||||
application.environment.env,
|
||||
);
|
||||
|
||||
const image = getImageName(application);
|
||||
const authConfig = getAuthConfig(application);
|
||||
const image = await getImageName(application);
|
||||
const authConfig = await getAuthConfig(application);
|
||||
const docker = await getRemoteDocker(application.serverId);
|
||||
|
||||
const settings: CreateServiceOptions = {
|
||||
@@ -190,7 +191,7 @@ export const mechanizeDockerContainer = async (
|
||||
}
|
||||
};
|
||||
|
||||
const getImageName = (application: ApplicationNested) => {
|
||||
const getImageName = async (application: ApplicationNested) => {
|
||||
const { appName, sourceType, dockerImage, registry, buildRegistry } =
|
||||
application;
|
||||
const imageName = `${appName}:latest`;
|
||||
@@ -199,18 +200,18 @@ const getImageName = (application: ApplicationNested) => {
|
||||
}
|
||||
|
||||
if (registry) {
|
||||
const registryTag = getRegistryTag(registry, imageName);
|
||||
return registryTag;
|
||||
const r = await findRegistryByIdWithCredentials(registry.registryId);
|
||||
return getRegistryTag(r, imageName);
|
||||
}
|
||||
if (buildRegistry) {
|
||||
const registryTag = getRegistryTag(buildRegistry, imageName);
|
||||
return registryTag;
|
||||
const r = await findRegistryByIdWithCredentials(buildRegistry.registryId);
|
||||
return getRegistryTag(r, imageName);
|
||||
}
|
||||
|
||||
return imageName;
|
||||
};
|
||||
|
||||
export const getAuthConfig = (application: ApplicationNested) => {
|
||||
export const getAuthConfig = async (application: ApplicationNested) => {
|
||||
const {
|
||||
registry,
|
||||
buildRegistry,
|
||||
@@ -222,23 +223,21 @@ export const getAuthConfig = (application: ApplicationNested) => {
|
||||
|
||||
if (sourceType === "docker") {
|
||||
if (username && password) {
|
||||
return {
|
||||
password,
|
||||
username,
|
||||
serveraddress: registryUrl || "",
|
||||
};
|
||||
return { password, username, serveraddress: registryUrl || "" };
|
||||
}
|
||||
} else if (registry) {
|
||||
const r = await findRegistryByIdWithCredentials(registry.registryId);
|
||||
return {
|
||||
password: registry.password,
|
||||
username: registry.username,
|
||||
serveraddress: registry.registryUrl,
|
||||
password: r.password,
|
||||
username: r.username,
|
||||
serveraddress: r.registryUrl,
|
||||
};
|
||||
} else if (buildRegistry) {
|
||||
const r = await findRegistryByIdWithCredentials(buildRegistry.registryId);
|
||||
return {
|
||||
password: buildRegistry.password,
|
||||
username: buildRegistry.username,
|
||||
serveraddress: buildRegistry.registryUrl,
|
||||
password: r.password,
|
||||
username: r.username,
|
||||
serveraddress: r.registryUrl,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import path from "node:path";
|
||||
import { getStaticCommand } from "@dokploy/server/utils/builders/static";
|
||||
import { nanoid } from "nanoid";
|
||||
import { quote } from "shell-quote";
|
||||
import { prepareEnvironmentVariablesForShell } from "../docker/utils";
|
||||
import { getBuildAppDirectory } from "../filesystem/directory";
|
||||
import type { ApplicationNested } from ".";
|
||||
@@ -52,10 +53,10 @@ export const getNixpacksCommand = (application: ApplicationNested) => {
|
||||
|
||||
bashCommand += `
|
||||
docker create --name ${buildContainerId} ${appName}
|
||||
mkdir -p ${localPath}
|
||||
docker cp ${buildContainerId}:/app/${publishDirectory}${isDirectory ? "/." : ""} ${path.join(buildAppDirectory, publishDirectory)} || {
|
||||
mkdir -p ${quote([localPath])}
|
||||
docker cp ${quote([`${buildContainerId}:/app/${publishDirectory}${isDirectory ? "/." : ""}`])} ${quote([localPath])} || {
|
||||
docker rm ${buildContainerId}
|
||||
echo "❌ Copying ${publishDirectory} to ${path.join(buildAppDirectory, publishDirectory)} failed" ;
|
||||
echo ${quote([`❌ Copying ${publishDirectory} to ${localPath} failed`])} ;
|
||||
exit 1;
|
||||
}
|
||||
docker rm ${buildContainerId}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user