forked from urvishpatelce/lxd-app
Compare commits
18 Commits
e96bcb7a94
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 19bdd41664 | |||
| b99533ced8 | |||
| d5ecf0da96 | |||
| fb51cd6e29 | |||
| 65b6f45753 | |||
| cfabf3c9f5 | |||
| 4072377548 | |||
| b96a1c0065 | |||
| c05d98f333 | |||
| 481508b88c | |||
| f8ab14cc29 | |||
| b48e04ba38 | |||
| 4ad0dfd5bc | |||
| 78b8a25546 | |||
| bd32f43c9e | |||
| a3f5b5a0cf | |||
| 627d462a8e | |||
| 7db9ce4d17 |
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
api/vendor/*
|
||||
|
||||
5
add-container.php
Normal file
5
add-container.php
Normal file
@ -0,0 +1,5 @@
|
||||
<?php
|
||||
if (count($argv) !== 3) return;
|
||||
$config = json_decode(file_get_contents(__DIR__ . '/api/config.json'), true);
|
||||
$config[$argv[1]] = $argv[2];
|
||||
file_put_contents(__DIR__ . '/api/config.json', json_encode($config));
|
||||
2
api/.env
2
api/.env
@ -6,4 +6,4 @@ LXD_CLIENT_CERT=/etc/ssl/lxdapp/client.crt
|
||||
LXD_CLIENT_KEY=/etc/ssl/lxdapp/client.key
|
||||
LXD_IMAGE_FINGERPRINT=2edfd84b1396
|
||||
AUTH_KEY=R9kX2HFA7ZjLdVYm8TsQWpCeNuB1v0GrS6MI4axf
|
||||
|
||||
STATEDIR=/tmp
|
||||
1407
api/composer.lock
generated
Normal file
1407
api/composer.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
@ -1,3 +1,3 @@
|
||||
{
|
||||
"lxdapp.local": "testone"
|
||||
"auftrag.local": "auftrag"
|
||||
}
|
||||
@ -6,14 +6,9 @@ use DI\ContainerBuilder;
|
||||
use Slim\Factory\AppFactory;
|
||||
use Dotenv\Dotenv;
|
||||
use App\Middleware\CorsMiddleware;
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use App\Controllers\CaptchaController;
|
||||
use App\Controllers\LoginController;
|
||||
use App\Controllers\HandoffController;
|
||||
use App\Services\LxdService;
|
||||
use Zounar\PHPProxy\Proxy;
|
||||
use App\Utils\LogWriterHelper;
|
||||
|
||||
require __DIR__ . '/../vendor/autoload.php';
|
||||
|
||||
@ -21,11 +16,9 @@ require __DIR__ . '/../vendor/autoload.php';
|
||||
$dotenv = Dotenv::createImmutable(__DIR__ . '/../');
|
||||
$dotenv->load();
|
||||
|
||||
$domain = $_ENV['MAIN_COOKIE_DOMAIN'] ?? '.lxdapp.local';
|
||||
session_set_cookie_params([
|
||||
'lifetime' => 0,
|
||||
'path' => '/',
|
||||
'domain' => $domain,
|
||||
'secure' => false, // set true if using HTTPS
|
||||
'httponly' => true,
|
||||
'samesite' => 'Lax',
|
||||
@ -39,7 +32,6 @@ if (session_status() === PHP_SESSION_NONE) {
|
||||
$containerBuilder = new ContainerBuilder();
|
||||
$containerBuilder->useAutowiring(true); // Enable autowiring globally
|
||||
|
||||
|
||||
// Add settings
|
||||
$settings = require __DIR__ . '/../src/Settings/Settings.php';
|
||||
$settings($containerBuilder);
|
||||
@ -64,7 +56,6 @@ $app->add(CorsMiddleware::class);
|
||||
// Register middleware
|
||||
(require __DIR__ . '/../src/Bootstrap/Middleware.php')($app);
|
||||
|
||||
|
||||
// Register routes
|
||||
|
||||
// API contianer proxy route
|
||||
@ -72,7 +63,6 @@ $app->group('/api', function ($group) {
|
||||
$group->get('/captcha', [CaptchaController::class, 'get']);
|
||||
$group->post('/login', [LoginController::class, 'index']);
|
||||
$group->get('/status', [LoginController::class, 'status']);
|
||||
$group->get('/handoff/post', [HandoffController::class, 'post']);
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@ -2,7 +2,6 @@
|
||||
|
||||
use Slim\App;
|
||||
use Slim\Middleware\ErrorMiddleware;
|
||||
use Slim\Middleware\BodyParsingMiddleware;
|
||||
|
||||
return function (App $app) {
|
||||
// Add body parsing middleware (for JSON, form, etc.)
|
||||
|
||||
@ -1,85 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Services\LxdService;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
|
||||
class HandoffController
|
||||
{
|
||||
public function post(ServerRequestInterface $req, ResponseInterface $res): ResponseInterface
|
||||
{
|
||||
// if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }
|
||||
|
||||
$q = $req->getQueryParams();
|
||||
$name = (string)($q['name'] ?? '');
|
||||
$id = (string)($q['handoff'] ?? '');
|
||||
$path = (string)($q['path'] ?? '/login');
|
||||
|
||||
if (!$name || !$id) {
|
||||
return $this->html($res, 400, '<h1>Bad request</h1>');
|
||||
}
|
||||
|
||||
$lxd = new LxdService();
|
||||
$ip = $lxd->getContainerIP($name);
|
||||
if (!$ip) {
|
||||
return $this->html($res, 503, '<h1>Container not ready</h1>');
|
||||
}
|
||||
|
||||
$key = "handoff:$name:$id";
|
||||
$data = $_SESSION[$key] ?? null;
|
||||
unset($_SESSION[$key]); // one-time use
|
||||
|
||||
if (!$data || empty($data['username']) || empty($data['password'])) {
|
||||
return $this->html($res, 410, '<h1>Handoff expired</h1>');
|
||||
}
|
||||
|
||||
// Restrict to relative paths
|
||||
$path = $this->sanitizePath($path);
|
||||
|
||||
// If your container has TLS, prefer https://
|
||||
$action = 'http://' . $ip . $path;
|
||||
|
||||
$html = <<<HTML
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head><meta charset="utf-8"><title>Signing you in…</title></head>
|
||||
<body>
|
||||
<form id="f" method="POST" action="{$this->e($action)}">
|
||||
<input type="hidden" name="username" value="{$this->e($data['username'])}">
|
||||
<input type="hidden" name="password" value="{$this->e($data['password'])}">
|
||||
</form>
|
||||
<script>document.getElementById('f').submit();</script>
|
||||
<noscript>
|
||||
<p>JavaScript is required to continue. Click the button below.</p>
|
||||
<button form="f" type="submit">Continue</button>
|
||||
</noscript>
|
||||
</body>
|
||||
</html>
|
||||
HTML;
|
||||
|
||||
return $this->html($res, 200, $html);
|
||||
}
|
||||
|
||||
private function e(string $s): string
|
||||
{
|
||||
return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
}
|
||||
|
||||
private function html(ResponseInterface $res, int $code, string $html): ResponseInterface
|
||||
{
|
||||
$res->getBody()->write($html);
|
||||
return $res->withHeader('Content-Type', 'text/html; charset=utf-8')->withStatus($code);
|
||||
}
|
||||
|
||||
private function sanitizePath(string $raw): string
|
||||
{
|
||||
if (preg_match('#^https?://#i', $raw)) return '/login';
|
||||
if (!str_starts_with($raw, '/')) return '/login';
|
||||
$path = parse_url($raw, PHP_URL_PATH) ?? '/login';
|
||||
$allow = ['/', '/login', '/signin'];
|
||||
return in_array($path, $allow, true) ? $path : '/login';
|
||||
}
|
||||
}
|
||||
|
||||
@ -7,6 +7,7 @@ use App\Services\LxdService;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use App\Utils\LogWriterHelper;
|
||||
use App\Utils\ContainerHelper;
|
||||
|
||||
class LoginController
|
||||
{
|
||||
@ -14,63 +15,51 @@ class LoginController
|
||||
* Login with captcha
|
||||
*/
|
||||
public function index(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
|
||||
{
|
||||
|
||||
{
|
||||
try {
|
||||
$mainDomain = $_ENV['MAIN_DOMAIN'] ?? 'lxdapp.local';
|
||||
$name = ContainerHelper::getName($request);
|
||||
|
||||
$origin = $request->getHeaderLine('Origin');
|
||||
if (!empty($origin)) {
|
||||
$domain = parse_url($origin, PHP_URL_HOST);
|
||||
} else {
|
||||
$domain = $request->getHeaderLine('Host');
|
||||
}
|
||||
|
||||
$configPath = __DIR__ . '/../../config.json';
|
||||
$config = file_exists($configPath) ? json_decode(file_get_contents($configPath), true) : [];
|
||||
$name = $config[$domain] ?? null;
|
||||
$params = (array)$request->getParsedBody();
|
||||
if(!$name){
|
||||
return $this->json($response, [
|
||||
'status' => 'not_found',
|
||||
'message' => 'Container not found',
|
||||
], 404);
|
||||
}
|
||||
$captcha = new PCaptcha();
|
||||
|
||||
if (!$captcha->validate_captcha($params['panswer'])) {
|
||||
if (!$name) {
|
||||
return $this->json($response, [
|
||||
'status' => 'not_found',
|
||||
'message' => 'Container not found',
|
||||
], 404);
|
||||
}
|
||||
|
||||
$captcha = new PCaptcha();
|
||||
if (!$captcha->validate_captcha($params['panswer'] ?? '')) {
|
||||
return $this->json($response, ['status' => 'error', 'message' => 'Invalid CAPTCHA'], 400);
|
||||
}
|
||||
|
||||
$lxd = new LxdService();
|
||||
|
||||
$status = $lxd->getContainerState($name)['metadata']['status'] ?? 'Stopped';
|
||||
if ($status !== 'Running') {
|
||||
$lxd->startContainer($name);
|
||||
}
|
||||
|
||||
LogWriterHelper::write($name);
|
||||
|
||||
// Write log
|
||||
LogWriterHelper::write($name, $request->getUri());
|
||||
|
||||
$redirect = '/waiting?name='.$name .'&redirect='.urlencode($params['redirect']);
|
||||
// Login success
|
||||
return $this->json($response, ['status' => 'success', 'message' => 'Container started!', 'redirect' => $redirect]);
|
||||
return $this->json($response, [
|
||||
'status' => 'success',
|
||||
'message' => 'Container gestartet!'
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
return $this->json($response, [
|
||||
'status' => 'error',
|
||||
'status' => 'error',
|
||||
'message' => $e->getMessage(),
|
||||
], 500);
|
||||
}
|
||||
}
|
||||
|
||||
public function status(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
|
||||
{
|
||||
$queryParams = $request->getQueryParams();
|
||||
$name = $queryParams['name'] ?? '';
|
||||
{
|
||||
$name = ContainerHelper::getName($request);
|
||||
|
||||
if (empty($name)) {
|
||||
return $this->json($response, [
|
||||
'status' => 'error',
|
||||
'status' => 'error',
|
||||
'message' => 'Missing container name.',
|
||||
], 400);
|
||||
}
|
||||
@ -80,7 +69,7 @@ class LoginController
|
||||
$state = $lxd->getContainerState($name);
|
||||
if (!$state) {
|
||||
return $this->json($response, [
|
||||
'status' => 'not_found',
|
||||
'status' => 'not_found',
|
||||
'message' => 'Container not found',
|
||||
], 404);
|
||||
}
|
||||
@ -88,46 +77,43 @@ class LoginController
|
||||
$status = $state['metadata']['status'] ?? 'Stopped';
|
||||
if ($status !== 'Running') {
|
||||
return $this->json($response, [
|
||||
'status' => 'starting',
|
||||
'status' => 'stopped',
|
||||
'message' => 'Container is not yet running',
|
||||
]);
|
||||
}
|
||||
|
||||
$ip = $lxd->getContainerIP($name);
|
||||
$nginx = $lxd->isServiceRunning($name, 'nginx');
|
||||
$mysql = $lxd->isServiceRunning($name, 'mysql');
|
||||
if ($ip && $nginx === 'active' && $mysql === 'active') {
|
||||
$nginx = $lxd->getContainerServiceStatus($name, 'nginx');
|
||||
$mysql = $lxd->getContainerServiceStatus($name, 'mariadb');
|
||||
|
||||
if ($nginx === 'active' && $mysql === 'active') {
|
||||
// ---- CHANGED: do NOT return fields/creds here ----
|
||||
return $this->json($response, [
|
||||
'status' => 'ready',
|
||||
'ip' => $ip,
|
||||
'status' => 'ready',
|
||||
'name' => $name,
|
||||
'message' => 'Container is ready',
|
||||
]);
|
||||
}
|
||||
|
||||
if($nginx === 'failed'){
|
||||
if ($nginx === 'failed') {
|
||||
return $this->json($response, [
|
||||
'status' => 'failed',
|
||||
'status' => 'failed',
|
||||
'message' => 'Failed to start web server service in container',
|
||||
], 400);
|
||||
}
|
||||
|
||||
if($mysql === 'failed'){
|
||||
if ($mysql === 'failed') {
|
||||
return $this->json($response, [
|
||||
'status' => 'failed',
|
||||
'status' => 'failed',
|
||||
'message' => 'Failed to start mysql service in container',
|
||||
], 400);
|
||||
}
|
||||
|
||||
return $this->json($response, [
|
||||
'status' => 'running',
|
||||
'status' => 'running',
|
||||
'message' => 'Container is running, waiting for services...',
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Sends a JSON response.
|
||||
*/
|
||||
protected function json($response, array $data, int $status = 200)
|
||||
{
|
||||
$payload = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
@ -140,4 +126,20 @@ class LoginController
|
||||
->withStatus($status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Allow only known relative paths (never full URLs)
|
||||
*/
|
||||
private function sanitizeRedirectPath(string $raw): string
|
||||
{
|
||||
// deny absolute URLs
|
||||
if (preg_match('#^https?://#i', $raw)) return '/login';
|
||||
if (!str_starts_with($raw, '/')) return '/login';
|
||||
|
||||
$path = parse_url($raw, PHP_URL_PATH) ?? '/login';
|
||||
|
||||
// allowlist of container paths you expect
|
||||
$allow = ['/', '/login', '/signin'];
|
||||
return in_array($path, $allow, true) ? $path : '/login';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,68 +0,0 @@
|
||||
<?php
|
||||
|
||||
require __DIR__ . '/../../vendor/autoload.php'; // Adjust path as needed
|
||||
|
||||
use App\Services\LxdService;
|
||||
|
||||
// Initialize LXD service
|
||||
$lxdService = new LxdService();
|
||||
|
||||
// Define the directory containing access logs
|
||||
$logDir = realpath(__DIR__ . '/../../public/last-access-logs'); // Adjust if you're in /app/src/Cron or similar
|
||||
|
||||
// Define the idle threshold in minutes
|
||||
$thresholdMinutes = 30;
|
||||
|
||||
// Iterate over all log files in the specified directory
|
||||
foreach (glob($logDir . '/*.txt') as $filePath) {
|
||||
// Extract the container name from the file name
|
||||
$containerName = basename($filePath, '.txt');
|
||||
|
||||
// Get the last line from the log file
|
||||
$lastLine = getLastLine($filePath);
|
||||
if (!$lastLine) {
|
||||
echo "No access logs found for $containerName.\n";
|
||||
continue;
|
||||
}
|
||||
|
||||
// Parse the timestamp from the last log entry
|
||||
$parts = explode(' : ', $lastLine);
|
||||
if (!isset($parts[0])) continue;
|
||||
|
||||
$lastAccess = DateTime::createFromFormat('Y-m-d H:i:s', trim($parts[0]));
|
||||
if (!$lastAccess) continue;
|
||||
|
||||
// Calculate the idle time in seconds
|
||||
$now = new DateTime();
|
||||
$interval = $now->getTimestamp() - $lastAccess->getTimestamp();
|
||||
|
||||
// Check if the container has been idle for longer than the threshold
|
||||
if ($interval > $thresholdMinutes * 60) {
|
||||
echo "$containerName has been idle for over $thresholdMinutes minutes. Stopping...\n";
|
||||
|
||||
try {
|
||||
// Check if the container exists and stop it if it does
|
||||
if ($lxdService->containerExists($containerName)) {
|
||||
$lxdService->stopContainer($containerName);
|
||||
echo "Stopped container: $containerName\n";
|
||||
} else {
|
||||
echo "Container $containerName does not exist.\n";
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
// Handle any errors that occur while stopping the container
|
||||
echo "Error stopping $containerName: " . $e->getMessage() . "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the last non-empty line from a file.
|
||||
*
|
||||
* @param string $filePath Path to the file.
|
||||
* @return string|null The last line, or null if the file is empty.
|
||||
*/
|
||||
function getLastLine(string $filePath): ?string
|
||||
{
|
||||
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||
return $lines ? end($lines) : null;
|
||||
}
|
||||
@ -10,7 +10,22 @@ class LxdService
|
||||
$this->baseUrl = $_ENV['LXD_API_URL'] ?? 'https://localhost:8443';
|
||||
}
|
||||
|
||||
private function curlInit($url, $method = '') {
|
||||
$ch = curl_init($url);
|
||||
|
||||
// Paths to client certificate and key for TLS authentication
|
||||
$clientCert = $_ENV['LXD_CLIENT_CERT'] ?? '/etc/ssl/lxdapp/client.crt';
|
||||
$clientKey = $_ENV['LXD_CLIENT_KEY'] ?? '/etc/ssl/lxdapp/client.key';
|
||||
|
||||
|
||||
curl_setopt($ch, CURLOPT_SSLCERT, $clientCert);
|
||||
curl_setopt($ch, CURLOPT_SSLKEY, $clientKey);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
if($method) curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
|
||||
return $ch;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an HTTP request to the LXD API.
|
||||
@ -22,28 +37,11 @@ class LxdService
|
||||
* @throws Exception
|
||||
*/
|
||||
private function request(string $method, string $endpoint, array $body = []): array {
|
||||
// if (!isset($_ENV['LXD_CLIENT_CERT'], $_ENV['LXD_CLIENT_KEY'])) {
|
||||
// throw new \Exception("LXD_CLIENT_CERT and LXD_CLIENT_KEY must be set in .env");
|
||||
// }
|
||||
|
||||
$ch = curl_init("{$this->baseUrl}{$endpoint}");
|
||||
|
||||
// Paths to client certificate and key for TLS authentication
|
||||
$clientCert = $_ENV['LXD_CLIENT_CERT'] ?? '/etc/ssl/lxdapp/client.crt';
|
||||
$clientKey = $_ENV['LXD_CLIENT_KEY'] ?? '/etc/ssl/lxdapp/client.key';
|
||||
|
||||
|
||||
curl_setopt($ch, CURLOPT_SSLCERT, $clientCert);
|
||||
curl_setopt($ch, CURLOPT_SSLKEY, $clientKey);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
|
||||
|
||||
$ch = $this->curlInit("{$this->baseUrl}{$endpoint}", $method);
|
||||
if (!empty($body)) {
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
|
||||
}
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
|
||||
|
||||
@ -59,6 +57,7 @@ class LxdService
|
||||
}
|
||||
|
||||
$json = json_decode($response, true);
|
||||
|
||||
if ($httpCode >= 400) {
|
||||
throw new Exception("LXD API Error: " . ($json['error'] ?? 'Unknown'));
|
||||
}
|
||||
@ -66,6 +65,34 @@ class LxdService
|
||||
return $json;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a GET request and returns raw (non-JSON) response.
|
||||
*
|
||||
* @param string $endpoint API endpoint
|
||||
* @return string Raw response body
|
||||
* @throws Exception
|
||||
*/
|
||||
private function requestRaw(string $endpoint): string {
|
||||
$url = "{$this->baseUrl}{$endpoint}";
|
||||
$ch = $this->curlInit($url);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
|
||||
$curlError = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
if ($response === false || $response === null) {
|
||||
throw new \Exception("Raw LXD API call failed: $curlError");
|
||||
}
|
||||
|
||||
if ($httpCode >= 400) {
|
||||
throw new \Exception("LXD raw API returned HTTP $httpCode");
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Retrieves the status of a container.
|
||||
*
|
||||
@ -162,11 +189,48 @@ class LxdService
|
||||
return null;
|
||||
}
|
||||
|
||||
public function isServiceRunning(string $container, string $service): string
|
||||
// public function isServiceRunning(string $container, string $service): string
|
||||
// {
|
||||
// $lxcPath = $_ENV['LXC_PATH'] ?: 'lxc';
|
||||
// $cmd = "$lxcPath exec {$container} -- systemctl is-active {$service} 2>&1";
|
||||
// $output = shell_exec($cmd);
|
||||
// return trim($output);
|
||||
// }
|
||||
|
||||
public function getContainerServiceStatus(string $container, string $service): string
|
||||
{
|
||||
$lxcPath = $_ENV['LXC_PATH'] ?: 'lxc';
|
||||
$cmd = "$lxcPath exec {$container} -- systemctl is-active {$service} 2>&1";
|
||||
$output = shell_exec($cmd);
|
||||
return trim($output);
|
||||
// Step 1: Prepare exec command
|
||||
$execPayload = [
|
||||
"command" => ["systemctl", "is-active", $service],
|
||||
"wait-for-websocket" => false,
|
||||
"record-output" => true,
|
||||
"interactive" => false
|
||||
];
|
||||
|
||||
// Step 2: Start exec operation
|
||||
$execResponse = $this->request('POST', "/1.0/instances/{$container}/exec", $execPayload);
|
||||
$operationUrl = $execResponse['operation'] ?? null;
|
||||
|
||||
if (!$operationUrl) {
|
||||
throw new \Exception("Failed to create exec operation");
|
||||
}
|
||||
|
||||
// Step 3: Wait for operation to complete
|
||||
$waitResponse = $this->request('GET', "{$operationUrl}/wait?timeout=10");
|
||||
$metadata = $waitResponse['metadata']['metadata'] ?? [];
|
||||
|
||||
$outputPaths = $metadata['output'] ?? [];
|
||||
$stdoutPath = $outputPaths['1'] ?? null;
|
||||
|
||||
if (!$stdoutPath) {
|
||||
throw new \Exception("No stdout path returned by LXD");
|
||||
}
|
||||
|
||||
// Step 4: Fetch raw stdout output
|
||||
$rawOutput = $this->requestRaw($stdoutPath);
|
||||
|
||||
return trim($rawOutput); // Expected: 'active', 'inactive', etc.
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
33
api/src/Utils/ContainerHelper.php
Normal file
33
api/src/Utils/ContainerHelper.php
Normal file
@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Utils;
|
||||
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
class ContainerHelper
|
||||
{
|
||||
public static function getName(ServerRequestInterface $request): ?string
|
||||
{
|
||||
// Try to get Origin header, fallback to Host
|
||||
$origin = $request->getHeaderLine('Origin');
|
||||
$domain = !empty($origin) ? parse_url($origin, PHP_URL_HOST) : $request->getHeaderLine('Host');
|
||||
|
||||
// Load config.json once
|
||||
$config = self::getConfig();
|
||||
return $config[$domain] ?? null;
|
||||
}
|
||||
|
||||
protected static function getConfig(): array
|
||||
{
|
||||
static $config = null;
|
||||
|
||||
if ($config !== null) {
|
||||
return $config;
|
||||
}
|
||||
|
||||
$configPath = __DIR__ . '/../../config.json';
|
||||
|
||||
return file_exists($configPath) ? json_decode(file_get_contents($configPath), true) : [];
|
||||
}
|
||||
}
|
||||
@ -3,19 +3,7 @@
|
||||
namespace App\Utils;
|
||||
|
||||
class LogWriterHelper {
|
||||
public static function write(string $name, string $uri): void {
|
||||
// Dynamically resolve the log directory relative to the current file
|
||||
$logDir = realpath(__DIR__ . '/../../public/last-access-logs');
|
||||
|
||||
// If the resolved path doesn't exist (e.g., public dir was missing), create it
|
||||
if (!$logDir) {
|
||||
$logDir = __DIR__ . '/../../public/last-access-logs';
|
||||
if (!file_exists($logDir)) {
|
||||
mkdir($logDir, 0777, true);
|
||||
}
|
||||
}
|
||||
|
||||
$logLine = date("Y-m-d H:i:s") . " : " . $uri . "\n";
|
||||
file_put_contents($logDir . '/' . $name . '.txt', $logLine, FILE_APPEND);
|
||||
public static function write(string $name): void {
|
||||
touch($_ENV['STATEDIR']."/".$name);
|
||||
}
|
||||
}
|
||||
9390
app/package-lock.json
generated
Normal file
9390
app/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
@ -2,16 +2,18 @@
|
||||
<div class="page-wrapper">
|
||||
<Spinner :loading="loading" />
|
||||
<div v-html="output" />
|
||||
<div v-if="!loading">
|
||||
<div v-if="allowAccess" class="login-container">
|
||||
<form @submit.prevent="submitForm" class="login-form" autocomplete="on">
|
||||
<h2 class="title">Login</h2>
|
||||
<div v-show="!loading && status ==='stopped'">
|
||||
<form name="loginForm" id="loginForm" method="post" action="/login.php" @submit.prevent="submitForm" class="login-form" autocomplete="on">
|
||||
<input type="hidden" name="relocation" value="route=search/search&type=simple" />
|
||||
|
||||
<h2 class="title">Login</h2>
|
||||
|
||||
<div class="input-group">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Username"
|
||||
v-model="username"
|
||||
name="username"
|
||||
required
|
||||
autocomplete="username"
|
||||
inputmode="email"
|
||||
@ -23,6 +25,7 @@
|
||||
type="password"
|
||||
placeholder="Password"
|
||||
v-model="password"
|
||||
name="password"
|
||||
required
|
||||
autocomplete="current-password"
|
||||
/>
|
||||
@ -31,29 +34,41 @@
|
||||
<Captcha ref="captchaRef" v-model:captcha="captchaValue" />
|
||||
<button type="submit" :disabled="loading || !captchaValue" class="btn">
|
||||
<span v-if="!loading">Login</span>
|
||||
<span v-else>Loading...</span>
|
||||
<span v-else>Lade Archiv...</span>
|
||||
</button>
|
||||
<p v-if="captchaError" class="error-text">{{ captchaError }}</p>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div v-else class="login-container">
|
||||
<h2 class="title">Access Denied</h2>
|
||||
<p>You must access this page through the proper login flow.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="loading || status !== 'stopped'" class="waiting-container">
|
||||
<h2>Status Mailarchiv</h2>
|
||||
<p v-if="status === 'ready'">Archiv ist bereit, sie werden weitergeleitet...</p>
|
||||
<p v-else-if="status === 'running'">Zugriff auf Archiv wird vorbereitet...</p>
|
||||
<p v-else-if="status === 'error'" class="error-text">{{ errorMessage }}</p>
|
||||
</div>
|
||||
<Spinner :loading="loading" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
/*definePageMeta({
|
||||
// This is an example of inline middleware
|
||||
middleware: async nuxtApp => {
|
||||
const host = useRequestURL().host
|
||||
const res = await $fetch('https://' + host + '/api/status')
|
||||
if (res.status === 'ready') {
|
||||
navigateTo(host, { external: true })
|
||||
return false;
|
||||
}
|
||||
return true
|
||||
},
|
||||
})*/
|
||||
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import Spinner from '@/components/Spinner.vue'
|
||||
import Captcha from '@/components/Captcha.vue'
|
||||
|
||||
const output = ref('')
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const loading = ref(true)
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
@ -61,19 +76,47 @@ const captchaRef = ref(null)
|
||||
const captchaValue = ref('')
|
||||
const captchaError = ref('')
|
||||
const allowAccess = ref(false)
|
||||
const interval = ref(null)
|
||||
const status = ref('starting')
|
||||
const errorMessage = ref('')
|
||||
|
||||
const POLL_MS = 5000
|
||||
const ALLOWED_REDIRECTS = new Set(['/', '/login', '/signin'])
|
||||
function sanitizeRedirect(raw) {
|
||||
if (typeof raw !== 'string') return '/login'
|
||||
if (raw.startsWith('http://') || raw.startsWith('https://')) return '/login'
|
||||
if (!raw.startsWith('/')) return '/login'
|
||||
const pathOnly = raw.split('?')[0]
|
||||
return ALLOWED_REDIRECTS.has(pathOnly) ? raw : '/login'
|
||||
|
||||
async function checkStatus () {
|
||||
try {
|
||||
const res = await $fetch(`${window.location.origin}/api/status`, {
|
||||
method: 'GET',
|
||||
cache: 'no-store'
|
||||
})
|
||||
status.value = res.status
|
||||
|
||||
if (res.status === 'ready') {
|
||||
if (interval.value) clearInterval(interval.value)
|
||||
loading.value = false
|
||||
if (username.value && password.value) {
|
||||
document.getElementById('loginForm').submit()
|
||||
} else {
|
||||
navigateTo(window.location.origin + '/', { external: true })
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
loading.value = false
|
||||
status.value = 'error'
|
||||
console.log(error)
|
||||
errorMessage.value = error?.data?.message || 'Internal server error!'
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
allowAccess.value = true
|
||||
loading.value = false
|
||||
checkStatus()
|
||||
interval.value = setInterval(checkStatus, POLL_MS)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (interval.value) clearInterval(interval.value)
|
||||
})
|
||||
|
||||
const submitForm = async () => {
|
||||
@ -81,42 +124,27 @@ const submitForm = async () => {
|
||||
output.value = ''
|
||||
captchaError.value = ''
|
||||
|
||||
// Read optional redirect from query but sanitize strictly
|
||||
const requested = sanitizeRedirect(String(route.query.redirect || '/login'))
|
||||
|
||||
try {
|
||||
// Optional CSRF token if you set one in a meta tag
|
||||
const csrf = document.querySelector('meta[name="csrf-token"]')?.content
|
||||
|
||||
const res = await $fetch(`${window.location.origin}/api/login`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(csrf ? { 'X-CSRF-Token': csrf } : {})
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
credentials: 'include',
|
||||
body: {
|
||||
username: username.value,
|
||||
password: password.value,
|
||||
source: 'login',
|
||||
panswer: captchaValue.value,
|
||||
redirect: requested
|
||||
panswer: captchaValue.value
|
||||
},
|
||||
throwHttpErrors: false
|
||||
})
|
||||
|
||||
if (res?.status === 'success' && res?.redirect) {
|
||||
router.push(res.redirect) // e.g. /waiting?name=...&handoff=...&path=/login
|
||||
} else {
|
||||
if (res?.status !== 'success') {
|
||||
captchaError.value = res?.message || 'Login failed'
|
||||
loading.value = false
|
||||
} else {
|
||||
status.value = 'starting'
|
||||
}
|
||||
} catch (error) {
|
||||
captchaError.value = error?.data?.message || 'Internal server error!'
|
||||
loading.value = false
|
||||
} finally {
|
||||
loading.value = false
|
||||
// scrub sensitive inputs
|
||||
password.value = ''
|
||||
captchaRef.value?.refreshCaptcha()
|
||||
captchaValue.value = ''
|
||||
}
|
||||
@ -163,5 +191,14 @@ const submitForm = async () => {
|
||||
border-color: #3b82f6;
|
||||
box-shadow: 0 0 0 2px rgba(59,130,246,.3);
|
||||
}
|
||||
.waiting-container {
|
||||
max-width: 100%;
|
||||
width: 400px;
|
||||
margin: 5rem auto;
|
||||
padding: 2rem;
|
||||
border-radius: 8px;
|
||||
background: #f9fafb;
|
||||
box-shadow: 0 4px 10px rgb(0 0 0 / 0.1);
|
||||
}
|
||||
.error-text { color: #b91c1c; margin-top: .5rem; }
|
||||
</style>
|
||||
@ -1,112 +0,0 @@
|
||||
<template>
|
||||
<div class="page-wrapper">
|
||||
<div class="waiting-container">
|
||||
<h2>Container Status: {{ status }}</h2>
|
||||
<p v-if="status === 'ready'">
|
||||
Your container is ready! <a :href="openLink" target="_blank" rel="noopener">Open it</a>
|
||||
</p>
|
||||
<p v-else-if="status === 'running'">Waiting for services to be ready...</p>
|
||||
<p v-else-if="status === 'starting'">Starting container...</p>
|
||||
<p v-else-if="status === 'error'" class="error-text">{{ errorMessage }}</p>
|
||||
</div>
|
||||
<Spinner :loading="loading" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, onUnmounted, computed } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
const name = String(route.query.name || '')
|
||||
const handoff = typeof route.query.handoff === 'string' ? route.query.handoff : ''
|
||||
const rawPath = typeof route.query.path === 'string' ? route.query.path : '/login'
|
||||
|
||||
function sanitizePath(p) {
|
||||
if (typeof p !== 'string') return '/login'
|
||||
if (p.startsWith('http://') || p.startsWith('https://')) return '/login'
|
||||
if (!p.startsWith('/')) return '/login'
|
||||
const allowed = new Set(['/', '/login', '/signin'])
|
||||
const pathOnly = p.split('?')[0]
|
||||
return allowed.has(pathOnly) ? p : '/login'
|
||||
}
|
||||
const safePath = sanitizePath(rawPath)
|
||||
|
||||
const loading = ref(true)
|
||||
const status = ref('starting')
|
||||
const ip = ref(null)
|
||||
const interval = ref(null)
|
||||
const errorMessage = ref(null)
|
||||
|
||||
const POLL_MS = 5000
|
||||
|
||||
const openLink = computed(() => (ip.value ? `http://${ip.value}` : '#'))
|
||||
|
||||
async function checkStatus () {
|
||||
try {
|
||||
const res = await $fetch(`${window.location.origin}/api/status?name=${encodeURIComponent(name)}`, {
|
||||
method: 'GET',
|
||||
cache: 'no-store'
|
||||
})
|
||||
|
||||
status.value = res.status
|
||||
if (res.ip) ip.value = res.ip
|
||||
|
||||
if (res.status === 'ready') {
|
||||
if (interval.value) clearInterval(interval.value)
|
||||
loading.value = false
|
||||
|
||||
// Prefer bridge handoff if we have an id; otherwise, just open container root.
|
||||
if (handoff) {
|
||||
const bridge = new URL(`${window.location.origin}/api/handoff/post`)
|
||||
bridge.searchParams.set('name', name)
|
||||
bridge.searchParams.set('handoff', handoff)
|
||||
bridge.searchParams.set('path', safePath)
|
||||
// Replace to avoid creating a back entry with sensitive navigation
|
||||
window.location.replace(bridge.toString())
|
||||
} else if (ip.value) {
|
||||
window.location.replace(`http://${ip.value}`)
|
||||
} else {
|
||||
window.location.replace(`http://${window.location.host}`)
|
||||
}
|
||||
} else {
|
||||
loading.value = true
|
||||
}
|
||||
} catch (error) {
|
||||
loading.value = false
|
||||
status.value = 'error'
|
||||
errorMessage.value = error?.data?.message || 'Internal server error!'
|
||||
|
||||
if (interval.value) clearInterval(interval.value)
|
||||
|
||||
// Bounce back to app without leaking anything sensitive
|
||||
setTimeout(() => {
|
||||
router.replace(`/app/`)
|
||||
}, 5000)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
checkStatus()
|
||||
interval.value = setInterval(checkStatus, POLL_MS)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (interval.value) clearInterval(interval.value)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.waiting-container {
|
||||
max-width: 100%;
|
||||
width: 400px;
|
||||
margin: 5rem auto;
|
||||
padding: 2rem;
|
||||
border-radius: 8px;
|
||||
background: #f9fafb;
|
||||
box-shadow: 0 4px 10px rgb(0 0 0 / 0.1);
|
||||
}
|
||||
.error-text { color: #b91c1c; }
|
||||
</style>
|
||||
29
index.php
29
index.php
@ -1,5 +1,4 @@
|
||||
<?php
|
||||
|
||||
// === Handle API requests ===
|
||||
$requestUri = $_SERVER['REQUEST_URI'];
|
||||
if (str_starts_with($requestUri, '/api/')) {
|
||||
@ -27,8 +26,7 @@ $container = $config[$host] ?? null;
|
||||
$lxd = new LxdService();
|
||||
|
||||
// === Helper URLs ===
|
||||
$redirectBase = parseUrl("$host/app?auth=ok&redirect=" . urlencode(getFullUrl()));
|
||||
$waitingPage = parseUrl("$host/app/waiting?name=$container&redirect=" . urlencode(getFullUrl()));
|
||||
$redirectBase = parseUrl("$host/app");
|
||||
// === If container is missing or invalid ===
|
||||
if (!$container || !$lxd->containerExists($container)) {
|
||||
redirect($redirectBase);
|
||||
@ -41,24 +39,16 @@ if ($state !== 'Running') {
|
||||
redirect($redirectBase);
|
||||
}
|
||||
|
||||
// === Check container status ===
|
||||
$state = $lxd->getContainerState($container)['metadata']['status'] ?? 'Stopped';
|
||||
// === Get container IP ===
|
||||
$nginx = $lxd->getContainerServiceStatus($container, 'nginx');
|
||||
$mysql = $lxd->getContainerServiceStatus($container, 'mariadb');
|
||||
|
||||
if ($state !== 'Running') {
|
||||
if ($nginx !== 'active' || $mysql !== 'active') {
|
||||
redirect($redirectBase);
|
||||
}
|
||||
|
||||
// === Get container IP ===
|
||||
$ip = $lxd->getContainerIP($container);
|
||||
$nginx = $lxd->isServiceRunning($container, 'nginx');
|
||||
$mysql = $lxd->isServiceRunning($container, 'mysql');
|
||||
|
||||
if (!$ip || $nginx !== 'active' || $mysql !== 'active') {
|
||||
redirect($waitingPage);
|
||||
}
|
||||
|
||||
// === Proxy to container ===
|
||||
proxy($container, "http://{$ip}{$requestUri}");
|
||||
proxy($container, "http://{$host}{$requestUri}");
|
||||
exit;
|
||||
|
||||
|
||||
@ -70,15 +60,14 @@ function redirect(string $to): void {
|
||||
}
|
||||
|
||||
function proxy(string $name, string $targetUrl): void {
|
||||
Proxy::$AUTH_KEY = $_ENV['AUTH_KEY'] ?? 'YOUR_DEFAULT_AUTH_KEY';
|
||||
Proxy::$ENABLE_AUTH = true;
|
||||
Proxy::$ENABLE_AUTH = false;
|
||||
Proxy::$HEADER_HTTP_PROXY_AUTH = 'HTTP_PROXY_AUTH';
|
||||
|
||||
$_SERVER['HTTP_PROXY_AUTH'] = Proxy::$AUTH_KEY;
|
||||
$_SERVER['HTTP_PROXY_TARGET_URL'] = $targetUrl;
|
||||
|
||||
$responseCode = Proxy::run();
|
||||
writeLog($name, $targetUrl);
|
||||
touch($_ENV['STATEDIR']."/".$name);
|
||||
|
||||
}
|
||||
|
||||
function getFullUrl(): string {
|
||||
|
||||
Reference in New Issue
Block a user