chore: clean up unused variables and improve error handling across codebase

This commit focuses on removing unused variables, adding placeholder error handling, and generally tidying up various files across the Dokploy application. Changes include:

- Removing unused imports and variables
- Adding placeholder error handling in catch blocks
- Cleaning up commented-out code
- Removing deprecated utility files
- Improving type safety and code consistency
This commit is contained in:
Mauricio Siu
2025-02-22 20:35:21 -06:00
parent 1a415b96c9
commit 8ab6d6b282
132 changed files with 375 additions and 471 deletions

View File

@@ -28,19 +28,16 @@ export const certificates = pgTable("certificate", {
}),
});
export const certificatesRelations = relations(
certificates,
({ one, many }) => ({
server: one(server, {
fields: [certificates.serverId],
references: [server.serverId],
}),
organization: one(organization, {
fields: [certificates.organizationId],
references: [organization.id],
}),
export const certificatesRelations = relations(certificates, ({ one }) => ({
server: one(server, {
fields: [certificates.serverId],
references: [server.serverId],
}),
);
organization: one(organization, {
fields: [certificates.organizationId],
references: [organization.id],
}),
}));
export const apiCreateCertificate = createInsertSchema(certificates, {
name: z.string().min(1),

View File

@@ -29,7 +29,7 @@ export const gitProvider = pgTable("git_provider", {
.references(() => organization.id, { onDelete: "cascade" }),
});
export const gitProviderRelations = relations(gitProvider, ({ one, many }) => ({
export const gitProviderRelations = relations(gitProvider, ({ one }) => ({
github: one(github, {
fields: [gitProvider.gitProviderId],
references: [github.gitProviderId],

View File

@@ -32,7 +32,7 @@ export const registry = pgTable("registry", {
.references(() => organization.id, { onDelete: "cascade" }),
});
export const registryRelations = relations(registry, ({ one, many }) => ({
export const registryRelations = relations(registry, ({ many }) => ({
applications: many(applications),
}));

View File

@@ -2,14 +2,12 @@ import type { IncomingMessage } from "node:http";
import * as bcrypt from "bcrypt";
import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import {
createAuthMiddleware,
organization,
twoFactor,
} from "better-auth/plugins";
import { organization, twoFactor } from "better-auth/plugins";
import { and, desc, eq } from "drizzle-orm";
import { db } from "../db";
import * as schema from "../db/schema";
import { sendVerificationEmail } from "../verification/send-verification-email";
import { IS_CLOUD } from "../constants";
export const auth = betterAuth({
database: drizzleAdapter(db, {
@@ -27,9 +25,18 @@ export const auth = betterAuth({
clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
},
},
emailVerification: {
sendOnSignUp: true,
autoSignInAfterVerification: true,
sendVerificationEmail: async ({ user, url }) => {
console.log("Sending verification email to", user.email);
await sendVerificationEmail(user.email, url);
},
},
emailAndPassword: {
enabled: true,
autoSignIn: !IS_CLOUD,
requireEmailVerification: IS_CLOUD,
password: {
async hash(password) {
return bcrypt.hashSync(password, 10);
@@ -39,33 +46,37 @@ export const auth = betterAuth({
},
},
},
hooks: {
after: createAuthMiddleware(async (ctx) => {
if (ctx.path.startsWith("/sign-up")) {
const newSession = ctx.context.newSession;
if (ctx.headers?.get("x-dokploy-token")) {
} else {
const organization = await db
.insert(schema.organization)
.values({
name: "My Organization",
ownerId: newSession?.user?.id || "",
createdAt: new Date(),
})
.returning()
.then((res) => res[0]);
await db.insert(schema.member).values({
userId: newSession?.user?.id || "",
organizationId: organization?.id || "",
role: "owner",
createdAt: new Date(),
});
}
}
}),
},
databaseHooks: {
user: {
create: {
after: async (user) => {
const isAdminPresent = await db.query.member.findFirst({
where: eq(schema.member.role, "owner"),
});
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(),
});
});
}
},
},
},
session: {
create: {
before: async (session) => {
@@ -106,7 +117,7 @@ export const auth = betterAuth({
plugins: [
twoFactor(),
organization({
async sendInvitationEmail(data, request) {
async sendInvitationEmail(data, _request) {
const inviteLink = `https://example.com/accept-invitation/${data.id}`;
// https://example.com/accept-invitation/8jlBi9Tb9isDb8mc8Sb85u1BaJYklKB2
// sendOrganizationInvitation({

View File

@@ -1,94 +0,0 @@
// import {
// decodeHex,
// encodeBase32LowerCaseNoPadding,
// encodeHexLowerCase,
// } from "@oslojs/encoding";
// import { generateRandomString } from "@oslojs/crypto/random";
// import { constantTimeEqual } from "@oslojs/crypto/subtle";
// import { scrypt } from "./scrypt/index";
// import type { RandomReader } from "@oslojs/crypto/random";
// async function generateScryptKey(
// data: string,
// salt: string,
// blockSize = 16,
// ): Promise<Uint8Array> {
// const encodedData = new TextEncoder().encode(data);
// const encodedSalt = new TextEncoder().encode(salt);
// const keyUint8Array = await scrypt(encodedData, encodedSalt, {
// N: 16384,
// r: blockSize,
// p: 1,
// dkLen: 64,
// });
// return new Uint8Array(keyUint8Array);
// }
// const random: RandomReader = {
// read(bytes: Uint8Array): void {
// crypto.getRandomValues(bytes);
// },
// };
// export function generateId(length: number): string {
// const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
// return generateRandomString(random, alphabet, length);
// }
// export function generateIdFromEntropySize(size: number): string {
// const buffer = crypto.getRandomValues(new Uint8Array(size));
// return encodeBase32LowerCaseNoPadding(buffer);
// }
// export class Scrypt implements PasswordHashingAlgorithm {
// async hash(password: string): Promise<string> {
// const salt = encodeHexLowerCase(crypto.getRandomValues(new Uint8Array(16)));
// const key = await generateScryptKey(password.normalize("NFKC"), salt);
// return `${salt}:${encodeHexLowerCase(key)}`;
// }
// async verify(hash: string, password: string): Promise<boolean> {
// const parts = hash.split(":");
// if (parts.length !== 2) return false;
// const [salt, key] = parts;
// const targetKey = await generateScryptKey(password.normalize("NFKC"), salt);
// return constantTimeEqual(targetKey, decodeHex(key));
// }
// }
// export class LegacyScrypt implements PasswordHashingAlgorithm {
// async hash(password: string): Promise<string> {
// const salt = encodeHexLowerCase(crypto.getRandomValues(new Uint8Array(16)));
// const key = await generateScryptKey(password.normalize("NFKC"), salt);
// return `s2:${salt}:${encodeHexLowerCase(key)}`;
// }
// async verify(hash: string, password: string): Promise<boolean> {
// const parts = hash.split(":");
// if (parts.length === 2) {
// const [salt, key] = parts;
// const targetKey = await generateScryptKey(
// password.normalize("NFKC"),
// salt,
// 8,
// );
// const result = constantTimeEqual(targetKey, decodeHex(key));
// return result;
// }
// if (parts.length !== 3) return false;
// const [version, salt, key] = parts;
// if (version === "s2") {
// const targetKey = await generateScryptKey(
// password.normalize("NFKC"),
// salt,
// );
// return constantTimeEqual(targetKey, decodeHex(key));
// }
// return false;
// }
// }
// export interface PasswordHashingAlgorithm {
// hash(password: string): Promise<string>;
// verify(hash: string, password: string): Promise<boolean>;
// }

View File

@@ -1 +0,0 @@
//

View File

@@ -73,7 +73,7 @@ export const readStatsFile = async (
const filePath = `${MONITORING_PATH}/${appName}/${statType}.json`;
const data = await promises.readFile(filePath, "utf-8");
return JSON.parse(data);
} catch (error) {
} catch (_error) {
return [];
}
};
@@ -108,7 +108,7 @@ export const readLastValueStatsFile = async (
const data = await promises.readFile(filePath, "utf-8");
const stats = JSON.parse(data);
return stats[stats.length - 1] || null;
} catch (error) {
} catch (_error) {
return null;
}
};

View File

@@ -12,8 +12,8 @@ import { IS_CLOUD } from "../constants";
export type User = typeof users_temp.$inferSelect;
export const createInvitation = async (
input: typeof apiCreateUserInvitation._type,
adminId: string,
_input: typeof apiCreateUserInvitation._type,
_adminId: string,
) => {
// await db.transaction(async (tx) => {
// const result = await tx
@@ -83,8 +83,8 @@ export const updateUser = async (userId: string, userData: Partial<User>) => {
};
export const updateAdminById = async (
adminId: string,
adminData: Partial<User>,
_adminId: string,
_adminData: Partial<User>,
) => {
// const admin = await db
// .update(admins)
@@ -102,8 +102,6 @@ export const isAdminPresent = async () => {
where: eq(member.role, "owner"),
});
console.log("admin", admin);
if (!admin) {
return false;
}

View File

@@ -98,7 +98,7 @@ export const getConfig = async (
const config = JSON.parse(stdout);
return config;
} catch (error) {}
} catch (_error) {}
};
export const getContainersByAppNameMatch = async (
@@ -156,7 +156,7 @@ export const getContainersByAppNameMatch = async (
});
return containers || [];
} catch (error) {}
} catch (_error) {}
return [];
};
@@ -214,7 +214,7 @@ export const getStackContainersByAppName = async (
});
return containers || [];
} catch (error) {}
} catch (_error) {}
return [];
};
@@ -274,7 +274,7 @@ export const getServiceContainersByAppName = async (
});
return containers || [];
} catch (error) {}
} catch (_error) {}
return [];
};
@@ -325,7 +325,7 @@ export const getContainersByAppLabel = async (
});
return containers || [];
} catch (error) {}
} catch (_error) {}
return [];
};
@@ -344,7 +344,7 @@ export const containerRestart = async (containerId: string) => {
const config = JSON.parse(stdout);
return config;
} catch (error) {}
} catch (_error) {}
};
export const getSwarmNodes = async (serverId?: string) => {
@@ -373,7 +373,7 @@ export const getSwarmNodes = async (serverId?: string) => {
.split("\n")
.map((line) => JSON.parse(line));
return nodesArray;
} catch (error) {}
} catch (_error) {}
};
export const getNodeInfo = async (nodeId: string, serverId?: string) => {
@@ -399,7 +399,7 @@ export const getNodeInfo = async (nodeId: string, serverId?: string) => {
const nodeInfo = JSON.parse(stdout);
return nodeInfo;
} catch (error) {}
} catch (_error) {}
};
export const getNodeApplications = async (serverId?: string) => {
@@ -431,7 +431,7 @@ export const getNodeApplications = async (serverId?: string) => {
.filter((service) => !service.Name.startsWith("dokploy-"));
return appArray;
} catch (error) {}
} catch (_error) {}
};
export const getApplicationInfo = async (
@@ -464,5 +464,5 @@ export const getApplicationInfo = async (
.map((line) => JSON.parse(line));
return appArray;
} catch (error) {}
} catch (_error) {}
};

View File

@@ -119,7 +119,7 @@ export const issueCommentExists = async ({
comment_id: comment_id,
});
return true;
} catch (error) {
} catch (_error) {
return false;
}
};

View File

@@ -211,7 +211,7 @@ export const deleteFileMount = async (mountId: string) => {
} else {
await removeFileOrDirectory(fullPath);
}
} catch (error) {}
} catch (_error) {}
};
export const getBaseFilesPath = async (mountId: string) => {

View File

@@ -103,7 +103,7 @@ export const removePreviewDeployment = async (previewDeploymentId: string) => {
for (const operation of cleanupOperations) {
try {
await operation();
} catch (error) {}
} catch (_error) {}
}
return deployment[0];
} catch (error) {

View File

@@ -66,7 +66,7 @@ export const setupMonitoring = async (serverId: string) => {
await container.inspect();
await container.remove({ force: true });
console.log("Removed existing container");
} catch (error) {
} catch (_error) {
// Container doesn't exist, continue
}
@@ -135,7 +135,7 @@ export const setupWebMonitoring = async (userId: string) => {
await container.inspect();
await container.remove({ force: true });
console.log("Removed existing container");
} catch (error) {}
} catch (_error) {}
await docker.createContainer(settings);
const newContainer = docker.getContainer(containerName);

View File

@@ -56,7 +56,7 @@ export const initializePostgres = async () => {
});
console.log("Postgres Started ✅");
} catch (error) {
} catch (_error) {
await docker.createService(settings);
console.log("Postgres Not Found: Starting ✅");
}

View File

@@ -52,7 +52,7 @@ export const initializeRedis = async () => {
...settings,
});
console.log("Redis Started ✅");
} catch (error) {
} catch (_error) {
await docker.createService(settings);
console.log("Redis Not Found: Starting ✅");
}

View File

@@ -89,7 +89,7 @@ export const serverAudit = async (serverId: string) => {
.on("data", (data: string) => {
output += data;
})
.stderr.on("data", (data) => {});
.stderr.on("data", (_data) => {});
});
})
.on("error", (err) => {

View File

@@ -128,7 +128,7 @@ export const serverValidate = async (serverId: string) => {
.on("data", (data: string) => {
output += data;
})
.stderr.on("data", (data) => {});
.stderr.on("data", (_data) => {});
});
})
.on("error", (err) => {

View File

@@ -18,7 +18,7 @@ export const dockerSwarmInitialized = async () => {
await docker.swarmInspect();
return true;
} catch (e) {
} catch (_e) {
return false;
}
};
@@ -41,7 +41,7 @@ export const dockerNetworkInitialized = async () => {
try {
await docker.getNetwork("dokploy-network").inspect();
return true;
} catch (e) {
} catch (_e) {
return false;
}
};

View File

@@ -127,7 +127,7 @@ export const initializeTraefik = async ({
});
console.log("Traefik Started ✅");
} catch (error) {
} catch (_error) {
await docker.createService(settings);
console.log("Traefik Not Found: Starting ✅");
}

View File

@@ -36,7 +36,7 @@ type AnyObj = Record<PropertyKey, unknown>;
type ZodObj<T extends AnyObj> = {
[key in keyof T]: z.ZodType<T[key]>;
};
const zObject = <T extends AnyObj>(arg: ZodObj<T>) => z.object(arg);
const _zObject = <T extends AnyObj>(arg: ZodObj<T>) => z.object(arg);
// const goodDogScheme = zObject<UserWithPosts>({
// // prueba: schema.selectDatabaseSchema,

View File

@@ -32,7 +32,7 @@ class LogRotationManager {
// return setting?.enableLogRotation ?? false;
}
private async setStateInDB(active: boolean): Promise<void> {
private async setStateInDB(_active: boolean): Promise<void> {
// const admin = await db.query.admins.findFirst({});
// if (!admin) {
// return;

View File

@@ -28,7 +28,7 @@ export const removeScheduleBackup = (backupId: string) => {
};
export const getS3Credentials = (destination: Destination) => {
const { accessKey, secretAccessKey, bucket, region, endpoint, provider } =
const { accessKey, secretAccessKey, region, endpoint, provider } =
destination;
const rcloneFlags = [
`--s3-access-key-id=${accessKey}`,

View File

@@ -98,8 +98,7 @@ export const getBuildComposeCommand = async (
logPath: string,
) => {
const { COMPOSE_PATH } = paths(true);
const { sourceType, appName, mounts, composeType, domains, composePath } =
compose;
const { sourceType, appName, mounts, composeType, domains } = compose;
const command = createCommand(compose);
const envCommand = getCreateEnvFileCommand(compose);
const projectPath = join(COMPOSE_PATH, compose.appName, "code");

View File

@@ -197,7 +197,7 @@ export const mechanizeDockerContainer = async (
ForceUpdate: inspect.Spec.TaskTemplate.ForceUpdate + 1,
},
});
} catch (error) {
} catch (_error) {
await docker.createService(settings);
}
};

View File

@@ -91,7 +91,7 @@ export const getNixpacksCommand = (
application: ApplicationNested,
logPath: string,
) => {
const { env, appName, publishDirectory, serverId } = application;
const { env, appName, publishDirectory } = application;
const buildAppDirectory = getBuildAppDirectory(application);
const buildContainerId = `${appName}-${nanoid(10)}`;

View File

@@ -98,7 +98,7 @@ export const buildMariadb = async (mariadb: MariadbNested) => {
version: Number.parseInt(inspect.Version.Index),
...settings,
});
} catch (error) {
} catch (_error) {
await docker.createService(settings);
}
};

View File

@@ -152,7 +152,7 @@ ${command ?? "wait $MONGOD_PID"}`;
version: Number.parseInt(inspect.Version.Index),
...settings,
});
} catch (error) {
} catch (_error) {
await docker.createService(settings);
}
};

View File

@@ -104,7 +104,7 @@ export const buildMysql = async (mysql: MysqlNested) => {
version: Number.parseInt(inspect.Version.Index),
...settings,
});
} catch (error) {
} catch (_error) {
await docker.createService(settings);
}
};

View File

@@ -95,7 +95,7 @@ export const buildRedis = async (redis: RedisNested) => {
version: Number.parseInt(inspect.Version.Index),
...settings,
});
} catch (error) {
} catch (_error) {
await docker.createService(settings);
}
};

View File

@@ -109,7 +109,7 @@ export const loadDockerComposeRemote = async (
if (!stdout) return null;
const parsedConfig = load(stdout) as ComposeSpecification;
return parsedConfig;
} catch (err) {
} catch (_err) {
return null;
}
};

View File

@@ -100,7 +100,7 @@ export const containerExists = async (containerName: string) => {
try {
await container.inspect();
return true;
} catch (error) {
} catch (_error) {
return false;
}
};
@@ -240,7 +240,7 @@ export const startServiceRemote = async (serverId: string, appName: string) => {
export const removeService = async (
appName: string,
serverId?: string | null,
deleteVolumes = false,
_deleteVolumes = false,
) => {
try {
const command = `docker service rm ${appName}`;

View File

@@ -34,7 +34,7 @@ export async function checkGPUStatus(serverId?: string): Promise<GPUInfo> {
...gpuInfo,
...cudaInfo,
};
} catch (error) {
} catch (_error) {
return {
driverInstalled: false,
driverVersion: undefined,
@@ -315,7 +315,7 @@ const setupLocalServer = async (daemonConfig: any) => {
try {
await execAsync(setupCommands);
} catch (error) {
} catch (_error) {
throw new Error(
"Failed to configure GPU support. Please ensure you have sudo privileges and try again.",
);

View File

@@ -27,7 +27,7 @@ export const execAsyncRemote = async (
throw err;
}
stream
.on("close", (code: number, signal: string) => {
.on("close", (code: number, _signal: string) => {
conn.end();
if (code === 0) {
resolve({ stdout, stderr });

View File

@@ -176,7 +176,6 @@ export const getBitbucketCloneCommand = async (
bitbucketBranch,
bitbucketId,
serverId,
bitbucket,
} = entity;
if (!serverId) {

View File

@@ -320,7 +320,7 @@ export const cloneGitRawRepository = async (entity: {
outputPath,
"--progress",
],
(data) => {},
(_data) => {},
{
env: {
...process.env,

View File

@@ -162,8 +162,6 @@ export const getGitlabCloneCommand = async (
) => {
const {
appName,
gitlabRepository,
gitlabOwner,
gitlabPathNamespace,
gitlabBranch,
gitlabId,
@@ -328,14 +326,7 @@ export const getGitlabBranches = async (input: {
};
export const cloneRawGitlabRepository = async (entity: Compose) => {
const {
appName,
gitlabRepository,
gitlabOwner,
gitlabBranch,
gitlabId,
gitlabPathNamespace,
} = entity;
const { appName, gitlabBranch, gitlabId, gitlabPathNamespace } = entity;
if (!gitlabId) {
throw new TRPCError({

View File

@@ -67,7 +67,7 @@ export const removeTraefikConfig = async (
if (fs.existsSync(configPath)) {
await fs.promises.unlink(configPath);
}
} catch (error) {}
} catch (_error) {}
};
export const removeTraefikConfigRemote = async (
@@ -78,7 +78,7 @@ export const removeTraefikConfigRemote = async (
const { DYNAMIC_TRAEFIK_PATH } = paths(true);
const configPath = path.join(DYNAMIC_TRAEFIK_PATH, `${appName}.yml`);
await execAsyncRemote(serverId, `rm ${configPath}`);
} catch (error) {}
} catch (_error) {}
};
export const loadOrCreateConfig = (appName: string): FileConfig => {
@@ -110,7 +110,7 @@ export const loadOrCreateConfigRemote = async (
http: { routers: {}, services: {} },
};
return parsedConfig;
} catch (err) {
} catch (_err) {
return fileConfig;
}
};
@@ -132,7 +132,7 @@ export const readRemoteConfig = async (serverId: string, appName: string) => {
const { stdout } = await execAsyncRemote(serverId, `cat ${configPath}`);
if (!stdout) return null;
return stdout;
} catch (err) {
} catch (_err) {
return null;
}
};

View File

@@ -0,0 +1,49 @@
import {
sendDiscordNotification,
sendEmailNotification,
} from "../utils/notifications/utils";
export const sendVerificationEmail = async (email: string, url: string) => {
await sendEmailNotification(
{
fromAddress: process.env.SMTP_FROM_ADDRESS || "",
toAddresses: [email],
smtpServer: process.env.SMTP_SERVER || "",
smtpPort: Number(process.env.SMTP_PORT),
username: process.env.SMTP_USERNAME || "",
password: process.env.SMTP_PASSWORD || "",
},
"Confirm your email | Dokploy",
`
Welcome to Dokploy!
Please confirm your email by clicking the link below:
<a href="${url}">
Confirm Email
</a>
`,
);
return true;
};
export const sendDiscordNotificationWelcome = async (email: string) => {
await sendDiscordNotification(
{
webhookUrl: process.env.DISCORD_WEBHOOK_URL || "",
},
{
title: "New User Registered",
color: 0x00ff00,
fields: [
{
name: "Email",
value: email,
inline: true,
},
],
timestamp: new Date(),
footer: {
text: "Dokploy User Registration Notification",
},
},
);
};