An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.
PHP coolifydatabasesdeploymentdockerdocker-composeinertiajslaravelmariadbmysqlnextjsnodejsphppostgresredisself-hostedself-hostingserverstatic-sitesveltesvelte5
fixes for terminal
Andras Bacsai117fbeb07c1a
diff --git a/app/Livewire/Project/Shared/Terminal.php b/app/Livewire/Project/Shared/Terminal.phpindex 331392118f..e070ee367b 100644--- a/app/Livewire/Project/Shared/Terminal.php+++ b/app/Livewire/Project/Shared/Terminal.php@@ -11,17 +11,19 @@ class Terminal extends Component#[On('send-terminal-command')]public function sendTerminalCommand($isContainer, $identifier, $serverUuid){- $server = Server::whereUuid($serverUuid)->firstOrFail();+ $server = Server::ownedByCurrentTeam()->whereUuid($serverUuid)->firstOrFail();- if (auth()->user()) {- $teams = auth()->user()->teams->pluck('id');- if (! $teams->contains($server->team_id) && ! $teams->contains(0)) {- throw new \Exception('User is not part of the team that owns this server');- }- }+ // if (auth()->user()) {+ // $teams = auth()->user()->teams->pluck('id');+ // if (! $teams->contains($server->team_id) && ! $teams->contains(0)) {+ // throw new \Exception('User is not part of the team that owns this server');+ // }+ // }if ($isContainer) {+ ray($identifier);$status = getContainerStatus($server, $identifier);+ ray($status);if ($status !== 'running') {return handleError(new \Exception('Container is not running'), $this);}diff --git a/app/Livewire/RunCommand.php b/app/Livewire/RunCommand.phpindex 2d01cbca0e..449ab1ea99 100644--- a/app/Livewire/RunCommand.php+++ b/app/Livewire/RunCommand.php@@ -2,7 +2,6 @@namespace App\Livewire;-use App\Models\Server;use Livewire\Attributes\On;use Livewire\Component;@@ -23,7 +22,7 @@ class RunCommand extends Componentprivate function getAllActiveContainers(){- return Server::all()->flatMap(function ($server) {+ return collect($this->servers)->flatMap(function ($server) {if (! $server->isFunctional()) {return [];}@@ -31,25 +30,52 @@ class RunCommand extends Componentreturn $server->definedResources()->filter(function ($resource) {$status = method_exists($resource, 'realStatus') ? $resource->realStatus() : (method_exists($resource, 'status') ? $resource->status() : 'exited');+return str_starts_with($status, 'running:');})->map(function ($resource) use ($server) {- $container_name = $resource->uuid;+ if (isDev()) {+ if (data_get($resource, 'name') === 'coolify-db') {+ $container_name = 'coolify-db';++ return [+ 'name' => $resource->name,+ 'connection_name' => $container_name,+ 'uuid' => $resource->uuid,+ 'status' => 'running',+ 'server' => $server,+ 'server_uuid' => $server->uuid,+ ];+ }+ }- if (class_basename($resource) === 'Application' || class_basename($resource) === 'Service') {- if ($server->isSwarm()) {- $container_name = $resource->uuid.'_'.$resource->uuid;- } else {+ if (class_basename($resource) === 'Application') {+ if (! $server->isSwarm()) {$current_containers = getCurrentApplicationContainerStatus($server, $resource->id, includePullrequests: true);- $container_name = data_get($current_containers->first(), 'Names');}+ $status = $resource->status;+ } elseif (class_basename($resource) === 'Service') {+ $current_containers = getCurrentServiceContainerStatus($server, $resource->id);+ $status = $resource->status();+ } else {+ $status = getContainerStatus($server, $resource->uuid);+ if ($status === 'running') {+ $current_containers = collect([+ 'Names' => $resource->name,+ ]);+ }+ }+ if ($server->isSwarm()) {+ $container_name = $resource->uuid.'_'.$resource->uuid;+ } else {+ $container_name = data_get($current_containers->first(), 'Names');}return ['name' => $resource->name,'connection_name' => $container_name,'uuid' => $resource->uuid,- 'status' => $resource->status,+ 'status' => $status,'server' => $server,'server_uuid' => $server->uuid,];diff --git a/bootstrap/helpers/docker.php b/bootstrap/helpers/docker.phpindex 90093deb8d..8256687437 100644--- a/bootstrap/helpers/docker.php+++ b/bootstrap/helpers/docker.php@@ -40,6 +40,20 @@ function getCurrentApplicationContainerStatus(Server $server, int $id, ?int $pulreturn $containers;}+function getCurrentServiceContainerStatus(Server $server, int $id): Collection+{+ $containers = collect([]);+ if (! $server->isSwarm()) {+ $containers = instant_remote_process(["docker ps -a --filter='label=coolify.serviceId={$id}' --format '{{json .}}' "], $server);+ $containers = format_docker_command_output_to_json($containers);+ $containers = $containers->filter();++ return $containers;+ }++ return $containers;+}+function format_docker_command_output_to_json($rawOutput): Collection{$outputLines = explode(PHP_EOL, $rawOutput);diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 64eb1d2a42..16bb354a5c 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -43,25 +43,23 @@ services:- /data/coolify/_volumes/redis/:/data# - coolify-redis-data-dev:/datasoketi:+ build:+ context: .+ dockerfile: ./docker/coolify-realtime/Dockerfileenv_file:- .envports:- "${FORWARD_SOKETI_PORT:-6001}:6001"- "6002:6002"volumes:- - ./docker/soketi-entrypoint/soketi-entrypoint.sh:/soketi-entrypoint.sh- - ./package.json:/terminal/package.json- - ./package-lock.json:/terminal/package-lock.json- - ./terminal-server.js:/terminal/terminal-server.js- ./storage:/var/www/html/storage- entrypoint: ["/bin/sh", "/soketi-entrypoint.sh"]environment:SOKETI_DEBUG: "false"SOKETI_DEFAULT_APP_ID: "${PUSHER_APP_ID:-coolify}"SOKETI_DEFAULT_APP_KEY: "${PUSHER_APP_KEY:-coolify}"SOKETI_DEFAULT_APP_SECRET: "${PUSHER_APP_SECRET:-coolify}"vite:- image: node:alpine+ image: node:20pull_policy: alwaysworking_dir: /var/www/html# environment:diff --git a/docker-compose.prod.yml b/docker-compose.prod.ymlindex ea882dd2d9..536a7183b4 100644--- a/docker-compose.prod.yml+++ b/docker-compose.prod.yml@@ -109,6 +109,7 @@ services:retries: 10timeout: 2ssoketi:+ image: 'ghcr.io/coollabsio/coolify-realtime:latest'ports:- "${SOKETI_PORT:-6001}:6001"- "6002:6002"diff --git a/docker-compose.windows.yml b/docker-compose.windows.ymlindex 0db35eb96b..2246e1867d 100644--- a/docker-compose.windows.yml+++ b/docker-compose.windows.yml@@ -102,8 +102,8 @@ services:interval: 5sretries: 10timeout: 2s-soketi:- image: 'quay.io/soketi/soketi:1.6-16-alpine'+ soketi:+ image: 'ghcr.io/coollabsio/coolify-realtime:latest'pull_policy: alwayscontainer_name: coolify-realtimerestart: alwaysdiff --git a/docker-compose.yml b/docker-compose.ymlindex 930c0a6b93..7d71ba8e12 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -24,7 +24,6 @@ services:networks:- coolifysoketi:- image: 'quay.io/soketi/soketi:1.6-16-alpine'container_name: coolify-realtimerestart: alwaysnetworks:diff --git a/docker/coolify-realtime/Dockerfile b/docker/coolify-realtime/Dockerfilenew file mode 100644index 0000000000..9a7a683768--- /dev/null+++ b/docker/coolify-realtime/Dockerfile@@ -0,0 +1,9 @@+FROM quay.io/soketi/soketi:1.6-16-alpine+WORKDIR /terminal+RUN apk add --no-cache openssh-client make g++ python3+COPY docker/coolify-realtime/package.json ./+RUN npm i+RUN npm rebuild node-pty --update-binary+COPY docker/coolify-realtime/soketi-entrypoint.sh /soketi-entrypoint.sh+COPY docker/coolify-realtime/terminal-server.js /terminal/terminal-server.js+ENTRYPOINT ["/bin/sh", "/soketi-entrypoint.sh"]diff --git a/docker/coolify-realtime/package.json b/docker/coolify-realtime/package.jsonnew file mode 100644index 0000000000..90d4f77db8--- /dev/null+++ b/docker/coolify-realtime/package.json@@ -0,0 +1,13 @@+{+ "private": true,+ "type": "module",+ "dependencies": {+ "@xterm/addon-fit": "^0.10.0",+ "@xterm/xterm": "^5.5.0",+ "cookie": "^0.6.0",+ "axios": "1.7.5",+ "dotenv": "^16.4.5",+ "node-pty": "^1.0.0",+ "ws": "^8.17.0"+ }+}diff --git a/docker/soketi-entrypoint/soketi-entrypoint.sh b/docker/coolify-realtime/soketi-entrypoint.shsimilarity index 79%rename from docker/soketi-entrypoint/soketi-entrypoint.shrename to docker/coolify-realtime/soketi-entrypoint.shindex 808e306e79..04e43ac819 100644--- a/docker/soketi-entrypoint/soketi-entrypoint.sh+++ b/docker/coolify-realtime/soketi-entrypoint.sh@@ -1,16 +1,4 @@#!/bin/sh--# Install openssh-client-apk add --no-cache openssh-client make g++ python3--cd /terminal--# Install npm dependencies-npm ci--# Rebuild node-pty-npm rebuild node-pty --update-binary-# Function to timestamp logstimestamp() {date "+%Y-%m-%d %H:%M:%S"@@ -36,4 +24,4 @@ trap 'forward_signal TERM' TERMwait -n# Exit with status of process that exited first-exit $?\ No newline at end of file+exit $?diff --git a/terminal-server.js b/docker/coolify-realtime/terminal-server.jssimilarity index 81%rename from terminal-server.jsrename to docker/coolify-realtime/terminal-server.jsindex a1555bf307..6afbd3445e 100755--- a/terminal-server.js+++ b/docker/coolify-realtime/terminal-server.js@@ -16,40 +16,40 @@ const server = http.createServer((req, res) => {});const verifyClient = async (info, callback) => {- const cookies = cookie.parse(info.req.headers.cookie || '');- const origin = new URL(info.origin);- const protocol = origin.protocol;- const xsrfToken = cookies['XSRF-TOKEN'];-- // Generate session cookie name based on APP_NAME- const appName = process.env.APP_NAME || 'laravel';- const sessionCookieName = `${appName.replace(/[^a-zA-Z0-9]/g, '_').toLowerCase()}_session`;- const laravelSession = cookies[sessionCookieName];-- // Verify presence of required tokens- if (!laravelSession || !xsrfToken) {- return callback(false, 401, 'Unauthorized: Missing required tokens');- }-- try {- // Authenticate with Laravel backend- const response = await axios.post(`${protocol}//coolify/terminal/auth`, null, {- headers: {- 'Cookie': `${sessionCookieName}=${laravelSession}`,- 'X-XSRF-TOKEN': xsrfToken- },- });+ const cookies = cookie.parse(info.req.headers.cookie || '');+ const origin = new URL(info.origin);+ const protocol = origin.protocol;+ const xsrfToken = cookies['XSRF-TOKEN'];++ // Generate session cookie name based on APP_NAME+ const appName = process.env.APP_NAME || 'laravel';+ const sessionCookieName = `${appName.replace(/[^a-zA-Z0-9]/g, '_').toLowerCase()}_session`;+ const laravelSession = cookies[sessionCookieName];++ // Verify presence of required tokens+ if (!laravelSession || !xsrfToken) {+ return callback(false, 401, 'Unauthorized: Missing required tokens');+ }- if (response.status === 200) {- // Authentication successful- callback(true);- } else {- callback(false, 401, 'Unauthorized: Invalid credentials');+ try {+ // Authenticate with Laravel backend+ const response = await axios.post(`${protocol}//coolify/terminal/auth`, null, {+ headers: {+ 'Cookie': `${sessionCookieName}=${laravelSession}`,+ 'X-XSRF-TOKEN': xsrfToken+ },+ });++ if (response.status === 200) {+ // Authentication successful+ callback(true);+ } else {+ callback(false, 401, 'Unauthorized: Invalid credentials');+ }+ } catch (error) {+ console.error('Authentication error:', error.message);+ callback(false, 500, 'Internal Server Error');}- } catch (error) {- console.error('Authentication error:', error.message);- callback(false, 500, 'Internal Server Error');- }};diff --git a/resources/views/livewire/project/shared/terminal.blade.php b/resources/views/livewire/project/shared/terminal.blade.phpindex 4e1a086e20..f351bd42fe 100644--- a/resources/views/livewire/project/shared/terminal.blade.php+++ b/resources/views/livewire/project/shared/terminal.blade.php@@ -1,11 +1,12 @@<div x-data="data()"><div x-show="!terminalActive" class="flex items-center justify-center w-full py-4 mx-auto h-[510px]">- <div class="w-full h-full border rounded dark:bg-coolgray-100 dark:border-coolgray-300">- <span class="font-mono text-sm text-gray-500">(connection closed)</span>+ <div+ class="w-full h-full bg-white border border-solid rounded dark:text-white dark:bg-coolgray-100 scrollbar border-neutral-300 dark:border-coolgray-300 p-1">+ <span class="font-mono text-sm text-gray-500 ">(connection closed)</span></div></div><div x-ref="terminalWrapper"- :class="fullscreen ? 'fullscreen' : 'relative w-full h-full py-4 mx-auto max-h-[510px]'">+ :class="fullscreen ? 'fullscreen' : 'relative w-full h-full py-4 mx-auto max-h-[510px]'"><div id="terminal" wire:ignore></div><button title="Minimize" x-show="fullscreen" class="fixed top-4 right-4" x-on:click="makeFullscreen"><svgclass="icon" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">@@ -24,169 +25,171 @@</div>@script- <script>- const MAX_PENDING_WRITES = 5;- let pendingWrites = 0;- let paused = false;-- let socket;- let commandBuffer = '';-- function initializeWebSocket() {- if (!socket || socket.readyState === WebSocket.CLOSED) {- const url = "{{ str_replace(['http://', 'https://'], '', config('app.url')) }}" || window.location.hostname;- socket = new WebSocket((window.location.protocol === 'https:' ? 'wss://' : 'ws://') +- url +- ':6002/terminal');- socket.onmessage = handleSocketMessage;- socket.onerror = (e) => {- console.error('WebSocket error:', e);- };+ <script>+ const MAX_PENDING_WRITES = 5;+ let pendingWrites = 0;+ let paused = false;++ let socket;+ let commandBuffer = '';++ function initializeWebSocket() {+ if (!socket || socket.readyState === WebSocket.CLOSED) {+ let url = "{{ str_replace(['http://', 'https://'], '', config('app.url')) }}" || window.location.hostname;+ // make sure the port is not included+ url = url.split(':')[0];+ socket = new WebSocket((window.location.protocol === 'https:' ? 'wss://' : 'ws://') ++ url ++ ':6002/terminal');+ socket.onmessage = handleSocketMessage;+ socket.onerror = (e) => {+ console.error('WebSocket error:', e);+ };+ }}- }-- function handleSocketMessage(event) {- // Initialize Terminal- if (event.data === 'pty-ready') {- term.open(document.getElementById('terminal'));- $data.terminalActive = true;- term.reset();- term.focus();- document.querySelector('.xterm-viewport').classList.add('scrollbar', 'rounded')- $data.resizeTerminal()- } else {- pendingWrites++;- term.write(event.data, flowControlCallback);++ function handleSocketMessage(event) {+ // Initialize Terminal+ if (event.data === 'pty-ready') {+ term.open(document.getElementById('terminal'));+ $data.terminalActive = true;+ term.reset();+ term.focus();+ document.querySelector('.xterm-viewport').classList.add('scrollbar', 'rounded')+ $data.resizeTerminal()+ } else {+ pendingWrites++;+ term.write(event.data, flowControlCallback);+ }}- }- function flowControlCallback() {- pendingWrites--;- if (pendingWrites > MAX_PENDING_WRITES && !paused) {- paused = true;- socket.send(JSON.stringify({- pause: true- }));- return;+ function flowControlCallback() {+ pendingWrites--;+ if (pendingWrites > MAX_PENDING_WRITES && !paused) {+ paused = true;+ socket.send(JSON.stringify({+ pause: true+ }));+ return;+ }+ if (pendingWrites <= MAX_PENDING_WRITES && paused) {+ paused = false;+ socket.send(JSON.stringify({+ resume: true+ }));+ return;+ }}- if (pendingWrites <= MAX_PENDING_WRITES && paused) {- paused = false;++ term.onData((data) => {socket.send(JSON.stringify({- resume: true+ message: data}));- return;- }- }- term.onData((data) => {- socket.send(JSON.stringify({- message: data- }));+ // Type CTRL + D or exit in the terminal+ if (data === '\x04' || (data === '\r' && stripAnsiCommands(commandBuffer).trim() === 'exit')) {+ checkIfProcessIsRunningAndKillIt();+ setTimeout(() => {+ term.reset();+ term.write('(connection closed)');+ $data.terminalActive = false;+ }, 500);+ commandBuffer = '';+ } else if (data === '\r') {+ commandBuffer = '';+ } else {+ commandBuffer += data;+ }+ });- // Type CTRL + D or exit in the terminal- if (data === '\x04' || (data === '\r' && stripAnsiCommands(commandBuffer).trim() === 'exit')) {- checkIfProcessIsRunningAndKillIt();- setTimeout(() => {- term.reset();- term.write('(connection closed)');- $data.terminalActive = false;- }, 500);- commandBuffer = '';- } else if (data === '\r') {- commandBuffer = '';- } else {- commandBuffer += data;+ function stripAnsiCommands(input) {+ return input.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '');}- });-- function stripAnsiCommands(input) {- return input.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '');- }-- // Copy and paste- // Enables ctrl + c and ctrl + v- // defaults otherwise to ctrl + insert, shift + insert- term.attachCustomKeyEventHandler((arg) => {- if (arg.ctrlKey && arg.code === "KeyV" && arg.type === "keydown") {- navigator.clipboard.readText()- .then(text => {- socket.send(JSON.stringify({- message: text- }));- })- };- if (arg.ctrlKey && arg.code === "KeyC" && arg.type === "keydown") {- const selection = term.getSelection();- if (selection) {- navigator.clipboard.writeText(selection);- return false;+ // Copy and paste+ // Enables ctrl + c and ctrl + v+ // defaults otherwise to ctrl + insert, shift + insert+ term.attachCustomKeyEventHandler((arg) => {+ if (arg.ctrlKey && arg.code === "KeyV" && arg.type === "keydown") {+ navigator.clipboard.readText()+ .then(text => {+ socket.send(JSON.stringify({+ message: text+ }));+ })+ };++ if (arg.ctrlKey && arg.code === "KeyC" && arg.type === "keydown") {+ const selection = term.getSelection();+ if (selection) {+ navigator.clipboard.writeText(selection);+ return false;+ }}- }- return true;- });+ return true;+ });- $wire.on('send-back-command', function(command) {- socket.send(JSON.stringify({- command: command- }));- });+ $wire.on('send-back-command', function(command) {+ socket.send(JSON.stringify({+ command: command+ }));+ });- window.addEventListener('beforeunload', function(e) {- checkIfProcessIsRunningAndKillIt();- });+ window.addEventListener('beforeunload', function(e) {+ checkIfProcessIsRunningAndKillIt();+ });- function checkIfProcessIsRunningAndKillIt() {- socket.send(JSON.stringify({- checkActive: 'force'- }));- }-- window.onresize = function() {- $data.resizeTerminal()- };-- Alpine.data('data', () => ({- fullscreen: false,- terminalActive: false,- init() {- this.$watch('terminalActive', (value) => {- this.$nextTick(() => {- if (value) {- $refs.terminalWrapper.style.display = 'block';- this.resizeTerminal();- } else {- $refs.terminalWrapper.style.display = 'none';- }- });- });- },- makeFullscreen() {- this.fullscreen = !this.fullscreen;- $nextTick(() => {- this.resizeTerminal()- })- },-- resizeTerminal() {- if (!this.terminalActive) return;-- fitAddon.fit();- const height = $refs.terminalWrapper.clientHeight;- const rows = height / term._core._renderService._charSizeService.height - 1;- var termWidth = term.cols;- var termHeight = parseInt(rows.toString(), 10);- term.resize(termWidth, termHeight);+ function checkIfProcessIsRunningAndKillIt() {socket.send(JSON.stringify({- resize: {- cols: termWidth,- rows: termHeight- }+ checkActive: 'force'}));}- }));- initializeWebSocket();- </script>+ window.onresize = function() {+ $data.resizeTerminal()+ };++ Alpine.data('data', () => ({+ fullscreen: false,+ terminalActive: false,+ init() {+ this.$watch('terminalActive', (value) => {+ this.$nextTick(() => {+ if (value) {+ $refs.terminalWrapper.style.display = 'block';+ this.resizeTerminal();+ } else {+ $refs.terminalWrapper.style.display = 'none';+ }+ });+ });+ },+ makeFullscreen() {+ this.fullscreen = !this.fullscreen;+ $nextTick(() => {+ this.resizeTerminal()+ })+ },++ resizeTerminal() {+ if (!this.terminalActive) return;++ fitAddon.fit();+ const height = $refs.terminalWrapper.clientHeight;+ const rows = height / term._core._renderService._charSizeService.height - 1;+ var termWidth = term.cols;+ var termHeight = parseInt(rows.toString(), 10);+ term.resize(termWidth, termHeight);+ socket.send(JSON.stringify({+ resize: {+ cols: termWidth,+ rows: termHeight+ }+ }));+ }+ }));++ initializeWebSocket();+ </script>@endscript-</div>\ No newline at end of file+</div>