feat(discovery+runtime): restore static-site wizard discovery + close /sites/[id] feature parity
Build / build (push) Successful in 10m43s

Two-stage feature arc closing the gaps left by the hard legacy cutover.
The static-site creation wizard regains its auto-discovery + connection-test
flow; /apps/[id] grows the runtime/storage/lifecycle surface the legacy
/sites/[id] page used to expose.

Backend (Go)
- internal/api/discovery.go: six admin-gated endpoints wrapping
  staticsite.GitProvider — POST /api/discovery/git/{detect-provider,
  test-connection,repos,branches,tree} + GET /api/discovery/image/conflicts.
  Identifier validation (validateGitIdent / validateGitBranch) at the
  boundary so provider URL interpolation cannot be hijacked via `..`.
  Upstream errors scrubbed: detailed slog on the server, generic 502 to
  the client (mitigates token-reflection-in-error-page).
- internal/api/workload_runtime.go: four endpoints —
  GET /api/workloads/{id}/runtime-state decodes containers.extra_json for
  static workloads; GET /api/workloads/{id}/storage execs `du -sb /app/data`
  with a 30s in-process cache (storageProbeCache) so polling can't turn
  into per-request execs; POST /api/workloads/{id}/{stop,start} iterate
  ListContainersByWorkload and call docker.StopContainer / StartContainer,
  returning 200 / 409 (nothing to act on) / 502 (all failed).
- internal/staticsite/safehttp.go: NewSafeHTTPClient + ValidateBaseURL +
  blockReason. DialContext re-resolves hostnames and refuses loopback /
  link-local / multicast / unspecified addresses. RFC1918 + ULA explicitly
  allowed (self-hosted Gitea on LAN is the dominant deployment).
  Replaced four raw &http.Client{} constructions in the provider files.
- internal/staticsite/gitlab_provider.go: url.PathEscape each segment in
  the raw-file URL builder for parity with projectPath().
- Test coverage: 26 cases in discovery_test.go (image-tag stripping,
  source-config decoding, conflict scenarios, validator boundaries,
  scheme rejection), 14 in workload_runtime_test.go (404 / 409 / nil-docker
  / probe-cache), 16 in safehttp_test.go (URL validation + block-reason
  policy matrix + live dial against loopback + AWS metadata literals).

Frontend (Svelte 5 + runes)
- web/src/lib/api.ts: typed wrappers for every endpoint, AbortSignal
  threaded through post(); ApiError exported so callers can narrow on
  e.status; new DetectedGitProvider narrow union.
- web/src/routes/apps/new/+page.svelte: static-form discovery controls
  (auto-detect provider, test connection, repo / branch / folder
  EntityPickers, Deno auto-detect); image-form conflict panel with
  debounced lookup + double-click submit guard ("Forge anyway") + Inspect
  button that pre-fills port/healthcheck; English error fallbacks routed
  through apps.new.errors.* (en + ru).
- web/src/routes/apps/[id]/+page.svelte: runtime-state panel + storage
  panel + Stop / Start / Open-site toolbar; universal live-state badge
  in the hero lede for image/compose/static (RUNNING / TRANSITIONING /
  STOPPED / NOT DEPLOYED / MIXED · n/m RUNNING); ContainerStats panel
  per row (auto-collapsing native <details> when N > 2); read-only
  webhook bindings summary card; responsive toolbar overflow with native
  <details> at <640px (z-index 100 above sticky nav).
- web/src/app.css: project-wide .forge-btn-ghost:focus-visible outline.

Hardening from go-reviewer + security-reviewer + typescript-reviewer +
frontend-design UI/UX subagents (0 CRITICAL, all HIGH/BLOCKER addressed
inline, IMPORTANT applied before commit):
- AbortController + per-call sequence tokens on every long-running
  fetch (loadRuntimeState / loadStorage / loadTriggerMeta / inspectImage /
  listImageConflicts) plus onDestroy cleanup so late resolves cannot
  mutate dead component state.
- doStop / doStart snapshot and restore `error` across the finally-block
  reload so a load()-cleared message doesn't hide a real failure.
- triggersById refreshed after inline trigger creation so the webhook
  card doesn't silently exclude the just-created trigger.
- Live-state badge wraps in role=status / aria-live=polite (no redundant
  aria-label).
- Webhook row has a single click target (was two pointing at the same URL).
- Empty webhook section hides entirely.
- Dropped role=menu / role=menuitem from the overflow menu (they would
  promise arrow-key nav we don't wire; native Tab + ESC carry it).

Doc
- docs/CODEMAPS/INDEX.md + new docs/CODEMAPS/discovery-and-runtime.md
  map the endpoint surface, security posture, frontend integration
  patterns, and an "add a new probe" recipe.

Verification
- svelte-check: 0 errors, 3 pre-existing a11y warnings.
- go build + go vet + go test ./...: all green.
- i18n parity: en + ru at 1413 keys each.
- Live smoke against :8090: 404 / 409 / 502 envelopes correct, discovery
  sanity passes, ProbeError surfaces on no-container path.
This commit is contained in:
2026-05-16 21:35:51 +03:00
parent ef62a41fc0
commit ea55d31177
19 changed files with 4333 additions and 81 deletions
+4
View File
@@ -248,6 +248,10 @@ input[type="number"] {
color: var(--text-primary);
border-color: var(--color-brand-300);
}
.forge-btn-ghost:focus-visible {
outline: 2px solid var(--border-focus);
outline-offset: 2px;
}
.forge-btn-ghost:disabled { opacity: 0.5; cursor: not-allowed; }
.forge-btn-icon {
+146 -7
View File
@@ -32,7 +32,7 @@ import type {
// ── Helpers ─────────────────────────────────────────────────────────
class ApiError extends Error {
export class ApiError extends Error {
constructor(
message: string,
public readonly status: number
@@ -141,11 +141,13 @@ function get<T>(path: string, signal?: AbortSignal): Promise<T> {
return request<T>(path, signal ? { signal } : undefined);
}
function post<T>(path: string, body?: unknown): Promise<T> {
return request<T>(path, {
function post<T>(path: string, body?: unknown, signal?: AbortSignal): Promise<T> {
const init: RequestInit = {
method: 'POST',
body: body !== undefined ? JSON.stringify(body) : undefined
});
};
if (signal) init.signal = signal;
return request<T>(path, init);
}
function put<T>(path: string, body: unknown): Promise<T> {
@@ -171,8 +173,146 @@ function patch<T>(path: string, body: unknown): Promise<T> {
// image port/healthcheck. `quickDeploy` (POST /api/deploy/quick) is gone:
// it created a legacy Project + Stage in the now-dead path.
export function inspectImage(image: string): Promise<InspectResult> {
return post<InspectResult>('/api/deploy/inspect', { image });
export function inspectImage(image: string, signal?: AbortSignal): Promise<InspectResult> {
return post<InspectResult>('/api/deploy/inspect', { image }, signal);
}
// ── Discovery (/apps/new wizard helpers) ───────────────────────────
// These endpoints back the auto-discovery + connection-test flow that
// the static-site creation wizard used in the legacy /sites/new page.
// They are admin-gated; the token is plaintext over HTTPS and is not
// persisted server-side.
// GitProviderKind is the union the *frontend* sends. The empty string
// means "auto-detect server-side" (DetectProviderWithProbe runs).
export type GitProviderKind = '' | 'gitea' | 'github' | 'gitlab';
// DetectedGitProvider is the narrower union the backend's detect
// endpoint actually returns — `staticsite.DetectProviderWithProbe`
// always resolves to one of the three concrete kinds (it falls back to
// `gitea` for unknown hosts). Kept distinct from GitProviderKind so a
// successful detection cannot ever set the dropdown back to "".
export type DetectedGitProvider = 'gitea' | 'github' | 'gitlab';
export interface RepoInfo {
owner: string;
name: string;
full_name: string;
description: string;
private: boolean;
html_url: string;
}
export interface FolderEntry {
path: string;
is_dir: boolean;
}
export interface DiscoveryGitRequest {
provider?: GitProviderKind;
base_url: string;
access_token?: string;
repo_owner?: string;
repo_name?: string;
branch?: string;
query?: string;
}
export interface ImageConflict {
id: string;
name: string;
image: string;
app_id?: string;
}
export function detectGitProvider(
baseURL: string,
signal?: AbortSignal
): Promise<{ provider: DetectedGitProvider }> {
return post<{ provider: DetectedGitProvider }>(
'/api/discovery/git/detect-provider',
{ base_url: baseURL },
signal
);
}
export function testGitConnection(
req: DiscoveryGitRequest,
signal?: AbortSignal
): Promise<{ status: string }> {
return post<{ status: string }>('/api/discovery/git/test-connection', req, signal);
}
export function listGitRepos(req: DiscoveryGitRequest, signal?: AbortSignal): Promise<RepoInfo[]> {
return post<RepoInfo[]>('/api/discovery/git/repos', req, signal);
}
export function listGitBranches(
req: DiscoveryGitRequest,
signal?: AbortSignal
): Promise<string[]> {
return post<string[]>('/api/discovery/git/branches', req, signal);
}
export function listGitTree(req: DiscoveryGitRequest, signal?: AbortSignal): Promise<FolderEntry[]> {
return post<FolderEntry[]>('/api/discovery/git/tree', req, signal);
}
export function listImageConflicts(image: string, signal?: AbortSignal): Promise<ImageConflict[]> {
return get<ImageConflict[]>(
`/api/discovery/image/conflicts?image=${encodeURIComponent(image)}`,
signal
);
}
// ── Workload runtime view (runtime-state, storage, stop, start) ────
// Backed by internal/api/workload_runtime.go. The shapes mirror the
// Go side exactly so the UI can render without further normalization.
export interface WorkloadRuntimeState {
source_kind: string;
has_state: boolean;
container_id?: string;
state?: string;
status?: string;
last_commit_sha?: string;
last_sync_at?: string;
last_error?: string;
}
export interface WorkloadStorageUsage {
source_kind: string;
enabled: boolean;
used_bytes: number;
limit_mb?: number;
probe_error?: string;
}
export interface StopStartResult {
touched: number;
failed: number;
}
export function getWorkloadRuntimeState(
id: string,
signal?: AbortSignal
): Promise<WorkloadRuntimeState> {
return get<WorkloadRuntimeState>(`/api/workloads/${id}/runtime-state`, signal);
}
export function getWorkloadStorage(
id: string,
signal?: AbortSignal
): Promise<WorkloadStorageUsage> {
return get<WorkloadStorageUsage>(`/api/workloads/${id}/storage`, signal);
}
export function stopWorkload(id: string): Promise<StopStartResult> {
return post<StopStartResult>(`/api/workloads/${id}/stop`);
}
export function startWorkload(id: string): Promise<StopStartResult> {
return post<StopStartResult>(`/api/workloads/${id}/start`);
}
// ── Registries ──────────────────────────────────────────────────────
@@ -1055,4 +1195,3 @@ export function getLogScanStats(signal?: AbortSignal): Promise<LogScanStats> {
return get<LogScanStats>('/api/log-scan-rules/stats', signal);
}
export { ApiError };
+93
View File
@@ -1253,6 +1253,29 @@
"staticRenderMarkdown": "Render markdown",
"staticRenderMarkdownDesc": "— auto-render <code>.md</code> files as HTML pages.",
"staticFoot": "The webhook secret for git push triggers lives on the workload's Webhook panel after creation.",
"staticDetectProvider": "Detect",
"staticDetectedOk": "Detected: {provider}",
"staticDetectedFailed": "Detection failed: {error}",
"staticTestConnection": "Test connection",
"staticConnectionOk": "Connected",
"staticConnectionFailed": "Connection failed: {error}",
"staticBrowseRepos": "Browse repositories",
"staticBrowseBranches": "Browse branches",
"staticBrowseFolders": "Browse folders",
"staticPickerRepoTitle": "Select repository",
"staticPickerRepoPlaceholder": "Filter repositories…",
"staticPickerBranchTitle": "Select branch",
"staticPickerBranchPlaceholder": "Filter branches…",
"staticFolderRoot": "/ (root)",
"staticFolderSelectedPrefix": "Selected folder:",
"staticTreeLoading": "Loading folder tree…",
"staticTreeEmpty": "No folders found in this branch.",
"staticDenoAutoDetected": "Auto-detected an <code>api/</code> folder — switched to Deno mode.",
"imageConflictTag": "IMAGE IN USE",
"imageConflictHeading": "{count} workload(s) already use this image:",
"imageConflictOpenBtn": "Open",
"imageConflictAcknowledgeNote": "If this is intentional (for example a separate stage), continue to create a new workload.",
"imageConflictBlockedSubmit": "Conflicts detected for this image — review the list above, then click Create again to proceed.",
"sourceConfigJsonTitle": "source_config.json · {kind}",
"sourceConfigJsonAria": "Source plugin configuration (JSON)",
"triggerNumLabel": "Trigger",
@@ -1273,6 +1296,22 @@
"cancel": "Cancel",
"submit": "Forge app",
"submitting": "Forging…",
"submitAnyway": "Forge anyway",
"errors": {
"detectionFailed": "Provider detection failed.",
"connectionFailed": "Connection failed.",
"reposFailed": "Failed to load repositories.",
"branchesFailed": "Failed to load branches.",
"treeFailed": "Failed to load folder tree.",
"sourceConfigInvalid": "Source config is not valid JSON.",
"triggerBindUnknown": "unknown error",
"createFailed": "Workload create failed.",
"inspectFailed": "Image inspect failed."
},
"imageInspect": "Inspect",
"imageInspectHint": "Pulls port + healthcheck from the image so you don't have to type them.",
"imageInspectOk": "Inspected — port + healthcheck filled.",
"imageInspectError": "Inspect failed: {error}",
"triggers": {
"section": "Trigger",
"sectionSub": "Optional. Pick how this app gets a redeploy signal — registry watcher, git event, or manual button.",
@@ -1304,6 +1343,60 @@
"deployError": "Deploy failed",
"saveError": "Save failed",
"deleteError": "Delete failed",
"runtimeState": {
"title": "Sync status",
"sub": "Last successful sync of the source repo and the current container state.",
"status": "Status",
"lastCommit": "Last commit",
"lastSync": "Last sync",
"container": "Container",
"neverDeployed": "Never deployed. Click Deploy to publish for the first time.",
"loading": "Loading runtime state…"
},
"storage": {
"title": "Persistent storage",
"sub": "Mounted at /app/data inside the container.",
"used": "Used",
"limit": "Limit",
"unlimited": "unlimited",
"unavailable": "Usage probe unavailable (container may be stopped).",
"loading": "Computing usage…"
},
"toolbar": {
"stop": "Stop",
"start": "Start",
"openSite": "Open",
"more": "More"
},
"liveBadge": {
"running": "RUNNING",
"transitioning": "TRANSITIONING",
"stopped": "STOPPED",
"notDeployed": "NOT DEPLOYED",
"mixed": "MIXED · {running}/{total} RUNNING"
},
"stats": {
"title": "Resource usage",
"sub": "CPU and memory of the running container.",
"subMany": "CPU and memory of each of the {count} containers."
},
"webhooks": {
"title": "Webhook bindings",
"sub": "Triggers wired to this app — manage URLs and signing on the trigger detail page.",
"openTrigger": "Open trigger",
"disabled": "disabled",
"empty": "No triggers bound to this app."
},
"errors": {
"stopFailed": "Stop failed.",
"stopNothing": "Nothing to stop — no running container.",
"stopAllFailed": "Stop failed — all containers refused to stop.",
"startFailed": "Start failed.",
"startNothing": "Nothing to start — deploy first to create a container.",
"startAllFailed": "Start failed — all containers refused to start.",
"runtimeStateFailed": "Failed to load runtime state.",
"storageFailed": "Failed to load storage usage."
},
"alertTag": "ERR",
"createdAt": "created",
"refreshLabel": "Refresh",
+93
View File
@@ -1253,6 +1253,29 @@
"staticRenderMarkdown": "Рендерить markdown",
"staticRenderMarkdownDesc": "— автоматически отдавать <code>.md</code> файлы как HTML-страницы.",
"staticFoot": "Секрет вебхука для git push-триггеров появляется в панели вебхука нагрузки после создания.",
"staticDetectProvider": "Определить",
"staticDetectedOk": "Определено: {provider}",
"staticDetectedFailed": "Не удалось определить: {error}",
"staticTestConnection": "Проверить соединение",
"staticConnectionOk": "Соединение установлено",
"staticConnectionFailed": "Ошибка соединения: {error}",
"staticBrowseRepos": "Выбрать репозиторий",
"staticBrowseBranches": "Выбрать ветку",
"staticBrowseFolders": "Выбрать папку",
"staticPickerRepoTitle": "Выбор репозитория",
"staticPickerRepoPlaceholder": "Фильтр репозиториев…",
"staticPickerBranchTitle": "Выбор ветки",
"staticPickerBranchPlaceholder": "Фильтр веток…",
"staticFolderRoot": "/ (корень)",
"staticFolderSelectedPrefix": "Выбранная папка:",
"staticTreeLoading": "Загрузка дерева папок…",
"staticTreeEmpty": "В этой ветке нет папок.",
"staticDenoAutoDetected": "Обнаружена папка <code>api/</code> — режим автоматически переключён на Deno.",
"imageConflictTag": "ОБРАЗ УЖЕ ИСПОЛЬЗУЕТСЯ",
"imageConflictHeading": "Этот образ уже используется в {count} нагрузке(ах):",
"imageConflictOpenBtn": "Открыть",
"imageConflictAcknowledgeNote": "Если это намеренно (например, отдельный этап), нажмите «Создать» ещё раз для продолжения.",
"imageConflictBlockedSubmit": "Обнаружены конфликты по этому образу — изучите список выше и нажмите «Создать» повторно для продолжения.",
"sourceConfigJsonTitle": "source_config.json · {kind}",
"sourceConfigJsonAria": "Конфигурация source-плагина (JSON)",
"triggerNumLabel": "Триггер",
@@ -1273,6 +1296,22 @@
"cancel": "Отмена",
"submit": "Создать приложение",
"submitting": "Создание…",
"submitAnyway": "Всё равно создать",
"errors": {
"detectionFailed": "Не удалось определить провайдера.",
"connectionFailed": "Ошибка соединения.",
"reposFailed": "Не удалось загрузить репозитории.",
"branchesFailed": "Не удалось загрузить ветки.",
"treeFailed": "Не удалось загрузить дерево папок.",
"sourceConfigInvalid": "source_config не является корректным JSON.",
"triggerBindUnknown": "неизвестная ошибка",
"createFailed": "Не удалось создать нагрузку.",
"inspectFailed": "Не удалось проинспектировать образ."
},
"imageInspect": "Инспектировать",
"imageInspectHint": "Подставляет порт и healthcheck из образа, чтобы не вводить вручную.",
"imageInspectOk": "Готово — порт и healthcheck подставлены.",
"imageInspectError": "Ошибка инспекции: {error}",
"triggers": {
"section": "Триггер",
"sectionSub": "Необязательно. Выберите, откуда придёт сигнал передеплоя — слежение за реестром, git-событие или ручная кнопка.",
@@ -1304,6 +1343,60 @@
"deployError": "Деплой не удался",
"saveError": "Сохранение не удалось",
"deleteError": "Удаление не удалось",
"runtimeState": {
"title": "Статус синхронизации",
"sub": "Последняя успешная синхронизация репозитория и текущее состояние контейнера.",
"status": "Статус",
"lastCommit": "Последний коммит",
"lastSync": "Последняя синхронизация",
"container": "Контейнер",
"neverDeployed": "Ещё не разворачивалось. Нажмите «Деплой», чтобы опубликовать впервые.",
"loading": "Загрузка состояния…"
},
"storage": {
"title": "Постоянное хранилище",
"sub": "Смонтировано в /app/data внутри контейнера.",
"used": "Использовано",
"limit": "Лимит",
"unlimited": "без лимита",
"unavailable": "Не удалось получить размер (контейнер мог быть остановлен).",
"loading": "Вычисление размера…"
},
"toolbar": {
"stop": "Стоп",
"start": "Старт",
"openSite": "Открыть",
"more": "Ещё"
},
"liveBadge": {
"running": "РАБОТАЕТ",
"transitioning": "ПЕРЕХОД",
"stopped": "ОСТАНОВЛЕНО",
"notDeployed": "НЕ РАЗВЁРНУТО",
"mixed": "СМЕШАННО · {running}/{total} РАБОТАЕТ"
},
"stats": {
"title": "Ресурсы",
"sub": "CPU и память запущенного контейнера.",
"subMany": "CPU и память по каждому из {count} контейнеров."
},
"webhooks": {
"title": "Привязки вебхуков",
"sub": "Триггеры, привязанные к приложению — управление URL и подписями на странице триггера.",
"openTrigger": "Открыть триггер",
"disabled": "отключён",
"empty": "К приложению не привязан ни один триггер."
},
"errors": {
"stopFailed": "Не удалось остановить.",
"stopNothing": "Останавливать нечего — нет запущенного контейнера.",
"stopAllFailed": "Остановка не удалась — все контейнеры отклонили запрос.",
"startFailed": "Не удалось запустить.",
"startNothing": "Запускать нечего — сначала выполните Деплой, чтобы создать контейнер.",
"startAllFailed": "Запуск не удался — все контейнеры отклонили запрос.",
"runtimeStateFailed": "Не удалось загрузить состояние.",
"storageFailed": "Не удалось загрузить размер хранилища."
},
"alertTag": "ОШ",
"createdAt": "создано",
"refreshLabel": "Обновить",
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff