* New Version: 3.0.0
This commit is contained in:
Andras Bacsai
2022-07-06 11:02:36 +02:00
committed by GitHub
parent 9137e8bc32
commit 87ba4560ad
491 changed files with 16824 additions and 20459 deletions

View File

@@ -0,0 +1,871 @@
import cuid from 'cuid';
import crypto from 'node:crypto'
import jsonwebtoken from 'jsonwebtoken';
import axios from 'axios';
import { day } from '../../../../lib/dayjs';
import type { FastifyRequest } from 'fastify';
import { FastifyReply } from 'fastify';
import { CheckDNS, DeleteApplication, DeployApplication, GetApplication, SaveApplication, SaveApplicationSettings } from '.';
import { setDefaultBaseImage, setDefaultConfiguration } from '../../../../lib/buildPacks/common';
import { asyncExecShell, checkDomainsIsValidInDNS, checkDoubleBranch, decrypt, encrypt, errorHandler, generateSshKeyPair, getContainerUsage, getDomain, isDev, isDomainConfigured, prisma, stopBuild, uniqueName } from '../../../../lib/common';
import { checkContainer, dockerInstance, getEngine, isContainerExited, removeContainer } from '../../../../lib/docker';
import { scheduler } from '../../../../lib/scheduler';
export async function listApplications(request: FastifyRequest) {
try {
const { teamId } = request.user
const applications = await prisma.application.findMany({
where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } },
include: { teams: true }
});
const settings = await prisma.setting.findFirst()
return {
applications,
settings
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getApplication(request: FastifyRequest<GetApplication>) {
try {
const { id } = request.params
const { teamId } = request.user
const appId = process.env['COOLIFY_APP_ID'];
let isRunning = false;
let isExited = false;
const application = await getApplicationFromDB(id, teamId);
if (application?.destinationDockerId && application.destinationDocker?.engine) {
isRunning = await checkContainer(application.destinationDocker.engine, id);
isExited = await isContainerExited(application.destinationDocker.engine, id);
}
return {
isQueueActive: scheduler.workers.has('deployApplication'),
isRunning,
isExited,
application,
appId
};
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function newApplication(request: FastifyRequest, reply: FastifyReply) {
try {
const name = uniqueName();
const { teamId } = request.user
const { id } = await prisma.application.create({
data: {
name,
teams: { connect: { id: teamId } },
settings: { create: { debug: false, previews: false } }
}
});
return reply.code(201).send({ id });
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
function decryptApplication(application: any) {
if (application) {
if (application?.gitSource?.githubApp?.clientSecret) {
application.gitSource.githubApp.clientSecret = decrypt(application.gitSource.githubApp.clientSecret) || null;
}
if (application?.gitSource?.githubApp?.webhookSecret) {
application.gitSource.githubApp.webhookSecret = decrypt(application.gitSource.githubApp.webhookSecret) || null;
}
if (application?.gitSource?.githubApp?.privateKey) {
application.gitSource.githubApp.privateKey = decrypt(application.gitSource.githubApp.privateKey) || null;
}
if (application?.gitSource?.gitlabApp?.appSecret) {
application.gitSource.gitlabApp.appSecret = decrypt(application.gitSource.gitlabApp.appSecret) || null;
}
if (application?.secrets.length > 0) {
application.secrets = application.secrets.map((s: any) => {
s.value = decrypt(s.value) || null
return s;
});
}
return application;
}
}
export async function getApplicationFromDB(id: string, teamId: string) {
try {
let application = await prisma.application.findFirst({
where: { id, teams: { some: { id: teamId === '0' ? undefined : teamId } } },
include: {
destinationDocker: true,
settings: true,
gitSource: { include: { githubApp: true, gitlabApp: true } },
secrets: true,
persistentStorage: true
}
});
if (!application) {
throw { status: 404, message: 'Application not found.' };
}
application = decryptApplication(application);
const buildPack = application?.buildPack || null;
const { baseImage, baseBuildImage, baseBuildImages, baseImages } = setDefaultBaseImage(
buildPack
);
// Set default build images
if (!application.baseImage) {
application.baseImage = baseImage;
}
if (!application.baseBuildImage) {
application.baseBuildImage = baseBuildImage;
}
return { ...application, baseBuildImages, baseImages };
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getApplicationFromDBWebhook(projectId: number, branch: string) {
try {
let application = await prisma.application.findFirst({
where: { projectId, branch, settings: { autodeploy: true } },
include: {
destinationDocker: true,
settings: true,
gitSource: { include: { githubApp: true, gitlabApp: true } },
secrets: true,
persistentStorage: true
}
});
if (!application) {
throw { status: 500, message: 'Application not configured.' }
}
application = decryptApplication(application);
const { baseImage, baseBuildImage, baseBuildImages, baseImages } = setDefaultBaseImage(
application.buildPack
);
// Set default build images
if (!application.baseImage) {
application.baseImage = baseImage;
}
if (!application.baseBuildImage) {
application.baseBuildImage = baseBuildImage;
}
return { ...application, baseBuildImages, baseImages };
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveApplication(request: FastifyRequest<SaveApplication>, reply: FastifyReply) {
try {
const { id } = request.params
let {
name,
buildPack,
fqdn,
port,
exposePort,
installCommand,
buildCommand,
startCommand,
baseDirectory,
publishDirectory,
pythonWSGI,
pythonModule,
pythonVariable,
dockerFileLocation,
denoMainFile,
denoOptions,
baseImage,
baseBuildImage
} = request.body
if (port) port = Number(port);
if (exposePort) {
exposePort = Number(exposePort);
}
if (denoOptions) denoOptions = denoOptions.trim();
const defaultConfiguration = await setDefaultConfiguration({
buildPack,
port,
installCommand,
startCommand,
buildCommand,
publishDirectory,
baseDirectory,
dockerFileLocation,
denoMainFile
});
await prisma.application.update({
where: { id },
data: {
name,
fqdn,
exposePort,
pythonWSGI,
pythonModule,
pythonVariable,
denoOptions,
baseImage,
baseBuildImage,
...defaultConfiguration
}
});
return reply.code(201).send();
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveApplicationSettings(request: FastifyRequest<SaveApplicationSettings>, reply: FastifyReply) {
try {
const { id } = request.params
const { debug, previews, dualCerts, autodeploy, branch, projectId } = request.body
const isDouble = await checkDoubleBranch(branch, projectId);
if (isDouble && autodeploy) {
throw { status: 500, message: 'Application not configured.' }
}
await prisma.application.update({
where: { id },
data: { settings: { update: { debug, previews, dualCerts, autodeploy } } },
include: { destinationDocker: true }
});
return reply.code(201).send();
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function stopApplication(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params
const { teamId } = request.user
const application = await getApplicationFromDB(id, teamId);
if (application?.destinationDockerId && application.destinationDocker?.engine) {
const { engine } = application.destinationDocker;
const found = await checkContainer(engine, id);
if (found) {
await removeContainer({ id, engine });
}
}
return reply.code(201).send();
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function deleteApplication(request: FastifyRequest<DeleteApplication>, reply: FastifyReply) {
try {
const { id } = request.params
const { teamId } = request.user
const application = await prisma.application.findUnique({
where: { id },
include: { destinationDocker: true }
});
if (application?.destinationDockerId && application.destinationDocker?.engine && application.destinationDocker?.network) {
const host = getEngine(application.destinationDocker.engine);
const { stdout: containers } = await asyncExecShell(
`DOCKER_HOST=${host} docker ps -a --filter network=${application.destinationDocker.network} --filter name=${id} --format '{{json .}}'`
);
if (containers) {
const containersArray = containers.trim().split('\n');
for (const container of containersArray) {
const containerObj = JSON.parse(container);
const id = containerObj.ID;
await removeContainer({ id, engine: application.destinationDocker.engine });
}
}
}
await prisma.applicationSettings.deleteMany({ where: { application: { id } } });
await prisma.buildLog.deleteMany({ where: { applicationId: id } });
await prisma.build.deleteMany({ where: { applicationId: id } });
await prisma.secret.deleteMany({ where: { applicationId: id } });
await prisma.applicationPersistentStorage.deleteMany({ where: { applicationId: id } });
if (teamId === '0') {
await prisma.application.deleteMany({ where: { id } });
} else {
await prisma.application.deleteMany({ where: { id, teams: { some: { id: teamId } } } });
}
return {}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function checkDNS(request: FastifyRequest<CheckDNS>) {
try {
const { id } = request.params
let { exposePort, fqdn, forceSave, dualCerts } = request.body
fqdn = fqdn.toLowerCase();
const { isDNSCheckEnabled } = await prisma.setting.findFirst({});
const found = await isDomainConfigured({ id, fqdn });
if (found) {
throw { status: 500, message: `Domain ${getDomain(fqdn).replace('www.', '')} is already in use!` }
}
if (exposePort) {
exposePort = Number(exposePort);
if (exposePort < 1024 || exposePort > 65535) {
throw { status: 500, message: `Exposed Port needs to be between 1024 and 65535.` }
}
const { default: getPort } = await import('get-port');
const publicPort = await getPort({ port: exposePort });
if (publicPort !== exposePort) {
throw { status: 500, message: `Port ${exposePort} is already in use.` }
}
}
if (isDNSCheckEnabled && !isDev && !forceSave) {
return await checkDomainsIsValidInDNS({ hostname: request.hostname, fqdn, dualCerts });
}
return {}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getUsage(request) {
try {
const { id } = request.params
const teamId = request.user?.teamId;
const application = await getApplicationFromDB(id, teamId);
let usage = {};
if (application.destinationDockerId) {
[usage] = await Promise.all([getContainerUsage(application.destinationDocker.engine, id)]);
}
return {
usage
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function deployApplication(request: FastifyRequest<DeployApplication>) {
try {
const { id } = request.params
const teamId = request.user?.teamId;
const { pullmergeRequestId = null, branch } = request.body
const buildId = cuid();
const application = await getApplicationFromDB(id, teamId);
if (application) {
if (!application?.configHash) {
const configHash = crypto.createHash('sha256')
.update(
JSON.stringify({
buildPack: application.buildPack,
port: application.port,
exposePort: application.exposePort,
installCommand: application.installCommand,
buildCommand: application.buildCommand,
startCommand: application.startCommand
})
)
.digest('hex');
await prisma.application.update({ where: { id }, data: { configHash } });
}
await prisma.application.update({ where: { id }, data: { updatedAt: new Date() } });
await prisma.build.create({
data: {
id: buildId,
applicationId: id,
branch: application.branch,
destinationDockerId: application.destinationDocker?.id,
gitSourceId: application.gitSource?.id,
githubAppId: application.gitSource?.githubApp?.id,
gitlabAppId: application.gitSource?.gitlabApp?.id,
status: 'queued',
type: 'manual'
}
});
if (pullmergeRequestId) {
scheduler.workers.get('deployApplication').postMessage({
build_id: buildId,
type: 'manual',
...application,
sourceBranch: branch,
pullmergeRequestId
});
} else {
scheduler.workers.get('deployApplication').postMessage({
build_id: buildId,
type: 'manual',
...application
});
}
return {
buildId
};
}
throw { status: 500, message: 'Application not found!' }
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveApplicationSource(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params
const { gitSourceId } = request.body
await prisma.application.update({
where: { id },
data: { gitSource: { connect: { id: gitSourceId } } }
});
return reply.code(201).send()
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getGitHubToken(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params
const { teamId } = request.user
const application = await getApplicationFromDB(id, teamId);
const payload = {
iat: Math.round(new Date().getTime() / 1000),
exp: Math.round(new Date().getTime() / 1000 + 60),
iss: application.gitSource.githubApp.appId
};
const githubToken = jsonwebtoken.sign(payload, application.gitSource.githubApp.privateKey, {
algorithm: 'RS256'
});
const { data } = await axios.post(`${application.gitSource.apiUrl}/app/installations/${application.gitSource.githubApp.installationId}/access_tokens`, {}, {
headers: {
Authorization: `Bearer ${githubToken}`
}
})
return reply.code(201).send({
token: data.token
})
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function checkRepository(request: FastifyRequest) {
try {
const { id } = request.params
const { repository, branch } = request.query
const application = await prisma.application.findUnique({
where: { id },
include: { gitSource: true }
});
const found = await prisma.application.findFirst({
where: { branch, repository, gitSource: { type: application.gitSource.type }, id: { not: id } }
});
return {
used: found ? true : false
};
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveRepository(request, reply) {
try {
const { id } = request.params
let { repository, branch, projectId, autodeploy, webhookToken } = request.body
repository = repository.toLowerCase();
branch = branch.toLowerCase();
projectId = Number(projectId);
if (webhookToken) {
await prisma.application.update({
where: { id },
data: { repository, branch, projectId, gitSource: { update: { gitlabApp: { update: { webhookToken: webhookToken ? webhookToken : undefined } } } }, settings: { update: { autodeploy } } }
});
} else {
await prisma.application.update({
where: { id },
data: { repository, branch, projectId, settings: { update: { autodeploy } } }
});
}
return reply.code(201).send()
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveDestination(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params
const { destinationId } = request.body
await prisma.application.update({
where: { id },
data: { destinationDocker: { connect: { id: destinationId } } }
});
return reply.code(201).send()
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getBuildPack(request) {
try {
const { id } = request.params
const teamId = request.user?.teamId;
const application = await getApplicationFromDB(id, teamId);
return {
type: application.gitSource.type,
projectId: application.projectId,
repository: application.repository,
branch: application.branch,
apiUrl: application.gitSource.apiUrl
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveBuildPack(request, reply) {
try {
const { id } = request.params
const { buildPack } = request.body
await prisma.application.update({ where: { id }, data: { buildPack } });
return reply.code(201).send()
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getSecrets(request: FastifyRequest) {
try {
const { id } = request.params
let secrets = await prisma.secret.findMany({
where: { applicationId: id },
orderBy: { createdAt: 'desc' }
});
secrets = secrets.map((secret) => {
secret.value = decrypt(secret.value);
return secret;
});
secrets = secrets.filter((secret) => !secret.isPRMRSecret).sort((a, b) => {
return ('' + a.name).localeCompare(b.name);
})
return {
secrets
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveSecret(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params
let { name, value, isBuildSecret, isPRMRSecret, isNew } = request.body
if (isNew) {
const found = await prisma.secret.findFirst({ where: { name, applicationId: id, isPRMRSecret } });
if (found) {
throw { status: 500, message: `Secret ${name} already exists.` }
} else {
value = encrypt(value);
await prisma.secret.create({
data: { name, value, isBuildSecret, isPRMRSecret, application: { connect: { id } } }
});
}
} else {
value = encrypt(value);
const found = await prisma.secret.findFirst({ where: { applicationId: id, name, isPRMRSecret } });
if (found) {
await prisma.secret.updateMany({
where: { applicationId: id, name, isPRMRSecret },
data: { value, isBuildSecret, isPRMRSecret }
});
} else {
await prisma.secret.create({
data: { name, value, isBuildSecret, isPRMRSecret, application: { connect: { id } } }
});
}
}
return reply.code(201).send()
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function deleteSecret(request: FastifyRequest) {
try {
const { id } = request.params
const { name } = request.body
await prisma.secret.deleteMany({ where: { applicationId: id, name } });
return {}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getStorages(request: FastifyRequest) {
try {
const { id } = request.params
const persistentStorages = await prisma.applicationPersistentStorage.findMany({ where: { applicationId: id } });
return {
persistentStorages
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveStorage(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params
const { path, newStorage, storageId } = request.body
if (newStorage) {
await prisma.applicationPersistentStorage.create({
data: { path, application: { connect: { id } } }
});
} else {
await prisma.applicationPersistentStorage.update({
where: { id: storageId },
data: { path }
});
}
return reply.code(201).send()
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function deleteStorage(request: FastifyRequest) {
try {
const { id } = request.params
const { path } = request.body
await prisma.applicationPersistentStorage.deleteMany({ where: { applicationId: id, path } });
return {}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getPreviews(request: FastifyRequest) {
try {
const { id } = request.params
const { teamId } = request.user
let secrets = await prisma.secret.findMany({
where: { applicationId: id },
orderBy: { createdAt: 'desc' }
});
secrets = secrets.map((secret) => {
secret.value = decrypt(secret.value);
return secret;
});
const applicationSecrets = secrets.filter((secret) => !secret.isPRMRSecret);
const PRMRSecrets = secrets.filter((secret) => secret.isPRMRSecret);
const destinationDocker = await prisma.destinationDocker.findFirst({
where: { application: { some: { id } }, teams: { some: { id: teamId } } }
});
const docker = dockerInstance({ destinationDocker });
const listContainers = await docker.engine.listContainers({
filters: { network: [destinationDocker.network], name: [id] }
});
const containers = listContainers.filter((container) => {
return (
container.Labels['coolify.configuration'] &&
container.Labels['coolify.type'] === 'standalone-application'
);
});
const jsonContainers = containers
.map((container) =>
JSON.parse(Buffer.from(container.Labels['coolify.configuration'], 'base64').toString())
)
.filter((container) => {
return container.pullmergeRequestId && container.applicationId === id;
});
return {
containers: jsonContainers,
applicationSecrets: applicationSecrets.sort((a, b) => {
return ('' + a.name).localeCompare(b.name);
}),
PRMRSecrets: PRMRSecrets.sort((a, b) => {
return ('' + a.name).localeCompare(b.name);
})
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getApplicationLogs(request: FastifyRequest) {
try {
const { id } = request.params
let { since = 0 } = request.query
if (since !== 0) {
since = day(since).unix();
}
const { destinationDockerId, destinationDocker } = await prisma.application.findUnique({
where: { id },
include: { destinationDocker: true }
});
if (destinationDockerId) {
const docker = dockerInstance({ destinationDocker });
try {
const container = await docker.engine.getContainer(id);
if (container) {
const { default: ansi } = await import('strip-ansi')
const logs = (
await container.logs({
stdout: true,
stderr: true,
timestamps: true,
since,
tail: 5000
})
)
.toString()
.split('\n')
.map((l) => ansi(l.slice(8)))
.filter((a) => a);
return {
logs
};
}
} catch (error) {
return {
logs: []
};
}
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getBuildLogs(request: FastifyRequest) {
try {
const { id } = request.params
let { buildId, skip = 0 } = request.query
if (typeof skip !== 'number') {
skip = Number(skip)
}
let builds = [];
const buildCount = await prisma.build.count({ where: { applicationId: id } });
if (buildId) {
builds = await prisma.build.findMany({ where: { applicationId: id, id: buildId } });
} else {
builds = await prisma.build.findMany({
where: { applicationId: id },
orderBy: { createdAt: 'desc' },
take: 5,
skip
});
}
builds = builds.map((build) => {
const updatedAt = day(build.updatedAt).utc();
build.took = updatedAt.diff(day(build.createdAt)) / 1000;
build.since = updatedAt.fromNow();
return build;
});
return {
builds,
buildCount
};
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getBuildIdLogs(request: FastifyRequest) {
try {
const { id, buildId } = request.params
let { sequence = 0 } = request.query
if (typeof sequence !== 'number') {
sequence = Number(sequence)
}
let logs = await prisma.buildLog.findMany({
where: { buildId, time: { gt: sequence } },
orderBy: { time: 'asc' }
});
const data = await prisma.build.findFirst({ where: { id: buildId } });
return {
logs,
status: data?.status || 'queued'
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getGitLabSSHKey(request: FastifyRequest) {
try {
const { id } = request.params
const application = await prisma.application.findUnique({
where: { id },
include: { gitSource: { include: { gitlabApp: true } } }
});
return { publicKey: application.gitSource.gitlabApp.publicSshKey };
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveGitLabSSHKey(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params
const application = await prisma.application.findUnique({
where: { id },
include: { gitSource: { include: { gitlabApp: true } } }
});
if (!application.gitSource?.gitlabApp?.privateSshKey) {
const keys = await generateSshKeyPair();
const encryptedPrivateKey = encrypt(keys.privateKey);
await prisma.gitlabApp.update({
where: { id: application.gitSource.gitlabApp.id },
data: { privateSshKey: encryptedPrivateKey, publicSshKey: keys.publicKey }
});
return reply.code(201).send({ publicKey: keys.publicKey })
}
return { message: 'SSH key already exists' }
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveDeployKey(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params
let { deployKeyId } = request.body;
deployKeyId = Number(deployKeyId);
const application = await prisma.application.findUnique({
where: { id },
include: { gitSource: { include: { gitlabApp: true } } }
});
await prisma.gitlabApp.update({
where: { id: application.gitSource.gitlabApp.id },
data: { deployKeyId }
});
return reply.code(201).send()
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function cancelDeployment(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params
const { buildId, applicationId } = request.body;
if (!buildId) {
throw { status: 500, message: 'buildId is required' }
}
await stopBuild(buildId, applicationId);
return reply.code(201).send()
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}

View File

@@ -0,0 +1,89 @@
import { FastifyPluginAsync } from 'fastify';
import { cancelDeployment, checkDNS, checkRepository, deleteApplication, deleteSecret, deleteStorage, deployApplication, getApplication, getApplicationLogs, getBuildIdLogs, getBuildLogs, getBuildPack, getGitHubToken, getGitLabSSHKey, getPreviews, getSecrets, getStorages, getUsage, listApplications, newApplication, saveApplication, saveApplicationSettings, saveApplicationSource, saveBuildPack, saveDeployKey, saveDestination, saveGitLabSSHKey, saveRepository, saveSecret, saveStorage, stopApplication } from './handlers';
export interface GetApplication {
Params: { id: string; }
}
export interface SaveApplication {
Params: { id: string; },
Body: any
}
export interface SaveApplicationSettings {
Params: { id: string; };
Querystring: { domain: string; };
Body: { debug: boolean; previews: boolean; dualCerts: boolean; autodeploy: boolean; branch: string; projectId: number; };
}
export interface DeleteApplication {
Params: { id: string; };
Querystring: { domain: string; };
}
export interface CheckDNS {
Params: { id: string; };
Querystring: { domain: string; };
}
export interface DeployApplication {
Params: { id: string },
Querystring: { domain: string }
Body: { pullmergeRequestId: string | null, branch: string }
}
const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
fastify.addHook('onRequest', async (request, reply) => {
return await request.jwtVerify()
})
fastify.get('/', async (request) => await listApplications(request));
fastify.post('/new', async (request, reply) => await newApplication(request, reply));
fastify.get<GetApplication>('/:id', async (request) => await getApplication(request));
fastify.post<SaveApplication>('/:id', async (request, reply) => await saveApplication(request, reply));
fastify.delete<DeleteApplication>('/:id', async (request, reply) => await deleteApplication(request, reply));
fastify.post('/:id/stop', async (request, reply) => await stopApplication(request, reply));
fastify.post<SaveApplicationSettings>('/:id/settings', async (request, reply) => await saveApplicationSettings(request, reply));
fastify.post<SaveApplicationSettings>('/:id/check', async (request) => await checkDNS(request));
fastify.get('/:id/secrets', async (request) => await getSecrets(request));
fastify.post('/:id/secrets', async (request, reply) => await saveSecret(request, reply));
fastify.delete('/:id/secrets', async (request) => await deleteSecret(request));
fastify.get('/:id/storages', async (request) => await getStorages(request));
fastify.post('/:id/storages', async (request, reply) => await saveStorage(request, reply));
fastify.delete('/:id/storages', async (request) => await deleteStorage(request));
fastify.get('/:id/previews', async (request) => await getPreviews(request));
fastify.get('/:id/logs', async (request) => await getApplicationLogs(request));
fastify.get('/:id/logs/build', async (request) => await getBuildLogs(request));
fastify.get('/:id/logs/build/:buildId', async (request) => await getBuildIdLogs(request));
fastify.get<DeployApplication>('/:id/usage', async (request) => await getUsage(request))
fastify.post<DeployApplication>('/:id/deploy', async (request) => await deployApplication(request))
fastify.post('/:id/cancel', async (request, reply) => await cancelDeployment(request, reply));
fastify.post('/:id/configuration/source', async (request, reply) => await saveApplicationSource(request, reply));
fastify.get('/:id/configuration/repository', async (request) => await checkRepository(request));
fastify.post('/:id/configuration/repository', async (request, reply) => await saveRepository(request, reply));
fastify.post('/:id/configuration/destination', async (request, reply) => await saveDestination(request, reply));
fastify.get('/:id/configuration/buildpack', async (request) => await getBuildPack(request));
fastify.post('/:id/configuration/buildpack', async (request, reply) => await saveBuildPack(request, reply));
fastify.get('/:id/configuration/sshkey', async (request) => await getGitLabSSHKey(request));
fastify.post('/:id/configuration/sshkey', async (request, reply) => await saveGitLabSSHKey(request, reply));
fastify.post('/:id/configuration/deploykey', async (request, reply) => await saveDeployKey(request, reply));
fastify.get('/:id/configuration/githubToken', async (request, reply) => await getGitHubToken(request, reply));
};
export default root;

View File

@@ -0,0 +1,471 @@
import cuid from 'cuid';
import type { FastifyRequest } from 'fastify';
import { FastifyReply } from 'fastify';
import yaml from 'js-yaml';
import fs from 'fs/promises';
import { asyncExecShell, ComposeFile, createDirectories, decrypt, encrypt, errorHandler, generateDatabaseConfiguration, generatePassword, getContainerUsage, getDatabaseImage, getDatabaseVersions, getFreePort, listSettings, makeLabelForStandaloneDatabase, prisma, startTcpProxy, startTraefikTCPProxy, stopDatabaseContainer, stopTcpHttpProxy, supportedDatabaseTypesAndVersions, uniqueName, updatePasswordInDb } from '../../../../lib/common';
import { dockerInstance, getEngine } from '../../../../lib/docker';
import { day } from '../../../../lib/dayjs';
export async function listDatabases(request: FastifyRequest) {
try {
const userId = request.user.userId;
const teamId = request.user.teamId;
let databases = []
if (teamId === '0') {
databases = await prisma.database.findMany({ include: { teams: true } });
} else {
databases = await prisma.database.findMany({
where: { teams: { some: { id: teamId } } },
include: { teams: true }
});
}
return {
databases
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function newDatabase(request: FastifyRequest, reply: FastifyReply) {
try {
const teamId = request.user.teamId;
const name = uniqueName();
const dbUser = cuid();
const dbUserPassword = encrypt(generatePassword());
const rootUser = cuid();
const rootUserPassword = encrypt(generatePassword());
const defaultDatabase = cuid();
const { id } = await prisma.database.create({
data: {
name,
defaultDatabase,
dbUser,
dbUserPassword,
rootUser,
rootUserPassword,
teams: { connect: { id: teamId } },
settings: { create: { isPublic: false } }
}
});
return reply.code(201).send({ id })
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getDatabase(request: FastifyRequest) {
try {
const { id } = request.params;
const teamId = request.user.teamId;
const database = await prisma.database.findFirst({
where: { id, teams: { some: { id: teamId === '0' ? undefined : teamId } } },
include: { destinationDocker: true, settings: true }
});
if (!database) {
throw { status: 404, message: 'Database not found.' }
}
if (database.dbUserPassword) database.dbUserPassword = decrypt(database.dbUserPassword);
if (database.rootUserPassword) database.rootUserPassword = decrypt(database.rootUserPassword);
const { destinationDockerId, destinationDocker } = database;
let isRunning = false;
if (destinationDockerId) {
const host = getEngine(destinationDocker.engine);
try {
const { stdout } = await asyncExecShell(
`DOCKER_HOST=${host} docker inspect --format '{{json .State}}' ${id}`
);
if (JSON.parse(stdout).Running) {
isRunning = true;
}
} catch (error) {
//
}
}
const configuration = generateDatabaseConfiguration(database);
const settings = await listSettings();
return {
privatePort: configuration?.privatePort,
database,
isRunning,
versions: await getDatabaseVersions(database.type),
settings
};
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getDatabaseTypes(request: FastifyRequest) {
try {
return {
types: supportedDatabaseTypesAndVersions
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveDatabaseType(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params;
const { type } = request.body;
await prisma.database.update({
where: { id },
data: { type }
});
return reply.code(201).send({})
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getVersions(request: FastifyRequest) {
try {
const teamId = request.user.teamId;
const { id } = request.params;
const { type } = await prisma.database.findFirst({
where: { id, teams: { some: { id: teamId === '0' ? undefined : teamId } } },
include: { destinationDocker: true, settings: true }
});
return {
versions: supportedDatabaseTypesAndVersions.find((name) => name.name === type).versions
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveVersion(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params;
const { version } = request.body;
await prisma.database.update({
where: { id },
data: {
version,
}
});
return reply.code(201).send({})
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveDatabaseDestination(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params;
const { destinationId } = request.body;
await prisma.database.update({
where: { id },
data: { destinationDocker: { connect: { id: destinationId } } }
});
const {
destinationDockerId,
destinationDocker: { engine },
version,
type
} = await prisma.database.findUnique({ where: { id }, include: { destinationDocker: true } });
if (destinationDockerId) {
const host = getEngine(engine);
if (type && version) {
const baseImage = getDatabaseImage(type);
asyncExecShell(`DOCKER_HOST=${host} docker pull ${baseImage}:${version}`);
}
}
return reply.code(201).send({})
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getDatabaseUsage(request: FastifyRequest) {
try {
const { id } = request.params;
const teamId = request.user.teamId;
let usage = {};
const database = await prisma.database.findFirst({
where: { id, teams: { some: { id: teamId === '0' ? undefined : teamId } } },
include: { destinationDocker: true, settings: true }
});
if (database.dbUserPassword) database.dbUserPassword = decrypt(database.dbUserPassword);
if (database.rootUserPassword) database.rootUserPassword = decrypt(database.rootUserPassword);
if (database.destinationDockerId) {
[usage] = await Promise.all([getContainerUsage(database.destinationDocker.engine, id)]);
}
return {
usage
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function startDatabase(request: FastifyRequest) {
try {
const teamId = request.user.teamId;
const { id } = request.params;
const database = await prisma.database.findFirst({
where: { id, teams: { some: { id: teamId === '0' ? undefined : teamId } } },
include: { destinationDocker: true, settings: true }
});
if (database.dbUserPassword) database.dbUserPassword = decrypt(database.dbUserPassword);
if (database.rootUserPassword) database.rootUserPassword = decrypt(database.rootUserPassword);
const {
type,
destinationDockerId,
destinationDocker,
publicPort,
settings: { isPublic }
} = database;
const { privatePort, environmentVariables, image, volume, ulimits } =
generateDatabaseConfiguration(database);
const network = destinationDockerId && destinationDocker.network;
const host = getEngine(destinationDocker.engine);
const engine = destinationDocker.engine;
const volumeName = volume.split(':')[0];
const labels = await makeLabelForStandaloneDatabase({ id, image, volume });
const { workdir } = await createDirectories({ repository: type, buildId: id });
const composeFile: ComposeFile = {
version: '3.8',
services: {
[id]: {
container_name: id,
image,
networks: [network],
environment: environmentVariables,
volumes: [volume],
ulimits,
labels,
restart: 'always',
deploy: {
restart_policy: {
condition: 'on-failure',
delay: '5s',
max_attempts: 3,
window: '120s'
}
}
}
},
networks: {
[network]: {
external: true
}
},
volumes: {
[volumeName]: {
external: true
}
}
};
const composeFileDestination = `${workdir}/docker-compose.yaml`;
await fs.writeFile(composeFileDestination, yaml.dump(composeFile));
try {
await asyncExecShell(`DOCKER_HOST=${host} docker volume create ${volumeName}`);
} catch (error) {
console.log(error);
}
try {
await asyncExecShell(`DOCKER_HOST=${host} docker compose -f ${composeFileDestination} up -d`);
if (isPublic) await startTcpProxy(destinationDocker, id, publicPort, privatePort);
return {};
} catch (error) {
throw {
error
};
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function stopDatabase(request: FastifyRequest) {
try {
const teamId = request.user.teamId;
const { id } = request.params;
const database = await prisma.database.findFirst({
where: { id, teams: { some: { id: teamId === '0' ? undefined : teamId } } },
include: { destinationDocker: true, settings: true }
});
if (database.dbUserPassword) database.dbUserPassword = decrypt(database.dbUserPassword);
if (database.rootUserPassword) database.rootUserPassword = decrypt(database.rootUserPassword);
const everStarted = await stopDatabaseContainer(database);
if (everStarted) await stopTcpHttpProxy(id, database.destinationDocker, database.publicPort);
await prisma.database.update({
where: { id },
data: {
settings: { upsert: { update: { isPublic: false }, create: { isPublic: false } } }
}
});
await prisma.database.update({ where: { id }, data: { publicPort: null } });
return {};
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getDatabaseLogs(request: FastifyRequest) {
try {
const teamId = request.user.teamId;
const { id } = request.params;
let { since = 0 } = request.query
if (since !== 0) {
since = day(since).unix();
}
const { destinationDockerId, destinationDocker } = await prisma.database.findUnique({
where: { id },
include: { destinationDocker: true }
});
if (destinationDockerId) {
const docker = dockerInstance({ destinationDocker });
try {
const container = await docker.engine.getContainer(id);
if (container) {
const { default: ansi } = await import('strip-ansi')
const logs = (
await container.logs({
stdout: true,
stderr: true,
timestamps: true,
since,
tail: 5000
})
)
.toString()
.split('\n')
.map((l) => ansi(l.slice(8)))
.filter((a) => a);
return {
logs
};
}
} catch (error) {
const { statusCode } = error;
if (statusCode === 404) {
return {
logs: []
};
}
}
}
return {
message: 'No logs found.'
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function deleteDatabase(request: FastifyRequest) {
try {
const teamId = request.user.teamId;
const { id } = request.params;
const database = await prisma.database.findFirst({
where: { id, teams: { some: { id: teamId === '0' ? undefined : teamId } } },
include: { destinationDocker: true, settings: true }
});
if (database.dbUserPassword) database.dbUserPassword = decrypt(database.dbUserPassword);
if (database.rootUserPassword) database.rootUserPassword = decrypt(database.rootUserPassword);
if (database.destinationDockerId) {
const everStarted = await stopDatabaseContainer(database);
if (everStarted) await stopTcpHttpProxy(id, database.destinationDocker, database.publicPort);
}
await prisma.databaseSettings.deleteMany({ where: { databaseId: id } });
await prisma.database.delete({ where: { id } });
return {}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveDatabase(request: FastifyRequest, reply: FastifyReply) {
try {
const teamId = request.user.teamId;
const { id } = request.params;
const {
name,
defaultDatabase,
dbUser,
dbUserPassword,
rootUser,
rootUserPassword,
version,
isRunning
} = request.body;
const database = await prisma.database.findFirst({
where: { id, teams: { some: { id: teamId === '0' ? undefined : teamId } } },
include: { destinationDocker: true, settings: true }
});
if (database.dbUserPassword) database.dbUserPassword = decrypt(database.dbUserPassword);
if (database.rootUserPassword) database.rootUserPassword = decrypt(database.rootUserPassword);
if (isRunning) {
if (database.dbUserPassword !== dbUserPassword) {
await updatePasswordInDb(database, dbUser, dbUserPassword, false);
} else if (database.rootUserPassword !== rootUserPassword) {
await updatePasswordInDb(database, rootUser, rootUserPassword, true);
}
}
const encryptedDbUserPassword = dbUserPassword && encrypt(dbUserPassword);
const encryptedRootUserPassword = rootUserPassword && encrypt(rootUserPassword);
await prisma.database.update({
where: { id },
data: {
name,
defaultDatabase,
dbUser,
dbUserPassword: encryptedDbUserPassword,
rootUser,
rootUserPassword: encryptedRootUserPassword,
version
}
});
return reply.code(201).send({})
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveDatabaseSettings(request: FastifyRequest) {
try {
const teamId = request.user.teamId;
const { id } = request.params;
const { isPublic, appendOnly = true } = request.body;
const publicPort = await getFreePort();
const settings = await listSettings();
await prisma.database.update({
where: { id },
data: {
settings: { upsert: { update: { isPublic, appendOnly }, create: { isPublic, appendOnly } } }
}
});
const database = await prisma.database.findFirst({
where: { id, teams: { some: { id: teamId === '0' ? undefined : teamId } } },
include: { destinationDocker: true, settings: true }
});
if (database.dbUserPassword) database.dbUserPassword = decrypt(database.dbUserPassword);
if (database.rootUserPassword) database.rootUserPassword = decrypt(database.rootUserPassword);
const { destinationDockerId, destinationDocker, publicPort: oldPublicPort } = database;
const { privatePort } = generateDatabaseConfiguration(database);
if (destinationDockerId) {
if (isPublic) {
await prisma.database.update({ where: { id }, data: { publicPort } });
if (settings.isTraefikUsed) {
await startTraefikTCPProxy(destinationDocker, id, publicPort, privatePort);
} else {
await startTcpProxy(destinationDocker, id, publicPort, privatePort);
}
} else {
await prisma.database.update({ where: { id }, data: { publicPort: null } });
await stopTcpHttpProxy(id, destinationDocker, oldPublicPort);
}
}
return { publicPort }
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}

View File

@@ -0,0 +1,32 @@
import { FastifyPluginAsync } from 'fastify';
import { deleteDatabase, getDatabase, getDatabaseLogs, getDatabaseTypes, getDatabaseUsage, getVersions, listDatabases, newDatabase, saveDatabase, saveDatabaseDestination, saveDatabaseSettings, saveDatabaseType, saveVersion, startDatabase, stopDatabase } from './handlers';
const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
fastify.addHook('onRequest', async (request, reply) => {
return await request.jwtVerify()
})
fastify.get('/', async (request) => await listDatabases(request));
fastify.post('/new', async (request, reply) => await newDatabase(request, reply));
fastify.get('/:id', async (request) => await getDatabase(request));
fastify.post('/:id', async (request, reply) => await saveDatabase(request, reply));
fastify.delete('/:id', async (request) => await deleteDatabase(request));
fastify.post('/:id/settings', async (request) => await saveDatabaseSettings(request));
fastify.get('/:id/configuration/type', async (request) => await getDatabaseTypes(request));
fastify.post('/:id/configuration/type', async (request, reply) => await saveDatabaseType(request, reply));
fastify.get('/:id/configuration/version', async (request) => await getVersions(request));
fastify.post('/:id/configuration/version', async (request, reply) => await saveVersion(request, reply));
fastify.post('/:id/configuration/destination', async (request, reply) => await saveDatabaseDestination(request, reply));
fastify.get('/:id/usage', async (request) => await getDatabaseUsage(request));
fastify.get('/:id/logs', async (request) => await getDatabaseLogs(request));
fastify.post('/:id/start', async (request) => await startDatabase(request));
fastify.post('/:id/stop', async (request) => await stopDatabase(request));
};
export default root;

View File

@@ -0,0 +1,200 @@
import type { FastifyRequest } from 'fastify';
import { FastifyReply } from 'fastify';
import { asyncExecShell, errorHandler, listSettings, prisma, startCoolifyProxy, startTraefikProxy, stopTraefikProxy } from '../../../../lib/common';
import { checkContainer, dockerInstance, getEngine } from '../../../../lib/docker';
export async function listDestinations(request: FastifyRequest) {
try {
const teamId = request.user.teamId;
let destinations = []
if (teamId === '0') {
destinations = await prisma.destinationDocker.findMany({ include: { teams: true } });
} else {
destinations = await prisma.destinationDocker.findMany({
where: { teams: { some: { id: teamId } } },
include: { teams: true }
});
}
return {
destinations
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function checkDestination(request: FastifyRequest) {
try {
const { network } = request.body;
const found = await prisma.destinationDocker.findFirst({ where: { network } });
if (found) {
throw {
message: `Network already exists: ${network}`
};
}
return {}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getDestination(request: FastifyRequest) {
try {
const { id } = request.params
const teamId = request.user?.teamId;
const destination = await prisma.destinationDocker.findFirst({
where: { id, teams: { some: { id: teamId === '0' ? undefined : teamId } } }
});
if (!destination) {
throw { status: 404, message: `Destination not found.` };
}
const settings = await listSettings();
let payload = {
destination,
settings,
state: false
};
if (destination?.remoteEngine) {
// const { stdout } = await asyncExecShell(
// `ssh -p ${destination.port} ${destination.user}@${destination.ipAddress} "docker ps -a"`
// );
// console.log(stdout)
// const engine = await generateRemoteEngine(destination);
// // await saveSshKey(destination);
// payload.state = await checkContainer(engine, 'coolify-haproxy');
} else {
let containerName = 'coolify-proxy';
if (!settings.isTraefikUsed) {
containerName = 'coolify-haproxy';
}
payload.state =
destination?.engine && (await checkContainer(destination.engine, containerName));
}
return {
...payload
};
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function newDestination(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params
let { name, network, engine, isCoolifyProxyUsed } = request.body
const teamId = request.user.teamId;
if (id === 'new') {
const host = getEngine(engine);
const docker = dockerInstance({ destinationDocker: { engine, network } });
const found = await docker.engine.listNetworks({ filters: { name: [`^${network}$`] } });
if (found.length === 0) {
await asyncExecShell(`DOCKER_HOST=${host} docker network create --attachable ${network}`);
}
await prisma.destinationDocker.create({
data: { name, teams: { connect: { id: teamId } }, engine, network, isCoolifyProxyUsed }
});
const destinations = await prisma.destinationDocker.findMany({ where: { engine } });
const destination = destinations.find((destination) => destination.network === network);
if (destinations.length > 0) {
const proxyConfigured = destinations.find(
(destination) => destination.network !== network && destination.isCoolifyProxyUsed === true
);
if (proxyConfigured) {
isCoolifyProxyUsed = !!proxyConfigured.isCoolifyProxyUsed;
}
await prisma.destinationDocker.updateMany({ where: { engine }, data: { isCoolifyProxyUsed } });
}
if (isCoolifyProxyUsed) {
const settings = await prisma.setting.findFirst();
if (settings?.isTraefikUsed) {
await startTraefikProxy(engine);
} else {
await startCoolifyProxy(engine);
}
}
return reply.code(201).send({ id: destination.id });
} else {
await prisma.destinationDocker.update({ where: { id }, data: { name, engine, network } });
return reply.code(201).send();
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function deleteDestination(request: FastifyRequest) {
try {
const { id } = request.params
const destination = await prisma.destinationDocker.delete({ where: { id } });
if (destination.isCoolifyProxyUsed) {
const host = getEngine(destination.engine);
const { network } = destination;
const settings = await prisma.setting.findFirst();
const containerName = settings.isTraefikUsed ? 'coolify-proxy' : 'coolify-haproxy';
const { stdout: found } = await asyncExecShell(
`DOCKER_HOST=${host} docker ps -a --filter network=${network} --filter name=${containerName} --format '{{.}}'`
);
if (found) {
await asyncExecShell(
`DOCKER_HOST="${host}" docker network disconnect ${network} ${containerName}`
);
await asyncExecShell(`DOCKER_HOST="${host}" docker network rm ${network}`);
}
}
return {}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveDestinationSettings(request: FastifyRequest, reply: FastifyReply) {
try {
const { engine, isCoolifyProxyUsed } = request.body;
await prisma.destinationDocker.updateMany({
where: { engine },
data: { isCoolifyProxyUsed }
});
return {
status: 202
}
// return reply.code(201).send();
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function startProxy(request: FastifyRequest, reply: FastifyReply) {
const { engine } = request.body;
try {
await startTraefikProxy(engine);
return {}
} catch ({ status, message }) {
await stopTraefikProxy(engine);
return errorHandler({ status, message })
}
}
export async function stopProxy(request: FastifyRequest, reply: FastifyReply) {
const settings = await prisma.setting.findFirst({});
const { engine } = request.body;
try {
await stopTraefikProxy(engine);
return {}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function restartProxy(request: FastifyRequest, reply: FastifyReply) {
const settings = await prisma.setting.findFirst({});
const { engine } = request.body;
try {
await stopTraefikProxy(engine);
await startTraefikProxy(engine);
await prisma.destinationDocker.updateMany({
where: { engine },
data: { isCoolifyProxyUsed: true }
});
return {}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}

View File

@@ -0,0 +1,24 @@
import { FastifyPluginAsync } from 'fastify';
import { checkDestination, deleteDestination, getDestination, listDestinations, newDestination, restartProxy, saveDestinationSettings, startProxy, stopProxy } from './handlers';
const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
fastify.addHook('onRequest', async (request, reply) => {
return await request.jwtVerify()
})
fastify.get('/', async (request) => await listDestinations(request));
fastify.post('/check', async (request) => await checkDestination(request));
fastify.get('/:id', async (request) => await getDestination(request));
fastify.post('/:id', async (request, reply) => await newDestination(request, reply));
fastify.delete('/:id', async (request) => await deleteDestination(request));
fastify.post('/:id/settings', async (request, reply) => await saveDestinationSettings(request, reply));
fastify.post('/:id/start', async (request, reply) => await startProxy(request, reply));
fastify.post('/:id/stop', async (request, reply) => await stopProxy(request, reply));
fastify.post('/:id/restart', async (request, reply) => await restartProxy(request, reply));
};
export default root;

View File

@@ -0,0 +1,280 @@
import os from 'node:os';
import osu from 'node-os-utils';
import axios from 'axios';
import compare from 'compare-versions';
import cuid from 'cuid';
import bcrypt from 'bcryptjs';
import { asyncExecShell, asyncSleep, errorHandler, isDev, prisma, uniqueName, version } from '../../../lib/common';
import type { FastifyReply, FastifyRequest } from 'fastify';
import type { Login, Update } from '.';
export async function hashPassword(password: string): Promise<string> {
const saltRounds = 15;
return bcrypt.hash(password, saltRounds);
}
export async function checkUpdate(request: FastifyRequest) {
try {
const currentVersion = version;
const { data: versions } = await axios.get(
`https://get.coollabs.io/versions.json?appId=${process.env['COOLIFY_APP_ID']}&version=${currentVersion}`
);
const latestVersion =
request.hostname === 'staging.coolify.io'
? versions['coolify'].next.version
: versions['coolify'].main.version;
const isUpdateAvailable = compare(latestVersion, currentVersion);
return {
isUpdateAvailable: isUpdateAvailable === 1,
latestVersion
};
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function update(request: FastifyRequest<Update>) {
const { latestVersion } = request.body;
try {
if (!isDev) {
const { isAutoUpdateEnabled } = (await prisma.setting.findFirst()) || {
isAutoUpdateEnabled: false
};
await asyncExecShell(`docker pull coollabsio/coolify:${latestVersion}`);
await asyncExecShell(`env | grep COOLIFY > .env`);
await asyncExecShell(
`sed -i '/COOLIFY_AUTO_UPDATE=/cCOOLIFY_AUTO_UPDATE=${isAutoUpdateEnabled}' .env`
);
await asyncExecShell(
`docker run --rm -tid --env-file .env -v /var/run/docker.sock:/var/run/docker.sock -v coolify-db coollabsio/coolify:${latestVersion} /bin/sh -c "env | grep COOLIFY > .env && echo 'TAG=${latestVersion}' >> .env && docker stop -t 0 coolify && docker rm coolify && docker compose up -d --force-recreate"`
);
return {};
} else {
console.log(latestVersion);
await asyncSleep(2000);
return {};
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function showUsage() {
try {
return {
usage: {
uptime: os.uptime(),
memory: await osu.mem.info(),
cpu: {
load: os.loadavg(),
usage: await osu.cpu.usage(),
count: os.cpus().length
},
disk: await osu.drive.info('/')
}
};
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function showDashboard(request: FastifyRequest) {
try {
const userId = request.user.userId;
const teamId = request.user.teamId;
const applicationsCount = await prisma.application.count({
where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } }
});
const sourcesCount = await prisma.gitSource.count({
where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } }
});
const destinationsCount = await prisma.destinationDocker.count({
where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } }
});
const teamsCount = await prisma.permission.count({ where: { userId } });
const databasesCount = await prisma.database.count({
where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } }
});
const servicesCount = await prisma.service.count({
where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } }
});
const teams = await prisma.permission.findMany({
where: { userId },
include: { team: { include: { _count: { select: { users: true } } } } }
});
return {
teams,
applicationsCount,
sourcesCount,
destinationsCount,
teamsCount,
databasesCount,
servicesCount,
};
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function login(request: FastifyRequest<Login>, reply: FastifyReply) {
if (request.user) {
return reply.redirect('/dashboard');
} else {
const { email, password, isLogin } = request.body || {};
if (!email || !password) {
throw { status: 500, message: 'Email and password are required.' };
}
const users = await prisma.user.count();
const userFound = await prisma.user.findUnique({
where: { email },
include: { teams: true, permission: true },
rejectOnNotFound: false
});
if (!userFound && isLogin) {
throw { status: 500, message: 'User not found.' };
}
const { isRegistrationEnabled, id } = await prisma.setting.findFirst()
let uid = cuid();
let permission = 'read';
let isAdmin = false;
if (users === 0) {
await prisma.setting.update({ where: { id }, data: { isRegistrationEnabled: false } });
uid = '0';
}
if (userFound) {
if (userFound.type === 'email') {
// TODO: Review this one
if (userFound.password === 'RESETME') {
const hashedPassword = await hashPassword(password);
if (userFound.updatedAt < new Date(Date.now() - 1000 * 60 * 10)) {
await prisma.user.update({
where: { email: userFound.email },
data: { password: 'RESETTIMEOUT' }
});
throw {
status: 500,
message: 'Password reset link has expired. Please request a new one.'
};
} else {
await prisma.user.update({
where: { email: userFound.email },
data: { password: hashedPassword }
});
return {
userId: userFound.id,
teamId: userFound.id,
permission: userFound.permission,
isAdmin: true
};
}
}
const passwordMatch = await bcrypt.compare(password, userFound.password);
if (!passwordMatch) {
throw {
status: 500,
message: 'Wrong password or email address.'
};
}
uid = userFound.id;
isAdmin = true;
}
} else {
permission = 'owner';
isAdmin = true;
if (!isRegistrationEnabled) {
throw {
status: 404,
message: 'Registration disabled by administrator.'
};
}
const hashedPassword = await hashPassword(password);
if (users === 0) {
await prisma.user.create({
data: {
id: uid,
email,
password: hashedPassword,
type: 'email',
teams: {
create: {
id: uid,
name: uniqueName(),
destinationDocker: { connect: { network: 'coolify' } }
}
},
permission: { create: { teamId: uid, permission: 'owner' } }
},
include: { teams: true }
});
} else {
await prisma.user.create({
data: {
id: uid,
email,
password: hashedPassword,
type: 'email',
teams: {
create: {
id: uid,
name: uniqueName()
}
},
permission: { create: { teamId: uid, permission: 'owner' } }
},
include: { teams: true }
});
}
}
return {
userId: uid,
teamId: uid,
permission,
isAdmin
};
}
}
export async function getCurrentUser(request: FastifyRequest, fastify) {
let token = null
try {
const user = await prisma.user.findUnique({
where: { id: request.user.userId }
})
if (!user) {
throw "User not found";
}
} catch (error) {
throw { status: 401, message: error };
}
if (request.query.teamId) {
try {
const user = await prisma.user.findFirst({
where: { id: request.user.userId, teams: { some: { id: request.query.teamId } } },
include: { teams: true, permission: true }
})
if (user) {
const payload = {
...request.user,
teamId: request.query.teamId,
permission: user.permission.find(p => p.teamId === request.query.teamId).permission || null,
isAdmin: user.permission.find(p => p.teamId === request.query.teamId).permission === 'owner'
}
token = fastify.jwt.sign(payload)
}
} catch (error) {
// No new token -> not switching teams
}
}
return {
settings: await prisma.setting.findFirst(),
token,
...request.user
}
}

View File

@@ -0,0 +1,453 @@
import cuid from 'cuid';
import type { FastifyRequest } from 'fastify';
import { FastifyReply } from 'fastify';
import { decrypt, errorHandler, prisma, uniqueName } from '../../../../lib/common';
import { day } from '../../../../lib/dayjs';
export async function listTeams(request: FastifyRequest) {
try {
const userId = request.user.userId;
const teamId = request.user.teamId;
const account = await prisma.user.findUnique({
where: { id: userId },
select: { id: true, email: true, teams: true }
});
let accounts = [];
let allTeams = [];
if (teamId === '0') {
accounts = await prisma.user.findMany({ select: { id: true, email: true, teams: true } });
allTeams = await prisma.team.findMany({
where: { users: { none: { id: userId } } },
include: { permissions: true }
});
}
const ownTeams = await prisma.team.findMany({
where: { users: { some: { id: userId } } },
include: { permissions: true }
});
const invitations = await prisma.teamInvitation.findMany({ where: { uid: userId } });
return {
ownTeams,
allTeams,
invitations,
account,
accounts
};
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function deleteTeam(request: FastifyRequest, reply: FastifyReply) {
try {
const userId = request.user.userId;
const { id } = request.params;
const aloneInTeams = await prisma.team.findMany({ where: { users: { every: { id: userId } }, id } });
if (aloneInTeams.length > 0) {
for (const team of aloneInTeams) {
const applications = await prisma.application.findMany({
where: { teams: { every: { id: team.id } } }
});
if (applications.length > 0) {
for (const application of applications) {
await prisma.application.update({
where: { id: application.id },
data: { teams: { connect: { id: '0' } } }
});
}
}
const services = await prisma.service.findMany({
where: { teams: { every: { id: team.id } } }
});
if (services.length > 0) {
for (const service of services) {
await prisma.service.update({
where: { id: service.id },
data: { teams: { connect: { id: '0' } } }
});
}
}
const databases = await prisma.database.findMany({
where: { teams: { every: { id: team.id } } }
});
if (databases.length > 0) {
for (const database of databases) {
await prisma.database.update({
where: { id: database.id },
data: { teams: { connect: { id: '0' } } }
});
}
}
const sources = await prisma.gitSource.findMany({
where: { teams: { every: { id: team.id } } }
});
if (sources.length > 0) {
for (const source of sources) {
await prisma.gitSource.update({
where: { id: source.id },
data: { teams: { connect: { id: '0' } } }
});
}
}
const destinations = await prisma.destinationDocker.findMany({
where: { teams: { every: { id: team.id } } }
});
if (destinations.length > 0) {
for (const destination of destinations) {
await prisma.destinationDocker.update({
where: { id: destination.id },
data: { teams: { connect: { id: '0' } } }
});
}
}
await prisma.teamInvitation.deleteMany({ where: { teamId: team.id } });
await prisma.permission.deleteMany({ where: { teamId: team.id } });
// await prisma.user.delete({ where: { id } });
await prisma.team.delete({ where: { id: team.id } });
}
}
const notAloneInTeams = await prisma.team.findMany({ where: { users: { some: { id: userId } } } });
if (notAloneInTeams.length > 0) {
for (const team of notAloneInTeams) {
await prisma.team.update({
where: { id: team.id },
data: { users: { disconnect: { id } } }
});
}
}
return reply.code(201).send()
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function newTeam(request: FastifyRequest, reply: FastifyReply) {
try {
const userId = request.user?.userId;
const name = uniqueName();
const { id } = await prisma.team.create({
data: {
name,
permissions: { create: { user: { connect: { id: userId } }, permission: 'owner' } },
users: { connect: { id: userId } }
}
});
return reply.code(201).send({ id })
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getTeam(request: FastifyRequest, reply: FastifyReply) {
try {
const userId = request.user.userId;
const teamId = request.user.teamId;
const { id } = request.params;
const user = await prisma.user.findFirst({
where: { id: userId, teams: teamId === '0' ? undefined : { some: { id } } },
include: { permission: true }
});
if (!user) return reply.code(401).send()
const permissions = await prisma.permission.findMany({
where: { teamId: id },
include: { user: { select: { id: true, email: true } } }
});
const team = await prisma.team.findUnique({ where: { id }, include: { permissions: true } });
const invitations = await prisma.teamInvitation.findMany({ where: { teamId: team.id } });
return {
team,
permissions,
invitations
};
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveTeam(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params;
const { name } = request.body;
await prisma.team.update({ where: { id }, data: { name: { set: name } } });
return reply.code(201).send()
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
// export async function deleteUser(request: FastifyRequest, reply: FastifyReply) {
// try {
// const userId = request.user.userId;
// const { id } = request.params;
// const aloneInTeams = await prisma.team.findMany({ where: { users: { every: { id: userId } }, id } });
// if (aloneInTeams.length > 0) {
// for (const team of aloneInTeams) {
// const applications = await prisma.application.findMany({
// where: { teams: { every: { id: team.id } } }
// });
// if (applications.length > 0) {
// for (const application of applications) {
// await prisma.application.update({
// where: { id: application.id },
// data: { teams: { connect: { id: '0' } } }
// });
// }
// }
// const services = await prisma.service.findMany({
// where: { teams: { every: { id: team.id } } }
// });
// if (services.length > 0) {
// for (const service of services) {
// await prisma.service.update({
// where: { id: service.id },
// data: { teams: { connect: { id: '0' } } }
// });
// }
// }
// const databases = await prisma.database.findMany({
// where: { teams: { every: { id: team.id } } }
// });
// if (databases.length > 0) {
// for (const database of databases) {
// await prisma.database.update({
// where: { id: database.id },
// data: { teams: { connect: { id: '0' } } }
// });
// }
// }
// const sources = await prisma.gitSource.findMany({
// where: { teams: { every: { id: team.id } } }
// });
// if (sources.length > 0) {
// for (const source of sources) {
// await prisma.gitSource.update({
// where: { id: source.id },
// data: { teams: { connect: { id: '0' } } }
// });
// }
// }
// const destinations = await prisma.destinationDocker.findMany({
// where: { teams: { every: { id: team.id } } }
// });
// if (destinations.length > 0) {
// for (const destination of destinations) {
// await prisma.destinationDocker.update({
// where: { id: destination.id },
// data: { teams: { connect: { id: '0' } } }
// });
// }
// }
// await prisma.teamInvitation.deleteMany({ where: { teamId: team.id } });
// await prisma.permission.deleteMany({ where: { teamId: team.id } });
// await prisma.user.delete({ where: { id: userId } });
// await prisma.team.delete({ where: { id: team.id } });
// }
// }
// const notAloneInTeams = await prisma.team.findMany({ where: { users: { some: { id: userId } } } });
// if (notAloneInTeams.length > 0) {
// for (const team of notAloneInTeams) {
// await prisma.team.update({
// where: { id: team.id },
// data: { users: { disconnect: { id } } }
// });
// }
// }
// return reply.code(201).send()
// } catch (error) {
// console.log(error)
// throw { status: 500, message: error }
// }
// }
export async function inviteToTeam(request: FastifyRequest, reply: FastifyReply) {
try {
const userId = request.user.userId;
const { email, permission, teamId, teamName } = request.body;
const userFound = await prisma.user.findUnique({ where: { email } });
if (!userFound) {
throw `No user found with '${email}' email address.`
}
const uid = userFound.id;
if (uid === userId) {
throw `Invitation to yourself? Whaaaaat?`
}
const alreadyInTeam = await prisma.team.findFirst({
where: { id: teamId, users: { some: { id: uid } } }
});
if (alreadyInTeam) {
throw {
message: `Already in the team.`
};
}
const invitationFound = await prisma.teamInvitation.findFirst({ where: { uid, teamId } });
if (invitationFound) {
if (day().toDate() < day(invitationFound.createdAt).add(1, 'day').toDate()) {
throw 'Invitiation already pending on user confirmation.'
} else {
await prisma.teamInvitation.delete({ where: { id: invitationFound.id } });
await prisma.teamInvitation.create({
data: { email, uid, teamId, teamName, permission }
});
return reply.code(201).send({ message: 'Invitiation sent.' })
}
} else {
await prisma.teamInvitation.create({
data: { email, uid, teamId, teamName, permission }
});
return reply.code(201).send({ message: 'Invitiation sent.' })
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function acceptInvitation(request: FastifyRequest) {
try {
const userId = request.user.userId;
const { id } = request.body;
const invitation = await prisma.teamInvitation.findFirst({
where: { uid: userId },
rejectOnNotFound: true
});
await prisma.team.update({
where: { id: invitation.teamId },
data: { users: { connect: { id: userId } } }
});
await prisma.permission.create({
data: {
user: { connect: { id: userId } },
permission: invitation.permission,
team: { connect: { id: invitation.teamId } }
}
});
await prisma.teamInvitation.delete({ where: { id } });
return {}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function revokeInvitation(request: FastifyRequest) {
try {
const { id } = request.body
await prisma.teamInvitation.delete({ where: { id } });
return {}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function removeUser(request: FastifyRequest, reply: FastifyReply) {
try {
const { uid } = request.body;
const user = await prisma.user.findUnique({ where: { id: uid }, include: { teams: true, permission: true } });
if (user) {
const permissions = user.permission;
if (permissions.length > 0) {
for (const permission of permissions) {
await prisma.permission.deleteMany({ where: { id: permission.id, userId: uid } });
}
}
const teams = user.teams;
if (teams.length > 0) {
for (const team of teams) {
const newTeam = await prisma.team.update({
where: { id: team.id },
data: { users: { disconnect: { id: uid } } },
include: { applications: true, database: true, gitHubApps: true, gitLabApps: true, gitSources: true, destinationDocker: true, service: true, users: true }
});
if (newTeam.users.length === 0) {
if (newTeam.applications.length > 0) {
for (const application of newTeam.applications) {
await prisma.application.update({
where: { id: application.id },
data: { teams: { disconnect: { id: team.id }, connect: { id: '0' } } }
});
}
}
if (newTeam.database.length > 0) {
for (const database of newTeam.database) {
await prisma.database.update({
where: { id: database.id },
data: { teams: { disconnect: { id: team.id }, connect: { id: '0' } } }
});
}
}
if (newTeam.service.length > 0) {
for (const service of newTeam.service) {
await prisma.service.update({
where: { id: service.id },
data: { teams: { disconnect: { id: team.id }, connect: { id: '0' } } }
});
}
}
if (newTeam.gitHubApps.length > 0) {
for (const gitHubApp of newTeam.gitHubApps) {
await prisma.githubApp.update({
where: { id: gitHubApp.id },
data: { teams: { disconnect: { id: team.id }, connect: { id: '0' } } }
});
}
}
if (newTeam.gitLabApps.length > 0) {
for (const gitLabApp of newTeam.gitLabApps) {
await prisma.gitlabApp.update({
where: { id: gitLabApp.id },
data: { teams: { disconnect: { id: team.id }, connect: { id: '0' } } }
});
}
}
if (newTeam.gitSources.length > 0) {
for (const gitSource of newTeam.gitSources) {
await prisma.gitSource.update({
where: { id: gitSource.id },
data: { teams: { disconnect: { id: team.id }, connect: { id: '0' } } }
});
}
}
if (newTeam.destinationDocker.length > 0) {
for (const destinationDocker of newTeam.destinationDocker) {
await prisma.destinationDocker.update({
where: { id: destinationDocker.id },
data: { teams: { disconnect: { id: team.id }, connect: { id: '0' } } }
});
}
}
await prisma.team.delete({ where: { id: team.id } });
}
}
}
}
await prisma.user.delete({ where: { id: uid } });
return reply.code(201).send()
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function setPermission(request: FastifyRequest, reply: FastifyReply) {
try {
const { userId, newPermission, permissionId } = request.body;
await prisma.permission.updateMany({
where: { id: permissionId, userId },
data: { permission: { set: newPermission } }
});
return reply.code(201).send()
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function changePassword(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.body;
await prisma.user.update({ where: { id: undefined }, data: { password: 'RESETME' } });
return reply.code(201).send()
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}

View File

@@ -0,0 +1,29 @@
import { FastifyPluginAsync } from 'fastify';
import { acceptInvitation, changePassword, deleteTeam, getTeam, inviteToTeam, listTeams, newTeam, removeUser, revokeInvitation, saveTeam, setPermission } from './handlers';
const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
fastify.addHook('onRequest', async (request, reply) => {
return await request.jwtVerify()
})
fastify.get('/', async (request) => await listTeams(request));
fastify.post('/new', async (request, reply) => await newTeam(request, reply));
fastify.get('/team/:id', async (request, reply) => await getTeam(request, reply));
fastify.post('/team/:id', async (request, reply) => await saveTeam(request, reply));
fastify.delete('/team/:id', async (request, reply) => await deleteTeam(request, reply));
fastify.post('/team/:id/invitation/invite', async (request, reply) => await inviteToTeam(request, reply))
fastify.post('/team/:id/invitation/accept', async (request) => await acceptInvitation(request));
fastify.post('/team/:id/invitation/revoke', async (request) => await revokeInvitation(request));
fastify.post('/team/:id/permission', async (request, reply) => await setPermission(request, reply));
fastify.delete('/user/remove', async (request, reply) => await removeUser(request, reply));
fastify.post('/user/password', async (request, reply) => await changePassword(request, reply));
// fastify.delete('/user', async (request, reply) => await deleteUser(request, reply));
};
export default root;

View File

@@ -0,0 +1,51 @@
import { FastifyPluginAsync } from 'fastify';
import { scheduler } from '../../../lib/scheduler';
import { checkUpdate, login, showDashboard, update, showUsage, getCurrentUser } from './handlers';
export interface Update {
Body: { latestVersion: string }
}
export interface Login {
Body: { email: string, password: string, isLogin: boolean }
}
const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
fastify.get('/', async function (_request, reply) {
return reply.redirect(302, '/');
});
fastify.post<Login>('/login', async (request, reply) => {
const payload = await login(request, reply)
const token = fastify.jwt.sign(payload)
return { token, payload }
});
fastify.get('/user', {
onRequest: [fastify.authenticate]
}, async (request) => await getCurrentUser(request, fastify));
fastify.get('/undead', {
onRequest: [fastify.authenticate]
}, async function () {
return { message: 'nope' };
});
fastify.get('/update', {
onRequest: [fastify.authenticate]
}, async (request) => await checkUpdate(request));
fastify.post<Update>(
'/update', {
onRequest: [fastify.authenticate]
},
async (request) => await update(request)
);
fastify.get('/resources', {
onRequest: [fastify.authenticate]
}, async (request) => await showDashboard(request));
fastify.get('/usage', {
onRequest: [fastify.authenticate]
}, async () => await showUsage());
};
export default root;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,70 @@
import { FastifyPluginAsync } from 'fastify';
import {
activatePlausibleUsers,
checkService,
deleteService,
deleteServiceSecret,
deleteServiceStorage,
getService,
getServiceLogs,
getServiceSecrets,
getServiceStorages,
getServiceType,
getServiceUsage,
getServiceVersions,
listServices,
newService,
saveService,
saveServiceDestination,
saveServiceSecret,
saveServiceSettings,
saveServiceStorage,
saveServiceType,
saveServiceVersion,
setSettingsService,
startService,
stopService
} from './handlers';
const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
fastify.addHook('onRequest', async (request, reply) => {
return await request.jwtVerify()
})
fastify.get('/', async (request) => await listServices(request));
fastify.post('/new', async (request, reply) => await newService(request, reply));
fastify.get('/:id', async (request) => await getService(request));
fastify.post('/:id', async (request, reply) => await saveService(request, reply));
fastify.delete('/:id', async (request) => await deleteService(request));
fastify.post('/:id/check', async (request) => await checkService(request));
fastify.post('/:id/settings', async (request, reply) => await saveServiceSettings(request, reply));
fastify.get('/:id/secrets', async (request) => await getServiceSecrets(request));
fastify.post('/:id/secrets', async (request, reply) => await saveServiceSecret(request, reply));
fastify.delete('/:id/secrets', async (request) => await deleteServiceSecret(request));
fastify.get('/:id/storages', async (request) => await getServiceStorages(request));
fastify.post('/:id/storages', async (request, reply) => await saveServiceStorage(request, reply));
fastify.delete('/:id/storages', async (request) => await deleteServiceStorage(request));
fastify.get('/:id/configuration/type', async (request) => await getServiceType(request));
fastify.post('/:id/configuration/type', async (request, reply) => await saveServiceType(request, reply));
fastify.get('/:id/configuration/version', async (request) => await getServiceVersions(request));
fastify.post('/:id/configuration/version', async (request, reply) => await saveServiceVersion(request, reply));
fastify.post('/:id/configuration/destination', async (request, reply) => await saveServiceDestination(request, reply));
fastify.get('/:id/usage', async (request) => await getServiceUsage(request));
fastify.get('/:id/logs', async (request) => await getServiceLogs(request));
fastify.post('/:id/:type/start', async (request) => await startService(request));
fastify.post('/:id/:type/stop', async (request) => await stopService(request));
fastify.post('/:id/:type/settings', async (request, reply) => await setSettingsService(request, reply));
fastify.post('/:id/plausibleanalytics/activate', async (request, reply) => await activatePlausibleUsers(request, reply));
};
export default root;

View File

@@ -0,0 +1,85 @@
import { promises as dns } from 'dns';
import type { FastifyReply, FastifyRequest } from 'fastify';
import { checkDomainsIsValidInDNS, errorHandler, getDomain, isDNSValid, isDomainConfigured, listSettings, prisma } from '../../../../lib/common';
export async function listAllSettings(request: FastifyRequest) {
try {
const settings = await listSettings();
return {
settings
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveSettings(request: FastifyRequest, reply: FastifyReply) {
try {
const {
fqdn,
isRegistrationEnabled,
dualCerts,
minPort,
maxPort,
isAutoUpdateEnabled,
isDNSCheckEnabled
} = request.body
const { id } = await listSettings();
await prisma.setting.update({
where: { id },
data: { isRegistrationEnabled, dualCerts, isAutoUpdateEnabled, isDNSCheckEnabled }
});
if (fqdn) {
await prisma.setting.update({ where: { id }, data: { fqdn } });
}
if (minPort && maxPort) {
await prisma.setting.update({ where: { id }, data: { minPort, maxPort } });
}
return reply.code(201).send()
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function deleteDomain(request: FastifyRequest, reply: FastifyReply) {
try {
const { fqdn } = request.body
let ip;
try {
ip = await dns.resolve(fqdn);
} catch (error) {
// Do not care.
}
await prisma.setting.update({ where: { fqdn }, data: { fqdn: null } });
return reply.redirect(302, ip ? `http://${ip[0]}:3000/settings` : undefined)
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function checkDomain(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params;
let { fqdn, forceSave, dualCerts, isDNSCheckEnabled } = request.body
if (fqdn) fqdn = fqdn.toLowerCase();
const found = await isDomainConfigured({ id, fqdn });
if (found) {
throw "Domain already configured";
}
if (isDNSCheckEnabled && !forceSave) {
return await checkDomainsIsValidInDNS({ hostname: request.hostname, fqdn, dualCerts });
}
return {};
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function checkDNS(request: FastifyRequest, reply: FastifyReply) {
try {
const { id, domain } = request.params;
await isDNSValid(request.hostname, domain);
return {}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}

View File

@@ -0,0 +1,17 @@
import { FastifyPluginAsync } from 'fastify';
import { checkDNS, checkDomain, deleteDomain, listAllSettings, saveSettings } from './handlers';
const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
fastify.addHook('onRequest', async (request, reply) => {
return await request.jwtVerify()
})
fastify.get('/', async (request) => await listAllSettings(request));
fastify.post('/', async (request, reply) => await saveSettings(request, reply));
fastify.delete('/', async (request, reply) => await deleteDomain(request, reply));
fastify.get('/check', async (request, reply) => await checkDNS(request, reply));
fastify.post('/check', async (request, reply) => await checkDomain(request, reply));
};
export default root;

View File

@@ -0,0 +1,182 @@
import cuid from 'cuid';
import type { FastifyRequest } from 'fastify';
import { FastifyReply } from 'fastify';
import { decrypt, encrypt, errorHandler, prisma } from '../../../../lib/common';
export async function listSources(request: FastifyRequest) {
try {
const teamId = request.user?.teamId;
const sources = await prisma.gitSource.findMany({
where: { teams: { some: { id: teamId === '0' ? undefined : teamId } } },
include: { teams: true, githubApp: true, gitlabApp: true }
});
return {
sources
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveSource(request, reply) {
try {
const { id } = request.params
const { name, htmlUrl, apiUrl } = request.body
await prisma.gitSource.update({
where: { id },
data: { name, htmlUrl, apiUrl }
});
return reply.code(201).send()
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function getSource(request: FastifyRequest) {
try {
const { id } = request.params
const { teamId } = request.user
const settings = await prisma.setting.findFirst({});
if (settings.proxyPassword) settings.proxyPassword = decrypt(settings.proxyPassword);
if (id === 'new') {
return {
source: {
name: null,
type: null,
htmlUrl: null,
apiUrl: null,
organization: null
},
settings
}
}
const source = await prisma.gitSource.findFirst({
where: { id, teams: { some: { id: teamId === '0' ? undefined : teamId } } },
include: { githubApp: true, gitlabApp: true }
});
if (!source) {
throw { status: 404, message: 'Source not found.' }
}
if (source?.githubApp?.clientSecret)
source.githubApp.clientSecret = decrypt(source.githubApp.clientSecret);
if (source?.githubApp?.webhookSecret)
source.githubApp.webhookSecret = decrypt(source.githubApp.webhookSecret);
if (source?.githubApp?.privateKey) source.githubApp.privateKey = decrypt(source.githubApp.privateKey);
if (source?.gitlabApp?.appSecret) source.gitlabApp.appSecret = decrypt(source.gitlabApp.appSecret);
return {
source,
settings
};
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function deleteSource(request) {
try {
const { id } = request.params
const source = await prisma.gitSource.delete({
where: { id },
include: { githubApp: true, gitlabApp: true }
});
if (source.githubAppId) {
await prisma.githubApp.delete({ where: { id: source.githubAppId } });
}
if (source.gitlabAppId) {
await prisma.gitlabApp.delete({ where: { id: source.gitlabAppId } });
}
return {}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveGitHubSource(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params
const { name, type, htmlUrl, apiUrl, organization } = request.body
const { teamId } = request.user
if (id === 'new') {
const newId = cuid()
await prisma.gitSource.create({
data: {
id: newId,
name,
htmlUrl,
apiUrl,
organization,
type: 'github',
teams: { connect: { id: teamId } }
}
});
return {
id: newId
}
}
throw { status: 500, message: 'Wrong request.' }
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function saveGitLabSource(request: FastifyRequest, reply: FastifyReply) {
try {
const { id } = request.params
const { teamId } = request.user
let { type, name, htmlUrl, apiUrl, oauthId, appId, appSecret, groupName } =
request.body
oauthId = Number(oauthId);
const encryptedAppSecret = encrypt(appSecret);
if (id === 'new') {
const newId = cuid()
await prisma.gitSource.create({ data: { id: newId, type, apiUrl, htmlUrl, name, teams: { connect: { id: teamId } } } });
await prisma.gitlabApp.create({
data: {
teams: { connect: { id: teamId } },
appId,
oauthId,
groupName,
appSecret: encryptedAppSecret,
gitSource: { connect: { id: newId } }
}
});
return {
status: 201,
id: newId
}
} else {
await prisma.gitSource.update({ where: { id }, data: { type, apiUrl, htmlUrl, name } });
await prisma.gitlabApp.update({
where: { id },
data: {
appId,
oauthId,
groupName,
appSecret: encryptedAppSecret,
}
});
}
return { status: 201 };
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function checkGitLabOAuthID(request: FastifyRequest) {
try {
const { oauthId } = request.body
const found = await prisma.gitlabApp.findFirst({ where: { oauthId: Number(oauthId) } });
if (found) {
throw { status: 500, message: 'OAuthID already configured in Coolify.' }
}
return {}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}

View File

@@ -0,0 +1,21 @@
import { FastifyPluginAsync } from 'fastify';
import { checkGitLabOAuthID, deleteSource, getSource, listSources, saveGitHubSource, saveGitLabSource, saveSource } from './handlers';
const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
fastify.addHook('onRequest', async (request, reply) => {
return await request.jwtVerify()
})
fastify.get('/', async (request) => await listSources(request));
fastify.get('/:id', async (request) => await getSource(request));
fastify.post('/:id', async (request, reply) => await saveSource(request, reply));
fastify.delete('/:id', async (request) => await deleteSource(request));
fastify.post('/:id/check', async (request) => await checkGitLabOAuthID(request));
fastify.post('/:id/github', async (request, reply) => await saveGitHubSource(request, reply));
fastify.post('/:id/gitlab', async (request, reply) => await saveGitLabSource(request, reply));
};
export default root;

View File

@@ -0,0 +1,222 @@
import axios from "axios";
import cuid from "cuid";
import crypto from "crypto";
import type { FastifyReply, FastifyRequest } from "fastify";
import { encrypt, errorHandler, isDev, prisma } from "../../../lib/common";
import { checkContainer, removeContainer } from "../../../lib/docker";
import { scheduler } from "../../../lib/scheduler";
import { getApplicationFromDB, getApplicationFromDBWebhook } from "../../api/v1/applications/handlers";
export async function installGithub(request: FastifyRequest, reply: FastifyReply): Promise<any> {
try {
const { gitSourceId, installation_id } = request.query;
const source = await prisma.gitSource.findUnique({
where: { id: gitSourceId },
include: { githubApp: true }
});
await prisma.githubApp.update({
where: { id: source.githubAppId },
data: { installationId: Number(installation_id) }
});
if (isDev) {
return reply.redirect(`http://localhost:3000/sources/${gitSourceId}`)
} else {
return reply.redirect(`/sources/${gitSourceId}`)
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function configureGitHubApp(request, reply) {
try {
const { code, state } = request.query;
const { apiUrl } = await prisma.gitSource.findFirst({
where: { id: state },
include: { githubApp: true, gitlabApp: true }
});
const { data }: any = await axios.post(`${apiUrl}/app-manifests/${code}/conversions`);
const { id, client_id, slug, client_secret, pem, webhook_secret } = data
const encryptedClientSecret = encrypt(client_secret);
const encryptedWebhookSecret = encrypt(webhook_secret);
const encryptedPem = encrypt(pem);
await prisma.githubApp.create({
data: {
appId: id,
name: slug,
clientId: client_id,
clientSecret: encryptedClientSecret,
webhookSecret: encryptedWebhookSecret,
privateKey: encryptedPem,
gitSource: { connect: { id: state } }
}
});
if (isDev) {
return reply.redirect(`http://localhost:3000/sources/${state}`)
} else {
return reply.redirect(`/sources/${state}`)
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function gitHubEvents(request: FastifyRequest, reply: FastifyReply): Promise<any> {
try {
const buildId = cuid();
const allowedGithubEvents = ['push', 'pull_request'];
const allowedActions = ['opened', 'reopened', 'synchronize', 'closed'];
const githubEvent = request.headers['x-github-event']?.toString().toLowerCase();
const githubSignature = request.headers['x-hub-signature-256']?.toString().toLowerCase();
if (!allowedGithubEvents.includes(githubEvent)) {
throw { status: 500, message: 'Event not allowed.' }
}
let repository, projectId, branch;
const body = request.body
if (githubEvent === 'push') {
repository = body.repository;
projectId = repository.id;
branch = body.ref.split('/')[2];
} else if (githubEvent === 'pull_request') {
repository = body.pull_request.head.repo;
projectId = repository.id;
branch = body.pull_request.head.ref.split('/')[2];
}
const applicationFound = await getApplicationFromDBWebhook(projectId, branch);
if (applicationFound) {
const webhookSecret = applicationFound.gitSource.githubApp.webhookSecret || null;
//@ts-ignore
const hmac = crypto.createHmac('sha256', webhookSecret);
const digest = Buffer.from(
'sha256=' + hmac.update(JSON.stringify(body)).digest('hex'),
'utf8'
);
if (!isDev) {
const checksum = Buffer.from(githubSignature, 'utf8');
//@ts-ignore
if (checksum.length !== digest.length || !crypto.timingSafeEqual(digest, checksum)) {
throw { status: 500, message: 'SHA256 checksum failed. Are you doing something fishy?' }
};
}
if (githubEvent === 'push') {
if (!applicationFound.configHash) {
const configHash = crypto
//@ts-ignore
.createHash('sha256')
.update(
JSON.stringify({
buildPack: applicationFound.buildPack,
port: applicationFound.port,
exposePort: applicationFound.exposePort,
installCommand: applicationFound.installCommand,
buildCommand: applicationFound.buildCommand,
startCommand: applicationFound.startCommand
})
)
.digest('hex');
await prisma.application.updateMany({
where: { branch, projectId },
data: { configHash }
});
}
await prisma.application.update({
where: { id: applicationFound.id },
data: { updatedAt: new Date() }
});
await prisma.build.create({
data: {
id: buildId,
applicationId: applicationFound.id,
destinationDockerId: applicationFound.destinationDocker.id,
gitSourceId: applicationFound.gitSource.id,
githubAppId: applicationFound.gitSource.githubApp?.id,
gitlabAppId: applicationFound.gitSource.gitlabApp?.id,
status: 'queued',
type: 'webhook_commit'
}
});
scheduler.workers.get('deployApplication').postMessage({
build_id: buildId,
type: 'webhook_commit',
...applicationFound
});
return {
message: 'Queued. Thank you!'
};
} else if (githubEvent === 'pull_request') {
const pullmergeRequestId = body.number;
const pullmergeRequestAction = body.action;
const sourceBranch = body.pull_request.head.ref;
if (!allowedActions.includes(pullmergeRequestAction)) {
throw { status: 500, message: 'Action not allowed.' }
}
if (applicationFound.settings.previews) {
if (applicationFound.destinationDockerId) {
const isRunning = await checkContainer(
applicationFound.destinationDocker.engine,
applicationFound.id
);
if (!isRunning) {
throw { status: 500, message: 'Application not running.' }
}
}
if (
pullmergeRequestAction === 'opened' ||
pullmergeRequestAction === 'reopened' ||
pullmergeRequestAction === 'synchronize'
) {
await prisma.application.update({
where: { id: applicationFound.id },
data: { updatedAt: new Date() }
});
await prisma.build.create({
data: {
id: buildId,
applicationId: applicationFound.id,
destinationDockerId: applicationFound.destinationDocker.id,
gitSourceId: applicationFound.gitSource.id,
githubAppId: applicationFound.gitSource.githubApp?.id,
gitlabAppId: applicationFound.gitSource.gitlabApp?.id,
status: 'queued',
type: 'webhook_pr'
}
});
scheduler.workers.get('deployApplication').postMessage({
build_id: buildId,
type: 'webhook_pr',
...applicationFound,
sourceBranch,
pullmergeRequestId
});
return {
message: 'Queued. Thank you!'
};
} else if (pullmergeRequestAction === 'closed') {
if (applicationFound.destinationDockerId) {
const id = `${applicationFound.id}-${pullmergeRequestId}`;
const engine = applicationFound.destinationDocker.engine;
await removeContainer({ id, engine });
}
return {
message: 'Removed preview. Thank you!'
};
}
} else {
throw { status: 500, message: 'Pull request previews are not enabled.' }
}
}
}
throw { status: 500, message: 'Not handled event.' }
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}

View File

@@ -0,0 +1,10 @@
import { FastifyPluginAsync } from 'fastify';
import { configureGitHubApp, gitHubEvents, installGithub } from './handlers';
const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
fastify.get('/', async (request, reply) => configureGitHubApp(request, reply));
fastify.get('/install', async (request, reply) => installGithub(request, reply));
fastify.post('/events', async (request, reply) => gitHubEvents(request, reply));
};
export default root;

View File

@@ -0,0 +1,178 @@
import axios from "axios";
import cuid from "cuid";
import crypto from "crypto";
import type { FastifyReply, FastifyRequest } from "fastify";
import { encrypt, errorHandler, isDev, listSettings, prisma } from "../../../lib/common";
import { checkContainer, removeContainer } from "../../../lib/docker";
import { scheduler } from "../../../lib/scheduler";
import { getApplicationFromDB, getApplicationFromDBWebhook } from "../../api/v1/applications/handlers";
export async function configureGitLabApp(request: FastifyRequest, reply: FastifyReply) {
try {
const { code, state } = request.query;
const { fqdn } = await listSettings();
const { gitSource: { gitlabApp: { appId, appSecret }, htmlUrl } } = await getApplicationFromDB(state, undefined);
let domain = `http://${request.hostname}`;
if (fqdn) domain = fqdn;
if (isDev) {
domain = `http://localhost:3001`;
}
const params = new URLSearchParams({
client_id: appId,
client_secret: appSecret,
code,
state,
grant_type: 'authorization_code',
redirect_uri: `${domain}/webhooks/gitlab`
});
const { data } = await axios.post(`${htmlUrl}/oauth/token`, params)
if (isDev) {
return reply.redirect(`http://localhost:3000/webhooks/success?token=${data.access_token}`)
}
return reply.redirect(`/webhooks/success?token=${data.access_token}`)
} catch ({ status, message, ...other }) {
console.log(other)
return errorHandler({ status, message })
}
}
export async function gitLabEvents(request: FastifyRequest, reply: FastifyReply) {
try {
const buildId = cuid();
const allowedActions = ['opened', 'reopen', 'close', 'open', 'update'];
const { object_kind: objectKind, ref, project_id } = request.body
const webhookToken = request.headers['x-gitlab-token'];
if (!webhookToken) {
throw { status: 500, message: 'Invalid webhookToken.' }
}
if (objectKind === 'push') {
const projectId = Number(project_id);
const branch = ref.split('/')[2];
const applicationFound = await getApplicationFromDBWebhook(projectId, branch);
if (applicationFound) {
if (!applicationFound.configHash) {
const configHash = crypto
.createHash('sha256')
.update(
JSON.stringify({
buildPack: applicationFound.buildPack,
port: applicationFound.port,
exposePort: applicationFound.exposePort,
installCommand: applicationFound.installCommand,
buildCommand: applicationFound.buildCommand,
startCommand: applicationFound.startCommand
})
)
.digest('hex');
await prisma.application.updateMany({
where: { branch, projectId },
data: { configHash }
});
}
await prisma.application.update({
where: { id: applicationFound.id },
data: { updatedAt: new Date() }
});
await prisma.build.create({
data: {
id: buildId,
applicationId: applicationFound.id,
destinationDockerId: applicationFound.destinationDocker.id,
gitSourceId: applicationFound.gitSource.id,
githubAppId: applicationFound.gitSource.githubApp?.id,
gitlabAppId: applicationFound.gitSource.gitlabApp?.id,
status: 'queued',
type: 'webhook_commit'
}
});
scheduler.workers.get('deployApplication').postMessage({
build_id: buildId,
type: 'webhook_commit',
...applicationFound
});
return {
message: 'Queued. Thank you!'
};
}
} else if (objectKind === 'merge_request') {
const { object_attributes: { work_in_progress: isDraft, action, source_branch: sourceBranch, target_branch: targetBranch, iid: pullmergeRequestId }, project: { id } } = request.body
const projectId = Number(id);
if (!allowedActions.includes(action)) {
throw { status: 500, message: 'Action not allowed.' }
}
if (isDraft) {
throw { status: 500, message: 'Draft MR, do nothing.' }
}
const applicationFound = await getApplicationFromDBWebhook(projectId, targetBranch);
if (applicationFound) {
if (applicationFound.settings.previews) {
if (applicationFound.destinationDockerId) {
const isRunning = await checkContainer(
applicationFound.destinationDocker.engine,
applicationFound.id
);
if (!isRunning) {
throw { status: 500, message: 'Application not running.' }
}
}
if (!isDev && applicationFound.gitSource.gitlabApp.webhookToken !== webhookToken) {
throw { status: 500, message: 'Invalid webhookToken. Are you doing something nasty?!' }
}
if (
action === 'opened' ||
action === 'reopen' ||
action === 'open' ||
action === 'update'
) {
await prisma.application.update({
where: { id: applicationFound.id },
data: { updatedAt: new Date() }
});
await prisma.build.create({
data: {
id: buildId,
applicationId: applicationFound.id,
destinationDockerId: applicationFound.destinationDocker.id,
gitSourceId: applicationFound.gitSource.id,
githubAppId: applicationFound.gitSource.githubApp?.id,
gitlabAppId: applicationFound.gitSource.gitlabApp?.id,
status: 'queued',
type: 'webhook_mr'
}
});
scheduler.workers.get('deployApplication').postMessage({
build_id: buildId,
type: 'webhook_mr',
...applicationFound,
sourceBranch,
pullmergeRequestId
});
return {
message: 'Queued. Thank you!'
};
} else if (action === 'close') {
if (applicationFound.destinationDockerId) {
const id = `${applicationFound.id}-${pullmergeRequestId}`;
const engine = applicationFound.destinationDocker.engine;
await removeContainer({ id, engine });
}
return {
message: 'Removed preview. Thank you!'
};
}
}
throw { status: 500, message: 'Merge request previews are not enabled.' }
}
}
throw { status: 500, message: 'Not handled event.' }
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}

View File

@@ -0,0 +1,9 @@
import { FastifyPluginAsync } from 'fastify';
import { configureGitLabApp, gitLabEvents } from './handlers';
const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
fastify.get('/', async (request, reply) => configureGitLabApp(request, reply));
fastify.post('/events', async (request, reply) => gitLabEvents(request, reply));
};
export default root;

View File

@@ -0,0 +1,489 @@
import { FastifyRequest } from "fastify";
import { asyncExecShell, errorHandler, getDomain, isDev, listServicesWithIncludes, prisma, supportedServiceTypesAndVersions } from "../../../lib/common";
import { getEngine } from "../../../lib/docker";
function configureMiddleware(
{ id, container, port, domain, nakedDomain, isHttps, isWWW, isDualCerts, scriptName, type },
traefik
) {
if (isHttps) {
traefik.http.routers[id] = {
entrypoints: ['web'],
rule: `Host(\`${nakedDomain}\`) || Host(\`www.${nakedDomain}\`)`,
service: `${id}`,
middlewares: ['redirect-to-https']
};
traefik.http.services[id] = {
loadbalancer: {
servers: [
{
url: `http://${container}:${port}`
}
]
}
};
if (isDualCerts) {
traefik.http.routers[`${id}-secure`] = {
entrypoints: ['websecure'],
rule: `Host(\`${nakedDomain}\`) || Host(\`www.${nakedDomain}\`)`,
service: `${id}`,
tls: {
certresolver: 'letsencrypt'
},
middlewares: []
};
} else {
if (isWWW) {
traefik.http.routers[`${id}-secure-www`] = {
entrypoints: ['websecure'],
rule: `Host(\`www.${nakedDomain}\`)`,
service: `${id}`,
tls: {
certresolver: 'letsencrypt'
},
middlewares: []
};
traefik.http.routers[`${id}-secure`] = {
entrypoints: ['websecure'],
rule: `Host(\`${nakedDomain}\`)`,
service: `${id}`,
tls: {
domains: {
main: `${domain}`
}
},
middlewares: ['redirect-to-www']
};
traefik.http.routers[`${id}`].middlewares.push('redirect-to-www');
} else {
traefik.http.routers[`${id}-secure-www`] = {
entrypoints: ['websecure'],
rule: `Host(\`www.${nakedDomain}\`)`,
service: `${id}`,
tls: {
domains: {
main: `${domain}`
}
},
middlewares: ['redirect-to-non-www']
};
traefik.http.routers[`${id}-secure`] = {
entrypoints: ['websecure'],
rule: `Host(\`${domain}\`)`,
service: `${id}`,
tls: {
certresolver: 'letsencrypt'
},
middlewares: []
};
traefik.http.routers[`${id}`].middlewares.push('redirect-to-non-www');
}
}
} else {
traefik.http.routers[id] = {
entrypoints: ['web'],
rule: `Host(\`${nakedDomain}\`) || Host(\`www.${nakedDomain}\`)`,
service: `${id}`,
middlewares: []
};
traefik.http.routers[`${id}-secure`] = {
entrypoints: ['websecure'],
rule: `Host(\`${nakedDomain}\`) || Host(\`www.${nakedDomain}\`)`,
service: `${id}`,
tls: {
domains: {
main: `${nakedDomain}`
}
},
middlewares: ['redirect-to-http']
};
traefik.http.services[id] = {
loadbalancer: {
servers: [
{
url: `http://${container}:${port}`
}
]
}
};
if (!isDualCerts) {
if (isWWW) {
traefik.http.routers[`${id}`].middlewares.push('redirect-to-www');
traefik.http.routers[`${id}-secure`].middlewares.push('redirect-to-www');
} else {
traefik.http.routers[`${id}`].middlewares.push('redirect-to-non-www');
traefik.http.routers[`${id}-secure`].middlewares.push('redirect-to-non-www');
}
}
}
if (type === 'plausibleanalytics' && scriptName && scriptName !== 'plausible.js') {
if (!traefik.http.routers[`${id}`].middlewares.includes(`${id}-redir`)) {
traefik.http.routers[`${id}`].middlewares.push(`${id}-redir`);
}
if (!traefik.http.routers[`${id}-secure`].middlewares.includes(`${id}-redir`)) {
traefik.http.routers[`${id}-secure`].middlewares.push(`${id}-redir`);
}
}
}
export async function traefikConfiguration(request, reply) {
try {
const traefik = {
http: {
routers: {},
services: {},
middlewares: {
'redirect-to-https': {
redirectscheme: {
scheme: 'https'
}
},
'redirect-to-http': {
redirectscheme: {
scheme: 'http'
}
},
'redirect-to-non-www': {
redirectregex: {
regex: '^https?://www\\.(.+)',
replacement: 'http://${1}'
}
},
'redirect-to-www': {
redirectregex: {
regex: '^https?://(?:www\\.)?(.+)',
replacement: 'http://www.${1}'
}
}
}
}
};
const applications = await prisma.application.findMany({
include: { destinationDocker: true, settings: true }
});
const data = {
applications: [],
services: [],
coolify: []
};
for (const application of applications) {
const {
fqdn,
id,
port,
destinationDocker,
destinationDockerId,
settings: { previews, dualCerts }
} = application;
if (destinationDockerId) {
const { engine, network } = destinationDocker;
const isRunning = true;
if (fqdn) {
const domain = getDomain(fqdn);
const nakedDomain = domain.replace(/^www\./, '');
const isHttps = fqdn.startsWith('https://');
const isWWW = fqdn.includes('www.');
if (isRunning) {
data.applications.push({
id,
container: id,
port: port || 3000,
domain,
nakedDomain,
isRunning,
isHttps,
isWWW,
isDualCerts: dualCerts
});
}
if (previews) {
const host = getEngine(engine);
const { stdout } = await asyncExecShell(
`DOCKER_HOST=${host} docker container ls --filter="status=running" --filter="network=${network}" --filter="name=${id}-" --format="{{json .Names}}"`
);
const containers = stdout
.trim()
.split('\n')
.filter((a) => a)
.map((c) => c.replace(/"/g, ''));
if (containers.length > 0) {
for (const container of containers) {
const previewDomain = `${container.split('-')[1]}.${domain}`;
const nakedDomain = previewDomain.replace(/^www\./, '');
data.applications.push({
id: container,
container,
port: port || 3000,
domain: previewDomain,
isRunning,
nakedDomain,
isHttps,
isWWW,
isDualCerts: dualCerts
});
}
}
}
}
}
}
const services = await listServicesWithIncludes();
for (const service of services) {
const {
fqdn,
id,
type,
destinationDocker,
destinationDockerId,
dualCerts,
plausibleAnalytics
} = service;
if (destinationDockerId) {
const { engine } = destinationDocker;
const found = supportedServiceTypesAndVersions.find((a) => a.name === type);
if (found) {
const port = found.ports.main;
const publicPort = service[type]?.publicPort;
const isRunning = true;
if (fqdn) {
const domain = getDomain(fqdn);
const nakedDomain = domain.replace(/^www\./, '');
const isHttps = fqdn.startsWith('https://');
const isWWW = fqdn.includes('www.');
if (isRunning) {
// Plausible Analytics custom script
let scriptName = false;
if (type === 'plausibleanalytics' && plausibleAnalytics.scriptName !== 'plausible.js') {
scriptName = plausibleAnalytics.scriptName;
}
let container = id;
let otherDomain = null;
let otherNakedDomain = null;
let otherIsHttps = null;
let otherIsWWW = null;
if (type === 'minio' && service.minio.apiFqdn) {
otherDomain = getDomain(service.minio.apiFqdn);
otherNakedDomain = otherDomain.replace(/^www\./, '');
otherIsHttps = service.minio.apiFqdn.startsWith('https://');
otherIsWWW = service.minio.apiFqdn.includes('www.');
}
data.services.push({
id,
container,
type,
otherDomain,
otherNakedDomain,
otherIsHttps,
otherIsWWW,
port,
publicPort,
domain,
nakedDomain,
isRunning,
isHttps,
isWWW,
isDualCerts: dualCerts,
scriptName
});
}
}
}
}
}
const { fqdn, dualCerts } = await prisma.setting.findFirst();
if (fqdn) {
const domain = getDomain(fqdn);
const nakedDomain = domain.replace(/^www\./, '');
const isHttps = fqdn.startsWith('https://');
const isWWW = fqdn.includes('www.');
data.coolify.push({
id: isDev ? 'host.docker.internal' : 'coolify',
container: isDev ? 'host.docker.internal' : 'coolify',
port: 3000,
domain,
nakedDomain,
isHttps,
isWWW,
isDualCerts: dualCerts
});
}
for (const application of data.applications) {
configureMiddleware(application, traefik);
}
for (const service of data.services) {
const { id, scriptName } = service;
configureMiddleware(service, traefik);
if (service.type === 'minio') {
service.id = id + '-minio';
service.container = id;
service.domain = service.otherDomain;
service.nakedDomain = service.otherNakedDomain;
service.isHttps = service.otherIsHttps;
service.isWWW = service.otherIsWWW;
service.port = 9000;
configureMiddleware(service, traefik);
}
if (scriptName) {
traefik.http.middlewares[`${id}-redir`] = {
replacepathregex: {
regex: `/js/${scriptName}`,
replacement: '/js/plausible.js'
}
};
}
}
for (const coolify of data.coolify) {
configureMiddleware(coolify, traefik);
}
if (Object.keys(traefik.http.routers).length === 0) {
traefik.http.routers = null;
}
if (Object.keys(traefik.http.services).length === 0) {
traefik.http.services = null;
}
return {
...traefik
}
} catch ({ status, message }) {
return errorHandler({ status, message })
}
}
export async function traefikOtherConfiguration(request: FastifyRequest, reply) {
try {
const { id } = request.query
if (id) {
const { privatePort, publicPort, type, address = id } = request.query
let traefik = {};
if (publicPort && type && privatePort) {
if (type === 'tcp') {
traefik = {
[type]: {
routers: {
[id]: {
entrypoints: [type],
rule: `HostSNI(\`*\`)`,
service: id
}
},
services: {
[id]: {
loadbalancer: {
servers: [{ address: `${address}:${privatePort}` }]
}
}
}
}
};
} else if (type === 'http') {
const service = await prisma.service.findFirst({
where: { id },
include: { minio: true }
});
if (service) {
if (service.type === 'minio') {
if (service?.minio?.apiFqdn) {
const {
minio: { apiFqdn }
} = service;
const domain = getDomain(apiFqdn);
const isHttps = apiFqdn.startsWith('https://');
traefik = {
[type]: {
routers: {
[id]: {
entrypoints: [type],
rule: `Host(\`${domain}\`)`,
service: id
}
},
services: {
[id]: {
loadbalancer: {
servers: [{ url: `http://${id}:${privatePort}` }]
}
}
}
}
};
if (isHttps) {
if (isDev) {
traefik[type].routers[id].tls = {
domains: {
main: `${domain}`
}
};
} else {
traefik[type].routers[id].tls = {
certresolver: 'letsencrypt'
};
}
}
}
} else {
if (service?.fqdn) {
const domain = getDomain(service.fqdn);
const isHttps = service.fqdn.startsWith('https://');
traefik = {
[type]: {
routers: {
[id]: {
entrypoints: [type],
rule: `Host(\`${domain}:${privatePort}\`)`,
service: id
}
},
services: {
[id]: {
loadbalancer: {
servers: [{ url: `http://${id}:${privatePort}` }]
}
}
}
}
};
if (isHttps) {
if (isDev) {
traefik[type].routers[id].tls = {
domains: {
main: `${domain}`
}
};
} else {
traefik[type].routers[id].tls = {
certresolver: 'letsencrypt'
};
}
}
}
}
} else {
throw { status: 500 }
}
}
} else {
throw { status: 500 }
}
return {
...traefik
};
}
throw { status: 500 }
} catch ({ status, message }) {
console.log(status, message);
return errorHandler({ status, message })
}
}

View File

@@ -0,0 +1,9 @@
import { FastifyPluginAsync } from 'fastify';
import { traefikConfiguration, traefikOtherConfiguration } from './handlers';
const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
fastify.get('/main.json', async (request, reply) => traefikConfiguration(request, reply));
fastify.get('/other.json', async (request, reply) => traefikOtherConfiguration(request, reply));
};
export default root;