Compare commits

..

3 Commits

Author SHA1 Message Date
5b977c1f41 wowowowowo
Some checks failed
CI / Lint (push) Failing after 22s
CI / Tests (push) Failing after 33s
2026-05-28 15:15:41 +01:00
8f603122e2 wip
All checks were successful
CI / Tests (push) Successful in 36s
CI / Lint (push) Successful in 1m3s
2026-05-24 13:55:30 +01:00
66f0ee9e50 Migrate to Gitea, switch JS tooling to oxlint/oxfmt, lift test coverage to 95%
All checks were successful
CI / Tests (push) Successful in 43s
CI / Lint (push) Successful in 1m3s
- Add .gitea/workflows/ci.yml ported from lifeos (lint + tests with coverage gate)
- Set up phpstan (larastan + peststan, baseline at level max)
- Replace eslint/prettier with oxlint/oxfmt; reformat resources/
- Add composer phpstan/coverage/quality scripts; restore --min=95 coverage gate
- Exclude integration plumbing (Saloon Hetzner classes, SSH wrappers, console
  commands, DTOs) from coverage to keep the gate focused on business logic
- Add ~12 new test files covering models, drivers, controllers, jobs, auth
  flows, request validators, and the IP CIDR helper
- Fix Support\Ip::inNetwork PHP 8.4 TypeError in CIDR mask check
- Fix FirewallRule::command comparing the enum-cast type column to a string
- Fix Server::network using the wrong foreign key column
- Remove unreachable code under abort(403) in RegisteredUserController
2026-05-13 16:51:07 +01:00
335 changed files with 19182 additions and 2209 deletions

View File

@@ -63,3 +63,5 @@ AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}" VITE_APP_NAME="${APP_NAME}"
HETZNER_KEY=

78
.gitea/workflows/ci.yml Normal file
View File

@@ -0,0 +1,78 @@
name: CI
on:
push:
branches:
- main
pull_request:
permissions:
contents: read
jobs:
lint:
name: Lint
runs-on: ubuntu-latest
container:
image: git.bayliss.cloud/harry/gitea-ci-runner:php8.4
defaults:
run:
shell: bash
steps:
- name: Check out repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Install Composer dependencies
run: composer install --no-interaction --prefer-dist --optimize-autoloader
- name: Install frontend dependencies
run: bun install --frozen-lockfile
- name: Run frontend lint
run: bun run lint:check
- name: Check frontend formatting
run: bun run format:check
- name: Check PHP formatting
run: vendor/bin/pint --test
- name: Run static analysis
run: composer phpstan
tests:
name: Tests
runs-on: ubuntu-latest
container:
image: git.bayliss.cloud/harry/gitea-ci-runner:php8.4
defaults:
run:
shell: bash
env:
APP_ENV: testing
APP_KEY: base64:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
CACHE_STORE: array
DB_CONNECTION: sqlite
DB_DATABASE: database/testing.sqlite
MAIL_MAILER: array
QUEUE_CONNECTION: sync
SESSION_DRIVER: array
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Prepare SQLite database
run: touch database/testing.sqlite
- name: Install Composer dependencies
run: composer install --no-interaction --prefer-dist --optimize-autoloader
- name: Run test suite with coverage
run: composer coverage

View File

@@ -1,3 +0,0 @@
resources/js/components/ui/*
resources/js/ziggy.js
resources/views/mail/*

View File

@@ -1,18 +0,0 @@
{
"semi": true,
"singleQuote": true,
"singleAttributePerLine": false,
"htmlWhitespaceSensitivity": "css",
"printWidth": 150,
"plugins": ["prettier-plugin-organize-imports", "prettier-plugin-tailwindcss"],
"tailwindFunctions": ["clsx", "cn"],
"tabWidth": 4,
"overrides": [
{
"files": "**/*.yml",
"options": {
"tabWidth": 2
}
}
]
}

View File

@@ -8,6 +8,7 @@ use App\Actions\Applications\VerifyRepositoryAccess;
use App\Enums\RepositoryType; use App\Enums\RepositoryType;
use App\Enums\ServerStatus; use App\Enums\ServerStatus;
use App\Http\Requests\StoreApplicationRequest; use App\Http\Requests\StoreApplicationRequest;
use App\Http\Requests\UpdateApplicationRequest;
use App\Models\Application; use App\Models\Application;
use App\Models\Organisation; use App\Models\Organisation;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
@@ -27,9 +28,12 @@ class ApplicationController extends Controller
public function create(Request $request): Response public function create(Request $request): Response
{ {
Organisation::findOrFail($request->route('organisation')); $organisation = Organisation::findOrFail($request->route('organisation'));
return inertia('applications/Create'); return inertia('applications/Create', [
'sourceProviders' => $organisation->sourceProviders()->get(),
'repositoryTypes' => RepositoryType::toArray(),
]);
} }
public function store(StoreApplicationRequest $request): RedirectResponse public function store(StoreApplicationRequest $request): RedirectResponse
@@ -38,8 +42,9 @@ class ApplicationController extends Controller
$application = $organisation->applications()->create([ $application = $organisation->applications()->create([
'name' => $request->string('name')->toString(), 'name' => $request->string('name')->toString(),
'source_provider_id' => $this->sourceProviderIdFor($organisation, $request->integer('source_provider_id') ?: null),
'repository_url' => $request->string('repository_url')->toString(), 'repository_url' => $request->string('repository_url')->toString(),
'repository_type' => RepositoryType::GIT, 'repository_type' => $request->enum('repository_type', RepositoryType::class),
'default_branch' => $request->string('default_branch')->toString(), 'default_branch' => $request->string('default_branch')->toString(),
]); ]);
@@ -56,14 +61,24 @@ class ApplicationController extends Controller
$id = $request->route('application'); $id = $request->route('application');
$organisation = Organisation::findOrFail($request->route('organisation')); $organisation = Organisation::findOrFail($request->route('organisation'));
$application = Application::with([ $application = Application::with([
'environments.buildArtifacts' => fn ($query) => $query->latest()->limit(5),
'environments.operations' => fn ($query) => $query->latest()->limit(1),
'environments.services.replicas',
'environments.services.endpoints',
'environments.services.slices', 'environments.services.slices',
'environments.attachments.service', 'environments.attachments.service',
'environments.variables', 'environments.variables',
'organisation', 'organisation',
'sourceProvider',
])->whereBelongsTo($organisation)->findOrFail($id); ])->whereBelongsTo($organisation)->findOrFail($id);
return inertia('applications/Show', [ return inertia('applications/Show', [
'application' => $application, 'application' => $application,
'deploymentRequirements' => [
'registryRequired' => $organisation->servers()->count() > 1 && $organisation->registries()->doesntExist(),
'registryCount' => $organisation->registries()->count(),
'serverCount' => $organisation->servers()->count(),
],
'servers' => inertia()->optional(function () use ($application) { 'servers' => inertia()->optional(function () use ($application) {
return $application return $application
->organisation ->organisation
@@ -75,6 +90,51 @@ class ApplicationController extends Controller
]); ]);
} }
public function edit(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
return inertia('applications/Edit', [
'application' => $application,
'repositoryTypes' => RepositoryType::toArray(),
'sourceProviders' => $organisation->sourceProviders()->get(),
]);
}
public function update(UpdateApplicationRequest $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$application->update([
'name' => $request->string('name')->toString(),
'source_provider_id' => $this->sourceProviderIdFor($organisation, $request->integer('source_provider_id') ?: null),
'repository_type' => $request->enum('repository_type', RepositoryType::class),
'repository_url' => $request->string('repository_url')->toString(),
'default_branch' => $request->string('default_branch')->toString(),
]);
return redirect()
->route('applications.show', [
'organisation' => $organisation->id,
'application' => $application->id,
])
->with('success', 'Application updated.');
}
public function destroy(Request $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$application->delete();
return redirect()
->route('applications.index', ['organisation' => $organisation->id])
->with('success', 'Application deleted.');
}
public function verifyRepository(Request $request): RedirectResponse public function verifyRepository(Request $request): RedirectResponse
{ {
$organisation = Organisation::findOrFail($request->route('organisation')); $organisation = Organisation::findOrFail($request->route('organisation'));
@@ -86,4 +146,23 @@ class ApplicationController extends Controller
return back()->with('success', 'Repository access verified.'); return back()->with('success', 'Repository access verified.');
} }
public function rotateDeployKey(Request $request, GenerateDeployKey $generateDeployKey): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$generateDeployKey->execute($application);
return back()->with('success', 'Deploy key rotated. Install the new public key before verifying access.');
}
private function sourceProviderIdFor(Organisation $organisation, ?int $sourceProviderId): ?int
{
if ($sourceProviderId === null) {
return null;
}
return $organisation->sourceProviders()->findOrFail($sourceProviderId)->id;
}
} }

View File

@@ -3,13 +3,8 @@
namespace App\Http\Controllers\Auth; namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Inertia\Inertia; use Inertia\Inertia;
use Inertia\Response; use Inertia\Response;
@@ -23,31 +18,8 @@ class RegisteredUserController extends Controller
return Inertia::render('auth/Register'); return Inertia::render('auth/Register');
} }
/**
* Handle an incoming registration request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): RedirectResponse public function store(Request $request): RedirectResponse
{ {
abort(403, 'Registration is disabled.'); abort(403, 'Registration is disabled.');
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|lowercase|email|max:255|unique:'.User::class,
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
Auth::login($user);
return to_route('dashboard');
} }
} }

View File

@@ -0,0 +1,44 @@
<?php
namespace App\Http\Controllers;
use App\Models\BuildArtifact;
use App\Models\Organisation;
use Illuminate\Http\Request;
use Inertia\Response;
class BuildArtifactController extends Controller
{
public function index(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
return inertia('build-artifacts/Index', [
'application' => $application,
'environment' => $environment,
'artifacts' => $environment->buildArtifacts()
->with(['builtByOperation', 'builtByService'])
->latest()
->paginate(30),
]);
}
public function show(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
/** @var BuildArtifact $artifact */
$artifact = $environment->buildArtifacts()
->with(['builtByOperation.steps', 'builtByService'])
->findOrFail($request->route('artifact'));
return inertia('build-artifacts/Show', [
'application' => $application,
'environment' => $environment,
'artifact' => $artifact,
]);
}
}

View File

@@ -6,6 +6,7 @@ use App\Actions\Environments\AttachManagedService;
use App\Enums\EnvironmentAttachmentRole; use App\Enums\EnvironmentAttachmentRole;
use App\Enums\ServiceType; use App\Enums\ServiceType;
use App\Http\Requests\StoreEnvironmentAttachmentRequest; use App\Http\Requests\StoreEnvironmentAttachmentRequest;
use App\Http\Requests\UpdateEnvironmentAttachmentRequest;
use App\Models\Organisation; use App\Models\Organisation;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -27,6 +28,12 @@ class EnvironmentAttachmentController extends Controller
->orderBy('name') ->orderBy('name')
->get(['id', 'name', 'type', 'category']), ->get(['id', 'name', 'type', 'category']),
'roles' => array_values(EnvironmentAttachmentRole::toArray()), 'roles' => array_values(EnvironmentAttachmentRole::toArray()),
'compatibility' => [
EnvironmentAttachmentRole::DATABASE->value => [ServiceType::POSTGRES->value],
EnvironmentAttachmentRole::CACHE->value => [ServiceType::VALKEY->value],
EnvironmentAttachmentRole::QUEUE->value => [ServiceType::VALKEY->value],
EnvironmentAttachmentRole::GATEWAY->value => [ServiceType::CADDY->value],
],
]); ]);
} }
@@ -37,7 +44,7 @@ class EnvironmentAttachmentController extends Controller
$environment = $application->environments()->findOrFail($request->route('environment')); $environment = $application->environments()->findOrFail($request->route('environment'));
$service = $organisation->services()->findOrFail($request->integer('service_id')); $service = $organisation->services()->findOrFail($request->integer('service_id'));
app(AttachManagedService::class)->execute( $attachment = app(AttachManagedService::class)->execute(
environment: $environment, environment: $environment,
service: $service, service: $service,
role: $request->enum('role', EnvironmentAttachmentRole::class), role: $request->enum('role', EnvironmentAttachmentRole::class),
@@ -46,6 +53,17 @@ class EnvironmentAttachmentController extends Controller
isPrimary: $request->boolean('is_primary', true), isPrimary: $request->boolean('is_primary', true),
); );
if ($request->enum('role', EnvironmentAttachmentRole::class) === EnvironmentAttachmentRole::GATEWAY && $attachment->serviceSlice) {
$attachment->serviceSlice->update([
'config' => [
...($attachment->serviceSlice->config ?? []),
'domain' => $request->filled('domain') ? $request->string('domain')->toString() : null,
'path_prefix' => $request->filled('path_prefix') ? $request->string('path_prefix')->toString() : '/',
'tls_enabled' => $request->boolean('tls_enabled', true),
],
]);
}
return redirect() return redirect()
->route('environments.show', [ ->route('environments.show', [
'organisation' => $organisation->id, 'organisation' => $organisation->id,
@@ -54,4 +72,73 @@ class EnvironmentAttachmentController extends Controller
]) ])
->with('success', 'Managed service attached.'); ->with('success', 'Managed service attached.');
} }
public function edit(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
$attachment = $environment->attachments()
->with(['service', 'serviceSlice'])
->findOrFail($request->route('attachment'));
return inertia('environment-attachments/Edit', [
'application' => $application,
'environment' => $environment,
'attachment' => $attachment,
'roles' => array_values(EnvironmentAttachmentRole::toArray()),
]);
}
public function update(UpdateEnvironmentAttachmentRequest $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
$attachment = $environment->attachments()->findOrFail($request->route('attachment'));
$attachment->update([
'role' => $request->enum('role', EnvironmentAttachmentRole::class),
'env_prefix' => $request->filled('env_prefix') ? $request->string('env_prefix')->toString() : null,
'is_primary' => $request->boolean('is_primary'),
]);
if ($attachment->serviceSlice && $request->enum('role', EnvironmentAttachmentRole::class) === EnvironmentAttachmentRole::GATEWAY) {
$attachment->serviceSlice->update([
'config' => [
...($attachment->serviceSlice->config ?? []),
'domain' => $request->filled('domain') ? $request->string('domain')->toString() : null,
'path_prefix' => $request->filled('path_prefix') ? $request->string('path_prefix')->toString() : '/',
'tls_enabled' => $request->boolean('tls_enabled', true),
'certificate_status' => $request->filled('certificate_status') ? $request->string('certificate_status')->toString() : null,
],
]);
}
return redirect()
->route('environments.show', [
'organisation' => $organisation->id,
'application' => $application->id,
'environment' => $environment->id,
])
->with('success', 'Attachment updated.');
}
public function destroy(Request $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
$attachment = $environment->attachments()->findOrFail($request->route('attachment'));
$attachment->delete();
return redirect()
->route('environments.show', [
'organisation' => $organisation->id,
'application' => $application->id,
'environment' => $environment->id,
])
->with('success', 'Attachment detached.');
}
} }

View File

@@ -2,12 +2,54 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Actions\Applications\CreateLaravelEnvironment;
use App\Enums\BuildStrategy;
use App\Enums\EnvironmentAttachmentRole;
use App\Enums\SchedulerMode;
use App\Enums\ServiceType;
use App\Http\Requests\StoreEnvironmentRequest;
use App\Http\Requests\UpdateEnvironmentRequest;
use App\Models\Environment;
use App\Models\Organisation; use App\Models\Organisation;
use App\Support\CaddyRouteRenderer;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Inertia\Response; use Inertia\Response;
class EnvironmentController extends Controller class EnvironmentController extends Controller
{ {
public function create(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
return inertia('environments/Create', [
'application' => $application,
]);
}
public function store(StoreEnvironmentRequest $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = app(CreateLaravelEnvironment::class)->execute(
application: $application,
name: $request->string('name')->toString(),
branch: $request->string('branch')->toString(),
phpVersion: $request->string('php_version')->toString(),
);
return redirect()
->route('environments.show', [
'organisation' => $organisation->id,
'application' => $application->id,
'environment' => $environment->id,
])
->with('success', 'Environment created.');
}
public function show(Request $request): Response public function show(Request $request): Response
{ {
$organisation = Organisation::findOrFail($request->route('organisation')); $organisation = Organisation::findOrFail($request->route('organisation'));
@@ -15,18 +57,151 @@ class EnvironmentController extends Controller
$environment = $application->environments() $environment = $application->environments()
->with([ ->with([
'services.replicas', 'services.replicas',
'services.endpoints',
'services.slices', 'services.slices',
'services.operations.steps', 'services.operations.steps',
'attachments.service', 'attachments.service',
'attachments.serviceSlice', 'attachments.serviceSlice',
'variables', 'variables',
'buildArtifacts.builtByService',
'operations.steps', 'operations.steps',
'operations.children.target',
]) ])
->findOrFail($request->route('environment')); ->findOrFail($request->route('environment'));
$serverCount = $this->serverIdsFor($environment)->count();
return inertia('environments/Show', [ return inertia('environments/Show', [
'application' => $application, 'application' => $application,
'environment' => $environment, 'environment' => $environment,
'deploymentRequirements' => [
'registryRequired' => $organisation->registries()->doesntExist() && $serverCount > 1,
'registryCount' => $organisation->registries()->count(),
'serverCount' => $serverCount,
],
'gatewayRoutePreviews' => $this->gatewayRoutePreviews($environment),
]); ]);
} }
public function edit(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()
->with('services')
->findOrFail($request->route('environment'));
return inertia('environments/Edit', [
'application' => $application,
'environment' => $environment,
'schedulerModes' => array_values(SchedulerMode::toArray()),
'buildStrategies' => array_values(BuildStrategy::toArray()),
]);
}
public function update(UpdateEnvironmentRequest $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()
->with('services')
->findOrFail($request->route('environment'));
$schedulerTargetServiceId = $request->integer('scheduler_target_service_id') ?: null;
if ($schedulerTargetServiceId !== null) {
abort_unless($environment->services()->whereKey($schedulerTargetServiceId)->exists(), 422);
}
$environment->update([
'name' => $request->string('name')->toString(),
'branch' => $request->string('branch')->toString(),
'status' => $request->string('status')->toString(),
'scheduler_enabled' => $request->boolean('scheduler_enabled'),
'scheduler_target_service_id' => $schedulerTargetServiceId,
'scheduler_mode' => $request->enum('scheduler_mode', SchedulerMode::class),
'build_config' => [
...($environment->build_config ?? []),
'build_strategy' => $request->enum('build_strategy', BuildStrategy::class)?->value,
'php_version' => $request->string('php_version')->toString(),
'document_root' => $request->string('document_root')->toString(),
'health_path' => $request->string('health_path')->toString(),
'js_package_manager' => $request->string('js_package_manager')->toString(),
'js_build_command' => $request->filled('js_build_command')
? $request->string('js_build_command')->toString()
: null,
],
]);
return redirect()
->route('environments.show', [
'organisation' => $organisation->id,
'application' => $application->id,
'environment' => $environment->id,
])
->with('success', 'Environment updated.');
}
public function destroy(Request $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
$environment->delete();
return redirect()
->route('applications.show', [
'organisation' => $organisation->id,
'application' => $application->id,
])
->with('success', 'Environment deleted.');
}
/**
* @return \Illuminate\Support\Collection<int, int>
*/
private function serverIdsFor(Environment $environment): Collection
{
return $environment->services
->flatMap(fn ($service) => [
$service->server_id,
...$service->replicas->pluck('server_id')->all(),
])
->filter()
->unique()
->values();
}
/**
* @return Collection<int, array{attachment_id: int, caddyfile: string}>
*/
private function gatewayRoutePreviews(Environment $environment): Collection
{
$upstreams = $this->previewGatewayUpstreams($environment);
$renderer = app(CaddyRouteRenderer::class);
return $environment->attachments
->filter(fn ($attachment): bool => $attachment->role === EnvironmentAttachmentRole::GATEWAY)
->map(fn ($attachment): array => [
'attachment_id' => $attachment->id,
'caddyfile' => $renderer->render($attachment, $upstreams),
])
->values();
}
/**
* @return array<int, string>
*/
private function previewGatewayUpstreams(Environment $environment): array
{
return $environment->services
->filter(fn ($service): bool => $service->type === ServiceType::LARAVEL && in_array('web', $service->process_roles ?? [], true))
->flatMap(fn ($service) => $service->replicas->map(
fn ($replica): string => ($replica->internal_host ?: $replica->container_name).':'.($replica->internal_port ?: 80)
))
->values()
->whenEmpty(fn ($upstreams) => $upstreams->push('web:80'))
->all();
}
} }

View File

@@ -2,15 +2,17 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Http\Requests\StoreEnvironmentDeploymentRequest;
use App\Jobs\Environments\DeployEnvironment; use App\Jobs\Environments\DeployEnvironment;
use App\Models\Application; use App\Models\Application;
use App\Models\Environment; use App\Models\Environment;
use App\Models\Organisation; use App\Models\Organisation;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Collection;
class EnvironmentDeploymentController extends Controller class EnvironmentDeploymentController extends Controller
{ {
public function store(Organisation $organisation, Application $application, Environment $environment): RedirectResponse public function store(StoreEnvironmentDeploymentRequest $request, Organisation $organisation, Application $application, Environment $environment): RedirectResponse
{ {
abort_unless( abort_unless(
(int) $application->organisation_id === (int) $organisation->id (int) $application->organisation_id === (int) $organisation->id
@@ -18,7 +20,16 @@ class EnvironmentDeploymentController extends Controller
404, 404,
); );
dispatch(new DeployEnvironment($environment)); $environment->loadMissing('services.replicas');
if ($organisation->registries()->doesntExist() && $this->serverIdsFor($environment)->count() > 1) {
return back()->with('error', 'Configure a registry before deploying this environment to multiple servers.');
}
dispatch(new DeployEnvironment(
environment: $environment,
targetCommit: $request->validated('target_commit') ?: null,
));
return redirect()->route('environments.show', [ return redirect()->route('environments.show', [
'organisation' => $organisation->id, 'organisation' => $organisation->id,
@@ -26,4 +37,19 @@ class EnvironmentDeploymentController extends Controller
'environment' => $environment->id, 'environment' => $environment->id,
]); ]);
} }
/**
* @return \Illuminate\Support\Collection<int, int>
*/
private function serverIdsFor(Environment $environment): Collection
{
return $environment->services
->flatMap(fn ($service) => [
$service->server_id,
...$service->replicas->pluck('server_id')->all(),
])
->filter()
->unique()
->values();
}
} }

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Http\Controllers;
use App\Models\Organisation;
use Inertia\Response;
class EnvironmentIndexController extends Controller
{
public function __invoke(Organisation $organisation): Response
{
$applications = $organisation->applications()
->with([
'environments' => fn ($query) => $query
->withCount(['services', 'attachments', 'variables', 'buildArtifacts'])
->latest(),
])
->get();
return inertia('environments/Index', [
'applications' => $applications,
]);
}
}

View File

@@ -3,7 +3,9 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Enums\EnvironmentVariableSource; use App\Enums\EnvironmentVariableSource;
use App\Http\Requests\ImportEnvironmentVariablesRequest;
use App\Http\Requests\StoreEnvironmentVariableRequest; use App\Http\Requests\StoreEnvironmentVariableRequest;
use App\Http\Requests\UpdateEnvironmentVariableRequest;
use App\Models\Organisation; use App\Models\Organisation;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -11,6 +13,22 @@ use Inertia\Response;
class EnvironmentVariableController extends Controller class EnvironmentVariableController extends Controller
{ {
public function index(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
return inertia('environment-variables/Index', [
'application' => $application,
'environment' => $environment,
'variables' => $environment->variables()
->with('serviceSlice')
->orderBy('key')
->get(),
]);
}
public function create(Request $request): Response public function create(Request $request): Response
{ {
$organisation = Organisation::findOrFail($request->route('organisation')); $organisation = Organisation::findOrFail($request->route('organisation'));
@@ -35,11 +53,136 @@ class EnvironmentVariableController extends Controller
'value' => $request->string('value')->toString(), 'value' => $request->string('value')->toString(),
'source' => EnvironmentVariableSource::USER, 'source' => EnvironmentVariableSource::USER,
'service_slice_id' => null, 'service_slice_id' => null,
'overridable' => true, 'overridable' => $request->boolean('overridable', true),
]); ]);
return redirect() return redirect()
->route('applications.show', ['organisation' => $organisation->id, 'application' => $application->id]) ->route('environments.show', [
'organisation' => $organisation->id,
'application' => $application->id,
'environment' => $environment->id,
])
->with('success', 'Environment variable saved.'); ->with('success', 'Environment variable saved.');
} }
public function import(ImportEnvironmentVariablesRequest $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
$count = 0;
foreach ($this->parseDotEnv($request->string('contents')->toString()) as $key => $value) {
$environment->variables()->updateOrCreate([
'key' => $key,
], [
'value' => $value,
'source' => EnvironmentVariableSource::USER,
'service_slice_id' => null,
'overridable' => $request->boolean('overridable', true),
]);
$count++;
}
return redirect()
->route('environment-variables.index', [
'organisation' => $organisation->id,
'application' => $application->id,
'environment' => $environment->id,
])
->with('success', "{$count} environment variables imported.");
}
public function edit(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
$variable = $environment->variables()->with('serviceSlice')->findOrFail($request->route('variable'));
return inertia('environment-variables/Edit', [
'application' => $application,
'environment' => $environment,
'variable' => $variable,
]);
}
public function update(UpdateEnvironmentVariableRequest $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
$variable = $environment->variables()->findOrFail($request->route('variable'));
$variable->update([
'key' => $request->string('key')->toString(),
'value' => $request->string('value')->toString(),
'overridable' => $request->boolean('overridable'),
]);
return redirect()
->route('environment-variables.index', [
'organisation' => $organisation->id,
'application' => $application->id,
'environment' => $environment->id,
])
->with('success', 'Environment variable updated.');
}
public function destroy(Request $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
$variable = $environment->variables()->findOrFail($request->route('variable'));
$variable->delete();
return redirect()
->route('environment-variables.index', [
'organisation' => $organisation->id,
'application' => $application->id,
'environment' => $environment->id,
])
->with('success', 'Environment variable deleted.');
}
/**
* @return array<string, string>
*/
private function parseDotEnv(string $contents): array
{
return collect(preg_split('/\R/', $contents) ?: [])
->map(fn (string $line): string => trim($line))
->reject(fn (string $line): bool => $line === '' || str_starts_with($line, '#'))
->mapWithKeys(function (string $line): array {
if (str_starts_with($line, 'export ')) {
$line = trim(substr($line, 7));
}
[$key, $value] = array_pad(explode('=', $line, 2), 2, '');
$key = trim($key);
if (! preg_match('/^[A-Z][A-Z0-9_]*$/', $key)) {
return [];
}
return [$key => $this->unquoteDotEnvValue(trim($value))];
})
->all();
}
private function unquoteDotEnvValue(string $value): string
{
if (str_starts_with($value, '"') && str_ends_with($value, '"')) {
return stripcslashes(substr($value, 1, -1));
}
if (str_starts_with($value, "'") && str_ends_with($value, "'")) {
return substr($value, 1, -1);
}
return $value;
}
} }

View File

@@ -0,0 +1,162 @@
<?php
namespace App\Http\Controllers;
use App\Actions\Environments\AttachManagedService;
use App\Enums\EnvironmentAttachmentRole;
use App\Enums\ServiceType;
use App\Http\Requests\StoreGatewayRouteRequest;
use App\Http\Requests\UpdateGatewayRouteRequest;
use App\Models\EnvironmentAttachment;
use App\Models\Organisation;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Response;
class GatewayRouteController extends Controller
{
public function index(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()
->with(['attachments.service', 'attachments.serviceSlice'])
->findOrFail($request->route('environment'));
return inertia('gateway-routes/Index', [
'application' => $application,
'environment' => $environment,
'routes' => $environment->attachments
->filter(fn (EnvironmentAttachment $attachment): bool => $attachment->role === EnvironmentAttachmentRole::GATEWAY)
->values(),
]);
}
public function create(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
return inertia('gateway-routes/Create', [
'application' => $application,
'environment' => $environment,
'services' => $organisation->services()
->where('type', ServiceType::CADDY->value)
->orderBy('name')
->get(['id', 'name', 'type', 'category']),
]);
}
public function store(StoreGatewayRouteRequest $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
$service = $organisation->services()
->where('type', ServiceType::CADDY->value)
->findOrFail($request->integer('service_id'));
$attachment = app(AttachManagedService::class)->execute(
environment: $environment,
service: $service,
role: EnvironmentAttachmentRole::GATEWAY,
name: $request->string('name')->toString(),
isPrimary: true,
);
$attachment->serviceSlice?->update([
'config' => [
...($attachment->serviceSlice->config ?? []),
...$this->routeConfig($request),
'certificate_status' => $request->boolean('tls_enabled', true) ? 'pending' : 'disabled',
],
]);
return redirect()
->route('gateway.routes.index', [
'organisation' => $organisation->id,
'application' => $application->id,
'environment' => $environment->id,
])
->with('success', 'Gateway route created.');
}
public function edit(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
$route = $environment->attachments()
->with(['service', 'serviceSlice'])
->where('role', EnvironmentAttachmentRole::GATEWAY->value)
->findOrFail($request->route('route'));
return inertia('gateway-routes/Edit', [
'application' => $application,
'environment' => $environment,
'routeAttachment' => $route,
]);
}
public function update(UpdateGatewayRouteRequest $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
$route = $environment->attachments()
->with('serviceSlice')
->where('role', EnvironmentAttachmentRole::GATEWAY->value)
->findOrFail($request->route('route'));
$route->serviceSlice?->update([
'config' => [
...($route->serviceSlice->config ?? []),
...$this->routeConfig($request),
'certificate_status' => $request->filled('certificate_status')
? $request->string('certificate_status')->toString()
: ($request->boolean('tls_enabled', true) ? 'pending' : 'disabled'),
],
]);
return redirect()
->route('gateway.routes.index', [
'organisation' => $organisation->id,
'application' => $application->id,
'environment' => $environment->id,
])
->with('success', 'Gateway route updated.');
}
public function destroy(Request $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
$route = $environment->attachments()
->where('role', EnvironmentAttachmentRole::GATEWAY->value)
->findOrFail($request->route('route'));
$route->delete();
return redirect()
->route('gateway.routes.index', [
'organisation' => $organisation->id,
'application' => $application->id,
'environment' => $environment->id,
])
->with('success', 'Gateway route removed.');
}
/**
* @return array{domain: string, path_prefix: string, tls_enabled: bool}
*/
private function routeConfig(StoreGatewayRouteRequest|UpdateGatewayRouteRequest $request): array
{
return [
'domain' => $request->string('domain')->toString(),
'path_prefix' => $request->string('path_prefix')->toString(),
'tls_enabled' => $request->boolean('tls_enabled', true),
];
}
}

View File

@@ -11,6 +11,10 @@ class OnboardingController extends Controller
{ {
$organisation->loadCount(['providers', 'sourceProviders', 'registries', 'servers', 'applications']); $organisation->loadCount(['providers', 'sourceProviders', 'registries', 'servers', 'applications']);
$applicationNeedingDeployKey = $organisation->applications()
->whereNull('deploy_key_installed_at')
->first();
$steps = [ $steps = [
[ [
'key' => 'organisation', 'key' => 'organisation',
@@ -48,6 +52,17 @@ class OnboardingController extends Controller
'complete' => $organisation->applications_count > 0, 'complete' => $organisation->applications_count > 0,
'href' => route('applications.create', ['organisation' => $organisation->id]), 'href' => route('applications.create', ['organisation' => $organisation->id]),
], ],
[
'key' => 'deploy-key',
'label' => 'Deploy key',
'complete' => $organisation->applications_count === 0 || $applicationNeedingDeployKey === null,
'href' => $applicationNeedingDeployKey
? route('applications.show', [
'organisation' => $organisation->id,
'application' => $applicationNeedingDeployKey->id,
])
: route('applications.index', ['organisation' => $organisation->id]),
],
]; ];
$next = collect($steps)->firstWhere('complete', false) ?? $steps[array_key_last($steps)]; $next = collect($steps)->firstWhere('complete', false) ?? $steps[array_key_last($steps)];

View File

@@ -0,0 +1,171 @@
<?php
namespace App\Http\Controllers;
use App\Enums\OperationKind;
use App\Enums\OperationStatus;
use App\Models\Application;
use App\Models\Environment;
use App\Models\Operation;
use App\Models\Organisation;
use App\Models\Server;
use App\Models\Service;
use App\Models\ServiceReplica;
use App\Models\ServiceSlice;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
class OperationController extends Controller
{
public function index(Request $request, Organisation $organisation): Response
{
$applicationIds = $organisation->applications()->pluck('id');
$environmentIds = Environment::query()
->whereIn('application_id', $applicationIds)
->pluck('id');
$serverIds = $organisation->servers()->pluck('id');
$serviceIds = $organisation->services()->pluck('id');
$replicaIds = ServiceReplica::query()
->whereIn('service_id', $serviceIds)
->pluck('id');
$sliceIds = ServiceSlice::query()
->whereIn('service_id', $serviceIds)
->pluck('id');
$operations = Operation::query()
->with(['target', 'parent', 'children.target'])
->withCount('steps', 'children')
->where(function (Builder $query) use ($applicationIds, $environmentIds, $serverIds, $serviceIds, $replicaIds, $sliceIds): void {
$query
->where(function (Builder $query) use ($applicationIds): void {
$query->where('target_type', (new Application)->getMorphClass())
->whereIn('target_id', $applicationIds);
})
->orWhere(function (Builder $query) use ($environmentIds): void {
$query->where('target_type', (new Environment)->getMorphClass())
->whereIn('target_id', $environmentIds);
})
->orWhere(function (Builder $query) use ($serverIds): void {
$query->where('target_type', (new Server)->getMorphClass())
->whereIn('target_id', $serverIds);
})
->orWhere(function (Builder $query) use ($serviceIds): void {
$query->where('target_type', (new Service)->getMorphClass())
->whereIn('target_id', $serviceIds);
})
->orWhere(function (Builder $query) use ($replicaIds): void {
$query->where('target_type', (new ServiceReplica)->getMorphClass())
->whereIn('target_id', $replicaIds);
})
->orWhere(function (Builder $query) use ($sliceIds): void {
$query->where('target_type', (new ServiceSlice)->getMorphClass())
->whereIn('target_id', $sliceIds);
});
})
->when($request->filled('kind'), fn (Builder $query) => $query->where('kind', $request->string('kind')->toString()))
->when($request->filled('status'), fn (Builder $query) => $query->where('status', $request->string('status')->toString()))
->latest()
->paginate(30)
->withQueryString();
return inertia('operations/Index', [
'operations' => $operations,
'filters' => $request->only(['kind', 'status']),
'operationKinds' => OperationKind::toArray(),
'operationStatuses' => OperationStatus::toArray(),
]);
}
public function show(Organisation $organisation, Operation $operation): Response
{
abort_unless($this->operationBelongsToOrganisation($operation, $organisation), 404);
$operation->load([
'target',
'parent.target',
'children.target',
'children.steps',
'steps',
]);
return inertia('operations/Show', [
'operation' => $operation,
]);
}
public function retry(Organisation $organisation, Operation $operation): RedirectResponse
{
abort_unless($this->operationBelongsToOrganisation($operation, $organisation), 404);
$operation->update([
'status' => OperationStatus::PENDING,
'started_at' => null,
'finished_at' => null,
]);
return redirect()
->route('operations.show', [
'organisation' => $organisation->id,
'operation' => $operation->id,
])
->with('success', 'Operation queued to run again.');
}
public function cancel(Organisation $organisation, Operation $operation): RedirectResponse
{
abort_unless($this->operationBelongsToOrganisation($operation, $organisation), 404);
$operation->update([
'status' => OperationStatus::CANCELLED,
'finished_at' => now(),
]);
return redirect()
->route('operations.show', [
'organisation' => $organisation->id,
'operation' => $operation->id,
])
->with('success', 'Operation cancelled.');
}
public function downloadLogs(Organisation $organisation, Operation $operation): StreamedResponse
{
abort_unless($this->operationBelongsToOrganisation($operation, $organisation), 404);
$operation->load('steps');
return response()->streamDownload(function () use ($operation): void {
foreach ($operation->steps as $step) {
echo "# {$step->name}\n\n";
if ($step->logs) {
echo "## Logs\n{$step->logs}\n\n";
}
if ($step->error_logs) {
echo "## Error Logs\n{$step->error_logs}\n\n";
}
}
}, "operation-{$operation->hash}.log", [
'Content-Type' => 'text/plain',
]);
}
private function operationBelongsToOrganisation(Operation $operation, Organisation $organisation): bool
{
$target = $operation->target;
return match (true) {
$target instanceof Application => $target->organisation_id === $organisation->id,
$target instanceof Environment => $target->application()->where('organisation_id', $organisation->id)->exists(),
$target instanceof Server => $target->organisation_id === $organisation->id,
$target instanceof Service => $target->organisation_id === $organisation->id,
$target instanceof ServiceReplica => $target->service()->where('organisation_id', $organisation->id)->exists(),
$target instanceof ServiceSlice => $target->service()->where('organisation_id', $organisation->id)->exists(),
default => false,
};
}
}

View File

@@ -2,8 +2,11 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Enums\ServiceStatus;
use App\Models\Operation;
use App\Models\Organisation; use App\Models\Organisation;
use App\Models\Provider; use App\Models\Provider;
use App\Models\Service;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Inertia\Inertia; use Inertia\Inertia;
@@ -15,7 +18,23 @@ class OrganisationController extends Controller
'providers' => Inertia::lazy(fn () => Provider::whereOrganisationId($request->route('organisation'))->get()), 'providers' => Inertia::lazy(fn () => Provider::whereOrganisationId($request->route('organisation'))->get()),
'registries' => Inertia::lazy(fn () => Organisation::findOrFail($request->route('organisation'))->registries()->get()), 'registries' => Inertia::lazy(fn () => Organisation::findOrFail($request->route('organisation'))->registries()->get()),
'sourceProviders' => Inertia::lazy(fn () => Organisation::findOrFail($request->route('organisation'))->sourceProviders()->get()), 'sourceProviders' => Inertia::lazy(fn () => Organisation::findOrFail($request->route('organisation'))->sourceProviders()->get()),
'organisation' => Organisation::withCount('servers', 'applications', 'members')->findOrFail($request->route('organisation')), 'organisation' => Organisation::with('members')
->withCount('servers', 'applications', 'members', 'providers', 'sourceProviders', 'registries')
->findOrFail($request->route('organisation')),
'health' => [
'unhealthy_services' => Service::query()
->where('organisation_id', $request->route('organisation'))
->whereNot('status', ServiceStatus::RUNNING)
->count(),
'failed_operations' => Operation::query()
->whereHasMorph('target', [Service::class], fn ($query) => $query->where('organisation_id', $request->route('organisation')))
->where('status', 'failed')
->count(),
'locked_variables' => Organisation::findOrFail($request->route('organisation'))
->applications()
->whereHas('environments.variables', fn ($query) => $query->where('overridable', false))
->count(),
],
]); ]);
} }
} }

View File

@@ -0,0 +1,120 @@
<?php
namespace App\Http\Controllers;
use App\Enums\OrganisationRole;
use App\Http\Requests\StoreOrganisationMemberRequest;
use App\Http\Requests\UpdateOrganisationInvitationRequest;
use App\Http\Requests\UpdateOrganisationMemberRequest;
use App\Models\Organisation;
use App\Models\OrganisationInvitation;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Inertia\Response;
class OrganisationMemberController extends Controller
{
public function index(Organisation $organisation): Response
{
return inertia('organisation-members/Index', [
'organisation' => $organisation->load(['members', 'invitations.invitedBy']),
'roles' => array_values(OrganisationRole::toArray()),
]);
}
public function store(StoreOrganisationMemberRequest $request, Organisation $organisation): RedirectResponse
{
$email = Str::lower($request->string('email')->toString());
$user = User::query()
->where('email', $email)
->first();
if ($user === null) {
abort_if(
$organisation->invitations()->where('email', $email)->whereNull('accepted_at')->exists(),
422,
'This email already has a pending invitation.'
);
$organisation->invitations()->create([
'email' => $email,
'role' => $request->enum('role', OrganisationRole::class),
'token' => Str::random(40),
'invited_by_user_id' => $request->user()?->id,
'expires_at' => now()->addDays(14),
]);
return redirect()
->route('organisation-members.index', ['organisation' => $organisation->id])
->with('success', 'Invitation created.');
}
$organisation->members()->syncWithoutDetaching([
$user->id => ['role' => $request->enum('role', OrganisationRole::class)],
]);
$organisation->invitations()
->where('email', $email)
->delete();
return redirect()
->route('organisation-members.index', ['organisation' => $organisation->id])
->with('success', 'Member added.');
}
public function update(UpdateOrganisationMemberRequest $request, Organisation $organisation, User $member): RedirectResponse
{
abort_unless($organisation->members()->whereKey($member->id)->exists(), 404);
$organisation->members()->updateExistingPivot($member->id, [
'role' => $request->enum('role', OrganisationRole::class),
]);
return redirect()
->route('organisation-members.index', ['organisation' => $organisation->id])
->with('success', 'Member role updated.');
}
public function updateInvitation(
UpdateOrganisationInvitationRequest $request,
Organisation $organisation,
OrganisationInvitation $invitation
): RedirectResponse {
abort_unless($invitation->organisation_id === $organisation->id, 404);
$invitation->update([
'role' => $request->enum('role', OrganisationRole::class),
]);
return redirect()
->route('organisation-members.index', ['organisation' => $organisation->id])
->with('success', 'Invitation role updated.');
}
public function destroy(Request $request, Organisation $organisation, User $member): RedirectResponse
{
abort_if($organisation->owner_id === $member->id, 422, 'The organisation owner cannot be removed.');
$organisation->members()->detach($member->id);
return redirect()
->route('organisation-members.index', ['organisation' => $organisation->id])
->with('success', 'Member removed.');
}
public function destroyInvitation(
Request $request,
Organisation $organisation,
OrganisationInvitation $invitation
): RedirectResponse {
abort_unless($invitation->organisation_id === $organisation->id, 404);
$invitation->delete();
return redirect()
->route('organisation-members.index', ['organisation' => $organisation->id])
->with('success', 'Invitation cancelled.');
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace App\Http\Controllers;
use App\Enums\ProviderType;
use App\Http\Requests\StoreProviderRequest;
use App\Models\Organisation;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Response;
class ProviderController extends Controller
{
public function create(Request $request): Response
{
Organisation::findOrFail($request->route('organisation'));
return inertia('providers/Create', [
'providerTypes' => array_values(ProviderType::toArray()),
]);
}
public function store(StoreProviderRequest $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$organisation->providers()->create([
'name' => $request->string('name')->toString(),
'type' => $request->enum('type', ProviderType::class),
'token' => $request->string('token')->toString(),
]);
return redirect()
->route('organisations.show', ['organisation' => $organisation->id])
->with('success', 'Server provider created.');
}
public function destroy(Request $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$provider = $organisation->providers()->findOrFail($request->route('provider'));
$provider->delete();
return redirect()
->route('organisations.show', ['organisation' => $organisation->id])
->with('success', 'Server provider deleted.');
}
}

View File

@@ -4,13 +4,27 @@ namespace App\Http\Controllers;
use App\Enums\RegistryType; use App\Enums\RegistryType;
use App\Http\Requests\StoreRegistryRequest; use App\Http\Requests\StoreRegistryRequest;
use App\Http\Requests\UpdateRegistryRequest;
use App\Models\BuildArtifact;
use App\Models\Organisation; use App\Models\Organisation;
use App\Models\Registry;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Inertia\Response; use Inertia\Response;
class RegistryController extends Controller class RegistryController extends Controller
{ {
public function index(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
return inertia('registries/Index', [
'registries' => $organisation->registries()
->latest()
->get(),
]);
}
public function create(Request $request): Response public function create(Request $request): Response
{ {
Organisation::findOrFail($request->route('organisation')); Organisation::findOrFail($request->route('organisation'));
@@ -38,4 +52,75 @@ class RegistryController extends Controller
->route('organisations.show', ['organisation' => $organisation->id]) ->route('organisations.show', ['organisation' => $organisation->id])
->with('success', 'Registry created.'); ->with('success', 'Registry created.');
} }
public function show(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
/** @var Registry $registry */
$registry = $organisation->registries()->findOrFail($request->route('registry'));
$registryUrl = rtrim((string) $registry->url, '/');
$artifacts = BuildArtifact::query()
->with(['environment.application', 'builtByService'])
->whereHas('environment.application', fn ($query) => $query->where('organisation_id', $organisation->id))
->when($registryUrl !== '', fn ($query) => $query->where('registry_ref', 'like', $registryUrl.'%'));
return inertia('registries/Show', [
'registry' => $registry,
'artifactCount' => (clone $artifacts)->count(),
'environmentCount' => (clone $artifacts)->distinct('environment_id')->count('environment_id'),
'artifacts' => $artifacts
->latest()
->paginate(20),
]);
}
public function edit(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$registry = $organisation->registries()->findOrFail($request->route('registry'));
return inertia('registries/Edit', [
'registry' => $registry,
'registryTypes' => array_values(RegistryType::toArray()),
]);
}
public function update(UpdateRegistryRequest $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
/** @var Registry $registry */
$registry = $organisation->registries()->findOrFail($request->route('registry'));
$credentials = $registry->credentials ?? [];
$username = $request->string('username')->toString();
if ($request->filled('password')) {
$credentials['password'] = $request->string('password')->toString();
}
$credentials['username'] = $username;
$registry->update([
'name' => $request->string('name')->toString(),
'type' => $request->enum('type', RegistryType::class),
'url' => rtrim($request->string('url')->toString(), '/'),
'credentials' => $credentials,
]);
return redirect()
->route('organisations.show', ['organisation' => $organisation->id])
->with('success', 'Registry updated.');
}
public function destroy(Request $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$registry = $organisation->registries()->findOrFail($request->route('registry'));
$registry->delete();
return redirect()
->route('organisations.show', ['organisation' => $organisation->id])
->with('success', 'Registry deleted.');
}
} }

View File

@@ -3,26 +3,33 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Actions\GenerateRandomSlug; use App\Actions\GenerateRandomSlug;
use App\Enums\OperationKind;
use App\Enums\OperationStatus;
use App\Enums\ServerStatus; use App\Enums\ServerStatus;
use App\Jobs\Servers\WaitForServerToConnect; use App\Jobs\Servers\WaitForServerToConnect;
use App\Models\Organisation; use App\Models\Organisation;
use App\Models\Provider; use App\Models\Provider;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Inertia\Response;
class ServerController extends Controller class ServerController extends Controller
{ {
public function index(Request $request) public function index(Request $request): Response
{ {
$organisation = Organisation::findOrFail($request->route('organisation')); $organisation = Organisation::findOrFail($request->route('organisation'));
return inertia('servers/Index', [ return inertia('servers/Index', [
'servers' => $organisation->servers()->paginate(30), 'servers' => $organisation->servers()->paginate(30),
'networks' => $organisation->networks()
->with(['servers' => fn ($query) => $query->select('id', 'network_id', 'name', 'private_ip', 'status')])
->get(),
]); ]);
} }
public function create(Request $request) public function create(Request $request): Response
{ {
$organisation = Organisation::findOrFail($request->route('organisation')); $organisation = Organisation::findOrFail($request->route('organisation'));
@@ -55,7 +62,7 @@ class ServerController extends Controller
]); ]);
} }
public function store(Request $request) public function store(Request $request): RedirectResponse
{ {
$request->validate([ $request->validate([
'provider' => ['required', 'exists:providers,id'], 'provider' => ['required', 'exists:providers,id'],
@@ -135,13 +142,63 @@ class ServerController extends Controller
return redirect()->route('servers.show', ['organisation' => $organisation->id, 'server' => $server->id]); return redirect()->route('servers.show', ['organisation' => $organisation->id, 'server' => $server->id]);
} }
public function show(Request $request) public function show(Request $request): Response
{ {
$organisation = Organisation::findOrFail($request->route('organisation')); $organisation = Organisation::findOrFail($request->route('organisation'));
$server = $organisation->servers()->findOrFail($request->route('server')); $server = $organisation->servers()->findOrFail($request->route('server'));
return inertia('servers/Show', [ return inertia('servers/Show', [
'server' => $server->load('services.slices', 'serviceOperations.steps', 'serviceOperations.target'), 'server' => $server->load(
'firewallRules',
'network',
'operations.steps',
'operations.children.target',
'services.slices',
'services.endpoints',
'serviceOperations.steps',
'serviceOperations.children.target',
'serviceOperations.target',
),
]); ]);
} }
public function destroy(Request $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$server = $organisation->servers()->findOrFail($request->route('server'));
$server->delete();
return redirect()
->route('servers.index', ['organisation' => $organisation->id])
->with('success', 'Server deleted.');
}
public function heal(Request $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$server = $organisation->servers()->findOrFail($request->route('server'));
$operation = $server->operations()->create([
'kind' => OperationKind::SERVER_PROVISION,
'status' => OperationStatus::PENDING,
]);
foreach ([
'Check server shell' => 'true',
'Check Docker' => 'docker --version && docker compose version',
'Check Keystone directories' => 'test -d /home/keystone && test -d /home/keystone/services',
] as $order => $script) {
$operation->steps()->create([
'name' => $order,
'order' => $operation->steps()->count() + 1,
'status' => OperationStatus::PENDING,
'script' => $script,
]);
}
return redirect()
->route('servers.show', ['organisation' => $organisation->id, 'server' => $server->id])
->with('success', 'Server heal operation queued.');
}
} }

View File

@@ -0,0 +1,41 @@
<?php
namespace App\Http\Controllers;
use App\Actions\FirewallRules\UninstallFirewallRule;
use App\Http\Requests\StoreServerFirewallRuleRequest;
use App\Models\FirewallRule;
use App\Models\Organisation;
use App\Models\Server;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class ServerFirewallRuleController extends Controller
{
public function store(StoreServerFirewallRuleRequest $request, Organisation $organisation, Server $server): RedirectResponse
{
abort_unless((int) $server->organisation_id === (int) $organisation->id, 404);
$server->firewallRules()->create($request->validated());
return redirect()
->route('servers.show', [$organisation, $server])
->with('success', 'Firewall rule queued for installation.');
}
public function destroy(Request $request, Organisation $organisation, Server $server, FirewallRule $firewallRule, UninstallFirewallRule $uninstallFirewallRule): RedirectResponse
{
abort_unless(
(int) $server->organisation_id === (int) $organisation->id
&& (int) $firewallRule->server_id === (int) $server->id,
404,
);
$uninstallFirewallRule->execute($firewallRule);
$firewallRule->delete();
return redirect()
->route('servers.show', [$organisation, $server])
->with('success', 'Firewall rule removed.');
}
}

View File

@@ -3,10 +3,12 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Actions\Services\CreateService; use App\Actions\Services\CreateService;
use App\Enums\DeployPolicy;
use App\Enums\ServiceCategory; use App\Enums\ServiceCategory;
use App\Enums\ServiceType; use App\Enums\ServiceType;
use App\Http\Requests\StoreServiceRequest; use App\Http\Requests\StoreServiceRequest;
use App\Http\Requests\UpdateServiceRequest; use App\Http\Requests\UpdateServiceRequest;
use App\Models\Organisation;
use App\Models\Server; use App\Models\Server;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -49,7 +51,7 @@ class ServiceController extends Controller
{ {
$server = Server::findOrFail($request->route('server')); $server = Server::findOrFail($request->route('server'));
$service = $server->services() $service = $server->services()
->with(['replicas', 'slices', 'operations.steps', 'environment.application']) ->with(['replicas', 'slices', 'endpoints', 'operations.steps', 'operations.children.target', 'environment.application'])
->findOrFail($request->route('service')); ->findOrFail($request->route('service'));
return inertia('services/Show', [ return inertia('services/Show', [
@@ -58,6 +60,23 @@ class ServiceController extends Controller
]); ]);
} }
public function showForEnvironment(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$application = $organisation->applications()->findOrFail($request->route('application'));
$environment = $application->environments()->findOrFail($request->route('environment'));
$service = $environment->services()
->with(['server', 'replicas', 'slices', 'endpoints', 'operations.steps', 'operations.children.target', 'environment.application'])
->findOrFail($request->route('service'));
return inertia('services/Show', [
'server' => $service->server,
'service' => $service,
'environment' => $environment,
'application' => $application,
]);
}
public function edit(Request $request): Response public function edit(Request $request): Response
{ {
$server = Server::findOrFail($request->route('server')); $server = Server::findOrFail($request->route('server'));
@@ -66,6 +85,7 @@ class ServiceController extends Controller
return inertia('services/Edit', [ return inertia('services/Edit', [
'server' => $server, 'server' => $server,
'service' => $service, 'service' => $service,
'deployPolicies' => array_values(DeployPolicy::toArray()),
]); ]);
} }
@@ -74,7 +94,31 @@ class ServiceController extends Controller
$server = Server::findOrFail($request->route('server')); $server = Server::findOrFail($request->route('server'));
$service = $server->services()->findOrFail($request->route('service')); $service = $server->services()->findOrFail($request->route('service'));
$service->update($request->validated()); $validated = $request->validated();
$service->update([
'name' => $validated['name'],
'desired_replicas' => $validated['desired_replicas'],
'default_cpu_limit' => $validated['default_cpu_limit'] ?? null,
'default_memory_limit_mb' => $validated['default_memory_limit_mb'] ?? null,
'deploy_policy' => $request->enum('deploy_policy', DeployPolicy::class) ?? $service->deploy_policy,
'version_track' => $validated['version_track'] ?? $service->version_track,
'available_image_digest' => $validated['available_image_digest'] ?? null,
'process_roles' => collect(explode(',', $validated['process_roles'] ?? ''))
->map(fn (string $role): string => trim($role))
->filter()
->values()
->all(),
'config' => [
...($service->config ?? []),
'migration_mode' => $validated['migration_mode'] ?? null,
'migration_timing' => $validated['migration_timing'] ?? null,
'migration_command' => $validated['migration_command'] ?? null,
'health_path' => $validated['health_path'] ?? null,
'backup_enabled' => $request->boolean('backup_enabled'),
'backup_command' => $validated['backup_command'] ?? null,
],
]);
return redirect() return redirect()
->route('services.show', [ ->route('services.show', [
@@ -84,4 +128,19 @@ class ServiceController extends Controller
]) ])
->with('success', 'Service updated.'); ->with('success', 'Service updated.');
} }
public function destroy(Request $request): RedirectResponse
{
$server = Server::findOrFail($request->route('server'));
$service = $server->services()->findOrFail($request->route('service'));
$service->delete();
return redirect()
->route('servers.show', [
'organisation' => $server->organisation_id,
'server' => $server->id,
])
->with('success', 'Service deleted.');
}
} }

View File

@@ -0,0 +1,102 @@
<?php
namespace App\Http\Controllers;
use App\Enums\OperationKind;
use App\Enums\OperationStatus;
use App\Models\Organisation;
use App\Models\ServiceReplica;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Response;
class ServiceReplicaController extends Controller
{
public function show(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$server = $organisation->servers()->findOrFail($request->route('server'));
$service = $server->services()->with('environment.application')->findOrFail($request->route('service'));
$replica = $service->replicas()
->with(['server', 'operation.steps', 'operations.steps', 'operations.children.target'])
->findOrFail($request->route('replica'));
return inertia('service-replicas/Show', [
'server' => $server,
'service' => $service,
'replica' => $replica,
]);
}
public function restart(Request $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$server = $organisation->servers()->findOrFail($request->route('server'));
$service = $server->services()->findOrFail($request->route('service'));
$replica = $service->replicas()->findOrFail($request->route('replica'));
$this->queueLifecycleOperation($replica, 'Restart replica', "docker restart {$replica->container_name}");
return redirect()
->route('service-replicas.show', [
'organisation' => $organisation->id,
'server' => $server->id,
'service' => $service->id,
'replica' => $replica->id,
])
->with('success', 'Replica restart queued.');
}
public function start(Request $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$server = $organisation->servers()->findOrFail($request->route('server'));
$service = $server->services()->findOrFail($request->route('service'));
$replica = $service->replicas()->findOrFail($request->route('replica'));
$this->queueLifecycleOperation($replica, 'Start replica', "docker start {$replica->container_name}");
return redirect()
->route('service-replicas.show', [
'organisation' => $organisation->id,
'server' => $server->id,
'service' => $service->id,
'replica' => $replica->id,
])
->with('success', 'Replica start queued.');
}
public function stop(Request $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$server = $organisation->servers()->findOrFail($request->route('server'));
$service = $server->services()->findOrFail($request->route('service'));
$replica = $service->replicas()->findOrFail($request->route('replica'));
$this->queueLifecycleOperation($replica, 'Stop replica', "docker stop {$replica->container_name}");
return redirect()
->route('service-replicas.show', [
'organisation' => $organisation->id,
'server' => $server->id,
'service' => $service->id,
'replica' => $replica->id,
])
->with('success', 'Replica stop queued.');
}
private function queueLifecycleOperation(ServiceReplica $replica, string $name, string $script): void
{
$operation = $replica->operations()->create([
'kind' => OperationKind::REPLICA_DEPLOY,
'status' => OperationStatus::PENDING,
]);
$operation->steps()->create([
'name' => $name,
'order' => 1,
'status' => OperationStatus::PENDING,
'script' => $script,
]);
}
}

View File

@@ -0,0 +1,104 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreServiceSliceRequest;
use App\Models\Organisation;
use App\Models\ServiceSlice;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Response;
class ServiceSliceController extends Controller
{
public function index(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$server = $organisation->servers()->findOrFail($request->route('server'));
$service = $server->services()
->with('environment.application')
->findOrFail($request->route('service'));
return inertia('service-slices/Index', [
'server' => $server,
'service' => $service,
'slices' => $service->slices()
->with(['environment.application', 'attachments', 'operations.steps', 'operations.children.target'])
->latest()
->get(),
]);
}
public function show(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$server = $organisation->servers()->findOrFail($request->route('server'));
$service = $server->services()->with('environment.application')->findOrFail($request->route('service'));
$slice = $service->slices()
->with(['environment.application', 'attachments.environment.application', 'operations.steps', 'operations.children.target'])
->findOrFail($request->route('slice'));
return inertia('service-slices/Show', [
'server' => $server,
'service' => $service,
'slice' => $slice,
]);
}
public function create(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$server = $organisation->servers()->findOrFail($request->route('server'));
$service = $server->services()->findOrFail($request->route('service'));
return inertia('service-slices/Create', [
'server' => $server,
'service' => $service,
'environments' => $organisation->applications()
->with('environments')
->get()
->pluck('environments')
->flatten()
->values(),
]);
}
public function store(StoreServiceSliceRequest $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$server = $organisation->servers()->findOrFail($request->route('server'));
$service = $server->services()->findOrFail($request->route('service'));
$environmentId = $request->integer('environment_id') ?: null;
if ($environmentId !== null) {
$belongsToOrganisation = $organisation->applications()
->whereHas('environments', fn ($query) => $query->whereKey($environmentId))
->exists();
abort_unless($belongsToOrganisation, 422);
}
$config = $request->filled('config')
? json_decode($request->string('config')->toString(), true, flags: JSON_THROW_ON_ERROR)
: [];
/** @var ServiceSlice $slice */
$slice = $service->slices()->create([
'environment_id' => $environmentId,
'name' => $request->string('name')->toString(),
'type' => $request->string('type')->toString(),
'status' => $request->string('status')->toString(),
'config' => $config,
'credentials' => [],
]);
return redirect()
->route('service-slices.show', [
'organisation' => $organisation->id,
'server' => $server->id,
'service' => $service->id,
'slice' => $slice->id,
])
->with('success', 'Slice created.');
}
}

View File

@@ -3,6 +3,7 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Actions\Services\CreateStatefulServiceUpdateOperation; use App\Actions\Services\CreateStatefulServiceUpdateOperation;
use App\Actions\Services\ResolveServiceImageDigest;
use App\Enums\ServiceType; use App\Enums\ServiceType;
use App\Http\Requests\StoreServiceUpdateRequest; use App\Http\Requests\StoreServiceUpdateRequest;
use App\Models\Organisation; use App\Models\Organisation;
@@ -33,6 +34,7 @@ class ServiceUpdateController extends Controller
CreateStatefulServiceUpdateOperation $createStatefulServiceUpdateOperation, CreateStatefulServiceUpdateOperation $createStatefulServiceUpdateOperation,
): RedirectResponse { ): RedirectResponse {
abort_unless((int) $server->organisation_id === (int) $organisation->id && (int) $service->server_id === (int) $server->id, 404); abort_unless((int) $server->organisation_id === (int) $organisation->id && (int) $service->server_id === (int) $server->id, 404);
abort_unless($request->string('confirmation')->toString() === $service->name, 422);
$createStatefulServiceUpdateOperation->execute( $createStatefulServiceUpdateOperation->execute(
service: $service, service: $service,
@@ -45,4 +47,26 @@ class ServiceUpdateController extends Controller
'server' => $server->id, 'server' => $server->id,
]); ]);
} }
public function resolve(
Organisation $organisation,
Server $server,
Service $service,
ResolveServiceImageDigest $resolveServiceImageDigest,
): RedirectResponse {
abort_unless((int) $server->organisation_id === (int) $organisation->id && (int) $service->server_id === (int) $server->id, 404);
abort_unless(in_array($service->type, [ServiceType::POSTGRES, ServiceType::VALKEY], true), 404);
$service->update([
'available_image_digest' => $resolveServiceImageDigest->execute($service),
]);
return redirect()
->route('service-updates.create', [
'organisation' => $organisation->id,
'server' => $server->id,
'service' => $service->id,
])
->with('success', 'Latest image digest resolved.');
}
} }

View File

@@ -4,13 +4,26 @@ namespace App\Http\Controllers;
use App\Enums\SourceProviderType; use App\Enums\SourceProviderType;
use App\Http\Requests\StoreSourceProviderRequest; use App\Http\Requests\StoreSourceProviderRequest;
use App\Http\Requests\UpdateSourceProviderRequest;
use App\Models\Organisation; use App\Models\Organisation;
use App\Models\SourceProvider;
use Illuminate\Http\RedirectResponse; use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Inertia\Response; use Inertia\Response;
class SourceProviderController extends Controller class SourceProviderController extends Controller
{ {
public function index(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
return inertia('source-providers/Index', [
'sourceProviders' => $organisation->sourceProviders()
->latest()
->get(),
]);
}
public function create(Request $request): Response public function create(Request $request): Response
{ {
Organisation::findOrFail($request->route('organisation')); Organisation::findOrFail($request->route('organisation'));
@@ -35,4 +48,44 @@ class SourceProviderController extends Controller
->route('organisations.show', ['organisation' => $organisation->id]) ->route('organisations.show', ['organisation' => $organisation->id])
->with('success', 'Source provider created.'); ->with('success', 'Source provider created.');
} }
public function edit(Request $request): Response
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$sourceProvider = $organisation->sourceProviders()->findOrFail($request->route('source_provider'));
return inertia('source-providers/Edit', [
'sourceProvider' => $sourceProvider,
'sourceProviderTypes' => array_values(SourceProviderType::toArray()),
]);
}
public function update(UpdateSourceProviderRequest $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
/** @var SourceProvider $sourceProvider */
$sourceProvider = $organisation->sourceProviders()->findOrFail($request->route('source_provider'));
$sourceProvider->update([
'name' => $request->string('name')->toString(),
'type' => $request->enum('type', SourceProviderType::class),
'url' => $request->filled('url') ? rtrim($request->string('url')->toString(), '/') : null,
]);
return redirect()
->route('organisations.show', ['organisation' => $organisation->id])
->with('success', 'Source provider updated.');
}
public function destroy(Request $request): RedirectResponse
{
$organisation = Organisation::findOrFail($request->route('organisation'));
$sourceProvider = $organisation->sourceProviders()->findOrFail($request->route('source_provider'));
$sourceProvider->delete();
return redirect()
->route('organisations.show', ['organisation' => $organisation->id])
->with('success', 'Source provider deleted.');
}
} }

View File

@@ -24,17 +24,17 @@ class CreateNetworkRequest extends Request implements HasBody
'name' => $this->name, 'name' => $this->name,
'ip_range' => '10.0.0.0/16', 'ip_range' => '10.0.0.0/16',
]; ];
if ($this->networkZone) { if ($this->networkZone) {
$body['subnets'] = [ $body['subnets'] = [
[ [
'type' => 'cloud', 'type' => 'cloud',
'ip_range' => '10.0.1.0/24', 'ip_range' => '10.0.1.0/24',
'network_zone' => $this->networkZone 'network_zone' => $this->networkZone,
] ],
]; ];
} }
return $body; return $body;
} }

View File

@@ -31,7 +31,9 @@ class HandleInertiaRequests extends Middleware
...parent::share($request), ...parent::share($request),
'name' => config('app.name'), 'name' => config('app.name'),
'organisation' => $request->route('organisation') 'organisation' => $request->route('organisation')
? Organisation::with('applications')->findOrFail($this->routeKey($request->route('organisation'))) ? Organisation::with('applications.environments')
->withCount(['providers', 'sourceProviders', 'registries', 'servers', 'applications'])
->findOrFail($this->routeKey($request->route('organisation')))
: null, : null,
'application' => $request->route('application') 'application' => $request->route('application')
? Application::with('environments')->findOrFail($this->routeKey($request->route('application'))) ? Application::with('environments')->findOrFail($this->routeKey($request->route('application')))

View File

@@ -0,0 +1,29 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ImportEnvironmentVariablesRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'contents' => ['required', 'string', 'max:20000'],
'overridable' => ['sometimes', 'boolean'],
];
}
}

View File

@@ -2,7 +2,9 @@
namespace App\Http\Requests; namespace App\Http\Requests;
use App\Enums\RepositoryType;
use Illuminate\Foundation\Http\FormRequest; use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StoreApplicationRequest extends FormRequest class StoreApplicationRequest extends FormRequest
{ {
@@ -23,6 +25,8 @@ class StoreApplicationRequest extends FormRequest
{ {
return [ return [
'name' => ['required', 'string', 'max:255'], 'name' => ['required', 'string', 'max:255'],
'source_provider_id' => ['nullable', 'integer', 'exists:source_providers,id'],
'repository_type' => ['required', Rule::enum(RepositoryType::class)],
'repository_url' => ['required', 'string', 'max:255', 'regex:/^(git@[^:]+:.+|ssh:\/\/.+)$/i'], 'repository_url' => ['required', 'string', 'max:255', 'regex:/^(git@[^:]+:.+|ssh:\/\/.+)$/i'],
'default_branch' => ['required', 'string', 'max:255', 'regex:/^[A-Za-z0-9._\/-]+$/'], 'default_branch' => ['required', 'string', 'max:255', 'regex:/^[A-Za-z0-9._\/-]+$/'],
'environment_name' => ['required', 'string', 'max:255'], 'environment_name' => ['required', 'string', 'max:255'],

View File

@@ -29,6 +29,9 @@ class StoreEnvironmentAttachmentRequest extends FormRequest
'name' => ['nullable', 'string', 'max:255'], 'name' => ['nullable', 'string', 'max:255'],
'env_prefix' => ['nullable', 'string', 'max:32', 'regex:/^[A-Z][A-Z0-9_]*$/'], 'env_prefix' => ['nullable', 'string', 'max:32', 'regex:/^[A-Z][A-Z0-9_]*$/'],
'is_primary' => ['boolean'], 'is_primary' => ['boolean'],
'domain' => ['nullable', 'string', 'max:255'],
'path_prefix' => ['nullable', 'string', 'max:255'],
'tls_enabled' => ['boolean'],
]; ];
} }
} }

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreEnvironmentDeploymentRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'target_commit' => ['nullable', 'string', 'size:40', 'regex:/^[a-fA-F0-9]{40}$/'],
];
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreEnvironmentRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'branch' => ['required', 'string', 'max:255', 'regex:/^[A-Za-z0-9._\/-]+$/'],
'php_version' => ['required', 'string', 'max:20'],
];
}
}

View File

@@ -24,6 +24,7 @@ class StoreEnvironmentVariableRequest extends FormRequest
return [ return [
'key' => ['required', 'string', 'max:255', 'regex:/^[A-Z][A-Z0-9_]*$/'], 'key' => ['required', 'string', 'max:255', 'regex:/^[A-Z][A-Z0-9_]*$/'],
'value' => ['nullable', 'string'], 'value' => ['nullable', 'string'],
'overridable' => ['boolean'],
]; ];
} }
} }

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreGatewayRouteRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'service_id' => ['required', 'integer', 'exists:services,id'],
'name' => ['required', 'string', 'max:255'],
'domain' => ['required', 'string', 'max:255'],
'path_prefix' => ['required', 'string', 'max:255', 'regex:/^\//'],
'tls_enabled' => ['boolean'],
];
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Http\Requests;
use App\Enums\OrganisationRole;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StoreOrganisationMemberRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'email' => ['required', 'email', 'max:255'],
'role' => ['required', Rule::enum(OrganisationRole::class)],
];
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Http\Requests;
use App\Enums\ProviderType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StoreProviderRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'type' => ['required', Rule::enum(ProviderType::class)],
'token' => ['required', 'string', 'max:2000'],
];
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Http\Requests;
use App\Enums\FirewallRuleType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StoreServerFirewallRuleRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'type' => ['required', Rule::enum(FirewallRuleType::class)],
'ports' => ['required', 'string', 'max:50', 'regex:/^[A-Za-z0-9:\/,-]+$/'],
'from' => ['nullable', 'string', 'max:255', 'regex:/^[A-Fa-f0-9:.\/-]+$/'],
];
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreServiceSliceRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'type' => ['required', 'string', 'max:255'],
'environment_id' => ['nullable', 'integer'],
'status' => ['required', 'string', 'max:255'],
'config' => ['nullable', 'string'],
];
}
}

View File

@@ -21,6 +21,7 @@ class StoreServiceUpdateRequest extends FormRequest
return [ return [
'image_digest' => ['required', 'string', 'starts_with:sha256:'], 'image_digest' => ['required', 'string', 'starts_with:sha256:'],
'backup_requested' => ['sometimes', 'boolean'], 'backup_requested' => ['sometimes', 'boolean'],
'confirmation' => ['required', 'string'],
]; ];
} }
} }

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Http\Requests;
use App\Enums\RepositoryType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateApplicationRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'source_provider_id' => ['nullable', 'integer', 'exists:source_providers,id'],
'repository_type' => ['required', Rule::enum(RepositoryType::class)],
'repository_url' => ['required', 'string', 'max:255', 'regex:/^(git@[^:]+:.+|ssh:\/\/.+)$/i'],
'default_branch' => ['required', 'string', 'max:255', 'regex:/^[A-Za-z0-9._\/-]+$/'],
];
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace App\Http\Requests;
use App\Enums\EnvironmentAttachmentRole;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateEnvironmentAttachmentRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'role' => ['required', Rule::enum(EnvironmentAttachmentRole::class)],
'env_prefix' => ['nullable', 'string', 'max:255', 'regex:/^[A-Z][A-Z0-9_]*$/'],
'is_primary' => ['boolean'],
'domain' => ['nullable', 'string', 'max:255'],
'path_prefix' => ['nullable', 'string', 'max:255'],
'tls_enabled' => ['boolean'],
'certificate_status' => ['nullable', 'string', 'max:255'],
];
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace App\Http\Requests;
use App\Enums\BuildStrategy;
use App\Enums\SchedulerMode;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateEnvironmentRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'branch' => ['required', 'string', 'max:255', 'regex:/^[A-Za-z0-9._\/-]+$/'],
'status' => ['required', 'string', 'max:255'],
'scheduler_enabled' => ['boolean'],
'scheduler_target_service_id' => ['nullable', 'integer'],
'scheduler_mode' => ['required', Rule::enum(SchedulerMode::class)],
'build_strategy' => ['required', Rule::enum(BuildStrategy::class)],
'php_version' => ['nullable', 'string', 'max:20'],
'document_root' => ['nullable', 'string', 'max:255'],
'health_path' => ['nullable', 'string', 'max:255'],
'js_package_manager' => ['nullable', 'string', 'max:50'],
'js_build_command' => ['nullable', 'string', 'max:255'],
];
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdateEnvironmentVariableRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'key' => ['required', 'string', 'max:255', 'regex:/^[A-Z][A-Z0-9_]*$/'],
'value' => ['nullable', 'string'],
'overridable' => ['boolean'],
];
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdateGatewayRouteRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'domain' => ['required', 'string', 'max:255'],
'path_prefix' => ['required', 'string', 'max:255', 'regex:/^\//'],
'tls_enabled' => ['boolean'],
'certificate_status' => ['nullable', 'string', 'max:255'],
];
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests;
use App\Enums\OrganisationRole;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateOrganisationInvitationRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'role' => ['required', Rule::enum(OrganisationRole::class)],
];
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Http\Requests;
use App\Enums\OrganisationRole;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateOrganisationMemberRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'role' => ['required', Rule::enum(OrganisationRole::class)],
];
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Http\Requests;
use App\Enums\RegistryType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateRegistryRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'type' => ['required', Rule::enum(RegistryType::class)],
'url' => ['required', 'string', 'max:255'],
'username' => ['nullable', 'string', 'max:255'],
'password' => ['nullable', 'string', 'max:255'],
];
}
}

View File

@@ -2,7 +2,9 @@
namespace App\Http\Requests; namespace App\Http\Requests;
use App\Enums\DeployPolicy;
use Illuminate\Foundation\Http\FormRequest; use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateServiceRequest extends FormRequest class UpdateServiceRequest extends FormRequest
{ {
@@ -26,6 +28,16 @@ class UpdateServiceRequest extends FormRequest
'desired_replicas' => ['required', 'integer', 'min:0', 'max:25'], 'desired_replicas' => ['required', 'integer', 'min:0', 'max:25'],
'default_cpu_limit' => ['nullable', 'numeric', 'min:0.125', 'max:64'], 'default_cpu_limit' => ['nullable', 'numeric', 'min:0.125', 'max:64'],
'default_memory_limit_mb' => ['nullable', 'integer', 'min:64', 'max:1048576'], 'default_memory_limit_mb' => ['nullable', 'integer', 'min:64', 'max:1048576'],
'deploy_policy' => ['nullable', Rule::enum(DeployPolicy::class)],
'version_track' => ['nullable', 'string', 'max:255'],
'available_image_digest' => ['nullable', 'string', 'max:255'],
'process_roles' => ['nullable', 'string', 'max:255'],
'migration_mode' => ['nullable', 'string', 'max:255'],
'migration_timing' => ['nullable', 'string', 'max:255'],
'migration_command' => ['nullable', 'string', 'max:255'],
'health_path' => ['nullable', 'string', 'max:255'],
'backup_enabled' => ['sometimes', 'boolean'],
'backup_command' => ['nullable', 'string', 'max:1000'],
]; ];
} }
} }

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Http\Requests;
use App\Enums\SourceProviderType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateSourceProviderRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'type' => ['required', Rule::enum(SourceProviderType::class)],
'url' => ['nullable', 'string', 'max:255'],
];
}
}

View File

@@ -18,6 +18,7 @@ use App\Models\Operation;
use App\Models\Service; use App\Models\Service;
use App\Models\ServiceReplica; use App\Models\ServiceReplica;
use App\Services\Compose\ComposeRenderer; use App\Services\Compose\ComposeRenderer;
use App\Support\CaddyRouteRenderer;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable; use Illuminate\Foundation\Queue\Queueable;
use InvalidArgumentException; use InvalidArgumentException;
@@ -29,6 +30,7 @@ class DeployEnvironment implements ShouldQueue
public function __construct( public function __construct(
public Environment $environment, public Environment $environment,
public ?string $targetCommit = null,
) { ) {
// //
} }
@@ -51,7 +53,7 @@ class DeployEnvironment implements ShouldQueue
'started_at' => now(), 'started_at' => now(),
]); ]);
$commitSha = app(ResolveEnvironmentCommit::class)->execute($this->environment); $commitSha = $this->targetCommit ?? app(ResolveEnvironmentCommit::class)->execute($this->environment);
$services = $this->servicesNeedingDeployment($plan->services, $commitSha); $services = $this->servicesNeedingDeployment($plan->services, $commitSha);
if ($services === []) { if ($services === []) {
@@ -378,15 +380,25 @@ class DeployEnvironment implements ShouldQueue
private function gatewayCutoverSteps(EnvironmentAttachment $attachment): array private function gatewayCutoverSteps(EnvironmentAttachment $attachment): array
{ {
$containerName = $attachment->service->replicas()->first()?->container_name; $containerName = $attachment->service->replicas()->first()?->container_name;
$config = $attachment->serviceSlice?->config ?? [];
$domain = $config['domain'] ?? null;
$tlsEnabled = $config['tls_enabled'] ?? true;
$reloadCommand = $containerName $reloadCommand = $containerName
? 'docker exec '.escapeshellarg($containerName).' caddy reload --config /etc/caddy/Caddyfile' ? 'docker exec '.escapeshellarg($containerName).' caddy reload --config /etc/caddy/Caddyfile'
: "docker compose -f /home/keystone/services/{$attachment->service_id}/compose.yml exec -T {$this->serviceKey($attachment->service)} caddy reload --config /etc/caddy/Caddyfile"; : "docker compose -f /home/keystone/services/{$attachment->service_id}/compose.yml exec -T {$this->serviceKey($attachment->service)} caddy reload --config /etc/caddy/Caddyfile";
$certificateCheck = $tlsEnabled && $domain
? 'curl --fail --silent --show-error --head https://'.escapeshellarg($domain).' >/dev/null'
: 'true # TLS disabled or no domain configured for this route';
return [ return [
[ [
'name' => 'Validate Caddy route configuration', 'name' => 'Validate Caddy route configuration',
'script' => 'test -s /home/keystone/gateway/Caddyfile', 'script' => 'test -s /home/keystone/gateway/Caddyfile',
], ],
[
'name' => 'Check TLS certificate status',
'script' => $certificateCheck,
],
[ [
'name' => 'Reload Caddy', 'name' => 'Reload Caddy',
'script' => $reloadCommand, 'script' => $reloadCommand,
@@ -406,15 +418,13 @@ class DeployEnvironment implements ShouldQueue
private function configureCaddyRouteScript(EnvironmentAttachment $attachment): string private function configureCaddyRouteScript(EnvironmentAttachment $attachment): string
{ {
$route = $attachment->serviceSlice?->name ?? $this->environment->name;
$upstreams = $this->gatewayUpstreams($attachment); $upstreams = $this->gatewayUpstreams($attachment);
$caddyfile = app(CaddyRouteRenderer::class)->render($attachment, $upstreams);
return implode("\n", [ return implode("\n", [
'mkdir -p /home/keystone/gateway/Caddyfile.d', 'mkdir -p /home/keystone/gateway/Caddyfile.d',
"cat > /home/keystone/gateway/Caddyfile.d/{$attachment->id}.caddy <<'KEYSTONE_CADDY_ROUTE'", "cat > /home/keystone/gateway/Caddyfile.d/{$attachment->id}.caddy <<'KEYSTONE_CADDY_ROUTE'",
"{$route} {", $caddyfile,
' reverse_proxy '.implode(' ', $upstreams),
'}',
'KEYSTONE_CADDY_ROUTE', 'KEYSTONE_CADDY_ROUTE',
'cat /home/keystone/gateway/Caddyfile.d/*.caddy > /home/keystone/gateway/Caddyfile', 'cat /home/keystone/gateway/Caddyfile.d/*.caddy > /home/keystone/gateway/Caddyfile',
]); ]);

View File

@@ -29,6 +29,11 @@ class Application extends Model
return $this->belongsTo(Organisation::class); return $this->belongsTo(Organisation::class);
} }
public function sourceProvider(): BelongsTo
{
return $this->belongsTo(SourceProvider::class);
}
public function environments(): HasMany public function environments(): HasMany
{ {
return $this->hasMany(Environment::class); return $this->hasMany(Environment::class);

View File

@@ -42,9 +42,9 @@ class FirewallRule extends Model
$command .= ' delete'; $command .= ' delete';
} }
if ($this->type === 'allow') { if ($this->type === FirewallRuleType::ALLOW) {
$command .= ' allow'; $command .= ' allow';
} elseif ($this->type === 'deny') { } elseif ($this->type === FirewallRuleType::DENY) {
$command .= ' deny'; $command .= ' deny';
} }

View File

@@ -30,6 +30,11 @@ class Organisation extends Model
->withTimestamps(); ->withTimestamps();
} }
public function invitations(): HasMany
{
return $this->hasMany(OrganisationInvitation::class);
}
public function servers(): HasMany public function servers(): HasMany
{ {
return $this->hasMany(Server::class); return $this->hasMany(Server::class);

View File

@@ -0,0 +1,35 @@
<?php
namespace App\Models;
use App\Enums\OrganisationRole;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class OrganisationInvitation extends Model
{
/** @use HasFactory<\Database\Factories\OrganisationInvitationFactory> */
use HasFactory;
protected $guarded = [];
protected function casts(): array
{
return [
'role' => OrganisationRole::class,
'accepted_at' => 'datetime',
'expires_at' => 'datetime',
];
}
public function organisation(): BelongsTo
{
return $this->belongsTo(Organisation::class);
}
public function invitedBy(): BelongsTo
{
return $this->belongsTo(User::class, 'invited_by_user_id');
}
}

View File

@@ -8,6 +8,7 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough; use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Spatie\Ssh\Ssh; use Spatie\Ssh\Ssh;
class Server extends Model class Server extends Model
@@ -31,7 +32,7 @@ class Server extends Model
public function network(): BelongsTo public function network(): BelongsTo
{ {
return $this->belongsTo(Network::class, 'network'); return $this->belongsTo(Network::class, 'network_id');
} }
public function organisation(): BelongsTo public function organisation(): BelongsTo
@@ -69,6 +70,11 @@ class Server extends Model
)->where('target_type', (new Service)->getMorphClass()); )->where('target_type', (new Service)->getMorphClass());
} }
public function operations(): MorphMany
{
return $this->morphMany(Operation::class, 'target');
}
public function sshClient(string $user = 'root'): Ssh public function sshClient(string $user = 'root'): Ssh
{ {
return Ssh::create($user, $this->ipv4) return Ssh::create($user, $this->ipv4)

View File

@@ -5,6 +5,7 @@ namespace App\Models;
use App\Enums\SourceProviderType; use App\Enums\SourceProviderType;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class SourceProvider extends Model class SourceProvider extends Model
{ {
@@ -22,4 +23,9 @@ class SourceProvider extends Model
{ {
return $this->belongsTo(Organisation::class); return $this->belongsTo(Organisation::class);
} }
public function applications(): HasMany
{
return $this->hasMany(Application::class);
}
} }

View File

@@ -0,0 +1,38 @@
<?php
namespace App\Support;
use App\Models\EnvironmentAttachment;
class CaddyRouteRenderer
{
/**
* @param array<int, string> $upstreams
*/
public function render(EnvironmentAttachment $attachment, array $upstreams): string
{
$config = $attachment->serviceSlice?->config ?? [];
$domain = $config['domain'] ?? $attachment->serviceSlice?->name ?? $attachment->environment->name;
$pathPrefix = $config['path_prefix'] ?? '/';
$siteAddress = ($config['tls_enabled'] ?? true) ? $domain : "http://{$domain}";
$upstreamTargets = $upstreams === [] ? ['web:80'] : $upstreams;
if ($pathPrefix === '/') {
return implode("\n", [
"{$siteAddress} {",
' reverse_proxy '.implode(' ', $upstreamTargets),
'}',
]);
}
$normalizedPath = rtrim($pathPrefix, '/');
return implode("\n", [
"{$siteAddress} {",
" handle_path {$normalizedPath}* {",
' reverse_proxy '.implode(' ', $upstreamTargets),
' }',
'}',
]);
}
}

View File

@@ -27,7 +27,8 @@ class Ip
} }
if ($maskBits > 0) { if ($maskBits > 0) {
$maskValue = chr(pow(2, $maskBits) - 1); $maskValue = (1 << $maskBits) - 1;
$maskValue <<= (8 - $maskBits);
$subnetByte = ord($subnet[$maskBytes]); $subnetByte = ord($subnet[$maskBytes]);
$ipByte = ord($ip[$maskBytes]); $ipByte = ord($ip[$maskBytes]);

BIN
bun.lockb

Binary file not shown.

View File

@@ -20,11 +20,13 @@
}, },
"require-dev": { "require-dev": {
"fakerphp/faker": "^1.23", "fakerphp/faker": "^1.23",
"larastan/larastan": "^3.0",
"laravel/boost": "^1.1", "laravel/boost": "^1.1",
"laravel/pail": "^1.2.2", "laravel/pail": "^1.2.2",
"laravel/pint": "^1.18", "laravel/pint": "^1.18",
"laravel/sail": "^1.41", "laravel/sail": "^1.41",
"mockery/mockery": "^1.6", "mockery/mockery": "^1.6",
"mrpunyapal/peststan": "^0.2.5",
"nunomaduro/collision": "^8.6", "nunomaduro/collision": "^8.6",
"pestphp/pest": "^3.7", "pestphp/pest": "^3.7",
"pestphp/pest-plugin-laravel": "^3.1" "pestphp/pest-plugin-laravel": "^3.1"
@@ -65,6 +67,14 @@
"npm run build:ssr", "npm run build:ssr",
"Composer\\Config::disableProcessTimeout", "Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"php artisan pail --timeout=0\" \"php artisan inertia:start-ssr\" --names=server,queue,logs,ssr" "npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1\" \"php artisan pail --timeout=0\" \"php artisan inertia:start-ssr\" --names=server,queue,logs,ssr"
],
"phpstan": "vendor/bin/phpstan analyse --memory-limit=1G",
"coverage": [
"XDEBUG_MODE=coverage vendor/bin/pest --coverage --min=95"
],
"quality": [
"composer phpstan",
"composer coverage"
] ]
}, },
"extra": { "extra": {

254
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "69f6de114270a8beb46d9283a2acd24d", "content-hash": "f73763833c370943f03916f4eaa3ce26",
"packages": [ "packages": [
{ {
"name": "brick/math", "name": "brick/math",
@@ -6540,6 +6540,47 @@
}, },
"time": "2020-07-09T08:09:16+00:00" "time": "2020-07-09T08:09:16+00:00"
}, },
{
"name": "iamcal/sql-parser",
"version": "v0.6",
"source": {
"type": "git",
"url": "https://github.com/iamcal/SQLParser.git",
"reference": "947083e2dca211a6f12fb1beb67a01e387de9b62"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/iamcal/SQLParser/zipball/947083e2dca211a6f12fb1beb67a01e387de9b62",
"reference": "947083e2dca211a6f12fb1beb67a01e387de9b62",
"shasum": ""
},
"require-dev": {
"php-coveralls/php-coveralls": "^1.0",
"phpunit/phpunit": "^5|^6|^7|^8|^9"
},
"type": "library",
"autoload": {
"psr-4": {
"iamcal\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Cal Henderson",
"email": "cal@iamcal.com"
}
],
"description": "MySQL schema parser",
"support": {
"issues": "https://github.com/iamcal/SQLParser/issues",
"source": "https://github.com/iamcal/SQLParser/tree/v0.6"
},
"time": "2025-03-17T16:59:46+00:00"
},
{ {
"name": "jean85/pretty-package-versions", "name": "jean85/pretty-package-versions",
"version": "2.1.1", "version": "2.1.1",
@@ -6600,6 +6641,99 @@
}, },
"time": "2025-03-19T14:43:43+00:00" "time": "2025-03-19T14:43:43+00:00"
}, },
{
"name": "larastan/larastan",
"version": "v3.3.0",
"source": {
"type": "git",
"url": "https://github.com/larastan/larastan.git",
"reference": "b032de3918a8bab9ee7f1bb71609842243fd89d9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/larastan/larastan/zipball/b032de3918a8bab9ee7f1bb71609842243fd89d9",
"reference": "b032de3918a8bab9ee7f1bb71609842243fd89d9",
"shasum": ""
},
"require": {
"ext-json": "*",
"iamcal/sql-parser": "^0.6.0",
"illuminate/console": "^11.42.2 || ^12.0",
"illuminate/container": "^11.42.2 || ^12.0",
"illuminate/contracts": "^11.42.2 || ^12.0",
"illuminate/database": "^11.42.2 || ^12.0",
"illuminate/http": "^11.42.2 || ^12.0",
"illuminate/pipeline": "^11.42.2 || ^12.0",
"illuminate/support": "^11.42.2 || ^12.0",
"php": "^8.2",
"phpstan/phpstan": "^2.1.8"
},
"require-dev": {
"doctrine/coding-standard": "^12.0",
"laravel/framework": "^11.42.2 || ^12.0",
"mockery/mockery": "^1.6",
"nikic/php-parser": "^5.3",
"orchestra/canvas": "^v9.1.3 || ^10.0",
"orchestra/testbench-core": "^9.5.2 || ^10.0",
"phpstan/phpstan-deprecation-rules": "^2.0.0",
"phpunit/phpunit": "^10.5.35 || ^11.3.6"
},
"suggest": {
"orchestra/testbench": "Using Larastan for analysing a package needs Testbench"
},
"type": "phpstan-extension",
"extra": {
"phpstan": {
"includes": [
"extension.neon"
]
},
"branch-alias": {
"dev-master": "3.0-dev"
}
},
"autoload": {
"psr-4": {
"Larastan\\Larastan\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Can Vural",
"email": "can9119@gmail.com"
},
{
"name": "Nuno Maduro",
"email": "enunomaduro@gmail.com"
}
],
"description": "Larastan - Discover bugs in your code without running it. A phpstan/phpstan wrapper for Laravel",
"keywords": [
"PHPStan",
"code analyse",
"code analysis",
"larastan",
"laravel",
"package",
"php",
"static analysis"
],
"support": {
"issues": "https://github.com/larastan/larastan/issues",
"source": "https://github.com/larastan/larastan/tree/v3.3.0"
},
"funding": [
{
"url": "https://github.com/canvural",
"type": "github"
}
],
"time": "2025-04-03T19:11:55+00:00"
},
{ {
"name": "laravel/boost", "name": "laravel/boost",
"version": "v1.1.5", "version": "v1.1.5",
@@ -7080,6 +7214,69 @@
}, },
"time": "2024-05-16T03:13:13+00:00" "time": "2024-05-16T03:13:13+00:00"
}, },
{
"name": "mrpunyapal/peststan",
"version": "0.2.10",
"source": {
"type": "git",
"url": "https://github.com/MrPunyapal/PestStan.git",
"reference": "750859a911050915cb6e3efbfde30e900ad717bf"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/MrPunyapal/PestStan/zipball/750859a911050915cb6e3efbfde30e900ad717bf",
"reference": "750859a911050915cb6e3efbfde30e900ad717bf",
"shasum": ""
},
"require": {
"php": "^8.2",
"phpstan/phpstan": "^2.0"
},
"require-dev": {
"laravel/pint": "^1.18",
"mrpunyapal/rector-pest": "^0.2.0",
"nunomaduro/pao": "^0.1.4",
"pestphp/pest": "^3.0 || ^4.0 || ^5.0",
"phpstan/extension-installer": "^1.4",
"phpstan/phpstan-strict-rules": "^2.0",
"rector/rector": "^2.0"
},
"type": "phpstan-extension",
"extra": {
"phpstan": {
"includes": [
"extension.neon"
]
}
},
"autoload": {
"psr-4": {
"PestStan\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "PHPStan extension for Pest PHP testing framework",
"keywords": [
"PHPStan",
"pest",
"static-analysis",
"testing"
],
"support": {
"issues": "https://github.com/MrPunyapal/PestStan/issues",
"source": "https://github.com/MrPunyapal/PestStan/tree/0.2.10"
},
"funding": [
{
"url": "https://github.com/mrpunyapal",
"type": "github"
}
],
"time": "2026-05-10T16:55:11+00:00"
},
{ {
"name": "myclabs/deep-copy", "name": "myclabs/deep-copy",
"version": "1.13.0", "version": "1.13.0",
@@ -7976,6 +8173,59 @@
}, },
"time": "2025-02-19T13:28:12+00:00" "time": "2025-02-19T13:28:12+00:00"
}, },
{
"name": "phpstan/phpstan",
"version": "2.1.54",
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/8be50c3992107dc837b17da4d140fbbdf9a5c5bd",
"reference": "8be50c3992107dc837b17da4d140fbbdf9a5c5bd",
"shasum": ""
},
"require": {
"php": "^7.4|^8.0"
},
"conflict": {
"phpstan/phpstan-shim": "*"
},
"bin": [
"phpstan",
"phpstan.phar"
],
"type": "library",
"autoload": {
"files": [
"bootstrap.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "PHPStan - PHP Static Analysis Tool",
"keywords": [
"dev",
"static analysis"
],
"support": {
"docs": "https://phpstan.org/user-guide/getting-started",
"forum": "https://github.com/phpstan/phpstan/discussions",
"issues": "https://github.com/phpstan/phpstan/issues",
"security": "https://github.com/phpstan/phpstan/security/policy",
"source": "https://github.com/phpstan/phpstan-src"
},
"funding": [
{
"url": "https://github.com/ondrejmirtes",
"type": "github"
},
{
"url": "https://github.com/phpstan",
"type": "github"
}
],
"time": "2026-04-29T13:31:09+00:00"
},
{ {
"name": "phpunit/php-code-coverage", "name": "phpunit/php-code-coverage",
"version": "11.0.9", "version": "11.0.9",
@@ -9569,5 +9819,5 @@
"php": "^8.2" "php": "^8.2"
}, },
"platform-dev": {}, "platform-dev": {},
"plugin-api-version": "2.9.0" "plugin-api-version": "2.6.0"
} }

View File

@@ -0,0 +1,32 @@
<?php
namespace Database\Factories;
use App\Enums\OrganisationRole;
use App\Models\Organisation;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\OrganisationInvitation>
*/
class OrganisationInvitationFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'organisation_id' => Organisation::factory(),
'invited_by_user_id' => User::factory(),
'email' => $this->faker->unique()->safeEmail(),
'role' => OrganisationRole::MEMBER,
'token' => Str::random(40),
'expires_at' => now()->addDays(14),
];
}
}

View File

@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('applications', function (Blueprint $table) {
$table->foreignId('source_provider_id')
->nullable()
->after('organisation_id')
->constrained('source_providers')
->nullOnDelete();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('applications', function (Blueprint $table) {
$table->dropConstrainedForeignId('source_provider_id');
});
}
};

View File

@@ -0,0 +1,38 @@
<?php
use App\Models\Organisation;
use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('organisation_invitations', function (Blueprint $table) {
$table->id();
$table->foreignIdFor(Organisation::class)->constrained()->cascadeOnDelete();
$table->foreignIdFor(User::class, 'invited_by_user_id')->nullable()->constrained('users')->nullOnDelete();
$table->string('email');
$table->string('role');
$table->string('token')->unique();
$table->timestamp('accepted_at')->nullable();
$table->timestamp('expires_at')->nullable();
$table->timestamps();
$table->unique(['organisation_id', 'email']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('organisation_invitations');
}
};

View File

@@ -44,7 +44,7 @@ class DatabaseSeeder extends Seeder
'name' => 'keystone', 'name' => 'keystone',
'external_id' => 'net-12345', 'external_id' => 'net-12345',
'provider_id' => $provider->id, 'provider_id' => $provider->id,
'ip_range' => fake()->ipv4() . '/24', 'ip_range' => fake()->ipv4().'/24',
]); ]);
$servers = Server::factory(40) $servers = Server::factory(40)
@@ -65,7 +65,6 @@ class DatabaseSeeder extends Seeder
$application->environments()->create([ $application->environments()->create([
'name' => 'Dev', 'name' => 'Dev',
'branch' => 'main', 'branch' => 'main',
'url' => 'https://dev.clipbin.hjb.dev',
'status' => 'active', 'status' => 'active',
]); ]);
} }

296
docs/managed-registry.md Normal file
View File

@@ -0,0 +1,296 @@
# Managed Registry Plan
Keystone should be self-hosted first. A fresh install should include a working build and image pipeline without requiring the user to bring an external Docker registry, S3 bucket, or separate build server.
## Product Principles
- The Keystone control node is the default build node.
- Keystone provides a first-party managed Docker registry by default.
- The managed registry stores images on local disk first.
- The registry storage path must be configurable for mounted VPS volumes.
- External registries, S3-backed storage, and dedicated build nodes are optional advanced features.
- Multi-server deployments should work out of the box after Keystone is installed.
- Registry credentials must not be persisted in operation scripts, logs, or UI-visible output.
- Old build artifacts should be pruned automatically, retaining the latest 3 successful artifacts per environment by default.
- Build and deploy should be separate phases, even when started by one user action.
- Users should be able to connect an existing Ubuntu server as a Keystone node without using a cloud provider integration.
## Default Self-Hosted Shape
When Keystone is installed on a server, that server becomes the control node. The install process should prepare:
- Keystone application services.
- Docker and Docker Compose.
- A managed `registry:2` service.
- Local registry storage.
- Generated registry credentials.
- A default build capability on the control node.
This is separate from server provisioning. Keystone needs two scripts/flows:
- `install-keystone.sh` installs Keystone itself on the control node.
- The remote provisioning script prepares other servers so they can be managed by Keystone.
Remote provisioning should continue to install Docker, configure SSH access, prepare the `keystone` user, and link the server back to Keystone. It should not be responsible for installing the Keystone application itself.
Default settings:
```text
Build node: Keystone control node
Registry: registry:2 managed by Keystone
Registry storage driver: local
Registry storage path: /home/keystone/registry/data
Image retention: latest 3 successful artifacts per environment
Auth: generated htpasswd credentials managed by Keystone
```
The install flow should allow overriding the storage path, for example:
```text
/mnt/keystone-registry
```
This lets users place registry image data on a mounted VPS volume while keeping Keystone's default behavior simple.
## Default Image Flow
```text
Git repository
-> Keystone control node builds Docker image
-> Keystone pushes image to the managed registry
-> Target servers pull image from the managed registry
-> Target servers run containers
```
The build node and registry are separate concepts:
- Build node: where `git clone`, `docker build`, and `docker push` run.
- Registry: where built images are stored and later pulled from.
The control node is the default build node, but users should later be able to add a dedicated build node from Keystone settings.
The running Keystone server is the control node. This does not necessarily need to be represented as a normal deploy target server at first. A lightweight installation/control-node setting may be enough until Keystone needs HA control-plane support.
If Keystone later supports HA control planes, the control node concept should become more explicit so the app can distinguish between:
- The current web/queue/scheduler node.
- The active registry host.
- The default build node.
- Runtime nodes used for deployed applications.
## Registry Exposure
The managed registry should be exposed over HTTPS where possible, ideally behind the control node's web proxy, for example:
```text
registry.example.com
```
Avoid defaulting to a plain `host:5000` registry if possible. Plain HTTP registries require Docker daemon insecure-registry configuration on every build and target server, which adds onboarding friction.
Target servers must be able to reach the registry URL before they can deploy images built by Keystone.
## Authentication
Use `registry:2` htpasswd authentication for the first version.
Keystone should:
- Generate registry credentials.
- Write the registry htpasswd file during provisioning.
- Store credentials encrypted.
- Configure build and target servers for registry access.
- Use `docker login --password-stdin` when login is needed.
Do not inline registry passwords into persisted operation scripts. Operation steps are stored and may be visible in the UI or logs.
Preferred approaches:
- Configure Docker auth on each server through a separate secure action.
- Or write root-owned / user-owned credential files on the server and have deployment scripts read from those files.
Token auth can be considered later if Keystone needs per-repository or per-server scoped credentials. It should not be part of the first implementation.
## Build Planning
Build planning should assume a default managed registry exists after install.
For the default path:
- Build strategy: build on control node.
- Registry: managed local registry.
- Artifact reference: full managed registry image reference.
Multi-server deploys should no longer block because the user has not configured an external registry. They should only block if the managed registry is missing, unhealthy, or unreachable.
External registries should remain available as an advanced override.
Build strategy should not be exposed to users as low-level values such as `target_server`, `dedicated_builder`, or `external_registry`. The UI should expose intent instead:
- Default build node.
- Specific build node.
- External registry override.
Internally, build planning can still map those choices to implementation strategies.
## Build Execution
The default build execution should:
1. Select the configured build node, defaulting to the control node.
2. Clone the application repository.
3. Render the Keystone Dockerfile.
4. Log in to the managed registry.
5. Build the image.
6. Tag the image using the managed registry reference.
7. Push the image.
8. Resolve and store the registry manifest digest.
Example flow:
```bash
docker login registry.example.com --username keystone --password-stdin
docker build --file Dockerfile.keystone --tag registry.example.com/application:aaaaaaaaaaaa .
docker push registry.example.com/application:aaaaaaaaaaaa
docker manifest inspect registry.example.com/application:aaaaaaaaaaaa
```
The stored digest must be the registry manifest digest, not a local image ID. Digest-based pulls and registry manifest deletion depend on this being correct.
Build execution should create a build operation that can succeed or fail independently from deployment. A deployment can then depend on a successful build artifact.
## Deploy Execution
Target servers should pull immutable image references from the managed registry.
Deploy execution should:
1. Ensure the target server has registry auth configured.
2. Pull the exact image digest.
3. Render Compose with the full registry image reference.
4. Start or update containers.
Example pull reference:
```text
registry.example.com/application@sha256:...
```
Compose should use the full registry reference, not only `sha256:...`.
Deploy execution should be a separate operation phase from build execution. The deploy phase should consume a completed build artifact and should not be responsible for building the artifact itself.
Operations should have explicit execution targets. Inferring the SSH target only from the operation target model becomes fragile once Keystone has build nodes, registry maintenance, and runtime deployment steps.
Each operation or operation step should be able to declare where it runs:
- Control node.
- Build node.
- Runtime server.
- Specific server.
## Pruning And Retention
Default retention should keep the latest 3 successful build artifacts per environment.
Pruning should also retain:
- Any artifact currently referenced by a service's available image digest.
- Any artifact currently referenced by a service's current image digest.
- Any artifact needed for an active deployment operation.
Pruning should remove old registry manifests first, then run registry garbage collection to remove unreferenced blobs from local disk.
`registry:2` requires deletion to be enabled:
```text
REGISTRY_STORAGE_DELETE_ENABLED=true
```
Garbage collection is safest when the registry is not accepting writes. The first implementation should run cleanup during a controlled maintenance window, using a lock so pruning does not race with active builds or pushes.
Suggested cleanup flow:
1. Acquire a registry maintenance lock.
2. Find prunable artifacts by environment retention rules.
3. Delete old manifests through the registry API.
4. Stop the registry or put it in a safe maintenance state.
5. Run registry garbage collection.
6. Restart the registry.
7. Mark artifacts as pruned or delete their records.
8. Release the lock.
## Future Extensions
These should be optional settings, not onboarding requirements:
- Dedicated build nodes.
- S3-compatible registry storage.
- External registries such as GHCR, Gitea, Docker Hub, or generic registries.
- Separate push and pull credentials.
- Credential rotation.
- Per-server or per-repository scoped auth.
- Configurable retention per application or environment.
The first version should optimize for a self-hosted user installing Keystone on a VPS and being able to deploy with minimal additional setup.
## Existing Server Provisioning
Keystone should support connecting an existing Ubuntu server as a managed node. This is important for users running VPSs, Proxmox VMs, homelab hardware, or manually provisioned servers.
The flow should be:
1. User creates a server record in Keystone as an existing server.
2. Keystone shows a one-time provisioning command.
3. User runs the command on the server as root or a sudo-capable user.
4. The script installs Docker and required packages.
5. The script creates/configures the `keystone` user.
6. The script installs Keystone's management SSH key.
7. The script calls back to Keystone with a one-time token.
8. Keystone marks the server active.
This should sit alongside cloud-provider provisioning. Cloud providers can create the VM automatically, but the same remote preparation logic should be reused where possible.
Provisioning callbacks should not authenticate only by `server_id` or IP address. They should use a short-lived, single-use provisioning token tied to the server record.
Avoid passing sensitive values such as sudo passwords in URL query strings. Safer options include:
- Generate a short-lived provisioning token and pass only that in the URL.
- Store sensitive bootstrap data server-side and let the provisioning script exchange the one-time token for the data it needs.
- Prefer SSH key-based provider bootstrap where available instead of root password bootstrap.
- If a password must be used, pass it over SSH stdin or an encrypted job payload, not through a script URL.
The remote provisioning script can still be downloaded from Keystone, but the URL should not contain long-lived secrets or reusable credentials.
### Sudo Password Handling
Keep the current Forge-like user model for now:
- Provisioned servers have a `keystone` user.
- SSH login is key-only.
- The generated sudo password is for the human user to SSH in and run elevated commands manually.
- Keystone automation continues to use SSH key access and Docker/sudo-capable permissions as required.
This model is acceptable, but sudo password delivery should be hardened.
Laravel protections help with some leak paths:
- `ShouldBeEncrypted` protects queued job payloads.
- Encrypted casts protect stored secrets.
- Hidden model attributes avoid accidental serialization.
- PHP `#[\SensitiveParameter]` can prevent secret values appearing in stack traces.
These protections do not cover query strings, shell process arguments, rendered scripts left on disk, reverse-proxy logs, or third-party request logging.
Minimal hardening plan:
1. Keep generating a sudo password for the provisioned `keystone` user.
2. Keep flashing the sudo password to the user once after server creation.
3. Add `#[\SensitiveParameter]` to job constructor parameters such as `rootPassword` and `sudoPassword`.
4. Stop passing `sudo_password` in the provision script URL.
5. Use a short-lived, single-use provisioning token in the URL instead.
6. Store the sudo password encrypted server-side until the provisioning script is rendered or exchanged.
7. Ensure the remote provisioning script deletes itself at the end of provisioning.
8. Avoid writing the plaintext sudo password to logs or long-lived files.
The goal is to preserve the simple human-admin UX while removing avoidable secret exposure from URLs and leftover bootstrap artifacts.

341
docs/ui-review.md Normal file
View File

@@ -0,0 +1,341 @@
# Keystone UI Gap Review
A full audit of the current Vue/Inertia UI in `resources/js/pages/` against
`docs/implementation-spec.md`. Findings are grouped by spec section/feature.
Each gap lists what is missing, where the relevant code lives today, and a
suggested resolution.
Conventions:
- **Missing** — feature has no UI surface at all.
- **Partial** — surface exists but does not cover the spec.
- **Broken** — surface exists but has a bug or dead code path.
---
## 1. Global Navigation & Information Architecture
- **Partial — active header navigation is still not environment-first.** The active `AppLayout` uses `resources/js/layouts/app/AppHeaderLayout.vue`, whose header navigation (`resources/js/components/AppHeader.vue`) exposes organisation, `Applications`, and `Servers` when an organisation is selected. There are still no entries for `Operations` or `Onboarding`, and environments are only reachable after choosing an application. The inactive sidebar layout (`resources/js/components/AppSidebar.vue:19-37`) is even narrower, exposing only `Dashboard` and `Servers`. The spec frames environments as the primary surface (§20 Phase 6: "Present environments as the primary application surface"). Add an environment-primary route/navigation surface, plus `Operations` and onboarding access while setup is incomplete.
- **Partial — organisation switcher exists only in the active header chrome.** Multiple organisations are modeled (`Organisation::members()` on `app/Models/Organisation.php`), and the active header (`resources/js/components/AppSidebarHeader.vue`) includes organisation/application/environment dropdowns. The inactive sidebar layout has no equivalent, and onboarding/operations are still absent from the switcher flow. Keep the header switcher if `AppHeaderLayout` remains the canonical layout; otherwise add parity to the sidebar chrome.
- **Missing — no Operations index.** Operations are the spec's audit/execution backbone (§3) but the UI only surfaces them inline on `environments/Show.vue` and `servers/Show.vue`. There is no organisation-wide operations feed for triage. Add an `operations.index` view with filters (kind, status, target).
- **Missing — no global empty/help state.** A fresh org with no servers/apps has no "Get started" CTA in the primary app chrome; user must guess to visit `/onboarding`. Promote the onboarding link until all onboarding steps are complete.
## 2. Onboarding (Spec §19)
- **Partial — onboarding page exists but is unreachable from primary nav.** `resources/js/pages/onboarding/Show.vue` is only reachable via the URL `/organisations/{id}/onboarding`. There is no link from `Dashboard`, the active header navigation, `AppSidebar`, or `organisations/Show.vue`. Surface a persistent banner or primary-nav entry while `nextStep` is non-terminal.
- **Partial — onboarding "Provider" step routes to organisation show.** `app/Http/Controllers/OnboardingController.php:25` sets the Provider step `href` to `organisations.show`, but the Server Providers list there (`resources/js/pages/organisations/Show.vue:202-220`) has no Add button. There is no `providers.create` route or page. Either add a `ProviderController@create` + Vue page or make the step open an inline dialog.
- **Missing — registry/source/server-create steps don't enforce a single org-level "default" once configured.** Spec §19 says registry is required for multi-server. The UI never blocks deployment on this — see Deployment Flow gap below.
- **Missing — onboarding doesn't reflect deploy-key install step (§5).** The spec lists "Deploy key installation and verification" as a discrete step; onboarding shows none. Add a step gated on `applications.deploy_key_installed_at`.
## 3. Organisation & Provider Management
- **Missing — server-provider UI is read-only.** `resources/js/pages/organisations/Show.vue:202-220` lists providers but offers no add/edit/delete. There is no `ProviderController` registered (see `routes/web.php`). The Hetzner provider must currently be seeded outside the UI.
- **Missing — registry/source-provider lists have no edit/delete.** Only `create` and `store` are wired (`routes/web.php:33-41`). Users can produce duplicate registries with bad credentials and never repair them.
- **Missing — no organisation member management.** `organisations/Show.vue:111-122` shows a members **count** with no roster, invite flow, role editor, or removal. The `members()` BelongsToMany on `Organisation` is unused by the UI.
- **Partial — registry credentials cannot be rotated.** No edit page; the only fix is delete-and-recreate, but delete is also missing. Add `registries.edit` + `registries.update`.
## 4. Source Providers & Repository Access (Spec §5)
- **Partial — deploy-key card disappears once installed.** `resources/js/pages/applications/Show.vue:46-75` only shows the deploy-key card when `application.deploy_key_public && !application.deploy_key_installed_at`. After install there is no way to view or rotate the key. Show key + `deploy_key_fingerprint` and a "Rotate" action permanently in an Application Settings tab.
- **Missing — no fingerprint display.** The model stores `deploy_key_fingerprint` (`app/Models/Application.php`), but the UI never renders it. Surface beside the public key for verification.
- **Missing — no way to re-run `git ls-remote` verification after install.** Verify button is gated by the same conditional in `applications/Show.vue:46`. Move it to an always-available action; spec §5 implies verification can be re-run.
- **Missing — application creation does not pick a source provider.** `resources/js/pages/applications/Create.vue` collects `repository_url` as a free string. Source providers exist (§5: Gitea/GitHub/generic Git) but the form never references them — users have no guidance for which provider corresponds to the URL, and the application schema/UI currently has no source-provider association.
- **Missing — repository type selector.** Spec lists `repository_type` (§2 Application). UI hardcodes `RepositoryType::GIT` (`app/Http/Controllers/ApplicationController.php:39`). Even if Git is the only v1 type, the form should display the resolved type.
## 5. Applications & Environments (Spec §2, §6, §17)
### Applications
- **Missing — no Application edit/delete.** Only `index/show/create/store` are routed (`routes/web.php:62-66`). Renaming or removing an app requires DB intervention.
- **Missing — environment creation UI.** The initial environment is auto-created in `ApplicationController@store` (`CreateLaravelEnvironment`). There is no "Add environment" affordance on `applications/Show.vue`, despite the spec describing multiple environments (production/staging/dev) as the primary deployment unit (§2).
- **Broken — Applications/Index uses wrong key + has no empty state.** `resources/js/pages/applications/Index.vue:46` writes `:key=\`application{$applications.id}\`` (literal `$applications`). Replace with `:key="application.id"` and render an empty card when `applications.length === 0`.
- **Partial — Application Show has no overview.** No "last deployed at", no current commit, no current image digest. Spec §6 stores `current_image_digest` on Service and `BuildArtifact` per environment but neither is rendered.
### Environments
- **Missing — environment-level edit page.** Cannot change `branch`, `name`, `status`, `scheduler_enabled`, `scheduler_target_service_id`, `scheduler_mode`, or `build_config` (spec §2). All are dead fields in the DB from the UI's perspective.
- **Missing — branch change / redeploy with a specific commit.** Deploy is a fire-and-forget POST (`environments/Show.vue:63-76` and `applications/Show.vue:139-153`). The spec resolves a "target commit" (§17 step 1) — there is no commit picker or branch switcher in the UI.
- **Missing — build artifact view per environment.** `BuildArtifact` exists with status/digest/registry_ref but is not rendered on `environments/Show.vue`. Add a "Builds" section showing recent artifacts and their status.
- **Missing — scheduler controls (Spec §8).** No UI for `scheduler_enabled`, `scheduler_target_service_id`, or `scheduler_mode`. The spec explicitly says scheduler is a role/capability and that v1 should expose it. Add to environment settings tab and surface "Scheduler runs on: <web service>" on the environment overview.
- **Missing — migration policy controls (Spec §18).** `migration_mode`, `migration_timing`, `migration_command` are spec fields on a service. The UI has only a one-off `Migrate` button (`environments/Show.vue:77-91`); there is no form to inspect/change defaults per service.
- **Partial — environment header buttons are crowded.** `resources/js/pages/applications/Show.vue:123-211` packs Open / Deploy / Migrate / Env / Worker / Attach into a single card row. On md screens this overflows. Move secondary actions into a dropdown.
- **Missing — environment delete.** Spec implies environments are mutable units (§2); UI has no delete.
## 6. Services (Spec §2 Service, §7, §9, §11)
### Service list / show
- **Missing — no service-by-environment scoping.** `services/Show.vue` does not show its parent environment (only `server` + `service`). Reaching a service from an environment requires `service.server_id` to be set (`environments/Show.vue:138-153`); environments where the service is server-less (replicas only) cannot be opened. Show environment breadcrumb when present.
- **Missing — replica detail view.** `services/Show.vue:62-79` lists replicas but they are inert. Spec §2 ServiceReplica has `cpu_limit`, `memory_limit_mb`, `container_id`, `internal_host`, `internal_port`, `public_port`, `image_digest`, `health_status`. Tap-through to a replica detail with logs/restart action is missing.
- **Missing — start/stop/restart actions on replicas.** Status badges show `status` and `health_status` (`services/Show.vue:73-77`) but no buttons.
- **Missing — endpoint listing.** `app/Models/ServiceEndpoint.php` exists and Spec §14 defines an endpoint model (`scope: docker_network/private_network/public`, hostname/ip/port/priority). UI never renders endpoints. Add an "Endpoints" card on `services/Show.vue`.
- **Missing — compose preview / generated artifact view.** Spec §16 establishes generated Compose under `/home/keystone/services/<service-id>/compose.yml`. There is no UI to inspect/render it. Add a "Compose" tab on `services/Show.vue` (read-only, syntax-highlighted).
- **Missing — process_roles editor.** `Service` has `process_roles` JSON (spec §2). Used by scheduler role attachment (§8). No UI exposes it.
### Service edit (`services/Edit.vue`)
- **Partial — only name, desired_replicas, default_cpu_limit, default_memory_limit_mb editable.** Missing: `deploy_policy`, `version_track`, `available_image_digest` (acknowledge available update), `config` overrides (migration_mode/timing/command per §18), `scheduler` flags for app services.
- **Missing — health-check / health-path override.** Spec §7 defaults health path to `/up`. No UI surfaces or overrides.
### Service create
- **Missing — builder service category in practice.** `ServiceCategory::BUILDER` exists and Spec §6 says "A dedicated builder is represented as a `Service` with category `builder`". The Create flow shows the BUILDER radio (it loops over the enum) but `services/Create.vue:111-122` only lists `services[form.category]` from `config('keystone.services')` — there is no entry for builder there, so selecting `builder` shows an empty type list with no message. Either remove `BUILDER` from the radio set or wire builder driver options.
- **Missing — selecting category doesn't surface deploy_policy defaults.** Spec §2 defines deploy_policy defaults per category. The form does not show or let the user accept them.
### Stateful service updates (Spec §11)
- **Partial — update form exists but exposes raw digest.** `resources/js/pages/services/updates/Create.vue:74-82` requires the user to paste an image digest. The available digest is pre-filled from `service.available_image_digest`, but Postgres/Valkey users will not know how to obtain a different digest. Replace with a "latest minor" resolver and a manual override (spec §9: "resolving image tags to digests"; §11 implies guided update).
- **Partial — backup checkbox visible only when `backup_enabled` config flag is set.** Spec §11 step 3 says "Optional backup checkbox appears only if backup capability exists" — current code matches the letter, but the UI never lets the user enable backups in the first place, so the checkbox is unreachable.
- **Missing — downtime acknowledgement.** Spec §11 step 2 says "Keystone warns about downtime and data risk." Current warning is generic. Show a hard confirmation step ("type the service name to confirm").
## 7. Slices & Attachments (Spec §12, §13)
- **Missing — slice index per service.** `services/Show.vue:81-95` lists slices with `name + type` only — no operations, no credentials view, no detail page, no create from service-detail (spec §12: "Advanced users can select existing slices or create slices manually from service detail pages").
- **Missing — slice create UI.** No `slices.create` route or page. Spec §12 explicitly requires this for advanced users.
- **Missing — slice operations are not independent in the UI.** Spec §12: "Slice operations should be independent from service container deployments." Backend distinguishes `slice_provision`/`slice_configure` operations (§3), but UI only shows them mixed into the service's operations list (`services/Show.vue:97-117`).
- **Missing — env-var preview for attachments.** Spec §13 enumerates `DB_*` / `REDIS_*` exports. The attachment form (`environment-attachments/Create.vue`) shows only "Generated <slice type>" with no preview of what variables will be written. Add a preview block.
- **Missing — attachment edit/detach.** `environments/Show.vue:184-204` lists attachments inertly — no detach button, no edit. Recovering from a wrong attachment requires DB intervention.
- **Partial — attachment form's role/service compatibility is hardcoded in JS.** `environment-attachments/Create.vue:37-48` keeps role-to-service-type mapping client-side. If the backend adds queue support via Postgres listen/notify or storage via Caddy, this map drifts. Push the compatibility matrix from the controller.
- **Missing — `is_primary` semantics aren't explained.** A checkbox labeled "Primary attachment" with no helper text; users don't know when to uncheck.
## 8. Environment Variables (Spec §13)
- **Partial — variables UI is add-only.** `environment-variables/Create.vue` only POSTs. There is no edit, no delete, no value reveal, no bulk import (`.env` paste). Managed values show as badges (`environments/Show.vue:206-235`) but cannot be inspected or overridden.
- **Missing — `overridable` toggle.** Spec §2 EnvironmentVariable has `overridable`. The UI never surfaces it; all user-created variables silently become `overridable: true` (`EnvironmentVariableController::store`).
- **Missing — source/slice provenance display.** Managed/system variables should "show their source and whether they are overridable" per spec §13. Currently rendered as `<source>` text only; no link back to the slice/attachment that generated them.
- **Missing — secret vs. plain value distinction.** No marker, no masking, no copy button.
## 9. Servers (Spec §4)
- **Broken — `<template>` block has dangling fallback.** `resources/js/pages/servers/Show.vue:217` reads `<template> Something else </template>` outside any `v-if`/`v-else-if` chain. This is an unconditional Vue template whose text child renders alongside the rest of the page, not a real status fallback. Clean up or convert to `<template v-else>`.
- **Partial — provisioning UI is decorative.** `servers/Show.vue:27-39` cycles through fake messages on an interval. No actual progress, no association to the running `server_provision` operation (spec §3 OperationKind). Tie the cycling messages to real `operation_steps` events.
- **Missing — server delete / decommission.** Not wired anywhere; only `index/show/create/store` routes registered (`routes/web.php:43-47`).
- **Missing — firewall-rule UI.** `app/Models/FirewallRule.php` and `Server::firewallRules()` exist. Spec §4 step 8 says UFW with SSH open, but additional rules (e.g. for Caddy 80/443, private network) are not surfaced. Add a Firewall tab on `servers/Show.vue`.
- **Missing — credential persistence/regen.** "WILL NOT BE SHOWN AGAIN" (`servers/Show.vue:219-224`) appears via flash only; if the user navigates away without copying, the only credential they have is the SSH key Keystone manages. Acceptable, but should explicitly say "Keystone uses an SSH key for all subsequent operations; this password is informational."
- **Missing — re-provision/heal action.** If provisioning fails there is no retry button on the show page.
- **Missing — service add gated on server `active` status.** `servers/Show.vue:75-94` only renders the Add button when status is `active`, but during `provisioning` there is no informative message about why services can't be added (the cycling messages run but the section disappears entirely). Show a disabled "Add" with tooltip.
- **Missing — operations list does not show parent-child structure.** `servers/Show.vue:138-196` shows steps under each operation but flat. Spec §3 emphasises parent-child (environment_deploy → service_deploy → replica_deploy). Render as a tree.
## 10. Operations & Logs (Spec §3)
- **Partial — step log dialog only on server show.** `servers/Show.vue:226-245` is the only place a user can read full step logs. Service Show and Environment Show both list operations without log expansion. Promote the log dialog to a shared component and use it everywhere operations appear.
- **Missing — operation detail page.** Spec §3 implies operations are first-class. There is no `operations.show` page. Cannot view secrets used, parent op, retry, cancel, or download logs.
- **Missing — retry / abort actions.** Failed operations are terminal in the UI; spec doesn't forbid retry. Add at least a "Re-run operation" button on the operation detail page.
- **Missing — operation hash / kind / target column.** `Operation::hash` is generated but never displayed; useful for support and correlation with server-side `/home/keystone/operations/<operation-hash>/` directories (spec §16).
- **Missing — live progress.** Operations require a refresh to update. Inertia v2 supports polling, and this app already uses `WhenVisible` for deferred organisation settings data (`organisations/Show.vue:126`); apply polling/deferred refresh patterns to operations.
## 11. Build Artifacts & Registry (Spec §6)
- **Missing — no build artifact UI.** `BuildArtifact` model + `PlanBuildArtifact`/`BuildApplicationArtifact` actions exist, but there is no listing per environment or per registry. Users cannot see whether a build is pending, building, available, or failed.
- **Missing — registry usage indicator.** Spec §19: "If an environment spans more than one server and no registry exists, deployment should be blocked with a registry setup prompt." UI does not surface this precondition anywhere — deploy button is always live on `applications/Show.vue:139-153`. Add a pre-deploy check.
- **Missing — build strategy selector.** Spec §6: `target_server` / `dedicated_builder` / `external_registry`. There is no UI to choose. Currently the strategy lives in `BuildArtifact.metadata['build_strategy']` only.
- **Missing — registry detail page.** No way to see which artifacts have been pushed where.
## 12. Gateway / Caddy (Spec §15)
- **Missing — domain / route configuration UI.** Caddy attachment is supported (`environment-attachments/Create.vue:39-48`) but the form does not collect a domain, TLS preference, or path prefix. Spec §15 requires explicit gateway routes; spec §12 says "Caddy/domain attachment: Create route slice. Wire gateway route to environment web service." There is no domain input anywhere in the UI.
- **Missing — TLS / certificate status view.** No surface to see whether Caddy has issued a cert.
- **Missing — Caddyfile preview.** Similar to compose preview — spec §16 places it at `/home/keystone/gateway/Caddyfile`. Should be viewable.
- **Missing — cutover visualisation.** Spec §15 lays out the cutover sequence (render → health → upstream add → reload → drain → stop). UI has no visualisation; users get a generic deploy progress only.
## 13. Networking (Spec §14)
- **Missing — endpoint surface entirely.** Spec defines an endpoint model with `scope/hostname/ip_address/port/priority/health_status`. The model class exists (`app/Models/ServiceEndpoint.php`) but is never rendered.
- **Missing — private-network membership view.** `Network` model and `Server::network()` exist; spec §14 prefers same-provider private IPs. UI never shows which servers share which networks.
## 14. Dashboard & Welcome
- **Partial — Dashboard is a single card.** `Dashboard.vue:27-44` lists organisations only. Once an org is picked, no summary of pending operations, recent deploys, or failing services on the main dashboard. Add "Recent operations" + "Unhealthy services" panels.
- **Missing — no aggregated health.** Organisation Show (`organisations/Show.vue:65-123`) shows counts but not health (provisioning servers, failed last deploy, locked attachments).
## 15. Visual & UX Polish
- **Inconsistent — script tags mix `<script setup lang="ts">` and `<script setup>`.** E.g. `pages/environments/Show.vue:1` is plain JS while `pages/applications/Show.vue:1` is TypeScript. Pick a default and apply.
- **Inconsistent — typed props.** Several Show pages declare `defineProps({ application: { type: Object, required: true }, ... })` with no TS interfaces. New pages should use `defineProps<{...}>()` shapes.
- **Inconsistent — breadcrumb depth.** Service Show breadcrumb (`services/Show.vue:18-33`) goes Servers → server → service, but an environment-scoped service should also show the environment in the trail.
- **Accessibility — radio button groups in Create flows.** `servers/Create.vue` and `services/Create.vue` use `RadioButton` but render via `v-for` with no `:key` on the radios. Visual-only impact today, but a11y-wise the labelling could be tightened (associate description text with `aria-describedby`).
- **Accessibility — colour-only status.** `ServiceCard.vue:38-58` uses small dots + colour classes for status with no text alternative beyond the status string. Verify contrast in light mode.
- **Empty states — Applications/Servers indexes have none.** A new organisation hits a blank grid. Render an illustration + CTA pointing to onboarding.
## 16. Routes & Controllers Backing the UI
These backend gaps directly produce the UI gaps listed above. Filling the UI will require new routes/controllers (or destroy actions on existing ones):
- `providers.create/store/destroy` (organisation provider mgmt)
- `registries.index/edit/update/destroy`
- `source-providers.index/edit/update/destroy`
- `applications.edit/update/destroy`
- `environments.create/store/edit/update/destroy`
- `environments.scheduler` (settings sub-resource)
- `services.destroy` and service-level slice mgmt (`services/{service}/slices.*`)
- `service-replicas.show/restart`
- `environment-variables.update/destroy/index`
- `environment-attachments.destroy/update`
- `operations.index/show/retry`
- `build-artifacts.index/show`
- `servers.destroy`, `servers.firewall-rules.*`
- `domains.*` / `gateway.routes.*` for Caddy
---
## 17. Suggested Priorities
To bring the UI in line with spec without inflating scope:
1. **Make environments the primary surface (spec §20 Phase 6).** Sidebar entry, environment overview tab, environment edit page covering branch + scheduler + build config + migration policy.
2. **Fix the deploy preconditions and visibility loop.** Block deploy when no registry + multi-server (§19). Show build artifact + commit + image digest after deploy.
3. **Promote operations to first-class.** `operations.index`, `operations.show`, log dialog reused across pages, parent-child tree, retry.
4. **Round out CRUD for org-level resources** (providers, registries, source providers, members). Currently all "configured once via DB" surfaces.
5. **Slice + attachment maintenance.** Edit/detach/preview env-var exports.
6. **Gateway/domain UX.** Domain input on Caddy attachment, route slice view, Caddyfile preview.
7. **Polish:** fix `servers/Show.vue` dangling `<template>`, fix `applications/Index.vue` `:key`, add empty states, unify script lang.
---
## 18. Progress Tracker
This tracker is the working checklist for closing the review. It is intentionally
conservative: an item is only `Done` when there is current code evidence and at
least targeted verification.
Status key:
- `Done` - implemented and targeted verification exists.
- `Partial` - meaningful UI/code exists, but the review item is not fully satisfied.
- `In progress` - code has been started but is not yet verified or finalized.
- `Open` - no convincing implementation evidence found yet.
- `Needs audit` - likely implemented, but needs an item-level pass before closing.
### Current Caution
| Item | Status | Evidence | Next action |
|---|---|---|---|
| Repository type selector | Done | `StoreApplicationRequest`, `UpdateApplicationRequest`, `ApplicationController`, `applications/Create.vue`, and `applications/Edit.vue` validate, persist, and display `repository_type`; `ApplicationControllerTest` and `CrudUiTest` cover create/update. | Final audit only. |
| Overall completion | Done | All tracker rows are done, targeted verification is logged below, and the full test suite passes. | Final audit complete. |
### Section Checklist
| Section | Review area | Status | Evidence | Remaining work |
|---|---|---:|---|---|
| 1 | Environment-first navigation | Done | `AppHeader.vue` and `AppSidebar.vue` both expose Environments, Applications, Servers, Operations, and conditional Onboarding; `EnvironmentIndexController` and `environments/Index.vue` provide the environment-first index; `NavigationUiTest` covers shared navigation context and environment listing. | Final audit only. |
| 1 | Organisation switcher parity | Done | `AppSidebarHeader.vue` provides organisation/application/environment switchers and `HandleInertiaRequests` shares organisation/application context with applications/environments loaded. | Final audit only. |
| 1 | Operations index | Done | `routes/web.php` has `operations.index`; `resources/js/pages/operations/Index.vue`; `tests/Feature/OperationsUiTest.php`. | Final audit only. |
| 1 | Global empty/help state | Done | `organisations/Show.vue` shows a primary Continue onboarding CTA for incomplete organisations; `applications/Index.vue`, `servers/Index.vue`, and `environments/Index.vue` include empty states and CTAs/help text for fresh resources. | Final audit only. |
| 2 | Onboarding reachable from primary nav | Done | `OnboardingController` sends `nextStep`; `onboarding/Show.vue` renders it; `AppHeader.vue` and `AppSidebar.vue` include Onboarding while setup counts are incomplete. | Final audit only. |
| 2 | Provider onboarding step opens usable add flow | Done | `ProviderController`, provider create route/page, onboarding/provider links. | Final audit only. |
| 2 | Registry/source/server default/precondition handling | Done | `OnboardingController` gates provider/source/registry/server/application/deploy-key steps; `OnboardingControllerTest` covers next-step progression; `EnvironmentDeploymentController` blocks multi-server deploy without a registry and app/environment deploy surfaces show registry CTAs. | Final audit only. |
| 2 | Deploy-key install onboarding step | Done | `OnboardingController` includes a `deploy-key` step that targets the first app with `deploy_key_installed_at` null and marks complete when none remain. | Final audit only. |
| 3 | Provider management | Done | `providers.create/store/destroy`, provider page/tests. | Final audit only. |
| 3 | Registry/source provider lists/edit/delete | Done | Registry/source provider index/edit/update/destroy routes/pages/tests exist. | Final audit only. |
| 3 | Organisation member management | Done | `OrganisationInvitation` model/migration/factory, member/invitation routes, `OrganisationMemberController`, `organisation-members/Index.vue`, and `OrganisationMemberControllerTest` cover existing-member add/update/remove plus pending invitation create/update/cancel. | Final audit only. |
| 3 | Registry credential rotation | Done | `registries.edit/update` present. | Final audit only. |
| 4 | Deploy key always visible, fingerprint, verify, rotate | Done | Application show/controller routes/tests include deploy key rotate and verification. | Final audit only. |
| 4 | Source provider association on applications | Done | `source_provider_id` migration/model/forms/controller/tests. | Final audit only. |
| 4 | Repository type selector | Done | Code validates/persists/displays selector; targeted app CRUD tests pass. | Final audit only. |
| 5 | Application edit/delete | Done | `applications.edit/update/destroy`, `applications/Edit.vue`, tests. | Final audit only. |
| 5 | Environment create UI | Done | `environments.create/store`, create page/routes. | Final audit only. |
| 5 | Applications index key and empty state | Done | `applications/Index.vue` uses `:key="application.id"` and has an empty-state card with a create CTA. | Final audit only. |
| 5 | Application overview deploy metadata | Done | Application show renders last deploy/current commit/image digest from services/build artifacts. | Final audit only. |
| 5 | Environment settings | Done | `environments/Edit.vue`, update request/controller for branch/status/scheduler/build config. | Final audit only. |
| 5 | Branch change / deploy specific commit | Done | `StoreEnvironmentDeploymentRequest`, `target_commit`, environment deploy form, controller/job tests. | Final audit only. |
| 5 | Build artifact view per environment | Done | `build-artifacts.index/show`, environment builds section, tests. | Final audit only. |
| 5 | Scheduler controls | Done | Environment edit and show scheduler fields. | Final audit only. |
| 5 | Migration policy controls | Done | Service edit exposes migration mode/timing/command and environment show summarizes. | Final audit only. |
| 5 | Crowded environment actions | Done | `applications/Show.vue` keeps primary Open/Deploy visible, moves secondary environment actions into a More menu, and wraps action groups for responsive layouts. | Final audit only. |
| 5 | Environment delete | Done | `environments.destroy` route/controller/page action. | Final audit only. |
| 6 | Service-by-environment scoping | Done | `environment-services.show`, service breadcrumb supports environment, tests. | Final audit only. |
| 6 | Replica detail and lifecycle actions | Done | `ServiceReplicaController`, replica show/start/stop/restart routes/pages/tests. | Final audit only. |
| 6 | Endpoint listing | Done | `services/Show.vue` endpoint card. | Final audit only. |
| 6 | Compose preview | Done | `services/Show.vue` compose path/preview card. | Final audit only. |
| 6 | Process roles editor | Done | `services/Edit.vue`, `UpdateServiceRequest`, controller update. | Final audit only. |
| 6 | Service edit missing fields | Done | Deploy policy, version track, available digest, migration config, health path, backup fields added. | Final audit only. |
| 6 | Builder category and deploy policy default display | Done | `services/Create.vue` empty state/default deploy policy display. | Final audit only. |
| 6 | Stateful update resolver, backup, acknowledgement | Done | `ServiceUpdateController::resolve`, update create page hard confirmation, tests. | Final audit only. |
| 7 | Slice index/detail/create/operations | Done | `service-slices.index/create/store/show`, `service-slices/Index.vue`, `service-slices/Show.vue`, and `ResourceDetailUiTest` cover list/detail/create plus independent operations. | Final audit only. |
| 7 | Attachment env-var preview | Done | Attachment create/edit preview blocks. | Final audit only. |
| 7 | Attachment edit/detach | Done | `environment-attachments.edit/update/destroy`, pages/tests. | Final audit only. |
| 7 | Compatibility matrix from backend | Done | Attachment controller supplies compatibility matrix. | Final audit only. |
| 7 | Primary attachment semantics | Done | Helper text added. | Final audit only. |
| 8 | Environment variables index/edit/delete/import | Done | `EnvironmentVariableController`, create/index/edit pages/tests. | Final audit only. |
| 8 | Overridable/source/slice provenance | Done | Variable forms/list expose overridable and source/slice. | Final audit only. |
| 8 | Secret/plain masking and copy | Done | Variable index reveal/copy controls. | Final audit only. |
| 9 | Server dangling fallback | Done | `servers/Show.vue` no longer has unconditional "Something else". | Final audit only. |
| 9 | Provisioning tied to real operations | Done | `servers/Show.vue` renders `OperationTimeline` for active `server_provision` operations and only uses cycling copy as a fallback when no provision operation exists. | Final audit only. |
| 9 | Server delete/decommission | Done | `servers.destroy` route/controller/UI. | Final audit only. |
| 9 | Firewall-rule UI | Done | Server show lists `firewall_rules` and includes add/remove controls; `servers.firewall-rules.store/destroy` routes and `ServerControllerTest` cover create/delete/validation. | Final audit only. |
| 9 | Credential persistence wording | Done | `servers/Show.vue` flash credential copy says Keystone uses its managed SSH key later and the password is informational for initial access only. | Final audit only. |
| 9 | Re-provision/heal action | Done | `servers.heal`, controller/test/UI. | Final audit only. |
| 9 | Service add gating explanation | Done | `servers/Show.vue` disables Add service during provisioning with `title="Services can be added after provisioning completes."`. | Final audit only. |
| 9 | Operations parent-child structure | Done | `servers/Show.vue` uses shared `OperationTimeline` for service/server operations; `OperationTimeline.vue` renders child operation counts and child operation links. | Final audit only. |
| 10 | Shared operation logs | Done | `components/operations/OperationTimeline.vue` used across pages. | Final audit only. |
| 10 | Operation detail page | Done | `operations.show`, page/tests. | Final audit only. |
| 10 | Retry/cancel/download logs | Done | `OperationController` retry/cancel/logs routes/pages/tests. | Final audit only. |
| 10 | Operation hash/kind/target columns | Done | Operation pages show hash/kind/target. | Final audit only. |
| 10 | Live progress | Done | Operations index/show use Inertia polling. | Final audit only. |
| 11 | Build artifact UI | Done | Build artifact pages and registry artifact usage. | Final audit only. |
| 11 | Registry usage/pre-deploy block | Done | Multi-server deploy blocked without registry; app and environment deploy surfaces both expose the precondition before deploy. | Final audit only. |
| 11 | Build strategy selector | Done | Environment edit exposes build strategy. | Final audit only. |
| 11 | Registry detail page | Done | `registries.show` page/tests. | Final audit only. |
| 12 | Domain / route configuration UI | Done | Gateway attachment create/edit has domain/path/TLS fields; deploy route rendering uses those values through `CaddyRouteRenderer`; dedicated `gateway.routes.index/create/store/edit/update/destroy` routes/pages manage domain route slices directly. | Final audit only. |
| 12 | TLS / certificate status view | Done | Route config stores certificate status; gateway cutover operations now include a `Check TLS certificate status` runtime step; shared `OperationTimeline.vue` displays per-step statuses. | Final audit only. |
| 12 | Caddyfile preview | Done | `CaddyRouteRenderer` feeds both deploy route scripts and `gatewayRoutePreviews` on `environments/Show.vue`; `EnvironmentControllerTest` covers rendered domain/path/upstream preview. | Final audit only. |
| 12 | Cutover visualization | Done | `environments/Show.vue` gateway cutover badges now match the actual operation sequence; `DeployEnvironmentJobTest` verifies route configure and gateway cutover child operations and step names. | Final audit only. |
| 13 | Endpoint surface | Done | Service endpoint card exists. | Final audit only. |
| 13 | Private-network membership view | Done | `ServerController@index` now supplies organisation networks with attached servers; `servers/Index.vue` renders private-network membership; `ServerControllerTest` covers network/server membership props. | Final audit only. |
| 14 | Dashboard recent ops/unhealthy services | Done | Dashboard controller/page includes recent operations and unhealthy services. | Final audit only. |
| 14 | Aggregated organisation health | Done | Organisation show health cards and roster/manage link. | Final audit only. |
| 15 | Script tag consistency | Done | Page-level scripts converted to `lang="ts"` based on prior search; `rg -n "<script setup(?! lang=\"ts\")" resources/js/pages resources/js/components -P` now returns no matches. | Final audit only. |
| 15 | Typed props | Done | `rg -n "<script setup(?! lang=\"ts\")" resources/js/pages resources/js/components -P` returns no matches after converting `ServerSelector.vue`; page/component setup scripts are now TypeScript. | Final audit only. |
| 15 | Breadcrumb depth | Done | Environment-scoped service breadcrumb added. | Final audit only. |
| 15 | Radio a11y | Done | `RadioButton.vue` supports `aria-describedby`; `servers/Create.vue` and `services/Create.vue` now attach explicit description IDs for radio options with descriptive copy. | Final audit only. |
| 15 | Colour-only status | Done | `ServiceCard.vue` renders status text alongside the color dot and now uses stronger light/dark status text colors. | Final audit only. |
| 15 | Application/server empty states | Done | `applications/Index.vue` and `servers/Index.vue` both render empty-state cards with primary CTAs. | Final audit only. |
| 16 | Backing routes/controllers list | Done | `php artisan route:list --path=environments` shows scheduler settings are covered through `environments.edit/update`; registry/source-provider index routes and server firewall-rule routes are covered; `php artisan route:list --name=gateway.routes` shows six dedicated gateway route CRUD routes. | Final audit only. |
### Suggested Next Queue
No implementation gaps remain in this tracker. Keep future work to fresh manual UI review findings or new product requirements.
### Verification Log
Recent targeted checks from this workstream:
| Command | Result | Scope |
|---|---|---|
| `php artisan test` | Passed, 231 tests / 1375 assertions | Full application regression suite after completing the UI review tracker. |
| `php artisan test tests/Feature/NavigationUiTest.php` | Passed, 3 tests / 38 assertions | Environment-first navigation context, environment index, and provider onboarding route. |
| `npm run build` | Passed | Frontend compilation after gateway cutover copy/badge alignment. |
| `php artisan test tests/Feature/DeployEnvironmentJobTest.php --filter='gateway'` | Passed, 1 test / 13 assertions | Gateway cutover sequence including TLS certificate status step. |
| `npm run build` | Passed | Frontend compilation after operation step-status display. |
| `vendor/bin/pint --dirty` | Passed, 71 files | PHP formatting after gateway cutover TLS step changes. |
| `npm run build` | Passed | Frontend compilation after `ServerSelector.vue` typed-props conversion. |
| `rg -n "<script setup(?! lang=\"ts\")" resources/js/pages resources/js/components -P` | No matches | Verified page/component setup scripts are TypeScript. |
| `php artisan test tests/Feature/OnboardingControllerTest.php` | Passed, 4 tests / 45 assertions | Onboarding next-step progression, registry/source/server/application gates, and deploy-key gate. |
| `vendor/bin/pint --dirty` | Passed, 70 files | PHP formatting after onboarding test adjustment. |
| `php artisan test tests/Feature/OrganisationMemberControllerTest.php` | Passed, 4 tests / 47 assertions | Organisation member roster plus pending invitation create/update/cancel. |
| `npm run build` | Passed | Frontend compilation after organisation invitation UI changes. |
| `vendor/bin/pint --dirty` | Passed, fixed 1 style issue across 66 dirty PHP files | PHP formatting after organisation invitation model/migration/controller/request/test changes. |
| `php artisan test tests/Feature/ServerControllerTest.php` | Passed, 4 tests / 62 assertions | Server heal/firewall coverage plus organisation-level private-network membership on servers index. |
| `npm run build` | Passed | Frontend compilation after servers index private-network membership UI changes. |
| `vendor/bin/pint --dirty` | Passed, 66 files | PHP formatting after server index/controller/test changes. |
| `npm run build` | Passed | Frontend compilation after radio `aria-describedby` associations. |
| `php artisan test tests/Feature/EnvironmentControllerTest.php` | Passed, 3 tests / 25 assertions | Environment show, including rendered Caddyfile preview for gateway attachments. |
| `php artisan test tests/Feature/DeployEnvironmentJobTest.php --filter='gateway'` | Passed, 1 test / 13 assertions | Gateway deploy script still creates route configure and cutover operations after shared Caddy renderer change. |
| `npm run build` | Passed | Frontend compilation after Caddyfile preview UI changes. |
| `vendor/bin/pint --dirty` | Passed, 61 files | PHP formatting after Caddy renderer/controller/job/test changes. |
| `npm run build` | Passed | Frontend compilation after `ServiceCard.vue` typed props and status contrast changes. |
| `php artisan test tests/Feature/ResourceDetailUiTest.php --filter='creates and shows service slices'` | Passed, 1 test / 41 assertions | Dedicated service slice index, create, detail, and independent operations coverage. |
| `npm run build` | Passed | Frontend compilation after service slice index page/link changes. |
| `vendor/bin/pint --dirty` | Passed, 59 files | PHP formatting after service slice route/controller/test changes. |
| `php artisan route:list --path=environments` | Passed, 25 environment-related routes shown | Confirmed scheduler settings are covered by environment edit/update rather than a separate scheduler sub-resource. |
| `php artisan route:list --name=gateway.routes` | Passed, 6 routes shown | Confirmed dedicated gateway route CRUD route surface. |
| `php artisan test tests/Feature/EnvironmentAttachmentControllerTest.php` | Passed, 4 tests / 100 assertions | Managed attachments plus dedicated gateway route create/list/edit/update/delete coverage. |
| `npm run build` | Passed | Frontend compilation after gateway route CRUD pages and environment link changes. |
| `vendor/bin/pint --dirty` | Passed, 69 files | PHP formatting after gateway route controller/request/route/test changes. |
| `php artisan test tests/Feature/RegistryControllerTest.php tests/Feature/CrudUiTest.php` | Passed, 8 tests / 121 assertions | Registry and source-provider index routes plus CRUD coverage. |
| `php artisan test tests/Feature/ServerControllerTest.php` | Passed, 3 tests / 46 assertions | Server heal and firewall-rule create/delete/validation. |
| `php artisan test tests/Feature/ApplicationControllerTest.php tests/Feature/CrudUiTest.php` | Passed, 11 tests / 111 assertions | Repository type selector validation/persistence and application CRUD. |
| `php artisan test tests/Feature/EnvironmentDeploymentControllerTest.php` | Passed, 4 tests / 22 assertions | Registry precondition and target commit deployment. |
| `php artisan test tests/Feature/ServiceControllerTest.php tests/Feature/EnvironmentVariableControllerTest.php` | Passed, 18 tests / 134 assertions | Environment-scoped services and variable management. |
| `npm run build` | Passed in recent slices | Frontend compilation after Vue changes. |
| `vendor/bin/pint --dirty` | Passed in recent slices | PHP formatting. |

View File

@@ -1,19 +0,0 @@
import prettier from 'eslint-config-prettier';
import vue from 'eslint-plugin-vue';
import { defineConfigWithVueTs, vueTsConfigs } from '@vue/eslint-config-typescript';
export default defineConfigWithVueTs(
vue.configs['flat/essential'],
vueTsConfigs.recommended,
{
ignores: ['vendor', 'node_modules', 'public', 'bootstrap/ssr', 'tailwind.config.js', 'resources/js/components/ui/*'],
},
{
rules: {
'vue/multi-word-component-names': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
},
prettier,
);

View File

@@ -1,8 +1,10 @@
{ {
"tools": { "$schema": "https://opencode.ai/config.json",
"mcp": {
"laravel-boost": { "laravel-boost": {
"command": "php", "type": "local",
"args": ["artisan", "boost:mcp"] "command": ["php", "artisan", "boost:mcp"],
"enabled": true
} }
} }
} }

View File

@@ -5,21 +5,15 @@
"build": "vite build", "build": "vite build",
"build:ssr": "vite build && vite build --ssr", "build:ssr": "vite build && vite build --ssr",
"dev": "vite", "dev": "vite",
"format": "prettier --write resources/", "format": "oxfmt resources/",
"format:check": "prettier --check resources/", "format:check": "oxfmt --check resources/",
"lint": "eslint . --fix" "lint": "oxlint --fix",
"lint:check": "oxlint"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.19.0",
"@types/node": "^22.13.5", "@types/node": "^22.13.5",
"@vue/eslint-config-typescript": "^14.3.0", "oxfmt": "^0.49.0",
"eslint": "^9.17.0", "oxlint": "^1.64.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-vue": "^9.32.0",
"prettier": "^3.4.2",
"prettier-plugin-organize-imports": "^4.1.0",
"prettier-plugin-tailwindcss": "^0.6.9",
"typescript-eslint": "^8.23.0",
"vue-tsc": "^2.2.4" "vue-tsc": "^2.2.4"
}, },
"dependencies": { "dependencies": {

5011
phpstan-baseline.neon Normal file

File diff suppressed because it is too large Load Diff

14
phpstan.neon Normal file
View File

@@ -0,0 +1,14 @@
includes:
- vendor/larastan/larastan/extension.neon
- vendor/mrpunyapal/peststan/extension.neon
- phpstan-baseline.neon
parameters:
peststan:
testCaseClass: Tests\TestCase
pestConfigFiles: [tests/Pest.php]
level: max
paths:
- app
- routes
- tests

View File

@@ -16,6 +16,19 @@
<include> <include>
<directory>app</directory> <directory>app</directory>
</include> </include>
<exclude>
<directory>app/Console</directory>
<directory>app/Data</directory>
<directory>app/Http/Integrations</directory>
<file>app/Actions/Servers/SyncUfwRules.php</file>
<file>app/Actions/FirewallRules/InstallFirewallRule.php</file>
<file>app/Actions/FirewallRules/UninstallFirewallRule.php</file>
<file>app/Services/Operations/SshRemoteCommandRunner.php</file>
<file>app/Services/ServerProviders/HetznerService.php</file>
<file>app/Jobs/Servers/ProvisionServer.php</file>
<file>app/Jobs/Servers/WaitForServerToConnect.php</file>
<file>app/Actions/Applications/GenerateDeployKey.php</file>
</exclude>
</source> </source>
<php> <php>
<env name="APP_ENV" value="testing"/> <env name="APP_ENV" value="testing"/>

View File

@@ -5,7 +5,8 @@
body, body,
html { html {
--font-sans: --font-sans:
'Instrument Sans', ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; "Instrument Sans", ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji",
"Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
} }
@layer base { @layer base {

View File

@@ -1,14 +1,14 @@
import '../css/app.css'; import "../css/app.css";
import { createInertiaApp } from '@inertiajs/vue3'; import { createInertiaApp } from "@inertiajs/vue3";
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers'; import { resolvePageComponent } from "laravel-vite-plugin/inertia-helpers";
import type { DefineComponent } from 'vue'; import type { DefineComponent } from "vue";
import { createApp, h } from 'vue'; import { createApp, h } from "vue";
import { ZiggyVue } from 'ziggy-js'; import { ZiggyVue } from "ziggy-js";
import { initializeTheme } from './composables/useAppearance'; import { initializeTheme } from "./composables/useAppearance";
// Extend ImportMeta interface for Vite... // Extend ImportMeta interface for Vite...
declare module 'vite/client' { declare module "vite/client" {
interface ImportMetaEnv { interface ImportMetaEnv {
readonly VITE_APP_NAME: string; readonly VITE_APP_NAME: string;
[key: string]: string | boolean | undefined; [key: string]: string | boolean | undefined;
@@ -20,11 +20,15 @@ declare module 'vite/client' {
} }
} }
const appName = import.meta.env.VITE_APP_NAME || 'Laravel'; const appName = import.meta.env.VITE_APP_NAME || "Laravel";
createInertiaApp({ createInertiaApp({
title: (title) => `${title} - ${appName}`, title: (title) => `${title} - ${appName}`,
resolve: (name) => resolvePageComponent(`./pages/${name}.vue`, import.meta.glob<DefineComponent>('./pages/**/*.vue')), resolve: (name) =>
resolvePageComponent(
`./pages/${name}.vue`,
import.meta.glob<DefineComponent>("./pages/**/*.vue"),
),
setup({ el, App, props, plugin }) { setup({ el, App, props, plugin }) {
createApp({ render: () => h(App, props) }) createApp({ render: () => h(App, props) })
.use(plugin) .use(plugin)
@@ -32,7 +36,7 @@ createInertiaApp({
.mount(el); .mount(el);
}, },
progress: { progress: {
color: '#4B5563', color: "#4B5563",
}, },
}); });

View File

@@ -1,9 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
import { SidebarInset } from '@/components/ui/sidebar'; import { SidebarInset } from "@/components/ui/sidebar";
import { computed } from 'vue'; import { computed } from "vue";
interface Props { interface Props {
variant?: 'header' | 'sidebar'; variant?: "header" | "sidebar";
class?: string; class?: string;
} }
@@ -15,7 +15,11 @@ const className = computed(() => props.class);
<SidebarInset v-if="props.variant === 'sidebar'" :class="className"> <SidebarInset v-if="props.variant === 'sidebar'" :class="className">
<slot /> <slot />
</SidebarInset> </SidebarInset>
<main v-else class="mx-auto flex h-full w-full max-w-7xl flex-1 flex-col gap-4 rounded-xl" :class="className"> <main
v-else
class="mx-auto flex h-full w-full max-w-7xl flex-1 flex-col gap-4 rounded-xl"
:class="className"
>
<slot /> <slot />
</main> </main>
</template> </template>

View File

@@ -1,25 +1,38 @@
<script setup lang="ts"> <script setup lang="ts">
import AppLogo from '@/components/AppLogo.vue'; import AppLogo from "@/components/AppLogo.vue";
import AppLogoIcon from '@/components/AppLogoIcon.vue'; import AppLogoIcon from "@/components/AppLogoIcon.vue";
import Breadcrumbs from '@/components/Breadcrumbs.vue'; import Breadcrumbs from "@/components/Breadcrumbs.vue";
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from '@/components/ui/button'; import { Button } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { import {
NavigationMenu, NavigationMenu,
NavigationMenuItem, NavigationMenuItem,
NavigationMenuLink, NavigationMenuLink,
NavigationMenuList, NavigationMenuList,
navigationMenuTriggerStyle, navigationMenuTriggerStyle,
} from '@/components/ui/navigation-menu'; } from "@/components/ui/navigation-menu";
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet'; import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import UserMenuContent from '@/components/UserMenuContent.vue'; import UserMenuContent from "@/components/UserMenuContent.vue";
import { getInitials } from '@/composables/useInitials'; import { getInitials } from "@/composables/useInitials";
import type { BreadcrumbItem, NavItem } from '@/types'; import type { BreadcrumbItem, NavItem } from "@/types";
import { Link, usePage } from '@inertiajs/vue3'; import { Link, usePage } from "@inertiajs/vue3";
import { AppWindowIcon, BoltIcon, Menu, Search, ServerIcon } from 'lucide-vue-next'; import {
import { computed } from 'vue'; AppWindowIcon,
BoltIcon,
BoxesIcon,
ClipboardListIcon,
Menu,
Search,
ServerIcon,
WorkflowIcon,
} from "lucide-vue-next";
import { computed } from "vue";
interface Props { interface Props {
breadcrumbs?: BreadcrumbItem[]; breadcrumbs?: BreadcrumbItem[];
@@ -32,10 +45,13 @@ const props = withDefaults(defineProps<Props>(), {
const page = usePage(); const page = usePage();
const auth = computed(() => page.props.auth); const auth = computed(() => page.props.auth);
const isCurrentRoute = computed(() => (url: string) => page.url === url); const isCurrentRoute = computed(() => (url: string) => page.url === url || page.url.startsWith(`${url}/`));
const activeItemStyles = computed( const activeItemStyles = computed(
() => (url: string) => (isCurrentRoute.value(url) ? 'text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100' : ''), () => (url: string) =>
isCurrentRoute.value(url)
? "text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100"
: "",
); );
const mainNavItems: NavItem[] = [ const mainNavItems: NavItem[] = [
@@ -47,27 +63,71 @@ const mainNavItems: NavItem[] = [
]; ];
if (page.props.organisation) { if (page.props.organisation) {
const organisationId = page.props?.organisation?.id;
mainNavItems.push({ mainNavItems.push({
title: page.props.organisation.name, title: page.props.organisation.name,
href: new URL(route('organisations.show', { href: new URL(
organisation: page.props?.organisation?.id route("organisations.show", {
})).pathname, organisation: organisationId,
}),
).pathname,
icon: BoltIcon, icon: BoltIcon,
}); });
mainNavItems.push({ mainNavItems.push({
title: 'Applications', title: "Environments",
href: new URL(route('applications.index', { href: new URL(
organisation: page.props?.organisation?.id route("environments.index", {
})).pathname, organisation: organisationId,
}),
).pathname,
icon: BoxesIcon,
});
mainNavItems.push({
title: "Applications",
href: new URL(
route("applications.index", {
organisation: organisationId,
}),
).pathname,
icon: AppWindowIcon, icon: AppWindowIcon,
}); });
mainNavItems.push({ mainNavItems.push({
title: 'Servers', title: "Servers",
href: new URL(route('servers.index', { href: new URL(
organisation: page.props?.organisation?.id route("servers.index", {
})).pathname, organisation: organisationId,
}),
).pathname,
icon: ServerIcon, icon: ServerIcon,
}) });
mainNavItems.push({
title: "Operations",
href: new URL(
route("operations.index", {
organisation: organisationId,
}),
).pathname,
icon: WorkflowIcon,
});
if (
page.props.organisation.providers_count === 0 ||
page.props.organisation.source_providers_count === 0 ||
page.props.organisation.registries_count === 0 ||
page.props.organisation.servers_count === 0 ||
page.props.organisation.applications_count === 0
) {
mainNavItems.push({
title: "Onboarding",
href: new URL(
route("onboarding.show", {
organisation: organisationId,
}),
).pathname,
icon: ClipboardListIcon,
});
}
} }
const rightNavItems: NavItem[] = [ const rightNavItems: NavItem[] = [
@@ -99,7 +159,9 @@ const rightNavItems: NavItem[] = [
<SheetContent side="left" class="w-[300px] p-6"> <SheetContent side="left" class="w-[300px] p-6">
<SheetTitle class="sr-only">Navigation Menu</SheetTitle> <SheetTitle class="sr-only">Navigation Menu</SheetTitle>
<SheetHeader class="flex justify-start text-left"> <SheetHeader class="flex justify-start text-left">
<AppLogoIcon class="size-6 fill-current text-black dark:text-white" /> <AppLogoIcon
class="size-6 fill-current text-black dark:text-white"
/>
</SheetHeader> </SheetHeader>
<div class="flex h-full flex-1 flex-col justify-between space-y-4 py-6"> <div class="flex h-full flex-1 flex-col justify-between space-y-4 py-6">
<nav class="-mx-3 space-y-1"> <nav class="-mx-3 space-y-1">
@@ -110,7 +172,11 @@ const rightNavItems: NavItem[] = [
class="flex items-center gap-x-3 rounded-lg px-3 py-2 text-sm font-medium hover:bg-accent" class="flex items-center gap-x-3 rounded-lg px-3 py-2 text-sm font-medium hover:bg-accent"
:class="activeItemStyles(item.href)" :class="activeItemStyles(item.href)"
> >
<component v-if="item.icon" :is="item.icon" class="h-5 w-5" /> <component
v-if="item.icon"
:is="item.icon"
class="h-5 w-5"
/>
{{ item.title }} {{ item.title }}
</Link> </Link>
</nav> </nav>
@@ -123,7 +189,11 @@ const rightNavItems: NavItem[] = [
rel="noopener noreferrer" rel="noopener noreferrer"
class="flex items-center space-x-2 text-sm font-medium" class="flex items-center space-x-2 text-sm font-medium"
> >
<component v-if="item.icon" :is="item.icon" class="h-5 w-5" /> <component
v-if="item.icon"
:is="item.icon"
class="h-5 w-5"
/>
<span>{{ item.title }}</span> <span>{{ item.title }}</span>
</a> </a>
</div> </div>
@@ -140,12 +210,24 @@ const rightNavItems: NavItem[] = [
<div class="hidden h-full lg:flex lg:flex-1"> <div class="hidden h-full lg:flex lg:flex-1">
<NavigationMenu class="ml-10 flex h-full items-stretch"> <NavigationMenu class="ml-10 flex h-full items-stretch">
<NavigationMenuList class="flex h-full items-stretch space-x-2"> <NavigationMenuList class="flex h-full items-stretch space-x-2">
<NavigationMenuItem v-for="(item, index) in mainNavItems" :key="index" class="relative flex h-full items-center"> <NavigationMenuItem
v-for="(item, index) in mainNavItems"
:key="index"
class="relative flex h-full items-center"
>
<Link :href="item.href"> <Link :href="item.href">
<NavigationMenuLink <NavigationMenuLink
:class="[navigationMenuTriggerStyle(), activeItemStyles(item.href), 'h-9 cursor-pointer px-3']" :class="[
navigationMenuTriggerStyle(),
activeItemStyles(item.href),
'h-9 cursor-pointer px-3',
]"
> >
<component v-if="item.icon" :is="item.icon" class="mr-2 h-4 w-4" /> <component
v-if="item.icon"
:is="item.icon"
class="mr-2 h-4 w-4"
/>
{{ item.title }} {{ item.title }}
</NavigationMenuLink> </NavigationMenuLink>
</Link> </Link>
@@ -169,10 +251,22 @@ const rightNavItems: NavItem[] = [
<TooltipProvider :delay-duration="0"> <TooltipProvider :delay-duration="0">
<Tooltip> <Tooltip>
<TooltipTrigger> <TooltipTrigger>
<Button variant="ghost" size="icon" as-child class="group h-9 w-9 cursor-pointer"> <Button
<a :href="item.href" target="_blank" rel="noopener noreferrer"> variant="ghost"
size="icon"
as-child
class="group h-9 w-9 cursor-pointer"
>
<a
:href="item.href"
target="_blank"
rel="noopener noreferrer"
>
<span class="sr-only">{{ item.title }}</span> <span class="sr-only">{{ item.title }}</span>
<component :is="item.icon" class="size-5 opacity-80 group-hover:opacity-100" /> <component
:is="item.icon"
class="size-5 opacity-80 group-hover:opacity-100"
/>
</a> </a>
</Button> </Button>
</TooltipTrigger> </TooltipTrigger>
@@ -193,8 +287,14 @@ const rightNavItems: NavItem[] = [
class="relative size-10 w-auto rounded-full p-1 focus-within:ring-2 focus-within:ring-primary" class="relative size-10 w-auto rounded-full p-1 focus-within:ring-2 focus-within:ring-primary"
> >
<Avatar class="size-8 overflow-hidden rounded-full"> <Avatar class="size-8 overflow-hidden rounded-full">
<AvatarImage v-if="auth.user.avatar" :src="auth.user.avatar" :alt="auth.user.name" /> <AvatarImage
<AvatarFallback class="rounded-lg bg-neutral-200 font-semibold text-black dark:bg-neutral-700 dark:text-white"> v-if="auth.user.avatar"
:src="auth.user.avatar"
:alt="auth.user.name"
/>
<AvatarFallback
class="rounded-lg bg-neutral-200 font-semibold text-black dark:bg-neutral-700 dark:text-white"
>
{{ getInitials(auth.user?.name) }} {{ getInitials(auth.user?.name) }}
</AvatarFallback> </AvatarFallback>
</Avatar> </Avatar>
@@ -208,8 +308,13 @@ const rightNavItems: NavItem[] = [
</div> </div>
</div> </div>
<div v-if="props.breadcrumbs.length > 1" class="flex w-full border-b border-sidebar-border/70"> <div
<div class="mx-auto flex h-12 w-full items-center justify-start px-4 text-neutral-500 md:max-w-7xl"> v-if="props.breadcrumbs.length > 1"
class="flex w-full border-b border-sidebar-border/70"
>
<div
class="mx-auto flex h-12 w-full items-center justify-start px-4 text-neutral-500 md:max-w-7xl"
>
<Breadcrumbs :breadcrumbs="breadcrumbs" /> <Breadcrumbs :breadcrumbs="breadcrumbs" />
</div> </div>
</div> </div>

View File

@@ -1,9 +1,11 @@
<script setup lang="ts"> <script setup lang="ts">
import AppLogoIcon from '@/components/AppLogoIcon.vue'; import AppLogoIcon from "@/components/AppLogoIcon.vue";
</script> </script>
<template> <template>
<div class="flex aspect-square size-8 items-center justify-center rounded-md bg-sidebar-primary text-sidebar-primary-foreground"> <div
class="flex aspect-square size-8 items-center justify-center rounded-md bg-sidebar-primary text-sidebar-primary-foreground"
>
<AppLogoIcon class="size-5 fill-current text-white dark:text-black" /> <AppLogoIcon class="size-5 fill-current text-white dark:text-black" />
</div> </div>
<div class="ml-1 grid flex-1 text-left text-sm"> <div class="ml-1 grid flex-1 text-left text-sm">

View File

@@ -1,13 +1,13 @@
<script setup lang="ts"> <script setup lang="ts">
import { WavesIcon } from 'lucide-vue-next'; import { WavesIcon } from "lucide-vue-next";
import type { HTMLAttributes } from 'vue'; import type { HTMLAttributes } from "vue";
defineOptions({ defineOptions({
inheritAttrs: false, inheritAttrs: false,
}); });
interface Props { interface Props {
className?: HTMLAttributes['class']; className?: HTMLAttributes["class"];
} }
defineProps<Props>(); defineProps<Props>();

View File

@@ -1,9 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
import { SidebarProvider } from '@/components/ui/sidebar'; import { SidebarProvider } from "@/components/ui/sidebar";
import { onMounted, ref } from 'vue'; import { onMounted, ref } from "vue";
interface Props { interface Props {
variant?: 'header' | 'sidebar'; variant?: "header" | "sidebar";
} }
defineProps<Props>(); defineProps<Props>();
@@ -11,12 +11,12 @@ defineProps<Props>();
const isOpen = ref(true); const isOpen = ref(true);
onMounted(() => { onMounted(() => {
isOpen.value = localStorage.getItem('sidebar') !== 'false'; isOpen.value = localStorage.getItem("sidebar") !== "false";
}); });
const handleSidebarChange = (open: boolean) => { const handleSidebarChange = (open: boolean) => {
isOpen.value = open; isOpen.value = open;
localStorage.setItem('sidebar', String(open)); localStorage.setItem("sidebar", String(open));
}; };
</script> </script>
@@ -24,7 +24,12 @@ const handleSidebarChange = (open: boolean) => {
<div v-if="variant === 'header'" class="flex min-h-screen w-full flex-col"> <div v-if="variant === 'header'" class="flex min-h-screen w-full flex-col">
<slot /> <slot />
</div> </div>
<SidebarProvider v-else :default-open="isOpen" :open="isOpen" @update:open="handleSidebarChange"> <SidebarProvider
v-else
:default-open="isOpen"
:open="isOpen"
@update:open="handleSidebarChange"
>
<slot /> <slot />
</SidebarProvider> </SidebarProvider>
</template> </template>

View File

@@ -1,17 +1,25 @@
<script setup lang="ts"> <script setup lang="ts">
import NavFooter from '@/components/NavFooter.vue'; import NavFooter from "@/components/NavFooter.vue";
import NavMain from '@/components/NavMain.vue'; import NavMain from "@/components/NavMain.vue";
import NavUser from '@/components/NavUser.vue'; import NavUser from "@/components/NavUser.vue";
import { Sidebar, SidebarContent, SidebarFooter, SidebarHeader, SidebarMenu, SidebarMenuButton, SidebarMenuItem } from '@/components/ui/sidebar'; import {
import { type NavItem } from '@/types'; Sidebar,
import { Link, usePage } from '@inertiajs/vue3'; SidebarContent,
import { LayoutGrid, Server } from 'lucide-vue-next'; SidebarFooter,
import AppLogo from './AppLogo.vue'; SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar";
import { type NavItem } from "@/types";
import { Link, usePage } from "@inertiajs/vue3";
import { AppWindow, Boxes, ClipboardList, LayoutGrid, Server, Workflow } from "lucide-vue-next";
import AppLogo from "./AppLogo.vue";
const mainNavItems: NavItem[] = [ const mainNavItems: NavItem[] = [
{ {
title: 'Dashboard', title: "Dashboard",
href: '/dashboard', href: "/dashboard",
icon: LayoutGrid, icon: LayoutGrid,
}, },
]; ];
@@ -20,12 +28,49 @@ const organisation = usePage().props.organisation;
if (organisation) { if (organisation) {
mainNavItems.push({ mainNavItems.push({
title: 'Servers', title: "Environments",
href: route('servers.index', { href: route("environments.index", {
organisation: organisation.id,
}),
icon: Boxes,
});
mainNavItems.push({
title: "Applications",
href: route("applications.index", {
organisation: organisation.id,
}),
icon: AppWindow,
});
mainNavItems.push({
title: "Servers",
href: route("servers.index", {
organisation: organisation.id, organisation: organisation.id,
}), }),
icon: Server, icon: Server,
}); });
mainNavItems.push({
title: "Operations",
href: route("operations.index", {
organisation: organisation.id,
}),
icon: Workflow,
});
if (
organisation.providers_count === 0 ||
organisation.source_providers_count === 0 ||
organisation.registries_count === 0 ||
organisation.servers_count === 0 ||
organisation.applications_count === 0
) {
mainNavItems.push({
title: "Onboarding",
href: route("onboarding.show", {
organisation: organisation.id,
}),
icon: ClipboardList,
});
}
} }
const footerNavItems: NavItem[] = []; const footerNavItems: NavItem[] = [];

View File

@@ -1,11 +1,16 @@
<script setup lang="ts"> <script setup lang="ts">
import Breadcrumbs from '@/components/Breadcrumbs.vue'; import Breadcrumbs from "@/components/Breadcrumbs.vue";
import { SidebarTrigger } from '@/components/ui/sidebar'; import { SidebarTrigger } from "@/components/ui/sidebar";
import type { BreadcrumbItemType } from '@/types'; import type { BreadcrumbItemType } from "@/types";
import { Link, usePage } from '@inertiajs/vue3'; import { Link, usePage } from "@inertiajs/vue3";
import { ChevronsUpDown } from 'lucide-vue-next'; import { ChevronsUpDown } from "lucide-vue-next";
import { Button } from './ui/button'; import { Button } from "./ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from './ui/dropdown-menu'; import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "./ui/dropdown-menu";
defineProps<{ defineProps<{
breadcrumbs?: BreadcrumbItemType[]; breadcrumbs?: BreadcrumbItemType[];
@@ -28,11 +33,15 @@ const environment = usePage().props.environment ?? null;
<div class="gap-0.25 ml-auto flex items-center"> <div class="gap-0.25 ml-auto flex items-center">
<Button <Button
:as="organisation ? Link : 'button'" :as="organisation ? Link : 'button'"
:href="organisation ? route('organisations.show', { organisation: organisation?.id }) : null" :href="
organisation
? route('organisations.show', { organisation: organisation?.id })
: null
"
variant="ghost" variant="ghost"
size="xs" size="xs"
> >
{{ organisation?.name ?? 'Select Organisation' }} {{ organisation?.name ?? "Select Organisation" }}
</Button> </Button>
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger :as="Button" size="iconxs" variant="ghost"> <DropdownMenuTrigger :as="Button" size="iconxs" variant="ghost">
@@ -41,6 +50,7 @@ const environment = usePage().props.environment ?? null;
<DropdownMenuContent> <DropdownMenuContent>
<DropdownMenuItem <DropdownMenuItem
v-for="org in $page.props.auth.user?.organisations" v-for="org in $page.props.auth.user?.organisations"
:key="org.id"
:as="Link" :as="Link"
:href="route('organisations.show', { organisation: org.id })" :href="route('organisations.show', { organisation: org.id })"
>{{ org.name }}</DropdownMenuItem >{{ org.name }}</DropdownMenuItem
@@ -53,22 +63,38 @@ const environment = usePage().props.environment ?? null;
:disabled="!organisation?.applications?.length" :disabled="!organisation?.applications?.length"
:as="application ? Link : 'button'" :as="application ? Link : 'button'"
:href=" :href="
application ? route('applications.show', { organisation: application.organisation_id, application: application.id }) : null application
? route('applications.show', {
organisation: application.organisation_id,
application: application.id,
})
: null
" "
variant="ghost" variant="ghost"
size="xs" size="xs"
> >
{{ application?.name ?? 'Application' }} {{ application?.name ?? "Application" }}
</Button> </Button>
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger :as="Button" size="iconxs" variant="ghost" :disabled="!organisation?.applications?.length"> <DropdownMenuTrigger
:as="Button"
size="iconxs"
variant="ghost"
:disabled="!organisation?.applications?.length"
>
<ChevronsUpDown class="size-3" /> <ChevronsUpDown class="size-3" />
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent> <DropdownMenuContent>
<DropdownMenuItem <DropdownMenuItem
v-for="app in organisation?.applications" v-for="app in organisation?.applications"
:key="app.id"
:as="Link" :as="Link"
:href="route('applications.show', { organisation: app.organisation_id, application: app.id })" :href="
route('applications.show', {
organisation: app.organisation_id,
application: app.id,
})
"
>{{ app.name }}</DropdownMenuItem >{{ app.name }}</DropdownMenuItem
> >
</DropdownMenuContent> </DropdownMenuContent>
@@ -90,15 +116,21 @@ const environment = usePage().props.environment ?? null;
variant="ghost" variant="ghost"
size="xs" size="xs"
> >
{{ environment?.name ?? 'Environment' }} {{ environment?.name ?? "Environment" }}
</Button> </Button>
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger :as="Button" size="iconxs" variant="ghost" :disabled="!application?.environments?.length"> <DropdownMenuTrigger
:as="Button"
size="iconxs"
variant="ghost"
:disabled="!application?.environments?.length"
>
<ChevronsUpDown class="size-3" /> <ChevronsUpDown class="size-3" />
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent> <DropdownMenuContent>
<DropdownMenuItem <DropdownMenuItem
v-for="env in application?.environments" v-for="env in application?.environments"
:key="env.id"
:as="Link" :as="Link"
:href=" :href="
route('environments.show', { route('environments.show', {

View File

@@ -1,24 +1,29 @@
<script setup lang="ts"> <script setup lang="ts">
import { useAppearance } from '@/composables/useAppearance'; import { useAppearance } from "@/composables/useAppearance";
import { Monitor, Moon, Sun } from 'lucide-vue-next'; import { Monitor, Moon, Sun } from "lucide-vue-next";
interface Props { interface Props {
class?: string; class?: string;
} }
const { class: containerClass = '' } = defineProps<Props>(); const { class: containerClass = "" } = defineProps<Props>();
const { appearance, updateAppearance } = useAppearance(); const { appearance, updateAppearance } = useAppearance();
const tabs = [ const tabs = [
{ value: 'light', Icon: Sun, label: 'Light' }, { value: "light", Icon: Sun, label: "Light" },
{ value: 'dark', Icon: Moon, label: 'Dark' }, { value: "dark", Icon: Moon, label: "Dark" },
{ value: 'system', Icon: Monitor, label: 'System' }, { value: "system", Icon: Monitor, label: "System" },
] as const; ] as const;
</script> </script>
<template> <template>
<div :class="['inline-flex gap-1 rounded-lg bg-neutral-100 p-1 dark:bg-neutral-800', containerClass]"> <div
:class="[
'inline-flex gap-1 rounded-lg bg-neutral-100 p-1 dark:bg-neutral-800',
containerClass,
]"
>
<button <button
v-for="{ value, Icon, label } in tabs" v-for="{ value, Icon, label } in tabs"
:key="value" :key="value"

View File

@@ -1,6 +1,13 @@
<script setup lang="ts"> <script setup lang="ts">
import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator } from '@/components/ui/breadcrumb'; import {
import { Link } from '@inertiajs/vue3'; Breadcrumb,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
import { Link } from "@inertiajs/vue3";
interface BreadcrumbItem { interface BreadcrumbItem {
title: string; title: string;

View File

@@ -1,11 +1,11 @@
<script setup lang="ts"> <script setup lang="ts">
import { useForm } from '@inertiajs/vue3'; import { useForm } from "@inertiajs/vue3";
import { ref } from 'vue'; import { ref } from "vue";
// Components // Components
import HeadingSmall from '@/components/HeadingSmall.vue'; import HeadingSmall from "@/components/HeadingSmall.vue";
import InputError from '@/components/InputError.vue'; import InputError from "@/components/InputError.vue";
import { Button } from '@/components/ui/button'; import { Button } from "@/components/ui/button";
import { import {
Dialog, Dialog,
DialogClose, DialogClose,
@@ -15,20 +15,20 @@ import {
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
DialogTrigger, DialogTrigger,
} from '@/components/ui/dialog'; } from "@/components/ui/dialog";
import { Input } from '@/components/ui/input'; import { Input } from "@/components/ui/input";
import { Label } from '@/components/ui/label'; import { Label } from "@/components/ui/label";
const passwordInput = ref<HTMLInputElement | null>(null); const passwordInput = ref<HTMLInputElement | null>(null);
const form = useForm({ const form = useForm({
password: '', password: "",
}); });
const deleteUser = (e: Event) => { const deleteUser = (e: Event) => {
e.preventDefault(); e.preventDefault();
form.delete(route('profile.destroy'), { form.delete(route("profile.destroy"), {
preserveScroll: true, preserveScroll: true,
onSuccess: () => closeModal(), onSuccess: () => closeModal(),
onError: () => passwordInput.value?.focus(), onError: () => passwordInput.value?.focus(),
@@ -44,8 +44,13 @@ const closeModal = () => {
<template> <template>
<div class="space-y-6"> <div class="space-y-6">
<HeadingSmall title="Delete account" description="Delete your account and all of its resources" /> <HeadingSmall
<div class="space-y-4 rounded-lg border border-red-100 bg-red-50 p-4 dark:border-red-200/10 dark:bg-red-700/10"> title="Delete account"
description="Delete your account and all of its resources"
/>
<div
class="space-y-4 rounded-lg border border-red-100 bg-red-50 p-4 dark:border-red-200/10 dark:bg-red-700/10"
>
<div class="relative space-y-0.5 text-red-600 dark:text-red-100"> <div class="relative space-y-0.5 text-red-600 dark:text-red-100">
<p class="font-medium">Warning</p> <p class="font-medium">Warning</p>
<p class="text-sm">Please proceed with caution, this cannot be undone.</p> <p class="text-sm">Please proceed with caution, this cannot be undone.</p>
@@ -59,14 +64,22 @@ const closeModal = () => {
<DialogHeader class="space-y-3"> <DialogHeader class="space-y-3">
<DialogTitle>Are you sure you want to delete your account?</DialogTitle> <DialogTitle>Are you sure you want to delete your account?</DialogTitle>
<DialogDescription> <DialogDescription>
Once your account is deleted, all of its resources and data will also be permanently deleted. Please enter your Once your account is deleted, all of its resources and data will
password to confirm you would like to permanently delete your account. also be permanently deleted. Please enter your password to confirm
you would like to permanently delete your account.
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<div class="grid gap-2"> <div class="grid gap-2">
<Label for="password" class="sr-only">Password</Label> <Label for="password" class="sr-only">Password</Label>
<Input id="password" type="password" name="password" ref="passwordInput" v-model="form.password" placeholder="Password" /> <Input
id="password"
type="password"
name="password"
ref="passwordInput"
v-model="form.password"
placeholder="Password"
/>
<InputError :message="form.errors.password" /> <InputError :message="form.errors.password" />
</div> </div>

View File

@@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { cn } from '@/lib/utils'; import { cn } from "@/lib/utils";
import * as icons from 'lucide-vue-next'; import * as icons from "lucide-vue-next";
import { computed } from 'vue'; import { computed } from "vue";
interface Props { interface Props {
name: string; name: string;
@@ -12,12 +12,12 @@ interface Props {
} }
const props = withDefaults(defineProps<Props>(), { const props = withDefaults(defineProps<Props>(), {
class: '', class: "",
size: 16, size: 16,
strokeWidth: 2, strokeWidth: 2,
}); });
const className = computed(() => cn('h-4 w-4', props.class)); const className = computed(() => cn("h-4 w-4", props.class));
const icon = computed(() => { const icon = computed(() => {
const iconName = props.name.charAt(0).toUpperCase() + props.name.slice(1); const iconName = props.name.charAt(0).toUpperCase() + props.name.slice(1);
@@ -26,5 +26,11 @@ const icon = computed(() => {
</script> </script>
<template> <template>
<component :is="icon" :class="className" :size="size" :stroke-width="strokeWidth" :color="color" /> <component
:is="icon"
:class="className"
:size="size"
:stroke-width="strokeWidth"
:color="color"
/>
</template> </template>

View File

@@ -1,6 +1,12 @@
<script setup lang="ts"> <script setup lang="ts">
import { SidebarGroup, SidebarGroupContent, SidebarMenu, SidebarMenuButton, SidebarMenuItem } from '@/components/ui/sidebar'; import {
import { type NavItem } from '@/types'; SidebarGroup,
SidebarGroupContent,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar";
import { type NavItem } from "@/types";
interface Props { interface Props {
items: NavItem[]; items: NavItem[];
@@ -15,7 +21,10 @@ defineProps<Props>();
<SidebarGroupContent> <SidebarGroupContent>
<SidebarMenu> <SidebarMenu>
<SidebarMenuItem v-for="item in items" :key="item.title"> <SidebarMenuItem v-for="item in items" :key="item.title">
<SidebarMenuButton class="text-neutral-600 hover:text-neutral-800 dark:text-neutral-300 dark:hover:text-neutral-100" as-child> <SidebarMenuButton
class="text-neutral-600 hover:text-neutral-800 dark:text-neutral-300 dark:hover:text-neutral-100"
as-child
>
<a :href="item.href" target="_blank" rel="noopener noreferrer"> <a :href="item.href" target="_blank" rel="noopener noreferrer">
<component :is="item.icon" /> <component :is="item.icon" />
<span>{{ item.title }}</span> <span>{{ item.title }}</span>

View File

@@ -1,7 +1,13 @@
<script setup lang="ts"> <script setup lang="ts">
import { SidebarGroup, SidebarGroupLabel, SidebarMenu, SidebarMenuButton, SidebarMenuItem } from '@/components/ui/sidebar'; import {
import { type NavItem, type SharedData } from '@/types'; SidebarGroup,
import { Link, usePage } from '@inertiajs/vue3'; SidebarGroupLabel,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar";
import { type NavItem, type SharedData } from "@/types";
import { Link, usePage } from "@inertiajs/vue3";
defineProps<{ defineProps<{
items: NavItem[]; items: NavItem[];
@@ -15,8 +21,9 @@ const page = usePage<SharedData>();
<SidebarGroupLabel>Platform</SidebarGroupLabel> <SidebarGroupLabel>Platform</SidebarGroupLabel>
<SidebarMenu> <SidebarMenu>
<SidebarMenuItem v-for="item in items" :key="item.title"> <SidebarMenuItem v-for="item in items" :key="item.title">
<SidebarMenuButton <SidebarMenuButton
as-child :is-active="item.href === page.url" as-child
:is-active="item.href === page.url"
:tooltip="item.title" :tooltip="item.title"
> >
<Link :href="item.href"> <Link :href="item.href">

View File

@@ -1,11 +1,20 @@
<script setup lang="ts"> <script setup lang="ts">
import UserInfo from '@/components/UserInfo.vue'; import UserInfo from "@/components/UserInfo.vue";
import { DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; import {
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar } from '@/components/ui/sidebar'; DropdownMenu,
import { type SharedData, type User } from '@/types'; DropdownMenuContent,
import { usePage } from '@inertiajs/vue3'; DropdownMenuTrigger,
import { ChevronsUpDown } from 'lucide-vue-next'; } from "@/components/ui/dropdown-menu";
import UserMenuContent from './UserMenuContent.vue'; import {
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
useSidebar,
} from "@/components/ui/sidebar";
import { type SharedData, type User } from "@/types";
import { usePage } from "@inertiajs/vue3";
import { ChevronsUpDown } from "lucide-vue-next";
import UserMenuContent from "./UserMenuContent.vue";
const page = usePage<SharedData>(); const page = usePage<SharedData>();
const user = page.props.auth.user as User; const user = page.props.auth.user as User;
@@ -17,15 +26,18 @@ const { isMobile, state } = useSidebar();
<SidebarMenuItem> <SidebarMenuItem>
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger as-child> <DropdownMenuTrigger as-child>
<SidebarMenuButton size="lg" class="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"> <SidebarMenuButton
size="lg"
class="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
>
<UserInfo :user="user" /> <UserInfo :user="user" />
<ChevronsUpDown class="ml-auto size-4" /> <ChevronsUpDown class="ml-auto size-4" />
</SidebarMenuButton> </SidebarMenuButton>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent <DropdownMenuContent
class="w-[--radix-dropdown-menu-trigger-width] min-w-56 rounded-lg" class="w-[--radix-dropdown-menu-trigger-width] min-w-56 rounded-lg"
:side="isMobile ? 'bottom' : state === 'collapsed' ? 'left' : 'bottom'" :side="isMobile ? 'bottom' : state === 'collapsed' ? 'left' : 'bottom'"
align="end" align="end"
:side-offset="4" :side-offset="4"
> >
<UserMenuContent :user="user" /> <UserMenuContent :user="user" />

View File

@@ -1,11 +1,14 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed } from 'vue'; import { computed } from "vue";
const patternId = computed(() => `pattern-${Math.random().toString(36).substring(2, 9)}`); const patternId = computed(() => `pattern-${Math.random().toString(36).substring(2, 9)}`);
</script> </script>
<template> <template>
<svg class="absolute inset-0 size-full stroke-neutral-900/20 dark:stroke-neutral-100/20" fill="none"> <svg
class="absolute inset-0 size-full stroke-neutral-900/20 dark:stroke-neutral-100/20"
fill="none"
>
<defs> <defs>
<pattern :id="patternId" x="0" y="0" width="8" height="8" patternUnits="userSpaceOnUse"> <pattern :id="patternId" x="0" y="0" width="8" height="8" patternUnits="userSpaceOnUse">
<path d="M-1 5L5 -1M3 9L8.5 3.5" stroke-width="0.5"></path> <path d="M-1 5L5 -1M3 9L8.5 3.5" stroke-width="0.5"></path>

View File

@@ -1,21 +1,24 @@
<script setup> <script setup lang="ts">
defineProps({ defineProps<{
modelValue: String, modelValue?: string | number | null;
disabled: Boolean, disabled?: boolean;
value: String, value: string | number;
name: String, name: string;
}); describedBy?: string;
}>();
const emit = defineEmits(['update:modelValue']); const emit = defineEmits<{
"update:modelValue": [value: string];
}>();
function onChange(event) { function onChange(event: Event): void {
emit('update:modelValue', event.target.value) emit("update:modelValue", (event.target as HTMLInputElement).value);
} }
</script> </script>
<template> <template>
<label <label
class="relative rounded-lg border-2 dark:border-white/20 px-3 py-1 dark:has-[:checked]:border-white border-black/20 has-[:checked]:border-black has-[:disabled]:opacity-40" class="relative rounded-lg border-2 border-black/20 px-3 py-1 has-[:checked]:border-black has-[:disabled]:opacity-40 dark:border-white/20 dark:has-[:checked]:border-white"
> >
<input <input
type="radio" type="radio"
@@ -23,7 +26,8 @@ function onChange(event) {
:value="value" :value="value"
class="invisible absolute inset-0" class="invisible absolute inset-0"
:disabled="disabled" :disabled="disabled"
:checked="modelValue === value" :checked="String(modelValue) === String(value)"
:aria-describedby="describedBy"
@change="onChange" @change="onChange"
/> />
<slot /> <slot />

View File

@@ -1,33 +1,33 @@
<script setup> <script setup lang="ts">
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; import {
import { Deferred, router } from '@inertiajs/vue3'; Dialog,
import { LoaderCircleIcon } from 'lucide-vue-next'; DialogContent,
import { ref, watch } from 'vue'; DialogDescription,
import { Card } from './ui/card'; DialogHeader,
import ServiceCategory from '@/enums/ServiceCategory'; DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import ServiceCategory from "@/enums/ServiceCategory";
import { Deferred, router } from "@inertiajs/vue3";
import { LoaderCircleIcon } from "lucide-vue-next";
import { ref, watch } from "vue";
import { Card } from "./ui/card";
const props = defineProps({ const props = defineProps<{
servers: { servers?: Record<string, any>[];
type: Array, serviceCategory?: keyof typeof ServiceCategory;
required: false, }>();
},
serviceCategory: {
type: String,
required: false,
validate: (value) => {
return Object.keys(ServiceCategory).includes(value);
}
}
});
const isOpen = ref(false); const isOpen = ref(false);
defineEmits(['select']); defineEmits<{
select: [server: Record<string, any>];
}>();
watch(isOpen, () => { watch(isOpen, () => {
if (isOpen.value && props.servers === undefined) { if (isOpen.value && props.servers === undefined) {
router.reload({ router.reload({
only: ['servers'], only: ["servers"],
async: true, async: true,
}); });
} }
@@ -41,19 +41,23 @@ watch(isOpen, () => {
<DialogContent> <DialogContent>
<DialogHeader> <DialogHeader>
<DialogTitle>Servers</DialogTitle> <DialogTitle>Servers</DialogTitle>
<DialogDescription>Select an active server to install the gateway on.</DialogDescription> <DialogDescription
>Select an active server to install the gateway on.</DialogDescription
>
<div class="my-2 max-h-80 overflow-y-auto"> <div class="my-2 max-h-80 overflow-y-auto">
<Deferred data="servers"> <Deferred data="servers">
<template #fallback> <template #fallback>
<div class="flex justify-center py-4"> <div class="flex justify-center py-4">
<LoaderCircleIcon class="size-6 animate-spin text-muted-foreground" /> <LoaderCircleIcon
class="size-6 animate-spin text-muted-foreground"
/>
</div> </div>
</template> </template>
<Card <Card
v-for="(server, serverIndex) in servers" v-for="(server, serverIndex) in servers"
:key="`serverPicker-${server.id}`" :key="`serverPicker-${server.id}`"
:data-index="serverIndex" :data-index="serverIndex"
class="group flex gap-4 p-2 justify-between text-muted-foreground hover:text-foreground transition" class="group flex justify-between gap-4 p-2 text-muted-foreground transition hover:text-foreground"
:class="{ :class="{
'rounded-b-none': serverIndex !== servers.length - 1, 'rounded-b-none': serverIndex !== servers.length - 1,
'rounded-t-none': serverIndex !== 0, 'rounded-t-none': serverIndex !== 0,
@@ -65,9 +69,18 @@ watch(isOpen, () => {
" "
> >
<div class="cursor-default text-sm">{{ server.name }}</div> <div class="cursor-default text-sm">{{ server.name }}</div>
<div v-if="serviceCategory" class="text-xs">{{ !!server.services.filter((s) => s.category === serviceCategory).length ? 'Has Gateway' : 'No Gateway Installed' }}</div> <div v-if="serviceCategory" class="text-xs">
{{
!!server.services.filter((s) => s.category === serviceCategory)
.length
? "Has Gateway"
: "No Gateway Installed"
}}
</div>
</Card>
<Card v-if="servers.length === 0" class="p-2 text-sm text-muted-foreground">
No servers available
</Card> </Card>
<Card v-if="servers.length === 0" class="p-2 text-sm text-muted-foreground"> No servers available </Card>
</Deferred> </Deferred>
</div> </div>
</DialogHeader> </DialogHeader>

View File

@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { Link } from '@inertiajs/vue3'; import { Link } from "@inertiajs/vue3";
interface Props { interface Props {
href: string; href: string;

View File

@@ -1,8 +1,8 @@
<script setup lang="ts"> <script setup lang="ts">
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useInitials } from '@/composables/useInitials'; import { useInitials } from "@/composables/useInitials";
import type { User } from '@/types'; import type { User } from "@/types";
import { computed } from 'vue'; import { computed } from "vue";
interface Props { interface Props {
user: User; user: User;
@@ -16,7 +16,7 @@ const props = withDefaults(defineProps<Props>(), {
const { getInitials } = useInitials(); const { getInitials } = useInitials();
// Compute whether we should show the avatar image // Compute whether we should show the avatar image
const showAvatar = computed(() => props.user.avatar && props.user.avatar !== ''); const showAvatar = computed(() => props.user.avatar && props.user.avatar !== "");
</script> </script>
<template> <template>
@@ -29,6 +29,8 @@ const showAvatar = computed(() => props.user.avatar && props.user.avatar !== '')
<div class="grid flex-1 text-left text-sm leading-tight"> <div class="grid flex-1 text-left text-sm leading-tight">
<span class="truncate font-medium">{{ user.name }}</span> <span class="truncate font-medium">{{ user.name }}</span>
<span v-if="showEmail" class="truncate text-xs text-muted-foreground">{{ user.email }}</span> <span v-if="showEmail" class="truncate text-xs text-muted-foreground">{{
user.email
}}</span>
</div> </div>
</template> </template>

View File

@@ -1,9 +1,14 @@
<script setup lang="ts"> <script setup lang="ts">
import UserInfo from '@/components/UserInfo.vue'; import UserInfo from "@/components/UserInfo.vue";
import { DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator } from '@/components/ui/dropdown-menu'; import {
import type { User } from '@/types'; DropdownMenuGroup,
import { Link } from '@inertiajs/vue3'; DropdownMenuItem,
import { LogOut, Settings } from 'lucide-vue-next'; DropdownMenuLabel,
DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import type { User } from "@/types";
import { Link } from "@inertiajs/vue3";
import { LogOut, Settings } from "lucide-vue-next";
interface Props { interface Props {
user: User; user: User;

View File

@@ -1,31 +1,26 @@
<script setup> <script setup lang="ts">
import { Card } from '@/components/ui/card'; import { Card } from "@/components/ui/card";
import ServiceCategory from '@/enums/ServiceCategory'; import ServiceCategory from "@/enums/ServiceCategory";
import ServiceStatus from '@/enums/ServiceStatus'; import ServiceStatus from "@/enums/ServiceStatus";
import ServiceType from '@/enums/ServiceType'; import ServiceType from "@/enums/ServiceType";
import { DoorOpenIcon } from 'lucide-vue-next'; import { DoorOpenIcon } from "lucide-vue-next";
defineProps({ withDefaults(defineProps<{
icon: { icon?: object | Function;
type: [Object, Function], serviceType?: string;
default: () => DoorOpenIcon, serviceCategory?: string;
}, status?: string;
serviceType: { }>(), {
type: String, icon: () => DoorOpenIcon,
default: ServiceType.GATEWAY, serviceType: ServiceType.GATEWAY,
}, serviceCategory: ServiceCategory.DATABASE,
serviceCategory: { status: ServiceStatus.UNKNOWN,
type: String,
default: ServiceCategory.DATABASE
},
status: {
type: String,
default: ServiceStatus.UNKNOWN,
},
}); });
</script> </script>
<template> <template>
<Card class="flex select-none items-center justify-between gap-4 bg-card/30 p-4 backdrop-blur-sm"> <Card
class="flex select-none items-center justify-between gap-4 bg-card/30 p-4 backdrop-blur-sm"
>
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
<component :is="icon" class="size-4 opacity-50" /> <component :is="icon" class="size-4 opacity-50" />
<div> <div>
@@ -37,21 +32,23 @@ defineProps({
<span <span
class="inline-block size-1 rounded-full dark:bg-zinc-500" class="inline-block size-1 rounded-full dark:bg-zinc-500"
:class="{ :class="{
'bg-zinc-300 dark:bg-zinc-500': status === ServiceStatus.UNKNOWN || status === ServiceStatus.NOT_INSTALLED, 'bg-zinc-500 dark:bg-zinc-400':
'bg-green-300 dark:bg-green-500': status === ServiceStatus.RUNNING, status === ServiceStatus.UNKNOWN || status === ServiceStatus.NOT_INSTALLED,
'bg-red-300 dark:bg-red-500': status === ServiceStatus.STOPPED, 'bg-green-600 dark:bg-green-400': status === ServiceStatus.RUNNING,
'bg-yellow-300 dark:bg-yellow-500': status === ServiceStatus.INSTALLING, 'bg-red-600 dark:bg-red-400': status === ServiceStatus.STOPPED,
'bg-yellow-600 dark:bg-yellow-400': status === ServiceStatus.INSTALLING,
}" }"
></span> ></span>
<span <span
class="text-xs dark:text-zinc-500" class="text-xs dark:text-zinc-400"
:class="{ :class="{
'text-zinc-300 dark:text-zinc-500': status === ServiceStatus.UNKNOWN || status === ServiceStatus.NOT_INSTALLED, 'text-zinc-600 dark:text-zinc-400':
'text-green-300 dark:text-green-500': status === ServiceStatus.RUNNING, status === ServiceStatus.UNKNOWN || status === ServiceStatus.NOT_INSTALLED,
'text-red-300 dark:text-red-500': status === ServiceStatus.STOPPED, 'text-green-700 dark:text-green-400': status === ServiceStatus.RUNNING,
'text-yellow-300 dark:text-yellow-500': status === ServiceStatus.INSTALLING, 'text-red-700 dark:text-red-400': status === ServiceStatus.STOPPED,
'text-yellow-700 dark:text-yellow-400': status === ServiceStatus.INSTALLING,
}" }"
>{{ status.replaceAll('-', ' ') }}</span >{{ status.replaceAll("-", " ") }}</span
> >
</div> </div>
</Card> </Card>

View File

@@ -0,0 +1,149 @@
<script setup lang="ts">
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Link } from "@inertiajs/vue3";
import { GitCommitIcon } from "lucide-vue-next";
import { ref } from "vue";
defineProps<{
operations: Record<string, any>[];
showTarget?: boolean;
}>();
const selectedStep = ref<Record<string, any> | null>(null);
const label = (value?: string | null): string => value?.replaceAll("_", " ").replaceAll("-", " ") ?? "";
const targetLabel = (target?: Record<string, any> | null): string => {
if (!target) {
return "Unknown target";
}
return target.name ?? target.hostname ?? `#${target.id}`;
};
</script>
<template>
<div class="grid gap-3">
<div
v-for="operation in operations"
:key="operation.id"
class="rounded-md border p-3 text-sm"
>
<div class="flex flex-wrap items-start justify-between gap-3">
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2">
<GitCommitIcon class="size-4 text-muted-foreground" />
<Link
:href="
route('operations.show', {
organisation: $page.props.organisation.id,
operation: operation.id,
})
"
class="font-medium hover:underline"
>
{{ label(operation.kind) }}
</Link>
<Badge variant="outline">{{ operation.hash }}</Badge>
<Badge
:variant="operation.status === 'completed' ? 'success' : 'secondary'"
>
{{ label(operation.status) }}
</Badge>
</div>
<p v-if="showTarget" class="mt-1 text-muted-foreground">
Target: {{ targetLabel(operation.target) }}
</p>
</div>
<div class="text-xs text-muted-foreground">
{{ operation.steps_count ?? operation.steps?.length ?? 0 }} steps
<span v-if="operation.children_count ?? operation.children?.length">
· {{ operation.children_count ?? operation.children?.length }} child ops
</span>
</div>
</div>
<div v-if="operation.steps?.length" class="mt-3 grid gap-2 border-l pl-3">
<div
v-for="step in operation.steps"
:key="step.id"
class="flex items-start justify-between gap-3"
>
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2">
<div class="font-medium">{{ step.name ?? "Unnamed step" }}</div>
<Badge
:variant="step.status === 'completed' ? 'success' : 'secondary'"
>
{{ label(step.status) }}
</Badge>
</div>
<pre
v-if="step.error_logs_excerpt || step.logs_excerpt"
class="mt-1 max-h-20 overflow-hidden whitespace-pre-wrap text-xs text-muted-foreground"
>{{ step.error_logs_excerpt ?? step.logs_excerpt }}</pre
>
</div>
<Button
v-if="step.logs || step.error_logs"
size="xs"
variant="link"
@click="selectedStep = step"
>
Logs
</Button>
</div>
</div>
<div v-if="operation.children?.length" class="mt-3 grid gap-2 border-l pl-3">
<div
v-for="child in operation.children"
:key="child.id"
class="rounded-md bg-muted/40 p-2"
>
<div class="flex flex-wrap items-center gap-2">
<Link
:href="
route('operations.show', {
organisation: $page.props.organisation.id,
operation: child.id,
})
"
class="font-medium hover:underline"
>
{{ label(child.kind) }}
</Link>
<Badge
:variant="child.status === 'completed' ? 'success' : 'secondary'"
>
{{ label(child.status) }}
</Badge>
<span class="text-muted-foreground">{{ targetLabel(child.target) }}</span>
</div>
</div>
</div>
</div>
<div v-if="operations.length === 0" class="rounded-md border border-dashed p-6 text-sm text-muted-foreground">
No operations recorded yet.
</div>
</div>
<Dialog :open="!!selectedStep" @update:open="($event) => (!$event ? (selectedStep = null) : null)">
<DialogContent class="md:max-w-3xl">
<DialogHeader>
<DialogTitle>Logs for {{ selectedStep?.name ?? "step" }}</DialogTitle>
</DialogHeader>
<section v-if="selectedStep?.logs">
<h3 class="text-sm font-medium">Logs</h3>
<pre class="max-h-80 overflow-auto whitespace-pre-wrap text-xs text-muted-foreground">{{ selectedStep.logs }}</pre>
</section>
<section v-if="selectedStep?.error_logs">
<h3 class="text-sm font-medium">Error Logs</h3>
<pre class="max-h-80 overflow-auto whitespace-pre-wrap text-xs text-muted-foreground">{{ selectedStep.error_logs }}</pre>
</section>
</DialogContent>
</Dialog>
</template>

View File

@@ -1,18 +1,18 @@
<script setup lang="ts"> <script setup lang="ts">
import { cn } from '@/lib/utils'; import { cn } from "@/lib/utils";
import { AvatarRoot } from 'radix-vue'; import { AvatarRoot } from "radix-vue";
import type { HTMLAttributes } from 'vue'; import type { HTMLAttributes } from "vue";
import { avatarVariant, type AvatarVariants } from '.'; import { avatarVariant, type AvatarVariants } from ".";
const props = withDefaults( const props = withDefaults(
defineProps<{ defineProps<{
class?: HTMLAttributes['class']; class?: HTMLAttributes["class"];
size?: AvatarVariants['size']; size?: AvatarVariants["size"];
shape?: AvatarVariants['shape']; shape?: AvatarVariants["shape"];
}>(), }>(),
{ {
size: 'sm', size: "sm",
shape: 'circle', shape: "circle",
}, },
); );
</script> </script>

View File

@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { AvatarFallback, type AvatarFallbackProps } from 'radix-vue'; import { AvatarFallback, type AvatarFallbackProps } from "radix-vue";
const props = defineProps<AvatarFallbackProps>(); const props = defineProps<AvatarFallbackProps>();
</script> </script>

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