feat: add first page with auth and containers list and agents
This commit is contained in:
121
web/src/lib/LogModal.svelte
Normal file
121
web/src/lib/LogModal.svelte
Normal file
@ -0,0 +1,121 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy, tick } from "svelte";
|
||||
import { connectLogs } from "./api";
|
||||
|
||||
let {
|
||||
agentId,
|
||||
containerId,
|
||||
containerName,
|
||||
onClose,
|
||||
}: {
|
||||
agentId: string;
|
||||
containerId: string;
|
||||
containerName: string;
|
||||
onClose: () => void;
|
||||
} = $props();
|
||||
|
||||
interface LogLine {
|
||||
stream: string;
|
||||
line: string;
|
||||
}
|
||||
|
||||
let lines = $state<LogLine[]>([]);
|
||||
let autoScroll = $state(true);
|
||||
let logEl = $state<HTMLElement | null>(null);
|
||||
let disconnect: (() => void) | null = null;
|
||||
|
||||
function stripAnsi(str: string): string {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
return str.replace(/\x1b\[[0-9;]*[mGKHF]/g, "");
|
||||
}
|
||||
|
||||
async function scrollToBottom() {
|
||||
if (!autoScroll || !logEl) return;
|
||||
await tick();
|
||||
logEl.scrollTop = logEl.scrollHeight;
|
||||
}
|
||||
|
||||
function onScroll() {
|
||||
if (!logEl) return;
|
||||
const atBottom = logEl.scrollHeight - logEl.scrollTop - logEl.clientHeight < 40;
|
||||
autoScroll = atBottom;
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
disconnect = connectLogs(agentId, containerId, async (msg) => {
|
||||
if (msg.line) {
|
||||
lines.push({ stream: msg.stream, line: stripAnsi(msg.line) });
|
||||
if (lines.length > 2000) lines = lines.slice(-2000);
|
||||
await scrollToBottom();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
onDestroy(() => disconnect?.());
|
||||
|
||||
function handleKey(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") onClose();
|
||||
}
|
||||
</script>
|
||||
|
||||
<svelte:window onkeydown={handleKey} />
|
||||
|
||||
<!-- Backdrop -->
|
||||
<div
|
||||
class="fixed inset-0 z-50 flex flex-col bg-black/70 backdrop-blur-sm"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="Logs — {containerName}"
|
||||
>
|
||||
<!-- Modal panel -->
|
||||
<div class="flex flex-col m-4 md:m-8 flex-1 min-h-0 card overflow-hidden">
|
||||
|
||||
<!-- Header -->
|
||||
<div class="flex items-center gap-3 px-4 py-3 border-b border-white/[0.07] shrink-0">
|
||||
<span class="w-2 h-2 rounded-full bg-signal-green animate-pulse"></span>
|
||||
<span class="font-mono text-sm font-semibold text-slate-200">{containerName}</span>
|
||||
<span class="text-xs text-slate-600 ml-1">logs</span>
|
||||
|
||||
<div class="ml-auto flex items-center gap-3">
|
||||
<label class="flex items-center gap-1.5 text-xs text-slate-500 cursor-pointer select-none">
|
||||
<input
|
||||
type="checkbox"
|
||||
bind:checked={autoScroll}
|
||||
class="accent-emerald w-3 h-3"
|
||||
/>
|
||||
Auto-scroll
|
||||
</label>
|
||||
<button
|
||||
onclick={() => { lines = []; }}
|
||||
class="nav-btn text-xs px-2"
|
||||
title="Effacer"
|
||||
>
|
||||
Effacer
|
||||
</button>
|
||||
<button onclick={onClose} class="nav-btn" title="Fermer (Échap)">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="M6 18L18 6M6 6l12 12"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Log output -->
|
||||
<div
|
||||
bind:this={logEl}
|
||||
onscroll={onScroll}
|
||||
class="flex-1 overflow-y-auto font-mono text-xs leading-5 p-4 space-y-px bg-abyss-900"
|
||||
>
|
||||
{#if lines.length === 0}
|
||||
<p class="text-slate-700 italic">En attente des logs…</p>
|
||||
{:else}
|
||||
{#each lines as { stream, line }, i (i)}
|
||||
<div class="whitespace-pre-wrap break-all {stream === 'stderr' ? 'text-signal-red/80' : 'text-slate-300'}">
|
||||
{line}
|
||||
</div>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
138
web/src/lib/api.ts
Normal file
138
web/src/lib/api.ts
Normal file
@ -0,0 +1,138 @@
|
||||
import { getToken, clearToken } from "./auth";
|
||||
|
||||
export interface ContainerPort {
|
||||
host_port: number;
|
||||
container_port: number;
|
||||
protocol: string;
|
||||
host_ip: string;
|
||||
}
|
||||
|
||||
export interface ContainerInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
image: string;
|
||||
status: string;
|
||||
state: string;
|
||||
ports: ContainerPort[];
|
||||
created_at: number;
|
||||
labels: Record<string, string>;
|
||||
compose_project: string;
|
||||
}
|
||||
|
||||
export interface ContainerEntry {
|
||||
agent_id: string;
|
||||
hostname: string;
|
||||
alias: string;
|
||||
ip_address: string;
|
||||
container: ContainerInfo;
|
||||
}
|
||||
|
||||
export interface Agent {
|
||||
id: string;
|
||||
hostname: string;
|
||||
alias: string;
|
||||
ip_address: string;
|
||||
arch: string;
|
||||
os: string;
|
||||
online: boolean;
|
||||
last_seen_at: string;
|
||||
}
|
||||
|
||||
const BASE = "/api/v1";
|
||||
|
||||
function authHeaders(): Record<string, string> {
|
||||
const token = getToken();
|
||||
return token ? { Authorization: `Bearer ${token}` } : {};
|
||||
}
|
||||
|
||||
async function apiFetch(input: string, init: RequestInit = {}): Promise<Response> {
|
||||
const r = await fetch(input, {
|
||||
...init,
|
||||
headers: { ...authHeaders(), ...(init.headers as Record<string, string> ?? {}) },
|
||||
});
|
||||
if (r.status === 401) {
|
||||
clearToken();
|
||||
location.href = "/login";
|
||||
throw new Error("Session expirée");
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
export async function fetchAgents(): Promise<Agent[]> {
|
||||
const r = await apiFetch(`${BASE}/agents`);
|
||||
if (!r.ok) throw new Error(`agents: ${r.status}`);
|
||||
return r.json();
|
||||
}
|
||||
|
||||
export async function updateAgent(id: string, alias: string): Promise<Agent> {
|
||||
const r = await apiFetch(`${BASE}/agents/${id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ alias }),
|
||||
});
|
||||
if (!r.ok) throw new Error(`update agent: ${r.status}`);
|
||||
return r.json();
|
||||
}
|
||||
|
||||
export async function fetchContainers(): Promise<ContainerEntry[]> {
|
||||
const ac = new AbortController();
|
||||
const t = setTimeout(() => ac.abort(), 8000);
|
||||
try {
|
||||
const r = await apiFetch(`${BASE}/containers`, { signal: ac.signal });
|
||||
if (!r.ok) throw new Error(`containers: ${r.status}`);
|
||||
return r.json();
|
||||
} finally {
|
||||
clearTimeout(t);
|
||||
}
|
||||
}
|
||||
|
||||
export async function containerAction(
|
||||
agentId: string,
|
||||
containerId: string,
|
||||
action: "start" | "stop" | "restart" | "remove"
|
||||
): Promise<{ command_id: string }> {
|
||||
const r = await apiFetch(
|
||||
`${BASE}/agents/${agentId}/containers/${containerId}/action`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action }),
|
||||
}
|
||||
);
|
||||
if (!r.ok) throw new Error(`action failed: ${r.status}`);
|
||||
return r.json();
|
||||
}
|
||||
|
||||
export function connectLogs(
|
||||
agentId: string,
|
||||
containerId: string,
|
||||
onLine: (line: { stream: string; line: string }) => void,
|
||||
tail = 200,
|
||||
follow = true,
|
||||
): () => void {
|
||||
const proto = location.protocol === "https:" ? "wss" : "ws";
|
||||
const token = getToken() ?? "";
|
||||
const ws = new WebSocket(
|
||||
`${proto}://${location.host}/api/v1/agents/${agentId}/containers/${containerId}/logs?token=${encodeURIComponent(token)}&tail=${tail}&follow=${follow}`
|
||||
);
|
||||
ws.onmessage = (e) => {
|
||||
try { onLine(JSON.parse(e.data)); } catch {}
|
||||
};
|
||||
return () => ws.close();
|
||||
}
|
||||
|
||||
export function connectEvents(
|
||||
onEvent: (evt: { type: string; agent_id?: string; payload: unknown }) => void
|
||||
): () => void {
|
||||
const proto = location.protocol === "https:" ? "wss" : "ws";
|
||||
const token = getToken() ?? "";
|
||||
const ws = new WebSocket(
|
||||
`${proto}://${location.host}/api/v1/events?token=${encodeURIComponent(token)}`
|
||||
);
|
||||
ws.onmessage = (e) => {
|
||||
try {
|
||||
onEvent(JSON.parse(e.data));
|
||||
} catch {}
|
||||
};
|
||||
return () => ws.close();
|
||||
}
|
||||
35
web/src/lib/auth.ts
Normal file
35
web/src/lib/auth.ts
Normal file
@ -0,0 +1,35 @@
|
||||
const KEY = "containarr_token";
|
||||
|
||||
export function getToken(): string | null {
|
||||
return localStorage.getItem(KEY);
|
||||
}
|
||||
|
||||
export function setToken(token: string) {
|
||||
localStorage.setItem(KEY, token);
|
||||
}
|
||||
|
||||
export function clearToken() {
|
||||
localStorage.removeItem(KEY);
|
||||
}
|
||||
|
||||
export function isLoggedIn(): boolean {
|
||||
const t = getToken();
|
||||
if (!t) return false;
|
||||
try {
|
||||
const payload = JSON.parse(atob(t.split(".")[1]));
|
||||
return payload.exp * 1000 > Date.now();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function login(username: string, password: string): Promise<void> {
|
||||
const r = await fetch("/api/v1/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
if (!r.ok) throw new Error("Identifiants invalides");
|
||||
const { token } = await r.json();
|
||||
setToken(token);
|
||||
}
|
||||
Reference in New Issue
Block a user