Just v2
This commit is contained in:
Andras Bacsai
2022-02-10 15:47:44 +01:00
committed by GitHub
parent a64b095c13
commit 460ae85226
403 changed files with 22039 additions and 12465 deletions

60
src/lib/api.ts Normal file
View File

@@ -0,0 +1,60 @@
async function send({ method, path, data = {}, headers, timeout = 30000 }) {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
const opts = { method, headers: {}, body: null, signal: controller.signal };
if (Object.keys(data).length > 0) {
let parsedData = data;
for (const [key, value] of Object.entries(data)) {
if (value === '') {
parsedData[key] = null;
}
}
if (parsedData) {
opts.headers['Content-Type'] = 'application/json';
opts.body = JSON.stringify(parsedData);
}
}
if (headers) {
opts.headers = {
...opts.headers,
...headers
};
}
const response = await fetch(`${path}`, opts);
clearTimeout(id);
const contentType = response.headers.get('content-type');
let responseData = {};
if (contentType) {
if (contentType?.indexOf('application/json') !== -1) {
responseData = await response.json();
} else if (contentType?.indexOf('text/plain') !== -1) {
responseData = await response.text();
} else {
return {};
}
} else {
return {};
}
if (!response.ok) throw responseData;
return responseData;
}
export function get(path, headers = {}): Promise<any> {
return send({ method: 'GET', path, headers });
}
export function del(path, data = {}, headers = {}): Promise<any> {
return send({ method: 'DELETE', path, data, headers });
}
export function post(path, data, headers = {}): Promise<any> {
return send({ method: 'POST', path, data, headers });
}
export function put(path, data, headers = {}): Promise<any> {
return send({ method: 'PUT', path, data, headers });
}

View File

@@ -1,29 +0,0 @@
import Deployment from '$models/Deployment';
import { saveAppLog } from './logging';
import * as packs from './packs';
export default async function (configuration) {
const { id, organization, name, branch } = configuration.repository;
const { domain } = configuration.publish;
const deployId = configuration.general.deployId;
const execute = packs[configuration.build.pack];
if (execute) {
await Deployment.findOneAndUpdate(
{ repoId: id, branch, deployId, organization, name, domain },
{ repoId: id, branch, deployId, organization, name, domain, progress: 'inprogress' }
);
await saveAppLog('### Building application.', configuration);
await execute(configuration);
await saveAppLog('### Building done.', configuration);
} else {
try {
await Deployment.findOneAndUpdate(
{ repoId: id, branch, deployId, organization, name, domain },
{ repoId: id, branch, deployId, organization, name, domain, progress: 'failed' }
);
} catch (error) {
// Hmm.
}
throw new Error('No buildpack found.');
}
}

View File

@@ -1,66 +0,0 @@
import { docker } from '$lib/api/docker';
import Deployment from '$models/Deployment';
import { execShellAsync } from '../common';
import crypto from 'crypto';
export async function deleteSameDeployments(configuration, originalDomain = null) {
await (
await docker.engine.listServices()
)
.filter((r) => r.Spec.Labels.managedBy === 'coolify' && r.Spec.Labels.type === 'application')
.map(async (s) => {
const running = JSON.parse(s.Spec.Labels.configuration);
if (
running.repository.id === configuration.repository.id &&
running.repository.branch === configuration.repository.branch &&
running.publish.domain === originalDomain || configuration.publish.domain
) {
await execShellAsync(`docker stack rm ${s.Spec.Labels['com.docker.stack.namespace']}`);
}
});
}
export async function cleanupStuckedDeploymentsInDB() {
// Cleanup stucked deployments.
await Deployment.updateMany(
{ progress: { $in: ['queued', 'inprogress'] } },
{ progress: 'failed' }
);
}
export async function purgeImagesContainers(configuration, deleteAll = false) {
const { name, tag } = configuration.build.container;
try {
await execShellAsync('docker container prune -f');
} catch (error) {
//
}
try {
if (deleteAll) {
const IDsToDelete = (
await execShellAsync(
`docker images ls --filter=reference='${name}' --format '{{json .ID }}'`
)
)
.trim()
.replace(/"/g, '')
.split('\n');
if (IDsToDelete.length > 0) await execShellAsync(`docker rmi -f ${IDsToDelete.join(' ')}`);
} else {
const IDsToDelete = (
await execShellAsync(
`docker images ls --filter=reference='${name}' --filter=before='${name}:${tag}' --format '{{json .ID }}'`
)
)
.trim()
.replace(/"/g, '')
.split('\n');
if (IDsToDelete.length > 1) await execShellAsync(`docker rmi -f ${IDsToDelete.join(' ')}`);
}
} catch (error) {
console.log(error);
}
try {
await execShellAsync('docker image prune -f');
} catch (error) {
//
}
}

View File

@@ -1,54 +0,0 @@
import jsonwebtoken from 'jsonwebtoken';
import { execShellAsync } from '../common';
export default async function (configuration) {
try {
const { GITHUB_APP_PRIVATE_KEY } = process.env;
const { workdir, isPreviewDeploymentEnabled, pullRequest } = configuration.general;
const { organization, name, branch } = configuration.repository;
const github = configuration.github;
if (!github.installation.id || !github.app.id) {
throw new Error('Github installation ID is invalid.');
}
const githubPrivateKey = GITHUB_APP_PRIVATE_KEY.replace(/\\n/g, '\n').replace(/"/g, '');
const payload = {
iat: Math.round(new Date().getTime() / 1000),
exp: Math.round(new Date().getTime() / 1000 + 60),
iss: parseInt(github.app.id)
};
const jwtToken = jsonwebtoken.sign(payload, githubPrivateKey, {
algorithm: 'RS256'
});
const { token } = await (
await fetch(
`https://api.github.com/app/installations/${github.installation.id}/access_tokens`,
{
method: 'POST',
headers: {
Authorization: 'Bearer ' + jwtToken,
Accept: 'application/vnd.github.machine-man-preview+json'
}
}
)
).json();
await execShellAsync(
`mkdir -p ${workdir} && git clone -q -b ${branch} https://x-access-token:${token}@github.com/${organization}/${name}.git ${workdir}/`
);
if (isPreviewDeploymentEnabled && pullRequest && pullRequest !== 0) {
await execShellAsync(
`cd ${workdir} && git fetch origin pull/${pullRequest}/head:pull_${pullRequest} && git checkout pull_${pullRequest}`
);
}
configuration.build.container.tag = (
await execShellAsync(`cd ${workdir}/ && git rev-parse HEAD`)
)
.replace('\n', '')
.slice(0, 7);
} catch (error) {
console.log(error);
}
}

View File

@@ -1,18 +0,0 @@
export const baseServiceConfiguration = {
replicas: 1,
restart_policy: {
condition: 'any',
max_attempts: 6
},
update_config: {
parallelism: 1,
delay: '10s',
order: 'start-first'
},
rollback_config: {
parallelism: 1,
delay: '10s',
order: 'start-first',
failure_action: 'rollback'
}
};

View File

@@ -1,198 +0,0 @@
import cuid from 'cuid';
import crypto from 'crypto';
import { uniqueNamesGenerator, adjectives, colors, animals } from 'unique-names-generator';
import { docker } from '$lib/api/docker';
import { baseServiceConfiguration } from './common';
import { execShellAsync } from '../common';
import { promises as fs } from 'fs';
import Configuration from '$models/Configuration';
function getUniq() {
return uniqueNamesGenerator({ dictionaries: [adjectives, animals, colors], length: 2 });
}
export function setDefaultConfiguration(configuration) {
const nickname = configuration.general.nickname || getUniq();
const deployId = cuid();
const shaBase = JSON.stringify({ path: configuration.publish.path, domain: configuration.publish.domain });
const sha256 = crypto.createHash('sha256').update(shaBase).digest('hex');
configuration.build.container.name = sha256.slice(0, 15);
configuration.general.nickname = nickname;
configuration.general.deployId = deployId;
configuration.general.workdir = `/tmp/${deployId}`;
if (configuration.general.isPreviewDeploymentEnabled && configuration.general.pullRequest !== 0) {
configuration.build.container.name = `pr${configuration.general.pullRequest}-${sha256.slice(
0,
8
)}`;
configuration.publish.domain = `pr${configuration.general.pullRequest}.${configuration.publish.domain}`;
}
if (!configuration.publish.path) configuration.publish.path = '/';
if (!configuration.publish.port) {
if (
configuration.build.pack === 'nodejs' ||
configuration.build.pack === 'nuxtjs' ||
configuration.build.pack === 'rust' ||
configuration.build.pack === 'nextjs' ||
configuration.build.pack === 'nestjs'
) {
configuration.publish.port = 3000;
} else if (configuration.build.pack === 'python') {
configuration.publish.port = 4000;
} else {
configuration.publish.port = 80;
}
}
if (!configuration.build.directory) configuration.build.directory = '';
if (configuration.build.directory.startsWith('/'))
configuration.build.directory = configuration.build.directory.replace('/', '');
if (!configuration.publish.directory) configuration.publish.directory = '';
if (configuration.publish.directory.startsWith('/'))
configuration.publish.directory = configuration.publish.directory.replace('/', '');
if (configuration.build.pack === 'nodejs') {
if (!configuration.build.command.installation)
configuration.build.command.installation = 'yarn install';
}
if (
configuration.build.pack === 'nodejs' ||
configuration.build.pack === 'vuejs' ||
configuration.build.pack === 'nuxtjs' ||
configuration.build.pack === 'nextjs' ||
configuration.build.pack === 'nestjs'
) {
if (!configuration.build.command.start) configuration.build.command.start = 'yarn start';
}
if (configuration.build.pack === 'python') {
if (!configuration.build.command.python.module)
configuration.build.command.python.module = 'main';
if (!configuration.build.command.python.instance)
configuration.build.command.python.instance = 'app';
}
configuration.build.container.baseSHA = crypto
.createHash('sha256')
.update(JSON.stringify(baseServiceConfiguration))
.digest('hex');
configuration.baseServiceConfiguration = baseServiceConfiguration;
return configuration;
}
export async function precheckDeployment(configuration) {
const services = await Configuration.find({
'publish.domain': configuration.publish.domain,
'publish.path': configuration.publish.path
})
// const services = (await docker.engine.listServices()).filter(
// (r) =>
// r.Spec.Labels.managedBy === 'coolify' &&
// r.Spec.Labels.type === 'application' &&
// JSON.parse(r.Spec.Labels.configuration).publish.domain === configuration.publish.domain
// );
let foundService = false;
let configChanged = false;
let imageChanged = false;
let forceUpdate = false;
for (const service of services) {
// const running = JSON.parse(service.Spec.Labels.configuration);
if (
service.repository.id === configuration.repository.id &&
service.repository.branch === configuration.repository.branch
) {
foundService = true;
// Base service configuration changed
if (
!service.build.container.baseSHA ||
service.build.container.baseSHA !== configuration.build.container.baseSHA
) {
forceUpdate = true;
}
// If the deployment is in error state, forceUpdate
const state = await execShellAsync(
`docker stack ps ${service.build.container.name} --format '{{ json . }}'`
);
const isError = state
.split('\n')
.filter((n) => n)
.map((s) => JSON.parse(s))
.filter(
(n) =>
n.DesiredState !== 'Running' && n.Image.split(':')[1] === service.build.container.tag
);
if (isError.length > 0) {
forceUpdate = true;
}
const compareObjects = (a, b) => {
if (a === b) return true;
if (typeof a != 'object' || typeof b != 'object' || a == null || b == null) return false;
const keysA = Object.keys(a),
keysB = Object.keys(b);
if (keysA.length != keysB.length) return false;
for (const key of keysA) {
if (!keysB.includes(key)) return false;
if (typeof a[key] === 'function' || typeof b[key] === 'function') {
if (a[key].toString() != b[key].toString()) return false;
} else {
if (!compareObjects(a[key], b[key])) return false;
}
}
return true;
};
const runningWithoutContainer = JSON.parse(JSON.stringify(service));
delete runningWithoutContainer.build.container;
const configurationWithoutContainer = JSON.parse(JSON.stringify(configuration));
delete configurationWithoutContainer.build.container;
// If only the configuration changed
if (
!compareObjects(runningWithoutContainer.build, configurationWithoutContainer.build) ||
!compareObjects(runningWithoutContainer.publish, configurationWithoutContainer.publish) ||
runningWithoutContainer.general.isPreviewDeploymentEnabled !==
configurationWithoutContainer.general.isPreviewDeploymentEnabled
) {
configChanged = true;
}
// If only the image changed
if (service.build.container.tag !== configuration.build.container.tag) imageChanged = true;
// If build pack changed, forceUpdate the service
if (service.build.pack !== configuration.build.pack) forceUpdate = true;
if (
configuration.general.isPreviewDeploymentEnabled &&
configuration.general.pullRequest !== 0
)
forceUpdate = true;
}
}
if (forceUpdate) {
imageChanged = false;
configChanged = false;
}
return {
foundService,
imageChanged,
configChanged,
forceUpdate
};
}
export async function updateServiceLabels(configuration) {
return await execShellAsync(
`docker service update --label-add configuration='${JSON.stringify(configuration)}' ${
configuration.build.container.name
}_${configuration.build.container.name}`
);
}

View File

@@ -1,69 +0,0 @@
import { promises as fs } from 'fs';
export default async function (configuration) {
const staticDeployments = ['react', 'vuejs', 'static', 'svelte', 'gatsby'];
try {
// TODO: Write full .dockerignore for all deployments!!
if (configuration.build.pack === 'php') {
await fs.writeFile(
`${configuration.general.workdir}/.htaccess`,
`
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php [QSA,L]
`
);
}
// await fs.writeFile(`${configuration.general.workdir}/.dockerignore`, 'node_modules')
if (staticDeployments.includes(configuration.build.pack)) {
await fs.writeFile(
`${configuration.general.workdir}/nginx.conf`,
`user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
access_log off;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html;
try_files $uri $uri/index.html $uri/ /index.html =404;
}
error_page 404 /50x.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
`
);
}
} catch (error) {
console.log(error);
throw new Error(error);
}
}

View File

@@ -1,80 +0,0 @@
import { docker } from '$lib/api/docker';
import { saveAppLog } from './logging';
import { promises as fs } from 'fs';
import { deleteSameDeployments, purgeImagesContainers } from './cleanup';
import yaml from 'js-yaml';
import { delay, execShellAsync } from '../common';
export default async function (configuration, nextStep) {
const generateEnvs = {};
for (const secret of configuration.publish.secrets) {
generateEnvs[secret.name] = secret.value;
}
const containerName = configuration.build.container.name;
const containerTag = configuration.build.container.tag;
// Only save SHA256 of it in the configuration label
const baseServiceConfiguration = configuration.baseServiceConfiguration;
delete configuration.baseServiceConfiguration;
const stack = {
version: '3.8',
services: {
[containerName]: {
image: `${containerName}:${containerTag}`,
networks: [`${docker.network}`],
environment: generateEnvs,
deploy: {
...baseServiceConfiguration,
labels: [
'managedBy=coolify',
'type=application',
'configuration=' + JSON.stringify(configuration),
'traefik.enable=true',
'traefik.http.services.' +
containerName +
`.loadbalancer.server.port=${configuration.publish.port}`,
'traefik.http.routers.' + containerName + '.entrypoints=websecure',
'traefik.http.routers.' +
containerName +
'.rule=Host(`' +
configuration.publish.domain +
'`) && PathPrefix(`' +
configuration.publish.path +
'`)',
'traefik.http.routers.' + containerName + '.tls.certresolver=letsencrypt',
'traefik.http.routers.' + containerName + '.middlewares=global-compress'
]
}
}
},
networks: {
[`${docker.network}`]: {
external: true
}
}
};
await saveAppLog('### Publishing.', configuration);
await fs.writeFile(`${configuration.general.workdir}/stack.yml`, yaml.dump(stack));
if (nextStep === 2) {
// console.log('image changed')
await execShellAsync(
`docker service update --image ${containerName}:${containerTag} ${containerName}_${containerName}`
);
} else {
// console.log('new deployment or force deployment or config changed')
// if (originalDomain !== configuration.publish.domain) {
// await deleteSameDeployments(configuration, originalDomain);
// } else {
// await deleteSameDeployments(configuration);
// }
// await deleteSameDeployments(configuration);
await execShellAsync(
`cat ${configuration.general.workdir}/stack.yml | docker stack deploy --prune -c - ${containerName}`
);
}
await saveAppLog('### Published done!', configuration);
}

View File

@@ -1,58 +0,0 @@
import Settings from '$models/Settings';
import ServerLog from '$models/ServerLog';
import ApplicationLog from '$models/ApplicationLog';
import dayjs from 'dayjs';
import { version } from '../../../../package.json';
function generateTimestamp() {
return `${dayjs().format('YYYY-MM-DD HH:mm:ss.SSS')} `;
}
const patterns = [
'[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
'(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
].join('|');
export async function saveAppLog(event, configuration, isError?: boolean) {
try {
const deployId = configuration.general.deployId;
const repoId = configuration.repository.id;
const branch = configuration.repository.branch;
if (isError) {
const clearedEvent =
'[ERROR 😱] ' +
generateTimestamp() +
event.replace(new RegExp(patterns, 'g'), '').replace(/(\r\n|\n|\r)/gm, '');
await new ApplicationLog({ repoId, branch, deployId, event: clearedEvent }).save();
} else {
if (event && event !== '\n') {
const clearedEvent =
'[INFO] ' +
generateTimestamp() +
event.replace(new RegExp(patterns, 'g'), '').replace(/(\r\n|\n|\r)/gm, '');
await new ApplicationLog({ repoId, branch, deployId, event: clearedEvent }).save();
}
}
} catch (error) {
console.log(error);
return error;
}
}
export async function saveServerLog(error) {
const settings = await Settings.findOne({ applicationName: 'coolify' });
const payload = {
message: error.message,
stack: error.stack,
type: error.type || 'spaghetticode',
version
};
const found = await ServerLog.find(payload);
if (found.length === 0 && error.message) await new ServerLog(payload).save();
if (settings && settings.sendErrors && process.env.NODE_ENV === 'production') {
await fetch('https://errors.coollabs.io/api/error', {
method: 'POST',
body: JSON.stringify({ ...payload })
});
}
}

View File

@@ -1,17 +0,0 @@
import { docker, streamEvents } from '$lib/api/docker';
import { promises as fs } from 'fs';
export default async function (configuration) {
const path = `${configuration.general.workdir}/${
configuration.build.directory ? configuration.build.directory : ''
}`;
if (fs.stat(`${path}/Dockerfile`)) {
const stream = await docker.engine.buildImage(
{ src: ['.'], context: path },
{ t: `${configuration.build.container.name}:${configuration.build.container.tag}` }
);
await streamEvents(stream, configuration);
} else {
throw new Error('No custom dockerfile found.');
}
}

View File

@@ -1,28 +0,0 @@
import { docker, streamEvents } from '$lib/api/docker';
import { promises as fs } from 'fs';
import { buildImage } from '../helpers';
// 'HEALTHCHECK --timeout=10s --start-period=10s --interval=5s CMD curl -I -s -f http://localhost/ || exit 1',
const publishStaticDocker = (configuration) => {
return [
'FROM nginx:stable-alpine',
'COPY nginx.conf /etc/nginx/nginx.conf',
'WORKDIR /usr/share/nginx/html',
`COPY --from=${configuration.build.container.name}:${configuration.build.container.tag}-cache /usr/src/app/${configuration.publish.directory} ./`,
'EXPOSE 80',
'CMD ["nginx", "-g", "daemon off;"]'
].join('\n');
};
export default async function (configuration) {
await buildImage(configuration, true);
await fs.writeFile(
`${configuration.general.workdir}/Dockerfile`,
publishStaticDocker(configuration)
);
const stream = await docker.engine.buildImage(
{ src: ['.'], context: configuration.general.workdir },
{ t: `${configuration.build.container.name}:${configuration.build.container.tag}` }
);
await streamEvents(stream, configuration);
}

View File

@@ -1,43 +0,0 @@
import { docker, streamEvents } from '$lib/api/docker';
import { promises as fs } from 'fs';
const buildImageNodeDocker = (configuration, prodBuild, generateEnvs) => {
return [
'FROM node:lts',
...generateEnvs,
'WORKDIR /usr/src/app',
`COPY ${configuration.build.directory}/package*.json ./`,
configuration.build.command.installation && `RUN ${configuration.build.command.installation}`,
`COPY ./${configuration.build.directory} ./`,
`RUN ${configuration.build.command.build}`,
prodBuild && `RUN rm -fr node_modules && ${configuration.build.command.installation} --prod`
].join('\n');
};
export async function buildImage(configuration, cacheBuild?: boolean, prodBuild?: boolean) {
// TODO: Edit secrets
// TODO: Add secret from .env file / json
const generateEnvs = [];
const dotEnv = []
for (const secret of configuration.publish.secrets) {
dotEnv.push(`${secret.name}=${secret.value}`)
if (secret.isBuild) generateEnvs.push(`ENV ${secret.name}=${secret.value}`)
}
await fs.writeFile(
`${configuration.general.workdir}/.env`,
dotEnv.join('\n')
)
await fs.writeFile(
`${configuration.general.workdir}/Dockerfile`,
buildImageNodeDocker(configuration, prodBuild, generateEnvs)
);
const stream = await docker.engine.buildImage(
{ src: ['.'], context: configuration.general.workdir },
{
t: `${configuration.build.container.name}:${cacheBuild
? `${configuration.build.container.tag}-cache`
: configuration.build.container.tag
}`
}
);
await streamEvents(stream, configuration);
}

View File

@@ -1,31 +0,0 @@
import { docker, streamEvents } from '$lib/api/docker';
import { promises as fs } from 'fs';
import { buildImage } from '../helpers';
// `HEALTHCHECK --timeout=10s --start-period=10s --interval=5s CMD curl -I -s -f http://localhost:${configuration.publish.port}${configuration.publish.path} || exit 1`,
const publishNodejsDocker = (configuration) => {
return [
'FROM node:lts',
'WORKDIR /usr/src/app',
configuration.build.command.build
? `COPY --from=${configuration.build.container.name}:${configuration.build.container.tag} /usr/src/app/${configuration.publish.directory} ./`
: `
COPY ${configuration.build.directory}/package*.json ./
RUN ${configuration.build.command.installation}
COPY ./${configuration.build.directory} ./`,
`EXPOSE ${configuration.publish.port}`,
`CMD ${configuration.build.command.start}`
].join('\n');
};
export default async function (configuration) {
if (configuration.build.command.build) await buildImage(configuration, false, true);
await fs.writeFile(
`${configuration.general.workdir}/Dockerfile`,
publishNodejsDocker(configuration)
);
const stream = await docker.engine.buildImage(
{ src: ['.'], context: configuration.general.workdir },
{ t: `${configuration.build.container.name}:${configuration.build.container.tag}` }
);
await streamEvents(stream, configuration);
}

View File

@@ -1,30 +0,0 @@
import { docker, streamEvents } from '$lib/api/docker';
import { promises as fs } from 'fs';
import { buildImage } from '../helpers';
// `HEALTHCHECK --timeout=10s --start-period=10s --interval=5s CMD curl -I -s -f http://localhost:${configuration.publish.port}${configuration.publish.path} || exit 1`,
const publishNodejsDocker = (configuration) => {
return [
'FROM node:lts',
'WORKDIR /usr/src/app',
configuration.build.command.build
? `COPY --from=${configuration.build.container.name}:${configuration.build.container.tag} /usr/src/app/${configuration.publish.directory} ./`
: `
COPY ${configuration.build.directory}/package*.json ./
RUN ${configuration.build.command.installation}
COPY ./${configuration.build.directory} ./`,
`EXPOSE ${configuration.publish.port}`,
`CMD ${configuration.build.command.start}`
].join('\n');
};
export default async function (configuration) {
await buildImage(configuration);
await fs.writeFile(
`${configuration.general.workdir}/Dockerfile`,
publishNodejsDocker(configuration)
);
const stream = await docker.engine.buildImage(
{ src: ['.'], context: configuration.general.workdir },
{ t: `${configuration.build.container.name}:${configuration.build.container.tag}` }
);
await streamEvents(stream, configuration);
}

View File

@@ -1,31 +0,0 @@
import { docker, streamEvents } from '$lib/api/docker';
import { promises as fs } from 'fs';
import { buildImage } from '../helpers';
// `HEALTHCHECK --timeout=10s --start-period=10s --interval=5s CMD curl -I -s -f http://localhost:${configuration.publish.port}${configuration.publish.path} || exit 1`,
const publishNodejsDocker = (configuration) => {
return [
'FROM node:lts',
'WORKDIR /usr/src/app',
configuration.build.command.build
? `COPY --from=${configuration.build.container.name}:${configuration.build.container.tag} /usr/src/app/${configuration.publish.directory} ./`
: `
COPY ${configuration.build.directory}/package*.json ./
RUN ${configuration.build.command.installation}
COPY ./${configuration.build.directory} ./`,
`EXPOSE ${configuration.publish.port}`,
`CMD ${configuration.build.command.start}`
].join('\n');
};
export default async function (configuration) {
if (configuration.build.command.build) await buildImage(configuration);
await fs.writeFile(
`${configuration.general.workdir}/Dockerfile`,
publishNodejsDocker(configuration)
);
const stream = await docker.engine.buildImage(
{ src: ['.'], context: configuration.general.workdir },
{ t: `${configuration.build.container.name}:${configuration.build.container.tag}` }
);
await streamEvents(stream, configuration);
}

View File

@@ -1,31 +0,0 @@
import { docker, streamEvents } from '$lib/api/docker';
import { promises as fs } from 'fs';
import { buildImage } from '../helpers';
// `HEALTHCHECK --timeout=10s --start-period=10s --interval=5s CMD curl -I -s -f http://localhost:${configuration.publish.port}${configuration.publish.path} || exit 1`,
const publishNodejsDocker = (configuration) => {
return [
'FROM node:lts',
'WORKDIR /usr/src/app',
configuration.build.command.build
? `COPY --from=${configuration.build.container.name}:${configuration.build.container.tag} /usr/src/app/${configuration.publish.directory} ./`
: `
COPY ${configuration.build.directory}/package*.json ./
RUN ${configuration.build.command.installation}
COPY ./${configuration.build.directory} ./`,
`EXPOSE ${configuration.publish.port}`,
`CMD ${configuration.build.command.start}`
].join('\n');
};
export default async function (configuration) {
await buildImage(configuration);
await fs.writeFile(
`${configuration.general.workdir}/Dockerfile`,
publishNodejsDocker(configuration)
);
const stream = await docker.engine.buildImage(
{ src: ['.'], context: configuration.general.workdir },
{ t: `${configuration.build.container.name}:${configuration.build.container.tag}` }
);
await streamEvents(stream, configuration);
}

View File

@@ -1,25 +0,0 @@
import { docker, streamEvents } from '$lib/api/docker';
import { promises as fs } from 'fs';
// 'HEALTHCHECK --timeout=10s --start-period=10s --interval=5s CMD curl -I -s -f http://localhost/ || exit 1',
const publishPHPDocker = (configuration) => {
return [
'FROM php:apache',
'RUN a2enmod rewrite',
'WORKDIR /usr/src/app',
`COPY ./${configuration.build.directory} /var/www/html`,
'EXPOSE 80',
'CMD ["apache2-foreground"]'
].join('\n');
};
export default async function (configuration) {
await fs.writeFile(
`${configuration.general.workdir}/Dockerfile`,
publishPHPDocker(configuration)
);
const stream = await docker.engine.buildImage(
{ src: ['.'], context: configuration.general.workdir },
{ t: `${configuration.build.container.name}:${configuration.build.container.tag}` }
);
await streamEvents(stream, configuration);
}

View File

@@ -1,24 +0,0 @@
import { docker, streamEvents } from '$lib/api/docker';
import { promises as fs } from 'fs';
// `HEALTHCHECK --timeout=10s --start-period=10s --interval=5s CMD curl -I -s -f http://localhost:${configuration.publish.port}${configuration.publish.path} || exit 1`,
const publishPython = (configuration) => {
return [
'FROM python:3-alpine',
'WORKDIR /usr/src/app',
'RUN pip install gunicorn',
`COPY ./${configuration.build.directory}/requirements.txt ./`,
`RUN pip install --no-cache-dir -r ./${configuration.build.directory}/requirements.txt`,
`COPY ./${configuration.build.directory}/ .`,
`EXPOSE ${configuration.publish.port}`,
`CMD gunicorn -w=4 ${configuration.build.command.python.module}:${configuration.build.command.python.instance}`
].join('\n');
};
export default async function (configuration) {
await fs.writeFile(`${configuration.general.workdir}/Dockerfile`, publishPython(configuration));
const stream = await docker.engine.buildImage(
{ src: ['.'], context: configuration.general.workdir },
{ t: `${configuration.build.container.name}:${configuration.build.container.tag}` }
);
await streamEvents(stream, configuration);
}

View File

@@ -1,28 +0,0 @@
import { docker, streamEvents } from '$lib/api/docker';
import { promises as fs } from 'fs';
import { buildImage } from '../helpers';
// 'HEALTHCHECK --timeout=10s --start-period=10s --interval=5s CMD curl -I -s -f http://localhost/ || exit 1',
const publishStaticDocker = (configuration) => {
return [
'FROM nginx:stable-alpine',
'COPY nginx.conf /etc/nginx/nginx.conf',
'WORKDIR /usr/share/nginx/html',
`COPY --from=${configuration.build.container.name}:${configuration.build.container.tag}-cache /usr/src/app/${configuration.publish.directory} ./`,
'EXPOSE 80',
'CMD ["nginx", "-g", "daemon off;"]'
].join('\n');
};
export default async function (configuration) {
await buildImage(configuration, true);
await fs.writeFile(
`${configuration.general.workdir}/Dockerfile`,
publishStaticDocker(configuration)
);
const stream = await docker.engine.buildImage(
{ src: ['.'], context: configuration.general.workdir },
{ t: `${configuration.build.container.name}:${configuration.build.container.tag}` }
);
await streamEvents(stream, configuration);
}

View File

@@ -1,66 +0,0 @@
import { docker, streamEvents } from '$lib/api/docker';
import { promises as fs } from 'fs';
import TOML from '@iarna/toml';
import { execShellAsync } from '$lib/api/common';
const publishRustDocker = (configuration, custom) => {
return [
'FROM rust:latest',
'WORKDIR /app',
`COPY --from=${configuration.build.container.name}:cache /app/target target`,
`COPY --from=${configuration.build.container.name}:cache /usr/local/cargo /usr/local/cargo`,
'COPY . .',
`RUN cargo build --release --bin ${custom.name}`,
'FROM debian:buster-slim',
'WORKDIR /app',
'RUN apt-get update -y && apt-get install -y --no-install-recommends openssl libcurl4 ca-certificates && apt-get autoremove -y && apt-get clean -y && rm -rf /var/lib/apt/lists/*',
'RUN update-ca-certificates',
`COPY --from=${configuration.build.container.name}:cache /app/target/release/${custom.name} ${custom.name}`,
`EXPOSE ${configuration.publish.port}`,
`CMD ["/app/${custom.name}"]`
].join('\n');
};
const cacheRustDocker = (configuration, custom) => {
return [
`FROM rust:latest AS planner-${configuration.build.container.name}`,
'WORKDIR /app',
'RUN cargo install cargo-chef',
'COPY . .',
'RUN cargo chef prepare --recipe-path recipe.json',
'FROM rust:latest',
'WORKDIR /app',
'RUN cargo install cargo-chef',
`COPY --from=planner-${configuration.build.container.name} /app/recipe.json recipe.json`,
'RUN cargo chef cook --release --recipe-path recipe.json'
].join('\n');
};
export default async function (configuration) {
const cargoToml = await execShellAsync(`cat ${configuration.general.workdir}/Cargo.toml`);
const parsedToml = TOML.parse(cargoToml);
const custom = {
name: parsedToml.package.name
};
await fs.writeFile(
`${configuration.general.workdir}/Dockerfile`,
cacheRustDocker(configuration, custom)
);
let stream = await docker.engine.buildImage(
{ src: ['.'], context: configuration.general.workdir },
{ t: `${configuration.build.container.name}:cache` }
);
await streamEvents(stream, configuration);
await fs.writeFile(
`${configuration.general.workdir}/Dockerfile`,
publishRustDocker(configuration, custom)
);
stream = await docker.engine.buildImage(
{ src: ['.'], context: configuration.general.workdir },
{ t: `${configuration.build.container.name}:${configuration.build.container.tag}` }
);
await streamEvents(stream, configuration);
}

View File

@@ -1,30 +0,0 @@
import { docker, streamEvents } from '$lib/api/docker';
import { promises as fs } from 'fs';
import { buildImage } from '../helpers';
// 'HEALTHCHECK --timeout=10s --start-period=10s --interval=5s CMD curl -I -s -f http://localhost/ || exit 1',
const publishStaticDocker = (configuration) => {
return [
'FROM nginx:stable-alpine',
'COPY nginx.conf /etc/nginx/nginx.conf',
'WORKDIR /usr/share/nginx/html',
configuration.build.command.build
? `COPY --from=${configuration.build.container.name}:${configuration.build.container.tag}-cache /usr/src/app/${configuration.publish.directory} ./`
: `COPY ./${configuration.build.directory} ./`,
'EXPOSE 80',
'CMD ["nginx", "-g", "daemon off;"]'
].join('\n');
};
export default async function (configuration) {
if (configuration.build.command.build) await buildImage(configuration, true);
await fs.writeFile(
`${configuration.general.workdir}/Dockerfile`,
publishStaticDocker(configuration)
);
const stream = await docker.engine.buildImage(
{ src: ['.'], context: configuration.general.workdir },
{ t: `${configuration.build.container.name}:${configuration.build.container.tag}` }
);
await streamEvents(stream, configuration);
}

View File

@@ -1,28 +0,0 @@
import { docker, streamEvents } from '$lib/api/docker';
import { promises as fs } from 'fs';
import { buildImage } from '../helpers';
// 'HEALTHCHECK --timeout=10s --start-period=10s --interval=5s CMD curl -I -s -f http://localhost/ || exit 1',
const publishStaticDocker = (configuration) => {
return [
'FROM nginx:stable-alpine',
'COPY nginx.conf /etc/nginx/nginx.conf',
'WORKDIR /usr/share/nginx/html',
`COPY --from=${configuration.build.container.name}:${configuration.build.container.tag}-cache /usr/src/app/${configuration.publish.directory} ./`,
'EXPOSE 80',
'CMD ["nginx", "-g", "daemon off;"]'
].join('\n');
};
export default async function (configuration) {
await buildImage(configuration, true);
await fs.writeFile(
`${configuration.general.workdir}/Dockerfile`,
publishStaticDocker(configuration)
);
const stream = await docker.engine.buildImage(
{ src: ['.'], context: configuration.general.workdir },
{ t: `${configuration.build.container.name}:${configuration.build.container.tag}` }
);
await streamEvents(stream, configuration);
}

View File

@@ -1,66 +0,0 @@
const defaultBuildAndDeploy = {
installation: 'yarn install',
build: 'yarn build',
start: 'yarn start'
};
const templates = {
svelte: {
pack: 'svelte',
...defaultBuildAndDeploy,
directory: 'public',
name: 'Svelte'
},
'@nestjs/core': {
pack: 'nestjs',
...defaultBuildAndDeploy,
start: 'yarn start:prod',
port: 3000,
name: 'NestJS'
},
next: {
pack: 'nextjs',
...defaultBuildAndDeploy,
port: 3000,
name: 'NextJS'
},
nuxt: {
pack: 'nuxtjs',
...defaultBuildAndDeploy,
port: 3000,
name: 'NuxtJS'
},
'react-scripts': {
pack: 'react',
...defaultBuildAndDeploy,
directory: 'build',
name: 'React'
},
'parcel-bundler': {
pack: 'static',
...defaultBuildAndDeploy,
directory: 'dist',
name: 'Parcel'
},
'@vue/cli-service': {
pack: 'vuejs',
...defaultBuildAndDeploy,
directory: 'dist',
port: 80,
name: 'Vue'
},
gatsby: {
pack: 'gatsby',
...defaultBuildAndDeploy,
directory: 'public',
name: 'Gatsby'
},
'preact-cli': {
pack: 'react',
...defaultBuildAndDeploy,
directory: 'build',
name: 'Preact'
}
};
export default templates;

View File

@@ -1,28 +0,0 @@
import { docker, streamEvents } from '$lib/api/docker';
import { promises as fs } from 'fs';
import { buildImage } from '../helpers';
// 'HEALTHCHECK --timeout=10s --start-period=10s --interval=5s CMD curl -I -s -f http://localhost/ || exit 1',
const publishStaticDocker = (configuration) => {
return [
'FROM nginx:stable-alpine',
'COPY nginx.conf /etc/nginx/nginx.conf',
'WORKDIR /usr/share/nginx/html',
`COPY --from=${configuration.build.container.name}:${configuration.build.container.tag}-cache /usr/src/app/${configuration.publish.directory} ./`,
'EXPOSE 80',
'CMD ["nginx", "-g", "daemon off;"]'
].join('\n');
};
export default async function (configuration) {
await buildImage(configuration, true);
await fs.writeFile(
`${configuration.general.workdir}/Dockerfile`,
publishStaticDocker(configuration)
);
const stream = await docker.engine.buildImage(
{ src: ['.'], context: configuration.general.workdir },
{ t: `${configuration.build.container.name}:${configuration.build.container.tag}` }
);
await streamEvents(stream, configuration);
}

View File

@@ -1,76 +0,0 @@
import Configuration from "$models/Configuration";
import { compareObjects, execShellAsync } from "../common";
export default async function (configuration) {
/*
0 => nothing changed, no need to redeploy
1 => force update
2 => configuration changed
3 => continue normally
*/
const currentConfiguration = await Configuration.findOne({
'general.nickname': configuration.general.nickname
})
if (currentConfiguration) {
// Base service configuration changed
if (
!currentConfiguration.build.container.baseSHA ||
currentConfiguration.build.container.baseSHA !== configuration.build.container.baseSHA
) {
return 1
}
// If the deployment is in error state, forceUpdate
try {
const state = await execShellAsync(
`docker stack ps ${currentConfiguration.build.container.name} --format '{{ json . }}'`
);
const isError = state
.split('\n')
.filter((n) => n)
.map((s) => JSON.parse(s))
.filter(
(n) =>
n.DesiredState !== 'Running' && n.Image.split(':')[1] === currentConfiguration.build.container.tag
);
if (isError.length > 0) {
return 1
}
} catch(error) {
console.log(error)
}
// If previewDeployments enabled
if (
currentConfiguration.general.isPreviewDeploymentEnabled &&
currentConfiguration.general.pullRequest !== 0
) {
return 1
}
// If build pack changed, forceUpdate the service
if (currentConfiguration.build.pack !== configuration.build.pack) {
return 1
}
const currentConfigurationCompare = JSON.parse(JSON.stringify(currentConfiguration));
const configurationCompare = JSON.parse(JSON.stringify(configuration));
delete currentConfigurationCompare.build.container;
delete configurationCompare.build.container;
if (
!compareObjects(currentConfigurationCompare.build, configurationCompare.build) ||
!compareObjects(currentConfigurationCompare.publish, configurationCompare.publish) ||
currentConfigurationCompare.general.isPreviewDeploymentEnabled !==
configurationCompare.general.isPreviewDeploymentEnabled
) {
return 1
}
if (currentConfiguration.build.container.tag !== configuration.build.container.tag) {
return 2
}
return 0
}
return 3
}

View File

@@ -1,44 +0,0 @@
import Configuration from "$models/Configuration";
import Deployment from "$models/Deployment";
export default async function (configuration) {
// Check if deployment is already queued
const alreadyQueued = await Deployment.find({
path: configuration.publish.path,
domain: configuration.publish.domain,
progress: { $in: ['queued', 'inprogress'] }
});
if (alreadyQueued.length > 0) {
return {
status: 200,
body: {
success: false,
message: 'Deployment already queued.'
}
};
}
const { id, organization, name, branch } = configuration.repository;
const { domain, path } = configuration.publish;
const { deployId, nickname } = configuration.general;
// Save new deployment
await new Deployment({
repoId: id,
branch,
deployId,
domain,
organization,
name,
nickname
}).save();
await Configuration.findOneAndUpdate(
{
'publish.domain': domain,
'publish.path': path,
'general.pullRequest': { $in: [null, 0] }
},
{ ...configuration },
{ upsert: true, new: true }
);
return
}

View File

@@ -1,32 +0,0 @@
import Deployment from '$models/Deployment';
import dayjs from 'dayjs';
import buildContainer from './buildContainer';
import { purgeImagesContainers } from './cleanup';
import { updateServiceLabels } from './configuration';
import copyFiles from './copyFiles';
import deploy from './deploy';
import { saveAppLog } from './logging';
export default async function (configuration, nextStep) {
const { id, organization, name, branch } = configuration.repository;
const { domain } = configuration.publish;
const { deployId } = configuration.general;
try {
await saveAppLog(`### Successfully queued.`, configuration);
await copyFiles(configuration);
await buildContainer(configuration);
await deploy(configuration, nextStep);
await Deployment.findOneAndUpdate(
{ repoId: id, branch, deployId, organization, name, domain },
{ repoId: id, branch, deployId, organization, name, domain, progress: 'done' }
);
await updateServiceLabels(configuration);
await purgeImagesContainers(configuration);
} catch (error) {
await Deployment.findOneAndUpdate(
{ repoId: id, branch, deployId, organization, name, domain },
{ repoId: id, branch, deployId, organization, name, domain, progress: 'failed' }
);
}
}

View File

@@ -1,72 +0,0 @@
import shell from 'shelljs';
import User from '$models/User';
import jsonwebtoken from 'jsonwebtoken';
import { saveServerLog } from './applications/logging';
export function execShellAsync(cmd, opts = {}) {
try {
return new Promise(function (resolve, reject) {
shell.config.silent = true;
shell.exec(cmd, opts, async function (code, stdout, stderr) {
if (code !== 0) {
await saveServerLog({ message: JSON.stringify({ cmd, opts, code, stdout, stderr }) });
return reject(new Error(stderr));
}
return resolve(stdout);
});
});
} catch (error) {
return new Error('Oops');
}
}
export function cleanupTmp(dir) {
if (dir !== '/') shell.rm('-fr', dir);
}
export async function verifyUserId(token) {
const { JWT_SIGN_KEY } = process.env;
try {
const verify = jsonwebtoken.verify(token, JWT_SIGN_KEY);
const found = await User.findOne({ uid: verify.jti });
if (found) {
return Promise.resolve(true);
} else {
return Promise.reject(false);
}
} catch (error) {
console.log(error);
return Promise.reject(false);
}
}
export function delay(t) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve('OK');
}, t);
});
}
export function compareObjects(a, b) {
if (a === b) return true;
if (typeof a != 'object' || typeof b != 'object' || a == null || b == null) return false;
const keysA = Object.keys(a),
keysB = Object.keys(b);
if (keysA.length != keysB.length) return false;
for (const key of keysA) {
if (!keysB.includes(key)) return false;
if (typeof a[key] === 'function' || typeof b[key] === 'function') {
if (a[key].toString() != b[key].toString()) return false;
} else {
if (!compareObjects(a[key], b[key])) return false;
}
}
return true;
};

View File

@@ -1,27 +0,0 @@
import Dockerode from 'dockerode';
import { saveAppLog } from './applications/logging';
const { DOCKER_ENGINE, DOCKER_NETWORK } = process.env;
export const docker = {
engine: new Dockerode({
socketPath: DOCKER_ENGINE
}),
network: DOCKER_NETWORK
};
export async function streamEvents(stream, configuration) {
await new Promise((resolve, reject) => {
docker.engine.modem.followProgress(stream, onFinished, onProgress);
function onFinished(err, res) {
if (err) reject(err);
resolve(res);
}
function onProgress(event) {
if (event.error) {
saveAppLog(event.error, configuration, true);
reject(event.error);
} else if (event.stream) {
saveAppLog(event.stream, configuration);
}
}
});
}

View File

@@ -1,23 +0,0 @@
import type { Request } from '@sveltejs/kit';
export async function githubAPI(
request: Request,
resource: string,
token?: string,
data?: Record<string, unknown>
) {
const base = 'https://api.github.com';
const res = await fetch(`${base}${resource}`, {
method: request.method,
headers: {
'content-type': 'application/json',
accept: 'application/json',
authorization: token ? `token ${token}` : ''
},
body: data && JSON.stringify(data)
});
return {
status: res.status,
body: await res.json()
};
}

View File

@@ -0,0 +1,191 @@
import { base64Encode } from '$lib/crypto';
import { getDomain, saveBuildLog, version } from '$lib/common';
import * as db from '$lib/database';
import { scanningTemplates } from '$lib/components/templates';
import { promises as fs } from 'fs';
import { staticDeployments } from '$lib/components/common';
export function makeLabelForStandaloneApplication({
applicationId,
fqdn,
name,
type,
pullmergeRequestId = null,
buildPack,
repository,
branch,
projectId,
port,
commit,
installCommand,
buildCommand,
startCommand,
baseDirectory,
publishDirectory
}) {
if (pullmergeRequestId) {
const protocol = fqdn.startsWith('https://') ? 'https' : 'http';
const domain = getDomain(fqdn);
fqdn = `${protocol}://${pullmergeRequestId}.${domain}`;
}
return [
'--label coolify.managed=true',
`--label coolify.version=${version}`,
`--label coolify.type=standalone-application`,
`--label coolify.configuration=${base64Encode(
JSON.stringify({
applicationId,
fqdn,
name,
type,
pullmergeRequestId,
buildPack,
repository,
branch,
projectId,
port,
commit,
installCommand,
buildCommand,
startCommand,
baseDirectory,
publishDirectory
})
)}`
];
}
export async function makeLabelForStandaloneDatabase({ id, image, volume }) {
const database = await db.prisma.database.findFirst({ where: { id } });
delete database.destinationDockerId;
delete database.createdAt;
delete database.updatedAt;
return [
'coolify.managed=true',
`coolify.version=${version}`,
`coolify.type=standalone-database`,
`coolify.configuration=${base64Encode(
JSON.stringify({
version,
image,
volume,
...database
})
)}`
];
}
export async function makeLabelForPlausibleAnalytics({ id, images, volume }) {
const service = await db.prisma.service.findFirst({
where: { id },
include: { plausibleAnalytics: true }
});
delete service.destinationDockerId;
delete service.createdAt;
delete service.updatedAt;
return [
'coolify.managed=true',
`coolify.version=${version}`,
`coolify.type=service-plausibleanalytics`,
`coolify.configuration=${base64Encode(
JSON.stringify({
version,
images,
volume,
...service
})
)}`
];
}
export const setDefaultConfiguration = async (data) => {
let { buildPack, port, installCommand, startCommand, buildCommand, publishDirectory } = data;
const template = scanningTemplates[buildPack];
if (!port) {
port = template?.port || 3000;
if (buildPack === 'static') port = 80;
else if (buildPack === 'node') port = 3000;
else if (buildPack === 'php') port = 80;
}
if (!installCommand) installCommand = template?.installCommand || 'yarn install';
if (!startCommand) startCommand = template?.startCommand || 'yarn start';
if (!buildCommand) buildCommand = template?.buildCommand || null;
if (!publishDirectory) publishDirectory = template?.publishDirectory || null;
return {
buildPack,
port,
installCommand,
startCommand,
buildCommand,
publishDirectory
};
};
export async function copyBaseConfigurationFiles(buildPack, workdir, buildId, applicationId) {
try {
// TODO: Write full .dockerignore for all deployments!!
if (buildPack === 'php') {
await fs.writeFile(
`${workdir}/.htaccess`,
`
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php [QSA,L]
`
);
saveBuildLog({ line: 'Copied default configuration file for PHP.', buildId, applicationId });
} else if (staticDeployments.includes(buildPack)) {
await fs.writeFile(
`${workdir}/nginx.conf`,
`user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
access_log off;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html;
try_files $uri $uri/index.html $uri/ /index.html =404;
}
error_page 404 /50x.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
`
);
saveBuildLog({ line: 'Copied default configuration file.', buildId, applicationId });
}
} catch (error) {
console.log(error);
throw new Error(error);
}
}

View File

@@ -0,0 +1,36 @@
import { buildImage } from '$lib/docker';
import { promises as fs } from 'fs';
export default async function ({
applicationId,
debug,
tag,
workdir,
docker,
buildId,
baseDirectory,
secrets
}) {
try {
let file = `${workdir}/Dockerfile`;
if (baseDirectory) {
file = `${workdir}/${baseDirectory}/Dockerfile`;
}
const Dockerfile: Array<string> = (await fs.readFile(`${file}`, 'utf8'))
.toString()
.trim()
.split('\n');
if (secrets.length > 0) {
secrets.forEach((secret) => {
if (secret.isBuildSecret) {
Dockerfile.push(`ARG ${secret.name} ${secret.value}`);
}
});
}
await fs.writeFile(`${file}`, Dockerfile.join('\n'));
await buildImage({ applicationId, tag, workdir, docker, buildId, debug });
} catch (error) {
throw error;
}
}

View File

@@ -0,0 +1,27 @@
import { buildCacheImageWithNode, buildImage } from '$lib/docker';
import { promises as fs } from 'fs';
const createDockerfile = async (data, imageforBuild): Promise<void> => {
const { applicationId, tag, workdir, publishDirectory } = data;
const Dockerfile: Array<string> = [];
Dockerfile.push(`FROM ${imageforBuild}`);
Dockerfile.push('WORKDIR /usr/share/nginx/html');
Dockerfile.push(`COPY --from=${applicationId}:${tag}-cache /usr/src/app/${publishDirectory} ./`);
Dockerfile.push(`EXPOSE 80`);
Dockerfile.push('CMD ["nginx", "-g", "daemon off;"]');
await fs.writeFile(`${workdir}/Dockerfile`, Dockerfile.join('\n'));
};
export default async function (data) {
try {
const image = 'nginx:stable-alpine';
const imageForBuild = 'node:lts';
await buildCacheImageWithNode(data, imageForBuild);
await createDockerfile(data, image);
await buildImage(data);
} catch (error) {
throw error;
}
}

View File

@@ -1,29 +1,27 @@
import vuejs from './vuejs';
import svelte from './svelte';
import Static from './static';
import rust from './rust';
import react from './react';
import php from './php';
import nuxtjs from './nuxtjs';
import nodejs from './nodejs';
import nextjs from './nextjs';
import nestjs from './nestjs';
import gatsby from './gatsby';
import node from './node';
import staticApp from './static';
import docker from './docker';
import python from './python';
import gatsby from './gatsby';
import svelte from './svelte';
import react from './react';
import nestjs from './nestjs';
import nextjs from './nextjs';
import nuxtjs from './nuxtjs';
import vuejs from './vuejs';
import php from './php';
import rust from './rust';
export {
vuejs,
svelte,
Static as static,
rust,
react,
php,
nuxtjs,
nodejs,
nextjs,
nestjs,
gatsby,
node,
staticApp as static,
docker,
python
gatsby,
svelte,
react,
nestjs,
nextjs,
nuxtjs,
vuejs,
php,
rust
};

View File

@@ -0,0 +1,29 @@
import { buildCacheImageWithNode, buildImage } from '$lib/docker';
import { promises as fs } from 'fs';
const createDockerfile = async (data, image): Promise<void> => {
const { applicationId, tag, port, startCommand, workdir, baseDirectory } = data;
const Dockerfile: Array<string> = [];
Dockerfile.push(`FROM ${image}`);
Dockerfile.push('WORKDIR /usr/src/app');
Dockerfile.push(
`COPY --from=${applicationId}:${tag}-cache /usr/src/app/${baseDirectory || ''} ./`
);
Dockerfile.push(`EXPOSE ${port}`);
Dockerfile.push(`CMD ${startCommand}`);
await fs.writeFile(`${workdir}/Dockerfile`, Dockerfile.join('\n'));
};
export default async function (data) {
try {
const image = 'node:lts';
const imageForBuild = 'node:lts';
await buildCacheImageWithNode(data, imageForBuild);
await createDockerfile(data, image);
await buildImage(data);
} catch (error) {
throw error;
}
}

View File

@@ -0,0 +1,45 @@
import { buildImage } from '$lib/docker';
import { promises as fs } from 'fs';
const createDockerfile = async (data, image): Promise<void> => {
const { workdir, port, installCommand, buildCommand, startCommand, baseDirectory, secrets } =
data;
const Dockerfile: Array<string> = [];
Dockerfile.push(`FROM ${image}`);
Dockerfile.push('WORKDIR /usr/src/app');
if (secrets.length > 0) {
secrets.forEach((secret) => {
if (secret.isBuildSecret) {
Dockerfile.push(`ARG ${secret.name} ${secret.value}`);
}
});
}
Dockerfile.push(`COPY ./${baseDirectory || ''}package*.json ./`);
try {
await fs.stat(`${workdir}/yarn.lock`);
Dockerfile.push(`COPY ./${baseDirectory || ''}yarn.lock ./`);
} catch (error) {}
try {
await fs.stat(`${workdir}/pnpm-lock.yaml`);
Dockerfile.push(`COPY ./${baseDirectory || ''}pnpm-lock.yaml ./`);
} catch (error) {}
Dockerfile.push(`RUN ${installCommand}`);
Dockerfile.push(`COPY ./${baseDirectory || ''} ./`);
if (buildCommand) {
Dockerfile.push(`RUN ${buildCommand}`);
}
Dockerfile.push(`EXPOSE ${port}`);
Dockerfile.push(`CMD ${startCommand}`);
await fs.writeFile(`${workdir}/Dockerfile`, Dockerfile.join('\n'));
};
export default async function (data) {
try {
const image = 'node:lts';
await createDockerfile(data, image);
await buildImage(data);
} catch (error) {
throw error;
}
}

View File

@@ -0,0 +1,45 @@
import { buildImage } from '$lib/docker';
import { promises as fs } from 'fs';
const createDockerfile = async (data, image): Promise<void> => {
const { workdir, port, installCommand, buildCommand, startCommand, baseDirectory, secrets } =
data;
const Dockerfile: Array<string> = [];
Dockerfile.push(`FROM ${image}`);
Dockerfile.push('WORKDIR /usr/src/app');
if (secrets.length > 0) {
secrets.forEach((secret) => {
if (secret.isBuildSecret) {
Dockerfile.push(`ARG ${secret.name} ${secret.value}`);
}
});
}
Dockerfile.push(`COPY ./${baseDirectory || ''}package*.json ./`);
try {
await fs.stat(`${workdir}/yarn.lock`);
Dockerfile.push(`COPY ./${baseDirectory || ''}yarn.lock ./`);
} catch (error) {}
try {
await fs.stat(`${workdir}/pnpm-lock.yaml`);
Dockerfile.push(`COPY ./${baseDirectory || ''}pnpm-lock.yaml ./`);
} catch (error) {}
Dockerfile.push(`RUN ${installCommand}`);
Dockerfile.push(`COPY ./${baseDirectory || ''} ./`);
if (buildCommand) {
Dockerfile.push(`RUN ${buildCommand}`);
}
Dockerfile.push(`EXPOSE ${port}`);
Dockerfile.push(`CMD ${startCommand}`);
await fs.writeFile(`${workdir}/Dockerfile`, Dockerfile.join('\n'));
};
export default async function (data) {
try {
const image = 'node:lts';
await createDockerfile(data, image);
await buildImage(data);
} catch (error) {
throw error;
}
}

View File

@@ -0,0 +1,45 @@
import { buildImage } from '$lib/docker';
import { promises as fs } from 'fs';
const createDockerfile = async (data, image): Promise<void> => {
const { workdir, port, installCommand, buildCommand, startCommand, baseDirectory, secrets } =
data;
const Dockerfile: Array<string> = [];
Dockerfile.push(`FROM ${image}`);
Dockerfile.push('WORKDIR /usr/src/app');
if (secrets.length > 0) {
secrets.forEach((secret) => {
if (secret.isBuildSecret) {
Dockerfile.push(`ARG ${secret.name} ${secret.value}`);
}
});
}
Dockerfile.push(`COPY ./${baseDirectory || ''}package*.json ./`);
try {
await fs.stat(`${workdir}/yarn.lock`);
Dockerfile.push(`COPY ./${baseDirectory || ''}yarn.lock ./`);
} catch (error) {}
try {
await fs.stat(`${workdir}/pnpm-lock.yaml`);
Dockerfile.push(`COPY ./${baseDirectory || ''}pnpm-lock.yaml ./`);
} catch (error) {}
Dockerfile.push(`RUN ${installCommand}`);
Dockerfile.push(`COPY ./${baseDirectory || ''} ./`);
if (buildCommand) {
Dockerfile.push(`RUN ${buildCommand}`);
}
Dockerfile.push(`EXPOSE ${port}`);
Dockerfile.push(`CMD ${startCommand}`);
await fs.writeFile(`${workdir}/Dockerfile`, Dockerfile.join('\n'));
};
export default async function (data) {
try {
const image = 'node:lts';
await createDockerfile(data, image);
await buildImage(data);
} catch (error) {
throw error;
}
}

25
src/lib/buildPacks/php.ts Normal file
View File

@@ -0,0 +1,25 @@
import { buildImage } from '$lib/docker';
import { promises as fs } from 'fs';
const createDockerfile = async (data, image): Promise<void> => {
const { workdir, baseDirectory } = data;
const Dockerfile: Array<string> = [];
Dockerfile.push(`FROM ${image}`);
Dockerfile.push('RUN a2enmod rewrite');
Dockerfile.push('WORKDIR /var/www/html');
Dockerfile.push(`COPY ./${baseDirectory || ''} /var/www/html`);
Dockerfile.push(`EXPOSE 80`);
Dockerfile.push('CMD ["apache2-foreground"]');
await fs.writeFile(`${workdir}/Dockerfile`, Dockerfile.join('\n'));
};
export default async function (data) {
try {
const image = 'php:apache';
await createDockerfile(data, image);
await buildImage(data);
} catch (error) {
throw error;
}
}

View File

@@ -0,0 +1,26 @@
import { buildCacheImageWithNode, buildImage } from '$lib/docker';
import { promises as fs } from 'fs';
const createDockerfile = async (data, image): Promise<void> => {
const { applicationId, tag, workdir, publishDirectory } = data;
const Dockerfile: Array<string> = [];
Dockerfile.push(`FROM ${image}`);
Dockerfile.push('WORKDIR /usr/share/nginx/html');
Dockerfile.push(`COPY --from=${applicationId}:${tag}-cache /usr/src/app/${publishDirectory} ./`);
Dockerfile.push(`EXPOSE 80`);
Dockerfile.push('CMD ["nginx", "-g", "daemon off;"]');
await fs.writeFile(`${workdir}/Dockerfile`, Dockerfile.join('\n'));
};
export default async function (data) {
try {
const image = 'nginx:stable-alpine';
const imageForBuild = 'node:lts';
await buildCacheImageWithNode(data, imageForBuild);
await createDockerfile(data, image);
await buildImage(data);
} catch (error) {
throw error;
}
}

View File

@@ -0,0 +1,43 @@
import { asyncExecShell } from '$lib/common';
import { buildCacheImageWithCargo, buildImage } from '$lib/docker';
import { promises as fs } from 'fs';
import TOML from '@iarna/toml';
const createDockerfile = async (data, image, name): Promise<void> => {
const { workdir, port, applicationId, tag } = data;
const Dockerfile: Array<string> = [];
Dockerfile.push(`FROM ${image}`);
Dockerfile.push('WORKDIR /usr/src/app');
Dockerfile.push(`COPY --from=${applicationId}:${tag}-cache /usr/src/app/target target`);
Dockerfile.push(`COPY --from=${applicationId}:${tag}-cache /usr/local/cargo /usr/local/cargo`);
Dockerfile.push(`COPY . .`);
Dockerfile.push(`RUN cargo build --release --bin ${name}`);
Dockerfile.push('FROM debian:buster-slim');
Dockerfile.push('WORKDIR /usr/src/app');
Dockerfile.push(
`RUN apt-get update -y && apt-get install -y --no-install-recommends openssl libcurl4 ca-certificates && apt-get autoremove -y && apt-get clean -y && rm -rf /var/lib/apt/lists/*`
);
Dockerfile.push(`RUN update-ca-certificates`);
Dockerfile.push(
`COPY --from=${applicationId}:${tag}-cache /usr/src/app/target/release/${name} ${name}`
);
Dockerfile.push(`EXPOSE ${port}`);
Dockerfile.push(`CMD ["/usr/src/app/${name}"]`);
await fs.writeFile(`${workdir}/Dockerfile`, Dockerfile.join('\n'));
};
export default async function (data) {
try {
const { workdir } = data;
const image = 'rust:latest';
const imageForBuild = 'rust:latest';
const { stdout: cargoToml } = await asyncExecShell(`cat ${workdir}/Cargo.toml`);
const parsedToml: any = TOML.parse(cargoToml);
const name = parsedToml.package.name;
await buildCacheImageWithCargo(data, imageForBuild);
await createDockerfile(data, image, name);
await buildImage(data);
} catch (error) {
throw error;
}
}

View File

@@ -0,0 +1,40 @@
import { buildCacheImageWithNode, buildImage } from '$lib/docker';
import { promises as fs } from 'fs';
const createDockerfile = async (data, image): Promise<void> => {
const { applicationId, tag, workdir, buildCommand, baseDirectory, publishDirectory, secrets } =
data;
const Dockerfile: Array<string> = [];
Dockerfile.push(`FROM ${image}`);
Dockerfile.push('WORKDIR /usr/share/nginx/html');
if (secrets.length > 0) {
secrets.forEach((secret) => {
if (secret.isBuildSecret) {
Dockerfile.push(`ARG ${secret.name} ${secret.value}`);
}
});
}
if (buildCommand) {
Dockerfile.push(
`COPY --from=${applicationId}:${tag}-cache /usr/src/app/${publishDirectory} ./`
);
} else {
Dockerfile.push(`COPY ./${baseDirectory || ''} ./`);
}
Dockerfile.push(`EXPOSE 80`);
Dockerfile.push('CMD ["nginx", "-g", "daemon off;"]');
await fs.writeFile(`${workdir}/Dockerfile`, Dockerfile.join('\n'));
};
export default async function (data) {
try {
const image = 'nginx:stable-alpine';
const imageForBuild = 'node:lts';
if (data.buildCommand) await buildCacheImageWithNode(data, imageForBuild);
await createDockerfile(data, image);
await buildImage(data);
} catch (error) {
throw error;
}
}

View File

@@ -0,0 +1,27 @@
import { buildCacheImageWithNode, buildImage } from '$lib/docker';
import { promises as fs } from 'fs';
const createDockerfile = async (data, image): Promise<void> => {
const { applicationId, tag, workdir, publishDirectory } = data;
const Dockerfile: Array<string> = [];
Dockerfile.push(`FROM ${image}`);
Dockerfile.push('WORKDIR /usr/share/nginx/html');
Dockerfile.push(`COPY --from=${applicationId}:${tag}-cache /usr/src/app/${publishDirectory} ./`);
Dockerfile.push(`EXPOSE 80`);
Dockerfile.push('CMD ["nginx", "-g", "daemon off;"]');
await fs.writeFile(`${workdir}/Dockerfile`, Dockerfile.join('\n'));
};
export default async function (data) {
try {
const image = 'nginx:stable-alpine';
const imageForBuild = 'node:lts';
await buildCacheImageWithNode(data, imageForBuild);
await createDockerfile(data, image);
await buildImage(data);
} catch (error) {
throw error;
}
}

View File

@@ -0,0 +1,26 @@
import { buildCacheImageWithNode, buildImage } from '$lib/docker';
import { promises as fs } from 'fs';
const createDockerfile = async (data, image): Promise<void> => {
const { applicationId, tag, workdir, publishDirectory } = data;
const Dockerfile: Array<string> = [];
Dockerfile.push(`FROM ${image}`);
Dockerfile.push('WORKDIR /usr/share/nginx/html');
Dockerfile.push(`COPY --from=${applicationId}:${tag}-cache /usr/src/app/${publishDirectory} ./`);
Dockerfile.push(`EXPOSE 80`);
Dockerfile.push('CMD ["nginx", "-g", "daemon off;"]');
await fs.writeFile(`${workdir}/Dockerfile`, Dockerfile.join('\n'));
};
export default async function (data) {
try {
const image = 'nginx:stable-alpine';
const imageForBuild = 'node:lts';
await buildCacheImageWithNode(data, imageForBuild);
await createDockerfile(data, image);
await buildImage(data);
} catch (error) {
throw error;
}
}

View File

@@ -1,9 +1,150 @@
export function dashify(str: string, options?: any) {
if (typeof str !== 'string') return str;
return str
.trim()
.replace(/\W/g, (m) => (/[À-ž]/.test(m) ? m : '-'))
.replace(/^-+|-+$/g, '')
.replace(/-{2,}/g, (m) => (options && options.condense ? '-' : m))
.toLowerCase();
}
import child from 'child_process';
import util from 'util';
import { dev } from '$app/env';
import * as Sentry from '@sentry/node';
import { uniqueNamesGenerator, Config, adjectives, colors, animals } from 'unique-names-generator';
import * as db from '$lib/database';
import { buildLogQueue } from './queues';
import { version as currentVersion } from '../../package.json';
import { dockerInstance } from './docker';
import dayjs from 'dayjs';
import Cookie from 'cookie';
try {
if (!dev) {
Sentry.init({
dsn: process.env['COOLIFY_SENTRY_DSN'],
tracesSampleRate: 0,
environment: 'production'
});
}
} catch (err) {
console.log('Could not initialize Sentry, no worries.');
}
const customConfig: Config = {
dictionaries: [adjectives, colors, animals],
style: 'capital',
separator: ' ',
length: 3
};
export const version = currentVersion;
export const asyncExecShell = util.promisify(child.exec);
export const asyncSleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));
export const sentry = Sentry;
export const uniqueName = () => uniqueNamesGenerator(customConfig);
export const saveBuildLog = async ({ line, buildId, applicationId }) => {
const addTimestamp = `${generateTimestamp()} ${line}`;
return await buildLogQueue.add(buildId, { buildId, line: addTimestamp, applicationId });
};
export const isTeamIdTokenAvailable = (request) => {
const cookie = request.headers.cookie
?.split(';')
.map((s) => s.trim())
.find((s) => s.startsWith('teamId='))
?.split('=')[1];
if (!cookie) {
return getTeam(request);
} else {
return cookie;
}
};
export const getTeam = (event) => {
const cookies: Cookies = Cookie.parse(event.request.headers.get('cookie'));
if (cookies.teamId) {
return cookies.teamId;
} else if (event.locals.session.data.teamId) {
return event.locals.session.data.teamId;
}
return null;
};
export const getUserDetails = async (event, isAdminRequired = true) => {
// try {
const teamId = getTeam(event);
const userId = event.locals.session.data.uid || null;
const { permission = 'read' } = await db.prisma.permission.findFirst({
where: { teamId, userId },
select: { permission: true },
rejectOnNotFound: true
});
const payload = {
teamId,
userId,
permission,
status: 200,
body: {
message: 'OK'
}
};
if (isAdminRequired && permission !== 'admin' && permission !== 'owner') {
payload.status = 401;
payload.body.message =
'You do not have permission to do this. \nAsk an admin to modify your permissions.';
}
return payload;
// } catch (err) {
// console.log(err);
// return {
// teamId: null,
// userId: null,
// permission: 'read',
// status: 401,
// body: {
// message: 'You do not have permission to do this. \nAsk an admin to modify your permissions.'
// }
// };
// }
};
export function getEngine(engine) {
return engine === '/var/run/docker.sock' ? 'unix:///var/run/docker.sock' : `tcp://${engine}:2375`;
}
export async function removeContainer(id, engine) {
const host = getEngine(engine);
try {
const { stdout } = await asyncExecShell(
`DOCKER_HOST=${host} docker inspect --format '{{json .State}}' ${id}`
);
if (JSON.parse(stdout).Running) {
await asyncExecShell(`DOCKER_HOST=${host} docker stop -t 0 ${id}`);
await asyncExecShell(`DOCKER_HOST=${host} docker rm ${id}`);
}
} catch (error) {
console.log(error);
throw error;
}
}
export const removeDestinationDocker = async ({ id, engine }) => {
return await removeContainer(id, engine);
};
export const createDirectories = async ({ repository, buildId }) => {
const repodir = `/tmp/build-sources/${repository}/`;
const workdir = `/tmp/build-sources/${repository}/${buildId}`;
await asyncExecShell(`mkdir -p ${workdir}`);
return {
workdir,
repodir
};
};
export function generateTimestamp() {
return `${dayjs().format('HH:mm:ss.SSS')} `;
}
export function getDomain(domain) {
return domain?.replace('https://', '').replace('http://', '');
}

View File

@@ -0,0 +1,148 @@
<script>
import { browser } from '$app/env';
import { toast } from '@zerodevx/svelte-toast';
export let value;
let showPassword = false;
export let disabled = false;
export let isPasswordField = false;
export let readonly = false;
export let textarea = false;
export let required = false;
export let pattern = null;
export let id;
export let name;
export let placeholder = '';
let disabledClass = 'bg-coolback disabled:bg-coolblack select-all';
let actionsShow = false;
let isHttps = browser && window.location.protocol === 'https:';
function showActions(value) {
actionsShow = value;
// if (value === false) {
// showPassword = false;
// }
}
function copyToClipboard() {
if (isHttps && navigator.clipboard) {
navigator.clipboard.writeText(value);
toast.push('Copied to clipboard');
}
}
</script>
<span
class="relative"
on:mouseenter={() => showActions(true)}
on:mouseleave={() => showActions(false)}
>
{#if !isPasswordField || showPassword}
{#if textarea}
<textarea
rows="3"
class={disabledClass}
{placeholder}
type="text"
{id}
{pattern}
{required}
{readonly}
{disabled}
{name}>{value}</textarea
>
{:else}
<input
class={disabledClass}
type="text"
{id}
{name}
{required}
{pattern}
{readonly}
bind:value
{disabled}
{placeholder}
/>
{/if}
{:else}
<input
class={disabledClass}
type="password"
{id}
{name}
{readonly}
{pattern}
{required}
bind:value
{disabled}
{placeholder}
/>
{/if}
{#if actionsShow}
<div class="absolute top-0 right-0 mx-2 cursor-pointer text-warmGray-600 hover:text-white">
<div class="flex space-x-2">
{#if isPasswordField}
<div on:click={() => (showPassword = !showPassword)}>
{#if showPassword}
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-6 w-6"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"
/>
</svg>
{:else}
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-6 w-6"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
/>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
/>
</svg>
{/if}
</div>
{/if}
{#if value && isHttps}
<div on:click={copyToClipboard}>
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-6 w-6"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
fill="none"
stroke-linecap="round"
stroke-linejoin="round"
>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<rect x="8" y="8" width="12" height="12" rx="2" />
<path d="M16 8v-2a2 2 0 0 0 -2 -2h-8a2 2 0 0 0 -2 2v8a2 2 0 0 0 2 2h2" />
</svg>
</div>
{/if}
</div>
</div>
{/if}
</span>

View File

@@ -0,0 +1,17 @@
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-6 w-6"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
fill="none"
stroke-linecap="round"
stroke-linejoin="round"
>
<path stroke="none" d="M0 0h24v24H0z" fill="none" />
<line x1="4" y1="7" x2="20" y2="7" />
<line x1="10" y1="11" x2="10" y2="17" />
<line x1="14" y1="11" x2="14" y2="17" />
<path d="M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2 -2l1 -12" />
<path d="M9 7v-3a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v3" />
</svg>

After

Width:  |  Height:  |  Size: 486 B

View File

@@ -0,0 +1,6 @@
<script>
export let text;
export let maxWidthClass = 'max-w-[24rem]';
</script>
<div class="py-1 text-xs text-stone-400 {maxWidthClass}">{@html text}</div>

View File

@@ -0,0 +1,67 @@
<script lang="ts">
export let fullscreen = true;
export let cover = false;
</script>
{#if fullscreen}
<div
class="main fixed left-0 top-0 flex h-full flex-wrap content-center"
class:bg-coolblack={cover}
>
<span class="loader" />
</div>
{:else}
<div class=" main h-64 py-24 left-0 top-0 flex flex-wrap content-center mx-auto">
<span class="loader" />
</div>
{/if}
<style lang="postcss">
.loader {
width: 8px;
height: 40px;
border-radius: 4px;
display: block;
margin: 20px auto;
position: relative;
background: currentColor;
color: #fff;
box-sizing: border-box;
animation: animloader 0.3s linear infinite alternate;
}
.loader::after,
.loader::before {
content: '';
width: 8px;
height: 4px;
border-radius: 4px;
background: currentColor;
position: absolute;
top: 50%;
transform: translateY(-50%);
left: 20px;
box-sizing: border-box;
animation: animloader2 0.3s linear infinite alternate;
}
.loader::before {
left: -20px;
animation-delay: 0s;
}
@keyframes animloader {
0% {
height: 48px;
}
100% {
height: 4px;
}
}
@keyframes animloader2 {
0% {
height: 4px;
}
100% {
height: 48px;
}
}
</style>

View File

@@ -0,0 +1,68 @@
<script lang="ts">
import Explainer from '$lib/components/Explainer.svelte';
export let setting;
export let title;
export let description;
export let isPadding = true;
export let disabled = false;
// export let disabledReason = '';
</script>
<li class="flex items-center py-4">
<div class="flex w-96 flex-col" class:px-4={isPadding} class:pr-32={!isPadding}>
<p class="text-xs font-bold text-stone-100 md:text-base">{title}</p>
<Explainer text={description} />
</div>
<!-- {#if disabled}
<div class="flex" class:px-4={isPadding} class:pr-32={!isPadding}>
<p class="text-xs font-bold text-stone-400">{disabledReason}</p>
</div>
{:else} -->
<div
type="button"
on:click
aria-pressed="false"
class="relative mx-20 inline-flex h-6 w-11 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out"
class:opacity-50={disabled}
class:bg-green-600={setting}
class:bg-stone-700={!setting}
>
<span class="sr-only">Use setting</span>
<span
class="pointer-events-none relative inline-block h-5 w-5 transform rounded-full bg-white shadow transition duration-200 ease-in-out"
class:translate-x-5={setting}
class:translate-x-0={!setting}
>
<span
class=" absolute inset-0 flex h-full w-full items-center justify-center transition-opacity duration-200 ease-in"
class:opacity-0={setting}
class:opacity-100={!setting}
aria-hidden="true"
>
<svg class="h-3 w-3 bg-white text-red-600" fill="none" viewBox="0 0 12 12">
<path
d="M4 8l2-2m0 0l2-2M6 6L4 4m2 2l2 2"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
</span>
<span
class="absolute inset-0 flex h-full w-full items-center justify-center transition-opacity duration-100 ease-out"
aria-hidden="true"
class:opacity-100={setting}
class:opacity-0={!setting}
>
<svg class="h-3 w-3 bg-white text-green-600" fill="currentColor" viewBox="0 0 12 12">
<path
d="M3.707 5.293a1 1 0 00-1.414 1.414l1.414-1.414zM5 8l-.707.707a1 1 0 001.414 0L5 8zm4.707-3.293a1 1 0 00-1.414-1.414l1.414 1.414zm-7.414 2l2 2 1.414-1.414-2-2-1.414 1.414zm3.414 2l4-4-1.414-1.414-4 4 1.414 1.414z"
/>
</svg>
</span>
</span>
</div>
<!-- {/if} -->
</li>

View File

@@ -0,0 +1,33 @@
export const asyncSleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));
export const dateOptions: DateTimeFormatOptions = {
year: 'numeric',
month: 'short',
day: '2-digit',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false
};
export async function getGithubToken({ apiUrl, application, githubToken }): Promise<void> {
const response = await fetch(
`${apiUrl}/app/installations/${application.gitSource.githubApp.installationId}/access_tokens`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${githubToken}`
}
}
);
if (!response.ok) {
throw new Error('Git Source not configured.');
}
const data = await response.json();
return data.token;
}
export const staticDeployments = ['react', 'vuejs', 'static', 'svelte', 'gatsby', 'php'];
export const notNodeDeployments = ['php', 'docker', 'rust'];
export function getDomain(domain) {
return domain?.replace('https://', '').replace('http://', '');
}

View File

@@ -0,0 +1,73 @@
<svg viewBox="0 0 128 128" class="absolute top-0 left-0 -m-8 h-16 w-16">
<g
><path
fill-rule="evenodd"
clip-rule="evenodd"
fill="#3A4D54"
d="M73.8 50.8h11.3v11.5h5.7c2.6 0 5.3-.5 7.8-1.3 1.2-.4 2.6-1 3.8-1.7-1.6-2.1-2.4-4.7-2.6-7.3-.3-3.5.4-8.1 2.8-10.8l1.2-1.4 1.4 1.1c3.6 2.9 6.5 6.8 7.1 11.4 4.3-1.3 9.3-1 13.1 1.2l1.5.9-.8 1.6c-3.2 6.2-9.9 8.2-16.4 7.8-9.8 24.3-31 35.8-56.8 35.8-13.3 0-25.5-5-32.5-16.8l-.1-.2-1-2.1c-2.4-5.2-3.1-10.9-2.6-16.6l.2-1.7h9.6v-11.4h11.3v-11.2h22.5v-11.3h13.5v22.5z"
/><path
fill="#00AADA"
d="M110.4 55.1c.8-5.9-3.6-10.5-6.4-12.7-3.1 3.6-3.6 13.2 1.3 17.2-2.8 2.4-8.5 4.7-14.5 4.7h-72.2c-.6 6.2.5 11.9 3 16.8l.8 1.5c.5.9 1.1 1.7 1.7 2.6 3 .2 5.7.3 8.2.2 4.9-.1 8.9-.7 12-1.7.5-.2.9.1 1.1.5.2.5-.1.9-.5 1.1-.4.1-.8.3-1.3.4-2.4.7-5 1.1-8.3 1.3h-.6000000000000001c-1.3.1-2.7.1-4.2.1-1.6 0-3.1 0-4.9-.1 6 6.8 15.4 10.8 27.2 10.8 25 0 46.2-11.1 55.5-35.9 6.7.7 13.1-1 16-6.7-4.5-2.7-10.5-1.8-13.9-.1z"
/><path
fill="#28B8EB"
d="M110.4 55.1c.8-5.9-3.6-10.5-6.4-12.7-3.1 3.6-3.6 13.2 1.3 17.2-2.8 2.4-8.5 4.7-14.5 4.7h-68c-.3 9.5 3.2 16.7 9.5 21 4.9-.1 8.9-.7 12-1.7.5-.2.9.1 1.1.5.2.5-.1.9-.5 1.1-.4.1-.8.3-1.3.4-2.4.7-5.2 1.2-8.5 1.4l-.1-.1c8.5 4.4 20.8 4.3 35-1.1 15.8-6.1 30.6-17.7 40.9-30.9-.2.1-.4.1-.5.2z"
/><path
fill="#028BB8"
d="M18.7 71.8c.4 3.3 1.4 6.4 2.9 9.3l.8 1.5c.5.9 1.1 1.7 1.7 2.6 3 .2 5.7.3 8.2.2 4.9-.1 8.9-.7 12-1.7.5-.2.9.1 1.1.5.2.5-.1.9-.5 1.1-.4.1-.8.3-1.3.4-2.4.7-5.2 1.2-8.5 1.4h-.4c-1.3.1-2.7.1-4.1.1-1.6 0-3.2 0-4.9-.1 6 6.8 15.5 10.8 27.3 10.8 21.4 0 40-8.1 50.8-26h-85.1v-.1z"
/><path
fill="#019BC6"
d="M23.5 71.8c1.3 5.8 4.3 10.4 8.8 13.5 4.9-.1 8.9-.7 12-1.7.5-.2.9.1 1.1.5.2.5-.1.9-.5 1.1-.4.1-.8.3-1.3.4-2.4.7-5.2 1.2-8.6 1.4 8.5 4.4 20.8 4.3 34.9-1.1 8.5-3.3 16.8-8.2 24.2-14.1h-70.6z"
/><path
fill-rule="evenodd"
clip-rule="evenodd"
fill="#00ACD3"
d="M28.4 52.7h9.8v9.8h-9.8v-9.8zm.8.8h.8v8.1h-.8v-8.1zm1.4 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zM39.6 41.5h9.8v9.8h-9.8v-9.8zm.9.8h.8v8.1h-.8v-8.1zm1.4 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.4 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1z"
/><path
fill-rule="evenodd"
clip-rule="evenodd"
fill="#23C2EE"
d="M39.6 52.7h9.8v9.8h-9.8v-9.8zm.9.8h.8v8.1h-.8v-8.1zm1.4 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.4 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1z"
/><path
fill-rule="evenodd"
clip-rule="evenodd"
fill="#00ACD3"
d="M50.9 52.7h9.8v9.8h-9.8v-9.8zm.8.8h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.4 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1z"
/><path
fill-rule="evenodd"
clip-rule="evenodd"
fill="#23C2EE"
d="M50.9 41.5h9.8v9.8h-9.8v-9.8zm.8.8h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.4 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zM62.2 52.7h9.8v9.8h-9.8v-9.8zm.8.8h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.4 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1z"
/><path
fill-rule="evenodd"
clip-rule="evenodd"
fill="#00ACD3"
d="M62.2 41.5h9.8v9.8h-9.8v-9.8zm.8.8h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.4 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1z"
/><path
fill-rule="evenodd"
clip-rule="evenodd"
fill="#23C2EE"
d="M62.2 30.2h9.8v9.8h-9.8v-9.8zm.8.8h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.4 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1z"
/><path
fill-rule="evenodd"
clip-rule="evenodd"
fill="#00ACD3"
d="M73.5 52.7h9.8v9.8h-9.8v-9.8zm.8.8h.8v8.1h-.8v-8.1zm1.4 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1zm1.5 0h.8v8.1h-.8v-8.1z"
/><path
fill-rule="evenodd"
clip-rule="evenodd"
fill="#D4EEF1"
d="M48.8 78.3c1.5 0 2.7 1.2 2.7 2.7 0 1.5-1.2 2.7-2.7 2.7-1.5 0-2.7-1.2-2.7-2.7 0-1.5 1.2-2.7 2.7-2.7"
/><path
fill-rule="evenodd"
clip-rule="evenodd"
fill="#3A4D54"
d="M48.8 79.1c.2 0 .5 0 .7.1-.2.1-.4.4-.4.7 0 .4.4.8.8.8.3 0 .6-.2.7-.4.1.2.1.5.1.7 0 1.1-.9 1.9-1.9 1.9-1.1 0-1.9-.9-1.9-1.9 0-1 .8-1.9 1.9-1.9M1.1 72.8h125.4c-2.7-.7-8.6-1.6-7.7-5.2-5 5.7-16.9 4-20 1.2-3.4 4.9-23 3-24.3-.8-4.2 5-17.3 5-21.5 0-1.4 3.8-21 5.7-24.3.8-3 2.8-15 4.5-20-1.2 1.1 3.5-4.9 4.5-7.6 5.2"
/><path
fill="#BFDBE0"
d="M56 97.8c-6.7-3.2-10.3-7.5-12.4-12.2-2.5.7-5.5 1.2-8.9 1.4-1.3.1-2.7.1-4.1.1-1.7 0-3.4 0-5.2-.1 6 6 13.6 10.7 27.5 10.8h3.1z"
/><path
fill="#D4EEF1"
d="M46.1 89.9c-.9-1.3-1.8-2.8-2.5-4.3-2.5.7-5.5 1.2-8.9 1.4 2.3 1.2 5.7 2.4 11.4 2.9z"
/></g
>
</svg>

After

Width:  |  Height:  |  Size: 4.6 KiB

View File

@@ -0,0 +1,6 @@
<svg class="absolute top-0 left-0 -m-4 h-10 w-10" viewBox="0 0 128 128">
<path
fill="#64328B"
d="M64,0C28.7,0,0,28.7,0,64v0c0,35.3,28.7,64,64,64s64-28.7,64-64v0C128,28.7,99.3,0,64,0z M13.2,64L64,114.8 C35.9,114.8,13.2,92.1,13.2,64z M75.4,113.5l-60.9-61C19.7,30,39.9,13.2,64,13.2c16.6,0,31.3,7.9,40.5,20.2l-7.5,7.2 C89.7,30.2,77.7,23.5,64,23.5c-17.6,0-32.5,11.2-38.1,26.8C33.1,57,75.4,98.8,78.1,102c12.7-4.7,22.3-15.5,25.4-28.9H81.9v-9.4 l33,0.2C114.8,88.2,98,108.4,75.4,113.5z"
/>
</svg>

After

Width:  |  Height:  |  Size: 494 B

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 6.1 KiB

View File

@@ -0,0 +1,5 @@
<svg class="absolute top-0 left-0 -m-4 h-10 w-10 fill-current text-blue-500" viewBox="0 0 128 128">
<path
d="M64 0C28.7 0 0 28.7 0 64s28.7 64 64 64c11.2 0 21.7-2.9 30.8-7.9L48.4 55.3v36.6h-6.8V41.8h6.8l50.5 75.8C116.4 106.2 128 86.5 128 64c0-35.3-28.7-64-64-64zm22.1 84.6l-7.5-11.3V41.8h7.5v42.8z"
/>
</svg>

After

Width:  |  Height:  |  Size: 312 B

View File

@@ -0,0 +1,14 @@
<svg
class="absolute top-0 left-0 -m-4 h-10 w-10 text-green-500"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
focusable="false"
data-prefix="fab"
data-icon="node-js"
role="img"
viewBox="0 0 448 512"
><path
fill="currentColor"
d="M224 508c-6.7 0-13.5-1.8-19.4-5.2l-61.7-36.5c-9.2-5.2-4.7-7-1.7-8 12.3-4.3 14.8-5.2 27.9-12.7 1.4-.8 3.2-.5 4.6.4l47.4 28.1c1.7 1 4.1 1 5.7 0l184.7-106.6c1.7-1 2.8-3 2.8-5V149.3c0-2.1-1.1-4-2.9-5.1L226.8 37.7c-1.7-1-4-1-5.7 0L36.6 144.3c-1.8 1-2.9 3-2.9 5.1v213.1c0 2 1.1 4 2.9 4.9l50.6 29.2c27.5 13.7 44.3-2.4 44.3-18.7V167.5c0-3 2.4-5.3 5.4-5.3h23.4c2.9 0 5.4 2.3 5.4 5.3V378c0 36.6-20 57.6-54.7 57.6-10.7 0-19.1 0-42.5-11.6l-48.4-27.9C8.1 389.2.7 376.3.7 362.4V149.3c0-13.8 7.4-26.8 19.4-33.7L204.6 9c11.7-6.6 27.2-6.6 38.8 0l184.7 106.7c12 6.9 19.4 19.8 19.4 33.7v213.1c0 13.8-7.4 26.7-19.4 33.7L243.4 502.8c-5.9 3.4-12.6 5.2-19.4 5.2zm149.1-210.1c0-39.9-27-50.5-83.7-58-57.4-7.6-63.2-11.5-63.2-24.9 0-11.1 4.9-25.9 47.4-25.9 37.9 0 51.9 8.2 57.7 33.8.5 2.4 2.7 4.2 5.2 4.2h24c1.5 0 2.9-.6 3.9-1.7s1.5-2.6 1.4-4.1c-3.7-44.1-33-64.6-92.2-64.6-52.7 0-84.1 22.2-84.1 59.5 0 40.4 31.3 51.6 81.8 56.6 60.5 5.9 65.2 14.8 65.2 26.7 0 20.6-16.6 29.4-55.5 29.4-48.9 0-59.6-12.3-63.2-36.6-.4-2.6-2.6-4.5-5.3-4.5h-23.9c-3 0-5.3 2.4-5.3 5.3 0 31.1 16.9 68.2 97.8 68.2 58.4-.1 92-23.2 92-63.4z"
/>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -0,0 +1,20 @@
<svg
class="absolute top-0 left-0 -m-4 h-10 w-10"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 400 400"
>
<g fill-rule="nonzero" transform="translate(0 50)" fill="none">
<path
d="M227.92099 83.45116l-13.6889 24.10141-46.8148-82.44693L23.7037 278.17052h97.3037c0 13.31084 10.61252 24.10142 23.70371 24.10142H23.70371c-8.46771 0-16.29145-4.59601-20.5246-12.05272-4.23315-7.4567-4.23272-16.64312.00114-24.0994L146.89383 13.05492c4.23415-7.45738 12.0596-12.05138 20.5284-12.05138 8.46878 0 16.29423 4.594 20.52839 12.05138l39.97037 70.39623z"
fill="#00C58E"
/>
<path
d="M331.6642 266.11981l-90.05432-158.56724-13.6889-24.10141-13.68888 24.10141-90.04445 158.56724c-4.23385 7.45629-4.23428 16.64271-.00113 24.09941 4.23314 7.4567 12.05689 12.05272 20.5246 12.05272h166.4c8.46946 0 16.29644-4.591 20.532-12.04837 4.23555-7.45736 4.23606-16.64592.00132-24.10376h.01976zM144.7111 278.17052L227.921 131.65399l83.19012 146.51653h-166.4z"
fill="#FFF"
/>
<path
d="M396.04938 290.22123c-4.23344 7.45557-12.05656 12.0507-20.52345 12.0507H311.1111c13.0912 0 23.7037-10.79057 23.7037-24.10141h40.66173L260.09877 74.98553l-18.4889 32.56704L227.921 83.45116l11.65432-20.51634c4.23416-7.45738 12.0596-12.05138 20.5284-12.05138 8.46879 0 16.29423 4.594 20.52839 12.05138l115.41728 203.185c4.23426 7.457 4.23426 16.6444 0 24.1014z"
fill="#108775"
/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -0,0 +1,6 @@
<svg viewBox="0 0 128 128" class="absolute top-0 left-0 -m-6 h-14 w-14 text-white">
<path
fill="#6181B6"
d="M64 33.039c-33.74 0-61.094 13.862-61.094 30.961s27.354 30.961 61.094 30.961 61.094-13.862 61.094-30.961-27.354-30.961-61.094-30.961zm-15.897 36.993c-1.458 1.364-3.077 1.927-4.86 2.507-1.783.581-4.052.461-6.811.461h-6.253l-1.733 10h-7.301l6.515-34h14.04c4.224 0 7.305 1.215 9.242 3.432 1.937 2.217 2.519 5.364 1.747 9.337-.319 1.637-.856 3.159-1.614 4.515-.759 1.357-1.75 2.624-2.972 3.748zm21.311 2.968l2.881-14.42c.328-1.688.208-2.942-.361-3.555-.57-.614-1.782-1.025-3.635-1.025h-5.79l-3.731 19h-7.244l6.515-33h7.244l-1.732 9h6.453c4.061 0 6.861.815 8.402 2.231s2.003 3.356 1.387 6.528l-3.031 15.241h-7.358zm40.259-11.178c-.318 1.637-.856 3.133-1.613 4.488-.758 1.357-1.748 2.598-2.971 3.722-1.458 1.364-3.078 1.927-4.86 2.507-1.782.581-4.053.461-6.812.461h-6.253l-1.732 10h-7.301l6.514-34h14.041c4.224 0 7.305 1.215 9.241 3.432 1.935 2.217 2.518 5.418 1.746 9.39zM95.919 54h-5.001l-2.727 14h4.442c2.942 0 5.136-.29 6.576-1.4 1.442-1.108 2.413-2.828 2.918-5.421.484-2.491.264-4.434-.66-5.458-.925-1.024-2.774-1.721-5.548-1.721zM38.934 54h-5.002l-2.727 14h4.441c2.943 0 5.136-.29 6.577-1.4 1.441-1.108 2.413-2.828 2.917-5.421.484-2.491.264-4.434-.66-5.458s-2.772-1.721-5.546-1.721z"
/>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -0,0 +1,50 @@
<svg class="absolute top-0 left-0 -m-6 h-14 w-14" viewBox="0 0 128 128">
<linearGradient
id="a"
gradientUnits="userSpaceOnUse"
x1="70.252"
y1="1237.476"
x2="170.659"
y2="1151.089"
gradientTransform="matrix(.563 0 0 -.568 -29.215 707.817)"
><stop offset="0" stop-color="#5A9FD4" /><stop
offset="1"
stop-color="#306998"
/></linearGradient
><path
fill="url(#a)"
d="M63.391 1.988c-4.222.02-8.252.379-11.8 1.007-10.45 1.846-12.346 5.71-12.346 12.837v9.411h24.693v3.137h-33.961c-7.176 0-13.46 4.313-15.426 12.521-2.268 9.405-2.368 15.275 0 25.096 1.755 7.311 5.947 12.519 13.124 12.519h8.491v-11.282c0-8.151 7.051-15.34 15.426-15.34h24.665c6.866 0 12.346-5.654 12.346-12.548v-23.513c0-6.693-5.646-11.72-12.346-12.837-4.244-.706-8.645-1.027-12.866-1.008zm-13.354 7.569c2.55 0 4.634 2.117 4.634 4.721 0 2.593-2.083 4.69-4.634 4.69-2.56 0-4.633-2.097-4.633-4.69-.001-2.604 2.073-4.721 4.633-4.721z"
/><linearGradient
id="b"
gradientUnits="userSpaceOnUse"
x1="209.474"
y1="1098.811"
x2="173.62"
y2="1149.537"
gradientTransform="matrix(.563 0 0 -.568 -29.215 707.817)"
><stop offset="0" stop-color="#FFD43B" /><stop
offset="1"
stop-color="#FFE873"
/></linearGradient
><path
fill="url(#b)"
d="M91.682 28.38v10.966c0 8.5-7.208 15.655-15.426 15.655h-24.665c-6.756 0-12.346 5.783-12.346 12.549v23.515c0 6.691 5.818 10.628 12.346 12.547 7.816 2.297 15.312 2.713 24.665 0 6.216-1.801 12.346-5.423 12.346-12.547v-9.412h-24.664v-3.138h37.012c7.176 0 9.852-5.005 12.348-12.519 2.578-7.735 2.467-15.174 0-25.096-1.774-7.145-5.161-12.521-12.348-12.521h-9.268zm-13.873 59.547c2.561 0 4.634 2.097 4.634 4.692 0 2.602-2.074 4.719-4.634 4.719-2.55 0-4.633-2.117-4.633-4.719 0-2.595 2.083-4.692 4.633-4.692z"
/><radialGradient
id="c"
cx="1825.678"
cy="444.45"
r="26.743"
gradientTransform="matrix(0 -.24 -1.055 0 532.979 557.576)"
gradientUnits="userSpaceOnUse"
><stop offset="0" stop-color="#B8B8B8" stop-opacity=".498" /><stop
offset="1"
stop-color="#7F7F7F"
stop-opacity="0"
/></radialGradient
><path
opacity=".444"
fill="url(#c)"
enable-background="new"
d="M97.309 119.597c0 3.543-14.816 6.416-33.091 6.416-18.276 0-33.092-2.873-33.092-6.416 0-3.544 14.815-6.417 33.092-6.417 18.275 0 33.091 2.872 33.091 6.417z"
/>
</svg>

After

Width:  |  Height:  |  Size: 2.2 KiB

View File

@@ -0,0 +1,7 @@
<svg class="absolute top-0 left-0 -m-4 h-10 w-10 text-blue-500" viewBox="0 0 128 128">
<g fill="#61DAFB"
><circle cx="64" cy="64" r="11.4" /><path
d="M107.3 45.2c-2.2-.8-4.5-1.6-6.9-2.3.6-2.4 1.1-4.8 1.5-7.1 2.1-13.2-.2-22.5-6.6-26.1-1.9-1.1-4-1.6-6.4-1.6-7 0-15.9 5.2-24.9 13.9-9-8.7-17.9-13.9-24.9-13.9-2.4 0-4.5.5-6.4 1.6-6.4 3.7-8.7 13-6.6 26.1.4 2.3.9 4.7 1.5 7.1-2.4.7-4.7 1.4-6.9 2.3-12.5 4.8-19.3 11.4-19.3 18.8s6.9 14 19.3 18.8c2.2.8 4.5 1.6 6.9 2.3-.6 2.4-1.1 4.8-1.5 7.1-2.1 13.2.2 22.5 6.6 26.1 1.9 1.1 4 1.6 6.4 1.6 7.1 0 16-5.2 24.9-13.9 9 8.7 17.9 13.9 24.9 13.9 2.4 0 4.5-.5 6.4-1.6 6.4-3.7 8.7-13 6.6-26.1-.4-2.3-.9-4.7-1.5-7.1 2.4-.7 4.7-1.4 6.9-2.3 12.5-4.8 19.3-11.4 19.3-18.8s-6.8-14-19.3-18.8zm-14.8-30.5c4.1 2.4 5.5 9.8 3.8 20.3-.3 2.1-.8 4.3-1.4 6.6-5.2-1.2-10.7-2-16.5-2.5-3.4-4.8-6.9-9.1-10.4-13 7.4-7.3 14.9-12.3 21-12.3 1.3 0 2.5.3 3.5.9zm-11.2 59.3c-1.8 3.2-3.9 6.4-6.1 9.6-3.7.3-7.4.4-11.2.4-3.9 0-7.6-.1-11.2-.4-2.2-3.2-4.2-6.4-6-9.6-1.9-3.3-3.7-6.7-5.3-10 1.6-3.3 3.4-6.7 5.3-10 1.8-3.2 3.9-6.4 6.1-9.6 3.7-.3 7.4-.4 11.2-.4 3.9 0 7.6.1 11.2.4 2.2 3.2 4.2 6.4 6 9.6 1.9 3.3 3.7 6.7 5.3 10-1.7 3.3-3.4 6.6-5.3 10zm8.3-3.3c1.5 3.5 2.7 6.9 3.8 10.3-3.4.8-7 1.4-10.8 1.9 1.2-1.9 2.5-3.9 3.6-6 1.2-2.1 2.3-4.2 3.4-6.2zm-25.6 27.1c-2.4-2.6-4.7-5.4-6.9-8.3 2.3.1 4.6.2 6.9.2 2.3 0 4.6-.1 6.9-.2-2.2 2.9-4.5 5.7-6.9 8.3zm-18.6-15c-3.8-.5-7.4-1.1-10.8-1.9 1.1-3.3 2.3-6.8 3.8-10.3 1.1 2 2.2 4.1 3.4 6.1 1.2 2.2 2.4 4.1 3.6 6.1zm-7-25.5c-1.5-3.5-2.7-6.9-3.8-10.3 3.4-.8 7-1.4 10.8-1.9-1.2 1.9-2.5 3.9-3.6 6-1.2 2.1-2.3 4.2-3.4 6.2zm25.6-27.1c2.4 2.6 4.7 5.4 6.9 8.3-2.3-.1-4.6-.2-6.9-.2-2.3 0-4.6.1-6.9.2 2.2-2.9 4.5-5.7 6.9-8.3zm22.2 21l-3.6-6c3.8.5 7.4 1.1 10.8 1.9-1.1 3.3-2.3 6.8-3.8 10.3-1.1-2.1-2.2-4.2-3.4-6.2zm-54.5-16.2c-1.7-10.5-.3-17.9 3.8-20.3 1-.6 2.2-.9 3.5-.9 6 0 13.5 4.9 21 12.3-3.5 3.8-7 8.2-10.4 13-5.8.5-11.3 1.4-16.5 2.5-.6-2.3-1-4.5-1.4-6.6zm-24.7 29c0-4.7 5.7-9.7 15.7-13.4 2-.8 4.2-1.5 6.4-2.1 1.6 5 3.6 10.3 6 15.6-2.4 5.3-4.5 10.5-6 15.5-13.8-4-22.1-10-22.1-15.6zm28.5 49.3c-4.1-2.4-5.5-9.8-3.8-20.3.3-2.1.8-4.3 1.4-6.6 5.2 1.2 10.7 2 16.5 2.5 3.4 4.8 6.9 9.1 10.4 13-7.4 7.3-14.9 12.3-21 12.3-1.3 0-2.5-.3-3.5-.9zm60.8-20.3c1.7 10.5.3 17.9-3.8 20.3-1 .6-2.2.9-3.5.9-6 0-13.5-4.9-21-12.3 3.5-3.8 7-8.2 10.4-13 5.8-.5 11.3-1.4 16.5-2.5.6 2.3 1 4.5 1.4 6.6zm9-15.6c-2 .8-4.2 1.5-6.4 2.1-1.6-5-3.6-10.3-6-15.6 2.4-5.3 4.5-10.5 6-15.5 13.8 4 22.1 10 22.1 15.6 0 4.7-5.8 9.7-15.7 13.4z"
/></g
>
</svg>

After

Width:  |  Height:  |  Size: 2.4 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

View File

@@ -0,0 +1,28 @@
<svg
class="absolute top-0 left-0 -m-4 h-10 w-10 text-white"
viewBox="0 0 32 32"
fill="none"
xmlns="http://www.w3.org/2000/svg"
><g clip-path="url(#HTML5_Clip0_4)"
><path
d="M30.216 0L27.6454 28.7967L16.0907 32L4.56783 28.8012L2 0H30.216Z"
fill="#E44D26"
/><path
d="M16.108 29.5515L25.4447 26.963L27.6415 2.35497H16.108V29.5515Z"
fill="#F16529"
/><path
d="M11.1109 9.4197H16.108V5.88731H7.25053L7.33509 6.83499L8.20327 16.5692H16.108V13.0369H11.4338L11.1109 9.4197Z"
fill="#EBEBEB"
/><path
d="M11.907 18.3354H8.36111L8.856 23.8818L16.0917 25.8904L16.108 25.8859V22.2108L16.0925 22.2149L12.1585 21.1527L11.907 18.3354Z"
fill="#EBEBEB"
/><path
d="M16.0958 16.5692H20.4455L20.0354 21.1504L16.0958 22.2138V25.8887L23.3373 23.8817L23.3904 23.285L24.2205 13.9855L24.3067 13.0369H16.0958V16.5692Z"
fill="white"
/><path
d="M16.0958 9.41105V9.41969H24.6281L24.6989 8.62572L24.8599 6.83499L24.9444 5.88731H16.0958V9.41105Z"
fill="white"
/></g
><defs><clipPath id="HTML5_Clip0_4"><rect width="32" height="32" fill="white" /></clipPath></defs
></svg
>

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1,21 @@
<svg
class="absolute top-0 left-0 -m-4 h-10 w-10"
version="1.1"
id="Layer_1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
x="0px"
y="0px"
viewBox="0 0 98.1 118"
style="enable-background:new 0 0 98.1 118;"
xml:space="preserve"
>
<path
fill="#FF3E00"
d="M91.8,15.6C80.9-0.1,59.2-4.7,43.6,5.2L16.1,22.8C8.6,27.5,3.4,35.2,1.9,43.9c-1.3,7.3-0.2,14.8,3.3,21.3 c-2.4,3.6-4,7.6-4.7,11.8c-1.6,8.9,0.5,18.1,5.7,25.4c11,15.7,32.6,20.3,48.2,10.4l27.5-17.5c7.5-4.7,12.7-12.4,14.2-21.1 c1.3-7.3,0.2-14.8-3.3-21.3c2.4-3.6,4-7.6,4.7-11.8C99.2,32.1,97.1,22.9,91.8,15.6"
/>
<path
fill="#FFFFFF"
d="M40.9,103.9c-8.9,2.3-18.2-1.2-23.4-8.7c-3.2-4.4-4.4-9.9-3.5-15.3c0.2-0.9,0.4-1.7,0.6-2.6l0.5-1.6l1.4,1 c3.3,2.4,6.9,4.2,10.8,5.4l1,0.3l-0.1,1c-0.1,1.4,0.3,2.9,1.1,4.1c1.6,2.3,4.4,3.4,7.1,2.7c0.6-0.2,1.2-0.4,1.7-0.7L65.5,72 c1.4-0.9,2.3-2.2,2.6-3.8c0.3-1.6-0.1-3.3-1-4.6c-1.6-2.3-4.4-3.3-7.1-2.6c-0.6,0.2-1.2,0.4-1.7,0.7l-10.5,6.7 c-1.7,1.1-3.6,1.9-5.6,2.4c-8.9,2.3-18.2-1.2-23.4-8.7c-3.1-4.4-4.4-9.9-3.4-15.3c0.9-5.2,4.1-9.9,8.6-12.7l27.5-17.5 c1.7-1.1,3.6-1.9,5.6-2.5c8.9-2.3,18.2,1.2,23.4,8.7c3.2,4.4,4.4,9.9,3.5,15.3c-0.2,0.9-0.4,1.7-0.7,2.6l-0.5,1.6l-1.4-1 c-3.3-2.4-6.9-4.2-10.8-5.4l-1-0.3l0.1-1c0.1-1.4-0.3-2.9-1.1-4.1c-1.6-2.3-4.4-3.3-7.1-2.6c-0.6,0.2-1.2,0.4-1.7,0.7L32.4,46.1 c-1.4,0.9-2.3,2.2-2.6,3.8s0.1,3.3,1,4.6c1.6,2.3,4.4,3.3,7.1,2.6c0.6-0.2,1.2-0.4,1.7-0.7l10.5-6.7c1.7-1.1,3.6-1.9,5.6-2.5 c8.9-2.3,18.2,1.2,23.4,8.7c3.2,4.4,4.4,9.9,3.5,15.3c-0.9,5.2-4.1,9.9-8.6,12.7l-27.5,17.5C44.8,102.5,42.9,103.3,40.9,103.9"
/>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,12 @@
<svg class="absolute top-0 left-0 -m-4 h-10 w-10 text-green-500" viewBox="0 0 128 128">
<path
d="m-2.3125e-8 8.9337 49.854 0.1586 14.167 24.47 14.432-24.47 49.547-0.1577-63.834 110.14zm126.98 0.6374-24.36 0.0207-38.476 66.052-38.453-66.052-24.749-0.0194 63.211 107.89zm-25.149-0.008-22.745 0.16758l-15.053 24.647-14.817-24.647-22.794-0.1679 37.731 64.476zM25.997 9.3929l23.002 0.0087M25.997 9.3929l23.002 0.0087"
fill="none"
/><path
d="m25.997 9.3929 23.002 0.0087l15.036 24.958 14.983-24.956 22.982-0.0057-37.85 65.655z"
fill="#35495e"
/><path
d="m0.91068 9.5686 25.066-0.1711 38.151 65.658 37.852-65.654 25.11 0.0263-62.966 108.06z"
fill="#41b883"
/>
</svg>

After

Width:  |  Height:  |  Size: 676 B

View File

@@ -0,0 +1,13 @@
<script lang="ts">
export let isAbsolute = false;
</script>
<svg
class={isAbsolute ? 'absolute top-0 left-0 -m-5 h-10 w-10' : 'mx-auto w-8 h-8'}
viewBox="0 0 9 8"
xmlns="http://www.w3.org/2000/svg"
><path d="m0 7h1v1h-1z" fill="#f00" /><path
d="m0 0h1v7h-1zm2 0h1v8h-1zm2 0h1v8h-1zm2 0h1v8h-1zm2 3.25h1v1.5h-1z"
fill="#fc0"
/></svg
>

View File

@@ -0,0 +1,18 @@
<script lang="ts">
export let isAbsolute = false;
</script>
<svg
class={isAbsolute
? 'absolute top-0 left-0 -m-5 h-10 w-10 fill-current text-red-500'
: 'mx-auto w-8 h-8 text-red-500'}
id="CouchDB"
fill="currentColor"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 128 128"
><g id="original"
><path
d="M101.4,77.2c0,5-2.7,7.5-7.6,7.7H33.9c-4.9,0-7.6-2.5-7.6-7.7,0-5,2.7-7.5,7.6-7.7H94.1C99,69.7,101.4,72.2,101.4,77.2ZM94.1,88.7H33.9c-4.9,0-7.6,2.4-7.6,7.7,0,5,2.7,7.4,7.6,7.7H94.1c4.9,0,7.6-2.5,7.6-7.7C101.4,91.1,99,88.7,94.1,88.7Zm18.6-42.1h0c-4.9,0-7.6,2.5-7.6,7.4V96.1c0,5,2.7,7.5,7.6,7.7h0c7.4-.2,11.3-7.7,11.3-22.9V62C124,51.8,120.1,46.8,112.7,46.6Zm-97.4,0h0C7.9,46.8,4,51.8,4,62V80.9c0,15.2,3.9,22.7,11.3,22.9h0c4.9,0,7.6-2.4,7.6-7.7V54.3C22.7,49.3,20.2,46.8,15.3,46.6Zm97.4-3.8c0-12.7-6.6-18.7-18.6-18.9H33.9c-12.2.2-18.6,6.5-18.6,18.9h0c7.4,0,11.3,4,11.3,11.5s3.9,11.4,11.3,11.4H90.4c7.3,0,11.3-3.9,11.3-11.4-.3-7.7,3.9-11.2,11-11.5Z"
/></g
></svg
>

View File

@@ -0,0 +1,33 @@
<script lang="ts">
export let isAbsolute = false;
</script>
<svg
class={isAbsolute ? 'absolute top-0 left-0 -m-5 h-10 w-10' : 'mx-auto w-8 h-8'}
xmlns="http://www.w3.org/2000/svg"
id="Layer_1"
data-name="Layer 1"
viewBox="0 0 216.56 448.5"
><defs
><style>
.cls-1 {
fill: #10aa50;
}
.cls-2 {
fill: #b8c4c2;
}
.cls-3 {
fill: #12924f;
}
</style></defs
><path
class="cls-1"
d="M202.8,179.68c-23-101.47-71-128.49-83.18-147.59C113,21.7,106.25,5.91,106.25,5.91c-.66,9-1.83,14.7-9.51,21.54C81.36,41.16,16,94.42,10.51,209.72c-5.12,107.5,79,173.8,90.18,180.65,8.54,4.2,19,.08,24-3.77,40.54-27.84,96-102.07,78.06-206.92"
/><path
class="cls-2"
d="M109.73,333.11c-2.11,26.62-3.63,42.11-9,57.29,0,0,3.54,25.33,6,52.17l8.77,0a488.62,488.62,0,0,1,9.57-56.2C113.71,380.8,110.16,356.46,109.73,333.11Z"
/><path
class="cls-3"
d="M125.06,386.39h0c-11.48-5.3-14.8-30.13-15.31-53.28A1090.8,1090.8,0,0,0,112.2,218.4c-.6-20.07.3-185.92-4.94-210.2,2.12,4.75,7.24,15.91,12.36,23.88,12.23,19.11,60.19,46.13,83.17,147.61C220.7,284.27,165.57,358.37,125.06,386.39Z"
/>
</svg>

View File

@@ -0,0 +1,17 @@
<script lang="ts">
export let isAbsolute = false;
</script>
<svg
class={isAbsolute ? 'absolute top-0 left-0 -m-5 h-10 w-10' : 'mx-auto w-8 h-8'}
xmlns="http://www.w3.org/2000/svg"
width="64"
height="64"
viewBox="0 0 25.6 25.6"
><path
d="M179.076 94.886c-3.568-.1-6.336.268-8.656 1.25-.668.27-1.74.27-1.828 1.116.357.355.4.936.713 1.428.535.893 1.473 2.096 2.32 2.72l2.855 2.053c1.74 1.07 3.703 1.695 5.398 2.766.982.625 1.963 1.428 2.945 2.098.5.357.803.938 1.428 1.16v-.135c-.312-.4-.402-.98-.713-1.428l-1.34-1.293c-1.293-1.74-2.9-3.258-4.64-4.506-1.428-.982-4.55-2.32-5.13-3.97l-.088-.1c.98-.1 2.14-.447 3.078-.715 1.518-.4 2.9-.312 4.46-.713l2.143-.625v-.4c-.803-.803-1.383-1.874-2.23-2.632-2.275-1.963-4.775-3.882-7.363-5.488-1.383-.892-3.168-1.473-4.64-2.23-.537-.268-1.428-.402-1.74-.848-.805-.98-1.25-2.275-1.83-3.436l-3.658-7.763c-.803-1.74-1.295-3.48-2.275-5.086-4.596-7.585-9.594-12.18-17.268-16.687-1.65-.937-3.613-1.34-5.7-1.83l-3.346-.18c-.715-.312-1.428-1.16-2.053-1.562-2.543-1.606-9.102-5.086-10.977-.5-1.205 2.9 1.785 5.755 2.8 7.228.76 1.026 1.74 2.186 2.277 3.346.3.758.4 1.562.713 2.365.713 1.963 1.383 4.15 2.32 5.98.5.937 1.025 1.92 1.65 2.767.357.5.982.714 1.115 1.517-.625.893-.668 2.23-1.025 3.347-1.607 5.042-.982 11.288 1.293 15 .715 1.115 2.4 3.57 4.686 2.632 2.008-.803 1.56-3.346 2.14-5.577.135-.535.045-.892.312-1.25v.1l1.83 3.703c1.383 2.186 3.793 4.462 5.8 5.98 1.07.803 1.918 2.187 3.256 2.677v-.135h-.088c-.268-.4-.67-.58-1.027-.892-.803-.803-1.695-1.785-2.32-2.677-1.873-2.498-3.523-5.265-4.996-8.12-.715-1.383-1.34-2.9-1.918-4.283-.27-.536-.27-1.34-.715-1.606-.67.98-1.65 1.83-2.143 3.034-.848 1.918-.936 4.283-1.248 6.737-.18.045-.1 0-.18.1-1.426-.356-1.918-1.83-2.453-3.078-1.338-3.168-1.562-8.254-.402-11.913.312-.937 1.652-3.882 1.117-4.774-.27-.848-1.16-1.338-1.652-2.008-.58-.848-1.203-1.918-1.605-2.855-1.07-2.5-1.605-5.265-2.766-7.764-.537-1.16-1.473-2.365-2.232-3.435-.848-1.205-1.783-2.053-2.453-3.48-.223-.5-.535-1.294-.178-1.83.088-.357.268-.5.623-.58.58-.5 2.232.134 2.812.4 1.65.67 3.033 1.294 4.416 2.23.625.446 1.295 1.294 2.098 1.518h.938c1.428.312 3.033.1 4.37.5 2.365.76 4.506 1.874 6.426 3.08 5.844 3.703 10.664 8.968 13.92 15.26.535 1.026.758 1.963 1.25 3.034.938 2.187 2.098 4.417 3.033 6.56.938 2.097 1.83 4.24 3.168 5.98.67.937 3.346 1.427 4.55 1.918.893.4 2.275.76 3.08 1.25 1.516.937 3.033 2.008 4.46 3.034.713.534 2.945 1.65 3.078 2.54zm-45.5-38.772a7.09 7.09 0 0 0-1.828.223v.1h.088c.357.714.982 1.205 1.428 1.83l1.027 2.142.088-.1c.625-.446.938-1.16.938-2.23-.268-.312-.312-.625-.535-.937-.268-.446-.848-.67-1.206-1.026z"
transform="matrix(.390229 0 0 .38781 -46.300037 -16.856717)"
fill-rule="evenodd"
fill="#00678c"
/></svg
>

View File

@@ -0,0 +1,56 @@
<script lang="ts">
export let isAbsolute = false;
</script>
<svg
class={isAbsolute ? 'absolute top-0 left-0 -m-5 h-10 w-10' : 'mx-auto w-8 h-8'}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 432.071 445.383"
xml:space="preserve"
>
<g id="orginal" style="fill-rule:nonzero;clip-rule:nonzero;stroke:#000000;stroke-miterlimit:4;" />
<g
id="Layer_x0020_3"
style="fill-rule:nonzero;clip-rule:nonzero;fill:none;stroke:#FFFFFF;stroke-width:12.4651;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:4;"
>
<path
style="fill:#000000;stroke:#000000;stroke-width:37.3953;stroke-linecap:butt;stroke-linejoin:miter;"
d="M323.205,324.227c2.833-23.601,1.984-27.062,19.563-23.239l4.463,0.392c13.517,0.615,31.199-2.174,41.587-7c22.362-10.376,35.622-27.7,13.572-23.148c-50.297,10.376-53.755-6.655-53.755-6.655c53.111-78.803,75.313-178.836,56.149-203.322 C352.514-5.534,262.036,26.049,260.522,26.869l-0.482,0.089c-9.938-2.062-21.06-3.294-33.554-3.496c-22.761-0.374-40.032,5.967-53.133,15.904c0,0-161.408-66.498-153.899,83.628c1.597,31.936,45.777,241.655,98.47,178.31 c19.259-23.163,37.871-42.748,37.871-42.748c9.242,6.14,20.307,9.272,31.912,8.147l0.897-0.765c-0.281,2.876-0.157,5.689,0.359,9.019c-13.572,15.167-9.584,17.83-36.723,23.416c-27.457,5.659-11.326,15.734-0.797,18.367c12.768,3.193,42.305,7.716,62.268-20.224 l-0.795,3.188c5.325,4.26,4.965,30.619,5.72,49.452c0.756,18.834,2.017,36.409,5.856,46.771c3.839,10.36,8.369,37.05,44.036,29.406c29.809-6.388,52.6-15.582,54.677-101.107"
/>
<path
style="fill:#336791;stroke:none;"
d="M402.395,271.23c-50.302,10.376-53.76-6.655-53.76-6.655c53.111-78.808,75.313-178.843,56.153-203.326c-52.27-66.785-142.752-35.2-144.262-34.38l-0.486,0.087c-9.938-2.063-21.06-3.292-33.56-3.496c-22.761-0.373-40.026,5.967-53.127,15.902 c0,0-161.411-66.495-153.904,83.63c1.597,31.938,45.776,241.657,98.471,178.312c19.26-23.163,37.869-42.748,37.869-42.748c9.243,6.14,20.308,9.272,31.908,8.147l0.901-0.765c-0.28,2.876-0.152,5.689,0.361,9.019c-13.575,15.167-9.586,17.83-36.723,23.416 c-27.459,5.659-11.328,15.734-0.796,18.367c12.768,3.193,42.307,7.716,62.266-20.224l-0.796,3.188c5.319,4.26,9.054,27.711,8.428,48.969c-0.626,21.259-1.044,35.854,3.147,47.254c4.191,11.4,8.368,37.05,44.042,29.406c29.809-6.388,45.256-22.942,47.405-50.555 c1.525-19.631,4.976-16.729,5.194-34.28l2.768-8.309c3.192-26.611,0.507-35.196,18.872-31.203l4.463,0.392c13.517,0.615,31.208-2.174,41.591-7c22.358-10.376,35.618-27.7,13.573-23.148z"
/>
<path
d="M215.866,286.484c-1.385,49.516,0.348,99.377,5.193,111.495c4.848,12.118,15.223,35.688,50.9,28.045c29.806-6.39,40.651-18.756,45.357-46.051c3.466-20.082,10.148-75.854,11.005-87.281"
/>
<path
d="M173.104,38.256c0,0-161.521-66.016-154.012,84.109c1.597,31.938,45.779,241.664,98.473,178.316c19.256-23.166,36.671-41.335,36.671-41.335"
/>
<path
d="M260.349,26.207c-5.591,1.753,89.848-34.889,144.087,34.417c19.159,24.484-3.043,124.519-56.153,203.329"
/>
<path
style="stroke-linejoin:bevel;"
d="M348.282,263.953c0,0,3.461,17.036,53.764,6.653c22.04-4.552,8.776,12.774-13.577,23.155c-18.345,8.514-59.474,10.696-60.146-1.069c-1.729-30.355,21.647-21.133,19.96-28.739c-1.525-6.85-11.979-13.573-18.894-30.338 c-6.037-14.633-82.796-126.849,21.287-110.183c3.813-0.789-27.146-99.002-124.553-100.599c-97.385-1.597-94.19,119.762-94.19,119.762"
/>
<path
d="M188.604,274.334c-13.577,15.166-9.584,17.829-36.723,23.417c-27.459,5.66-11.326,15.733-0.797,18.365c12.768,3.195,42.307,7.718,62.266-20.229c6.078-8.509-0.036-22.086-8.385-25.547c-4.034-1.671-9.428-3.765-16.361,3.994z"
/>
<path
d="M187.715,274.069c-1.368-8.917,2.93-19.528,7.536-31.942c6.922-18.626,22.893-37.255,10.117-96.339c-9.523-44.029-73.396-9.163-73.436-3.193c-0.039,5.968,2.889,30.26-1.067,58.548c-5.162,36.913,23.488,68.132,56.479,64.938"
/>
<path
style="fill:#FFFFFF;stroke-width:4.155;stroke-linecap:butt;stroke-linejoin:miter;"
d="M172.517,141.7c-0.288,2.039,3.733,7.48,8.976,8.207c5.234,0.73,9.714-3.522,9.998-5.559c0.284-2.039-3.732-4.285-8.977-5.015c-5.237-0.731-9.719,0.333-9.996,2.367z"
/>
<path
style="fill:#FFFFFF;stroke-width:2.0775;stroke-linecap:butt;stroke-linejoin:miter;"
d="M331.941,137.543c0.284,2.039-3.732,7.48-8.976,8.207c-5.238,0.73-9.718-3.522-10.005-5.559c-0.277-2.039,3.74-4.285,8.979-5.015c5.239-0.73,9.718,0.333,10.002,2.368z"
/>
<path
d="M350.676,123.432c0.863,15.994-3.445,26.888-3.988,43.914c-0.804,24.748,11.799,53.074-7.191,81.435"
/>
<path style="stroke-width:3;" d="M0,60.232" />
</g>
</svg>

View File

@@ -0,0 +1,36 @@
<script lang="ts">
export let isAbsolute = false;
</script>
<svg
class={isAbsolute ? 'absolute top-0 left-0 -m-5 h-10 w-10' : 'mx-auto w-8 h-8'}
height="64"
viewBox="0 0 32 32"
width="64"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
><defs
><path
id="a"
d="m45.536 38.764c-2.013 1.05-12.44 5.337-14.66 6.494s-3.453 1.146-5.207.308-12.85-5.32-14.85-6.276c-1-.478-1.524-.88-1.524-1.26v-3.813s14.447-3.145 16.78-3.982 3.14-.867 5.126-.14 13.853 2.868 15.814 3.587v3.76c0 .377-.452.8-1.477 1.324z"
/><path
id="b"
d="m45.536 28.733c-2.013 1.05-12.44 5.337-14.66 6.494s-3.453 1.146-5.207.308-12.85-5.32-14.85-6.276-2.04-1.613-.077-2.382l15.332-5.935c2.332-.837 3.14-.867 5.126-.14s12.35 4.853 14.312 5.57 2.037 1.31.024 2.36z"
/></defs
><g transform="matrix(.848327 0 0 .848327 -7.883573 -9.449691)"
><use fill="#a41e11" xlink:href="#a" /><path
d="m45.536 34.95c-2.013 1.05-12.44 5.337-14.66 6.494s-3.453 1.146-5.207.308-12.85-5.32-14.85-6.276-2.04-1.613-.077-2.382l15.332-5.936c2.332-.836 3.14-.867 5.126-.14s12.35 4.852 14.31 5.582 2.037 1.31.024 2.36z"
fill="#d82c20"
/><use fill="#a41e11" xlink:href="#a" y="-6.218" /><use fill="#d82c20" xlink:href="#b" /><path
d="m45.536 26.098c-2.013 1.05-12.44 5.337-14.66 6.495s-3.453 1.146-5.207.308-12.85-5.32-14.85-6.276c-1-.478-1.524-.88-1.524-1.26v-3.815s14.447-3.145 16.78-3.982 3.14-.867 5.126-.14 13.853 2.868 15.814 3.587v3.76c0 .377-.452.8-1.477 1.324z"
fill="#a41e11"
/><use fill="#d82c20" xlink:href="#b" y="-6.449" /><g fill="#fff"
><path
d="m29.096 20.712-1.182-1.965-3.774-.34 2.816-1.016-.845-1.56 2.636 1.03 2.486-.814-.672 1.612 2.534.95-3.268.34zm-6.296 3.912 8.74-1.342-2.64 3.872z"
/><ellipse cx="20.444" cy="21.402" rx="4.672" ry="1.811" /></g
><path d="m42.132 21.138-5.17 2.042-.004-4.087z" fill="#7a0c00" /><path
d="m36.963 23.18-.56.22-5.166-2.042 5.723-2.264z"
fill="#ad2115"
/></g
></svg
>

View File

@@ -0,0 +1,9 @@
<script lang="ts">
export let isAbsolute = false;
</script>
<img
alt="minio logo"
class={isAbsolute ? 'w-7 absolute top-0 left-0 -m-3 -mt-5' : 'w-4 mx-auto'}
src="https://cdn.coollabs.io/assets/coolify/services/minio/MINIO_Bird.png"
/>

View File

@@ -0,0 +1,9 @@
<script lang="ts">
export let isAbsolute = false;
</script>
<img
alt="nocodb logo"
class={isAbsolute ? 'w-10 absolute top-0 left-0 -m-5' : 'w-8 mx-auto'}
src="https://cdn.coollabs.io/assets/coolify/services/nocodb/nocodb.png"
/>

View File

@@ -0,0 +1,9 @@
<script lang="ts">
export let isAbsolute = false;
</script>
<img
alt="plausible logo"
class={isAbsolute ? 'w-10 absolute top-0 left-0 -m-5' : 'w-6 mx-auto'}
src="https://cdn.coollabs.io/assets/coolify/services/plausible/logo_sm.png"
/>

View File

@@ -0,0 +1,22 @@
<script lang="ts">
export let isAbsolute = false;
</script>
<svg
class={isAbsolute ? 'w-10 h-10 absolute top-0 left-0 -m-5' : 'w-8 mx-auto'}
viewBox="0 0 128 128"
>
<path
d="M3.656 45.043s-3.027-2.191.61-5.113l8.468-7.594s2.426-2.559 4.989-.328l78.175 59.328v28.45s-.039 4.468-5.757 3.976zm0 0"
fill="#2489ca"
/><path
d="M23.809 63.379L3.656 81.742s-2.07 1.543 0 4.305l9.356 8.527s2.222 2.395 5.508-.328l21.359-16.238zm0 0"
fill="#1070b3"
/><path
d="M59.184 63.531l36.953-28.285-.239-28.297S94.32.773 89.055 3.99L39.879 48.851zm0 0"
fill="#0877b9"
/><path
d="M90.14 123.797c2.145 2.203 4.747 1.48 4.747 1.48l28.797-14.222c3.687-2.52 3.171-5.645 3.171-5.645V20.465c0-3.735-3.812-5.024-3.812-5.024L98.082 3.38c-5.453-3.379-9.027.61-9.027.61s4.593-3.317 6.843 2.96v112.317c0 .773-.164 1.53-.492 2.214-.656 1.332-2.086 2.57-5.504 2.051zm0 0"
fill="#3c99d4"
/>
</svg>

View File

@@ -0,0 +1,12 @@
<script lang="ts">
export let isAbsolute = false;
</script>
<svg class={isAbsolute ? 'w-10 absolute top-0 left-0 -m-5' : 'w-8 mx-auto'} viewBox="0 0 128 128">
<path
fill-rule="evenodd"
clip-rule="evenodd"
fill="white"
d="M64.094 126.224c34.275-.052 62.021-27.933 62.021-62.325 0-33.833-27.618-61.697-60.613-62.286C30.85.995 1.894 29.113 1.885 63.21c-.01 35.079 27.612 63.064 62.209 63.014zM63.993 4.63c32.907-.011 59.126 26.725 59.116 60.28-.011 31.679-26.925 58.18-59.092 58.187-32.771.007-59.125-26.563-59.124-59.608.002-32.193 26.766-58.848 59.1-58.859zM39.157 35.896c.538 1.793-.968 2.417-2.569 2.542-1.685.13-3.369.257-5.325.406 6.456 19.234 12.815 38.183 19.325 57.573.464-.759.655-.973.739-1.223 3.574-10.682 7.168-21.357 10.651-32.069.318-.977.16-2.271-.188-3.275-1.843-5.32-4.051-10.524-5.667-15.908-1.105-3.686-2.571-6.071-6.928-5.644-.742.073-1.648-1.524-2.479-2.349 1.005-.6 2.003-1.704 3.017-1.719a849.593 849.593 0 0126.618.008c1.018.017 2.016 1.15 3.021 1.765-.88.804-1.639 2.01-2.668 2.321-1.651.498-3.482.404-5.458.58l19.349 57.56c2.931-9.736 5.658-18.676 8.31-27.639 2.366-8.001.956-15.473-3.322-22.52-1.286-2.119-2.866-4.175-3.595-6.486-.828-2.629-1.516-5.622-1.077-8.259.745-4.469 4.174-6.688 8.814-7.113C74.333.881 34.431 9.317 19.728 34.922c5.66-.261 11.064-.604 16.472-.678 1.022-.013 2.717.851 2.957 1.652zm10.117 77.971c-.118.345-.125.729-.218 1.302 10.943 3.034 21.675 2.815 32.659-.886l-16.78-45.96c-5.37 15.611-10.52 30.575-15.661 45.544zm-8.456-2.078l-25.281-69.35c-11.405 22.278-2.729 56.268 25.281 69.35zm76.428-44.562c.802-10.534-2.832-25.119-5.97-27.125-.35 3.875-.106 8.186-1.218 12.114-2.617 9.255-5.817 18.349-8.899 27.468-3.35 9.912-6.832 19.779-10.257 29.666 16.092-9.539 24.935-23.618 26.344-42.123z"
/>
</svg>

View File

@@ -0,0 +1,155 @@
const defaultBuildAndDeploy = {
installCommand: 'yarn install',
buildCommand: 'yarn build',
startCommand: 'yarn start'
};
export const buildPacks = [
{
name: 'node',
installCommand: null,
buildCommand: null,
startCommand: null,
publishDirectory: null,
port: null,
fancyName: 'Node.js',
hoverColor: 'hover:bg-green-700',
color: 'bg-green-700'
},
{
name: 'static',
...defaultBuildAndDeploy,
publishDirectory: 'dist',
port: 80,
fancyName: 'Static',
hoverColor: 'hover:bg-orange-700',
color: 'bg-orange-700'
},
{
name: 'docker',
installCommand: null,
buildCommand: null,
startCommand: null,
publishDirectory: null,
port: null,
fancyName: 'Docker',
hoverColor: 'hover:bg-sky-700',
color: 'bg-sky-700'
},
{
name: 'svelte',
...defaultBuildAndDeploy,
publishDirectory: 'public',
port: 80,
fancyName: 'Svelte',
hoverColor: 'hover:bg-orange-700',
color: 'bg-orange-700'
},
{
name: 'nestjs',
...defaultBuildAndDeploy,
startCommand: 'yarn start:prod',
port: 3000,
fancyName: 'NestJS',
hoverColor: 'hover:bg-red-700',
color: 'bg-red-700'
},
{
name: 'react',
...defaultBuildAndDeploy,
publishDirectory: 'build',
port: 80,
fancyName: 'React',
hoverColor: 'hover:bg-blue-700',
color: 'bg-blue-700'
},
{
name: 'nextjs',
...defaultBuildAndDeploy,
port: 3000,
fancyName: 'NextJS',
hoverColor: 'hover:bg-blue-700',
color: 'bg-blue-700'
},
{
name: 'gatsby',
...defaultBuildAndDeploy,
publishDirectory: 'public',
port: 80,
fancyName: 'Gatsby',
hoverColor: 'hover:bg-blue-700',
color: 'bg-blue-700'
},
{
name: 'vuejs',
...defaultBuildAndDeploy,
publishDirectory: 'dist',
port: 80,
fancyName: 'VueJS',
hoverColor: 'hover:bg-green-700',
color: 'bg-green-700'
},
{
name: 'nuxtjs',
...defaultBuildAndDeploy,
port: 3000,
fancyName: 'NuxtJS',
hoverColor: 'hover:bg-green-700',
color: 'bg-green-700'
},
{
name: 'preact',
...defaultBuildAndDeploy,
publishDirectory: 'build',
port: 80,
fancyName: 'Preact',
hoverColor: 'hover:bg-blue-700',
color: 'bg-blue-700'
},
{
name: 'php',
port: 80,
fancyName: 'PHP',
hoverColor: 'hover:bg-indigo-700',
color: 'bg-indigo-700'
},
{
name: 'rust',
port: 3000,
fancyName: 'Rust',
hoverColor: 'hover:bg-pink-700',
color: 'bg-pink-700'
}
];
export const scanningTemplates = {
svelte: {
buildPack: 'svelte'
},
'@nestjs/core': {
buildPack: 'nestjs'
},
next: {
buildPack: 'nextjs'
},
nuxt: {
buildPack: 'nuxtjs'
},
'react-scripts': {
buildPack: 'react'
},
'parcel-bundler': {
buildPack: 'static'
},
'@vue/cli-service': {
buildPack: 'vuejs'
},
vuejs: {
buildPack: 'vuejs'
},
gatsby: {
buildPack: 'gatsby'
},
'preact-cli': {
buildPack: 'react'
}
};

View File

@@ -1,8 +0,0 @@
export const publicPages = [
'/',
'/api/v1/login/github/app',
'/api/v1/webhooks/deploy',
'/success',
'/api/v1/login/email'
];
export const VITE_GITHUB_APP_NAME = import.meta.env.VITE_GITHUB_APP_NAME;

36
src/lib/crypto.ts Normal file
View File

@@ -0,0 +1,36 @@
import crypto from 'crypto';
const algorithm = 'aes-256-ctr';
export const base64Encode = (text: string) => {
return Buffer.from(text).toString('base64');
};
export const base64Decode = (text: string) => {
return Buffer.from(text, 'base64').toString('ascii');
};
export const encrypt = (text: string) => {
if (text) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(algorithm, process.env['COOLIFY_SECRET_KEY'], iv);
const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
return JSON.stringify({
iv: iv.toString('hex'),
content: encrypted.toString('hex')
});
}
};
export const decrypt = (hashString: string) => {
if (hashString) {
const hash: Hash = JSON.parse(hashString);
const decipher = crypto.createDecipheriv(
algorithm,
process.env['COOLIFY_SECRET_KEY'],
Buffer.from(hash.iv, 'hex')
);
const decrpyted = Buffer.concat([
decipher.update(Buffer.from(hash.content, 'hex')),
decipher.final()
]);
return decrpyted.toString();
}
};

View File

@@ -0,0 +1,230 @@
import { decrypt, encrypt } from '$lib/crypto';
import { removeProxyConfiguration } from '$lib/haproxy';
import { asyncExecShell, getEngine, removeContainer } from '$lib/common';
import { getDomain, removeDestinationDocker } from '$lib/common';
import { prisma } from './common';
export async function listApplications(teamId) {
return await prisma.application.findMany({ where: { teams: { some: { id: teamId } } } });
}
export async function newApplication({ name, teamId }) {
return await prisma.application.create({
data: {
name,
teams: { connect: { id: teamId } },
settings: { create: { debug: false, previews: false } }
}
});
}
export async function importApplication({
name,
teamId,
fqdn,
port,
buildCommand,
startCommand,
installCommand
}) {
return await prisma.application.create({
data: {
name,
fqdn,
port,
buildCommand,
startCommand,
installCommand,
teams: { connect: { id: teamId } }
}
});
}
export async function removeApplication({ id, teamId }) {
const { fqdn, destinationDockerId, destinationDocker } = await prisma.application.findUnique({
where: { id },
include: { destinationDocker: true }
});
const domain = getDomain(fqdn);
if (destinationDockerId) {
const host = getEngine(destinationDocker.engine);
const { stdout: containers } = await asyncExecShell(
`DOCKER_HOST=${host} docker ps -a --filter network=${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;
const preview = containerObj.Image.split('-')[1];
await removeDestinationDocker({ id, engine: destinationDocker.engine });
if (preview) {
await removeProxyConfiguration({ domain: `${preview}.${domain}` });
} else {
await removeProxyConfiguration({ domain });
}
}
}
}
await prisma.applicationSettings.deleteMany({ where: { application: { id } } });
await prisma.buildLog.deleteMany({ where: { applicationId: id } });
await prisma.secret.deleteMany({ where: { applicationId: id } });
await prisma.application.deleteMany({ where: { id, teams: { some: { id: teamId } } } });
}
export async function getApplicationWebhook({ projectId, branch }) {
try {
let body = await prisma.application.findFirst({
where: { projectId, branch },
include: {
destinationDocker: true,
settings: true,
gitSource: { include: { githubApp: true, gitlabApp: true } },
secrets: true
}
});
if (body.gitSource?.githubApp?.clientSecret) {
body.gitSource.githubApp.clientSecret = decrypt(body.gitSource.githubApp.clientSecret);
}
if (body.gitSource?.githubApp?.webhookSecret) {
body.gitSource.githubApp.webhookSecret = decrypt(body.gitSource.githubApp.webhookSecret);
}
if (body.gitSource?.githubApp?.privateKey) {
body.gitSource.githubApp.privateKey = decrypt(body.gitSource.githubApp.privateKey);
}
if (body?.gitSource?.gitlabApp?.appSecret) {
body.gitSource.gitlabApp.appSecret = decrypt(body.gitSource.gitlabApp.appSecret);
}
if (body?.gitSource?.gitlabApp?.webhookToken) {
body.gitSource.gitlabApp.webhookToken = decrypt(body.gitSource.gitlabApp.webhookToken);
}
if (body?.secrets.length > 0) {
body.secrets = body.secrets.map((s) => {
s.value = decrypt(s.value);
return s;
});
}
return { ...body };
} catch (e) {
throw { status: 404, body: { message: e.message } };
}
}
export async function getApplication({ id, teamId }) {
let body = await prisma.application.findFirst({
where: { id, teams: { some: { id: teamId } } },
include: {
destinationDocker: true,
settings: true,
gitSource: { include: { githubApp: true, gitlabApp: true } },
secrets: true
}
});
if (body.gitSource?.githubApp?.clientSecret) {
body.gitSource.githubApp.clientSecret = decrypt(body.gitSource.githubApp.clientSecret);
}
if (body.gitSource?.githubApp?.webhookSecret) {
body.gitSource.githubApp.webhookSecret = decrypt(body.gitSource.githubApp.webhookSecret);
}
if (body.gitSource?.githubApp?.privateKey) {
body.gitSource.githubApp.privateKey = decrypt(body.gitSource.githubApp.privateKey);
}
if (body?.gitSource?.gitlabApp?.appSecret) {
body.gitSource.gitlabApp.appSecret = decrypt(body.gitSource.gitlabApp.appSecret);
}
if (body?.secrets.length > 0) {
body.secrets = body.secrets.map((s) => {
s.value = decrypt(s.value);
return s;
});
}
return { ...body };
}
export async function configureGitRepository({ id, repository, branch, projectId, webhookToken }) {
if (webhookToken) {
const encryptedWebhookToken = encrypt(webhookToken);
return await prisma.application.update({
where: { id },
data: {
repository,
branch,
projectId,
gitSource: { update: { gitlabApp: { update: { webhookToken: encryptedWebhookToken } } } }
}
});
} else {
return await prisma.application.update({
where: { id },
data: { repository, branch, projectId }
});
}
}
export async function configureBuildPack({ id, buildPack }) {
return await prisma.application.update({ where: { id }, data: { buildPack } });
}
export async function configureApplication({
id,
buildPack,
name,
fqdn,
port,
installCommand,
buildCommand,
startCommand,
baseDirectory,
publishDirectory
}) {
return await prisma.application.update({
where: { id },
data: {
buildPack,
fqdn,
port,
installCommand,
buildCommand,
startCommand,
baseDirectory,
publishDirectory,
name
}
});
}
export async function setApplicationSettings({ id, debug, previews }) {
return await prisma.application.update({
where: { id },
data: { settings: { update: { debug, previews } } },
include: { destinationDocker: true }
});
}
export async function createBuild({
id,
applicationId,
destinationDockerId,
gitSourceId,
githubAppId,
gitlabAppId,
type
}) {
return await prisma.build.create({
data: {
id,
applicationId,
destinationDockerId,
gitSourceId,
githubAppId,
gitlabAppId,
status: 'running',
type
}
});
}

View File

@@ -0,0 +1,38 @@
import { getDomain } from '$lib/common';
import { prisma, PrismaErrorHandler } from './common';
export async function isBranchAlreadyUsed({ repository, branch, id }) {
const application = await prisma.application.findUnique({
where: { id },
include: { gitSource: true }
});
return await prisma.application.findFirst({
where: { branch, repository, gitSource: { type: application.gitSource.type }, id: { not: id } }
});
}
export async function isDockerNetworkExists({ network }) {
return await prisma.destinationDocker.findFirst({ where: { network } });
}
export async function isSecretExists({ id, name }) {
return await prisma.secret.findFirst({ where: { name, applicationId: id } });
}
export async function isDomainConfigured({ id, fqdn }) {
const domain = getDomain(fqdn);
const foundApp = await prisma.application.findFirst({
where: { fqdn: { endsWith: domain }, id: { not: id } },
select: { fqdn: true }
});
const foundService = await prisma.service.findFirst({
where: { fqdn: { endsWith: domain }, id: { not: id } },
select: { fqdn: true }
});
const coolifyFqdn = await prisma.setting.findFirst({
where: { fqdn: { endsWith: domain }, id: { not: id } },
select: { fqdn: true }
});
if (foundApp || foundService || coolifyFqdn) return true;
return false;
}

232
src/lib/database/common.ts Normal file
View File

@@ -0,0 +1,232 @@
import { dev } from '$app/env';
import { sentry } from '$lib/common';
import * as Prisma from '@prisma/client';
import { default as ProdPrisma } from '@prisma/client';
import generator from 'generate-password';
import forge from 'node-forge';
export function generatePassword(length = 24) {
return generator.generate({
length,
numbers: true,
strict: true
});
}
let { PrismaClient } = Prisma;
let P = Prisma.Prisma;
if (!dev) {
PrismaClient = ProdPrisma.PrismaClient;
P = ProdPrisma.Prisma;
}
let prismaOptions = {
rejectOnNotFound: false
};
if (dev) {
prismaOptions = {
errorFormat: 'pretty',
rejectOnNotFound: false,
log: [
{
emit: 'event',
level: 'query'
}
]
};
}
export const prisma = new PrismaClient(prismaOptions);
export function PrismaErrorHandler(e) {
sentry.captureException(e);
const payload = {
status: e.status || 500,
body: {
message: 'Ooops, something is not okay, are you okay?',
error: e.error || e.message
}
};
if (e.name === 'NotFoundError') {
payload.status = 404;
}
if (e instanceof P.PrismaClientKnownRequestError) {
if (e.code === 'P2002') {
payload.body.message = 'Already exists. Choose another name.';
}
}
// console.error(e)
return payload;
}
export async function generateSshKeyPair(): Promise<{ publicKey: string; privateKey: string }> {
return await new Promise(async (resolve, reject) => {
forge.pki.rsa.generateKeyPair({ bits: 4096, workers: -1 }, function (err, keys) {
if (keys) {
resolve({
publicKey: forge.ssh.publicKeyToOpenSSH(keys.publicKey),
privateKey: forge.ssh.privateKeyToOpenSSH(keys.privateKey)
});
} else {
reject(keys);
}
});
});
}
export const supportedDatabaseTypesAndVersions = [
{
name: 'mongodb',
fancyName: 'MongoDB',
baseImage: 'bitnami/mongodb',
versions: ['5.0.5', '4.4.11', '4.2.18', '4.0.27']
},
{ name: 'mysql', fancyName: 'MySQL', baseImage: 'bitnami/mysql', versions: ['8.0.27', '5.7.36'] },
{
name: 'postgresql',
fancyName: 'PostgreSQL',
baseImage: 'bitnami/postgresql',
versions: ['14.1.0', '13.5.0', '12.9.0', '11.14.0', '10.19.0', '9.6.24']
},
{
name: 'redis',
fancyName: 'Redis',
baseImage: 'bitnami/redis',
versions: ['6.2.6', '6.0.16', '5.0.14']
},
{ name: 'couchdb', fancyName: 'CouchDB', baseImage: 'bitnami/couchdb', versions: ['3.2.1'] }
];
export const supportedServiceTypesAndVersions = [
{
name: 'plausibleanalytics',
fancyName: 'Plausible Analytics',
baseImage: 'plausible/analytics',
versions: ['latest']
},
{ name: 'nocodb', fancyName: 'NocoDB', baseImage: 'nocodb/nocodb', versions: ['latest'] },
{ name: 'minio', fancyName: 'MinIO', baseImage: 'minio/minio', versions: ['latest'] },
{
name: 'vscodeserver',
fancyName: 'VSCode Server',
baseImage: 'codercom/code-server',
versions: ['latest']
},
{
name: 'wordpress',
fancyName: 'Wordpress',
baseImage: 'wordpress',
versions: ['latest', 'php8.1', 'php8.0', 'php7.4', 'php7.3']
}
];
export function getVersions(type) {
const found = supportedDatabaseTypesAndVersions.find((t) => t.name === type);
if (found) {
return found.versions;
}
return [];
}
export function getDatabaseImage(type) {
const found = supportedDatabaseTypesAndVersions.find((t) => t.name === type);
if (found) {
return found.baseImage;
}
return '';
}
export function getServiceImage(type) {
const found = supportedServiceTypesAndVersions.find((t) => t.name === type);
if (found) {
return found.baseImage;
}
return '';
}
export function generateDatabaseConfiguration(database) {
const {
id,
dbUser,
dbUserPassword,
rootUser,
rootUserPassword,
defaultDatabase,
version,
type,
settings: { appendOnly }
} = database;
const baseImage = getDatabaseImage(type);
if (type === 'mysql') {
return {
// url: `mysql://${dbUser}:${dbUserPassword}@${id}:${isPublic ? port : 3306}/${defaultDatabase}`,
privatePort: 3306,
environmentVariables: {
MYSQL_USER: dbUser,
MYSQL_PASSWORD: dbUserPassword,
MYSQL_ROOT_PASSWORD: rootUserPassword,
MYSQL_ROOT_USER: rootUser,
MYSQL_DATABASE: defaultDatabase
},
image: `${baseImage}:${version}`,
volume: `${id}-${type}-data:/bitnami/mysql/data`,
ulimits: {}
};
} else if (type === 'mongodb') {
return {
// url: `mongodb://${dbUser}:${dbUserPassword}@${id}:${isPublic ? port : 27017}/${defaultDatabase}`,
privatePort: 27017,
environmentVariables: {
MONGODB_ROOT_USER: rootUser,
MONGODB_ROOT_PASSWORD: rootUserPassword
},
image: `${baseImage}:${version}`,
volume: `${id}-${type}-data:/bitnami/mongodb`,
ulimits: {}
};
} else if (type === 'postgresql') {
return {
// url: `psql://${dbUser}:${dbUserPassword}@${id}:${isPublic ? port : 5432}/${defaultDatabase}`,
privatePort: 5432,
environmentVariables: {
POSTGRESQL_PASSWORD: dbUserPassword,
POSTGRESQL_USERNAME: dbUser,
POSTGRESQL_DATABASE: defaultDatabase
},
image: `${baseImage}:${version}`,
volume: `${id}-${type}-data:/bitnami/postgresql`,
ulimits: {}
};
} else if (type === 'redis') {
return {
// url: `redis://${dbUser}:${dbUserPassword}@${id}:${isPublic ? port : 6379}/${defaultDatabase}`,
privatePort: 6379,
environmentVariables: {
REDIS_PASSWORD: dbUserPassword,
REDIS_AOF_ENABLED: appendOnly ? 'yes' : 'no'
},
image: `${baseImage}:${version}`,
volume: `${id}-${type}-data:/bitnami/redis/data`,
ulimits: {}
};
} else if (type === 'couchdb') {
return {
// url: `couchdb://${dbUser}:${dbUserPassword}@${id}:${isPublic ? port : 5984}/${defaultDatabase}`,
privatePort: 5984,
environmentVariables: {
COUCHDB_PASSWORD: dbUserPassword,
COUCHDB_USER: dbUser
},
image: `${baseImage}:${version}`,
volume: `${id}-${type}-data:/bitnami/couchdb`,
ulimits: {}
};
}
// } else if (type === 'clickhouse') {
// return {
// url: `clickhouse://${dbUser}:${dbUserPassword}@${id}:${port}/${defaultDatabase}`,
// privatePort: 9000,
// image: `bitnami/clickhouse-server:${version}`,
// volume: `${id}-${type}-data:/var/lib/clickhouse`,
// ulimits: {
// nofile: {
// soft: 262144,
// hard: 262144
// }
// }
// }
// }
}

View File

@@ -0,0 +1,148 @@
import { decrypt, encrypt } from '$lib/crypto';
import { dockerInstance } from '$lib/docker';
import cuid from 'cuid';
import { generatePassword } from '.';
import { prisma, PrismaErrorHandler } from './common';
import getPort from 'get-port';
import { asyncExecShell, getEngine, removeContainer } from '$lib/common';
export async function listDatabases(teamId) {
return await prisma.database.findMany({ where: { teams: { some: { id: teamId } } } });
}
export async function newDatabase({ name, teamId }) {
const dbUser = cuid();
const dbUserPassword = encrypt(generatePassword());
const rootUser = cuid();
const rootUserPassword = encrypt(generatePassword());
const defaultDatabase = cuid();
let publicPort = await getPort();
let i = 0;
do {
const usedPorts = await prisma.database.findMany({ where: { publicPort } });
if (usedPorts.length === 0) break;
publicPort = await getPort();
i++;
} while (i < 10);
if (i === 9) {
throw {
error: 'No free port found!? Is it possible?'
};
}
return await prisma.database.create({
data: {
name,
publicPort,
defaultDatabase,
dbUser,
dbUserPassword,
rootUser,
rootUserPassword,
teams: { connect: { id: teamId } },
settings: { create: { isPublic: false } }
}
});
}
export async function getDatabase({ id, teamId }) {
const body = await prisma.database.findFirst({
where: { id, teams: { some: { id: teamId } } },
include: { destinationDocker: true, settings: true }
});
if (body.dbUserPassword) body.dbUserPassword = decrypt(body.dbUserPassword);
if (body.rootUserPassword) body.rootUserPassword = decrypt(body.rootUserPassword);
return { ...body };
}
export async function removeDatabase({ id }) {
await prisma.databaseSettings.deleteMany({ where: { databaseId: id } });
await prisma.database.delete({ where: { id } });
return;
}
export async function configureDatabaseType({ id, type }) {
return await prisma.database.update({
where: { id },
data: { type }
});
}
export async function setDatabase({
id,
version,
isPublic,
appendOnly
}: {
id: string;
version?: string;
isPublic?: boolean;
appendOnly?: boolean;
}) {
return await prisma.database.update({
where: { id },
data: {
version,
settings: { upsert: { update: { isPublic, appendOnly }, create: { isPublic, appendOnly } } }
}
});
}
export async function updateDatabase({
id,
name,
defaultDatabase,
dbUser,
dbUserPassword,
rootUser,
rootUserPassword,
version
}) {
const encryptedDbUserPassword = dbUserPassword && encrypt(dbUserPassword);
const encryptedRootUserPassword = rootUserPassword && encrypt(rootUserPassword);
return await prisma.database.update({
where: { id },
data: {
name,
defaultDatabase,
dbUser,
dbUserPassword: encryptedDbUserPassword,
rootUser,
rootUserPassword: encryptedRootUserPassword,
version
}
});
}
// export async function setDatabaseSettings({ id, isPublic }) {
// try {
// await prisma.databaseSettings.update({ where: { databaseId: id }, data: { isPublic } })
// return { status: 201 }
// } catch (e) {
// throw PrismaErrorHandler(e)
// }
// }
export async function stopDatabase(database) {
let everStarted = false;
const {
id,
destinationDockerId,
destinationDocker: { engine }
} = database;
if (destinationDockerId) {
try {
const host = getEngine(engine);
const { stdout } = await asyncExecShell(
`DOCKER_HOST=${host} docker inspect --format '{{json .State}}' ${id}`
);
if (stdout) {
everStarted = true;
await removeContainer(id, engine);
}
} catch (error) {
//
}
}
return everStarted;
}

View File

@@ -0,0 +1,132 @@
import { asyncExecShell, getEngine } from '$lib/common';
import { dockerInstance } from '$lib/docker';
import { defaultProxyImageHttp, defaultProxyImageTcp, startCoolifyProxy } from '$lib/haproxy';
import { getDatabaseImage } from '.';
import { prisma, PrismaErrorHandler } from './common';
export async function listDestinations(teamId) {
return await prisma.destinationDocker.findMany({ where: { teams: { some: { id: teamId } } } });
}
export async function configureDestinationForService({ id, destinationId }) {
return await prisma.service.update({
where: { id },
data: { destinationDocker: { connect: { id: destinationId } } }
});
}
export async function configureDestinationForApplication({ id, destinationId }) {
return await prisma.application.update({
where: { id },
data: { destinationDocker: { connect: { id: destinationId } } }
});
}
export async function configureDestinationForDatabase({ id, destinationId }) {
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}`);
asyncExecShell(`DOCKER_HOST=${host} docker pull coollabsio/${defaultProxyImageTcp}`);
asyncExecShell(`DOCKER_HOST=${host} docker pull coollabsio/${defaultProxyImageHttp}`);
asyncExecShell(`DOCKER_HOST=${host} docker pull certbot/certbot:latest`);
asyncExecShell(`DOCKER_HOST=${host} docker pull alpine:latest`);
}
}
}
export async function updateDestination({ id, name, engine, network }) {
return await prisma.destinationDocker.update({ where: { id }, data: { name, engine, network } });
}
export async function newDestination({ name, teamId, engine, network, isCoolifyProxyUsed }) {
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) {
if (proxyConfigured.isCoolifyProxyUsed) {
isCoolifyProxyUsed = true;
} else {
isCoolifyProxyUsed = false;
}
}
await prisma.destinationDocker.updateMany({ where: { engine }, data: { isCoolifyProxyUsed } });
}
if (isCoolifyProxyUsed) await startCoolifyProxy(engine);
return destination.id;
}
export async function removeDestination({ id }) {
const destination = await prisma.destinationDocker.delete({ where: { id } });
if (destination.isCoolifyProxyUsed) {
const host = getEngine(destination.engine);
const { network } = destination;
const { stdout: found } = await asyncExecShell(
`DOCKER_HOST=${host} docker ps -a --filter network=${network} --filter name=coolify-haproxy --format '{{.}}'`
);
if (found) {
await asyncExecShell(
`DOCKER_HOST="${host}" docker network disconnect ${network} coolify-haproxy`
);
await asyncExecShell(`DOCKER_HOST="${host}" docker network rm ${network}`);
}
}
}
export async function getDestination({ id, teamId }) {
return await prisma.destinationDocker.findFirst({
where: { id, teams: { some: { id: teamId } } }
});
}
export async function getDestinationByApplicationId({ id, teamId }) {
return await prisma.destinationDocker.findFirst({
where: { application: { some: { id } }, teams: { some: { id: teamId } } }
});
}
export async function setDestinationSettings({ engine, isCoolifyProxyUsed }) {
return await prisma.destinationDocker.updateMany({
where: { engine },
data: { isCoolifyProxyUsed }
});
// if (isCoolifyProxyUsed) {
// await installCoolifyProxy(engine)
// await configureNetworkCoolifyProxy(engine)
// } else {
// // TODO: must check if other destination is using the proxy??? or not?
// const domain = await prisma.setting.findUnique({ where: { name: 'domain' }, rejectOnNotFound: false })
// if (!domain) {
// await uninstallCoolifyProxy(engine)
// } else {
// return {
// stastus: 500,
// body: {
// message: 'You can not disable the Coolify proxy while the domain is set for Coolify itself.'
// }
// }
// }
// }
}

View File

@@ -0,0 +1,71 @@
import { decrypt, encrypt } from '$lib/crypto';
import { prisma, PrismaErrorHandler } from './common';
export async function listSources(teamId) {
return await prisma.gitSource.findMany({
where: { teams: { some: { id: teamId } } },
include: { githubApp: true, gitlabApp: true }
});
}
export async function newSource({ name, teamId, type, htmlUrl, apiUrl, organization }) {
return await prisma.gitSource.create({
data: {
teams: { connect: { id: teamId } },
name,
type,
htmlUrl,
apiUrl,
organization
}
});
}
export async function removeSource({ id }) {
// TODO: Disconnect application with this sourceId! Maybe not needed?
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 } });
}
export async function getSource({ id, teamId }) {
let body = await prisma.gitSource.findFirst({
where: { id, teams: { some: { id: teamId } } },
include: { githubApp: true, gitlabApp: true }
});
if (body?.githubApp?.clientSecret)
body.githubApp.clientSecret = decrypt(body.githubApp.clientSecret);
if (body?.githubApp?.webhookSecret)
body.githubApp.webhookSecret = decrypt(body.githubApp.webhookSecret);
if (body?.githubApp?.privateKey) body.githubApp.privateKey = decrypt(body.githubApp.privateKey);
if (body?.gitlabApp?.appSecret) body.gitlabApp.appSecret = decrypt(body.gitlabApp.appSecret);
return body;
}
export async function addSource({ id, appId, teamId, oauthId, groupName, appSecret }) {
const encrptedAppSecret = encrypt(appSecret);
return await prisma.gitlabApp.create({
data: {
teams: { connect: { id: teamId } },
appId,
oauthId,
groupName,
appSecret: encrptedAppSecret,
gitSource: { connect: { id } }
}
});
}
export async function configureGitsource({ id, gitSourceId }) {
return await prisma.application.update({
where: { id },
data: { gitSource: { connect: { id: gitSourceId } } }
});
}
export async function updateGitsource({ id, name }) {
return await prisma.gitSource.update({
where: { id },
data: { name }
});
}

View File

@@ -0,0 +1,44 @@
import { decrypt, encrypt } from '$lib/crypto';
import { prisma, PrismaErrorHandler } from './common';
export async function addInstallation({ gitSourceId, installation_id }) {
const source = await prisma.gitSource.findUnique({
where: { id: gitSourceId },
include: { githubApp: true }
});
return await prisma.githubApp.update({
where: { id: source.githubAppId },
data: { installationId: Number(installation_id) }
});
}
export async function getUniqueGithubApp({ githubAppId }) {
let body = await prisma.githubApp.findUnique({ where: { id: githubAppId } });
if (body.privateKey) body.privateKey = decrypt(body.privateKey);
return body;
}
export async function createGithubApp({
id,
client_id,
slug,
client_secret,
pem,
webhook_secret,
state
}) {
const encryptedClientSecret = encrypt(client_secret);
const encryptedWebhookSecret = encrypt(webhook_secret);
const encryptedPem = encrypt(pem);
return await prisma.githubApp.create({
data: {
appId: id,
name: slug,
clientId: client_id,
clientSecret: encryptedClientSecret,
webhookSecret: encryptedWebhookSecret,
privateKey: encryptedPem,
gitSource: { connect: { id: state } }
}
});
}

View File

@@ -0,0 +1,37 @@
import { encrypt } from '$lib/crypto';
import { generateSshKeyPair, prisma, PrismaErrorHandler } from './common';
export async function updateDeployKey({ id, deployKeyId }) {
const application = await prisma.application.findUnique({
where: { id },
include: { gitSource: { include: { gitlabApp: true } } }
});
return await prisma.gitlabApp.update({
where: { id: application.gitSource.gitlabApp.id },
data: { deployKeyId }
});
}
export async function getSshKey({ id }) {
const application = await prisma.application.findUnique({
where: { id },
include: { gitSource: { include: { gitlabApp: true } } }
});
return { status: 200, body: { publicKey: application.gitSource.gitlabApp.publicSshKey } };
}
export async function generateSshKey({ id }) {
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 { status: 201, body: { publicKey: keys.publicKey } };
} else {
return { status: 200 };
}
}

14
src/lib/database/index.ts Normal file
View File

@@ -0,0 +1,14 @@
export * from './applications';
export * from './checks';
export * from './common';
export * from './destinations';
export * from './github';
export * from './gitlab';
export * from './gitSources';
export * from './logs';
export * from './settings';
export * from './users';
export * from './teams';
export * from './secrets';
export * from './databases';
export * from './services';

13
src/lib/database/logs.ts Normal file
View File

@@ -0,0 +1,13 @@
import { prisma, PrismaErrorHandler } from './common';
export async function listLogs({ buildId, last = 0 }) {
try {
const body = await prisma.buildLog.findMany({
where: { buildId, time: { gt: last } },
orderBy: { time: 'asc' }
});
return [...body];
} catch (e) {
throw PrismaErrorHandler(e);
}
}

View File

@@ -0,0 +1,21 @@
import { encrypt } from '$lib/crypto';
import { prisma, PrismaErrorHandler } from './common';
export async function listSecrets({ applicationId }) {
return await prisma.secret.findMany({
where: { applicationId },
orderBy: { createdAt: 'desc' },
select: { id: true, createdAt: true, name: true, isBuildSecret: true }
});
}
export async function createSecret({ id, name, value, isBuildSecret }) {
value = encrypt(value);
return await prisma.secret.create({
data: { name, value, isBuildSecret, application: { connect: { id } } }
});
}
export async function removeSecret({ id, name }) {
return await prisma.secret.deleteMany({ where: { applicationId: id, name } });
}

View File

@@ -0,0 +1,137 @@
import { decrypt, encrypt } from '$lib/crypto';
import { dockerInstance } from '$lib/docker';
import cuid from 'cuid';
import { generatePassword } from '.';
import { prisma, PrismaErrorHandler } from './common';
export async function listServices(teamId) {
return await prisma.service.findMany({ where: { teams: { some: { id: teamId } } } });
}
export async function newService({ name, teamId }) {
return await prisma.service.create({ data: { name, teams: { connect: { id: teamId } } } });
}
export async function getService({ id, teamId }) {
const body = await prisma.service.findFirst({
where: { id, teams: { some: { id: teamId } } },
include: {
destinationDocker: true,
plausibleAnalytics: true,
minio: true,
vscodeserver: true,
wordpress: true
}
});
if (body.plausibleAnalytics?.postgresqlPassword)
body.plausibleAnalytics.postgresqlPassword = decrypt(
body.plausibleAnalytics.postgresqlPassword
);
if (body.plausibleAnalytics?.password)
body.plausibleAnalytics.password = decrypt(body.plausibleAnalytics.password);
if (body.plausibleAnalytics?.secretKeyBase)
body.plausibleAnalytics.secretKeyBase = decrypt(body.plausibleAnalytics.secretKeyBase);
if (body.minio?.rootUserPassword)
body.minio.rootUserPassword = decrypt(body.minio.rootUserPassword);
if (body.vscodeserver?.password) body.vscodeserver.password = decrypt(body.vscodeserver.password);
if (body.wordpress?.mysqlPassword)
body.wordpress.mysqlPassword = decrypt(body.wordpress.mysqlPassword);
if (body.wordpress?.mysqlRootUserPassword)
body.wordpress.mysqlRootUserPassword = decrypt(body.wordpress.mysqlRootUserPassword);
return { ...body };
}
export async function configureServiceType({ id, type }) {
if (type === 'plausibleanalytics') {
const password = encrypt(generatePassword());
const postgresqlUser = cuid();
const postgresqlPassword = encrypt(generatePassword());
const postgresqlDatabase = 'plausibleanalytics';
const secretKeyBase = encrypt(generatePassword(64));
await prisma.service.update({
where: { id },
data: {
type,
plausibleAnalytics: {
create: {
postgresqlDatabase,
postgresqlUser,
postgresqlPassword,
password,
secretKeyBase
}
}
}
});
} else if (type === 'nocodb') {
await prisma.service.update({
where: { id },
data: { type }
});
} else if (type === 'minio') {
const rootUser = cuid();
const rootUserPassword = encrypt(generatePassword());
await prisma.service.update({
where: { id },
data: { type, minio: { create: { rootUser, rootUserPassword } } }
});
} else if (type === 'vscodeserver') {
const password = encrypt(generatePassword());
await prisma.service.update({
where: { id },
data: { type, vscodeserver: { create: { password } } }
});
} else if (type === 'wordpress') {
const mysqlUser = cuid();
const mysqlPassword = encrypt(generatePassword());
const mysqlRootUser = cuid();
const mysqlRootUserPassword = encrypt(generatePassword());
await prisma.service.update({
where: { id },
data: {
type,
wordpress: { create: { mysqlPassword, mysqlRootUserPassword, mysqlRootUser, mysqlUser } }
}
});
}
}
export async function setService({ id, version }) {
return await prisma.service.update({
where: { id },
data: { version }
});
}
export async function updatePlausibleAnalyticsService({ id, fqdn, email, username, name }) {
await prisma.plausibleAnalytics.update({ where: { serviceId: id }, data: { email, username } });
await prisma.service.update({ where: { id }, data: { name, fqdn } });
}
export async function updateNocoDbOrMinioService({ id, fqdn, name }) {
return await prisma.service.update({ where: { id }, data: { fqdn, name } });
}
export async function updateVsCodeServer({ id, fqdn, name }) {
return await prisma.service.update({ where: { id }, data: { fqdn, name } });
}
export async function updateWordpress({ id, fqdn, name, mysqlDatabase, extraConfig }) {
return await prisma.service.update({
where: { id },
data: { fqdn, name, wordpress: { update: { mysqlDatabase, extraConfig } } }
});
}
export async function updateMinioService({ id, publicPort }) {
return await prisma.minio.update({ where: { serviceId: id }, data: { publicPort } });
}
export async function removeService({ id }) {
await prisma.plausibleAnalytics.deleteMany({ where: { serviceId: id } });
await prisma.minio.deleteMany({ where: { serviceId: id } });
await prisma.vscodeserver.deleteMany({ where: { serviceId: id } });
await prisma.wordpress.deleteMany({ where: { serviceId: id } });
await prisma.service.delete({ where: { id } });
}

View File

@@ -0,0 +1,8 @@
import { decrypt } from '$lib/crypto';
import { prisma } from './common';
export async function listSettings() {
let settings = await prisma.setting.findFirst({});
if (settings.proxyPassword) settings.proxyPassword = decrypt(settings.proxyPassword);
return settings;
}

20
src/lib/database/teams.ts Normal file
View File

@@ -0,0 +1,20 @@
import { prisma, PrismaErrorHandler } from './common';
export async function listTeams() {
return await prisma.team.findMany();
}
export async function newTeam({ name, userId }) {
return await prisma.team.create({
data: {
name,
permissions: { create: { user: { connect: { id: userId } }, permission: 'owner' } },
users: { connect: { id: userId } }
}
});
}
export async function getMyTeams({ userId }) {
return await prisma.permission.findMany({
where: { userId },
include: { team: { include: { _count: { select: { users: true } } } } }
});
}

125
src/lib/database/users.ts Normal file
View File

@@ -0,0 +1,125 @@
import cuid from 'cuid';
import bcrypt from 'bcrypt';
import { prisma, PrismaErrorHandler } from './common';
import { asyncExecShell, removeContainer, uniqueName } from '$lib/common';
import * as db from '$lib/database';
import { startCoolifyProxy } from '$lib/haproxy';
export async function login({ email, password }) {
const saltRounds = 15;
const users = await prisma.user.count();
const userFound = await prisma.user.findUnique({
where: { email },
include: { teams: true },
rejectOnNotFound: false
});
// Registration disabled if database is not seeded properly
const { isRegistrationEnabled, id } = await db.listSettings();
let uid = cuid();
// Disable registration if we are registering the first user.
if (users === 0) {
await prisma.setting.update({ where: { id }, data: { isRegistrationEnabled: false } });
// Create default network & start Coolify Proxy
asyncExecShell(`docker network create --attachable coolify`)
.then(() => {
console.log('Network created');
})
.catch(() => {
console.log('Network already exists');
});
startCoolifyProxy('/var/run/docker.sock')
.then(() => {
console.log('Coolify Proxy Started');
})
.catch((err) => {
console.log(err);
});
uid = '0';
}
if (userFound) {
if (userFound.type === 'email') {
const passwordMatch = await bcrypt.compare(password, userFound.password);
if (!passwordMatch) {
throw {
error: 'Wrong password or email address.'
};
}
uid = userFound.id;
}
} else {
// If registration disabled, return 403
if (!isRegistrationEnabled) {
throw {
error: 'Registration disabled by administrator.'
};
}
const hashedPassword = await bcrypt.hash(password, saltRounds);
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 }
});
}
}
// const token = jsonwebtoken.sign({}, secretKey, {
// expiresIn: 15778800,
// algorithm: 'HS256',
// audience: 'coolify',
// issuer: 'coolify',
// jwtid: uid,
// subject: `User:${uid}`,
// notBefore: -1000
// });
return {
status: 200,
headers: {
'Set-Cookie': `teamId=${uid}; HttpOnly; Path=/; Max-Age=15778800;`
},
body: {
uid,
teamId: uid
}
};
}
export async function getUser({ userId }) {
return await prisma.user.findUnique({ where: { id: userId } });
}

7
src/lib/dayjs.ts Normal file
View File

@@ -0,0 +1,7 @@
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc.js';
import relativeTime from 'dayjs/plugin/relativeTime.js';
dayjs.extend(utc);
dayjs.extend(relativeTime);
export { dayjs };

160
src/lib/docker.ts Normal file
View File

@@ -0,0 +1,160 @@
import Dockerode from 'dockerode';
import { promises as fs } from 'fs';
import { saveBuildLog } from './common';
export async function buildCacheImageWithNode(data, imageForBuild) {
const {
applicationId,
tag,
workdir,
docker,
buildId,
baseDirectory,
installCommand,
buildCommand,
debug,
secrets
} = data;
const Dockerfile: Array<string> = [];
Dockerfile.push(`FROM ${imageForBuild}`);
Dockerfile.push('WORKDIR /usr/src/app');
if (secrets.length > 0) {
secrets.forEach((secret) => {
if (!secret.isBuildSecret) {
Dockerfile.push(`ARG ${secret.name} ${secret.value}`);
}
});
}
// TODO: If build command defined, install command should be the default yarn install
if (installCommand) {
Dockerfile.push(`COPY ./${baseDirectory || ''}package*.json ./`);
try {
await fs.stat(`${workdir}/yarn.lock`);
Dockerfile.push(`COPY ./${baseDirectory || ''}yarn.lock ./`);
} catch (error) {}
try {
await fs.stat(`${workdir}/pnpm-lock.yaml`);
Dockerfile.push(`COPY ./${baseDirectory || ''}pnpm-lock.yaml ./`);
} catch (error) {}
Dockerfile.push(`RUN ${installCommand}`);
}
Dockerfile.push(`COPY ./${baseDirectory || ''} ./`);
Dockerfile.push(`RUN ${buildCommand}`);
await fs.writeFile(`${workdir}/Dockerfile-cache`, Dockerfile.join('\n'));
await buildImage({ applicationId, tag, workdir, docker, buildId, isCache: true, debug });
}
export async function buildCacheImageWithCargo(data, imageForBuild) {
const {
applicationId,
tag,
workdir,
docker,
buildId,
baseDirectory,
installCommand,
buildCommand,
debug,
secrets
} = data;
const Dockerfile: Array<string> = [];
Dockerfile.push(`FROM ${imageForBuild} as planner-${applicationId}`);
Dockerfile.push('WORKDIR /usr/src/app');
Dockerfile.push('RUN cargo install cargo-chef');
Dockerfile.push('COPY . .');
Dockerfile.push('RUN cargo chef prepare --recipe-path recipe.json');
Dockerfile.push(`FROM ${imageForBuild}`);
Dockerfile.push('WORKDIR /usr/src/app');
Dockerfile.push('RUN cargo install cargo-chef');
Dockerfile.push(`COPY --from=planner-${applicationId} /usr/src/app/recipe.json recipe.json`);
Dockerfile.push('RUN cargo chef cook --release --recipe-path recipe.json');
await fs.writeFile(`${workdir}/Dockerfile-cache`, Dockerfile.join('\n'));
await buildImage({ applicationId, tag, workdir, docker, buildId, isCache: true, debug });
}
export async function buildImage({
applicationId,
tag,
workdir,
docker,
buildId,
isCache = false,
debug = false
}) {
if (isCache) {
saveBuildLog({ line: `Building cache image started.`, buildId, applicationId });
} else {
saveBuildLog({ line: `Building image started.`, buildId, applicationId });
}
if (!debug && isCache) {
saveBuildLog({
line: `Debug turned off. To see more details, allow it in the configuration.`,
buildId,
applicationId
});
}
const stream = await docker.engine.buildImage(
{ src: ['.'], context: workdir },
{
dockerfile: isCache ? 'Dockerfile-cache' : 'Dockerfile',
t: `${applicationId}:${tag}${isCache ? '-cache' : ''}`
}
);
await streamEvents({ stream, docker, buildId, applicationId, debug });
}
export function dockerInstance({ destinationDocker }): { engine: Dockerode; network: string } {
// new Docker({protocol:"ssh", host: '188.34.164.25',port: 22, username:'root', sshOptions: {agentForward: true, agent:process.env.SSH_AUTH_SOCK}})
return {
engine: new Dockerode({
socketPath: destinationDocker.engine
}),
network: destinationDocker.network
};
}
export async function streamEvents({ stream, docker, buildId, applicationId, debug }) {
await new Promise((resolve, reject) => {
docker.engine.modem.followProgress(stream, onFinished, onProgress);
function onFinished(err, res) {
if (err) reject(err);
resolve(res);
}
function onProgress(event) {
if (event.error) {
reject(event.error);
} else if (event.stream) {
if (event.stream !== '\n') {
if (debug)
saveBuildLog({ line: `${event.stream.replace('\n', '')}`, buildId, applicationId });
}
}
}
});
}
export const baseServiceConfigurationDocker = {
restart_policy: {
condition: 'any',
max_attempts: 6
}
};
export const baseServiceConfigurationSwarm = {
replicas: 1,
restart_policy: {
condition: 'any',
max_attempts: 6
},
update_config: {
parallelism: 1,
delay: '10s',
order: 'start-first'
},
rollback_config: {
parallelism: 1,
delay: '10s',
order: 'start-first',
failure_action: 'rollback'
}
};

81
src/lib/form.ts Normal file
View File

@@ -0,0 +1,81 @@
import { toast } from '@zerodevx/svelte-toast';
export function errorNotification(message: string) {
console.error(message);
if (typeof message !== 'string') {
toast.push('Ooops, something is not okay, are you okay?');
} else {
toast.push(message);
}
}
export function enhance(
form: HTMLFormElement,
{
beforeSubmit,
final,
pending,
error,
result
}: {
beforeSubmit?: () => Promise<void>;
final?: () => Promise<void>;
pending?: (data: FormData, form: HTMLFormElement) => void;
error?: (res: Response, error: Error, form: HTMLFormElement) => void;
result?: (res: Response, form: HTMLFormElement) => void;
}
): { destroy: () => void } {
let current_token: unknown;
async function handle_submit(e: Event) {
const token = (current_token = {});
e.preventDefault();
let body = new FormData(form);
let parsedData = body;
body.forEach((data, key) => {
if (data === '' || data === null) parsedData.delete(key);
});
body = parsedData;
if (beforeSubmit) await beforeSubmit();
if (pending) pending(body, form);
try {
const res = await fetch(form.action, {
method: form.method,
headers: {
accept: 'application/json'
},
body
});
if (token !== current_token) return;
if (res.ok) {
if (result) result(res, form);
} else if (error) {
error(res, null, form);
} else {
// TODO: Add error frontend here
const { message } = await res.json();
errorNotification(message);
}
} catch (e) {
if (error) {
error(null, e, form);
} else {
throw e;
}
} finally {
if (final) final();
}
}
form.addEventListener('submit', handle_submit);
return {
destroy() {
form.removeEventListener('submit', handle_submit);
}
};
}

9
src/lib/github.ts Normal file
View File

@@ -0,0 +1,9 @@
export function dashify(str: string, options?: any): string {
if (typeof str !== 'string') return str;
return str
.trim()
.replace(/\W/g, (m) => (/[À-ž]/.test(m) ? m : '-'))
.replace(/^-+|-+$/g, '')
.replace(/-{2,}/g, (m) => (options && options.condense ? '-' : m))
.toLowerCase();
}

634
src/lib/haproxy/index.ts Normal file
View File

@@ -0,0 +1,634 @@
import { dev } from '$app/env';
import { asyncExecShell, getEngine } from '$lib/common';
import got from 'got';
import * as db from '$lib/database';
import { letsEncrypt } from '$lib/letsencrypt';
const url = dev ? 'http://localhost:5555' : 'http://coolify-haproxy:5555';
export const defaultProxyImage = `coolify-haproxy-alpine:latest`;
export const defaultProxyImageTcp = `coolify-haproxy-tcp-alpine:latest`;
export const defaultProxyImageHttp = `coolify-haproxy-http-alpine:latest`;
export async function haproxyInstance() {
const { proxyPassword } = await db.listSettings();
return got.extend({
prefixUrl: url,
username: 'admin',
password: proxyPassword
});
}
export async function getRawConfiguration(): Promise<RawHaproxyConfiguration> {
return await (await haproxyInstance()).get(`v2/services/haproxy/configuration/raw`).json();
}
export async function getNextTransactionVersion(): Promise<number> {
const raw = await getRawConfiguration();
if (raw?._version) {
return raw._version;
}
return 1;
}
export async function getNextTransactionId(): Promise<string> {
const version = await getNextTransactionVersion();
const newTransaction: NewTransaction = await (
await haproxyInstance()
)
.post('v2/services/haproxy/transactions', {
searchParams: {
version
}
})
.json();
return newTransaction.id;
}
export async function completeTransaction(transactionId) {
const haproxy = await haproxyInstance();
return await haproxy.put(`v2/services/haproxy/transactions/${transactionId}`);
}
export async function removeProxyConfiguration({ domain }) {
const haproxy = await haproxyInstance();
const transactionId = await getNextTransactionId();
const backendFound = await haproxy
.get(`v2/services/haproxy/configuration/backends/${domain}`)
.json();
if (backendFound) {
await haproxy
.delete(`v2/services/haproxy/configuration/backends/${domain}`, {
searchParams: {
transaction_id: transactionId
}
})
.json();
await completeTransaction(transactionId);
}
}
export async function forceSSLOffApplication({ domain }) {
if (!dev) {
const haproxy = await haproxyInstance();
await checkHAProxy(haproxy);
const transactionId = await getNextTransactionId();
try {
const rules: any = await haproxy
.get(`v2/services/haproxy/configuration/http_request_rules`, {
searchParams: {
parent_name: 'http',
parent_type: 'frontend'
}
})
.json();
if (rules.data.length > 0) {
const rule = rules.data.find((rule) => rule.cond_test.includes(`-i ${domain}`));
if (rule) {
await haproxy
.delete(`v2/services/haproxy/configuration/http_request_rules/${rule.index}`, {
searchParams: {
transaction_id: transactionId,
parent_name: 'http',
parent_type: 'frontend'
}
})
.json();
}
}
} catch (error) {
console.log(error);
} finally {
await completeTransaction(transactionId);
}
} else {
console.log(`[DEBUG] Removing ssl for ${domain}`);
}
}
export async function forceSSLOnApplication({ domain }) {
if (!dev) {
const haproxy = await haproxyInstance();
await checkHAProxy(haproxy);
const transactionId = await getNextTransactionId();
try {
const rules: any = await haproxy
.get(`v2/services/haproxy/configuration/http_request_rules`, {
searchParams: {
parent_name: 'http',
parent_type: 'frontend'
}
})
.json();
let nextRule = 0;
if (rules.data.length > 0) {
const rule = rules.data.find((rule) => rule.cond_test.includes(`-i ${domain}`));
if (rule) return;
nextRule = rules.data[rules.data.length - 1].index + 1;
}
await haproxy
.post(`v2/services/haproxy/configuration/http_request_rules`, {
searchParams: {
transaction_id: transactionId,
parent_name: 'http',
parent_type: 'frontend'
},
json: {
index: nextRule,
cond: 'if',
cond_test: `{ hdr(Host) -i ${domain} } !{ ssl_fc }`,
type: 'redirect',
redir_type: 'scheme',
redir_value: 'https',
redir_code: 301
}
})
.json();
} catch (error) {
console.log(error);
throw error;
} finally {
await completeTransaction(transactionId);
}
} else {
console.log(`[DEBUG] Adding ssl for ${domain}`);
}
}
export async function deleteProxy({ id }) {
const haproxy = await haproxyInstance();
try {
await checkHAProxy(haproxy);
} catch (error) {
return;
}
const transactionId = await getNextTransactionId();
try {
await haproxy.get(`v2/services/haproxy/configuration/backends/${id}`).json();
await haproxy
.delete(`v2/services/haproxy/configuration/backends/${id}`, {
searchParams: {
transaction_id: transactionId
}
})
.json();
await haproxy.get(`v2/services/haproxy/configuration/frontends/${id}`).json();
await haproxy
.delete(`v2/services/haproxy/configuration/frontends/${id}`, {
searchParams: {
transaction_id: transactionId
}
})
.json();
} catch (error) {
console.log(error.response.body);
} finally {
await completeTransaction(transactionId);
}
}
// export async function configureProxyForDatabase({ id, port, isPublic, privatePort }) {
// const haproxy = await haproxyInstance()
// try {
// await checkHAProxy()
// } catch (error) {
// return
// }
// let alreadyConfigured = false
// try {
// const backend: any = await haproxy.get(`v2/services/haproxy/configuration/backends/${id}`).json()
// const server: any = await haproxy.get(`v2/services/haproxy/configuration/servers/${id}`, {
// searchParams: {
// backend: id
// },
// }).json()
// if (backend.data.name === id) {
// if (server.data.port === privatePort) {
// if (server.data.check === 'enabled') {
// if (server.data.address === id) {
// alreadyConfigured = true
// }
// }
// }
// }
// } catch (error) {
// console.log('error getting backend or server', error.response.body)
// }
// if (alreadyConfigured) return
// const transactionId = await getNextTransactionId()
// try {
// await haproxy.post('v2/services/haproxy/configuration/backends', {
// searchParams: {
// transaction_id: transactionId
// },
// json: {
// "init-addr": "last,libc,none",
// "mode": "tcp",
// "name": id
// }
// })
// await haproxy.post('v2/services/haproxy/configuration/servers', {
// searchParams: {
// transaction_id: transactionId,
// backend: id
// },
// json: {
// "address": id,
// "check": "enabled",
// "name": id,
// "port": privatePort
// }
// })
// await haproxy.post('v2/services/haproxy/configuration/frontends', {
// searchParams: {
// transaction_id: transactionId,
// backend: id
// },
// json: {
// "default_backend": id,
// "mode": "tcp",
// "name": id
// }
// })
// await haproxy.post('v2/services/haproxy/configuration/binds', {
// searchParams: {
// transaction_id: transactionId,
// frontend: id
// },
// json: {
// "address": "*",
// "name": id,
// "port": port
// }
// })
// } catch (error) {
// console.log(error.response.body)
// throw error.response.body
// } finally {
// try {
// await completeTransaction(transactionId)
// } catch (error) {
// console.log(error.response.body)
// }
// }
// await configureDatabaseVisibility({ id, isPublic })
// }
export async function reloadHaproxy(engine) {
const host = getEngine(engine);
return await asyncExecShell(`DOCKER_HOST=${host} docker exec coolify-haproxy kill -HUP 1`);
}
export async function configureProxyForApplication({ domain, imageId, applicationId, port }) {
const haproxy = await haproxyInstance();
await checkHAProxy(haproxy);
let serverConfigured = false;
let backendAvailable: any = null;
try {
backendAvailable = await haproxy
.get(`v2/services/haproxy/configuration/backends/${domain}`)
.json();
const server: any = await haproxy
.get(`v2/services/haproxy/configuration/servers/${imageId}`, {
searchParams: {
backend: domain
}
})
.json();
if (backendAvailable && server) {
// Very sophisticated way to check if the server is already configured in proxy
if (backendAvailable.data.forwardfor.enabled === 'enabled') {
if (backendAvailable.data.name === domain) {
if (server.data.check === 'enabled') {
if (server.data.address === applicationId) {
if (server.data.port === port) {
serverConfigured = true;
}
}
}
}
}
}
} catch (error) {
//console.log('error getting backend or server', error?.response?.body);
//
}
if (serverConfigured) return;
const transactionId = await getNextTransactionId();
if (backendAvailable) {
await haproxy
.delete(`v2/services/haproxy/configuration/backends/${domain}`, {
searchParams: {
transaction_id: transactionId
}
})
.json();
}
try {
await haproxy.post('v2/services/haproxy/configuration/backends', {
searchParams: {
transaction_id: transactionId
},
json: {
'init-addr': 'last,libc,none',
forwardfor: { enabled: 'enabled' },
name: domain
}
});
await haproxy.post('v2/services/haproxy/configuration/servers', {
searchParams: {
transaction_id: transactionId,
backend: domain
},
json: {
address: imageId,
check: 'enabled',
name: imageId,
port: port
}
});
} catch (error) {
throw error?.response?.body || error;
} finally {
await completeTransaction(transactionId);
}
}
export async function configureCoolifyProxyOff({ domain }) {
const haproxy = await haproxyInstance();
await checkHAProxy(haproxy);
try {
const transactionId = await getNextTransactionId();
await haproxy.get(`v2/services/haproxy/configuration/backends/${domain}`).json();
await haproxy
.delete(`v2/services/haproxy/configuration/backends/${domain}`, {
searchParams: {
transaction_id: transactionId
}
})
.json();
await completeTransaction(transactionId);
if (!dev) {
await forceSSLOffApplication({ domain });
}
} catch (error) {
throw error?.response?.body || error;
}
}
export async function checkHAProxy(haproxy) {
if (!haproxy) haproxy = await haproxyInstance();
try {
await haproxy.get('v2/info');
} catch (error) {
throw 'HAProxy is not running, but it should be!';
}
}
export async function configureCoolifyProxyOn({ domain }) {
const haproxy = await haproxyInstance();
await checkHAProxy(haproxy);
let serverConfigured = false;
let backendAvailable: any = null;
try {
backendAvailable = await haproxy
.get(`v2/services/haproxy/configuration/backends/${domain}`)
.json();
const server: any = await haproxy
.get(`v2/services/haproxy/configuration/servers/coolify`, {
searchParams: {
backend: domain
}
})
.json();
if (backendAvailable && server) {
// Very sophisticated way to check if the server is already configured in proxy
if (backendAvailable.data.forwardfor.enabled === 'enabled') {
if (backendAvailable.data.name === domain) {
if (server.data.check === 'enabled') {
if (server.data.address === dev ? 'host.docker.internal' : 'coolify') {
if (server.data.port === 3000) {
serverConfigured = true;
}
}
}
}
}
}
} catch (error) {}
if (serverConfigured) return;
const transactionId = await getNextTransactionId();
try {
await haproxy.post('v2/services/haproxy/configuration/backends', {
searchParams: {
transaction_id: transactionId
},
json: {
adv_check: 'httpchk',
httpchk_params: {
method: 'GET',
uri: '/undead.json'
},
'init-addr': 'last,libc,none',
forwardfor: { enabled: 'enabled' },
name: domain
}
});
await haproxy.post('v2/services/haproxy/configuration/servers', {
searchParams: {
transaction_id: transactionId,
backend: domain
},
json: {
address: dev ? 'host.docker.internal' : 'coolify',
check: 'enabled',
fall: 10,
name: 'coolify',
port: 3000
}
});
} catch (error) {
console.log(error);
throw error;
} finally {
await completeTransaction(transactionId);
}
}
export async function stopTcpHttpProxy(destinationDocker, publicPort) {
const { engine } = destinationDocker;
const host = getEngine(engine);
const containerName = `haproxy-for-${publicPort}`;
const found = await checkContainer(engine, containerName);
try {
if (found) {
return await asyncExecShell(
`DOCKER_HOST=${host} docker stop -t 0 ${containerName} && docker rm ${containerName}`
);
}
} catch (error) {
return error;
}
}
export async function startTcpProxy(destinationDocker, id, publicPort, privatePort) {
const { network, engine } = destinationDocker;
const host = getEngine(engine);
const containerName = `haproxy-for-${publicPort}`;
const found = await checkContainer(engine, containerName);
const foundDB = await checkContainer(engine, id);
try {
if (foundDB && !found) {
return await asyncExecShell(
`DOCKER_HOST=${host} docker run --restart always -e PORT=${publicPort} -e APP=${id} -e PRIVATE_PORT=${privatePort} --add-host 'host.docker.internal:host-gateway' --network ${network} -p ${publicPort}:${publicPort} --name ${containerName} -d coollabsio/${defaultProxyImageTcp}`
);
}
} catch (error) {
return error;
}
}
export async function startHttpProxy(destinationDocker, id, publicPort, privatePort) {
const { network, engine } = destinationDocker;
const host = getEngine(engine);
const containerName = `haproxy-for-${publicPort}`;
const found = await checkContainer(engine, containerName);
const foundDB = await checkContainer(engine, id);
try {
if (foundDB && !found) {
return await asyncExecShell(
`DOCKER_HOST=${host} docker run --restart always -e PORT=${publicPort} -e APP=${id} -e PRIVATE_PORT=${privatePort} --add-host 'host.docker.internal:host-gateway' --network ${network} -p ${publicPort}:${publicPort} --name ${containerName} -d coollabsio/${defaultProxyImageHttp}`
);
}
} catch (error) {
return error;
}
}
export async function startCoolifyProxy(engine) {
const host = getEngine(engine);
const found = await checkContainer(engine, 'coolify-haproxy');
const { proxyPassword, proxyUser } = await db.listSettings();
if (!found) {
await asyncExecShell(
`DOCKER_HOST="${host}" docker run -e HAPROXY_USERNAME=${proxyUser} -e HAPROXY_PASSWORD=${proxyPassword} --restart always --add-host 'host.docker.internal:host-gateway' -v coolify-ssl-certs:/usr/local/etc/haproxy/ssl --network coolify-infra -p "80:80" -p "443:443" -p "8404:8404" -p "5555:5555" -p "5000:5000" --name coolify-haproxy -d coollabsio/${defaultProxyImage}`
);
}
await configureNetworkCoolifyProxy(engine);
}
export async function checkContainer(engine, container) {
const host = getEngine(engine);
let containerFound = false;
try {
const { stdout } = await asyncExecShell(
`DOCKER_HOST="${host}" docker inspect --format '{{json .State}}' ${container}`
);
const parsedStdout = JSON.parse(stdout);
const status = parsedStdout.Status;
const isRunning = parsedStdout.Running;
if (status === 'exited' || status === 'created') {
await asyncExecShell(`DOCKER_HOST="${host}" docker rm ${container}`);
}
if (isRunning) {
containerFound = true;
}
} catch (err) {
// Container not found
}
return containerFound;
}
export async function stopCoolifyProxy(engine) {
const host = getEngine(engine);
const found = await checkContainer(engine, 'coolify-haproxy');
await db.setDestinationSettings({ engine, isCoolifyProxyUsed: false });
try {
if (found) {
await asyncExecShell(
`DOCKER_HOST="${host}" docker stop -t 0 coolify-haproxy && docker rm coolify-haproxy`
);
}
} catch (error) {
return error;
}
}
export async function configureNetworkCoolifyProxy(engine) {
const host = getEngine(engine);
const destinations = await db.prisma.destinationDocker.findMany({ where: { engine } });
destinations.forEach(async (destination) => {
try {
await asyncExecShell(
`DOCKER_HOST="${host}" docker network connect ${destination.network} coolify-haproxy`
);
} catch (err) {
// TODO: handle error
}
});
}
export async function configureSimpleServiceProxyOn({ id, domain, port }) {
const haproxy = await haproxyInstance();
try {
await checkHAProxy(haproxy);
} catch (error) {
return;
}
try {
await haproxy.get(`v2/services/haproxy/configuration/backends/${domain}`).json();
return;
} catch (error) {}
try {
const transactionId = await getNextTransactionId();
await haproxy.post('v2/services/haproxy/configuration/backends', {
searchParams: {
transaction_id: transactionId
},
json: {
'init-addr': 'last,libc,none',
forwardfor: { enabled: 'enabled' },
name: domain
}
});
await haproxy.post('v2/services/haproxy/configuration/servers', {
searchParams: {
transaction_id: transactionId,
backend: domain
},
json: {
address: id,
check: 'enabled',
name: id,
port: port
}
});
await completeTransaction(transactionId);
} catch (error) {
console.log(error);
}
}
export async function configureSimpleServiceProxyOff({ domain }) {
const haproxy = await haproxyInstance();
await checkHAProxy(haproxy);
try {
await haproxy.get(`v2/services/haproxy/configuration/backends/${domain}`).json();
const transactionId = await getNextTransactionId();
await haproxy
.delete(`v2/services/haproxy/configuration/backends/${domain}`, {
searchParams: {
transaction_id: transactionId
}
})
.json();
await completeTransaction(transactionId);
} catch (error) {}
return;
}

View File

@@ -0,0 +1,50 @@
import { asyncExecShell, saveBuildLog } from '$lib/common';
import got from 'got';
import jsonwebtoken from 'jsonwebtoken';
import * as db from '$lib/database';
import { PrismaErrorHandler } from '$lib/database';
export default async function ({
applicationId,
debug,
workdir,
githubAppId,
repository,
branch,
buildId
}): Promise<any> {
try {
saveBuildLog({ line: 'GitHub importer started', buildId, applicationId });
const { privateKey, appId, installationId } = await db.getUniqueGithubApp({ githubAppId });
const githubPrivateKey = privateKey.replace(/\\n/g, '\n').replace(/"/g, '');
const payload = {
iat: Math.round(new Date().getTime() / 1000),
exp: Math.round(new Date().getTime() / 1000 + 60),
iss: appId
};
const jwtToken = jsonwebtoken.sign(payload, githubPrivateKey, {
algorithm: 'RS256'
});
const { token } = await got
.post(`https://api.github.com/app/installations/${installationId}/access_tokens`, {
headers: {
Authorization: `Bearer ${jwtToken}`,
Accept: 'application/vnd.github.machine-man-preview+json'
}
})
.json();
saveBuildLog({
line: `Cloning ${repository}:${branch} branch.`,
buildId,
applicationId
});
await asyncExecShell(
`git clone -q -b ${branch} https://x-access-token:${token}@github.com/${repository}.git ${workdir}/ && cd ${workdir} && git submodule update --init --recursive && cd ..`
);
const { stdout: commit } = await asyncExecShell(`cd ${workdir}/ && git rev-parse HEAD`);
return commit.replace('\n', '');
} catch (error) {
return PrismaErrorHandler(error);
}
}

View File

@@ -0,0 +1,29 @@
import { asyncExecShell, saveBuildLog } from '$lib/common';
import { PrismaErrorHandler } from '$lib/database';
export default async function ({
applicationId,
debug,
workdir,
repodir,
repository,
branch,
buildId,
privateSshKey
}): Promise<any> {
saveBuildLog({ line: 'GitLab importer started.', buildId, applicationId });
await asyncExecShell(`echo '${privateSshKey}' > ${repodir}/id.rsa`);
await asyncExecShell(`chmod 600 ${repodir}/id.rsa`);
saveBuildLog({
line: `Cloning ${repository}:${branch} branch.`,
buildId,
applicationId
});
await asyncExecShell(
`git clone -q -b ${branch} git@gitlab.com:${repository}.git --config core.sshCommand="ssh -q -i ${repodir}id.rsa -o StrictHostKeyChecking=no" ${workdir}/ && cd ${workdir}/ && git submodule update --init --recursive && cd ..`
);
const { stdout: commit } = await asyncExecShell(`cd ${workdir}/ && git rev-parse HEAD`);
return commit.replace('\n', '');
}

Some files were not shown because too many files have changed in this diff Show More