Merge remote-tracking branch 'origin/canary' into fix/env-update-issue

# Conflicts:
#	packages/server/src/utils/builders/railpack.ts
This commit is contained in:
Mauricio Siu
2026-08-03 03:53:41 -06:00
550 changed files with 127113 additions and 34784 deletions
+11 -1
View File
@@ -81,7 +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;
};
if (!globalForDocker.docker) {
globalForDocker.docker = getDockerConfig();
}
export const docker = globalForDocker.docker;
export const paths = (isServer = false) => {
const BASE_PATH =
+6 -19
View File
@@ -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 };
+37
View File
@@ -8,6 +8,7 @@ import {
timestamp,
} from "drizzle-orm/pg-core";
import { nanoid } from "nanoid";
import { network } from "./network";
import { projects } from "./project";
import { server } from "./server";
import { ssoProvider } from "./sso";
@@ -108,6 +109,7 @@ export const organizationRelations = relations(
references: [user.id],
}),
servers: many(server),
networks: many(network),
projects: many(projects),
members: many(member),
ssoProviders: many(ssoProvider),
@@ -214,8 +216,43 @@ 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 passkey = pgTable(
"passkey",
{
id: text("id").primaryKey(),
name: text("name"),
publicKey: text("public_key").notNull(),
userId: text("user_id")
.notNull()
.references(() => user.id, { onDelete: "cascade" }),
credentialID: text("credential_id").notNull(),
counter: integer("counter").notNull(),
deviceType: text("device_type").notNull(),
backedUp: boolean("backed_up").notNull(),
transports: text("transports"),
createdAt: timestamp("created_at"),
aaguid: text("aaguid"),
},
(table) => [
index("passkey_userId_idx").on(table.userId),
index("passkey_credentialID_idx").on(table.credentialID),
],
);
export const passkeyRelations = relations(passkey, ({ one }) => ({
user: one(user, {
fields: [passkey.userId],
references: [user.id],
}),
}));
export const apikey = pgTable("apikey", {
id: text("id").primaryKey(),
name: text("name"),
+9
View File
@@ -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),
+18 -7
View File
@@ -51,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",
@@ -82,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),
@@ -105,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"),
@@ -228,6 +233,10 @@ export const applications = pgTable("application", {
onDelete: "set null",
},
),
networkIds: text("networkIds").array().default([]),
detachDokployNetwork: boolean("detachDokployNetwork")
.notNull()
.default(false),
});
export const applicationsRelations = relations(
@@ -369,6 +378,8 @@ const createSchema = createInsertSchema(applications, {
previewRequireCollaboratorPermissions: z.boolean().optional(),
watchPaths: z.array(z.string()).optional().optional(),
previewLabels: z.array(z.string()).optional(),
networkIds: z.array(z.string()).optional(),
detachDokployNetwork: z.boolean().optional(),
cleanCache: z.boolean().optional(),
stopGracePeriodSwarm: z.number().nullable(),
endpointSpecSwarm: EndpointSpecSwarmSchema.nullable(),
+2 -1
View File
@@ -91,4 +91,5 @@ export type AuditResourceType =
| "cluster"
| "mount"
| "application"
| "compose";
| "compose"
| "network";
+7 -1
View File
@@ -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(),
+39 -3
View File
@@ -1,5 +1,12 @@
import { relations } from "drizzle-orm";
import { boolean, integer, pgEnum, pgTable, text } from "drizzle-orm/pg-core";
import {
boolean,
integer,
jsonb,
pgEnum,
pgTable,
text,
} from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { nanoid } from "nanoid";
import { z } from "zod";
@@ -17,7 +24,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 +51,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"),
@@ -86,6 +98,7 @@ export const compose = pgTable("compose", {
.default(false),
triggerType: triggerType("triggerType").default("push"),
composeStatus: applicationStatus("composeStatus").notNull().default("idle"),
icon: text("icon"),
environmentId: text("environmentId")
.notNull()
.references(() => environments.environmentId, { onDelete: "cascade" }),
@@ -108,6 +121,15 @@ export const compose = pgTable("compose", {
serverId: text("serverId").references(() => server.serverId, {
onDelete: "cascade",
}),
serviceNetworks: jsonb("serviceNetworks")
.$type<
Array<{
serviceName: string;
networkIds: string[];
detachDokployNetwork: boolean;
}>
>()
.default([]),
});
export const composeRelations = relations(compose, ({ one, many }) => ({
@@ -169,6 +191,20 @@ const createSchema = createInsertSchema(compose, {
.optional(),
triggerType: z.enum(["push", "tag"]).optional(),
composeStatus: z.enum(["idle", "running", "done", "error"]).optional(),
icon: z
.string()
.max(2 * 1024 * 1024, "Icon must be less than 2MB")
.nullable()
.optional(),
serviceNetworks: z
.array(
z.object({
serviceName: z.string(),
networkIds: z.array(z.string()),
detachDokployNetwork: z.boolean(),
}),
)
.optional(),
});
export const apiCreateCompose = createSchema.pick({
+3
View File
@@ -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());
+2 -1
View File
@@ -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" }),
@@ -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),
});
+3
View File
@@ -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";
@@ -19,6 +20,7 @@ export * from "./mariadb";
export * from "./mongo";
export * from "./mount";
export * from "./mysql";
export * from "./network";
export * from "./notification";
export * from "./patch";
export * from "./port";
@@ -30,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";
+8 -1
View File
@@ -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"),
@@ -82,6 +83,10 @@ export const libsql = pgTable("libsql", {
stopGracePeriodSwarm: bigint("stopGracePeriodSwarm", { mode: "number" }),
endpointSpecSwarm: json("endpointSpecSwarm").$type<EndpointSpecSwarm>(),
replicas: integer("replicas").default(1).notNull(),
networkIds: text("networkIds").array().default([]),
detachDokployNetwork: boolean("detachDokployNetwork")
.notNull()
.default(false),
createdAt: text("createdAt")
.notNull()
.$defaultFn(() => new Date().toISOString()),
@@ -145,6 +150,8 @@ const createSchema = createInsertSchema(libsql, {
networkSwarm: NetworkSwarmSchema.nullable(),
stopGracePeriodSwarm: z.number().nullable(),
endpointSpecSwarm: EndpointSpecSwarmSchema.nullable(),
networkIds: z.array(z.string()).optional(),
detachDokployNetwork: z.boolean().optional(),
});
export const apiCreateLibsql = createSchema
+16 -2
View File
@@ -1,5 +1,12 @@
import { relations } from "drizzle-orm";
import { bigint, integer, json, pgTable, text } from "drizzle-orm/pg-core";
import {
bigint,
boolean,
integer,
json,
pgTable,
text,
} from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { nanoid } from "nanoid";
import { z } from "zod";
@@ -33,6 +40,7 @@ import {
APP_NAME_REGEX,
DATABASE_PASSWORD_MESSAGE,
DATABASE_PASSWORD_REGEX,
encryptedText,
generateAppName,
} from "./utils";
@@ -54,7 +62,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"),
@@ -87,6 +95,10 @@ export const mariadb = pgTable("mariadb", {
serverId: text("serverId").references(() => server.serverId, {
onDelete: "cascade",
}),
networkIds: text("networkIds").array().default([]),
detachDokployNetwork: boolean("detachDokployNetwork")
.notNull()
.default(false),
});
export const mariadbRelations = relations(mariadb, ({ one, many }) => ({
@@ -147,6 +159,8 @@ const createSchema = createInsertSchema(mariadb, {
stopGracePeriodSwarm: z.number().nullable(),
endpointSpecSwarm: EndpointSpecSwarmSchema.nullable(),
ulimitsSwarm: UlimitsSwarmSchema.nullable(),
networkIds: z.array(z.string()).optional(),
detachDokployNetwork: z.boolean().optional(),
});
export const apiCreateMariaDB = createSchema.pick({
+8 -1
View File
@@ -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"),
@@ -91,6 +92,10 @@ export const mongo = pgTable("mongo", {
onDelete: "cascade",
}),
replicaSets: boolean("replicaSets").default(false),
networkIds: text("networkIds").array().default([]),
detachDokployNetwork: boolean("detachDokployNetwork")
.notNull()
.default(false),
});
export const mongoRelations = relations(mongo, ({ one, many }) => ({
@@ -145,6 +150,8 @@ const createSchema = createInsertSchema(mongo, {
stopGracePeriodSwarm: z.number().nullable(),
endpointSpecSwarm: EndpointSpecSwarmSchema.nullable(),
ulimitsSwarm: UlimitsSwarmSchema.nullable(),
networkIds: z.array(z.string()).optional(),
detachDokployNetwork: z.boolean().optional(),
});
export const apiCreateMongo = createSchema.pick({
+16 -2
View File
@@ -1,5 +1,12 @@
import { relations } from "drizzle-orm";
import { bigint, integer, json, pgTable, text } from "drizzle-orm/pg-core";
import {
bigint,
boolean,
integer,
json,
pgTable,
text,
} from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { nanoid } from "nanoid";
import { z } from "zod";
@@ -33,6 +40,7 @@ import {
APP_NAME_REGEX,
DATABASE_PASSWORD_MESSAGE,
DATABASE_PASSWORD_REGEX,
encryptedText,
generateAppName,
} from "./utils";
@@ -54,7 +62,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"),
@@ -85,6 +93,10 @@ export const mysql = pgTable("mysql", {
serverId: text("serverId").references(() => server.serverId, {
onDelete: "cascade",
}),
networkIds: text("networkIds").array().default([]),
detachDokployNetwork: boolean("detachDokployNetwork")
.notNull()
.default(false),
});
export const mysqlRelations = relations(mysql, ({ one, many }) => ({
@@ -144,6 +156,8 @@ const createSchema = createInsertSchema(mysql, {
stopGracePeriodSwarm: z.number().nullable(),
endpointSpecSwarm: EndpointSpecSwarmSchema.nullable(),
ulimitsSwarm: UlimitsSwarmSchema.nullable(),
networkIds: z.array(z.string()).optional(),
detachDokployNetwork: z.boolean().optional(),
});
export const apiCreateMySql = createSchema.pick({
+125
View File
@@ -0,0 +1,125 @@
import { relations } from "drizzle-orm";
import { boolean, jsonb, 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 { server } from "./server";
export const networkDriver = pgEnum("networkDriver", ["bridge", "overlay"]);
export const network = pgTable("network", {
networkId: text("networkId")
.notNull()
.primaryKey()
.$defaultFn(() => nanoid()),
name: text("name").notNull(),
driver: networkDriver("driver").notNull().default("bridge"),
internal: boolean("internal").notNull().default(false),
attachable: boolean("attachable").notNull().default(false),
enableIPv4: boolean("enableIPv4").notNull().default(true),
enableIPv6: boolean("enableIPv6").notNull().default(false),
ipam: jsonb("ipam")
.$type<{
driver?: string;
config?: Array<{ subnet?: string; gateway?: string; ipRange?: string }>;
}>()
.default({}),
createdAt: text("createdAt")
.notNull()
.$defaultFn(() => new Date().toISOString()),
organizationId: text("organizationId")
.notNull()
.references(() => organization.id, { onDelete: "cascade" }),
serverId: text("serverId").references(() => server.serverId, {
onDelete: "cascade",
}),
});
export const networkRelations = relations(network, ({ one }) => ({
organization: one(organization, {
fields: [network.organizationId],
references: [organization.id],
}),
server: one(server, {
fields: [network.serverId],
references: [server.serverId],
}),
}));
const createSchema = createInsertSchema(network, {
networkId: z.string().min(1),
name: z.string().min(1),
driver: z.enum(["bridge", "overlay"]).optional(),
internal: z.boolean().optional(),
attachable: z.boolean().optional(),
enableIPv4: z.boolean().optional(),
enableIPv6: z.boolean().optional(),
ipam: z
.object({
driver: z.string().optional(),
config: z
.array(
z.object({
subnet: z.string().optional(),
gateway: z.string().optional(),
ipRange: z.string().optional(),
}),
)
.optional(),
})
.optional(),
organizationId: z.string().min(1),
serverId: z.string().optional().nullable(),
});
const validateNetworkInput = (
input: {
enableIPv4?: boolean;
enableIPv6?: boolean;
ipam?: {
config?: Array<{ subnet?: string; gateway?: string; ipRange?: string }>;
} | null;
},
ctx: z.RefinementCtx,
) => {
if (input.enableIPv4 === false && input.enableIPv6 !== true) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["enableIPv4"],
message: "IPv4 or IPv6 must be enabled",
});
}
for (const [index, entry] of (input.ipam?.config ?? []).entries()) {
if (!entry.subnet && (entry.gateway || entry.ipRange)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["ipam", "config", index, "subnet"],
message: "Gateway and IP range require a subnet",
});
}
}
};
export const apiCreateNetwork = createSchema
.pick({
name: true,
driver: true,
internal: true,
attachable: true,
enableIPv4: true,
enableIPv6: true,
ipam: true,
serverId: true,
})
.partial()
.required({ name: true })
.superRefine(validateNetworkInput);
export const apiFindOneNetwork = z.object({
networkId: z.string().min(1),
});
export const apiRemoveNetwork = z.object({
networkId: z.string().min(1),
});
+16 -2
View File
@@ -1,5 +1,12 @@
import { relations } from "drizzle-orm";
import { bigint, integer, json, pgTable, text } from "drizzle-orm/pg-core";
import {
bigint,
boolean,
integer,
json,
pgTable,
text,
} from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { nanoid } from "nanoid";
import { z } from "zod";
@@ -33,6 +40,7 @@ import {
APP_NAME_REGEX,
DATABASE_PASSWORD_MESSAGE,
DATABASE_PASSWORD_REGEX,
encryptedText,
generateAppName,
} from "./utils";
@@ -53,7 +61,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"),
@@ -85,6 +93,10 @@ export const postgres = pgTable("postgres", {
serverId: text("serverId").references(() => server.serverId, {
onDelete: "cascade",
}),
networkIds: text("networkIds").array().default([]),
detachDokployNetwork: boolean("detachDokployNetwork")
.notNull()
.default(false),
});
export const postgresRelations = relations(postgres, ({ one, many }) => ({
@@ -139,6 +151,8 @@ const createSchema = createInsertSchema(postgres, {
stopGracePeriodSwarm: z.number().nullable(),
endpointSpecSwarm: EndpointSpecSwarmSchema.nullable(),
ulimitsSwarm: UlimitsSwarmSchema.nullable(),
networkIds: z.array(z.string()).optional(),
detachDokployNetwork: z.boolean().optional(),
});
export const apiCreatePostgres = createSchema.pick({
+3 -1
View File
@@ -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({
+21 -3
View File
@@ -1,5 +1,12 @@
import { relations } from "drizzle-orm";
import { bigint, integer, json, pgTable, text } from "drizzle-orm/pg-core";
import {
bigint,
boolean,
integer,
json,
pgTable,
text,
} from "drizzle-orm/pg-core";
import { createInsertSchema } from "drizzle-zod";
import { nanoid } from "nanoid";
import { z } from "zod";
@@ -27,7 +34,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 +56,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"),
@@ -75,6 +87,10 @@ export const redis = pgTable("redis", {
serverId: text("serverId").references(() => server.serverId, {
onDelete: "cascade",
}),
networkIds: text("networkIds").array().default([]),
detachDokployNetwork: boolean("detachDokployNetwork")
.notNull()
.default(false),
});
export const redisRelations = relations(redis, ({ one, many }) => ({
@@ -124,6 +140,8 @@ const createSchema = createInsertSchema(redis, {
stopGracePeriodSwarm: z.number().nullable(),
endpointSpecSwarm: EndpointSpecSwarmSchema.nullable(),
ulimitsSwarm: UlimitsSwarmSchema.nullable(),
networkIds: z.array(z.string()).optional(),
detachDokployNetwork: z.boolean().optional(),
});
export const apiCreateRedis = createSchema.pick({
+5 -6
View File
@@ -44,12 +44,11 @@ export const registryRelations = relations(registry, ({ many }) => ({
}),
}));
// Image references require a lowercase namespace (e.g. Docker Hub username).
const registryUsernameSchema = z
.string()
.trim()
.min(1)
.transform((s) => s.toLowerCase());
// 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)
+4 -1
View File
@@ -57,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, {
@@ -78,7 +79,9 @@ export const schedulesRelations = relations(schedules, ({ one, many }) => ({
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
View 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],
}),
}));
+15 -1
View File
@@ -19,6 +19,7 @@ import { libsql } from "./libsql";
import { mariadb } from "./mariadb";
import { mongo } from "./mongo";
import { mysql } from "./mysql";
import { network } from "./network";
import { postgres } from "./postgres";
import { redis } from "./redis";
import { schedules } from "./schedule";
@@ -41,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()
@@ -124,6 +126,7 @@ export const serverRelations = relations(server, ({ one, many }) => ({
mysql: many(mysql),
postgres: many(postgres),
certificates: many(certificates),
networks: many(network),
organization: one(organization, {
fields: [server.organizationId],
references: [organization.id],
@@ -147,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),
@@ -170,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,
+1 -1
View File
@@ -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",
}),
+35
View File
@@ -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";
@@ -98,6 +105,8 @@ export const webServerSettings = pgTable("webServerSettings", {
}),
// 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
@@ -161,6 +170,11 @@ export const apiUpdateWebServerSettings = createSchema.partial().extend({
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
+12 -2
View File
@@ -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,6 +13,7 @@ import {
Tailwind,
Text,
} from "@react-email/components";
import { emailTailwindConfig } from "../tailwind-config";
interface InvitationEmailProps {
inviteLink: string;
@@ -30,17 +31,7 @@ export const InvitationEmail = ({
<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 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 */}
@@ -12,6 +12,7 @@ import {
Tailwind,
Text,
} from "@react-email/components";
import { emailTailwindConfig } from "../tailwind-config";
export type TemplateProps = {
userName: string;
@@ -27,17 +28,7 @@ export const VerifyEmailTemplate = ({
<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 */}
@@ -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">
+6 -5
View File
@@ -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"
}
}
@@ -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",
},
},
},
};
+6 -1
View File
@@ -28,6 +28,7 @@ export * from "./services/mariadb";
export * from "./services/mongo";
export * from "./services/mount";
export * from "./services/mysql";
export * from "./services/network";
export * from "./services/notification";
export * from "./services/patch";
export * from "./services/patch-repo";
@@ -35,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";
@@ -50,9 +53,9 @@ 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";
export * from "./setup/server-audit";
export * from "./setup/server-setup";
export * from "./setup/server-validate";
@@ -102,6 +105,7 @@ 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 +131,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";
+49
View File
@@ -0,0 +1,49 @@
import { apiKey } from "@better-auth/api-key";
import { passkey } from "@better-auth/passkey";
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(),
passkey(),
organization({
ac,
roles: { owner: ownerRole, admin: adminRole, member: memberRole },
dynamicAccessControl: {
enabled: true,
maximumRolesPerOrganization: 10,
},
}),
scim(),
admin(),
],
});
+417 -364
View File
@@ -1,10 +1,12 @@
import type { IncomingMessage } from "node:http";
import { apiKey } from "@better-auth/api-key";
import { passkey } from "@better-auth/passkey";
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 { IS_CLOUD } from "../constants";
@@ -29,404 +31,455 @@ 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",
...(!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",
},
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,
sendOnSignIn: true,
sendVerificationEmail: async ({ user, url }) => {
if (IS_CLOUD) {
await sendVerificationEmail({
userName: user.name || "User",
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,
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: "Reset your password",
text: `
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 && !isAdminPresent) {
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(),
passkey(),
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,
},
}),
...(IS_CLOUD
? [
admin({
adminUserIds: [process.env.USER_ADMIN_ID as string],
}),
]
: []),
],
});
}),
// 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: [] },
),
],
});
// 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;
@@ -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
View 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.",
);
};
+4
View File
@@ -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
+71 -5
View File
@@ -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
+22 -12
View File
@@ -95,26 +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) {
+12 -2
View File
@@ -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 || [];
+6 -5
View File
@@ -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);
+8 -2
View File
@@ -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(
+11 -1
View File
@@ -83,7 +83,17 @@ export const findDeploymentById = async (deploymentId: string) => {
const deployment = await db.query.deployments.findFirst({
where: eq(deployments.deploymentId, deploymentId),
with: {
application: true,
application: {
columns: {
applicationId: true,
appName: true,
name: true,
serverId: true,
},
},
compose: {
columns: { composeId: true, appName: true, name: true, serverId: true },
},
schedule: true,
},
});
+2 -1
View File
@@ -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 {
@@ -519,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) {
+9 -3
View File
@@ -80,7 +80,9 @@ export const findDomainById = async (domainId: string) => {
const domain = await db.query.domains.findFirst({
where: eq(domains.domainId, domainId),
with: {
application: true,
application: {
columns: { applicationId: true, appName: true, name: true },
},
},
});
if (!domain) {
@@ -96,7 +98,9 @@ export const findDomainsByApplicationId = async (applicationId: string) => {
const domainsArray = await db.query.domains.findMany({
where: eq(domains.applicationId, applicationId),
with: {
application: true,
application: {
columns: { applicationId: true, appName: true, name: true },
},
},
});
@@ -107,7 +111,9 @@ export const findDomainsByComposeId = async (composeId: string) => {
const domainsArray = await db.query.domains.findMany({
where: eq(domains.composeId, composeId),
with: {
compose: true,
compose: {
columns: { composeId: true, appName: true, name: true },
},
},
});
+89 -8
View File
@@ -168,6 +168,7 @@ export const findEnvironmentById = async (environmentId: string) => {
composeStatus: true,
description: true,
serverId: true,
icon: true,
},
},
libsql: {
@@ -201,18 +202,56 @@ export const findEnvironmentById = async (environmentId: string) => {
};
export const findEnvironmentsByProjectId = async (projectId: string) => {
const serviceColumns = {
name: true,
description: true,
appName: true,
createdAt: true,
serverId: true,
applicationStatus: true,
} as const;
const projectEnvironments = await db.query.environments.findMany({
where: eq(environments.projectId, projectId),
orderBy: asc(environments.createdAt),
with: {
applications: true,
mariadb: true,
mongo: true,
mysql: true,
postgres: true,
redis: true,
compose: true,
libsql: true,
applications: {
columns: { ...serviceColumns, applicationId: true, icon: true },
with: { server: { columns: { name: true } } },
},
mariadb: {
columns: { ...serviceColumns, mariadbId: true },
with: { server: { columns: { name: true } } },
},
mongo: {
columns: { ...serviceColumns, mongoId: true },
with: { server: { columns: { name: true } } },
},
mysql: {
columns: { ...serviceColumns, mysqlId: true },
with: { server: { columns: { name: true } } },
},
postgres: {
columns: { ...serviceColumns, postgresId: true },
with: { server: { columns: { name: true } } },
},
redis: {
columns: { ...serviceColumns, redisId: true },
with: { server: { columns: { name: true } } },
},
compose: {
columns: {
...serviceColumns,
composeId: true,
composeStatus: true,
icon: true,
},
with: { server: { columns: { name: true } } },
},
libsql: {
columns: { ...serviceColumns, libsqlId: true },
with: { server: { columns: { name: true } } },
},
project: true,
},
columns: {
@@ -308,6 +347,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",
});
}
};
+8 -2
View File
@@ -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 {
+8 -2
View File
@@ -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 {
+8 -2
View File
@@ -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 {
+23 -74
View File
@@ -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;
@@ -106,81 +107,29 @@ export const createFileMount = async (mountId: string) => {
};
export const findMountById = async (mountId: string) => {
const serviceWith = {
columns: { serverId: true, appName: true },
with: {
environment: {
columns: {},
with: {
project: { columns: { organizationId: true } },
},
},
},
} as const;
const mount = await db.query.mounts.findFirst({
where: eq(mounts.mountId, mountId),
with: {
application: {
with: {
environment: {
with: {
project: true,
},
},
},
},
compose: {
with: {
environment: {
with: {
project: true,
},
},
},
},
libsql: {
with: {
environment: {
with: {
project: true,
},
},
},
},
mariadb: {
with: {
environment: {
with: {
project: true,
},
},
},
},
mongo: {
with: {
environment: {
with: {
project: true,
},
},
},
},
mysql: {
with: {
environment: {
with: {
project: true,
},
},
},
},
postgres: {
with: {
environment: {
with: {
project: true,
},
},
},
},
redis: {
with: {
environment: {
with: {
project: true,
},
},
},
},
application: serviceWith,
compose: serviceWith,
libsql: serviceWith,
mariadb: serviceWith,
mongo: serviceWith,
mysql: serviceWith,
postgres: serviceWith,
redis: serviceWith,
},
});
if (!mount) {
@@ -317,7 +266,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 +286,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);
+8 -2
View File
@@ -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 {
+359
View File
@@ -0,0 +1,359 @@
import { db } from "@dokploy/server/db";
import { type apiCreateNetwork, network } from "@dokploy/server/db/schema";
import { TRPCError } from "@trpc/server";
import { and, eq, inArray, isNull } from "drizzle-orm";
import type { z } from "zod";
import { IS_CLOUD } from "../constants";
import type { ApplicationNested } from "../utils/builders";
import { getRemoteDocker } from "../utils/servers/remote-docker";
const RESERVED_NETWORKS = [
"bridge",
"host",
"none",
"ingress",
"docker_gwbridge",
"dokploy-network",
];
type DockerNetworkInfo = {
Name: string;
Driver: string;
Internal?: boolean;
Attachable?: boolean;
Ingress?: boolean;
EnableIPv4?: boolean;
EnableIPv6?: boolean;
IPAM?: {
Driver?: string;
Config?: Array<{
Subnet?: string;
Gateway?: string;
IPRange?: string;
}> | null;
};
};
const isImportableDockerNetwork = (dockerNetwork: DockerNetworkInfo) =>
!RESERVED_NETWORKS.includes(dockerNetwork.Name) &&
!dockerNetwork.Ingress &&
(dockerNetwork.Driver === "bridge" || dockerNetwork.Driver === "overlay");
const mapDockerNetworkToRow = (
dockerNetwork: DockerNetworkInfo,
organizationId: string,
serverId: string | null,
) => ({
name: dockerNetwork.Name,
driver: dockerNetwork.Driver as "bridge" | "overlay",
internal: dockerNetwork.Internal ?? false,
attachable: dockerNetwork.Attachable ?? false,
// Older daemons don't report EnableIPv4; IPv4 is always on there
enableIPv4: dockerNetwork.EnableIPv4 ?? true,
enableIPv6: dockerNetwork.EnableIPv6 ?? false,
ipam: {
driver: dockerNetwork.IPAM?.Driver,
config: (dockerNetwork.IPAM?.Config ?? []).map((c) => ({
subnet: c.Subnet,
gateway: c.Gateway,
ipRange: c.IPRange,
})),
},
organizationId,
serverId,
});
const findNetworksByServer = async (
organizationId: string,
serverId: string | null,
) => {
return await db.query.network.findMany({
where: and(
eq(network.organizationId, organizationId),
serverId ? eq(network.serverId, serverId) : isNull(network.serverId),
),
});
};
export const findNetworksToSync = async (
organizationId: string,
serverId: string | null,
) => {
if (IS_CLOUD && !serverId) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Server is required",
});
}
const docker = await getRemoteDocker(serverId);
let dockerNetworks: DockerNetworkInfo[] = [];
try {
dockerNetworks = (await docker.listNetworks()) as DockerNetworkInfo[];
} catch (error) {
throw new TRPCError({
code: "BAD_REQUEST",
message:
error instanceof Error
? error.message
: "Failed to list Docker networks",
cause: error,
});
}
const existing = await findNetworksByServer(organizationId, serverId);
const existingNames = new Set(existing.map((row) => row.name));
const dockerNames = new Set(dockerNetworks.map((d) => d.Name));
const importable = dockerNetworks
.filter(
(dockerNetwork) =>
isImportableDockerNetwork(dockerNetwork) &&
!existingNames.has(dockerNetwork.Name),
)
.map((dockerNetwork) => ({
name: dockerNetwork.Name,
driver: dockerNetwork.Driver,
internal: dockerNetwork.Internal ?? false,
attachable: dockerNetwork.Attachable ?? false,
subnets: (dockerNetwork.IPAM?.Config ?? [])
.map((c) => c.Subnet)
.filter((s): s is string => !!s),
}));
// Rows in Dokploy whose network no longer exists in Docker
const missing = existing
.filter((row) => !dockerNames.has(row.name))
.map((row) => ({ networkId: row.networkId, name: row.name }));
return { importable, missing };
};
export const importDockerNetworks = async (
organizationId: string,
serverId: string | null,
names: string[],
) => {
if (IS_CLOUD && !serverId) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Server is required",
});
}
const docker = await getRemoteDocker(serverId);
const existing = await findNetworksByServer(organizationId, serverId);
const existingNames = new Set(existing.map((row) => row.name));
const imported: string[] = [];
const errors: { name: string; error: string }[] = [];
for (const name of names) {
if (existingNames.has(name)) {
errors.push({ name, error: "Already imported" });
continue;
}
try {
const info = (await docker
.getNetwork(name)
.inspect()) as DockerNetworkInfo;
if (!isImportableDockerNetwork(info)) {
errors.push({ name, error: "Network is reserved or not supported" });
continue;
}
await db
.insert(network)
.values(mapDockerNetworkToRow(info, organizationId, serverId));
imported.push(name);
} catch (error) {
errors.push({
name,
error:
error instanceof Error ? error.message : "Failed to inspect network",
});
}
}
return { imported, errors };
};
export const findNetworkById = async (networkId: string) => {
const [row] = await db
.select()
.from(network)
.where(eq(network.networkId, networkId))
.limit(1);
if (!row) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Network not found",
});
}
return row;
};
export const createNetwork = async (
input: z.infer<typeof apiCreateNetwork>,
organizationId: string,
) => {
if (IS_CLOUD) {
if (!input.serverId) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Server is required",
});
}
}
const created = await db.transaction(async (tx) => {
const [row] = await tx
.insert(network)
.values({
...input,
organizationId,
})
.returning();
if (!row) {
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to create network",
});
}
await createDockerNetworkFromRow(row);
return row;
});
return created;
};
const createDockerNetworkFromRow = async (row: typeof network.$inferSelect) => {
const ipam = row.ipam ?? {};
const ipamConfig = (ipam.config ?? [])
.map((c) => {
const entry: Record<string, string> = {};
if (c.subnet) entry.Subnet = c.subnet;
if (c.gateway) entry.Gateway = c.gateway;
if (c.ipRange) entry.IPRange = c.ipRange;
return entry;
})
.filter((e) => Object.keys(e).length > 0);
const docker = await getRemoteDocker(row.serverId ?? null);
try {
await docker.createNetwork({
Name: row.name,
Driver: row.driver,
CheckDuplicate: true,
Internal: row.internal,
Attachable: row.attachable,
// EnableIPv4 is missing from dockerode's types but supported by
// the daemon (API >= 1.47); the body is sent as-is
EnableIPv4: row.enableIPv4,
EnableIPv6: row.enableIPv6,
IPAM: {
Driver: ipam.driver || "default",
Config: ipamConfig.length > 0 ? ipamConfig : undefined,
},
} as Parameters<typeof docker.createNetwork>[0]);
} catch (error) {
throw new TRPCError({
code: "BAD_REQUEST",
message:
error instanceof Error
? error.message
: "Failed to create Docker network",
cause: error,
});
}
};
export const recreateNetwork = async (networkId: string) => {
const row = await findNetworkById(networkId);
await createDockerNetworkFromRow(row);
return row;
};
export const resolveServiceNetworks = async (
application: Partial<ApplicationNested>,
) => {
if (application.networkSwarm) {
return application.networkSwarm;
}
const { networkIds, detachDokployNetwork } = application;
const rows =
networkIds && networkIds.length > 0
? await db.query.network.findMany({
where: and(
inArray(network.networkId, networkIds),
eq(network.driver, "overlay"),
),
columns: { name: true },
})
: [];
const networks = detachDokployNetwork ? [] : ["dokploy-network"];
for (const row of rows) {
networks.push(row.name);
}
return networks.map((name) => ({ Target: name }));
};
export const inspectNetwork = async (networkId: string) => {
const row = await findNetworkById(networkId);
const docker = await getRemoteDocker(row.serverId ?? null);
try {
return await docker.getNetwork(row.name).inspect();
} catch (error) {
throw new TRPCError({
code: "BAD_REQUEST",
message:
error instanceof Error
? error.message
: "Failed to inspect Docker network",
cause: error,
});
}
};
export const removeNetwork = async (networkId: string) => {
const row = await findNetworkById(networkId);
const docker = await getRemoteDocker(row.serverId ?? null);
try {
await docker.getNetwork(row.name).remove();
} catch (error) {
const statusCode = (error as { statusCode?: number })?.statusCode;
if (statusCode !== 404) {
throw new TRPCError({
code: "BAD_REQUEST",
message:
error instanceof Error
? error.message
: "Failed to remove Docker network",
cause: error,
});
}
}
const [deleted] = await db
.delete(network)
.where(eq(network.networkId, networkId))
.returning();
if (!deleted) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Network not found",
});
}
return deleted;
};
+3 -2
View File
@@ -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);
@@ -170,6 +170,8 @@ const getLegacyOverrides = (
},
gitProviders: {
read: !!memberRecord.canAccessToGitProviders,
create: !!memberRecord.canAccessToGitProviders,
delete: !!memberRecord.canAccessToGitProviders,
},
};
};
+2 -6
View File
@@ -30,12 +30,8 @@ export const finPortById = async (portId: string) => {
where: eq(ports.portId, portId),
with: {
application: {
with: {
environment: {
with: {
project: true,
},
},
columns: {
applicationId: true,
},
},
},
+8 -2
View File
@@ -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 {
@@ -17,7 +17,7 @@ import { manageDomain } from "../utils/traefik/domain";
import { findApplicationById } from "./application";
import { removeDeploymentsByPreviewDeploymentId } from "./deployment";
import { createDomain } from "./domain";
import { type Github, getIssueComment } from "./github";
import { findGithubById, getIssueComment } from "./github";
import { getWebServerSettings } from "./web-server-settings";
export type PreviewDeployment = typeof previewDeployments.$inferSelect;
@@ -142,7 +142,17 @@ export const createPreviewDeployment = async (
org?.ownerId || "",
);
const octokit = authGithub(application?.github as Github);
if (!application.githubId) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Github Account not configured correctly",
});
}
// `findApplicationById` redacts `githubPrivateKey` from the `github`
// relation, so the provider must be refetched to authenticate.
const githubProvider = await findGithubById(application.githubId);
const octokit = authGithub(githubProvider);
const runningComment = getIssueComment(
application.name,
+71 -8
View File
@@ -48,19 +48,60 @@ export const createProject = async (
};
export const findProjectById = async (projectId: string) => {
const serviceColumns = {
name: true,
description: true,
appName: true,
createdAt: true,
serverId: true,
applicationStatus: true,
} as const;
const project = await db.query.projects.findFirst({
where: eq(projects.projectId, projectId),
with: {
environments: {
with: {
applications: true,
compose: true,
libsql: true,
mariadb: true,
mongo: true,
mysql: true,
postgres: true,
redis: true,
applications: {
columns: {
...serviceColumns,
applicationId: true,
icon: true,
},
with: { server: { columns: { name: true } } },
},
compose: {
columns: {
...serviceColumns,
composeId: true,
composeStatus: true,
},
with: { server: { columns: { name: true } } },
},
libsql: {
columns: { ...serviceColumns, libsqlId: true },
with: { server: { columns: { name: true } } },
},
mariadb: {
columns: { ...serviceColumns, mariadbId: true },
with: { server: { columns: { name: true } } },
},
mongo: {
columns: { ...serviceColumns, mongoId: true },
with: { server: { columns: { name: true } } },
},
mysql: {
columns: { ...serviceColumns, mysqlId: true },
with: { server: { columns: { name: true } } },
},
postgres: {
columns: { ...serviceColumns, postgresId: true },
with: { server: { columns: { name: true } } },
},
redis: {
columns: { ...serviceColumns, redisId: true },
with: { server: { columns: { name: true } } },
},
},
},
projectTags: {
@@ -107,27 +148,49 @@ export const updateProjectById = async (
export const validUniqueServerAppName = async (appName: string) => {
const query = await db.query.environments.findMany({
columns: { environmentId: true },
with: {
applications: {
where: eq(applications.appName, appName),
columns: {
appName: true,
},
},
libsql: {
where: eq(libsql.appName, appName),
columns: {
appName: true,
},
},
mariadb: {
where: eq(mariadb.appName, appName),
columns: {
appName: true,
},
},
mongo: {
where: eq(mongo.appName, appName),
columns: {
appName: true,
},
},
mysql: {
where: eq(mysql.appName, appName),
columns: {
appName: true,
},
},
postgres: {
where: eq(postgres.appName, appName),
columns: {
appName: true,
},
},
redis: {
where: eq(redis.appName, appName),
columns: {
appName: true,
},
},
},
});
@@ -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;
};
@@ -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,
};
};
+2 -1
View File
@@ -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 {
+45 -9
View File
@@ -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;
@@ -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,
) => {
+44 -31
View File
@@ -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,
@@ -21,9 +20,14 @@ import { getRemoteDocker } from "../utils/servers/remote-docker";
import { type Application, findApplicationById } from "./application";
import { findDeploymentById } from "./deployment";
import type { Mount } from "./mount";
import { resolveServiceNetworks } from "./network";
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 +60,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));
@@ -84,19 +106,7 @@ export const findRollbackById = async (rollbackId: string) => {
const result = await db.query.rollbacks.findFirst({
where: eq(rollbacks.rollbackId, rollbackId),
with: {
deployment: {
with: {
application: {
with: {
environment: {
with: {
project: true,
},
},
},
},
},
},
deployment: true,
},
});
@@ -162,7 +172,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 +207,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,
@@ -236,6 +246,10 @@ const rollbackApplication = async (
const volumesMount = generateVolumeMounts(mounts);
const resolvedNetworks = await resolveServiceNetworks(
fullContext as Parameters<typeof resolveServiceNetworks>[0],
);
const {
HealthCheck,
RestartPolicy,
@@ -244,9 +258,10 @@ const rollbackApplication = async (
Mode,
RollbackConfig,
UpdateConfig,
Networks,
Ulimits,
} = generateConfigContainer(fullContext as ApplicationNested);
} = generateConfigContainer(
fullContext as Parameters<typeof generateConfigContainer>[0],
);
const bindsMount = generateBindMounts(mounts);
const envVariables = prepareEnvironmentVariables(
@@ -254,18 +269,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: {
@@ -283,7 +296,7 @@ const rollbackApplication = async (
...(Ulimits && { Ulimits }),
Labels,
},
Networks,
Networks: resolvedNetworks,
RestartPolicy,
Placement,
Resources: {
+48 -1
View File
@@ -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>,
) => {
@@ -39,6 +81,11 @@ export const findScheduleById = async (scheduleId: string) => {
where: eq(schedules.scheduleId, scheduleId),
with: {
application: {
columns: {
applicationId: true,
appName: true,
serverId: true,
},
with: {
environment: {
with: {
+30 -8
View File
@@ -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),
@@ -79,15 +100,16 @@ export const deleteServer = async (serverId: string) => {
export const haveActiveServices = async (serverId: string) => {
const currentServer = await db.query.server.findFirst({
where: eq(server.serverId, serverId),
columns: { serverId: true },
with: {
applications: true,
compose: true,
libsql: true,
mariadb: true,
mongo: true,
mysql: true,
postgres: true,
redis: true,
applications: { columns: { applicationId: true } },
compose: { columns: { composeId: true } },
libsql: { columns: { libsqlId: true } },
mariadb: { columns: { mariadbId: true } },
mongo: { columns: { mongoId: true } },
mysql: { columns: { mysqlId: true } },
postgres: { columns: { postgresId: true } },
redis: { columns: { redisId: true } },
},
});
+18 -2
View File
@@ -4,11 +4,12 @@ import {
apikey,
invitation,
member,
passkey,
user,
} from "@dokploy/server/db/schema";
import { TRPCError } from "@trpc/server";
import * as bcrypt from "bcrypt";
import { and, eq } from "drizzle-orm";
import { and, desc, eq } from "drizzle-orm";
import { auth } from "../lib/auth";
export type User = typeof user.$inferSelect;
@@ -396,6 +397,21 @@ export const findMemberById = async (
return result;
};
export const findPasskeysByUserId = async (userId: string) => {
return db.query.passkey.findMany({
where: eq(passkey.userId, userId),
columns: {
id: true,
name: true,
deviceType: true,
backedUp: true,
createdAt: true,
aaguid: true,
},
orderBy: [desc(passkey.createdAt)],
});
};
export const createOrganizationUserWithCredentials = async ({
organizationId,
email,
@@ -430,7 +446,7 @@ export const createOrganizationUserWithCredentials = async ({
.insert(user)
.values({
email: normalizedEmail,
emailVerified: false,
emailVerified: true,
updatedAt: now,
})
.returning({
+11 -1
View File
@@ -13,6 +13,11 @@ export const findVolumeBackupById = async (volumeBackupId: string) => {
where: eq(volumeBackups.volumeBackupId, volumeBackupId),
with: {
application: {
columns: {
applicationId: true,
appName: true,
serverId: true,
},
with: {
environment: {
with: {
@@ -84,7 +89,12 @@ export const findVolumeBackupById = async (volumeBackupId: string) => {
},
},
},
destination: true,
destination: {
columns: {
accessKey: false,
secretAccessKey: false,
},
},
},
});
@@ -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;
}
};
-66
View File
@@ -1,66 +0,0 @@
import type { CreateServiceOptions } from "dockerode";
import { docker } from "../constants";
import { pullImage } from "../utils/docker/utils";
export const initializeRedis = async () => {
const imageName = "redis:7";
const containerName = "dokploy-redis";
const settings: CreateServiceOptions = {
Name: containerName,
TaskTemplate: {
ContainerSpec: {
Image: imageName,
Mounts: [
{
Type: "volume",
Source: "dokploy-redis",
Target: "/data",
},
],
},
Networks: [{ Target: "dokploy-network" }],
Placement: {
Constraints: ["node.role==manager"],
},
},
Mode: {
Replicated: {
Replicas: 1,
},
},
...(process.env.NODE_ENV === "development" && {
EndpointSpec: {
Ports: [
{
TargetPort: 6379,
PublishedPort: 6379,
Protocol: "tcp",
PublishMode: "host",
},
],
},
}),
};
try {
await pullImage(imageName);
const service = docker.getService(containerName);
const inspect = await service.inspect();
await service.update({
version: Number.parseInt(inspect.Version.Index),
...settings,
});
console.log("Redis Started ✅");
} catch (_) {
try {
await docker.createService(settings);
} catch (error: any) {
if (error?.statusCode !== 409) {
throw error;
}
console.log("Redis service already exists, continuing...");
}
console.log("Redis Not Found: Starting ✅");
}
};
+17 -1
View File
@@ -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). "
+43
View File
@@ -74,6 +74,49 @@ export async function fetchTemplatesList(
}));
}
const LOGO_MIME_TYPES: Record<string, string> = {
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
svg: "image/svg+xml",
webp: "image/webp",
gif: "image/gif",
};
export async function fetchTemplateLogo(
templateId: string,
baseUrl = "https://templates.dokploy.com",
): Promise<string | null> {
try {
const templates = await fetchTemplatesList(baseUrl);
const template = templates.find((t) => t.id === templateId);
if (!template?.logo) return null;
const response = await fetch(
`${baseUrl}/blueprints/${templateId}/${template.logo}`,
{ signal: AbortSignal.timeout(10000) },
);
if (!response.ok) return null;
const buffer = Buffer.from(await response.arrayBuffer());
if (buffer.length === 0) return null;
const contentType = response.headers.get("content-type")?.split(";")[0];
const extension = template.logo.split(".").pop()?.toLowerCase() ?? "";
const mimeType = contentType?.startsWith("image/")
? contentType
: LOGO_MIME_TYPES[extension];
if (!mimeType) return null;
const dataUrl = `data:${mimeType};base64,${buffer.toString("base64")}`;
if (dataUrl.length > 2 * 1024 * 1024) return null;
return dataUrl;
} catch {
return null;
}
}
/**
* Fetches a specific template's files
*/
+3 -2
View File
@@ -35,7 +35,8 @@ export const generateRandomDomain = ({
projectName,
}: Schema): string => {
const hash = randomBytes(3).toString("hex");
const slugIp = serverIp.replaceAll(".", "-").replaceAll(":", "-");
const effectiveIp = serverIp || "127.0.0.1";
const slugIp = effectiveIp.replaceAll(".", "-").replaceAll(":", "-");
// Domain labels have a max length of 63 characters
// Reserve space for: hash (6) + separators (1-2) + ip section + dot + sslip.io (8)
@@ -46,7 +47,7 @@ export const generateRandomDomain = ({
? projectName.substring(0, maxProjectNameLength)
: projectName;
return `${truncatedProjectName}-${hash}${slugIp === "" ? "" : `-${slugIp}`}.sslip.io`;
return `${truncatedProjectName}-${hash}-${slugIp}.sslip.io`;
};
export const generateHash = (length = 8): string => {
@@ -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);
}
@@ -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({
+2 -1
View File
@@ -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}`;
+6 -3
View File
@@ -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)));
}
};
+2 -1
View File
@@ -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 {
+2 -1
View File
@@ -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({
+2 -1
View File
@@ -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({
+2 -1
View File
@@ -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 {
@@ -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]"');
};
+18 -11
View File
@@ -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) {
@@ -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");
+15 -4
View File
@@ -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;
}
+25 -24
View File
@@ -1,3 +1,5 @@
import { resolveServiceNetworks } from "@dokploy/server/services/network";
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 +30,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 } };
}
@@ -99,6 +101,8 @@ export const mechanizeDockerContainer = async (
const volumesMount = generateVolumeMounts(mounts);
const resolvedNetworks = await resolveServiceNetworks(application);
const {
HealthCheck,
RestartPolicy,
@@ -107,7 +111,6 @@ export const mechanizeDockerContainer = async (
Mode,
RollbackConfig,
UpdateConfig,
Networks,
StopGracePeriod,
EndpointSpec,
Ulimits,
@@ -121,8 +124,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 = {
@@ -146,7 +149,7 @@ export const mechanizeDockerContainer = async (
...(Ulimits && { Ulimits }),
Labels,
},
Networks,
Networks: resolvedNetworks,
RestartPolicy,
Placement,
Resources: {
@@ -190,7 +193,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 +202,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 +225,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