Add admin capsule management, fix file browser for special files, normalize dialog styles
- Admin capsule CRUD: list, create (platform templates), get detail with terminal/files/metrics, snapshot, destroy - First signup auto-promotes to platform admin - JWT auth via query param for WebSocket connections - File browser: handle non-regular files (devices, pipes, sockets) gracefully instead of showing raw backend errors - Normalize admin template dialogs to match established dialog patterns: remove accent bars, unify animation/shadow/button styles
This commit is contained in:
12
db/migrations/20260412213141_seed_platform_team.sql
Normal file
12
db/migrations/20260412213141_seed_platform_team.sql
Normal file
@ -0,0 +1,12 @@
|
||||
-- +goose Up
|
||||
|
||||
-- Seed the platform team row. This is the sentinel team (all-zeros UUID) that
|
||||
-- owns platform-wide resources: global templates, admin-created capsules, etc.
|
||||
-- No user can become a member of this team — it exists solely to satisfy
|
||||
-- foreign key constraints and to act as a namespace for platform resources.
|
||||
INSERT INTO teams (id, name, slug)
|
||||
VALUES ('00000000-0000-0000-0000-000000000000', 'Platform', 'platform')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- +goose Down
|
||||
DELETE FROM teams WHERE id = '00000000-0000-0000-0000-000000000000';
|
||||
@ -35,6 +35,9 @@ SELECT EXISTS(
|
||||
SELECT 1 FROM admin_permissions WHERE user_id = $1 AND permission = $2
|
||||
) AS has_permission;
|
||||
|
||||
-- name: CountUsers :one
|
||||
SELECT COUNT(*) FROM users;
|
||||
|
||||
-- name: SearchUsersByEmailPrefix :many
|
||||
SELECT id, email FROM users WHERE email LIKE $1 || '%' ORDER BY email LIMIT 10;
|
||||
|
||||
|
||||
40
frontend/src/lib/api/admin-capsules.ts
Normal file
40
frontend/src/lib/api/admin-capsules.ts
Normal file
@ -0,0 +1,40 @@
|
||||
import { apiFetch, type ApiResult } from '$lib/api/client';
|
||||
import type { Capsule, CreateCapsuleParams, Snapshot } from '$lib/api/capsules';
|
||||
import type { AdminTemplate } from '$lib/api/builds';
|
||||
|
||||
export async function listAdminCapsules(): Promise<ApiResult<Capsule[]>> {
|
||||
return apiFetch('GET', '/api/v1/admin/capsules');
|
||||
}
|
||||
|
||||
export async function getAdminCapsule(id: string): Promise<ApiResult<Capsule>> {
|
||||
return apiFetch('GET', `/api/v1/admin/capsules/${id}`);
|
||||
}
|
||||
|
||||
export async function createAdminCapsule(params: CreateCapsuleParams): Promise<ApiResult<Capsule>> {
|
||||
return apiFetch('POST', '/api/v1/admin/capsules', params);
|
||||
}
|
||||
|
||||
export async function destroyAdminCapsule(id: string): Promise<ApiResult<void>> {
|
||||
return apiFetch('DELETE', `/api/v1/admin/capsules/${id}`);
|
||||
}
|
||||
|
||||
export async function snapshotAdminCapsule(id: string, name?: string): Promise<ApiResult<Snapshot>> {
|
||||
return apiFetch('POST', `/api/v1/admin/capsules/${id}/snapshot`, { name });
|
||||
}
|
||||
|
||||
/** Fetch platform templates for the admin create dialog. */
|
||||
export async function listPlatformTemplates(): Promise<ApiResult<Snapshot[]>> {
|
||||
const result = await apiFetch<AdminTemplate[]>('GET', '/api/v1/admin/templates');
|
||||
if (!result.ok) return result;
|
||||
// Map AdminTemplate → Snapshot shape.
|
||||
const snapshots: Snapshot[] = result.data.map((t) => ({
|
||||
name: t.name,
|
||||
type: t.type,
|
||||
vcpus: t.vcpus || undefined,
|
||||
memory_mb: t.memory_mb || undefined,
|
||||
size_bytes: t.size_bytes,
|
||||
created_at: t.created_at,
|
||||
platform: true,
|
||||
}));
|
||||
return { ok: true, data: snapshots };
|
||||
}
|
||||
@ -4,7 +4,7 @@ import { type ApiResult } from '$lib/api/client';
|
||||
export type FileEntry = {
|
||||
name: string;
|
||||
path: string;
|
||||
type: 'file' | 'directory' | 'symlink';
|
||||
type: 'file' | 'directory' | 'symlink' | 'unknown';
|
||||
size: number;
|
||||
mode: number;
|
||||
permissions: string;
|
||||
@ -53,12 +53,12 @@ export function formatFileSize(bytes: number): string {
|
||||
return `${val < 10 ? val.toFixed(1) : Math.round(val)} ${units[i]}`;
|
||||
}
|
||||
|
||||
export async function listDir(capsuleId: string, path: string, depth = 1): Promise<ApiResult<ListDirResponse>> {
|
||||
export async function listDir(capsuleId: string, path: string, depth = 1, basePath = '/api/v1/capsules'): Promise<ApiResult<ListDirResponse>> {
|
||||
try {
|
||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||
if (auth.token) headers['Authorization'] = `Bearer ${auth.token}`;
|
||||
|
||||
const res = await fetch(`/api/v1/capsules/${capsuleId}/files/list`, {
|
||||
const res = await fetch(`${basePath}/${capsuleId}/files/list`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({ path, depth }),
|
||||
@ -76,12 +76,13 @@ export async function readFile(
|
||||
capsuleId: string,
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
basePath = '/api/v1/capsules',
|
||||
): Promise<ApiResult<string>> {
|
||||
try {
|
||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||
if (auth.token) headers['Authorization'] = `Bearer ${auth.token}`;
|
||||
|
||||
const res = await fetch(`/api/v1/capsules/${capsuleId}/files/read`, {
|
||||
const res = await fetch(`${basePath}/${capsuleId}/files/read`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({ path }),
|
||||
@ -113,11 +114,12 @@ export async function downloadFile(
|
||||
path: string,
|
||||
filename: string,
|
||||
signal?: AbortSignal,
|
||||
basePath = '/api/v1/capsules',
|
||||
): Promise<void> {
|
||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||
if (auth.token) headers['Authorization'] = `Bearer ${auth.token}`;
|
||||
|
||||
const res = await fetch(`/api/v1/capsules/${capsuleId}/files/read`, {
|
||||
const res = await fetch(`${basePath}/${capsuleId}/files/read`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({ path }),
|
||||
|
||||
@ -15,8 +15,8 @@ export type MetricsResponse = {
|
||||
points: MetricPoint[];
|
||||
};
|
||||
|
||||
export async function fetchCapsuleMetrics(id: string, range: MetricRange): Promise<ApiResult<MetricsResponse>> {
|
||||
return apiFetch('GET', `/api/v1/capsules/${id}/metrics?range=${range}`);
|
||||
export async function fetchCapsuleMetrics(id: string, range: MetricRange, basePath = '/api/v1/capsules'): Promise<ApiResult<MetricsResponse>> {
|
||||
return apiFetch('GET', `${basePath}/${id}/metrics?range=${range}`);
|
||||
}
|
||||
|
||||
export const METRIC_RANGES: MetricRange[] = ['5m', '10m', '1h', '6h', '24h'];
|
||||
|
||||
@ -3,7 +3,8 @@
|
||||
import { auth } from '$lib/auth.svelte';
|
||||
import {
|
||||
IconServer,
|
||||
IconTemplate,
|
||||
IconBox,
|
||||
IconMonitor,
|
||||
IconSettings,
|
||||
IconLogout,
|
||||
IconSidebar,
|
||||
@ -22,7 +23,8 @@
|
||||
};
|
||||
|
||||
const managementItems: NavItem[] = [
|
||||
{ label: 'Templates', icon: IconTemplate, href: '/admin/templates' },
|
||||
{ label: 'Templates', icon: IconBox, href: '/admin/templates' },
|
||||
{ label: 'Capsules', icon: IconMonitor, href: '/admin/capsules' },
|
||||
{ label: 'Hosts', icon: IconServer, href: '/admin/hosts' }
|
||||
];
|
||||
|
||||
|
||||
@ -1,12 +1,15 @@
|
||||
<script lang="ts">
|
||||
import { createCapsule, listSnapshots, type Capsule, type CreateCapsuleParams, type Snapshot } from '$lib/api/capsules';
|
||||
import { createAdminCapsule, listPlatformTemplates } from '$lib/api/admin-capsules';
|
||||
|
||||
type Props = {
|
||||
open: boolean;
|
||||
onclose: () => void;
|
||||
oncreated?: (capsule: Capsule) => void;
|
||||
/** 'team' = user-scoped templates (default), 'platform' = admin platform templates only */
|
||||
templateSource?: 'team' | 'platform';
|
||||
};
|
||||
let { open, onclose, oncreated }: Props = $props();
|
||||
let { open, onclose, oncreated, templateSource = 'team' }: Props = $props();
|
||||
|
||||
let createForm = $state<CreateCapsuleParams>({ template: 'minimal', vcpus: 1, memory_mb: 512, timeout_sec: 0 });
|
||||
let creating = $state(false);
|
||||
@ -37,7 +40,8 @@
|
||||
$effect(() => {
|
||||
if (open && templates.length === 0 && !templatesLoading) {
|
||||
templatesLoading = true;
|
||||
listSnapshots().then((result) => {
|
||||
const fetcher = templateSource === 'platform' ? listPlatformTemplates : listSnapshots;
|
||||
fetcher().then((result) => {
|
||||
if (result.ok) templates = result.data;
|
||||
templatesLoading = false;
|
||||
});
|
||||
@ -112,7 +116,8 @@
|
||||
async function handleCreate() {
|
||||
creating = true;
|
||||
createError = null;
|
||||
const result = await createCapsule(createForm);
|
||||
const creator = templateSource === 'platform' ? createAdminCapsule : createCapsule;
|
||||
const result = await creator(createForm);
|
||||
if (result.ok) {
|
||||
createForm = { template: 'minimal', vcpus: 1, memory_mb: 512, timeout_sec: 0 };
|
||||
templateQuery = 'minimal';
|
||||
|
||||
@ -14,9 +14,14 @@
|
||||
type Props = {
|
||||
capsuleId: string;
|
||||
isRunning: boolean;
|
||||
apiBasePath?: string;
|
||||
/** Hide the file preview pane when no file is selected */
|
||||
compact?: boolean;
|
||||
/** Show only the file tree, completely removing the preview panel */
|
||||
treeOnly?: boolean;
|
||||
};
|
||||
|
||||
let { capsuleId, isRunning }: Props = $props();
|
||||
let { capsuleId, isRunning, apiBasePath = '/api/v1/capsules', compact = false, treeOnly = false }: Props = $props();
|
||||
|
||||
// Directory navigation state
|
||||
let currentPath = $state('~');
|
||||
@ -95,6 +100,9 @@
|
||||
// may point to devices, sockets, or directories that can't be read as a file.
|
||||
const isDownloadable = $derived(selectedFile?.type === 'file');
|
||||
|
||||
// Device files, pipes, sockets, etc. — can't be read or downloaded.
|
||||
const isSpecialFile = $derived(selectedFile?.type === 'unknown');
|
||||
|
||||
async function navigateTo(path: string) {
|
||||
// Abort any in-flight file read and invalidate stale generation so the
|
||||
// abort error isn't surfaced in the UI.
|
||||
@ -141,7 +149,7 @@
|
||||
dirLoading = true;
|
||||
dirError = null;
|
||||
const gen = ++dirGeneration;
|
||||
const result = await listDir(capsuleId, currentPath);
|
||||
const result = await listDir(capsuleId, currentPath, 1, apiBasePath);
|
||||
if (gen !== dirGeneration) return; // stale response
|
||||
if (result.ok) {
|
||||
entries = result.data.entries ?? [];
|
||||
@ -171,6 +179,11 @@
|
||||
fileError = null;
|
||||
highlightedTokens = null;
|
||||
|
||||
// Non-regular files (devices, pipes, sockets) — nothing to read
|
||||
if (entry.type === 'unknown') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if we should preview or prompt download
|
||||
if (isBinaryFile(entry.name) || isFileTooLarge(entry.size)) {
|
||||
// Don't load content — the preview pane will show download prompt
|
||||
@ -182,7 +195,7 @@
|
||||
const controller = new AbortController();
|
||||
fileAbort = controller;
|
||||
try {
|
||||
const result = await readFile(capsuleId, entry.path, controller.signal);
|
||||
const result = await readFile(capsuleId, entry.path, controller.signal, apiBasePath);
|
||||
if (gen !== fileGeneration) return; // stale response — user clicked another file
|
||||
if (result.ok) {
|
||||
if (looksLikeBinary(result.data)) {
|
||||
@ -222,7 +235,7 @@
|
||||
if (!selectedFile || downloading || selectedFile.type !== 'file') return;
|
||||
downloading = true;
|
||||
try {
|
||||
await downloadFile(capsuleId, selectedFile.path, selectedFile.name);
|
||||
await downloadFile(capsuleId, selectedFile.path, selectedFile.name, undefined, apiBasePath);
|
||||
} catch {
|
||||
fileError = 'Download failed';
|
||||
}
|
||||
@ -239,7 +252,7 @@
|
||||
|
||||
async function navigateOrOpenFile(path: string) {
|
||||
// First try as directory
|
||||
const dirResult = await listDir(capsuleId, path);
|
||||
const dirResult = await listDir(capsuleId, path, 1, apiBasePath);
|
||||
if (dirResult.ok) {
|
||||
// Resolve actual path from entries (handles ~ expansion by envd)
|
||||
const resolvedEntries = dirResult.data.entries ?? [];
|
||||
@ -270,7 +283,7 @@
|
||||
// Navigate to parent directory
|
||||
currentPath = parentPath;
|
||||
pathInput = parentPath;
|
||||
const parentResult = await listDir(capsuleId, parentPath);
|
||||
const parentResult = await listDir(capsuleId, parentPath, 1, apiBasePath);
|
||||
if (parentResult.ok) {
|
||||
entries = parentResult.data.entries ?? [];
|
||||
// Find the file in parent listing
|
||||
@ -295,6 +308,7 @@
|
||||
function fileIcon(entry: FileEntry): string {
|
||||
if (entry.type === 'directory') return 'dir';
|
||||
if (entry.type === 'symlink') return 'link';
|
||||
if (entry.type === 'unknown') return 'special';
|
||||
return 'file';
|
||||
}
|
||||
|
||||
@ -448,7 +462,8 @@
|
||||
<div class="flex flex-1 min-h-0">
|
||||
|
||||
<!-- Left panel: File tree -->
|
||||
<div class="flex w-[380px] shrink-0 flex-col border-r border-[var(--color-border)] bg-[var(--color-bg-2)]">
|
||||
<div class="flex shrink-0 flex-col bg-[var(--color-bg-2)] {(treeOnly || (compact && !selectedFile)) ? 'flex-1' : 'w-[380px] border-r border-[var(--color-border)]'}"
|
||||
>
|
||||
|
||||
<!-- Path input -->
|
||||
<form onsubmit={handlePathSubmit} class="border-b border-[var(--color-border)] px-4 py-3">
|
||||
@ -575,6 +590,11 @@
|
||||
<path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
|
||||
<path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
|
||||
</svg>
|
||||
{:else if fileIcon(entry) === 'special'}
|
||||
<svg class="shrink-0 text-[var(--color-text-muted)]" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="12" cy="12" r="10" />
|
||||
<line x1="4.93" y1="4.93" x2="19.07" y2="19.07" />
|
||||
</svg>
|
||||
{:else}
|
||||
<svg class="shrink-0" style="color: {extColor(entry.name)}" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
|
||||
@ -636,6 +656,7 @@
|
||||
</div>
|
||||
|
||||
<!-- Right panel: File preview -->
|
||||
{#if !treeOnly && (!compact || selectedFile)}
|
||||
<div class="flex flex-1 flex-col min-w-0 bg-[var(--color-bg-1)]">
|
||||
{#if !selectedFile}
|
||||
<!-- Empty state -->
|
||||
@ -720,8 +741,30 @@
|
||||
<span class="text-meta text-[var(--color-red)]">{fileError}</span>
|
||||
</div>
|
||||
</div>
|
||||
{:else if isSpecialFile}
|
||||
<!-- Device file, pipe, socket, etc. — can't read or download -->
|
||||
<div class="flex flex-1 items-center justify-center py-20">
|
||||
<div class="flex flex-col items-center gap-5 text-center" style="animation: fadeUp 0.25s ease both">
|
||||
<div class="flex h-14 w-14 items-center justify-center rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-3)]">
|
||||
<svg class="text-[var(--color-text-muted)]" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="12" cy="12" r="10" />
|
||||
<line x1="4.93" y1="4.93" x2="19.07" y2="19.07" />
|
||||
</svg>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<span class="text-ui font-medium text-[var(--color-text-primary)]">Special file</span>
|
||||
<span class="text-meta text-[var(--color-text-tertiary)]">
|
||||
<code class="rounded bg-[var(--color-bg-4)] px-1.5 py-0.5 font-mono text-[var(--color-text-secondary)]">{selectedFile.name}</code>
|
||||
is a device, socket, or pipe
|
||||
</span>
|
||||
<span class="mt-1 text-meta text-[var(--color-text-muted)]">
|
||||
Special files can't be previewed or downloaded.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else if !isDownloadable}
|
||||
<!-- Non-regular file (symlink, etc.) — no preview or download -->
|
||||
<!-- Symlink — no preview or download -->
|
||||
<div class="flex flex-1 items-center justify-center py-20">
|
||||
<div class="flex flex-col items-center gap-5 text-center" style="animation: fadeUp 0.25s ease both">
|
||||
<div class="flex h-14 w-14 items-center justify-center rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-3)]">
|
||||
@ -807,6 +850,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@ -6,9 +6,10 @@
|
||||
capsuleId: string;
|
||||
isRunning: boolean;
|
||||
visible?: boolean;
|
||||
apiBasePath?: string;
|
||||
};
|
||||
|
||||
let { capsuleId, isRunning, visible = true }: Props = $props();
|
||||
let { capsuleId, isRunning, visible = true, apiBasePath = '/api/v1/capsules' }: Props = $props();
|
||||
|
||||
type ConnectionState = 'idle' | 'connecting' | 'connected' | 'disconnected' | 'error';
|
||||
|
||||
@ -93,7 +94,7 @@
|
||||
function getWsUrl(): string {
|
||||
const proto = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const token = auth.token ? `?token=${encodeURIComponent(auth.token)}` : '';
|
||||
return `${proto}//${window.location.host}/api/v1/capsules/${capsuleId}/pty${token}`;
|
||||
return `${proto}//${window.location.host}${apiBasePath}/${capsuleId}/pty${token}`;
|
||||
}
|
||||
|
||||
function wsSend(ws: WebSocket | null, data: string) {
|
||||
|
||||
334
frontend/src/routes/admin/capsules/+page.svelte
Normal file
334
frontend/src/routes/admin/capsules/+page.svelte
Normal file
@ -0,0 +1,334 @@
|
||||
<script lang="ts">
|
||||
import AdminSidebar from '$lib/components/AdminSidebar.svelte';
|
||||
import CreateCapsuleDialog from '$lib/components/CreateCapsuleDialog.svelte';
|
||||
import CopyButton from '$lib/components/CopyButton.svelte';
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { toast } from '$lib/toast.svelte';
|
||||
import {
|
||||
listAdminCapsules,
|
||||
destroyAdminCapsule,
|
||||
} from '$lib/api/admin-capsules';
|
||||
import type { Capsule } from '$lib/api/capsules';
|
||||
|
||||
let collapsed = $state(
|
||||
typeof window !== 'undefined'
|
||||
? localStorage.getItem('wrenn_sidebar_collapsed') === 'true'
|
||||
: false
|
||||
);
|
||||
|
||||
let capsules = $state<Capsule[]>([]);
|
||||
let loading = $state(true);
|
||||
let error = $state<string | null>(null);
|
||||
let showCreateDialog = $state(false);
|
||||
|
||||
// Destroy state
|
||||
let destroyTarget = $state<Capsule | null>(null);
|
||||
let destroying = $state(false);
|
||||
let destroyError = $state<string | null>(null);
|
||||
|
||||
// Polling
|
||||
let pollInterval: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
let runningCount = $derived(capsules.filter((c) => c.status === 'running').length);
|
||||
let pausedCount = $derived(capsules.filter((c) => c.status === 'paused').length);
|
||||
|
||||
async function fetchCapsules() {
|
||||
const result = await listAdminCapsules();
|
||||
if (result.ok) {
|
||||
capsules = result.data;
|
||||
error = null;
|
||||
} else {
|
||||
error = result.error;
|
||||
}
|
||||
loading = false;
|
||||
}
|
||||
|
||||
function handleCreated(capsule: Capsule) {
|
||||
goto(`/admin/capsules/${capsule.id}`);
|
||||
}
|
||||
|
||||
async function handleDestroy() {
|
||||
if (!destroyTarget) return;
|
||||
destroying = true;
|
||||
destroyError = null;
|
||||
const result = await destroyAdminCapsule(destroyTarget.id);
|
||||
if (result.ok) {
|
||||
capsules = capsules.filter((c) => c.id !== destroyTarget!.id);
|
||||
destroyTarget = null;
|
||||
toast.success('Capsule destroyed');
|
||||
} else {
|
||||
destroyError = result.error;
|
||||
}
|
||||
destroying = false;
|
||||
}
|
||||
|
||||
function statusColor(status: string): string {
|
||||
switch (status) {
|
||||
case 'running': return 'var(--color-accent)';
|
||||
case 'paused': return 'var(--color-amber)';
|
||||
case 'error': return 'var(--color-red)';
|
||||
default: return 'var(--color-text-muted)';
|
||||
}
|
||||
}
|
||||
|
||||
function statusBg(status: string): string {
|
||||
switch (status) {
|
||||
case 'running': return 'rgba(94,140,88,0.12)';
|
||||
case 'paused': return 'rgba(212,167,60,0.12)';
|
||||
case 'error': return 'rgba(207,129,114,0.12)';
|
||||
default: return 'rgba(255,255,255,0.05)';
|
||||
}
|
||||
}
|
||||
|
||||
function statusBorder(status: string): string {
|
||||
switch (status) {
|
||||
case 'running': return 'rgba(94,140,88,0.3)';
|
||||
case 'paused': return 'rgba(212,167,60,0.3)';
|
||||
case 'error': return 'rgba(207,129,114,0.3)';
|
||||
default: return 'rgba(255,255,255,0.08)';
|
||||
}
|
||||
}
|
||||
|
||||
function fmtDate(iso: string | null | undefined): string {
|
||||
if (!iso) return '—';
|
||||
return new Date(iso).toLocaleString([], {
|
||||
month: 'short', day: 'numeric',
|
||||
hour: '2-digit', minute: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
fetchCapsules();
|
||||
pollInterval = setInterval(fetchCapsules, 15_000);
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (pollInterval) clearInterval(pollInterval);
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Wrenn Admin — Capsules</title>
|
||||
</svelte:head>
|
||||
|
||||
<div class="flex h-screen overflow-hidden bg-[var(--color-bg-0)]">
|
||||
<AdminSidebar bind:collapsed />
|
||||
|
||||
<main class="flex min-w-0 flex-1 flex-col overflow-hidden">
|
||||
<!-- Header -->
|
||||
<header class="relative shrink-0 border-b border-[var(--color-border)] bg-[var(--color-bg-1)]">
|
||||
<div class="absolute inset-0 bg-gradient-to-b from-[var(--color-accent)]/[0.02] to-transparent pointer-events-none"></div>
|
||||
|
||||
<div class="relative flex items-start justify-between px-8 pt-7 pb-5">
|
||||
<div>
|
||||
<h1 class="font-serif text-page leading-none tracking-[-0.03em] text-[var(--color-text-bright)]">
|
||||
Capsules
|
||||
</h1>
|
||||
<p class="mt-2 text-ui text-[var(--color-text-tertiary)]">
|
||||
Launch temporary capsules to build and snapshot platform templates.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onclick={() => { showCreateDialog = true; }}
|
||||
class="group flex items-center gap-2.5 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2.5 text-ui font-semibold text-white shadow-sm transition-all duration-200 hover:shadow-[0_0_20px_var(--color-accent-glow-mid)] hover:brightness-115 hover:-translate-y-px active:translate-y-0"
|
||||
>
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" class="transition-transform duration-200 group-hover:rotate-90"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
|
||||
Launch Capsule
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Stats strip -->
|
||||
{#if !loading && !error}
|
||||
<div class="relative flex items-center gap-3 px-8 pb-5">
|
||||
<span class="inline-flex items-center gap-1.5 rounded-full border border-[var(--color-border)] bg-[var(--color-bg-2)] px-2.5 py-1 text-label font-semibold text-[var(--color-text-secondary)]">
|
||||
<span class="font-mono text-[var(--color-text-bright)]">{capsules.length}</span>
|
||||
total
|
||||
</span>
|
||||
{#if runningCount > 0}
|
||||
<span class="inline-flex items-center gap-1.5 rounded-full border border-[var(--color-accent)]/25 bg-[var(--color-accent)]/8 px-2.5 py-1 text-label font-semibold text-[var(--color-accent-bright)]">
|
||||
<span class="h-[5px] w-[5px] rounded-full bg-[var(--color-accent)]" style="animation: wrenn-glow 2.5s ease-in-out infinite"></span>
|
||||
<span class="font-mono">{runningCount}</span>
|
||||
running
|
||||
</span>
|
||||
{/if}
|
||||
{#if pausedCount > 0}
|
||||
<span class="inline-flex items-center gap-1.5 rounded-full border border-[var(--color-amber)]/25 bg-[var(--color-amber)]/8 px-2.5 py-1 text-label font-semibold text-[var(--color-amber)]">
|
||||
<span class="font-mono">{pausedCount}</span>
|
||||
paused
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</header>
|
||||
|
||||
<!-- Content -->
|
||||
<div class="flex-1 overflow-y-auto px-8 py-6">
|
||||
{#if loading}
|
||||
<div class="flex items-center justify-center py-24">
|
||||
<div class="flex items-center gap-3 text-ui text-[var(--color-text-secondary)]">
|
||||
<svg class="animate-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56" /></svg>
|
||||
Loading capsules...
|
||||
</div>
|
||||
</div>
|
||||
{:else if error}
|
||||
<div class="flex items-center gap-3 rounded-[var(--radius-card)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/8 px-5 py-4">
|
||||
<svg class="shrink-0 text-[var(--color-red)]" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />
|
||||
</svg>
|
||||
<span class="text-ui text-[var(--color-red)]">{error}</span>
|
||||
</div>
|
||||
{:else if capsules.length === 0}
|
||||
<div class="flex flex-col items-center justify-center py-28 text-center">
|
||||
<div class="mb-5 flex h-16 w-16 items-center justify-center rounded-2xl border border-[var(--color-border)] bg-[var(--color-bg-2)]">
|
||||
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="var(--color-text-muted)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<polyline points="4 17 10 11 4 5" /><line x1="12" y1="19" x2="20" y2="19" />
|
||||
</svg>
|
||||
</div>
|
||||
<h2 class="font-serif text-heading tracking-[-0.02em] text-[var(--color-text-bright)]">No capsules</h2>
|
||||
<p class="mt-2 max-w-[340px] text-ui text-[var(--color-text-tertiary)]">
|
||||
Launch a capsule, configure it interactively, then snapshot it as a platform template.
|
||||
</p>
|
||||
<button
|
||||
onclick={() => { showCreateDialog = true; }}
|
||||
class="mt-6 flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2.5 text-ui font-semibold text-white shadow-sm transition-all duration-200 hover:shadow-[0_0_20px_var(--color-accent-glow-mid)] hover:brightness-115 hover:-translate-y-px active:translate-y-0"
|
||||
>
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
|
||||
Launch Capsule
|
||||
</button>
|
||||
</div>
|
||||
{:else}
|
||||
<!-- Capsule table -->
|
||||
<div class="overflow-hidden rounded-[var(--radius-card)] border border-[var(--color-border)]">
|
||||
<table class="w-full">
|
||||
<thead>
|
||||
<tr class="border-b border-[var(--color-border)] bg-[var(--color-bg-2)]">
|
||||
<th class="px-5 py-3 text-left text-label font-semibold uppercase tracking-[0.06em] text-[var(--color-text-tertiary)]">ID</th>
|
||||
<th class="px-5 py-3 text-left text-label font-semibold uppercase tracking-[0.06em] text-[var(--color-text-tertiary)]">Status</th>
|
||||
<th class="px-5 py-3 text-left text-label font-semibold uppercase tracking-[0.06em] text-[var(--color-text-tertiary)]">Template</th>
|
||||
<th class="px-5 py-3 text-left text-label font-semibold uppercase tracking-[0.06em] text-[var(--color-text-tertiary)]">Specs</th>
|
||||
<th class="px-5 py-3 text-left text-label font-semibold uppercase tracking-[0.06em] text-[var(--color-text-tertiary)]">Started</th>
|
||||
<th class="px-5 py-3 text-right text-label font-semibold uppercase tracking-[0.06em] text-[var(--color-text-tertiary)]">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-[var(--color-border)]">
|
||||
{#each capsules as capsule (capsule.id)}
|
||||
<tr class="group transition-colors duration-100 hover:bg-[var(--color-bg-2)]">
|
||||
<td class="px-5 py-3.5">
|
||||
<div class="flex items-center gap-2">
|
||||
<a
|
||||
href="/admin/capsules/{capsule.id}"
|
||||
class="font-mono text-ui text-[var(--color-text-bright)] transition-colors duration-150 hover:text-[var(--color-accent-bright)]"
|
||||
>
|
||||
{capsule.id}
|
||||
</a>
|
||||
<CopyButton value={capsule.id} />
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-5 py-3.5">
|
||||
<span
|
||||
class="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-label font-semibold uppercase tracking-[0.05em]"
|
||||
style="color: {statusColor(capsule.status)}; background: {statusBg(capsule.status)}; border: 1px solid {statusBorder(capsule.status)}"
|
||||
>
|
||||
{#if capsule.status === 'running'}
|
||||
<span class="relative flex h-[5px] w-[5px] shrink-0">
|
||||
<span class="animate-status-ping absolute inline-flex h-full w-full rounded-full bg-[var(--color-accent)]"></span>
|
||||
<span class="relative inline-flex h-[5px] w-[5px] rounded-full bg-[var(--color-accent)]"></span>
|
||||
</span>
|
||||
{/if}
|
||||
{capsule.status}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-5 py-3.5">
|
||||
<span class="font-mono text-ui text-[var(--color-text-secondary)]">{capsule.template}</span>
|
||||
</td>
|
||||
<td class="px-5 py-3.5">
|
||||
<span class="font-mono text-meta text-[var(--color-text-secondary)]">
|
||||
{capsule.vcpus}v · {capsule.memory_mb}MB
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-5 py-3.5">
|
||||
<span class="font-mono text-meta text-[var(--color-text-muted)]">{fmtDate(capsule.started_at)}</span>
|
||||
</td>
|
||||
<td class="px-5 py-3.5 text-right">
|
||||
<div class="flex items-center justify-end gap-2">
|
||||
<a
|
||||
href="/admin/capsules/{capsule.id}"
|
||||
class="rounded-[var(--radius-button)] border border-[var(--color-border)] px-3 py-1.5 text-meta font-medium text-[var(--color-text-secondary)] transition-colors duration-150 hover:bg-[var(--color-bg-3)] hover:text-[var(--color-text-primary)]"
|
||||
>
|
||||
Open
|
||||
</a>
|
||||
{#if capsule.status === 'running' || capsule.status === 'paused'}
|
||||
<button
|
||||
onclick={() => { destroyTarget = capsule; destroyError = null; }}
|
||||
class="rounded-[var(--radius-button)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/8 px-3 py-1.5 text-meta font-medium text-[var(--color-red)] transition-all duration-150 hover:bg-[var(--color-red)]/15 hover:border-[var(--color-red)]/50"
|
||||
>
|
||||
Destroy
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{/each}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<CreateCapsuleDialog
|
||||
open={showCreateDialog}
|
||||
onclose={() => { showCreateDialog = false; }}
|
||||
oncreated={handleCreated}
|
||||
templateSource="platform"
|
||||
/>
|
||||
|
||||
<!-- Destroy confirmation dialog -->
|
||||
{#if destroyTarget}
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center">
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="absolute inset-0 bg-black/60"
|
||||
onclick={() => { if (!destroying) { destroyTarget = null; } }}
|
||||
onkeydown={(e) => { if (e.key === 'Escape' && !destroying) { destroyTarget = null; } }}
|
||||
></div>
|
||||
<div class="relative w-full max-w-[380px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] p-6" style="animation: fadeUp 0.2s ease both; box-shadow: var(--shadow-dialog)">
|
||||
<h2 class="font-serif text-heading tracking-[-0.02em] text-[var(--color-text-bright)]">Destroy Capsule</h2>
|
||||
<p class="mt-2 text-ui text-[var(--color-text-tertiary)]">
|
||||
Terminate <span class="font-mono text-[var(--color-text-secondary)]">{destroyTarget.id}</span> and destroy all data inside it. This cannot be undone.
|
||||
</p>
|
||||
|
||||
{#if destroyError}
|
||||
<div class="mt-4 rounded-[var(--radius-input)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-3 py-2 text-meta text-[var(--color-red)]">
|
||||
{destroyError}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mt-6 flex justify-end gap-3">
|
||||
<button
|
||||
onclick={() => { destroyTarget = null; }}
|
||||
disabled={destroying}
|
||||
class="rounded-[var(--radius-button)] border border-[var(--color-border)] px-4 py-2 text-ui text-[var(--color-text-secondary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)] disabled:opacity-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onclick={handleDestroy}
|
||||
disabled={destroying}
|
||||
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-red)] px-5 py-2 text-ui font-semibold text-white transition-all duration-150 hover:brightness-110 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
|
||||
>
|
||||
{#if destroying}
|
||||
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
|
||||
</svg>
|
||||
Destroying...
|
||||
{:else}
|
||||
Destroy
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
623
frontend/src/routes/admin/capsules/[id]/+page.svelte
Normal file
623
frontend/src/routes/admin/capsules/[id]/+page.svelte
Normal file
@ -0,0 +1,623 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy, tick } from 'svelte';
|
||||
import { page } from '$app/stores';
|
||||
import { goto } from '$app/navigation';
|
||||
import AdminSidebar from '$lib/components/AdminSidebar.svelte';
|
||||
import TerminalTab from '$lib/components/TerminalTab.svelte';
|
||||
import FilesTab from '$lib/components/FilesTab.svelte';
|
||||
import { toast } from '$lib/toast.svelte';
|
||||
import {
|
||||
getAdminCapsule,
|
||||
destroyAdminCapsule,
|
||||
snapshotAdminCapsule,
|
||||
} from '$lib/api/admin-capsules';
|
||||
import type { Capsule } from '$lib/api/capsules';
|
||||
import {
|
||||
fetchCapsuleMetrics,
|
||||
METRIC_RANGES,
|
||||
METRIC_POLL_INTERVALS,
|
||||
type MetricRange,
|
||||
type MetricPoint
|
||||
} from '$lib/api/metrics';
|
||||
|
||||
const capsuleId: string = $page.params.id ?? '';
|
||||
const API_BASE = '/api/v1/admin/capsules';
|
||||
|
||||
let collapsed = $state(
|
||||
typeof window !== 'undefined'
|
||||
? localStorage.getItem('wrenn_sidebar_collapsed') === 'true'
|
||||
: false
|
||||
);
|
||||
|
||||
let capsule = $state<Capsule | null>(null);
|
||||
let capsuleLoading = $state(true);
|
||||
let capsuleError = $state<string | null>(null);
|
||||
|
||||
// Destroy dialog
|
||||
let showDestroy = $state(false);
|
||||
let destroying = $state(false);
|
||||
let destroyError = $state<string | null>(null);
|
||||
|
||||
// Snapshot dialog
|
||||
let showSnapshot = $state(false);
|
||||
let snapshotName = $state('');
|
||||
let snapshotting = $state(false);
|
||||
let snapshotError = $state<string | null>(null);
|
||||
|
||||
// Metrics state
|
||||
let range = $state<MetricRange>('5m');
|
||||
let points = $state<MetricPoint[]>([]);
|
||||
let metricsLoading = $state(true);
|
||||
|
||||
let canvasCpu = $state<HTMLCanvasElement | undefined>(undefined);
|
||||
let canvasRam = $state<HTMLCanvasElement | undefined>(undefined);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let chartCpu: any = null;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let chartRam: any = null;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let ChartJS = $state<any>(null);
|
||||
let metricsPollInterval: ReturnType<typeof setInterval> | null = null;
|
||||
let lastDataKey = '';
|
||||
|
||||
const metricsAvailable = $derived(
|
||||
capsule?.status === 'running' || capsule?.status === 'paused'
|
||||
);
|
||||
|
||||
const latestCpu = $derived<number | null>(
|
||||
points.length > 0 ? points[points.length - 1].cpu_pct : null
|
||||
);
|
||||
const latestRamMB = $derived<number | null>(
|
||||
points.length > 0 ? points[points.length - 1].mem_bytes / 1_048_576 : null
|
||||
);
|
||||
|
||||
async function loadCapsule() {
|
||||
const result = await getAdminCapsule(capsuleId);
|
||||
if (result.ok) {
|
||||
capsule = result.data;
|
||||
capsuleError = null;
|
||||
} else {
|
||||
capsuleError = result.error;
|
||||
}
|
||||
capsuleLoading = false;
|
||||
}
|
||||
|
||||
async function loadMetrics() {
|
||||
if (!metricsAvailable) return;
|
||||
const result = await fetchCapsuleMetrics(capsuleId, range, API_BASE);
|
||||
if (result.ok) {
|
||||
points = result.data.points;
|
||||
}
|
||||
metricsLoading = false;
|
||||
updateCharts();
|
||||
}
|
||||
|
||||
function smooth(data: number[], window: number): number[] {
|
||||
if (window <= 1) return data;
|
||||
const out: number[] = [];
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
const start = Math.max(0, i - Math.floor(window / 2));
|
||||
const end = Math.min(data.length, i + Math.ceil(window / 2));
|
||||
let sum = 0;
|
||||
for (let j = start; j < end; j++) sum += data[j];
|
||||
out.push(+(sum / (end - start)).toFixed(2));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function smoothWindow(count: number): number {
|
||||
if (count < 60) return 1;
|
||||
if (count < 200) return 3;
|
||||
if (count < 600) return 5;
|
||||
return 9;
|
||||
}
|
||||
|
||||
function updateCharts() {
|
||||
if (!points.length) return;
|
||||
const key = `${points.length}:${points.at(-1)?.timestamp_unix ?? ''}`;
|
||||
if (key === lastDataKey) return;
|
||||
lastDataKey = key;
|
||||
const labels = points.map((p) => {
|
||||
const d = new Date(p.timestamp_unix * 1000);
|
||||
if (range === '5m' || range === '10m') {
|
||||
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
||||
}
|
||||
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
});
|
||||
const w = smoothWindow(points.length);
|
||||
if (chartCpu) {
|
||||
chartCpu.data.labels = labels;
|
||||
chartCpu.data.datasets[0].data = smooth(points.map((p) => +p.cpu_pct.toFixed(2)), w);
|
||||
chartCpu.update();
|
||||
}
|
||||
if (chartRam) {
|
||||
chartRam.data.labels = labels;
|
||||
chartRam.data.datasets[0].data = smooth(points.map((p) => +(p.mem_bytes / 1_048_576).toFixed(1)), w);
|
||||
chartRam.update();
|
||||
}
|
||||
}
|
||||
|
||||
function setRange(r: MetricRange) {
|
||||
range = r;
|
||||
lastDataKey = '';
|
||||
metricsLoading = true;
|
||||
restartMetricsPolling();
|
||||
}
|
||||
|
||||
function stopMetricsPolling() {
|
||||
if (metricsPollInterval) { clearInterval(metricsPollInterval); metricsPollInterval = null; }
|
||||
}
|
||||
|
||||
function restartMetricsPolling() {
|
||||
stopMetricsPolling();
|
||||
loadMetrics();
|
||||
metricsPollInterval = setInterval(loadMetrics, METRIC_POLL_INTERVALS[range]);
|
||||
}
|
||||
|
||||
const C_BLUE = '#5a9fd4';
|
||||
const C_BLUE_FILL = 'rgba(90,159,212,0.11)';
|
||||
const C_AMBER = '#d4a73c';
|
||||
const C_AMBER_FILL = 'rgba(212,167,60,0.11)';
|
||||
const C_GRID = 'rgba(255,255,255,0.05)';
|
||||
const C_TICK = '#635f5c';
|
||||
const FONT_MONO = "'JetBrains Mono', monospace";
|
||||
|
||||
const BASE_CHART_OPTIONS = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
animation: false as const,
|
||||
interaction: { mode: 'index' as const, intersect: false },
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
tooltip: {
|
||||
backgroundColor: '#111412',
|
||||
borderColor: '#1f2321',
|
||||
borderWidth: 1,
|
||||
titleColor: '#454340',
|
||||
bodyColor: '#d4cfc8',
|
||||
titleFont: { family: FONT_MONO, size: 10 },
|
||||
bodyFont: { family: FONT_MONO, size: 11 },
|
||||
padding: 8,
|
||||
caretSize: 4,
|
||||
},
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
grid: { color: C_GRID },
|
||||
ticks: { color: C_TICK, font: { family: FONT_MONO, size: 9 }, maxTicksLimit: 5, maxRotation: 0 },
|
||||
border: { color: C_GRID },
|
||||
},
|
||||
y: {
|
||||
grid: { color: C_GRID },
|
||||
ticks: { color: C_TICK, font: { family: FONT_MONO, size: 9 } },
|
||||
border: { color: C_GRID },
|
||||
beginAtZero: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
function initCharts() {
|
||||
if (!ChartJS || !canvasCpu || !canvasRam) return;
|
||||
chartCpu?.destroy();
|
||||
chartRam?.destroy();
|
||||
|
||||
chartCpu = new ChartJS(canvasCpu, {
|
||||
type: 'line',
|
||||
data: { labels: [], datasets: [{ data: [], borderColor: C_BLUE, backgroundColor: C_BLUE_FILL, borderWidth: 1.5, fill: true, tension: 0, pointRadius: 0, pointHoverRadius: 3, pointHoverBackgroundColor: C_BLUE }] },
|
||||
options: { ...BASE_CHART_OPTIONS, scales: { ...BASE_CHART_OPTIONS.scales, y: { ...BASE_CHART_OPTIONS.scales.y, ticks: { ...BASE_CHART_OPTIONS.scales.y.ticks, callback: (v: string | number) => `${+v}%` } } } },
|
||||
});
|
||||
|
||||
chartRam = new ChartJS(canvasRam, {
|
||||
type: 'line',
|
||||
data: { labels: [], datasets: [{ data: [], borderColor: C_AMBER, backgroundColor: C_AMBER_FILL, borderWidth: 1.5, fill: true, tension: 0, pointRadius: 0, pointHoverRadius: 3, pointHoverBackgroundColor: C_AMBER }] },
|
||||
options: { ...BASE_CHART_OPTIONS, scales: { ...BASE_CHART_OPTIONS.scales, y: { ...BASE_CHART_OPTIONS.scales.y, ticks: { ...BASE_CHART_OPTIONS.scales.y.ticks, callback: (v: string | number) => `${+v} MB` } } } },
|
||||
});
|
||||
|
||||
updateCharts();
|
||||
}
|
||||
|
||||
// Re-create charts when ChartJS loads
|
||||
$effect(() => {
|
||||
if (!ChartJS || !metricsAvailable) return;
|
||||
tick().then(() => {
|
||||
if (canvasCpu && canvasRam) {
|
||||
initCharts();
|
||||
restartMetricsPolling();
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
stopMetricsPolling();
|
||||
chartCpu?.destroy(); chartCpu = null;
|
||||
chartRam?.destroy(); chartRam = null;
|
||||
};
|
||||
});
|
||||
|
||||
async function handleDestroy() {
|
||||
destroying = true;
|
||||
destroyError = null;
|
||||
const result = await destroyAdminCapsule(capsuleId);
|
||||
if (result.ok) {
|
||||
toast.success('Capsule destroyed');
|
||||
goto('/admin/capsules');
|
||||
} else {
|
||||
destroyError = result.error;
|
||||
}
|
||||
destroying = false;
|
||||
}
|
||||
|
||||
async function handleSnapshot() {
|
||||
snapshotting = true;
|
||||
snapshotError = null;
|
||||
const result = await snapshotAdminCapsule(capsuleId, snapshotName.trim() || undefined);
|
||||
if (result.ok) {
|
||||
toast.success(`Snapshot "${result.data.name}" created`);
|
||||
goto('/admin/templates');
|
||||
} else {
|
||||
snapshotError = result.error;
|
||||
}
|
||||
snapshotting = false;
|
||||
}
|
||||
|
||||
function statusColor(status: string): string {
|
||||
switch (status) {
|
||||
case 'running': return 'var(--color-accent)';
|
||||
case 'paused': return 'var(--color-amber)';
|
||||
case 'error': return 'var(--color-red)';
|
||||
default: return 'var(--color-text-muted)';
|
||||
}
|
||||
}
|
||||
|
||||
function statusBg(status: string): string {
|
||||
switch (status) {
|
||||
case 'running': return 'rgba(94,140,88,0.12)';
|
||||
case 'paused': return 'rgba(212,167,60,0.12)';
|
||||
case 'error': return 'rgba(207,129,114,0.12)';
|
||||
default: return 'rgba(255,255,255,0.05)';
|
||||
}
|
||||
}
|
||||
|
||||
function statusBorder(status: string): string {
|
||||
switch (status) {
|
||||
case 'running': return 'rgba(94,140,88,0.3)';
|
||||
case 'paused': return 'rgba(212,167,60,0.3)';
|
||||
case 'error': return 'rgba(207,129,114,0.3)';
|
||||
default: return 'rgba(255,255,255,0.08)';
|
||||
}
|
||||
}
|
||||
|
||||
function fmtDate(iso: string | null | undefined): string {
|
||||
if (!iso) return '—';
|
||||
return new Date(iso).toLocaleString([], {
|
||||
month: 'short', day: 'numeric',
|
||||
hour: '2-digit', minute: '2-digit', second: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
// Poll capsule status while it's active
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
onMount(async () => {
|
||||
await loadCapsule();
|
||||
pollTimer = setInterval(loadCapsule, 10_000);
|
||||
|
||||
if (metricsAvailable) {
|
||||
const mod = await import('chart.js/auto');
|
||||
ChartJS = mod.Chart;
|
||||
}
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
if (pollTimer) clearInterval(pollTimer);
|
||||
stopMetricsPolling();
|
||||
chartCpu?.destroy();
|
||||
chartRam?.destroy();
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
<title>Wrenn Admin — {capsuleId}</title>
|
||||
</svelte:head>
|
||||
|
||||
<div class="flex h-screen overflow-hidden bg-[var(--color-bg-0)]">
|
||||
<AdminSidebar bind:collapsed />
|
||||
|
||||
<main class="flex min-w-0 flex-1 flex-col overflow-hidden">
|
||||
{#if capsuleLoading}
|
||||
<div class="flex flex-1 items-center justify-center">
|
||||
<div class="flex items-center gap-3 text-ui text-[var(--color-text-secondary)]">
|
||||
<svg class="animate-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56" /></svg>
|
||||
Loading capsule...
|
||||
</div>
|
||||
</div>
|
||||
{:else if capsuleError}
|
||||
<div class="p-8">
|
||||
<div class="flex items-center gap-3 rounded-[var(--radius-card)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/8 px-5 py-4">
|
||||
<svg class="shrink-0 text-[var(--color-red)]" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />
|
||||
</svg>
|
||||
<span class="text-ui text-[var(--color-red)]">{capsuleError}</span>
|
||||
</div>
|
||||
</div>
|
||||
{:else if capsule}
|
||||
<!-- Header bar -->
|
||||
<div class="flex shrink-0 items-center gap-4 border-b border-[var(--color-border)] bg-[var(--color-bg-1)] px-6 py-2.5">
|
||||
<a
|
||||
href="/admin/capsules"
|
||||
class="flex items-center gap-1.5 text-meta text-[var(--color-text-tertiary)] transition-colors duration-150 hover:text-[var(--color-text-secondary)]"
|
||||
>
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
|
||||
Capsules
|
||||
</a>
|
||||
<div class="h-4 w-px bg-[var(--color-border)]"></div>
|
||||
|
||||
<span class="font-mono text-ui text-[var(--color-text-bright)]">{capsuleId}</span>
|
||||
|
||||
<span
|
||||
class="inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-badge font-semibold uppercase tracking-[0.05em]"
|
||||
style="color: {statusColor(capsule.status)}; background: {statusBg(capsule.status)}; border: 1px solid {statusBorder(capsule.status)}"
|
||||
>
|
||||
{#if capsule.status === 'running'}
|
||||
<span class="relative flex h-[5px] w-[5px] shrink-0">
|
||||
<span class="animate-status-ping absolute inline-flex h-full w-full rounded-full bg-[var(--color-accent)]"></span>
|
||||
<span class="relative inline-flex h-[5px] w-[5px] rounded-full bg-[var(--color-accent)]"></span>
|
||||
</span>
|
||||
{/if}
|
||||
{capsule.status}
|
||||
</span>
|
||||
|
||||
<!-- Capsule info chips -->
|
||||
<div class="flex items-center gap-2 text-badge text-[var(--color-text-muted)]">
|
||||
<span class="font-mono">{capsule.template}</span>
|
||||
<span class="text-[var(--color-border-mid)]">/</span>
|
||||
<span class="font-mono">{capsule.vcpus}v · {capsule.memory_mb}MB</span>
|
||||
</div>
|
||||
|
||||
<div class="flex-1"></div>
|
||||
|
||||
{#if capsule.status === 'running' || capsule.status === 'paused'}
|
||||
<button
|
||||
onclick={() => { showSnapshot = true; snapshotName = ''; snapshotError = null; }}
|
||||
disabled={snapshotting}
|
||||
class="flex items-center gap-1.5 rounded-[var(--radius-button)] border border-[var(--color-accent)]/30 bg-[var(--color-accent)]/8 px-3 py-1.5 text-meta font-medium text-[var(--color-accent-bright)] transition-all duration-150 hover:bg-[var(--color-accent)]/15 hover:border-[var(--color-accent)]/50 disabled:opacity-50"
|
||||
>
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 4h-5L7 7H2v13a2 2 0 002 2h16a2 2 0 002-2V7h-5l-2.5-3z" /><circle cx="12" cy="15" r="3" /></svg>
|
||||
Snapshot
|
||||
</button>
|
||||
<button
|
||||
onclick={() => { showDestroy = true; destroyError = null; }}
|
||||
disabled={destroying}
|
||||
class="flex items-center gap-1.5 rounded-[var(--radius-button)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/8 px-3 py-1.5 text-meta font-medium text-[var(--color-red)] transition-all duration-150 hover:bg-[var(--color-red)]/15 hover:border-[var(--color-red)]/50 disabled:opacity-50"
|
||||
>
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6" /><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2" /></svg>
|
||||
Destroy
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<!-- Split panels: 50/50 -->
|
||||
<div class="flex flex-1 overflow-hidden">
|
||||
|
||||
<!-- Left: Terminal -->
|
||||
<div class="flex w-1/2 flex-col overflow-hidden border-r border-[var(--color-border)]">
|
||||
<TerminalTab {capsuleId} isRunning={capsule.status === 'running'} apiBasePath={API_BASE} />
|
||||
</div>
|
||||
|
||||
<!-- Right: Metrics (top) + Files (bottom) -->
|
||||
<div class="flex w-1/2 flex-col overflow-hidden">
|
||||
|
||||
<!-- Metrics section -->
|
||||
{#if metricsAvailable}
|
||||
<div class="flex flex-1 flex-col min-h-0 border-b border-[var(--color-border)]">
|
||||
<!-- Range selector bar -->
|
||||
<div class="flex items-center justify-between border-b border-[var(--color-border)] bg-[var(--color-bg-1)] px-5 py-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="flex items-center gap-1.5 text-badge font-semibold uppercase tracking-[0.05em] text-[var(--color-accent-mid)]">
|
||||
<span class="h-[5px] w-[5px] rounded-full bg-[var(--color-accent)]" style="animation: wrenn-glow 2.5s ease-in-out infinite"></span>
|
||||
Live
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex overflow-hidden rounded-[var(--radius-button)] border border-[var(--color-border)]">
|
||||
{#each METRIC_RANGES as r, i}
|
||||
<button
|
||||
onclick={() => setRange(r)}
|
||||
class="px-2.5 py-1 font-mono text-badge transition-colors duration-150
|
||||
{range === r
|
||||
? 'bg-[var(--color-bg-5)] text-[var(--color-text-bright)]'
|
||||
: 'text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-3)] hover:text-[var(--color-text-secondary)]'}
|
||||
{i > 0 ? 'border-l border-[var(--color-border)]' : ''}"
|
||||
>
|
||||
{r}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Stacked charts — each grows to fill half -->
|
||||
<div class="flex flex-1 flex-col divide-y divide-[var(--color-border)] min-h-0">
|
||||
<!-- CPU chart -->
|
||||
<div class="flex flex-1 flex-col min-h-0 bg-[var(--color-bg-1)]">
|
||||
<div class="flex shrink-0 items-center justify-between px-5 py-2">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="h-2 w-2 shrink-0 rounded-full" style="background: {C_BLUE}"></span>
|
||||
<span class="text-label font-semibold uppercase tracking-[0.06em] text-[var(--color-text-tertiary)]">CPU Usage</span>
|
||||
</div>
|
||||
{#if latestCpu !== null}
|
||||
<div class="flex items-baseline gap-1">
|
||||
<span class="font-serif text-heading leading-none tracking-[-0.04em] text-[var(--color-text-bright)]">{latestCpu.toFixed(1)}</span>
|
||||
<span class="font-mono text-badge text-[var(--color-text-muted)]">%</span>
|
||||
</div>
|
||||
{:else if metricsLoading}
|
||||
<span class="font-serif text-heading leading-none text-[var(--color-text-muted)]">—</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="relative flex-1 min-h-0 px-4 pb-3">
|
||||
<canvas bind:this={canvasCpu}></canvas>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- RAM chart -->
|
||||
<div class="flex flex-1 flex-col min-h-0 bg-[var(--color-bg-1)]">
|
||||
<div class="flex shrink-0 items-center justify-between px-5 py-2">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="h-2 w-2 shrink-0 rounded-full" style="background: {C_AMBER}"></span>
|
||||
<span class="text-label font-semibold uppercase tracking-[0.06em] text-[var(--color-text-tertiary)]">RAM Usage</span>
|
||||
</div>
|
||||
{#if latestRamMB !== null}
|
||||
<div class="flex items-baseline gap-1">
|
||||
<span class="font-serif text-heading leading-none tracking-[-0.04em] text-[var(--color-text-bright)]">{latestRamMB.toFixed(0)}</span>
|
||||
<span class="font-mono text-badge text-[var(--color-text-muted)]">MB</span>
|
||||
</div>
|
||||
{:else if metricsLoading}
|
||||
<span class="font-serif text-heading leading-none text-[var(--color-text-muted)]">—</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="relative flex-1 min-h-0 px-4 pb-3">
|
||||
<canvas bind:this={canvasRam}></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- File tree (fills remaining space) -->
|
||||
<div class="flex flex-1 flex-col overflow-hidden">
|
||||
<FilesTab {capsuleId} isRunning={capsule.status === 'running'} apiBasePath={API_BASE} compact />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<!-- Snapshot dialog -->
|
||||
{#if showSnapshot}
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center">
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="absolute inset-0 bg-black/60"
|
||||
onclick={() => { if (!snapshotting) showSnapshot = false; }}
|
||||
onkeydown={(e) => { if (e.key === 'Escape' && !snapshotting) showSnapshot = false; }}
|
||||
></div>
|
||||
|
||||
<div class="relative w-full max-w-[420px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] overflow-hidden" style="animation: fadeUp 0.2s ease both; box-shadow: var(--shadow-dialog)">
|
||||
<div class="flex items-center gap-4 border-b border-[var(--color-border)] bg-[var(--color-bg-3)] px-6 py-5">
|
||||
<div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-[var(--radius-input)] bg-[var(--color-accent)]/15 text-[var(--color-accent)] shadow-[0_0_12px_var(--color-accent-glow)]">
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M14.5 4h-5L7 7H2v13a2 2 0 002 2h16a2 2 0 002-2V7h-5l-2.5-3z" />
|
||||
<circle cx="12" cy="15" r="3" />
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<h2 class="font-serif text-heading tracking-[-0.02em] text-[var(--color-text-bright)]">Snapshot as platform template</h2>
|
||||
<p class="mt-0.5 text-meta text-[var(--color-text-muted)] font-mono">{capsuleId}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="px-6 pt-5 pb-6 space-y-4">
|
||||
<div class="flex items-start gap-2.5 rounded-[var(--radius-input)] border border-[var(--color-amber)]/25 bg-[var(--color-amber)]/8 px-3 py-2.5">
|
||||
<svg class="mt-px shrink-0 text-[var(--color-amber)]" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
|
||||
<line x1="12" y1="9" x2="12" y2="13" />
|
||||
<line x1="12" y1="17" x2="12.01" y2="17" />
|
||||
</svg>
|
||||
<p class="text-meta text-[var(--color-amber)] leading-relaxed">This will <strong class="font-semibold">pause, snapshot, and destroy</strong> the capsule. The snapshot will be available as a platform template for all teams.</p>
|
||||
</div>
|
||||
|
||||
{#if snapshotError}
|
||||
<div class="rounded-[var(--radius-input)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-3 py-2 text-meta text-[var(--color-red)]">
|
||||
{snapshotError}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div>
|
||||
<div class="mb-1.5 flex items-baseline justify-between">
|
||||
<label class="text-label font-semibold uppercase tracking-[0.05em] text-[var(--color-text-tertiary)]" for="admin-snapshot-name">Template name</label>
|
||||
<span class="text-meta text-[var(--color-text-muted)]">optional</span>
|
||||
</div>
|
||||
<input
|
||||
id="admin-snapshot-name"
|
||||
type="text"
|
||||
bind:value={snapshotName}
|
||||
disabled={snapshotting}
|
||||
class="w-full rounded-[var(--radius-input)] border border-[var(--color-border)] bg-[var(--color-bg-4)] px-3 py-2 font-mono text-ui text-[var(--color-text-bright)] outline-none placeholder:text-[var(--color-text-muted)] transition-colors duration-150 focus:border-[var(--color-accent)] disabled:opacity-50"
|
||||
placeholder="e.g. python-3.12, node-22-dev"
|
||||
onkeydown={(e) => { if (e.key === 'Enter' && !snapshotting) handleSnapshot(); }}
|
||||
/>
|
||||
<p class="mt-1.5 text-meta text-[var(--color-text-muted)]">Leave blank for an auto-generated name. If the name already exists, it will be overwritten.</p>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-3 pt-1">
|
||||
<button
|
||||
onclick={() => { showSnapshot = false; }}
|
||||
disabled={snapshotting}
|
||||
class="rounded-[var(--radius-button)] border border-[var(--color-border)] px-4 py-2 text-ui text-[var(--color-text-secondary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)] disabled:opacity-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onclick={handleSnapshot}
|
||||
disabled={snapshotting}
|
||||
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2 text-ui font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
|
||||
>
|
||||
{#if snapshotting}
|
||||
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
|
||||
</svg>
|
||||
Snapshotting...
|
||||
{:else}
|
||||
Snapshot & Destroy
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Destroy dialog -->
|
||||
{#if showDestroy}
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center">
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="absolute inset-0 bg-black/60"
|
||||
onclick={() => { if (!destroying) showDestroy = false; }}
|
||||
onkeydown={(e) => { if (e.key === 'Escape' && !destroying) showDestroy = false; }}
|
||||
></div>
|
||||
<div class="relative w-full max-w-[380px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] p-6" style="animation: fadeUp 0.2s ease both; box-shadow: var(--shadow-dialog)">
|
||||
<h2 class="font-serif text-heading tracking-[-0.02em] text-[var(--color-text-bright)]">Destroy Capsule</h2>
|
||||
<p class="mt-2 text-ui text-[var(--color-text-tertiary)]">
|
||||
Terminate <span class="font-mono text-[var(--color-text-secondary)]">{capsuleId}</span> and destroy all data inside it. This cannot be undone.
|
||||
</p>
|
||||
|
||||
{#if destroyError}
|
||||
<div class="mt-4 rounded-[var(--radius-input)] border border-[var(--color-red)]/30 bg-[var(--color-red)]/5 px-3 py-2 text-meta text-[var(--color-red)]">
|
||||
{destroyError}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mt-6 flex justify-end gap-3">
|
||||
<button
|
||||
onclick={() => { showDestroy = false; }}
|
||||
disabled={destroying}
|
||||
class="rounded-[var(--radius-button)] border border-[var(--color-border)] px-4 py-2 text-ui text-[var(--color-text-secondary)] transition-colors duration-150 hover:border-[var(--color-border-mid)] hover:text-[var(--color-text-primary)] disabled:opacity-50"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
onclick={handleDestroy}
|
||||
disabled={destroying}
|
||||
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-red)] px-5 py-2 text-ui font-semibold text-white transition-all duration-150 hover:brightness-110 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
|
||||
>
|
||||
{#if destroying}
|
||||
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
|
||||
</svg>
|
||||
Destroying...
|
||||
{:else}
|
||||
Destroy
|
||||
{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
@ -727,20 +727,16 @@
|
||||
<!-- ── Create Template Dialog ──────────────────────────────────────── -->
|
||||
{#if showCreate}
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center">
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="absolute inset-0 bg-black/60"
|
||||
role="button"
|
||||
tabindex="-1"
|
||||
onclick={() => { if (!creating) showCreate = false; }}
|
||||
onkeydown={(e) => { if (e.key === 'Escape' && !creating) showCreate = false; }}
|
||||
></div>
|
||||
<div
|
||||
class="relative w-full max-w-[520px] max-h-[90vh] overflow-y-auto rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] shadow-dialog"
|
||||
style="animation: fadeUp 0.18s cubic-bezier(0.25,1,0.5,1) both"
|
||||
class="relative w-full max-w-[520px] max-h-[90vh] overflow-y-auto rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)]"
|
||||
style="animation: fadeUp 0.2s ease both; box-shadow: var(--shadow-dialog)"
|
||||
>
|
||||
<!-- Top accent edge -->
|
||||
<div class="h-[2px] rounded-t-[var(--radius-card)] bg-gradient-to-r from-transparent via-[var(--color-accent)] to-transparent"></div>
|
||||
|
||||
<div class="p-6">
|
||||
<h2 class="font-serif text-heading leading-tight tracking-[-0.02em] text-[var(--color-text-bright)]">
|
||||
Create Template
|
||||
@ -903,7 +899,7 @@
|
||||
<button
|
||||
onclick={handleCreate}
|
||||
disabled={creating || !createForm.name.trim() || !createForm.recipe.trim()}
|
||||
class="group flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2.5 text-ui font-semibold text-white transition-all duration-200 hover:shadow-[0_0_20px_var(--color-accent-glow-mid)] hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0 disabled:hover:shadow-none"
|
||||
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-accent)] px-5 py-2 text-ui font-semibold text-white transition-all duration-150 hover:brightness-115 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
|
||||
>
|
||||
{#if creating}
|
||||
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
|
||||
@ -921,20 +917,16 @@
|
||||
<!-- ── Delete Template Confirmation ────────────────────────────────── -->
|
||||
{#if deleteTarget}
|
||||
<div class="fixed inset-0 z-50 flex items-center justify-center">
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions -->
|
||||
<div
|
||||
class="absolute inset-0 bg-black/60"
|
||||
role="button"
|
||||
tabindex="-1"
|
||||
onclick={() => { if (!deleting) deleteTarget = null; }}
|
||||
onkeydown={(e) => { if (e.key === 'Escape' && !deleting) deleteTarget = null; }}
|
||||
></div>
|
||||
<div
|
||||
class="relative w-full max-w-[420px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)] shadow-dialog"
|
||||
style="animation: fadeUp 0.18s cubic-bezier(0.25,1,0.5,1) both"
|
||||
class="relative w-full max-w-[420px] rounded-[var(--radius-card)] border border-[var(--color-border-mid)] bg-[var(--color-bg-2)]"
|
||||
style="animation: fadeUp 0.2s ease both; box-shadow: var(--shadow-dialog)"
|
||||
>
|
||||
<!-- Danger accent edge -->
|
||||
<div class="h-[2px] rounded-t-[var(--radius-card)] bg-gradient-to-r from-transparent via-[var(--color-red)] to-transparent"></div>
|
||||
|
||||
<div class="p-6">
|
||||
<h2 class="font-serif text-heading leading-tight tracking-[-0.02em] text-[var(--color-text-bright)]">
|
||||
Delete Template
|
||||
@ -960,7 +952,7 @@
|
||||
<button
|
||||
onclick={handleDeleteTemplate}
|
||||
disabled={deleting}
|
||||
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-red)] px-5 py-2.5 text-ui font-semibold text-white transition-all duration-200 hover:shadow-[0_0_16px_rgba(207,129,114,0.25)] hover:brightness-110 disabled:opacity-50"
|
||||
class="flex items-center gap-2 rounded-[var(--radius-button)] bg-[var(--color-red)] px-5 py-2 text-ui font-semibold text-white transition-all duration-150 hover:brightness-110 hover:-translate-y-px active:translate-y-0 disabled:opacity-50 disabled:hover:translate-y-0"
|
||||
>
|
||||
{#if deleting}
|
||||
<svg class="animate-spin" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>
|
||||
|
||||
247
internal/api/handlers_admin_capsules.go
Normal file
247
internal/api/handlers_admin_capsules.go
Normal file
@ -0,0 +1,247 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"connectrpc.com/connect"
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"git.omukk.dev/wrenn/wrenn/internal/audit"
|
||||
"git.omukk.dev/wrenn/wrenn/internal/auth"
|
||||
"git.omukk.dev/wrenn/wrenn/internal/db"
|
||||
"git.omukk.dev/wrenn/wrenn/internal/id"
|
||||
"git.omukk.dev/wrenn/wrenn/internal/lifecycle"
|
||||
"git.omukk.dev/wrenn/wrenn/internal/service"
|
||||
"git.omukk.dev/wrenn/wrenn/internal/validate"
|
||||
pb "git.omukk.dev/wrenn/wrenn/proto/hostagent/gen"
|
||||
)
|
||||
|
||||
type adminCapsuleHandler struct {
|
||||
svc *service.SandboxService
|
||||
db *db.Queries
|
||||
pool *lifecycle.HostClientPool
|
||||
audit *audit.AuditLogger
|
||||
}
|
||||
|
||||
func newAdminCapsuleHandler(svc *service.SandboxService, db *db.Queries, pool *lifecycle.HostClientPool, al *audit.AuditLogger) *adminCapsuleHandler {
|
||||
return &adminCapsuleHandler{svc: svc, db: db, pool: pool, audit: al}
|
||||
}
|
||||
|
||||
// Create handles POST /v1/admin/capsules.
|
||||
func (h *adminCapsuleHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
var req createSandboxRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "invalid JSON body")
|
||||
return
|
||||
}
|
||||
|
||||
ac := auth.MustFromContext(r.Context())
|
||||
|
||||
sb, err := h.svc.Create(r.Context(), service.SandboxCreateParams{
|
||||
TeamID: id.PlatformTeamID,
|
||||
Template: req.Template,
|
||||
VCPUs: req.VCPUs,
|
||||
MemoryMB: req.MemoryMB,
|
||||
TimeoutSec: req.TimeoutSec,
|
||||
})
|
||||
if err != nil {
|
||||
status, code, msg := serviceErrToHTTP(err)
|
||||
writeError(w, status, code, msg)
|
||||
return
|
||||
}
|
||||
|
||||
h.audit.LogSandboxCreate(r.Context(), ac, sb.ID, sb.Template)
|
||||
writeJSON(w, http.StatusCreated, sandboxToResponse(sb))
|
||||
}
|
||||
|
||||
// List handles GET /v1/admin/capsules.
|
||||
func (h *adminCapsuleHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
sandboxes, err := h.svc.List(r.Context(), id.PlatformTeamID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "db_error", "failed to list sandboxes")
|
||||
return
|
||||
}
|
||||
|
||||
resp := make([]sandboxResponse, len(sandboxes))
|
||||
for i, sb := range sandboxes {
|
||||
resp[i] = sandboxToResponse(sb)
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// Get handles GET /v1/admin/capsules/{id}.
|
||||
func (h *adminCapsuleHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
sandboxIDStr := chi.URLParam(r, "id")
|
||||
|
||||
sandboxID, err := id.ParseSandboxID(sandboxIDStr)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "invalid sandbox ID")
|
||||
return
|
||||
}
|
||||
|
||||
sb, err := h.svc.Get(r.Context(), sandboxID, id.PlatformTeamID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "not_found", "sandbox not found")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, sandboxToResponse(sb))
|
||||
}
|
||||
|
||||
// Destroy handles DELETE /v1/admin/capsules/{id}.
|
||||
func (h *adminCapsuleHandler) Destroy(w http.ResponseWriter, r *http.Request) {
|
||||
sandboxIDStr := chi.URLParam(r, "id")
|
||||
ac := auth.MustFromContext(r.Context())
|
||||
|
||||
sandboxID, err := id.ParseSandboxID(sandboxIDStr)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "invalid sandbox ID")
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.svc.Destroy(r.Context(), sandboxID, id.PlatformTeamID); err != nil {
|
||||
status, code, msg := serviceErrToHTTP(err)
|
||||
writeError(w, status, code, msg)
|
||||
return
|
||||
}
|
||||
|
||||
h.audit.LogSandboxDestroy(r.Context(), ac, sandboxID)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
type adminSnapshotRequest struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
// Snapshot handles POST /v1/admin/capsules/{id}/snapshot.
|
||||
// Pauses the capsule, takes a snapshot as a platform template, then destroys the capsule.
|
||||
func (h *adminCapsuleHandler) Snapshot(w http.ResponseWriter, r *http.Request) {
|
||||
sandboxIDStr := chi.URLParam(r, "id")
|
||||
ac := auth.MustFromContext(r.Context())
|
||||
|
||||
sandboxID, err := id.ParseSandboxID(sandboxIDStr)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "invalid sandbox ID")
|
||||
return
|
||||
}
|
||||
|
||||
var req adminSnapshotRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "invalid JSON body")
|
||||
return
|
||||
}
|
||||
|
||||
if req.Name == "" {
|
||||
req.Name = id.NewSnapshotName()
|
||||
}
|
||||
if err := validate.SafeName(req.Name); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", fmt.Sprintf("invalid snapshot name: %s", err))
|
||||
return
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
|
||||
// Verify sandbox exists and belongs to platform team BEFORE any
|
||||
// destructive operations (template overwrite).
|
||||
sb, err := h.db.GetSandboxByTeam(ctx, db.GetSandboxByTeamParams{ID: sandboxID, TeamID: id.PlatformTeamID})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "not_found", "sandbox not found")
|
||||
return
|
||||
}
|
||||
if sb.Status != "running" && sb.Status != "paused" {
|
||||
writeError(w, http.StatusConflict, "invalid_state", "sandbox must be running or paused")
|
||||
return
|
||||
}
|
||||
|
||||
// Check if name already exists as a platform template.
|
||||
if existing, err := h.db.GetPlatformTemplateByName(ctx, req.Name); err == nil {
|
||||
// Delete old snapshot files from all hosts before removing the DB record.
|
||||
if err := deleteSnapshotBroadcast(ctx, h.db, h.pool, existing.TeamID, existing.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "agent_error", "failed to delete existing snapshot files")
|
||||
return
|
||||
}
|
||||
if err := h.db.DeleteTemplateByTeam(ctx, db.DeleteTemplateByTeamParams{Name: req.Name, TeamID: id.PlatformTeamID}); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "db_error", "failed to remove existing template record")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
agent, err := agentForHost(ctx, h.db, h.pool, sb.HostID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, "host_unavailable", "sandbox host is not reachable")
|
||||
return
|
||||
}
|
||||
|
||||
// Pre-mark sandbox as "paused" to prevent the reconciler from racing.
|
||||
if sb.Status == "running" {
|
||||
if _, err := h.db.UpdateSandboxStatus(ctx, db.UpdateSandboxStatusParams{
|
||||
ID: sandboxID, Status: "paused",
|
||||
}); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "db_error", "failed to update sandbox status")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Use a detached context so the snapshot completes even if the client disconnects.
|
||||
snapCtx, snapCancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer snapCancel()
|
||||
|
||||
newTemplateID := id.NewTemplateID()
|
||||
|
||||
resp, err := agent.CreateSnapshot(snapCtx, connect.NewRequest(&pb.CreateSnapshotRequest{
|
||||
SandboxId: sandboxIDStr,
|
||||
Name: req.Name,
|
||||
TeamId: formatUUIDForRPC(id.PlatformTeamID),
|
||||
TemplateId: formatUUIDForRPC(newTemplateID),
|
||||
}))
|
||||
if err != nil {
|
||||
// Snapshot failed — revert status.
|
||||
if sb.Status == "running" {
|
||||
if _, dbErr := h.db.UpdateSandboxStatus(snapCtx, db.UpdateSandboxStatusParams{
|
||||
ID: sandboxID, Status: "running",
|
||||
}); dbErr != nil {
|
||||
slog.Error("failed to revert sandbox status after snapshot error", "sandbox_id", sandboxIDStr, "error", dbErr)
|
||||
}
|
||||
}
|
||||
status, code, msg := agentErrToHTTP(err)
|
||||
writeError(w, status, code, msg)
|
||||
return
|
||||
}
|
||||
|
||||
tmpl, err := h.db.InsertTemplate(snapCtx, db.InsertTemplateParams{
|
||||
ID: newTemplateID,
|
||||
Name: req.Name,
|
||||
Type: "snapshot",
|
||||
Vcpus: sb.Vcpus,
|
||||
MemoryMb: sb.MemoryMb,
|
||||
SizeBytes: resp.Msg.SizeBytes,
|
||||
TeamID: id.PlatformTeamID,
|
||||
DefaultUser: "root",
|
||||
DefaultEnv: []byte("{}"),
|
||||
})
|
||||
if err != nil {
|
||||
slog.Error("failed to insert template record", "name", req.Name, "error", err)
|
||||
writeError(w, http.StatusInternalServerError, "db_error", "snapshot created but failed to record in database")
|
||||
return
|
||||
}
|
||||
|
||||
// Destroy the ephemeral capsule after successful snapshot.
|
||||
if err := h.svc.Destroy(snapCtx, sandboxID, id.PlatformTeamID); err != nil {
|
||||
slog.Error("failed to destroy capsule after snapshot", "sandbox_id", sandboxIDStr, "error", err)
|
||||
// Don't fail the response — the snapshot was created successfully.
|
||||
}
|
||||
|
||||
h.audit.LogSnapshotCreate(snapCtx, ac, req.Name)
|
||||
|
||||
if ctx.Err() != nil {
|
||||
slog.Info("snapshot created but client disconnected before response", "name", req.Name)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, templateToResponse(tmpl))
|
||||
}
|
||||
@ -126,6 +126,14 @@ func (h *authHandler) Signup(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
qtx := h.db.WithTx(tx)
|
||||
|
||||
// The first user to sign up becomes a platform admin.
|
||||
userCount, err := qtx.CountUsers(ctx)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "db_error", "failed to check user count")
|
||||
return
|
||||
}
|
||||
isFirstUser := userCount == 0
|
||||
|
||||
userID := id.NewUserID()
|
||||
_, err = qtx.InsertUser(ctx, db.InsertUserParams{
|
||||
ID: userID,
|
||||
@ -143,6 +151,13 @@ func (h *authHandler) Signup(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if isFirstUser {
|
||||
if err := qtx.SetUserAdmin(ctx, db.SetUserAdminParams{ID: userID, IsAdmin: true}); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "db_error", "failed to set admin status")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Create default team.
|
||||
teamID := id.NewTeamID()
|
||||
if _, err := qtx.InsertTeam(ctx, db.InsertTeamParams{
|
||||
@ -169,7 +184,7 @@ func (h *authHandler) Signup(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
token, err := auth.SignJWT(h.jwtSecret, userID, teamID, req.Email, req.Name, "owner", false)
|
||||
token, err := auth.SignJWT(h.jwtSecret, userID, teamID, req.Email, req.Name, "owner", isFirstUser)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "internal_error", "failed to generate token")
|
||||
return
|
||||
|
||||
@ -38,8 +38,8 @@ func newSnapshotHandler(svc *service.TemplateService, db *db.Queries, pool *life
|
||||
// deleteSnapshotBroadcast attempts to delete snapshot files on all online hosts.
|
||||
// Snapshots aren't currently host-tracked in the DB, so we broadcast to all hosts
|
||||
// and ignore NotFound errors.
|
||||
func (h *snapshotHandler) deleteSnapshotBroadcast(ctx context.Context, teamID, templateID pgtype.UUID) error {
|
||||
hosts, err := h.db.ListActiveHosts(ctx)
|
||||
func deleteSnapshotBroadcast(ctx context.Context, queries *db.Queries, pool *lifecycle.HostClientPool, teamID, templateID pgtype.UUID) error {
|
||||
hosts, err := queries.ListActiveHosts(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list hosts: %w", err)
|
||||
}
|
||||
@ -47,7 +47,7 @@ func (h *snapshotHandler) deleteSnapshotBroadcast(ctx context.Context, teamID, t
|
||||
if host.Status != "online" {
|
||||
continue
|
||||
}
|
||||
agent, err := h.pool.GetForHost(host)
|
||||
agent, err := pool.GetForHost(host)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
@ -141,7 +141,7 @@ func (h *snapshotHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
// Delete old snapshot files from all hosts before removing the DB record.
|
||||
if err := h.deleteSnapshotBroadcast(ctx, existing.TeamID, existing.ID); err != nil {
|
||||
if err := deleteSnapshotBroadcast(ctx, h.db, h.pool, existing.TeamID, existing.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "agent_error", "failed to delete existing snapshot files")
|
||||
return
|
||||
}
|
||||
@ -279,7 +279,7 @@ func (h *snapshotHandler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.deleteSnapshotBroadcast(ctx, tmpl.TeamID, tmpl.ID); err != nil {
|
||||
if err := deleteSnapshotBroadcast(ctx, h.db, h.pool, tmpl.TeamID, tmpl.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "agent_error", "failed to delete snapshot files")
|
||||
return
|
||||
}
|
||||
|
||||
@ -5,8 +5,23 @@ import (
|
||||
|
||||
"git.omukk.dev/wrenn/wrenn/internal/auth"
|
||||
"git.omukk.dev/wrenn/wrenn/internal/db"
|
||||
"git.omukk.dev/wrenn/wrenn/internal/id"
|
||||
)
|
||||
|
||||
// injectPlatformTeam overwrites the AuthContext's TeamID with the platform
|
||||
// sentinel UUID. This lets existing team-scoped handlers (exec, files, pty,
|
||||
// metrics) work unchanged under admin routes. Must run after requireAdmin.
|
||||
func injectPlatformTeam() func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ac := auth.MustFromContext(r.Context())
|
||||
ac.TeamID = id.PlatformTeamID
|
||||
ctx := auth.WithAuthContext(r.Context(), ac)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// requireAdmin validates that the authenticated user is a platform admin.
|
||||
// Must run after requireJWT (depends on AuthContext being present).
|
||||
// Re-validates against the DB — the JWT is_admin claim is for UI only;
|
||||
|
||||
@ -8,18 +8,21 @@ import (
|
||||
"git.omukk.dev/wrenn/wrenn/internal/id"
|
||||
)
|
||||
|
||||
// requireJWT validates the Authorization: Bearer <token> header, verifies the JWT
|
||||
// signature and expiry, and stamps UserID + TeamID + Email into the request context.
|
||||
// requireJWT validates a JWT from the Authorization: Bearer header or the
|
||||
// ?token= query parameter (for WebSocket connections that cannot send headers).
|
||||
func requireJWT(secret []byte) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
header := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(header, "Bearer ") {
|
||||
var tokenStr string
|
||||
if header := r.Header.Get("Authorization"); strings.HasPrefix(header, "Bearer ") {
|
||||
tokenStr = strings.TrimPrefix(header, "Bearer ")
|
||||
} else if t := r.URL.Query().Get("token"); t != "" {
|
||||
tokenStr = t
|
||||
}
|
||||
if tokenStr == "" {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "Authorization: Bearer <token> required")
|
||||
return
|
||||
}
|
||||
|
||||
tokenStr := strings.TrimPrefix(header, "Bearer ")
|
||||
claims, err := auth.VerifyJWT(secret, tokenStr)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "invalid or expired token")
|
||||
|
||||
@ -74,6 +74,7 @@ func New(
|
||||
buildH := newBuildHandler(buildSvc, queries, pool)
|
||||
channelH := newChannelHandler(channelSvc, al)
|
||||
ptyH := newPtyHandler(queries, pool)
|
||||
adminCapsules := newAdminCapsuleHandler(sandboxSvc, queries, pool, al)
|
||||
|
||||
// OpenAPI spec and docs.
|
||||
r.Get("/openapi.yaml", serveOpenAPI)
|
||||
@ -207,6 +208,23 @@ func New(
|
||||
r.Get("/builds", buildH.List)
|
||||
r.Get("/builds/{id}", buildH.Get)
|
||||
r.Post("/builds/{id}/cancel", buildH.Cancel)
|
||||
r.Post("/capsules", adminCapsules.Create)
|
||||
r.Get("/capsules", adminCapsules.List)
|
||||
r.Route("/capsules/{id}", func(r chi.Router) {
|
||||
r.Use(injectPlatformTeam())
|
||||
r.Get("/", adminCapsules.Get)
|
||||
r.Delete("/", adminCapsules.Destroy)
|
||||
r.Post("/snapshot", adminCapsules.Snapshot)
|
||||
r.Post("/exec", exec.Exec)
|
||||
r.Get("/exec/stream", execStream.ExecStream)
|
||||
r.Post("/files/write", files.Upload)
|
||||
r.Post("/files/read", files.Download)
|
||||
r.Post("/files/list", fsH.ListDir)
|
||||
r.Post("/files/mkdir", fsH.MakeDir)
|
||||
r.Post("/files/remove", fsH.Remove)
|
||||
r.Get("/metrics", metricsH.GetMetrics)
|
||||
r.Get("/pty", ptyH.PtySession)
|
||||
})
|
||||
})
|
||||
|
||||
return &Server{router: r, BuildSvc: buildSvc}
|
||||
|
||||
@ -11,6 +11,17 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const countUsers = `-- name: CountUsers :one
|
||||
SELECT COUNT(*) FROM users
|
||||
`
|
||||
|
||||
func (q *Queries) CountUsers(ctx context.Context) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, countUsers)
|
||||
var count int64
|
||||
err := row.Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
const deleteAdminPermission = `-- name: DeleteAdminPermission :exec
|
||||
DELETE FROM admin_permissions WHERE user_id = $1 AND permission = $2
|
||||
`
|
||||
|
||||
Reference in New Issue
Block a user