Files
tiny-forge/web/src/lib/components/InstanceCard.svelte
T
alexei.dolgolyov a4362b842d
Build / build (push) Successful in 11m42s
fix: harden security, fix concurrency bugs, and address review findings
Security:
- rate limit /api/webhook routes per-IP and cap concurrent site syncs
- global SSE connection cap (256) with new sse_gate
- validate ?tail= and cap JSON log responses at 4 MiB
- strip ANSI/CSI/OSC and control bytes from streamed log lines
- redact webhook secret from request log middleware
- scrub host details from /api/health for non-admin viewers
- drop container_id from /api/system/stats/top for non-admins
- generate webhook secrets via crypto/rand; require >=32 chars on insert
- verify iid path consistency in streamContainerLogs
- LimitReader on site webhook body; reject malformed non-empty bodies

Concurrency / correctness:
- stats collector: Stop() no longer hangs without Start(), semaphore
  acquired in parent loop so ctx cancellation short-circuits the queue,
  in-flight tick cancellable via shared base context, zero-ts guard
- webhook handler: replace fire-and-forget goroutine with WaitGroup-tracked
  workers + Drain() wired into graceful shutdown
- $derived(() => ...) mis-idiom fixed in ContainerStats / InstanceCard /
  ProjectCard (returned function instead of value)
- SystemResourcesCard: rename `window` and `t` locals to avoid shadowing
  globalThis.window and the i18n `t` import

Quality / performance:
- replace O(n^2) insertion sort with sort.Slice in stats top
- runMigrations only swallows duplicate-column / already-exists errors
- PruneStatsSamplesBefore wrapped in a transaction
- collapse N+1 in unusedImageStats / pruneImages to one ListAllInstances
  pass; surface DB errors instead of silently treating them as inactive
- run Docker Info + DiskUsage in parallel via errgroup
- container log SSE emits `: ping` heartbeat every 20 s
- imageMatches case-insensitive on registry host (RFC behaviour)
- log warning on invalid stage tag pattern instead of silent skip
- reject malformed non-empty site webhook payloads

Frontend / i18n:
- shared formatBytes utility replaces three local copies
- statsInterval store drives dynamic "no samples / collection disabled"
  copy across ContainerStats and SystemResourcesCard
- top consumers row now shows owner_name (project/stage or site name)
- drop seven `as any` casts on the Settings type; add cloudflare_api_token
  write-only field
- move "Service status", "Docker daemon", "Docker unreachable",
  "Proxy unreachable", "reachable", and "Docker daemon is not reachable."
  strings into en/ru i18n bundles
2026-05-07 00:56:14 +03:00

176 lines
5.7 KiB
Svelte

<!--
Task 5: Instance card with inline status badges, icon action buttons, improved layout.
-->
<script lang="ts">
import type { Instance } from '$lib/types';
import StatusBadge from './StatusBadge.svelte';
import ContainerStats from './ContainerStats.svelte';
import ContainerLogs from './ContainerLogs.svelte';
import ConfirmDialog from './ConfirmDialog.svelte';
import { IconPlay, IconStop, IconRestart, IconTrash, IconExternalLink, IconEvents } from '$lib/components/icons';
import { t } from '$lib/i18n';
import { fmt } from '$lib/format/datetime';
import * as api from '$lib/api';
interface Props {
instance: Instance;
projectId: string;
domain?: string;
onchange?: () => void;
}
const { instance, projectId, domain = '', onchange }: Props = $props();
let loading = $state(false);
let error = $state('');
let confirmAction = $state<'stop' | 'restart' | 'remove' | null>(null);
let showLogs = $state(false);
const subdomainUrl = $derived(
instance.subdomain && domain
? `https://${instance.subdomain}.${domain}`
: instance.subdomain ? `https://${instance.subdomain}` : ''
);
const timeSinceCreated = $derived($fmt.relative(instance.created_at));
async function handleAction(action: 'stop' | 'start' | 'restart' | 'remove') {
loading = true;
error = '';
confirmAction = null;
try {
switch (action) {
case 'stop':
await api.stopInstance(projectId, instance.stage_id, instance.id);
break;
case 'start':
await api.startInstance(projectId, instance.stage_id, instance.id);
break;
case 'restart':
await api.restartInstance(projectId, instance.stage_id, instance.id);
break;
case 'remove':
await api.removeInstance(projectId, instance.stage_id, instance.id);
break;
}
onchange?.();
} catch (e) {
error = e instanceof Error ? e.message : $t('instance.actionFailed');
} finally {
loading = false;
}
}
function requestConfirm(action: 'stop' | 'restart' | 'remove') {
confirmAction = action;
}
</script>
<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-4 shadow-[var(--shadow-sm)] transition-all duration-200 hover:shadow-[var(--shadow-md)]">
<div class="flex items-start justify-between">
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2">
<span class="truncate font-mono text-sm font-medium text-[var(--text-primary)]">
{instance.image_tag}
</span>
<StatusBadge status={instance.status} size="sm" />
</div>
{#if subdomainUrl}
<a
href={subdomainUrl}
target="_blank"
rel="noopener noreferrer"
class="mt-1.5 inline-flex items-center gap-1 text-xs text-[var(--text-link)] hover:text-[var(--text-link-hover)] transition-colors"
>
{instance.subdomain}
<IconExternalLink size={12} />
</a>
{/if}
<div class="mt-1.5 flex items-center gap-3 text-xs text-[var(--text-tertiary)]">
<span class="rounded bg-[var(--surface-card-hover)] px-1.5 py-0.5 font-mono">:{instance.port}</span>
<span>{timeSinceCreated}</span>
</div>
</div>
<!-- Action buttons -->
<div class="ml-3 flex items-center gap-1">
{#if instance.status === 'running'}
<button
type="button"
class="rounded-lg p-2 text-[var(--text-tertiary)] hover:bg-amber-50 hover:text-amber-600 disabled:opacity-50 transition-all duration-150 active:animate-press"
title={$t('common.stop')}
disabled={loading}
onclick={() => requestConfirm('stop')}
>
<IconStop size={16} />
</button>
<button
type="button"
class="rounded-lg p-2 text-[var(--text-tertiary)] hover:bg-blue-50 hover:text-blue-600 disabled:opacity-50 transition-all duration-150 active:animate-press"
title={$t('common.restart')}
disabled={loading}
onclick={() => requestConfirm('restart')}
>
<IconRestart size={16} />
</button>
{:else if instance.status === 'stopped'}
<button
type="button"
class="rounded-lg p-2 text-[var(--text-tertiary)] hover:bg-emerald-50 hover:text-emerald-600 disabled:opacity-50 transition-all duration-150 active:animate-press"
title={$t('common.start')}
disabled={loading}
onclick={() => handleAction('start')}
>
<IconPlay size={16} />
</button>
{/if}
<button
type="button"
class="rounded-lg p-2 text-[var(--text-tertiary)] hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-gray-800 dark:hover:text-gray-300 transition-all duration-150"
title={$t('logs.title')}
onclick={() => { showLogs = !showLogs; }}
>
<IconEvents size={16} />
</button>
<button
type="button"
class="rounded-lg p-2 text-[var(--text-tertiary)] hover:bg-red-50 hover:text-red-600 disabled:opacity-50 transition-all duration-150 active:animate-press"
title={$t('common.remove')}
disabled={loading}
onclick={() => requestConfirm('remove')}
>
<IconTrash size={16} />
</button>
</div>
</div>
{#if instance.status === 'running'}
<ContainerStats source={{ kind: 'instance', projectId, stageId: instance.stage_id, instanceId: instance.id }} />
{/if}
{#if showLogs}
<div class="mt-2">
<ContainerLogs
source={{ kind: 'instance', projectId, stageId: instance.stage_id, instanceId: instance.id }}
onclose={() => { showLogs = false; }}
/>
</div>
{/if}
{#if error}
<p class="mt-2 text-xs text-[var(--color-danger)]">{error}</p>
{/if}
</div>
<ConfirmDialog
open={confirmAction !== null}
title={confirmAction ? $t(`confirm.${confirmAction}Instance`) : ''}
message={confirmAction ? $t(`instance.${confirmAction}Confirm`) : ''}
confirmLabel={confirmAction ? $t(`confirm.${confirmAction}Action`) : ''}
confirmVariant={confirmAction === 'remove' ? 'danger' : 'primary'}
onconfirm={() => { if (confirmAction) handleAction(confirmAction); }}
oncancel={() => { confirmAction = null; }}
/>