Search by

atannex / terminal

Atanga1920

A secure, real-time terminal for Laravel: live PTY sessions on this server, in Docker containers or over SSH, in the browser (xterm.js), over WebSockets (Laravel Reverb) or plain HTTP. Off by default; Gate-based permissions, session ownership, password re-check, origin checks, limits and an audit tr

Package info

github.com/atannex/terminal

pkg:composer/atannex/terminal

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v1.0.1 2026-12-01 23:49 UTC

This package is auto-updated.

Last update: 2026-12-01 23:50:56 UTC


README

A browser-based terminal for Laravel applications.

atannex/terminal lets authorized users open shell sessions directly from your Laravel application. Sessions can run on the Laravel server, inside a Docker container, or on another server through SSH.

It supports interactive shells, command execution, terminal input and output, multiple tabs, session reconnection, and WebSocket streaming with Laravel Reverb.

Security notice: A web terminal gives users access to the operating-system account running the session. Keep the terminal disabled until you have configured access permissions. Only grant access to people who are trusted to use a shell on the target machine.

Features

  • Interactive terminal sessions in the browser
  • Local, Docker, and SSH targets
  • Multiple terminal tabs
  • Session reconnection after refreshing the page
  • Terminal input, output, resizing, and Ctrl+C support
  • Full-screen and embedded Blade component
  • HTTP streaming, polling, or WebSocket transport
  • Laravel Reverb support
  • Configurable access permissions
  • Session and resource limits
  • Session and security audit logging
  • Artisan commands for installation, diagnostics, and session management
  • Custom target drivers

Requirements

  • PHP 8.2 or later
  • Laravel 11, 12, or 13
  • Linux or macOS for the machine running terminal sessions
  • proc_open enabled in PHP
  • python3 (recommended) or the script utility for interactive sessions

Without python3 or script, the package can use command mode. In command mode, commands run individually and their output is streamed, but interactive programs and prompts are not supported.

Optional dependencies:

  • ext-pcntl and ext-posix in CLI PHP
  • Laravel Reverb for WebSocket transport
  • Docker CLI for Docker targets
  • SSH client for SSH targets

Installation

Install the package with Composer:

composer require atannex/terminal

Run the installation command:

php artisan terminal:install

The installer publishes the configuration file, checks the environment, and explains any additional setup required.

Run the migrations if you want database-backed session records and audit logs:

php artisan migrate

The package creates:

  • terminal_sessions — session ownership, target, status, and lifecycle information
  • terminal_audit_logs — audit records

The package can also run without these tables, using files to store session information and logs for the audit trail.

Enable the terminal

The terminal is disabled by default.

In your .env file, enable it:

TERMINAL_ENABLED=true

If your configuration is cached, clear it:

php artisan config:clear

The terminal page is available at:

https://your-app.com/terminal

Before enabling it in production, configure who is allowed to use it. See Access control.

Access control

Access is denied by default. Choose the method that fits your application.

Option 1: Authorize users with a callback

Register the callback in a service provider's boot() method:

use Atannex\Terminal\Terminal;

Terminal::auth(fn ($user) => $user?->isSuperAdmin());

The callback receives the user, permission being checked, and request context. You can use these to decide what each user is allowed to do.

For example, allow administrators to view sessions, but allow only a designated operator to interact with them:

use Atannex\Terminal\Terminal;
use Atannex\Terminal\Enums\Permission;

Terminal::auth(function ($user, Permission $permission, array $context) {
    if (! $user?->hasRole('admin')) {
        return false;
    }

    return $permission === Permission::View
        || $user->email === 'lead@example.com';
});

Option 2: Allow specific users

In .env, specify user IDs or email addresses:

TERMINAL_ALLOW_USERS=you@example.com,ops@example.com

Users in this list receive all terminal permissions.

Option 3: Use Laravel Gates

You can define a single Gate for terminal access:

Gate::define('viewTerminal', fn ($user) =>
    $user->email === 'you@example.com'
);

Or define individual abilities:

  • terminal.view
  • terminal.open
  • terminal.write
  • terminal.resize
  • terminal.terminate

The package checks the configured authorization methods in order. A Gate::before() hook by itself does not enable access; enabling the terminal must remain an explicit decision.

Terminal permissions

Permission What it allows
view View the terminal page and permitted sessions
open Start a session or run a command
write Send input to a session
resize Resize the terminal
terminate Close a session

Opening the terminal

Full-page terminal

Visit:

/terminal

The page includes controls for opening sessions, switching tabs, clearing output, reconnecting, entering full-screen mode, and closing sessions.

Embed a terminal in a Blade page

Use the Blade component:

<x-terminal />

Set a custom height:

<x-terminal height="70vh" />

Enable tabs, disable shortcuts, and choose a target:

<x-terminal
    :tabs="true"
    :shortcuts="false"
    target="app"
    class="my-terminal"
/>

Component options

Option Default Description
height 480px Terminal height
tabs false Allow multiple sessions in the component
shortcuts true Show configured shortcut buttons
fill false Fill the parent container
target Default target Target used when opening new sessions
class — Additional CSS classes

The component loads its own scripts and styles. You do not need to run a frontend build or publish assets to use it. Assets are included only once per page, even if you embed multiple terminals.

The component respects authorization and renders nothing for users who are not allowed to use the terminal. It can be used with Livewire and Turbo pages.

Keyboard shortcuts

  • Ctrl+C — Interrupt the running process, or copy selected text
  • Ctrl+Shift+C — Copy
  • Ctrl+Shift+V — Paste
  • Ctrl+D — End the shell
  • Enter after a session has ended — Start a new session

On phones and tablets, an additional key row provides Esc, Tab, Ctrl, arrow keys, Ctrl+C, and Ctrl+D.

Shortcut buttons

Shortcut buttons place a command on the prompt. The command is not executed until the user presses Enter.

Customize them in config/terminal.php:

'frontend' => [
    'shortcuts' => [
        'git pull',
        'composer install --no-dev --optimize-autoloader',
        'php artisan migrate --force',
        'php artisan optimize',
    ],
],

Styling

The terminal uses CSS custom properties. You can customize its appearance:

.atx-terminal {
    --atx-bg: #000;
    --atx-accent: #ff7a59;
    --atx-radius: 0;
}

The terminal font and color theme can also be configured through terminal.frontend.theme.

Sessions continue running after a page refresh. When you reconnect, the terminal attaches to the existing session and restores its output.

Targets

A target defines where the shell runs. The browser sends the target's configured name; server addresses, container names, and SSH credentials remain in your Laravel configuration.

Set the default target in config/terminal.php:

'default_target' => 'local',

Local target

A local target opens a shell on the machine running Laravel:

'local' => [
    'driver' => 'local',
    'label' => 'This server',
    'shell' => null, // Uses bash, or sh if bash is unavailable
    'cwd' => null,   // Defaults to the project root
],

If Laravel runs inside Docker, the local target runs inside that container.

Docker target

A Docker target runs a shell inside an existing container using docker exec:

'app' => [
    'driver' => 'docker',
    'label' => 'App container',
    'container' => 'my-app-php',
    'shell' => '/bin/sh',
    'user' => 'www-data', // Optional
    'workdir' => '/var/www/html',
    'ability' => 'terminal.docker',
],

The web server's user must have permission to access the Docker daemon. On many systems, Docker access is equivalent to root access. Grant it only when you understand the security implications.

SSH target

An SSH target connects to another machine:

'production' => [
    'driver' => 'ssh',
    'label' => 'Production',
    'host' => 'app.example.com',
    'port' => 22,
    'username' => 'deploy',
    'identity_file' => storage_path('app/terminal/id_ed25519'),
    'known_hosts' => storage_path('app/terminal/known_hosts'),
    'ability' => 'terminal.production',
],

Create and verify the host's known-host entry:

ssh-keyscan -p 22 app.example.com > storage/app/terminal/known_hosts

Use a dedicated SSH key with restricted permissions:

chmod 600 storage/app/terminal/id_ed25519

Keep the key and known_hosts file outside your public directory. SSH connections use strict host-key checking and batch mode. Agent forwarding and port forwarding are not enabled.

Restrict access to individual targets

The ability key adds a Laravel Gate check before a user can open that target.

For example:

Gate::define('terminal.production', fn ($user) =>
    $user->email === 'lead@example.com'
);

Assign a separate ability to Docker and SSH targets so users who can access the local shell do not automatically gain access to other machines.

Add your own target driver

You can add support for another environment, such as Kubernetes, by implementing the Atannex\Terminal\Contracts\Driver contract and registering it.

Example driver:

use Atannex\Terminal\Contracts\Driver;
use Atannex\Terminal\Facades\Terminal;
use Atannex\Terminal\Targets\Target;

class KubernetesDriver implements Driver
{
    public function problem(Target $target): ?string
    {
        return null;
    }

    public function interactive(Target $target, array $session): array
    {
        return [
            'kubectl',
            '-n',
            $target->get('namespace', 'default'),
            'exec',
            '-it',
            $target->get('pod'),
            '--',
            '/bin/sh',
        ];
    }

    public function command(Target $target, string $script, string $cwd): array
    {
        return [
            'kubectl',
            '-n',
            $target->get('namespace', 'default'),
            'exec',
            '-i',
            $target->get('pod'),
            '--',
            'sh',
            '-c',
            $script,
        ];
    }

    public function workingDirectory(Target $target): string
    {
        return '/';
    }

    public function localFilesystem(): bool
    {
        return false;
    }
}

Register the driver in a service provider:

Terminal::extend('kubernetes', fn ($app) => new KubernetesDriver);

Then add a target to config/terminal.php:

'web' => [
    'driver' => 'kubernetes',
    'pod' => 'web-0',
    'namespace' => 'prod',
    'ability' => 'terminal.k8s',
],

Drivers must return argument arrays rather than shell command strings. Validate configuration values that are passed as command arguments.

WebSockets with Laravel Reverb

The package uses HTTP streaming or polling by default. If Laravel Reverb is configured, you can use WebSockets to deliver terminal output as soon as it is available.

Install broadcasting and Reverb:

php artisan install:broadcasting

Start Reverb:

php artisan reverb:start

In production, keep Reverb running using a process manager such as Supervisor or systemd.

Set the transport in .env:

TERMINAL_TRANSPORT=websocket

You can also use auto, which uses WebSockets when a Reverb connection is configured.

The package reads the reverb connection from config/broadcasting.php and authorizes its own channels. You do not need to configure terminal channels in routes/channels.php.

If the browser connects to Reverb through a proxy or a different host, configure the client address:

TERMINAL_WS_CLIENT_HOST=ws.example.com
TERMINAL_WS_CLIENT_PORT=443
TERMINAL_WS_CLIENT_SCHEME=https

Terminal input is still sent through HTTP requests. If Reverb becomes unavailable, the terminal falls back to HTTP and continues working.

Any server compatible with the Pusher protocol can be used in the same way.

Using the package from PHP

You can create and manage sessions from your application code using the facade.

use Atannex\Terminal\Facades\Terminal;

$session = Terminal::create([
    'user' => $user,
    'target' => 'local',
]);

$session->write("php artisan about\n");

// Send Ctrl+C:
$session->write("\x03");

// Send Ctrl+D:
$session->write("\x04");

$output = $session->read(0)['data'];

$session->resize(132, 40);

$status = $session->status();

$session->terminate();

Retrieve sessions

// Get a session only if it belongs to the supplied user.
$session = Terminal::session($id, $user);

// Get sessions belonging to a user.
$sessions = Terminal::sessions($user);

// Get all active sessions.
$sessions = Terminal::active();

// Get targets the user is allowed to open.
$targets = Terminal::targetsFor($user);

Check permissions and terminal mode

use Atannex\Terminal\Enums\Permission;

$allowed = Terminal::allows($user, Permission::Open);

$mode = Terminal::mode(); // 'interactive' or 'command'

Calls made directly through the package API are trusted calls. Terminal::create() does not perform the same permission checks as the web routes. If your application performs actions on behalf of a user, check permissions using Terminal::allows() first.

Reading session output

read($offset) returns an array:

[
    'offset' => 1234, // Offset to use for the next read
    'from' => 1200,   // Offset where this output begins
    'data' => '...',  // Output bytes
]

Session statuses include:

  • Starting
  • Running
  • Exited
  • Terminated
  • Expired
  • Failed
  • Lost

Errors are represented by Atannex\Terminal\Exceptions\TerminalException subclasses, including authorization errors, missing or ended sessions, session-limit errors, unavailable targets, and process-start errors.

Events

The package dispatches events during session activity.

Event When it is dispatched
TerminalSessionStarted A shell starts (session, user)
TerminalSessionStopped A session exits, closes, expires, or is lost (session, status, exitCode)
TerminalSessionFailed A session fails to start (target, user, reason)
TerminalInputReceived Input is received (session, data)
TerminalOutputReceived Output is read over HTTP (session, data, offset); not dispatched for WebSocket pushes
TerminalAccessDenied Access is refused (user, reason, ip, sessionId)

Events are in Atannex\Terminal\Events.

Example: log access denials to a security log channel:

use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Atannex\Terminal\Events\TerminalAccessDenied;

Event::listen(
    TerminalAccessDenied::class,
    fn ($event) => Log::channel('security')->warning(
        'Terminal access refused',
        [
            'reason' => $event->reason,
            'ip' => $event->ip,
        ]
    )
);

TerminalInputReceived contains the input exactly as typed. It may include passwords or other secrets, so handle this event carefully.

Artisan commands

Installation and diagnostics

php artisan terminal:install
php artisan terminal:diagnose
php artisan terminal:diagnose --spawn
php artisan terminal:diagnose --fresh
  • terminal:install publishes configuration and optional assets, then checks the server.
  • terminal:diagnose reports requirements and environment checks.
  • terminal:diagnose --spawn also attempts to start a real session.
  • terminal:diagnose --fresh clears previous diagnostic findings before checking again.

Check status and manage sessions

php artisan terminal:status
php artisan terminal:sessions
php artisan terminal:sessions --all
php artisan terminal:sessions --kill=ID
php artisan terminal:sessions --kill-all
php artisan terminal:cleanup
  • terminal:status shows whether the terminal is enabled, its mode, transport, targets, and running sessions.
  • terminal:sessions lists running sessions.
  • terminal:sessions --all includes ended sessions.
  • terminal:sessions --kill=ID closes a specific session.
  • terminal:sessions --kill-all closes all sessions.
  • terminal:cleanup removes expired sessions, leftover files, and old records.

Schedule cleanup in routes/console.php:

use Illuminate\Support\Facades\Schedule;

Schedule::command('terminal:cleanup')->hourly();

Configuration

The package's settings are available in config/terminal.php. Environment variables can be used to adjust most options.

Environment variable Default Description
TERMINAL_ENABLED false Enable or disable the terminal
TERMINAL_PATH_PREFIX terminal URL prefix
TERMINAL_DOMAIN — Restrict terminal routes to a domain
TERMINAL_ALLOW_USERS — User IDs or emails allowed access
TERMINAL_CONFIRM_PASSWORD true Require password confirmation
TERMINAL_PASSWORD_TIMEOUT 900 Seconds before password confirmation is required again
TERMINAL_VALIDATE_ORIGIN true Validate request origin
TERMINAL_ALLOWED_ORIGINS — Additional allowed origins
TERMINAL_ALLOWED_IPS Any IP addresses or CIDR ranges allowed
TERMINAL_MODE auto interactive, command, or auto
TERMINAL_TARGET local Default target
TERMINAL_SHELL bash, or sh Local shell
TERMINAL_CWD Project root Local working directory
TERMINAL_PHP Detected CLI PHP executable
TERMINAL_PATH — Additional command paths, separated by colons
TERMINAL_SESSION_STORE auto database, file, or auto
TERMINAL_DB_CONNECTION Default Database connection for session records
TERMINAL_STORAGE storage/terminal Session file storage
TERMINAL_MAX_SESSIONS_PER_USER 2 Maximum sessions per user
TERMINAL_MAX_SESSIONS 10 Maximum sessions on the server
TERMINAL_IDLE_TIMEOUT 900 Idle timeout in seconds
TERMINAL_SESSION_LIFETIME 28800 Maximum session lifetime in seconds
TERMINAL_SESSION_RETENTION 7 Days to retain ended sessions
TERMINAL_MAX_OUTPUT 1048576 Maximum output bytes stored per session
TERMINAL_COMMAND_TIMEOUT 300 Command-mode timeout in seconds
TERMINAL_LIMIT_MEMORY — Process memory limit in MB (requires Python)
TERMINAL_LIMIT_CPU — CPU time limit in seconds (requires Python)
TERMINAL_LIMIT_PROCESSES — Process count limit for the server user
TERMINAL_LIMIT_FILE_SIZE — Maximum file size in MB
TERMINAL_TRANSPORT auto websocket, stream, poll, or auto
TERMINAL_STREAM_SECONDS 20 Duration of a streamed response
TERMINAL_BROADCAST_CONNECTION reverb Broadcasting connection
TERMINAL_WS_APP_ID — WebSocket application ID
TERMINAL_WS_KEY — WebSocket application key
TERMINAL_WS_SECRET — WebSocket application secret
TERMINAL_WS_HOST — WebSocket server host
TERMINAL_WS_PORT — WebSocket server port
TERMINAL_WS_SCHEME — WebSocket server scheme
TERMINAL_WS_CLIENT_HOST Server host Host the browser connects to
TERMINAL_WS_CLIENT_PORT Server port Browser WebSocket port
TERMINAL_WS_CLIENT_SCHEME Server scheme Browser WebSocket scheme
TERMINAL_AUDIT true Enable audit logging
TERMINAL_AUDIT_CHANNEL Default Log channel for audit records
TERMINAL_AUDIT_DATABASE true Store audit records in the database
TERMINAL_AUDIT_COMMANDS false Record commands typed (may include secrets)
TERMINAL_AUDIT_RETENTION 90 Audit retention in days
TERMINAL_ASSETS route route or published assets

Other settings available directly in config/terminal.php include:

  • middleware — defaults to ['web', 'auth']; change it to use your application's guard, such as ['web', 'auth:admin']
  • targets — define local, Docker, SSH, or custom targets
  • shell.env — additional environment variables for shell processes
  • security.rate_limits — rate-limit settings
  • frontend.shortcuts — terminal shortcut commands
  • frontend.theme — terminal appearance

Security

A browser-based terminal should be treated like SSH access. Review these recommendations before using it in production.

Security features included

  • Disabled by default
  • Access denied until authorization is configured
  • Password confirmation before opening, with a configurable timeout
  • Origin validation and CSRF protection
  • Rate limits on requests that change session state
  • Optional IP allow-list
  • Sessions are private to the user who opened them
  • Session, idle, output, and resource limits
  • Processes started by a session are terminated when the session ends
  • Shell processes do not inherit the application's .env variables or the web server's open sockets
  • Targets are selected by configured names; URLs are not executed as commands
  • Audit records for session activity and access denials
  • Terminal output is not stored in the database
  • Typed commands are logged only when TERMINAL_AUDIT_COMMANDS=true

Production recommendations

  • Use HTTPS.
  • Allow only named users who already have shell access to the machine.
  • Restrict access by IP or VPN when possible.
  • Run the web server as an unprivileged user, never root.
  • Give Docker and SSH targets separate authorization abilities.
  • Use a dedicated SSH key with restricted permissions.
  • Keep SSH keys, configuration secrets, and host-key files outside the public directory.
  • Send audit logs to a destination that terminal users cannot modify.
  • Consider enabling the terminal only when needed.
  • Do not grant shell access to ordinary application users. If users need a limited operation, build a dedicated application feature instead.

Report security issues privately to atangageihlekecollins@gmail.com rather than opening a public issue.

Deployment notes

Local development

The PHP development server handles one request at a time. The package uses polling automatically in this environment.

You can also start multiple workers:

PHP_CLI_SERVER_WORKERS=4 php artisan serve

Linux VPS

Install python3 and ensure CLI PHP has pcntl and posix enabled.

Make the session directory writable by the web server:

mkdir -p storage/terminal

Restarting PHP-FPM does not necessarily end existing sessions. To close all sessions during deployment:

php artisan terminal:sessions --kill-all

Docker

Your image needs a shell, python3, the PHP pcntl and posix extensions, and a process init that handles child processes.

For Alpine-based images:

RUN apk add --no-cache bash python3

Install the PHP extensions as appropriate for your image:

RUN docker-php-ext-install pcntl posix

Use an init such as tini or run the container with --init so orphaned processes are reaped.

Multiple servers

Sessions run on the server that started them. If you have multiple servers behind a load balancer, route terminal requests back to the server hosting the session.

Shared hosting

Shared hosting providers have different process restrictions. Run the diagnostic command instead of assuming the environment supports interactive sessions:

php artisan terminal:diagnose --spawn

The package does not attempt to bypass hosting restrictions.

Common limitations include:

  • proc_open disabled — the terminal cannot run.
  • python3 and script unavailable, or background processes are stopped — command mode may be used instead.
  • Incorrect PHP CLI executable — set TERMINAL_PHP to its full path.
  • Commands such as composer or git are not found — set TERMINAL_PATH.
  • Output arrives in bursts — use polling with TERMINAL_TRANSPORT=poll.

Troubleshooting

The /terminal page returns 404

Check that the terminal is enabled:

TERMINAL_ENABLED=true

If your configuration is cached, clear it:

php artisan config:clear

Access is denied (403)

Check that you configured Terminal::auth(), a Gate, or TERMINAL_ALLOW_USERS. Also check whether your IP is included in TERMINAL_ALLOWED_IPS.

The audit log may contain the reason for the denial. If the application is behind a proxy, configure Laravel's trusted proxies correctly.

Origin validation fails

If the terminal page is hosted on a different origin, add that origin to TERMINAL_ALLOWED_ORIGINS.

Password confirmation keeps appearing

Check whether the session cookie is being retained. Review SESSION_DOMAIN and SESSION_SECURE_COOKIE, especially if you are testing over HTTP.

The terminal opens in command mode

Run:

php artisan terminal:diagnose

Install python3 or script if needed. If a host has stopped sessions, resolve the issue and rerun:

php artisan terminal:diagnose --fresh

A live terminal cannot start

The error may include the worker's underlying error. Check whether TERMINAL_PHP points to the correct command-line PHP executable.

WebSocket connection fails

Check that Reverb is running and accessible from the browser. HTTPS pages require a secure WebSocket connection (wss). The terminal can continue using HTTP while WebSockets are unavailable.

Sessions end unexpectedly

Sessions close after the idle timeout or maximum session lifetime. Review:

  • TERMINAL_IDLE_TIMEOUT
  • TERMINAL_SESSION_LIFETIME

The session limit has been reached

Check TERMINAL_MAX_SESSIONS_PER_USER. Close an unused session or terminate one from the command line:

php artisan terminal:sessions --kill=ID

Known limitations

  • Windows is not supported as the session host. WSL may work as a Linux environment.
  • The SSH driver's commands and checks are implemented, but end-to-end testing against a real SSH server has not been completed.
  • Kubernetes is not included as a built-in driver; an example custom driver is provided above.
  • Recording input in live sessions is best-effort. A terminal cannot always distinguish user typing from text echoed by a program.
  • Resource limits require Python and apply to local sessions.
  • With plain POSIX sh and no Bash, file descriptors above 9 are not closed before a session starts.
  • Sessions are tied to the server that starts them.

Upgrading

Update the package:

composer update atannex/terminal

Run any new migrations and check the environment:

php artisan migrate
php artisan terminal:diagnose

Running sessions may continue using the version they started with; new sessions use the updated package.

If you published the assets, publish them again:

php artisan vendor:publish --tag=terminal-assets --force

Removing the package

Removing the package does not automatically delete session records, audit logs, or files.

  1. Close running sessions:

    php artisan terminal:sessions --kill-all
  2. Remove your Terminal::auth() or Gate definitions and any <x-terminal /> components.

  3. Remove the package:

    composer remove atannex/terminal
  4. If you also want to remove stored data, delete the terminal_sessions and terminal_audit_logs tables, storage/terminal/, config/terminal.php, and the TERMINAL_* entries from .env.

Developing the package

Clone the repository and install dependencies:

composer install
npm install

Build frontend assets:

npm run build

Run the tests:

composer test

Start the playground:

composer serve

Start Reverb for the playground:

composer reverb

Check code style:

vendor/bin/pint

License

MIT