Compare commits

..

20 Commits

Author SHA1 Message Date
19bdd41664 fix 2025-09-08 13:59:28 +02:00
b99533ced8 fix 2025-09-03 17:21:27 +02:00
d5ecf0da96 fix 2025-09-03 16:52:42 +02:00
fb51cd6e29 fix 2025-09-03 16:49:26 +02:00
65b6f45753 test 2025-09-03 16:47:28 +02:00
cfabf3c9f5 test 2025-09-03 16:44:57 +02:00
4072377548 fix 2025-09-03 16:35:53 +02:00
b96a1c0065 fix 2025-09-03 16:32:13 +02:00
c05d98f333 fix 2025-09-03 16:30:08 +02:00
481508b88c fix 2025-09-03 16:28:16 +02:00
f8ab14cc29 test 2025-09-03 16:26:31 +02:00
b48e04ba38 remove vendor 2025-09-03 16:09:59 +02:00
4ad0dfd5bc Merge branch 'urvishpatelce-main' 2025-09-03 16:05:59 +02:00
78b8a25546 fix 2025-09-03 15:58:46 +02:00
bd32f43c9e fixes 2025-09-03 15:57:56 +02:00
a3f5b5a0cf fix: update code 2025-09-02 20:38:58 +02:00
627d462a8e fixes 2025-09-01 16:40:37 +00:00
7db9ce4d17 fix: update service api call 2025-09-01 15:06:16 +02:00
e96bcb7a94 fix: update pass credentials to container 2025-08-21 11:41:30 +02:00
6c553bea8a fix: update waiting logic 2025-08-18 18:50:34 +02:00
16 changed files with 11106 additions and 348 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
api/vendor/*

5
add-container.php Normal file
View 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));

View File

@ -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

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,3 @@
{
"lxdapp.local": "testone"
"auftrag.local": "auftrag"
}

View File

@ -6,13 +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\Services\LxdService;
use Zounar\PHPProxy\Proxy;
use App\Utils\LogWriterHelper;
require __DIR__ . '/../vendor/autoload.php';
@ -20,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',
@ -38,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);
@ -63,7 +56,6 @@ $app->add(CorsMiddleware::class);
// Register middleware
(require __DIR__ . '/../src/Bootstrap/Middleware.php')($app);
// Register routes
// API contianer proxy route
@ -71,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']);
});
/**

View File

@ -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.)

View File

@ -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
{
@ -15,46 +16,35 @@ class LoginController
*/
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'])) {
$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);
}
// Write log
LogWriterHelper::write($name, $request->getUri());
LogWriterHelper::write($name);
$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',
@ -65,8 +55,7 @@ class LoginController
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, [
@ -88,18 +77,19 @@ 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,
'name' => $name,
'message' => 'Container is ready',
]);
}
@ -124,10 +114,6 @@ class LoginController
]);
}
/**
* 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';
}
}

View File

@ -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;
}

View File

@ -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.
}
}

View 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) : [];
}
}

View File

@ -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

File diff suppressed because it is too large Load Diff

View File

@ -2,125 +2,155 @@
<div class="page-wrapper">
<Spinner :loading="loading" />
<div v-html="output" />
<!-- 👇 Only show form if access is allowed -->
<div v-if="!loading">
<div v-if="allowAccess" class="login-container">
<form @submit.prevent="submitForm" class="login-form">
<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"
/>
</div>
<div class="input-group">
<input
type="password"
placeholder="Password"
v-model="password"
name="password"
required
autocomplete="current-password"
/>
</div>
<!-- Include Captcha -->
<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>
<br/>
<p v-if="captchaError" class="error-text">{{ captchaError }}</p>
</form>
</div>
<!-- 👇 Show this if the user did not come from an approved source -->
<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 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>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import Spinner from '@/components/Spinner.vue';
import Captcha from '@/components/Captcha.vue';
/*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 loading = ref(true)
const username = ref('')
const password = ref('')
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'])
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!'
}
}
const output = ref('');
const router = useRouter();
const route = useRoute();
const loading = ref(true);
const username = ref('');
const password = ref('');
const captchaRef = ref(null);
const captchaValue = ref('');
const captchaError = ref('');
const redirectTo = ref('/');
const allowAccess = ref(false) // 🔐 This controls what to show
// 🟡 Grab redirect param on load
onMounted(() => {
const redirectParam = route.query.redirect;
const authParam = route.query.auth;
if (redirectParam && typeof redirectParam === 'string') {
redirectTo.value = decodeURIComponent(redirectParam);
}
// ✅ More reliable than document.referrer
if (authParam === 'ok') {
allowAccess.value = true;
}
allowAccess.value = true
loading.value = false
checkStatus()
interval.value = setInterval(checkStatus, POLL_MS)
})
loading.value = false;
});
onUnmounted(() => {
if (interval.value) clearInterval(interval.value)
})
const submitForm = async () => {
loading.value = true;
output.value = '';
const encodedRedirect = new URL(redirectTo.value, window.location.origin);
encodedRedirect.searchParams.set('username', username.value);
encodedRedirect.searchParams.set('password', password.value);
loading.value = true
output.value = ''
captchaError.value = ''
try {
const res = await $fetch(`${window.location.origin}/api/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Type': 'application/json'
},
body: {
username: username.value,
password: password.value,
source: 'login',
panswer: captchaValue.value,
redirect: encodedRedirect.toString()
panswer: captchaValue.value
},
credentials: 'include',
throwHttpErrors: false, // important: do NOT throw on 401/4xx
});
captchaError.value = '';
router.push(res.redirect);
// window.location.href = encodedRedirect.toString();
} catch (error) {
if (error.statusCode === 400) {
captchaError.value = error?.data?.message || 'Invalid CAPTCHA';
loading.value = false;
throwHttpErrors: false
})
if (res?.status !== 'success') {
captchaError.value = res?.message || 'Login failed'
} else {
captchaError.value = error?.data?.message || 'Internal server error!';
// window.location.reload();
loading.value = false;
status.value = 'starting'
}
} catch (error) {
captchaError.value = error?.data?.message || 'Internal server error!'
} finally {
captchaRef.value?.refreshCaptcha();
captchaValue.value = '';
loading.value = false
// scrub sensitive inputs
captchaRef.value?.refreshCaptcha()
captchaValue.value = ''
}
}
};
</script>
<style scoped>
.login-container {
max-width: 100%;
@ -141,22 +171,15 @@ const submitForm = async () => {
padding: 0.8rem;
font-weight: 600;
font-size: 1.1rem;
background-color: #3b82f6; /* blue-500 */
background-color: #3b82f6;
color: white;
border: none;
border-radius: 6px;
cursor: pointer;
transition: background-color 0.3s;
}
.btn:hover:not(:disabled) {
background-color: #2563eb; /* blue-600 */
}
.btn:disabled {
background-color: #93c5fd; /* blue-300 */
cursor: not-allowed;
}
.btn:hover:not(:disabled) { background-color: #2563eb; }
.btn:disabled { background-color: #93c5fd; cursor: not-allowed; }
.input-group input {
padding: 0.8rem;
border: 1px solid #ccc;
@ -166,7 +189,16 @@ const submitForm = async () => {
.input-group input:focus {
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);
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>

View File

@ -1,76 +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="`http://${ip}`" target="_blank">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 { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
const name = route.query.name;
const redirect = route.query.redirect;
const loading = ref(true);
const status = ref('starting');
const ip = ref(null);
const interval = ref(null);
const errorMessage = ref(null);
const checkStatus = async () => {
try {
const res = await $fetch(`${window.location.origin}/api/status?name=${name}`);
status.value = res.status;
if (interval.value) {
clearInterval(interval.value);
}
if (res.status === 'ready') {
ip.value = res.ip;
// Redirect or show login link
window.location.href= 'http://'+ window.location.host;
}
} catch (error) {
loading.value = false;
status.value = 'error';
errorMessage.value = error?.data?.message || 'Internal server error!';
clearInterval(interval.value);
setTimeout( () => {
router.replace(`/app/?auth=ok&redirect=${redirect}`);
}, 5000);
}
};
onMounted(() => {
checkStatus();
interval.value = setInterval(checkStatus, 3000); // Poll every 3s
});
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);
}
</style>

View File

@ -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 {