diff --git a/CLAUDE.md b/CLAUDE.md index eac753c9..555c7f2d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -85,6 +85,75 @@ dev server against it — it never touches the repository configured in `.env`. minted directly (same HMAC scheme as `SessionService`), so specs don't need to drive the login form except in `e2e/specs/login.spec.ts`, which covers that mechanism itself. +## UI (v3 redesign, in progress) + +The redesign uses the Kettu palette (ink surfaces, `brand-500` orange `#f95d11`, Inter). `/brand` is +the live catalog of everything below; it uses the bare layout (no app sidebar/navbar) and needs a +session like any other page. Check it there before inventing a new style. + +**Rule: styling is classes, behavior is components.** + +- **Styling only → `k-*` classes** from `src/lib/styles/brand.css` (imported by `app.css`): + buttons (`k-btn` + `k-btn-primary|secondary|outline-brand|ghost|danger`, sizes `k-btn-sm|lg`, + `k-btn-icon`), inputs/textarea/native select (`k-input`, `k-label`, `k-help`), checkbox/radio + (`k-checkbox`), badges (`k-badge` + `-brand|ok|warn|danger|info`), `k-kbd`, cards (`k-card`, + `k-card-hover`, `k-panel`), `k-popover`, `k-divider`, navigation (`k-nav-item` with + `aria-current="page"`, `k-nav-heading`), headings (`k-text-gradient`, `k-text-gradient-brand`). + They work on any element (``, ` + {/if} + + + GitOps + + + {#if user && onsearch} + + + + {/if} + +
+ {#if user && onsearch} + {/if} -
- + - {#if user} -
+ {#if user} + + {#snippet trigger(props)} - - {#if showUserDropdown} - - {/if} + {/snippet} +
+

{user.username}

+ {#if roleName}

{roleName}

{/if}
- {/if} -
+ + {$_('nav.profile')} + {$_('nav.changeOrganization')} + {#if settingsHref} + {$_('sidebar.modules.clusterSettings')} + {/if} + + {$_('nav.signOut')} + + {/if}
diff --git a/src/lib/components/AppSidebar.svelte b/src/lib/components/AppSidebar.svelte index f166e94d..a313365c 100644 --- a/src/lib/components/AppSidebar.svelte +++ b/src/lib/components/AppSidebar.svelte @@ -1,626 +1,214 @@ + - diff --git a/src/lib/components/AuditFieldValue.svelte b/src/lib/components/AuditFieldValue.svelte index b10fc1b9..b819073f 100644 --- a/src/lib/components/AuditFieldValue.svelte +++ b/src/lib/components/AuditFieldValue.svelte @@ -5,46 +5,37 @@ export let tone: 'before' | 'after' | 'plain' = 'plain'; const textTone: Record<'before' | 'after' | 'plain', string> = { - before: 'text-red-600 line-through', - after: 'font-medium text-emerald-700', - plain: 'text-slate-700', + before: 'text-red-300 line-through', + after: 'font-medium text-green-300', + plain: 'text-fg', }; {#if !value} - — + — {:else if value.kind === 'text'} {value.text} {:else if value.kind === 'flags'}
{#each value.flags as flag} {flag.label} - {flag.label} - {/each}
{:else if value.kind === 'list'}
{#each value.items as item} - {@const [scope, action] = item.split(':')} - - {#if action} - {scope} - {action} - {:else} - {item} - {/if} - + {item} {/each}
{:else}
{JSON.stringify(value.json, null, 2)}
+ class="max-h-48 overflow-auto rounded-lg border border-white/8 bg-ink-950 p-2 font-mono text-[11px] leading-relaxed text-fg">{JSON.stringify(value.json, null, 2)} {/if} diff --git a/src/lib/components/AuditLog.svelte b/src/lib/components/AuditLog.svelte index c293e01d..959cdc4d 100644 --- a/src/lib/components/AuditLog.svelte +++ b/src/lib/components/AuditLog.svelte @@ -1,5 +1,20 @@ -
- {#if analysis && complianceReport} - - {/if} -
- {#each tabs as tab}{/each} +{#if !analysis} +
+ 🦊 +

Todavía no se ha ejecutado ningún análisis

+

+ Envía el resultado de Trivy, Syft o Gitleaks desde tu pipeline a la API de scan y aparecerá + aquí. +

- {#if !analysis}
- Todavía no se ha ejecutado ningún análisis. -
{:else if activeTab === 'summary'} (riskInfoModalOpen = true)} - />{:else if activeTab === 'vulnerabilities'}
-
- {#each vulnerabilitySubTabs as subTab}{/each} -
- {#if activeVulnerabilityTab === 'cve'}{:else}{/if} -
{:else if activeTab === 'secrets'}{:else}{/if} -
+ {#if aside} +
{@render aside()}
+ {/if} +{:else} +
+
+ +
-{#if riskInfoModalOpen}{/if} +
+{/if} diff --git a/src/lib/components/Footer.svelte b/src/lib/components/Footer.svelte deleted file mode 100644 index 2fb86a91..00000000 --- a/src/lib/components/Footer.svelte +++ /dev/null @@ -1,157 +0,0 @@ - - - diff --git a/src/lib/components/RoleDetail.svelte b/src/lib/components/RoleDetail.svelte index 26853c0a..795b0a2a 100644 --- a/src/lib/components/RoleDetail.svelte +++ b/src/lib/components/RoleDetail.svelte @@ -2,15 +2,17 @@ import { deserialize } from '$app/forms'; import { goto, invalidateAll } from '$app/navigation'; import { - CheckCircle, + ArrowLeft, ChevronDown, ChevronRight, - Pencil, + KeyRound, + LoaderCircle, + Lock, Save, Trash2, Users, - X, } from '@lucide/svelte'; + import { Field, Modal, toast } from '#lib/components/ui'; import permissionsCatalog, { defaultActions } from '#lib/config/permissions'; import { normalizePermissionGrant, toStoredPermissionGrant } from '#lib/permissions'; import { _ } from '#lib/i18n'; @@ -74,8 +76,35 @@ let selectedPermissions = toUiPermissions(role?.permissions ?? []); let saving = false; let deleting = false; - let detailError = ''; - let detailSuccess = ''; + let deleteOpen = false; + // en un rol nuevo el slug se genera a partir del nombre hasta que se edita a mano + let slugTouched = false; + $: if (isCreate && !slugTouched) roleSlug = slugify(roleName); + + function slugify(value: string): string { + return value + .toLowerCase() + .normalize('NFD') + .replace(/[\u0300-\u036f]/g, '') + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); + } + + function levelLabel(level: AccessLevel): string { + return level === 'none' + ? $_('roleDetail.noAccess') + : level === 'read' + ? $_('roleDetail.readOnly') + : level === 'full' + ? $_('roleDetail.fullAccess') + : $_('roleDetail.custom'); + } + + function setAllExpanded(open: boolean) { + expanded = Object.fromEntries( + permissionRows.filter((row) => hasExpandableContent(row)).map((row) => [row.key, open]), + ); + } let expanded: Record = defaultExpanded(getPermissionRows(scope)); let accessLevelOverrides: Record = {}; @@ -362,13 +391,6 @@ return row.hasChildren || row.permissions.length > 0; } - function flashSuccess(message: string) { - detailSuccess = message; - setTimeout(() => { - detailSuccess = ''; - }, 2500); - } - async function submitAction(action: string, values: Record) { const formData = new FormData(); for (const [key, value] of Object.entries(values)) formData.set(key, value); @@ -383,8 +405,12 @@ return result.type === 'success' ? (result.data as { role?: RoleRow } | undefined) : null; } - async function saveRole() { - detailError = ''; + async function saveRole(event?: SubmitEvent) { + event?.preventDefault(); + if (!roleName.trim() || !roleSlug.trim()) { + toast.error($_('roleDetail.nameRequired')); + return; + } saving = true; try { @@ -396,14 +422,15 @@ }); if (isCreate && result?.role?.id) { + toast.success($_('roleDetail.saved'), roleName.trim()); await goto(`${cancelHref}/${result.role.id}`); return; } await invalidateAll(); - flashSuccess($_('roleDetail.saved')); + toast.success($_('roleDetail.saved'), roleName.trim()); } catch (error: unknown) { - detailError = error instanceof Error ? error.message : $_('roleDetail.saveFailed'); + toast.error(error instanceof Error ? error.message : $_('roleDetail.saveFailed')); } finally { saving = false; } @@ -412,13 +439,14 @@ async function deleteRole() { if (!role) return; - detailError = ''; deleting = true; try { await submitAction('deleteRole', { id: role.id }); + deleteOpen = false; + toast.success($_('roleDetail.deleted'), role.name); await goto(cancelHref); } catch (error: unknown) { - detailError = error instanceof Error ? error.message : $_('roleDetail.deleteFailed'); + toast.error(error instanceof Error ? error.message : $_('roleDetail.deleteFailed')); } finally { deleting = false; } @@ -429,230 +457,279 @@ {title || $_('roleDetail.defaultTitle')} -
- {#if detailError} -
- {detailError} -
- {/if} - {#if detailSuccess} -
- {detailSuccess} +
+
+ -
- {/if} - -
-
+ +
+
+

+ {scope === 'organization' + ? $_('roleDetail.orgRoleDetails') + : scope === 'project' + ? $_('roleDetail.projectRoleDetails') + : $_('roleDetail.clusterRoleDetails')} +

+ {#if canSave} + + {#snippet children(control)} + + {/snippet} + + + {#snippet children(control)} + (slugTouched = true)} + /> + {/snippet} + + {:else} +
-
{$_('roleDetail.roleId')}
-
{role.id}
+
{$_('common.name')}
+
{roleName}
- {/if} - -
- - -
- -
- - -
- -
-
{$_('common.description')}
-
- {isCreate - ? $_('roleDetail.newRole') - : `${roleName || $_('common.role')} ${$_('roleDetail.roleSuffix')}`} +
+
{$_('common.slug')}
+
{roleSlug}
+
+ {/if} + +
+
+
+
+ {$_('roleDetail.permissions')} +
+
+ {selectedPermissions.length} +
- {#if !isCreate} -
-
{$_('usersComponent.defaultTitle')}
-
- - {role?.userCount ?? 0} -
+
+
+ {$_('usersComponent.defaultTitle')} +
+
+ {role?.userCount ?? 0} +
{/if} -
- - -
-
-

{$_('roleDetail.permissions')}

-
- {#if !isCreate && canDelete} - - {/if} - {#if canSave} - - {/if} - + {#if !isCreate && role?.id} +

+ {$_('roleDetail.roleId')}: {role.id} +

+ {/if} +
+ +
+ -
- - - - - - - - - {#each visiblePermissionRows as permissionRow (permissionRow.key)} - - - - - {#if expanded[permissionRow.key] && permissionRow.permissions.length} - - - + {/if} + {/key} {/if} - {/each} - -
{$_('roleDetail.resource')}{$_('roleDetail.permission')}
-
- {#if hasExpandableContent(permissionRow)} - - {:else} - - {/if} - - {rowLabel(permissionRow)} - -
-
- {#if permissionRow.permissions.length} - {#key `${permissionRow.key}:${accessLevelKey}`} - - {/key} - {:else} - {$_('roleDetail.sectionGroup')} - {/if} -
+
    + {#each visiblePermissionRows as permissionRow (permissionRow.key)} +
  • +
    + {#if hasExpandableContent(permissionRow)} + + {:else} + + {/if} + {rowLabel(permissionRow)} + + {#if permissionRow.permissions.length} + {#key `${permissionRow.key}:${accessLevelKey}`} + {@const level = accessLevel(permissionRow)} + {#if hasInheritedAccess(permissionRow)} + {$_('roleDetail.inherited')} + {:else}
    - {#each visibleRowPermissions(permissionRow) as permission} - {@const action = actionFrom(permission)} - {#key `${permission}:${accessLevelKey}`} - - {/key} + {#each selectableAccessLevels(permissionRow) as option} + {/each}
    -
-
+
+ + {#if expanded[permissionRow.key] && permissionRow.permissions.length} +
+ {#each visibleRowPermissions(permissionRow) as permission} + {@const action = actionFrom(permission)} + {#key `${permission}:${accessLevelKey}`} + {@const checked = isVisiblePermissionSelected(permissionRow, permission)} + + {/key} + {/each} +
+ {/if} + + {/each} +
-
+ + +{#if role} + + {#snippet icon()} + + {/snippet} + {#snippet footer()} + + + {/snippet} + +{/if} diff --git a/src/lib/components/RolePermissions.svelte b/src/lib/components/RolePermissions.svelte index 4be78fc3..74d3ff14 100644 --- a/src/lib/components/RolePermissions.svelte +++ b/src/lib/components/RolePermissions.svelte @@ -1,13 +1,8 @@ + @@ -61,86 +68,84 @@
-
+
-

{resolvedTitle}

-

{resolvedDescription}

+

{resolvedTitle}

+

+ {description || $_('rolePermissions.defaultDescription')} +

{#if canCreate} - - - {$_('rolePermissions.addRole')} + + {$_('rolePermissions.addRole')} {/if} -
+ - {#if roles.length === 0} -
- {$_('rolePermissions.empty')} +
+
+ + + {$_('rolePermissions.count', { values: { count: initialRoles.length } })} +
- {:else} -
- - - - - - - - - - - - {#each roles as role, index (role.id)} - - - - - - - - {/each} - -
{$_('common.name')}{$_('common.slug')}DescripciónUsuariosAcciones
- - - - - - {role.name} - {#if isSystemRole(role)} - Sistema - {/if} - - - - {role.slug} - {roleDescription(role)} - - - {role.userCount ?? 0} + + {#if roles.length === 0} +

+ {initialRoles.length === 0 ? $_('rolePermissions.empty') : $_('rolePermissions.noMatches')} +

+ {:else} +
-
- - - -
-
-
- {/if} + {roleDescription(role)} + + + + + + {/each} + + {/if} +
diff --git a/src/lib/components/SidebarFooter.svelte b/src/lib/components/SidebarFooter.svelte new file mode 100644 index 00000000..754f269e --- /dev/null +++ b/src/lib/components/SidebarFooter.svelte @@ -0,0 +1,145 @@ + + + +{#if !collapsed} +
+

GitOps {packageJson.version}

+ {#if latestRelease} + {$_('footer.updateAvailable')}: {latestRelease.tag_name} + {:else} + {$_('sidebar.whatsNew')} + {/if} +
+{/if} + +
+ {#if showSyncStatus} + + + {#if !collapsed}GitDB · {status.label}{/if} + + {:else if !collapsed} + + {/if} + {#if ontogglecollapse} + + {/if} +
diff --git a/src/lib/components/Users.svelte b/src/lib/components/Users.svelte index a4a1e352..af412c34 100644 --- a/src/lib/components/Users.svelte +++ b/src/lib/components/Users.svelte @@ -1,27 +1,36 @@ + - {title || $_('usersComponent.defaultTitle')} + {resolvedTitle} -
-
+
+
-

- {title || $_('usersComponent.defaultTitle')} -

-

+

{resolvedTitle}

+

{description || $_('usersComponent.defaultDescription')}

@@ -293,190 +283,174 @@ {#if scope === 'organization'} {/if} -
{/if} -
- -
-
- - -
-
- - {#if error} -
- {error} + + +
+
+ + + {$_('usersComponent.count', { values: { count: users.length } })} +
- {/if} - {#if success} -
- {success} -
- {/if} - - {#if filteredUsers.length === 0} -
- -

- {users.length === 0 ? $_('usersComponent.empty') : $_('usersComponent.emptySearch')} -

-
- {:else} -
-
- - - - - + {#if filteredUsers.length === 0} +
+ + + +

+ {users.length === 0 ? $_('usersComponent.empty') : $_('usersComponent.emptySearch')} +

+ {#if users.length === 0 && canCreate} + + {/if} +
+ {:else} +
+
{$_('usersComponent.user')}{$_('common.email')}
+ + + {#if scope === 'cluster'} - + {/if} - - - - + + + + - + {#each filteredUsers as user (user.id)} - - - + + {#if scope === 'cluster'} - {/if} - - - - +
{$_('usersComponent.user')}{$_('usersComponent.organizations')}{$_('usersComponent.organizations')}{$_('common.role')}{$_('common.status')}{$_('usersComponent.added')}{$_('common.actions')}{$_('common.role')}{$_('common.status')}{$_('usersComponent.added')}{$_('common.actions')}
{user.username}{user.email || '-'}
+
+ + + {user.username} + {user.email || '—'} + +
+
+ {#if user.organizations?.length}
{#each user.organizations as organization (organization.id)} - + {organization.name} - {#if organization.role} - · - {organization.role} - {/if} + {#if organization.role}· {organization.role}{/if} {/each}
{:else} - - + — {/if}
- {#if canUpdate} -
- - {#if openRoleMenuId === user.id} -
{user.role?.name ?? $_('usersComponent.selectRole')} + {#if savingAccessId === user.id}{:else}{/if} + + {/snippet} + {#each roles as role (role.id)} + selectRole(user, role)}>{role.name} - {#each roles as role (role.id)} - - {/each} -
- {/if} -
+ {/each} + {:else} - {user.role?.name ?? $_('usersComponent.selectRole')} + {user.role?.name ?? '—'} {/if}
- - + + {user.status === 'invited' ? $_('usersComponent.invited') : $_('common.active')} {formatDate(user.createdAt)} -
+
{formatDate(user.createdAt)} +
{#if user.status === 'invited' && canCreate} {/if} {#if canDelete} {/if}
@@ -486,240 +460,174 @@
-
- {/if} + {/if} +
-{#if addModalOpen} - -
- -
-{/if} - -{#if inviteModalOpen} - -
- -
-{/if} - -{#if removeModalUser} - -
- +{/if} diff --git a/src/lib/components/code-report/CodeReportSbom.svelte b/src/lib/components/code-report/CodeReportSbom.svelte index 51403261..d33e7a5b 100644 --- a/src/lib/components/code-report/CodeReportSbom.svelte +++ b/src/lib/components/code-report/CodeReportSbom.svelte @@ -1,124 +1,219 @@ -
- {#if !analysis} -

- Todavía no se ha generado ningún SBOM con syft en este servicio. -

- {:else if analysis.status === 'failed'} -
- {analysis.error || 'La generación del SBOM falló.'} -
- {:else if analysis.status === 'in_progress'} -

- La generación del SBOM está en curso. -

- {:else if components.length === 0} -

- El SBOM no contiene componentes o el formato no es reconocido. -

- {:else} +{#if !analysis} +
+ Este servicio todavía no tiene un inventario de dependencias (Syft · SBOM). +
+{:else if analysis.status === 'failed'} +
+ + {analysis.error || 'La generación del SBOM falló.'} +
+{:else if analysis.status === 'in_progress'} +
+ La generación del SBOM está en curso. +
+{:else if components.length === 0} +
+ El SBOM no contiene componentes o su formato no se reconoce. +
+{:else} +
-
-

Componentes

-

{components.length}

+
+

Componentes

+

{components.length}

-
-

Ecosistemas

-

{componentTypes.length}

+
+

Ecosistemas

+

{types.length}

+

+ {types + .slice() + .sort((left, right) => right.count - left.count) + .slice(0, 3) + .map((item) => item.value) + .join(' · ')} +

-
-

Con licencia

-

- {licensedCount}/{components.length} +

+

Con licencia declarada

+

+ {Math.round((licensed / components.length) * 100)}%

+

{licensed} de {components.length}

-
- - -
-
- - - - - - - - - - - - {#each filteredComponents as component, index (component.purl + component.name + index)} - - - - - - + +
+
+ +
+ + 8} + options={[ + { value: 'all', label: 'Todas las licencias' }, + ...licenses.map(([name, count]) => ({ + value: name, + label: name, + hint: String(count), + })), + ]} + /> +
+ {filtered.length} de {components.length} +
+ +
+
ComponenteVersiónTipoLicenciasUbicación
- - {component.name} - - {#if component.purl} - {component.purl} - {/if} - {component.version} - {component.type} - - {component.licenses.length > 0 ? component.licenses.join(', ') : 'No declarada'} - - {component.locations[0] || '—'} -
+ + + + + + + - {/each} - -
ComponenteVersiónEcosistemaLicenciasUbicación
+ + + {#each filtered.slice(0, limit) as component, index (component.purl + component.name + index)} + + + + {component.name} + + {#if component.purl} + {component.purl} + {/if} + + {component.version} + {component.type} + + {#if component.licenses.length > 0} + {component.licenses.join(', ')} + {:else} + Sin declarar + {/if} + + + {component.locations[0] || '—'} + + + {:else} + + + Ningún componente coincide con los filtros. + + + {/each} + + +
+ + {#if filtered.length > limit} +
+ +
+ {/if}
- {/if} -
+
+{/if} diff --git a/src/lib/components/code-report/CodeReportSecrets.svelte b/src/lib/components/code-report/CodeReportSecrets.svelte index 6c7b406e..03acfe42 100644 --- a/src/lib/components/code-report/CodeReportSecrets.svelte +++ b/src/lib/components/code-report/CodeReportSecrets.svelte @@ -1,135 +1,187 @@ -
- {#if !analysis} -

- Todavía no se ha ejecutado ningún análisis de secretos con gitleaks en este servicio. -

- {:else if analysis.status === 'failed'} +{#if !analysis} +
+ Este servicio todavía no tiene un análisis de secretos (Gitleaks). +
+{:else if analysis.status === 'failed'} +
+ + {analysis.error || 'El análisis de secretos falló.'} +
+{:else if analysis.status === 'in_progress'} +
+ El análisis de secretos está en curso. +
+{:else if secrets.length === 0} +
+ +

Sin secretos expuestos

+

Gitleaks no ha encontrado credenciales en el código.

+
+{:else} +
- {analysis.error || 'El análisis de secretos falló.'} -
- {:else if analysis.status === 'in_progress'} -

- El análisis de secretos está en curso. -

- {:else if secrets.length === 0} -

- No se han detectado secretos expuestos en este análisis. -

- {:else} -
-
- {secrets.length} secreto{secrets.length === 1 - ? '' - : 's'} expuesto{secrets.length === 1 ? '' : 's'} + +
+

+ {secrets.length} + {secrets.length === 1 ? 'secreto expuesto' : 'secretos expuestos'} en {files} + {files === 1 ? 'archivo' : 'archivos'} +

+

+ Rota cada credencial aunque la borres del código: sigue en el historial de git. Después, + muévela al Vault. +

-
-
- {#each filteredSecrets as secret, index (secret.id + index)} -
- - {secret.severity} - {secret.ruleId} - {secret.title} - {secret.file}{secret.lineStart !== null ? `:${secret.lineStart}` : ''} - -
-
-
-
Archivo
-
- {secret.file} -
-
-
-
Líneas
-
- {secret.lineStart !== null - ? secret.lineEnd !== null && secret.lineEnd !== secret.lineStart - ? `${secret.lineStart}-${secret.lineEnd}` - : secret.lineStart - : 'No indicadas'} -
-
-
-
Entropía
-
- {secret.entropy !== null ? secret.entropy.toFixed(2) : 'No indicada'} -
-
- {#if secret.commit} -
-
Commit
-
- {secret.commit.slice(0, 10)} -
-
- {/if} - {#if secret.author} -
-
Autor
-
{secret.author}
-
- {/if} - {#if secret.date} -
-
Fecha
-
- {new Date(secret.date).toLocaleString()} -
+ +
+
+ + {filtered.length} de {secrets.length} +
+ +
    + {#each filtered as secret, index (secret.id + index)} +
  • +
    + + + +
    +

    + {secret.ruleId} + {#if secret.title && secret.title !== secret.ruleId} + {secret.title} + {/if} +

    +

    + {secret.file}{#if lines(secret)}:{lines(secret)}{/if} +

    - {/if} -
- {#if secret.match} -

- Coincidencia (enmascarada) -

-
{secret.match}
- {/if} -

- Rota esta credencial aunque la elimines del código: sigue presente en el historial de - git. -

-
-
- {/each} + {#if secret.severity !== 'unknown'} + {SEVERITY_LABEL[secret.severity]} + {/if} + +
+
+
+
Archivo
+
+ {secret.file}{#if lines(secret)}:{lines(secret)}{/if} +
+
+ {#if secret.commit} +
+
Commit
+
{secret.commit.slice(0, 10)}
+
+ {/if} + {#if secret.entropy !== null} +
+
Entropía
+
{secret.entropy.toFixed(2)}
+
+ {/if} + {#if secret.author} +
+
Autor
+
{secret.author}
+
+ {/if} + {#if secret.date} +
+
Fecha
+
{date(secret.date)}
+
+ {/if} +
+ {#if secret.match} +
+

+ Coincidencia (enmascarada) +

+
{secret.match}
+
+ {/if} +
+ + + {:else} +
  • + Ningún secreto coincide con la búsqueda. +
  • + {/each} +
    - {/if} -
    +
    +{/if} diff --git a/src/lib/components/code-report/CodeReportSummary.svelte b/src/lib/components/code-report/CodeReportSummary.svelte index 9530624f..987df4a9 100644 --- a/src/lib/components/code-report/CodeReportSummary.svelte +++ b/src/lib/components/code-report/CodeReportSummary.svelte @@ -1,211 +1,521 @@ -
    -
    -
    -

    - Estado de seguridad -

    -

    {riskLevel.label}

    -

    - Puntuación calculada según la severidad de las vulnerabilidades detectadas. -

    -
    -
    -

    Riesgo

    -

    {riskScore}

    -

    puntos ponderados

    -
    -
    - -
    -
    -
    -

    - Información del servicio -

    - {#if service}

    {service.name}

    -

    {service.slug}

    - {#if service.description}

    - {service.description} -

    {/if}{#if service.tags?.length}
    - {#each service.tags as tag}{tag}{/each} -
    {/if}{:else}

    Información no disponible.

    {/if} -
    -
    -
    -
    -

    - Información del repositorio +

    + +
    +
    +
    +
    +
    +

    + Estado de seguridad +

    +

    {level.label}

    +
    +
    +

    {riskScore}

    +

    puntos

    +
    +
    + + {#if summary && total > 0} + +
      + {#each severities as key (key)} +
    • + +
    • + {/each} +
    + {:else if summary} +

    + Sin vulnerabilidades en el último análisis.

    -

    - {gitInfo?.repositoryUrl ? 'Repositorio conectado' : 'Sin repositorio conectado'} -

    + {/if} + + {#if summary && total > 0} +
    +
    + Con parche disponible + {fixable} de {total} +
    +
    +
    +
    +

    + Actualizar esas dependencias bajaría el riesgo a + {riskWithoutFixable} puntos. +

    +
    + {/if} + + +
    + +
    +
    +
    +

    Análisis

    + {#if analyzedAt} +

    + {relative(analyzedAt)} · {dateTime(analyzedAt)} +

    + {/if} +
    - {#if gitInfo?.repositoryUrl}{@const ProviderIcon = providerIcon()}{/if} -
    - {#if gitInfo?.repositoryUrl}{gitInfo.repositoryUrl}{:else}

    - Este análisis no incluye un repositorio configurado. -

    {/if} - {#if gitInfo} -
    - {#if shortCommit}
    -
    Commit
    -
    - {#if commitHref}{shortCommit}{:else}{shortCommit}{/if} -
    -
    {/if} - {#if authorName}
    -
    Autor
    -
    {authorName}
    -
    {/if} -
    - {/if} -
    -
    -

    - Histórico de ejecuciones -

    -

    - {analysisHistoryLength} análisis completado{analysisHistoryLength === 1 ? '' : 's'} -

    - {#if toolRuns.length > 0}
      - {#each toolRuns as run (run.tool)}
    • + + {#if gitInfo && (repoLabel || gitInfo.commit || gitInfo.branch || authorName)} +
      + {#if repoLabel} +
      +
      Repositorio
      +
      + {#if /^https?:/.test(repoBase ?? '')} + {repoLabel} ↗ + {:else}{repoLabel}{/if} +
      +
      + {/if} + {#if gitInfo.branch}
      - -

      - {run.createdAt ? new Date(run.createdAt).toLocaleString() : 'Nunca ejecutado'} -

      +
      Rama
      +
      + {gitInfo.branch} +
      - {run.status ? (runStatusLabels[run.status] ?? run.status) : 'Sin datos'} +
      Commit
      +
      + {#if commitHref} + {gitInfo.commit.slice(0, 8)} + {:else} + {gitInfo.commit.slice(0, 8)} + {/if} +
      +
    + {/if} + {#if gitInfo.commitMessage} +
    +
    Mensaje
    +
    + {gitInfo.commitMessage} +
    +
    + {/if} + {#if authorName} +
    +
    Autor
    +
    + {authorName} +
    +
    + {/if} + {#if gitInfo.artifactName} +
    +
    Artefacto
    +
    + {gitInfo.artifactName} + {#if gitInfo.artifactType}· {gitInfo.artifactType}{/if} +
    +
    + {/if} + + {:else} +

    + Este análisis no incluye información del repositorio. Envía gitInfo desde tu pipeline para ver rama, commit y autor. +

    + {/if} + + {#if toolRuns.length > 0} +
      + {#each toolRuns as run (run.tool)} + {@const status = run.status ? runStatus[run.status] : null} +
    • +
      + + {#if status} + + {/if} +
      +

      + {#if !run.createdAt} + Nunca ejecutado + {:else if run.status === 'failed'} + Fallido · {relative(run.createdAt)} + {:else if run.status === 'in_progress'} + En curso · {relative(run.createdAt)} + {:else} + {relative(run.createdAt)} + {/if} +

      +
    • + {/each} +
    + {/if} + +
    + + {#if complianceReport} + + {/if} + + +
    +
    +
    +
    +
    +

    Qué corregir primero

    +

    + Críticas y altas ordenadas por severidad y CVSS, con su versión corregida +

    +
    + {#if summary && summary.totalVulnerabilities > 0} + - {/each} - {:else if analysis}

    - Último: {analysis.tool}·{new Date(analysis.createdAt).toLocaleString()} -

    {/if} -
    -
    -
    -
    -

    Evolución del riesgo

    -
    - {#if historyPoints.length > 0}{:else}
    - Todavía no hay historial suficiente. -
    {/if} -
    -
    -
    -

    Indicadores clave

    -
    - {#each severityKeys as severity}
    -

    {summary?.vulnerabilities[severity]}

    -

    - {severity} + {/if} +

    + {#if priorities.length === 0} +

    + No hay vulnerabilidades críticas ni altas.

    -
    {/each} + {:else} +
      + {#each priorities as finding, index (finding.id + finding.packageName + index)} +
    • + {SEVERITY_LABEL[finding.severity]} +
      +

      + {finding.packageName} + {finding.id} +

      +

      + {finding.title || finding.packagePath} +

      +
      + + {finding.installedVersion} + {#if finding.fixedVersion} + → + {finding.fixedVersion} + {:else} + · sin parche + {/if} + +
    • + {/each} +
    + {/if} +
    + +
    +
    +
    +

    Evolución del riesgo

    +

    + Riesgo ponderado de cada análisis de vulnerabilidades +

    +
    +
    + {#if trendPoints.length > 1} + + {:else} +

    + Hacen falta al menos dos análisis para ver la evolución. +

    + {/if} +
    -
    -
    -
    Dependencias
    -
    {summary?.dependencies}
    -
    -
    -
    Archivos afectados
    -
    {fileCount}
    -
    -
    - + +
    + {#if aside}{@render aside()}{/if} + +
    + {#if available.includes('vulnerabilities')} + + {/if} + {#if available.includes('sbom')} + + {/if} + {#if available.includes('secrets')} + + {/if} +
    +
    +
    + + +
    + {#each severities as key (key)} +
    +

    + + {SEVERITY_LABEL[key]} × {riskWeights[key]} +

    +

    + {summary?.vulnerabilities[key] ?? 0} detectadas +

    +
    + {/each} +
    +

    + (C × {riskWeights.critical}) + (H × {riskWeights.high}) + (M × {riskWeights.medium}) + (L × {riskWeights.low}) + = {riskScore} +

    +

    + Bajo 1-7 · medio 8-19 · alto 20-39 · crítico 40+ o cualquier vulnerabilidad crítica. Los pesos + se cambian en los ajustes de Code Report. +

    +
    diff --git a/src/lib/components/code-report/CodeReportToolBadge.svelte b/src/lib/components/code-report/CodeReportToolBadge.svelte index 60ed2e9f..cc379bdd 100644 --- a/src/lib/components/code-report/CodeReportToolBadge.svelte +++ b/src/lib/components/code-report/CodeReportToolBadge.svelte @@ -1,37 +1,26 @@ - + {preset.label} diff --git a/src/lib/components/code-report/CodeReportVulnerabilities.svelte b/src/lib/components/code-report/CodeReportVulnerabilities.svelte index 2b36d325..e4672e53 100644 --- a/src/lib/components/code-report/CodeReportVulnerabilities.svelte +++ b/src/lib/components/code-report/CodeReportVulnerabilities.svelte @@ -1,129 +1,288 @@ -
    - {#if analysis.status === 'failed' && analysis.error}
    + Este servicio todavía no tiene un análisis de vulnerabilidades (Trivy). +
    +{:else if analysis.status === 'failed'} +
    + + {analysis.error || 'El análisis de vulnerabilidades falló.'} +
    +{:else if analysis.status === 'in_progress'} +
    + El análisis de vulnerabilidades está en curso. +
    +{:else if vulnerabilities.length === 0} +
    + - {analysis.error} -
    {:else if vulnerabilities.length === 0}

    - No se han detectado vulnerabilidades en este análisis. -

    {:else}
    - +

    Sin vulnerabilidades

    +

    Este análisis no ha detectado ninguna vulnerabilidad.

    +
    +{:else} +
    +
    +
    + +
    +
    + +
    -
    - {#each filteredVulnerabilities as finding, index (finding.id + finding.target + finding.packageName + index)}
    - {finding.severity}{finding.id}{finding.title}{findingStatus(finding)}{finding.cvssScore !== null - ? `CVSS ${finding.cvssScore.toFixed(1)}` - : 'Sin CVSS'}CVE ↗ -
    -

    {finding.description || finding.title}

    -
    -
    -

    - Ubicación detectada -

    -

    {finding.packagePath}

    - {#if finding.packageIdentifier}

    - Identificador: {finding.packageIdentifier} -

    {/if}{#if finding.lineStart !== null}

    + {:else} +

    +
    + + + {#if query || onlyFixable || severity !== 'all'} + + {/if} + + {filtered.length} de {vulnerabilities.length} + +
    + + {#if filtered.length === 0} +

    + Ninguna vulnerabilidad coincide con los filtros. +

    + {:else} +
      + {#each filtered as finding, index (finding.id + finding.target + finding.packageName + index)} +
    • +
      + - Línea{finding.lineEnd !== null && finding.lineEnd !== finding.lineStart - ? `s ${finding.lineStart}-${finding.lineEnd}` - : ` ${finding.lineStart}`} -

      {:else}

      - Este informe no incluye línea ni fragmento de código. -

      {/if}{#if finding.codeSnippet}
      {finding.codeSnippet}
      {/if} -
    -
    -
    -
    Paquete
    -
    {finding.packageName}
    -
    -
    -
    Estado Trivy
    -
    {finding.status}
    -
    -
    -
    Versión instalada
    -
    - {finding.installedVersion} -
    -
    -
    -
    Versión corregida
    -
    - {finding.fixedVersion || 'No indicada'} -
    -
    -
    -
    CWE
    -
    - {finding.cweIds.length > 0 ? finding.cweIds.join(', ') : 'No indicado'} -
    -
    -
    -
    -
    - Abrir {finding.id} en NVD ↗{#if finding.primaryUrl}Ver advisory ↗{/if} -
    -
    -
    {/each} -
    {/if} -
    + + {SEVERITY_LABEL[finding.severity]} +
    +

    + {finding.id} + {finding.packageName} +

    +

    + {finding.title || finding.packagePath} +

    +
    + + + {finding.cvssScore !== null ? `CVSS ${finding.cvssScore.toFixed(1)}` : '—'} + + + +
    + {#if finding.description} +

    {finding.description}

    + {/if} + +
    +
    +
    Paquete
    +
    {finding.packageName}
    +
    +
    +
    Versión instalada
    +
    {finding.installedVersion}
    +
    +
    +
    Versión corregida
    +
    + {finding.fixedVersion || 'No indicada'} +
    +
    +
    +
    Acción
    +
    {statusLabel(finding)}
    +
    +
    +
    Ubicación
    +
    + {finding.packagePath}{#if lines(finding)}:{lines(finding)}{/if} +
    +
    +
    +
    CWE
    +
    + {finding.cweIds.length > 0 ? finding.cweIds.join(', ') : '—'} +
    +
    + {#if finding.epssScore !== null} +
    +
    EPSS
    +
    + {(finding.epssScore * 100).toFixed(2)} % +
    +
    + {/if} +
    + + {#if finding.codeSnippet} +
    {finding.codeSnippet}
    + {/if} + +
    + {finding.id} en NVD + {#if finding.primaryUrl && finding.primaryUrl !== finding.cveUrl} + Advisory + {/if} +
    +
    + + + {/each} + + {/if} +
    + {/if} + +{/if} diff --git a/src/lib/components/code-report/CveDetailView.svelte b/src/lib/components/code-report/CveDetailView.svelte index a7466aea..4e8030a6 100644 --- a/src/lib/components/code-report/CveDetailView.svelte +++ b/src/lib/components/code-report/CveDetailView.svelte @@ -1,27 +1,16 @@ - - function cweUrl(cweId: string) { - const number = cweId.match(/\d+/)?.[0]; - return number ? `https://cwe.mitre.org/data/definitions/${number}.html` : ''; - } +
    - - Volver a CVEs - + {#if backHref} + + {backLabel} + + {/if} -
    -
    -

    {cve.id}

    - - {cve.severity} - - {#if cve.cvssScore !== null} - CVSS {cve.cvssScore.toFixed(1)} +
    +
    +
    + {SEVERITY_LABEL[cve.severity]} + {#if fixable} + Parche disponible + {:else} + Sin parche + {/if} +
    +

    {cve.id}

    + {#if cve.title}

    {cve.title}

    {/if} +

    + Afecta a {serviceCount} + {serviceCount === 1 ? 'servicio' : 'servicios'}{#if showProject && projectCount > 1} + en {projectCount} proyectos{/if}. +

    +
    +
    + {#if cve.cveUrl} + + {vulnerabilitySourceLabel(cve.id)} + + {/if} + {#if cve.primaryUrl && cve.primaryUrl !== cve.cveUrl} + + Advisory + {/if}
    - {#if cve.title} -

    {cve.title}

    - {/if} -
    - -
    - {#each tabs as tab} - - {/each} -
    - - {#if activeTab === 'info'} -
    -
    - -
    -

    Severidad

    -

    {cve.severity}

    -
    -
    - {#if cve.publishedDate} -
    - -
    -

    Publicado

    -

    {new Date(cve.publishedDate).toLocaleDateString()}

    + + +
    +
    +
    +

    Descripción

    + {#if description} +
    + + {@html description}
    + {:else} +

    + El informe no incluye descripción para este CVE. +

    + {/if} +
    + +
    +
    +

    Cómo corregirlo

    +

    + Paquetes afectados y la versión a la que hay que actualizar +

    - {/if} -
    - -
    -

    Overview

    - {#if renderedDescription} - -
    {@html renderedDescription}
    - {:else} -

    Sin descripcion disponible.

    - {/if} - {#if cve.lastModifiedDate} -

    - Ultima actualizacion: {new Date(cve.lastModifiedDate).toLocaleDateString()} -

    - {/if} -
    - -
    -

    CWE

    - {#if cve.cweIds.length === 0} -

    No se ha indicado una clasificacion CWE para este CVE.

    - {:else} -
    - {#each cve.cweIds as cweId (cweId)} - - {cweId} - +
      + {#each remediations as item (item.packageName + item.fixedVersion)} +
    • + {item.packageName} + + {item.installedVersions.join(', ')} + → + {#if item.fixedVersion} + {item.fixedVersion} + {:else} + sin versión corregida + {/if} + + + {item.serviceCount} + {item.serviceCount === 1 ? 'servicio' : 'servicios'} + +
    • {/each} +
    + {#if !fixable} +

    + + No hay versión corregida publicada. Valora mitigarlo (configuración, WAF) o sustituir el paquete. +

    + {/if} +
    + +
    +
    +
    +

    Servicios afectados

    +

    Según el último análisis de cada servicio

    +
    + {#if affected.length > 5} + + {/if}
    - {/if} -
    - -
    -
    -
    - - CVSS - - - -
    -

    - {cve.cvssScore !== null ? cve.cvssScore.toFixed(1) : '-'} -

    -
    -
    -
    -

    Escala 0-10

    -
    - -
    -
    - - EPSS Score - - - -
    -

    - {cve.epssScore !== null ? `${(cve.epssScore * 100).toFixed(3)}%` : '-'} -

    -
    -
    -
    -

    Probabilidad de explotacion

    -
    - -
    -
    - - EPSS Percentil - - - -
    -

    - {cve.epssPercentile !== null ? `${(cve.epssPercentile * 100).toFixed(1)}%` : '-'} -

    -
    -
    +
    + + + + + + + + + + + + {#each filtered as item, index (item.projectSlug + item.serviceSlug + item.packageName + item.target + index)} + + + + + + + + {:else} + + + + {/each} + +
    ServicioPaqueteVersiónUbicaciónAnalizado
    + + {item.serviceName} + + + {#if showProject}

    {item.projectName}

    {/if} +
    {item.packageName} + {item.installedVersion} + {#if item.fixedVersion} → {item.fixedVersion}{/if} + + {item.target || '—'} + {date(item.scannedAt)}
    Ningún servicio coincide.
    -

    Frente al resto de CVEs conocidas

    -
    +
    -
    -

    - Como solucionarlo -

    - {#if remediations.some((remediation) => remediation.fixedVersion)} - - {:else} -

    - Ninguno de los paquetes afectados tiene aun una version corregida publicada. Revisa el advisory - para posibles mitigaciones alternativas. -

    - {/if} -
    + + diff --git a/src/lib/components/code-report/CveListView.svelte b/src/lib/components/code-report/CveListView.svelte index 71fb099b..aa46bb53 100644 --- a/src/lib/components/code-report/CveListView.svelte +++ b/src/lib/components/code-report/CveListView.svelte @@ -1,214 +1,444 @@ - - type ProjectFilterOption = { - slug: string; - name: string; - }; + -
    -
    - -

    {infoMessage}

    +{#if cves.length === 0} +
    + +

    {emptyTitle}

    +

    {emptyMessage}

    +{:else} +
    +
    +
    +

    CVEs abiertos

    +

    {stats.total}

    +

    + en {stats.services} + {stats.services === 1 ? 'servicio' : 'servicios'} +

    +
    + + +
    +

    Por severidad

    + +
      + {#each ['critical', 'high', 'medium', 'low'] as const as key (key)} +
    • + {SEVERITY_LABEL[key]} + {scoped.filter((cve) => cve.severity === key).length} +
    • + {/each} +
    +
    +
    -
    - - - {#if showProjectFilter} - - {/if} - - -
    - - {#if filteredCves.length === 0} -
    - -

    - {cves.length === 0 ? emptyMessage : 'Sin resultados para tu busqueda.'} -

    -
    - {:else} -
    - - - - - - - - - - - - {#each paginatedCves as cve (cve.id)} - - - - - - - - {/each} - -
    CVESeveridadCVSSServicios afectadosApariciones
    - - {cve.id} - - {#if cve.title} -

    {cve.title}

    - {/if} -
    - - {#if cve.severity === 'critical'}{/if} - {cve.severity} - - - {cve.cvssScore !== null ? cve.cvssScore.toFixed(1) : '-'} - {cve.affectedServiceCount}{cve.occurrenceCount}
    -
    -
    - Mostrando {rangeStart}-{rangeEnd} de {filteredCves.length} -
    +
    +{/if} diff --git a/src/lib/components/code-report/RiskTrendChart.svelte b/src/lib/components/code-report/RiskTrendChart.svelte new file mode 100644 index 00000000..529380a0 --- /dev/null +++ b/src/lib/components/code-report/RiskTrendChart.svelte @@ -0,0 +1,166 @@ + + + +
    + +
    + +
    + +
    + +{#if showTable} +
    + + + + + + + + + + + + + {#each [...points].reverse() as point (point.id)} + + + + + + + + + {/each} + +
    FechaRiesgoCHML
    {format(point.createdAt, true)}{point.score}{point.critical}{point.high}{point.medium}{point.low}
    +
    +{/if} diff --git a/src/lib/components/code-report/SecurityPolicyComplianceCard.svelte b/src/lib/components/code-report/SecurityPolicyComplianceCard.svelte index 8ac55bda..fee0dd96 100644 --- a/src/lib/components/code-report/SecurityPolicyComplianceCard.svelte +++ b/src/lib/components/code-report/SecurityPolicyComplianceCard.svelte @@ -1,168 +1,139 @@ -
    -
    - -
    -
    -
    - -
    -
    -

    - Security Policies -

    -

    {theme.title}

    -

    {subtitle}

    -
    +
    +
    + + + +
    +

    {theme.title}

    +

    {subtitle}

    - -
    +
    {#if report.blockingFailures > 0} - - - {report.blockingFailures} bloqueantes + + {report.blockingFailures} + {report.blockingFailures === 1 ? 'bloqueante' : 'bloqueantes'} {/if} {#if policiesHref} - - Ver políticas - + Ver políticas {/if} {#if report.evaluations.length > 0} {/if}
    {#if expanded && report.evaluations.length > 0} -
    +
      {#each report.evaluations as evaluation (evaluation.policyId)} -
      -
      -
      - {#if !evaluation.evaluable} - - {:else if evaluation.passed} - - {:else} - - {/if} -

      {evaluation.policyName}

      - - {evaluation.enforcement === 'block' ? 'Bloquear' : 'Avisar'} - -
      +
    • +
      + {#if !evaluation.evaluable} + + {:else if evaluation.passed} + + {:else} + + {/if} +

      {evaluation.policyName}

      + {evaluation.enforcement === 'block' ? 'Bloquear' : 'Avisar'} {!evaluation.evaluable ? 'No evaluada' : evaluation.passed ? 'Cumple' : 'Incumple'}
      {#if !evaluation.evaluable} -

      {evaluation.skippedReason}

      +

      {evaluation.skippedReason}

      {:else} -
        +
          {#each evaluation.checks as item (item.key)} -
        • -
          -

          +

        • +
          +

          {item.label}

          -

          {item.message}

          +

          {item.message}

          {#if !item.passed && item.samples.length > 0} -

          - Ej.: {item.samples.join(', ')} - {#if item.actual > item.samples.length} - y {item.actual - item.samples.length} más - {/if} +

          + {item.samples.join(', ')}{#if item.actual > item.samples.length} + y {item.actual - item.samples.length} más{/if}

          {/if}
          {item.actual}{item.limit !== null ? ` / ${item.limit}` : ''} @@ -170,8 +141,8 @@ {/each}
        {/if} -
    • + {/each} -
      +
    {/if}
    diff --git a/src/lib/components/code-report/SecurityPolicyForm.svelte b/src/lib/components/code-report/SecurityPolicyForm.svelte index 211733bb..b606f347 100644 --- a/src/lib/components/code-report/SecurityPolicyForm.svelte +++ b/src/lib/components/code-report/SecurityPolicyForm.svelte @@ -1,6 +1,13 @@ +
    { submitting = true; - return async ({ update }) => { - await update(); + error = null; + return async ({ result, update }) => { submitting = false; + if (result.type === 'redirect') { + toast.success('Política creada', name); + await goto(result.location, { invalidateAll: true }); + } else if (result.type === 'success') { + toast.success('Política guardada', name); + await update({ reset: false }); + onsuccess?.(); + } else if (result.type === 'failure') { + error = result.data?.error ? String(result.data.error) : 'No se pudo guardar la política'; + toast.error('No se pudo guardar la política', error); + } else { + await update(); + } }; }} - class="space-y-4" > - {#if errorMessage} -

    {errorMessage}

    + {#if error} + {/if} -
    -

    1. Información general

    -

    Identifica la política dentro del proyecto.

    - -
    - - + +
    + General +
    + + {#snippet children(control)} + + {/snippet} + + + {#snippet children(control)} + { + slugTouched = true; + slug = event.currentTarget.value; + }} + {...control} + /> + {/snippet} +
    - - -
    - -
    -

    2. Tipo de política

    -

    Determina qué reglas puedes configurar.

    - -
    - {#each SECURITY_POLICY_TYPES as value} + + {#snippet aside()}Opcional{/snippet} + {#snippet children(control)} + + {/snippet} + + + + +
    + Qué vigila +
    + {#each SECURITY_POLICY_TYPES as value (value)} + {@const meta = SECURITY_POLICY_TYPE_META[value]} {/each}
    -
    + -
    -

    3. Alcance

    -

    A qué servicios del proyecto se aplica.

    - -
    - {#each scopeModes as option} - - {/each} -
    + +
    + Reglas +

    Deja un campo vacío para no aplicar ese límite.

    - {#if scope.mode === 'services'} -
    - {#each services as service (service.id)} -
    - -
    -

    4. Reglas

    -

    - Deja un campo vacío para no aplicar ese límite. -

    - - {#if type === 'vulnerabilities'} -
    - {#each severityFields as field} -
    - -
    -

    5. Aplicación

    -

    Qué ocurre cuando un análisis incumple la política.

    - -
    - {#each SECURITY_POLICY_ENFORCEMENTS as value} - - {/each} -
    - - -
    - -
    - -
    - +{/snippet} diff --git a/src/lib/components/monitoring/DeleteMonitorModal.svelte b/src/lib/components/monitoring/DeleteMonitorModal.svelte new file mode 100644 index 00000000..09b21aa8 --- /dev/null +++ b/src/lib/components/monitoring/DeleteMonitorModal.svelte @@ -0,0 +1,69 @@ + + + + + + + {#snippet icon()} + + {/snippet} + {#snippet footer()} + + + {/snippet} + diff --git a/src/lib/components/monitoring/LatencyChart.svelte b/src/lib/components/monitoring/LatencyChart.svelte index 44d54389..68467593 100644 --- a/src/lib/components/monitoring/LatencyChart.svelte +++ b/src/lib/components/monitoring/LatencyChart.svelte @@ -9,6 +9,7 @@ import { onDestroy, untrack } from 'svelte'; import type { Chart as ChartType, ChartDataset, ScriptableContext } from 'chart.js'; import { _, locale } from '#lib/i18n'; + import { Tabs, tabId, tabPanelId } from '#lib/components/ui'; import { formatLatency } from '#lib/monitoring/format'; import type { CheckOutcome } from '#lib/monitoring/types'; import type { BarData } from './types'; @@ -27,16 +28,19 @@ degradedThresholdMs: number; } = $props(); + // paleta de /brand: series en orden fijo (series-1, series-2); los colores de estado solo + // marcan estado (puntos y tramos), nunca una serie const COLORS = { - avg: '#38bdf8', - p95: '#a78bfa', + avg: '#e14607', + p95: '#3b82f6', threshold: '#f59e0b', - up: '#34d399', - degraded: '#fbbf24', - down: '#fb7185', - grid: 'rgba(148, 163, 184, 0.08)', - tick: '#64748b', + up: '#22c55e', + degraded: '#f59e0b', + down: '#ef4444', + grid: 'rgba(255, 255, 255, 0.06)', + tick: '#72727e', }; + const uid = $props.id(); const withLatency = (bars: BarData[]) => bars.filter((bar) => bar.latencyAvg !== null).length; @@ -119,10 +123,10 @@ function areaGradient(context: ScriptableContext<'line'>) { const { ctx, chartArea } = context.chart; - if (!chartArea) return 'rgba(56, 189, 248, 0.15)'; + if (!chartArea) return 'rgba(225, 70, 7, 0.12)'; const gradient = ctx.createLinearGradient(0, chartArea.top, 0, chartArea.bottom); - gradient.addColorStop(0, 'rgba(56, 189, 248, 0.35)'); - gradient.addColorStop(1, 'rgba(56, 189, 248, 0)'); + gradient.addColorStop(0, 'rgba(225, 70, 7, 0.28)'); + gradient.addColorStop(1, 'rgba(225, 70, 7, 0)'); return gradient; } @@ -219,13 +223,13 @@ plugins: { legend: { display: false }, tooltip: { - backgroundColor: '#0b1829', - borderColor: '#1e3a5f', + backgroundColor: '#17171d', + borderColor: 'rgba(255, 255, 255, 0.1)', borderWidth: 1, - titleColor: '#e2e8f0', - bodyColor: '#cbd5e1', + titleColor: '#e7e7ea', + bodyColor: '#a9a9b3', padding: 10, - cornerRadius: 10, + cornerRadius: 8, usePointStyle: true, boxPadding: 4, callbacks: { @@ -243,7 +247,12 @@ x: { grid: { display: false }, border: { display: false }, - ticks: { color: COLORS.tick, maxTicksLimit: 8, maxRotation: 0, font: { size: 10 } }, + ticks: { + color: COLORS.tick, + maxTicksLimit: 8, + maxRotation: 0, + font: { size: 11, family: 'Inter, ui-sans-serif, system-ui' }, + }, }, y: { beginAtZero: true, @@ -252,7 +261,7 @@ ticks: { color: COLORS.tick, maxTicksLimit: 5, - font: { size: 10 }, + font: { size: 11, family: 'Inter, ui-sans-serif, system-ui' }, callback: (value) => formatLatency(Number(value)), }, }, @@ -280,78 +289,72 @@ onDestroy(() => chart?.destroy()); - const ranges: { key: Range; label: string }[] = [ - { key: 'recent', label: '1 h' }, - { key: 'hour', label: '24 h' }, - { key: 'day', label: '90 d' }, + const ranges = [ + { value: 'recent', label: '1 h' }, + { value: 'hour', label: '24 h' }, + { value: 'day', label: '90 d' }, ]; -
    +
    -

    {$_('monitoring.latency.title')}

    -

    +

    {$_('monitoring.latency.title')}

    +

    {range === 'recent' ? $_('monitoring.latency.recentHelp') : $_('monitoring.latency.aggregateHelp')}

    -
    - {#each ranges as option (option.key)} - - {/each} -
    + range, (next) => (range = next as Range)} + />
    {#if summary} -
    - +
    + {range === 'recent' ? $_('monitoring.latency.responseTime') : $_('monitoring.latency.avg')} - {formatLatency(summary.avg)} + {formatLatency(summary.avg)} - + {#if range !== 'recent'} {/if} - p95 {formatLatency(summary.p95)} + p95 {formatLatency(summary.p95)} - min {formatLatency(summary.min)} - max {formatLatency(summary.max)} + min {formatLatency(summary.min)} + max {formatLatency(summary.max)} {#if degradedThresholdMs > 0} - + {$_('monitoring.latency.threshold')} - {formatLatency(degradedThresholdMs)} + {formatLatency(degradedThresholdMs)} {/if}
    {/if} -
    +
    {#if !hasData} -

    +

    {$_('monitoring.latency.noData')}

    {/if} diff --git a/src/lib/components/monitoring/MonitorForm.svelte b/src/lib/components/monitoring/MonitorForm.svelte index ce0403cf..84c39a83 100644 --- a/src/lib/components/monitoring/MonitorForm.svelte +++ b/src/lib/components/monitoring/MonitorForm.svelte @@ -1,7 +1,14 @@ + +
    { - intent = submitter?.getAttribute('formaction') === '?/test' ? 'test' : 'save'; - return async ({ update }) => { - await update({ reset: false }); + intent = submitter?.getAttribute('formaction')?.endsWith('?/test') ? 'test' : 'save'; + return async ({ result, update }) => { + if (!action) { + await update({ reset: false }); + } else if (result.type === 'failure') { + localErrors = (result.data?.errors as Record) ?? {}; + localTest = null; + } else if (result.type === 'success') { + localErrors = {}; + localTest = (result.data?.test as TestResult) ?? null; + } else { + if (result.type === 'redirect') onsaved?.(); + await applyAction(result); + } intent = null; }; }} > - -
    -

    {$_('monitoring.form.requestTitle')}

    -

    {$_('monitoring.form.requestHelp')}

    + +
    +

    {$_('monitoring.form.requestTitle')}

    +

    {$_('monitoring.form.requestHelp')}

    -
    -
    - - - {#if error('name')}

    {error('name')}

    {/if} -
    +
    + + {#snippet children(control)} + + {/snippet} + + + + {#snippet children(control)} +
    + + +
    + {/snippet} +
    + + + {#snippet children(control)} + + {/snippet} + -
    - -
    + + {#snippet children(control)} - -
    - {#if error('method')}

    {error('method')}

    {/if} - {#if error('url')}

    {error('url')}

    {/if} -
    - -
    - - -

    {$_('monitoring.form.serviceHelp')}

    - {#if error('serviceId')}

    {error('serviceId')}

    {/if} -
    - -
    - - - {#if error('intervalSeconds')}

    - {error('intervalSeconds')} -

    {/if} -
    + {/snippet} +
    - -
    + +
    -

    {$_('monitoring.form.headersTitle')}

    -

    {$_('monitoring.form.headersHelp')}

    +

    {$_('monitoring.form.headersTitle')}

    +

    {$_('monitoring.form.headersHelp')}

    - {#if error('headers')}

    {error('headers')}

    {/if} + {#if error('headers')}

    {error('headers')}

    {/if}
    {#each headers as header, index (index)} + {@const nameError = error(`headers.${index}.name`)} + {@const valueError = error(`headers.${index}.value`)}
    - {#if error(`headers.${index}.name`)}

    - {error(`headers.${index}.name`)} -

    {/if} + {#if nameError}

    {nameError}

    {/if}
    - {#if error(`headers.${index}.value`)}

    - {error(`headers.${index}.value`)} -

    {/if} + {#if valueError}

    {valueError}

    {/if}
    {/each}
    -

    {$_('monitoring.form.secretsNote')}

    +

    {$_('monitoring.form.secretsNote')}

    {#if sendsBody} -
    - - +
    + + {#snippet children(control)} + + {/snippet} + {#if editing && hasStoredBody} -
    {/if}
    - -
    - + +
    + - {$_('monitoring.form.conditionsTitle')} - {$_('monitoring.form.conditionsHelp')}{$_('monitoring.form.conditionsHelp')} - {$_('monitoring.form.show')} - + + {$_('monitoring.form.show')} + + + -
    -
    - - -

    {$_('monitoring.form.expectedStatusHelp')}

    - {#if error('expectedStatus')}

    - {error('expectedStatus')} -

    {/if} -
    -
    - - - {#if error('timeoutMs')}

    {error('timeoutMs')}

    {/if} -
    -
    - - -

    {$_('monitoring.form.degradedThresholdHelp')}

    - {#if error('degradedThresholdMs')}

    - {error('degradedThresholdMs')} -

    {/if} -
    -
    - - -

    {$_('monitoring.form.confirmationsHelp')}

    - {#if error('confirmations')}

    - {error('confirmations')} -

    {/if} -
    -
    - {#if test} - + {#if shownTest} + {/if} -
    - {$_('common.cancel')} - {#if canTest} - + {/if} + - {/if} - -
    +
    + {/if} diff --git a/src/lib/components/monitoring/MonitorRow.svelte b/src/lib/components/monitoring/MonitorRow.svelte index 4c6866d7..b8c74555 100644 --- a/src/lib/components/monitoring/MonitorRow.svelte +++ b/src/lib/components/monitoring/MonitorRow.svelte @@ -37,33 +37,27 @@
    -

    +

    {monitor.name}

    -

    - {monitor.method} +

    + {monitor.method} {monitor.displayUrl}

    - + {$_(`monitoring.status.${status}`)} {#if since !== null && (status === 'down' || status === 'degraded')} · {formatDuration(since)} {/if} {#if serviceName} - + {serviceName} {/if} @@ -74,7 +68,7 @@
    {#if stats} -
    +
    {range === 'hour' ? $_('monitoring.bars.hoursAgo', { values: { count: 24 } }) @@ -83,13 +77,13 @@ {range === 'hour' ? $_('monitoring.bars.now') : $_('monitoring.bars.today')}
    {:else} -
    +
    {/if}
    -

    {formatUptime(uptime)}

    -

    +

    {formatUptime(uptime)}

    +

    {range === 'hour' ? $_('monitoring.uptime.h24') : $_('monitoring.uptime.d30')}

    @@ -101,11 +95,11 @@ width={72} height={28} /> -
    -

    +

    +

    {formatLatency(stats?.latency24h.avg)}

    -

    p95 {formatLatency(stats?.latency24h.p95)}

    +

    p95 {formatLatency(stats?.latency24h.p95)}

    diff --git a/src/lib/components/monitoring/NewMonitorModal.svelte b/src/lib/components/monitoring/NewMonitorModal.svelte new file mode 100644 index 00000000..1b480123 --- /dev/null +++ b/src/lib/components/monitoring/NewMonitorModal.svelte @@ -0,0 +1,97 @@ + + + + + {#snippet icon()} + + {/snippet} + + {#key session} + toast.success($_('monitoring.created'))} + /> + {/key} + + {#snippet footer()} + + {#if canTest} + + {/if} + + {/snippet} + diff --git a/src/lib/components/monitoring/ServiceMonitors.svelte b/src/lib/components/monitoring/ServiceMonitors.svelte index 2b95e969..29883c4b 100644 --- a/src/lib/components/monitoring/ServiceMonitors.svelte +++ b/src/lib/components/monitoring/ServiceMonitors.svelte @@ -30,19 +30,19 @@ }); -
    +
    {#if monitoring.monitors.length === 0} -

    {$_('monitoring.service.empty')}

    +

    {$_('monitoring.service.empty')}

    {:else}
    {#each monitoring.monitors as row (row.monitor.id)} diff --git a/src/lib/components/monitoring/Sparkline.svelte b/src/lib/components/monitoring/Sparkline.svelte index 59d379c0..d3a95763 100644 --- a/src/lib/components/monitoring/Sparkline.svelte +++ b/src/lib/components/monitoring/Sparkline.svelte @@ -8,9 +8,9 @@ }: { values: (number | null)[]; status?: string; width?: number; height?: number } = $props(); const colors: Record = { - up: '#34d399', - degraded: '#fbbf24', - down: '#fb7185', + up: '#22c55e', + degraded: '#f59e0b', + down: '#ef4444', }; // stable between SSR and hydration const uid = $props.id(); @@ -39,7 +39,7 @@ ? `${line} L${points.at(-1)![0].toFixed(1)},${height} L${points[0][0].toFixed(1)},${height} Z` : '', ); - let color = $derived(colors[status] ?? '#64748b'); + let color = $derived(colors[status] ?? '#72727e');
    @@ -30,7 +30,7 @@ {$_(`monitoring.test.result.${outcome.status}`)}

    {#if outcome.error} -

    +

    {outcome.cause ? $_(`monitoring.causes.${outcome.cause}`) : ''} — {outcome.error}

    {/if} @@ -38,21 +38,15 @@
    {#if outcome.httpStatus !== null} - + HTTP {outcome.httpStatus} {/if} - + {formatLatency(outcome.latencyMs)} {#if preview && preview.redirects > 0} - + {$_('monitoring.test.redirects', { values: { count: preview.redirects }, })} @@ -63,33 +57,33 @@ {#if preview}
    -

    +

    {preview.finalUrl}

    {#if headerEntries.length} -
    +
    {$_('monitoring.test.responseHeaders', { values: { count: headerEntries.length } })}
    {#each headerEntries as [name, value] (name)} -
    {name}
    -
    {value}
    +
    {name}
    +
    {value}
    {/each}
    {/if} {#if preview.bodyPreview}
    -

    {$_('monitoring.test.body')}

    +

    {$_('monitoring.test.body')}

    {preview.bodyPreview}
    + class="max-h-64 overflow-auto rounded-xl border border-white/8 bg-ink-950 p-3 font-mono text-[11px] leading-relaxed whitespace-pre-wrap text-fg">{preview.bodyPreview}
    {/if}
    diff --git a/src/lib/components/monitoring/UptimeBars.svelte b/src/lib/components/monitoring/UptimeBars.svelte index 6ff1eb0b..7d9c8592 100644 --- a/src/lib/components/monitoring/UptimeBars.svelte +++ b/src/lib/components/monitoring/UptimeBars.svelte @@ -34,7 +34,7 @@ {#each bars as bar, index (bar.start)}
    {/if} diff --git a/src/lib/components/ui/CommandPalette.svelte b/src/lib/components/ui/CommandPalette.svelte new file mode 100644 index 00000000..1d30ad5d --- /dev/null +++ b/src/lib/components/ui/CommandPalette.svelte @@ -0,0 +1,220 @@ + + + + + + + +{#if open} +
    + + + +
    +{/if} diff --git a/src/lib/components/ui/Drawer.svelte b/src/lib/components/ui/Drawer.svelte new file mode 100644 index 00000000..cf1fed82 --- /dev/null +++ b/src/lib/components/ui/Drawer.svelte @@ -0,0 +1,15 @@ + + + + diff --git a/src/lib/components/ui/DropdownMenu.svelte b/src/lib/components/ui/DropdownMenu.svelte new file mode 100644 index 00000000..2e62665a --- /dev/null +++ b/src/lib/components/ui/DropdownMenu.svelte @@ -0,0 +1,173 @@ + + + + + + + +
    + {@render trigger(triggerProps)} + + {#if open} +
    (`#${CSS.escape(triggerId)}`) ?? root, + align, + matchWidth: block, + }} + use:overlayLayer={() => close()} + onkeydown={onPanelKeydown} + transition:fly={{ y: -4, duration: 120, easing: cubicOut }} + > + {@render children()} +
    + {/if} +
    diff --git a/src/lib/components/ui/Field.svelte b/src/lib/components/ui/Field.svelte new file mode 100644 index 00000000..4881e8c7 --- /dev/null +++ b/src/lib/components/ui/Field.svelte @@ -0,0 +1,78 @@ + + + + + +
    +
    + + {#if aside}{@render aside()}{/if} +
    + {@render children(control)} + {#if error} +

    + {error} +

    + {:else if help} +

    {help}

    + {/if} +
    diff --git a/src/lib/components/ui/MenuItem.svelte b/src/lib/components/ui/MenuItem.svelte new file mode 100644 index 00000000..92c7d36b --- /dev/null +++ b/src/lib/components/ui/MenuItem.svelte @@ -0,0 +1,86 @@ + + + +{#snippet content()} + {#if isCheckbox} + + {#if checked}{/if} + + {:else if Icon} + + {/if} + {@render children()} + {#if shortcut} + {#each shortcut as key}{key}{/each} + {/if} +{/snippet} + +{#if href && !disabled} + {@render content()} +{:else} + +{/if} diff --git a/src/lib/components/ui/Modal.svelte b/src/lib/components/ui/Modal.svelte new file mode 100644 index 00000000..74a40104 --- /dev/null +++ b/src/lib/components/ui/Modal.svelte @@ -0,0 +1,148 @@ + + + +{#if open} +
    + + +
    + {#if header} + {@render header(titleId)} + {:else} +
    + {#if icon}{@render icon()}{/if} +
    +

    {title}

    + {#if description}

    + {description} +

    {/if} +
    + {#if dismissible} + + {/if} +
    + {/if} + + {#if children} +
    + {@render children()} +
    + {/if} + + {#if footer} +
    + {@render footer()} +
    + {/if} +
    +
    +{/if} diff --git a/src/lib/components/ui/Select.svelte b/src/lib/components/ui/Select.svelte new file mode 100644 index 00000000..86a6db98 --- /dev/null +++ b/src/lib/components/ui/Select.svelte @@ -0,0 +1,156 @@ + + + + + + + {#snippet trigger(props)} + + {/snippet} + + {#if searchable} + +
    + {/if} + +
    + {#each filtered as option (option.value)} + + {:else} +

    Sin resultados

    + {/each} +
    +
    + +{#if name}{/if} diff --git a/src/lib/components/ui/Switch.svelte b/src/lib/components/ui/Switch.svelte new file mode 100644 index 00000000..80cf83c4 --- /dev/null +++ b/src/lib/components/ui/Switch.svelte @@ -0,0 +1,58 @@ + + + + +{#if name && checked}{/if} diff --git a/src/lib/components/ui/Tabs.svelte b/src/lib/components/ui/Tabs.svelte new file mode 100644 index 00000000..cb8c1aa1 --- /dev/null +++ b/src/lib/components/ui/Tabs.svelte @@ -0,0 +1,136 @@ + + + + + +{#if variant === 'underline'} +
    +
    + {#each items as item (item.value)} + {@const active = item.value === value} + + {/each} +
    +
    +{:else} +
    + {#each items as item (item.value)} + {@const active = item.value === value} + + {/each} +
    +{/if} diff --git a/src/lib/components/ui/TagInput.svelte b/src/lib/components/ui/TagInput.svelte new file mode 100644 index 00000000..7eec8ec8 --- /dev/null +++ b/src/lib/components/ui/TagInput.svelte @@ -0,0 +1,308 @@ + + + + + + + +
    + +
    input?.focus()} + > + {#each values as value (value)} + {@const tag = view(value)} + + {#if tag.icon}{/if} + {tag.label} + + + {/each} + 0} + aria-controls={listId} + aria-autocomplete="list" + aria-activedescendant={open && options[active] ? `${uid}-opt-${active}` : undefined} + aria-describedby={[describedby, invalid ? errorId : null].filter(Boolean).join(' ') || + undefined} + placeholder={values.length === 0 ? placeholder : ''} + {disabled} + bind:value={query} + oninput={() => { + open = true; + invalid = false; + active = 0; + }} + onfocus={() => (open = true)} + onkeydown={onKeydown} + /> +
    + {#if invalid && invalidMessage} + + {/if} +
    + +{#if open && options.length > 0} +
      (open = false)} + > + {#each rows as option, index (option.value)} + {@const heading = option.heading} + {#if heading} + + {/if} +
    • { + event.preventDefault(); + add(option.value); + }} + onpointerenter={() => (active = index)} + > + {#if option.icon}{/if} + + {#if !option.group && custom === option.value}+ + {/if}{option.label} + + {#if option.hint}{option.hint}{/if} +
    • + {/each} +
    +{/if} diff --git a/src/lib/components/ui/Toaster.svelte b/src/lib/components/ui/Toaster.svelte new file mode 100644 index 00000000..03b60f8f --- /dev/null +++ b/src/lib/components/ui/Toaster.svelte @@ -0,0 +1,44 @@ + + + +
    + {#each toasts as item (item.id)} + {@const tone = tones[item.tone]} +
    + +
    +

    {item.title}

    + {#if item.description}

    {item.description}

    {/if} +
    + +
    + {/each} +
    diff --git a/src/lib/components/ui/index.ts b/src/lib/components/ui/index.ts new file mode 100644 index 00000000..01c5229b --- /dev/null +++ b/src/lib/components/ui/index.ts @@ -0,0 +1,24 @@ +/** + * Componentes de UI con comportamiento (UI v3). + * Lo que solo es estilo (botones, enlaces, badges, cards, inputs) son clases `k-*` de + * `src/lib/styles/brand.css`. Catálogo y ejemplos en /brand. + */ +export { default as CommandPalette } from './CommandPalette.svelte'; +export type { CommandGroup, CommandItem } from './CommandPalette.svelte'; +export { default as Drawer } from './Drawer.svelte'; +export { default as DropdownMenu } from './DropdownMenu.svelte'; +export type { DropdownTriggerProps } from './DropdownMenu.svelte'; +export { default as Field } from './Field.svelte'; +export type { FieldControlProps } from './Field.svelte'; +export { default as MenuItem } from './MenuItem.svelte'; +export { default as Modal } from './Modal.svelte'; +export { default as Select } from './Select.svelte'; +export type { SelectOption } from './Select.svelte'; +export { default as Switch } from './Switch.svelte'; +export { default as TagInput } from './TagInput.svelte'; +export type { TagSuggestion, TagView } from './TagInput.svelte'; +export { default as Tabs, tabId, tabPanelId } from './Tabs.svelte'; +export type { TabItem } from './Tabs.svelte'; +export { default as Toaster } from './Toaster.svelte'; +export { toast } from './toast.svelte'; +export type { ToastTone } from './toast.svelte'; diff --git a/src/lib/components/ui/overlay.ts b/src/lib/components/ui/overlay.ts new file mode 100644 index 00000000..56a02cf6 --- /dev/null +++ b/src/lib/components/ui/overlay.ts @@ -0,0 +1,171 @@ +/** + * Utilidades compartidas por los overlays de la UI (Modal, Drawer, DropdownMenu, Select, + * CommandPalette). Son acciones de Svelte (`use:`) para que cada componente las combine. + */ + +const FOCUSABLE = + 'a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'; + +// ---------- Capas: Esc solo cierra el overlay que está arriba ---------- + +const layers: number[] = []; +let nextLayer = 0; + +/** + * Registra el nodo como una capa. Al pulsar Esc solo se avisa a la capa superior, así un + * dropdown abierto dentro de un modal se cierra sin cerrar también el modal. + */ +export function overlayLayer(_node: HTMLElement, onEscape: () => void) { + const id = nextLayer++; + let handler = onEscape; + layers.push(id); + + function onKeydown(event: KeyboardEvent) { + if (event.key !== 'Escape' || layers[layers.length - 1] !== id) return; + event.preventDefault(); + event.stopPropagation(); + handler(); + } + + window.addEventListener('keydown', onKeydown); + return { + update(next: () => void) { + handler = next; + }, + destroy() { + window.removeEventListener('keydown', onKeydown); + const index = layers.indexOf(id); + if (index !== -1) layers.splice(index, 1); + }, + }; +} + +// ---------- Bloqueo del scroll del fondo (con contador para overlays anidados) ---------- + +let locks = 0; +let previousOverflow = ''; + +export function scrollLock(_node: HTMLElement) { + if (locks === 0) { + previousOverflow = document.body.style.overflow; + document.body.style.overflow = 'hidden'; + } + locks++; + return { + destroy() { + locks--; + if (locks === 0) document.body.style.overflow = previousOverflow; + }, + }; +} + +// ---------- Foco atrapado dentro del overlay, y devuelto al cerrar ---------- + +export function focusableIn(node: HTMLElement) { + return Array.from(node.querySelectorAll(FOCUSABLE)).filter( + (el) => el.offsetParent !== null || el === document.activeElement, + ); +} + +/** + * Mueve el foco al primer `[data-autofocus]` (o al propio panel), lo mantiene dentro con Tab y + * lo devuelve al elemento que lo tenía cuando el overlay se cierra. + */ +export function focusTrap(node: HTMLElement) { + const previous = document.activeElement as HTMLElement | null; + + requestAnimationFrame(() => { + const target = node.querySelector('[data-autofocus]') ?? node; + target.focus({ preventScroll: true }); + }); + + function onKeydown(event: KeyboardEvent) { + if (event.key !== 'Tab') return; + const items = focusableIn(node); + if (items.length === 0) { + event.preventDefault(); + return; + } + const first = items[0]; + const last = items[items.length - 1]; + if (event.shiftKey && (document.activeElement === first || document.activeElement === node)) { + event.preventDefault(); + last.focus(); + } else if (!event.shiftKey && document.activeElement === last) { + event.preventDefault(); + first.focus(); + } + } + + node.addEventListener('keydown', onKeydown); + return { + destroy() { + node.removeEventListener('keydown', onKeydown); + if (previous && document.contains(previous)) previous.focus({ preventScroll: true }); + }, + }; +} + +// ---------- Paneles flotantes: fuera del flujo para que ningún overflow los recorte ---------- + +export type FloatingOptions = { + /** Elemento al que se ancla el panel (el botón que lo abre). */ + anchor: HTMLElement | null | undefined; + align?: 'start' | 'end'; + /** El panel mide al menos lo mismo que el ancla (selects). */ + matchWidth?: boolean; + offset?: number; +}; + +const VIEWPORT_MARGIN = 8; + +/** + * Mueve el panel a y lo coloca con `position: fixed` junto a su ancla. Así no lo recorta + * el `overflow` de una tabla con scroll ni el cuerpo de un modal. Si no cabe debajo, se abre + * hacia arriba; se recoloca al hacer scroll (en cualquier contenedor) o al redimensionar. + */ +export function floating(node: HTMLElement, initial: FloatingOptions) { + let options = initial; + document.body.appendChild(node); + node.style.position = 'fixed'; + node.style.top = '0px'; + node.style.left = '0px'; + + function place() { + const anchor = options.anchor; + if (!anchor || !anchor.isConnected) return; + const gap = options.offset ?? 6; + const rect = anchor.getBoundingClientRect(); + if (options.matchWidth) node.style.minWidth = `${rect.width}px`; + const width = node.offsetWidth; + const height = node.offsetHeight; + const below = window.innerHeight - rect.bottom - gap - VIEWPORT_MARGIN; + const above = rect.top - gap - VIEWPORT_MARGIN; + const top = height > below && above > below ? rect.top - gap - height : rect.bottom + gap; + let left = options.align === 'end' ? rect.right - width : rect.left; + left = Math.min(Math.max(left, VIEWPORT_MARGIN), window.innerWidth - width - VIEWPORT_MARGIN); + node.style.top = `${Math.max(top, VIEWPORT_MARGIN)}px`; + node.style.left = `${left}px`; + // si tampoco cabe arriba, el panel se acorta y hace scroll + node.style.maxHeight = `${Math.max(below, above, 160)}px`; + } + + place(); + const observer = new ResizeObserver(place); + observer.observe(node); + window.addEventListener('scroll', place, true); + window.addEventListener('resize', place); + + return { + update(next: FloatingOptions) { + options = next; + place(); + }, + destroy() { + observer.disconnect(); + window.removeEventListener('scroll', place, true); + window.removeEventListener('resize', place); + node.remove(); + }, + }; +} diff --git a/src/lib/components/ui/toast.svelte.ts b/src/lib/components/ui/toast.svelte.ts new file mode 100644 index 00000000..bb181df1 --- /dev/null +++ b/src/lib/components/ui/toast.svelte.ts @@ -0,0 +1,54 @@ +/** + * Avisos efímeros. Pon una vez en el layout y llama a `toast.*` desde el cliente: + * + * import { toast } from '#lib/components/ui'; + * toast.success('Secreto guardado', 'DATABASE_URL · prod'); + * + * Solo para eventos del navegador (clics, respuestas de fetch). No lo llames durante el SSR: + * el estado es de módulo y se compartiría entre peticiones. + */ + +export type ToastTone = 'success' | 'error' | 'warning' | 'info'; + +export type ToastItem = { + id: number; + tone: ToastTone; + title: string; + description?: string; + /** Milisegundos; 0 = no se cierra solo. */ + duration: number; +}; + +type ToastOptions = { description?: string; duration?: number }; + +const MAX_VISIBLE = 4; +let nextId = 0; + +export const toasts = $state([]); +// Temporizadores fuera del estado reactivo: no hace falta que la UI los observe. +const timers: Record> = {}; + +function dismiss(id: number) { + const index = toasts.findIndex((t) => t.id === id); + if (index !== -1) toasts.splice(index, 1); + clearTimeout(timers[id]); + delete timers[id]; +} + +function push(tone: ToastTone, title: string, options: string | ToastOptions = {}) { + const { description, duration = tone === 'error' ? 6000 : 4000 } = + typeof options === 'string' ? { description: options } : options; + const id = ++nextId; + toasts.push({ id, tone, title, description, duration }); + while (toasts.length > MAX_VISIBLE) dismiss(toasts[0].id); + if (duration > 0) timers[id] = setTimeout(() => dismiss(id), duration); + return id; +} + +export const toast = { + success: (title: string, options?: string | ToastOptions) => push('success', title, options), + error: (title: string, options?: string | ToastOptions) => push('error', title, options), + warning: (title: string, options?: string | ToastOptions) => push('warning', title, options), + info: (title: string, options?: string | ToastOptions) => push('info', title, options), + dismiss, +}; diff --git a/src/lib/database/schemas.ts b/src/lib/database/schemas.ts index aeb46b66..23f83264 100644 --- a/src/lib/database/schemas.ts +++ b/src/lib/database/schemas.ts @@ -65,6 +65,8 @@ export const ApiKeyEntity = entity('api_keys', { expiresAt: timestamp(), lastUsedAt: timestamp(), revokedAt: timestamp(), + /** Última vez que se regeneró el secreto de la clave; null si nunca se ha rotado. */ + rotatedAt: timestamp(), createdAt: timestamp() .notNull() .$defaultFn(() => new Date().toISOString()), diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 47a97a69..0d19eacc 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -10,7 +10,17 @@ "profile": "Profile", "changeOrganization": "Change Organization", "signOut": "Sign out", - "account": "Account" + "account": "Account", + "search": "Search", + "searchPlaceholder": "Search pages, projects, settings…", + "openMenu": "Open menu", + "closeMenu": "Close menu", + "projects": "Projects", + "navigation": "Navigation", + "searchProjects": "Search project…", + "noProjectsFound": "No project matches.", + "noOrganization": "No organization", + "breadcrumbs": "Breadcrumbs" }, "sidebar": { "organization": "Organization", @@ -60,8 +70,10 @@ "registration": "Registration", "events": "Events", "alerts": "Alerts", - "monitors": "Monitors" - } + "monitors": "Monitors", + "projectDashboard": "Dashboard" + }, + "whatsNew": "What's new" }, "footer": { "currentVersion": "Current Version", @@ -393,6 +405,135 @@ "infoMessage": "This list aggregates CVEs from all organization projects using the latest completed analysis for each service.", "emptyMessage": "No CVEs have been detected in this organization yet." }, + "dashboard": { + "title": "Dashboard", + "subtitle": "Health of every project in the organization and what needs your attention.", + "updatedAt": "Updated at {time}", + "kpisLabel": "Key metrics", + "noAccess": "No access", + "kpi": { + "projects": "Active projects", + "projectsDetail": "{critical} critical · {warning} with warnings · {ok} healthy", + "security": "Security score", + "criticalCount": "{count} critical", + "highCount": "{count} high", + "uptime": "Uptime 24 h", + "noMonitors": "No monitors configured", + "monitorsFailing": "{count} failing", + "monitorsTotal": "{count} monitors", + "users": "Users", + "usersDetail": "{active} active · {invited} invited", + "usersDisabled": "{count} disabled", + "keys": "Keys at risk", + "keysAtRiskOf": "of {count} keys", + "secrets": "{count} secrets in the vault" + }, + "severity": { + "critical": "critical", + "warning": "warnings", + "info": "to review" + }, + "attention": { + "title": "What to review", + "description": "Most urgent first, across every project you can access.", + "emptyTitle": "All clear", + "emptyDescription": "Nothing critical or pending in the projects you can see.", + "showAll": "Show all ({count})", + "showLess": "Show less", + "kinds": { + "monitorsDown": { + "title": "Monitors down", + "description": "Services that are not responding right now." + }, + "exposedSecrets": { + "title": "Secrets exposed in code", + "description": "Gitleaks found credentials in the latest scan." + }, + "criticalVulns": { + "title": "Critical vulnerabilities", + "description": "Open in the latest scan of each service." + }, + "keysExpired": { + "title": "Expired keys", + "description": "Still registered but no longer valid: revoke or regenerate them." + }, + "monitorsDegraded": { + "title": "Degraded monitors", + "description": "Responding, but slow or with intermittent errors." + }, + "keysExpiring": { + "title": "Keys expiring soon", + "description": "Expire in less than {days} days." + }, + "keysNotRotated": { + "title": "Keys not rotated", + "description": "Not regenerated for more than {days} days." + }, + "keysNoExpiry": { + "title": "Keys without expiry", + "description": "They have no expiration date." + }, + "keysUnused": { + "title": "Unused keys", + "description": "Not used for more than {days} days." + }, + "staleScans": { + "title": "Services not scanned", + "description": "No scan for more than {days} days." + }, + "vaultMissing": { + "title": "Empty vault values", + "description": "Secrets without a value in some environment." + }, + "vaultStale": { + "title": "Old secrets", + "description": "Unchanged for more than {days} days." + }, + "invitedUsers": { + "title": "Pending invitations", + "description": "Invited users who haven't signed in yet." + }, + "pendingEvents": { + "title": "Unreviewed events", + "description": "Organization activity waiting for review." + } + } + }, + "keys": { + "title": "Key risk", + "description": "Server access keys across all projects. Rotate them at least every {days} days.", + "empty": "No active server access keys." + }, + "activity": "Activity", + "pendingEvents": "Unreviewed events", + "pendingEventsDescription": "Recent activity waiting for review", + "alerts": "Active alerts", + "alertsDescription": "{total} organization alerts", + "cves": "Organization CVEs", + "cvesDescription": "Vulnerabilities grouped across projects", + "status": { + "critical": "Critical", + "warning": "Warnings", + "ok": "Healthy", + "unknown": "No data" + }, + "projects": { + "title": "Project health", + "description": "Sorted by severity.", + "archived": "{count} archived not shown", + "filterLabel": "Filter by status", + "all": "All", + "score": "Score", + "critical": "Critical", + "uptime": "Uptime", + "monitorsFailing": "{count} monitors failing", + "exposedSecrets": "{count} exposed secrets", + "keysAtRisk": "{count} keys at risk", + "vaultMissing": "{count} empty values", + "allGood": "No issues", + "noData": "No active products or no access to their data" + } + }, "events": { "title": "Events", "description": "What happened in the organization and its projects. Mark each event as reviewed once you have dealt with it.", @@ -418,6 +559,14 @@ "ack": "Mark as reviewed", "ackedBy": "Reviewed by {name} · {date}", "ackFailed": "The event could not be marked as reviewed.", + "yesterday": "Yesterday", + "acked": "Reviewed", + "pending": "Pending", + "actor": "Actor", + "scope": "Scope", + "fieldsTitle": "Details", + "noFields": "This event has no further details.", + "ackedByShort": "Reviewed by {name}", "modules": { "code_report": "Code Report", "vault": "Vault", @@ -530,7 +679,22 @@ "days7": "7 days", "days30": "30 days", "days90": "90 days", - "days365": "365 days" + "days365": "365 days", + "failed": "The action could not be completed.", + "revokedToast": "Key revoked", + "emptyHelp": "Create a key so your CI/CD can send Code Report analyses to this project.", + "createDescription": "The key only sees this project and has the permissions of the role you pick.", + "neverWarning": "A key that never expires is a risk if it leaks. Rotate it from time to time.", + "tokenTitle": "Your new key", + "token": "Token", + "usage": "Usage example", + "done": "Done, I've copied it", + "rotateTitle": "Rotate the key?", + "rotateDescription": "A new token will be generated for “{name}” and the current one stops working immediately.", + "rotateConfirm": "Rotate key", + "revokeTitle": "Revoke the key?", + "revokeDescription": "“{name}” stops working immediately. This can't be undone.", + "revokeConfirm": "Revoke key" }, "overview": { "codeReport": "Code Report", @@ -587,8 +751,21 @@ "copyProjectSlug": "Copy project slug", "optionalDescription": "Optional description", "comingSoon": "Coming soon", - "transferSoon": "Coming soon" - } + "transferSoon": "Coming soon", + "subtitle": "General details, enabled modules and integrations of the project.", + "general": "General", + "generalDescription": "Project name, slug and description.", + "slugHelp": "Used in URLs and the CLI. Changing it breaks old links.", + "noDescription": "No description.", + "moduleCodeReport": "Vulnerabilities, dependencies and security policies.", + "moduleVault": "Encrypted secrets and credentials per environment.", + "moduleMonitoring": "HTTP monitors with uptime, latency and incidents.", + "moduleStateIac": "Pulumi state and storage backends.", + "unsaved": "You have unsaved changes.", + "discard": "Discard", + "typeToConfirm": "Type {name} to confirm" + }, + "title": "Project settings" }, "codeReport": { "dashboard": { @@ -753,7 +930,7 @@ "soon": "Soon", "comingSoon": "Coming soon", "generalTitle": "General", - "generalDescription": "Module-wide parameters to score risk and classify findings in this project.", + "generalDescription": "How risk is scored and which analysis tools this project uses.", "riskMultipliers": "Security Risk Multipliers", "formulaDescription": "Formula applied in service detail: (Critical × M_c) + (High × M_h) + (Medium × M_m) + (Low × M_l).", "critical": "Critical", @@ -848,7 +1025,50 @@ "descriptionPlaceholder": "Optional description", "deleteConfirmTitle": "Delete project", "deleteConfirmStart": "Are you sure you want to delete ", - "deleteConfirmEnd": "? This action cannot be undone." + "deleteConfirmEnd": "? This action cannot be undone.", + "clearSearch": "Clear search", + "clearFilters": "Clear filters", + "filterLabel": "Filter by status", + "filterAll": "All", + "filterActive": "Active", + "filterArchived": "Archived", + "archived": "Archived", + "actionsFor": "Actions for {name}", + "projectSettings": "Project settings", + "noDescription": "No description", + "noModules": "No modules enabled", + "createdOn": "Created {date}", + "emptyDescription": "Create the organization's first project to start using Code Report, Vault or Monitoring.", + "createModalDescription": "The project is created with its default roles.", + "slugHelp": "Identifier used in URLs and the CLI. Leave it empty to generate it from the name." + }, + "security": { + "title": "Security", + "description": "How people access this organization and how its data is protected. Identity providers are configured at the GitOps level; this page shows their status.", + "postureTitle": "Security posture", + "postureHint": "Access and data protection controls that apply to every project in the organization.", + "postureSummary": "of {total} controls enabled", + "checkLocal": "Username and password", + "checkGoogle": "Google Workspace SSO", + "checkSaml": "SAML SSO", + "checkEncryption": "Managed encryption", + "on": "Enabled", + "off": "Disabled", + "identityTitle": "Identity providers", + "alwaysOn": "Always on", + "localTitle": "Username and password", + "localFootnote": "It can't be disabled: it is the organization's fallback access.", + "allowedDomains": "Allowed domains", + "anyDomain": "No domain restriction", + "autoProvision": "Auto-provisioning", + "autoProvisionOn": "New accounts from allowed domains are created on first sign-in.", + "autoProvisionOff": "Only existing or invited users can sign in.", + "keyRotation": "Key rotation", + "keyRotationDescription": "Rotate the organization's encryption keys without downtime.", + "encryptionPolicy": "Encryption policy", + "encryptionPolicyDescription": "Set the minimum encryption requirements for the organization's data.", + "scopedSecrets": "Scoped secrets", + "scopedSecretsDescription": "Protect secrets with separate keys per organization and project." }, "serverAccessKeys": { "title": "Server Access Keys", @@ -907,13 +1127,27 @@ "removeModalDescriptionStart": "Remove access for", "removeModalDescriptionEnd": "? This will revoke this scope assignment.", "removing": "Removing...", - "adding": "Adding..." + "adding": "Adding...", + "count": "{count} user(s)", + "changeRole": "Change {name}'s role", + "addProjectDescription": "Give an organization user access to this project.", + "newUserDescription": "Create the account and assign a role.", + "noAssignableUsers": "Every organization user already has access to this project.", + "chooseUser": "Choose a user" }, "rolePermissions": { "defaultTitle": "Roles & Permissions", "defaultDescription": "Manage user roles and granular access policies.", "addRole": "Add role", - "empty": "No roles found." + "empty": "No roles found.", + "clusterAdminDescription": "Full access to GitOps and every organization.", + "clusterUserDescription": "Read access and limited resource management.", + "permissionCount": "{count} permission(s) configured.", + "search": "Search roles", + "count": "{count} role(s)", + "noMatches": "No role matches the search.", + "system": "System", + "users": "Users with this role" }, "roleDetail": { "edit": "Edit", @@ -943,7 +1177,20 @@ "sectionGroup": "Section group", "addClusterRole": "Add GitOps Role", "addOrganizationRole": "Add Organization Role", - "addProjectRole": "Add Project Role" + "addProjectRole": "Add Project Role", + "defaultTitle": "Role", + "nameRequired": "Name and slug are required.", + "deleted": "Role deleted", + "backToRoles": "Back to roles", + "createRole": "Create role", + "slugHelp": "Generated from the name. It can't be changed later.", + "slugLocked": "The slug can't be changed.", + "permissionsHelp": "Choose the access level for each resource. “Custom” lets you pick single actions.", + "expandAll": "Expand all", + "collapseAll": "Collapse all", + "inherited": "Inherited", + "deleteTitle": "Delete the role?", + "deleteDescription": "“{name}” will be deleted. {count} user(s) have this role." }, "auditLog": { "defaultTitle": "Audit Log", @@ -978,6 +1225,9 @@ "noChanges": "No changes detected.", "before": "Before", "after": "After", + "changesTitle": "Changes", + "previousChange": "Previous change", + "nextChange": "Next change", "actions": { "insert": "insert", "update": "update", @@ -985,7 +1235,9 @@ "other": "other" }, "actionsLabel": "Action", - "entity": "Entity" + "entity": "Entity", + "period": "Period", + "pagination": "Pagination" }, "subNavbar": { "defaultLabel": "State", @@ -1426,13 +1678,18 @@ "too_many": "There are too many items.", "unknown_user": "Some user does not belong to this scope.", "unknown_role": "Some role does not belong to this scope.", - "invalid_channel": "Channel not available." + "invalid_channel": "Channel not available.", + "invalid_email": "Some email is not valid.", + "invalid_slack_channel": "Use Slack channel names like #alerts.", + "invalid_url": "Use a valid http(s) URL." }, "channels": { "mail": "Email", "in_app": "In-app notification", "slack": "Slack", - "soon": "Coming soon" + "soon": "Coming soon", + "google_chat": "Google Chat", + "webhook": "Webhook" }, "list": { "title": "Alerts", @@ -1457,7 +1714,10 @@ "confirmDelete": "Delete this alert? This cannot be undone.", "throttle": "At most one email every {minutes} min", "inheritedTitle": "Organization alerts", - "inheritedDescription": "These alerts are defined in the organization and also fire for this project’s events. They can only be changed from the organization settings." + "inheritedDescription": "These alerts are defined in the organization and also fire for this project’s events. They can only be changed from the organization settings.", + "deleted": "Alert deleted", + "deleteTitle": "Delete the alert?", + "channelsColumn": "Destinations" }, "editor": { "newTitle": "New alert", @@ -1500,7 +1760,13 @@ "test": "Test alert", "create": "Create alert", "saveChanges": "Save changes", - "fixErrors": "Check the highlighted fields." + "fixErrors": "Check the highlighted fields.", + "externalEmails": "External emails (optional, comma-separated)", + "targets": { + "slack": "Slack channels, e.g. #alerts", + "google_chat": "Google Chat spaces", + "webhook": "Webhook URLs" + } }, "test": { "matched": "The example event matches the conditions.", @@ -1510,7 +1776,53 @@ "denied": "{count} recipients would not get it because they cannot view this event.", "nothingSent": "This is a test: no email was sent." }, - "mailDisabled": "Email is not configured (NOTIFICATION_SMTP_*): alerts are saved but will not be sent." + "mailDisabled": "Email is not configured (NOTIFICATION_SMTP_*): alerts are saved but will not be sent.", + "wizard": { + "subtitle": "Pick an event, filter it if you like and decide where to notify.", + "steps": "Steps", + "step": { + "event": "Event", + "conditions": "Conditions", + "channels": "Destinations", + "review": "Review" + }, + "searchEvents": "Search events…", + "noEvents": "No event matches the search.", + "conditionsIntro": "Optional: the alert only fires when “{event}” meets these conditions.", + "channelsTitle": "Channels", + "channelsHelp": "Pick one or more: one notification is sent per channel.", + "mailDescription": "Users, roles or external addresses", + "slackDescription": "Posts to one or more channels", + "googleChatDescription": "Posts to Google Chat spaces", + "webhookDescription": "POST with the event as JSON", + "groupRoles": "Roles", + "groupUsers": "Users", + "mailTargets": "Recipients", + "mailTargetsHelp": "Search users or roles, or type an email and press Enter.", + "mailPlaceholder": "User, role or email…", + "slackTargets": "Slack channels", + "slackTargetsHelp": "Type the channel name and press Enter.", + "googleChatTargets": "Google Chat spaces", + "googleChatTargetsHelp": "Name of the space to post to.", + "googleChatPlaceholder": "Space name…", + "webhookTargets": "URLs", + "webhookTargetsHelp": "They receive a POST with the event as JSON.", + "throttle": "Maximum frequency", + "throttle_0": "Every event", + "throttle_15": "15 min", + "throttle_60": "1 hour", + "throttle_1440": "1 day", + "throttleCustom": "or every", + "enabledHelp": "Turn it off to pause it without deleting it.", + "summary": "Summary", + "stepOf": "Step {current} of {total}", + "back": "Back", + "next": "Next", + "skipConditions": "No conditions", + "created": "Alert created", + "saved": "Alert saved", + "failed": "Could not complete it. Try again." + } }, "monitoring": { "title": "Monitoring", @@ -1581,7 +1893,9 @@ "scheduled": "{count} scheduled monitors", "overdue": "{count} checks running late", "dedicatedRepo": "Metrics in a dedicated GitDB repository", - "sharedRepo": "Metrics in the main GitDB repository" + "sharedRepo": "Metrics in the main GitDB repository", + "filterLabel": "Filter by status", + "rangeLabel": "Bar period" }, "table": { "monitor": "Monitor", @@ -1599,7 +1913,8 @@ }, "delete": { "title": "Delete monitor", - "description": "“{name}” will be deleted with its uptime history and incidents. This can't be undone." + "description": "“{name}” will be deleted with its uptime history and incidents. This can't be undone.", + "done": "Monitor deleted" }, "detail": { "since": "for {duration}", @@ -1696,6 +2011,7 @@ "recentHelp": "Every check of the last hour (in memory), colored by status.", "aggregateHelp": "Average and p95 of the stored aggregates.", "noData": "No response times in this period yet." - } + }, + "created": "Monitor created" } } diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index 0135907a..e955b3e0 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -10,7 +10,17 @@ "profile": "Perfil", "changeOrganization": "Cambiar organización", "signOut": "Cerrar sesión", - "account": "Cuenta" + "account": "Cuenta", + "search": "Buscar", + "searchPlaceholder": "Busca páginas, proyectos, ajustes…", + "openMenu": "Abrir menú", + "closeMenu": "Cerrar menú", + "projects": "Proyectos", + "navigation": "Navegación", + "searchProjects": "Buscar proyecto…", + "noProjectsFound": "Ningún proyecto coincide.", + "noOrganization": "Sin organización", + "breadcrumbs": "Migas de pan" }, "sidebar": { "organization": "Organización", @@ -60,8 +70,10 @@ "registration": "Registro", "events": "Eventos", "alerts": "Alertas", - "monitors": "Monitores" - } + "monitors": "Monitores", + "projectDashboard": "Dashboard" + }, + "whatsNew": "Ver novedades" }, "footer": { "currentVersion": "Versión actual", @@ -393,6 +405,135 @@ "infoMessage": "Este listado agrupa los CVEs de todos los proyectos de la organización usando el último análisis completado de cada servicio.", "emptyMessage": "Todavía no se han detectado CVEs en esta organización." }, + "dashboard": { + "title": "Dashboard", + "subtitle": "Estado de todos los proyectos de la organización y lo que necesita tu atención.", + "updatedAt": "Actualizado a las {time}", + "kpisLabel": "Métricas generales", + "noAccess": "Sin acceso", + "kpi": { + "projects": "Proyectos activos", + "projectsDetail": "{critical} críticos · {warning} con avisos · {ok} bien", + "security": "Puntuación de seguridad", + "criticalCount": "{count} críticas", + "highCount": "{count} altas", + "uptime": "Disponibilidad 24 h", + "noMonitors": "Sin monitores configurados", + "monitorsFailing": "{count} con fallos", + "monitorsTotal": "{count} monitores", + "users": "Usuarios", + "usersDetail": "{active} activos · {invited} invitados", + "usersDisabled": "{count} desactivados", + "keys": "Claves en riesgo", + "keysAtRiskOf": "de {count} claves", + "secrets": "{count} secretos en el vault" + }, + "severity": { + "critical": "críticos", + "warning": "avisos", + "info": "a revisar" + }, + "attention": { + "title": "Qué revisar", + "description": "Lo más urgente primero, en todos los proyectos a los que tienes acceso.", + "emptyTitle": "Todo en orden", + "emptyDescription": "No hay nada crítico ni pendiente en los proyectos que puedes ver.", + "showAll": "Ver todo ({count})", + "showLess": "Ver menos", + "kinds": { + "monitorsDown": { + "title": "Monitores caídos", + "description": "Servicios que no responden ahora mismo." + }, + "exposedSecrets": { + "title": "Secretos expuestos en el código", + "description": "Gitleaks ha encontrado credenciales en el último análisis." + }, + "criticalVulns": { + "title": "Vulnerabilidades críticas", + "description": "Abiertas en el último análisis de cada servicio." + }, + "keysExpired": { + "title": "Claves caducadas", + "description": "Siguen dadas de alta pero ya no sirven: revócalas o regenéralas." + }, + "monitorsDegraded": { + "title": "Monitores degradados", + "description": "Responden, pero lentos o con errores intermitentes." + }, + "keysExpiring": { + "title": "Claves que caducan pronto", + "description": "Caducan en menos de {days} días." + }, + "keysNotRotated": { + "title": "Claves sin rotar", + "description": "Más de {days} días sin regenerarse." + }, + "keysNoExpiry": { + "title": "Claves sin caducidad", + "description": "No tienen fecha de caducidad." + }, + "keysUnused": { + "title": "Claves sin uso", + "description": "Sin usarse en más de {days} días." + }, + "staleScans": { + "title": "Servicios sin analizar", + "description": "Sin análisis en más de {days} días." + }, + "vaultMissing": { + "title": "Valores vacíos en el vault", + "description": "Secretos sin valor en algún entorno." + }, + "vaultStale": { + "title": "Secretos antiguos", + "description": "Sin cambios en más de {days} días." + }, + "invitedUsers": { + "title": "Invitaciones pendientes", + "description": "Usuarios invitados que aún no han entrado." + }, + "pendingEvents": { + "title": "Eventos sin revisar", + "description": "Actividad de la organización pendiente de revisar." + } + } + }, + "keys": { + "title": "Riesgo de las claves", + "description": "Claves de acceso de servidor de todos los proyectos. Rótalas al menos cada {days} días.", + "empty": "No hay claves de acceso de servidor activas." + }, + "activity": "Actividad", + "pendingEvents": "Eventos sin revisar", + "pendingEventsDescription": "Actividad reciente pendiente de revisar", + "alerts": "Alertas activas", + "alertsDescription": "{total} alertas de la organización", + "cves": "CVEs de la organización", + "cvesDescription": "Vulnerabilidades agrupadas de todos los proyectos", + "status": { + "critical": "Crítico", + "warning": "Avisos", + "ok": "Bien", + "unknown": "Sin datos" + }, + "projects": { + "title": "Estado de los proyectos", + "description": "Ordenados por gravedad.", + "archived": "{count} archivados no se muestran", + "filterLabel": "Filtrar por estado", + "all": "Todos", + "score": "Puntos", + "critical": "Críticas", + "uptime": "Uptime", + "monitorsFailing": "{count} monitores con fallos", + "exposedSecrets": "{count} secretos expuestos", + "keysAtRisk": "{count} claves en riesgo", + "vaultMissing": "{count} valores vacíos", + "allGood": "Sin incidencias", + "noData": "Sin productos activos o sin acceso a sus datos" + } + }, "events": { "title": "Eventos", "description": "Lo que ha ocurrido en la organización y en sus proyectos. Marca cada evento como revisado cuando lo hayas atendido.", @@ -418,6 +559,14 @@ "ack": "Marcar como revisado", "ackedBy": "Revisado por {name} · {date}", "ackFailed": "No se ha podido marcar el evento como revisado.", + "yesterday": "Ayer", + "acked": "Revisado", + "pending": "Pendiente", + "actor": "Autor", + "scope": "Ámbito", + "fieldsTitle": "Detalles", + "noFields": "Este evento no tiene más detalles.", + "ackedByShort": "Revisado por {name}", "modules": { "code_report": "Code Report", "vault": "Vault", @@ -530,7 +679,22 @@ "days7": "7 días", "days30": "30 días", "days90": "90 días", - "days365": "365 días" + "days365": "365 días", + "failed": "No se pudo completar la acción.", + "revokedToast": "Key revocada", + "emptyHelp": "Crea una key para que tu CI/CD envíe los análisis de Code Report a este proyecto.", + "createDescription": "La key solo verá este proyecto y tendrá los permisos del rol que elijas.", + "neverWarning": "Una key sin caducidad es un riesgo si se filtra. Rótala de vez en cuando.", + "tokenTitle": "Tu nueva key", + "token": "Token", + "usage": "Ejemplo de uso", + "done": "Hecho, ya la he copiado", + "rotateTitle": "¿Rotar la key?", + "rotateDescription": "Se generará un token nuevo para «{name}» y el actual dejará de funcionar inmediatamente.", + "rotateConfirm": "Rotar key", + "revokeTitle": "¿Revocar la key?", + "revokeDescription": "«{name}» dejará de funcionar inmediatamente. No se puede deshacer.", + "revokeConfirm": "Revocar key" }, "overview": { "codeReport": "Code Report", @@ -587,8 +751,21 @@ "copyProjectSlug": "Copiar slug del proyecto", "optionalDescription": "Descripción opcional", "comingSoon": "Próximamente", - "transferSoon": "Próximamente" - } + "transferSoon": "Próximamente", + "subtitle": "Datos generales, módulos activos e integraciones del proyecto.", + "general": "General", + "generalDescription": "Nombre, slug y descripción del proyecto.", + "slugHelp": "Se usa en las URLs y en la CLI. Si lo cambias, los enlaces antiguos dejarán de funcionar.", + "noDescription": "Sin descripción.", + "moduleCodeReport": "Vulnerabilidades, dependencias y políticas de seguridad.", + "moduleVault": "Secretos y credenciales cifrados por entorno.", + "moduleMonitoring": "Monitores HTTP con uptime, latencia e incidencias.", + "moduleStateIac": "Estado de Pulumi y backends de almacenamiento.", + "unsaved": "Tienes cambios sin guardar.", + "discard": "Descartar", + "typeToConfirm": "Escribe {name} para confirmar" + }, + "title": "Ajustes del proyecto" }, "codeReport": { "dashboard": { @@ -753,7 +930,7 @@ "soon": "Próximamente", "comingSoon": "Próximamente", "generalTitle": "General", - "generalDescription": "Parámetros globales del módulo para puntuar riesgo y clasificar findings en este proyecto.", + "generalDescription": "Cómo se puntúa el riesgo y qué herramientas de análisis se usan en este proyecto.", "riskMultipliers": "Multiplicadores de riesgo de seguridad", "formulaDescription": "Fórmula aplicada en el detalle de servicio: (Critical × M_c) + (High × M_h) + (Medium × M_m) + (Low × M_l).", "critical": "Critical", @@ -848,7 +1025,50 @@ "descriptionPlaceholder": "Descripción opcional", "deleteConfirmTitle": "Eliminar proyecto", "deleteConfirmStart": "¿Seguro que quieres eliminar ", - "deleteConfirmEnd": "? Esta acción no se puede deshacer." + "deleteConfirmEnd": "? Esta acción no se puede deshacer.", + "clearSearch": "Limpiar búsqueda", + "clearFilters": "Quitar filtros", + "filterLabel": "Filtrar por estado", + "filterAll": "Todos", + "filterActive": "Activos", + "filterArchived": "Archivados", + "archived": "Archivado", + "actionsFor": "Acciones de {name}", + "projectSettings": "Ajustes del proyecto", + "noDescription": "Sin descripción", + "noModules": "Sin módulos activos", + "createdOn": "Creado el {date}", + "emptyDescription": "Crea el primer proyecto de la organización para empezar a usar Code Report, Vault o Monitoring.", + "createModalDescription": "El proyecto se crea con sus roles por defecto.", + "slugHelp": "Identificador en las URL y en la CLI. Si lo dejas vacío, se genera a partir del nombre." + }, + "security": { + "title": "Seguridad", + "description": "Cómo se accede a esta organización y cómo se protegen sus datos. Los proveedores de identidad se configuran a nivel de GitOps; aquí ves su estado.", + "postureTitle": "Postura de seguridad", + "postureHint": "Controles de acceso y protección de datos que aplican a todos los proyectos de la organización.", + "postureSummary": "de {total} controles activos", + "checkLocal": "Usuario y contraseña", + "checkGoogle": "SSO con Google Workspace", + "checkSaml": "SSO con SAML", + "checkEncryption": "Cifrado gestionado", + "on": "Activado", + "off": "Desactivado", + "identityTitle": "Proveedores de identidad", + "alwaysOn": "Siempre activo", + "localTitle": "Usuario y contraseña", + "localFootnote": "No se puede desactivar: es el acceso de respaldo de la organización.", + "allowedDomains": "Dominios permitidos", + "anyDomain": "Sin restricción de dominio", + "autoProvision": "Alta automática", + "autoProvisionOn": "Las cuentas nuevas de los dominios permitidos se crean al primer acceso.", + "autoProvisionOff": "Solo pueden entrar usuarios que ya existen o tienen invitación.", + "keyRotation": "Rotación de claves", + "keyRotationDescription": "Rota las claves de cifrado de la organización sin cortar el servicio.", + "encryptionPolicy": "Política de cifrado", + "encryptionPolicyDescription": "Define los requisitos mínimos de cifrado para los datos de la organización.", + "scopedSecrets": "Secretos por ámbito", + "scopedSecretsDescription": "Protege los secretos con claves distintas por organización y proyecto." }, "serverAccessKeys": { "title": "Claves de acceso del servidor", @@ -907,13 +1127,27 @@ "removeModalDescriptionStart": "Eliminar el acceso de", "removeModalDescriptionEnd": "? Esto revocará la asignación de este alcance.", "removing": "Eliminando...", - "adding": "Añadiendo..." + "adding": "Añadiendo...", + "count": "{count} usuario(s)", + "changeRole": "Cambiar el rol de {name}", + "addProjectDescription": "Da acceso a este proyecto a un usuario de la organización.", + "newUserDescription": "Crea la cuenta y asígnale un rol.", + "noAssignableUsers": "Todos los usuarios de la organización ya tienen acceso a este proyecto.", + "chooseUser": "Elige un usuario" }, "rolePermissions": { "defaultTitle": "Roles y permisos", "defaultDescription": "Gestiona roles de usuario y políticas de acceso granulares.", "addRole": "Añadir rol", - "empty": "No se encontraron roles." + "empty": "No se encontraron roles.", + "clusterAdminDescription": "Acceso completo a GitOps y a todas las organizaciones.", + "clusterUserDescription": "Acceso de lectura y gestión de recursos limitados.", + "permissionCount": "{count} permiso(s) configurados.", + "search": "Buscar roles", + "count": "{count} rol(es)", + "noMatches": "Ningún rol coincide con la búsqueda.", + "system": "Sistema", + "users": "Usuarios con este rol" }, "roleDetail": { "edit": "Editar", @@ -943,7 +1177,20 @@ "sectionGroup": "Grupo de secciones", "addClusterRole": "Añadir rol de GitOps", "addOrganizationRole": "Añadir rol de la organización", - "addProjectRole": "Añadir rol del proyecto" + "addProjectRole": "Añadir rol del proyecto", + "defaultTitle": "Rol", + "nameRequired": "El nombre y el slug son obligatorios.", + "deleted": "Rol eliminado", + "backToRoles": "Volver a roles", + "createRole": "Crear rol", + "slugHelp": "Se genera a partir del nombre. No se puede cambiar después.", + "slugLocked": "El slug no se puede cambiar.", + "permissionsHelp": "Elige el nivel de acceso de cada recurso. «Personalizado» permite marcar acciones sueltas.", + "expandAll": "Expandir todo", + "collapseAll": "Contraer todo", + "inherited": "Heredado", + "deleteTitle": "¿Eliminar el rol?", + "deleteDescription": "Se eliminará «{name}». Hay {count} usuario(s) con este rol." }, "auditLog": { "defaultTitle": "Registro de auditoría", @@ -978,6 +1225,9 @@ "noChanges": "No se detectaron cambios.", "before": "Antes", "after": "Después", + "changesTitle": "Cambios", + "previousChange": "Cambio anterior", + "nextChange": "Cambio siguiente", "actions": { "insert": "creación", "update": "actualización", @@ -985,7 +1235,9 @@ "other": "otro" }, "actionsLabel": "Acción", - "entity": "Entidad" + "entity": "Entidad", + "period": "Periodo", + "pagination": "Paginación" }, "subNavbar": { "defaultLabel": "Estado", @@ -1426,13 +1678,18 @@ "too_many": "Hay demasiados elementos.", "unknown_user": "Algún usuario no pertenece a este ámbito.", "unknown_role": "Algún rol no pertenece a este ámbito.", - "invalid_channel": "Canal no disponible." + "invalid_channel": "Canal no disponible.", + "invalid_email": "Algún email no es válido.", + "invalid_slack_channel": "Usa nombres de canal de Slack como #alertas.", + "invalid_url": "Usa una URL http(s) válida." }, "channels": { "mail": "Email", "in_app": "Notificación en la app", "slack": "Slack", - "soon": "Próximamente" + "soon": "Próximamente", + "google_chat": "Google Chat", + "webhook": "Webhook" }, "list": { "title": "Alertas", @@ -1457,7 +1714,10 @@ "confirmDelete": "¿Borrar esta alerta? No se puede deshacer.", "throttle": "Máx. un email cada {minutes} min", "inheritedTitle": "Alertas de la organización", - "inheritedDescription": "Estas alertas se definen en la organización y también se disparan con los eventos de este proyecto. Solo se pueden cambiar desde los ajustes de la organización." + "inheritedDescription": "Estas alertas se definen en la organización y también se disparan con los eventos de este proyecto. Solo se pueden cambiar desde los ajustes de la organización.", + "deleted": "Alerta eliminada", + "deleteTitle": "¿Borrar la alerta?", + "channelsColumn": "Destinos" }, "editor": { "newTitle": "Nueva alerta", @@ -1500,7 +1760,13 @@ "test": "Probar alerta", "create": "Crear alerta", "saveChanges": "Guardar cambios", - "fixErrors": "Revisa los campos marcados." + "fixErrors": "Revisa los campos marcados.", + "externalEmails": "Emails externos (opcional, separados por comas)", + "targets": { + "slack": "Canales de Slack, p. ej. #alertas", + "google_chat": "Espacios de Google Chat", + "webhook": "URLs de webhook" + } }, "test": { "matched": "El evento de ejemplo cumple las condiciones.", @@ -1510,7 +1776,53 @@ "denied": "{count} destinatarios no lo recibirían porque no pueden ver este evento.", "nothingSent": "Es una prueba: no se ha enviado ningún email." }, - "mailDisabled": "El email no está configurado (NOTIFICATION_SMTP_*): las alertas se guardan, pero no se enviarán." + "mailDisabled": "El email no está configurado (NOTIFICATION_SMTP_*): las alertas se guardan, pero no se enviarán.", + "wizard": { + "subtitle": "Elige un evento, fíltralo si quieres y decide por dónde avisar.", + "steps": "Pasos", + "step": { + "event": "Evento", + "conditions": "Condiciones", + "channels": "Destinos", + "review": "Revisar" + }, + "searchEvents": "Buscar eventos…", + "noEvents": "Ningún evento coincide con la búsqueda.", + "conditionsIntro": "Opcional: la alerta solo saltará cuando «{event}» cumpla estas condiciones.", + "channelsTitle": "Canales", + "channelsHelp": "Elige uno o varios: se enviará un aviso por cada canal.", + "mailDescription": "Usuarios, roles o direcciones externas", + "slackDescription": "Publica en uno o varios canales", + "googleChatDescription": "Publica en espacios de Google Chat", + "webhookDescription": "POST con el evento en JSON", + "groupRoles": "Roles", + "groupUsers": "Usuarios", + "mailTargets": "Destinatarios", + "mailTargetsHelp": "Busca usuarios o roles, o escribe un email y pulsa Enter.", + "mailPlaceholder": "Usuario, rol o email…", + "slackTargets": "Canales de Slack", + "slackTargetsHelp": "Escribe el nombre del canal y pulsa Enter.", + "googleChatTargets": "Espacios de Google Chat", + "googleChatTargetsHelp": "Nombre del espacio donde se publicará.", + "googleChatPlaceholder": "Nombre del espacio…", + "webhookTargets": "URLs", + "webhookTargetsHelp": "Recibirán un POST con el evento en JSON.", + "throttle": "Frecuencia máxima", + "throttle_0": "Cada evento", + "throttle_15": "15 min", + "throttle_60": "1 hora", + "throttle_1440": "1 día", + "throttleCustom": "o cada", + "enabledHelp": "Desactívala para pausarla sin borrarla.", + "summary": "Resumen", + "stepOf": "Paso {current} de {total}", + "back": "Atrás", + "next": "Siguiente", + "skipConditions": "Sin condiciones", + "created": "Alerta creada", + "saved": "Alerta guardada", + "failed": "No se pudo completar. Inténtalo de nuevo." + } }, "monitoring": { "title": "Monitoring", @@ -1581,7 +1893,9 @@ "scheduled": "{count} monitores programados", "overdue": "{count} comprobaciones con retraso", "dedicatedRepo": "Métricas en repositorio GitDB dedicado", - "sharedRepo": "Métricas en el repositorio GitDB principal" + "sharedRepo": "Métricas en el repositorio GitDB principal", + "filterLabel": "Filtrar por estado", + "rangeLabel": "Periodo de las barras" }, "table": { "monitor": "Monitor", @@ -1599,7 +1913,8 @@ }, "delete": { "title": "Eliminar monitor", - "description": "Se eliminará «{name}» junto con su historial de uptime e incidencias. No se puede deshacer." + "description": "Se eliminará «{name}» junto con su historial de uptime e incidencias. No se puede deshacer.", + "done": "Monitor eliminado" }, "detail": { "since": "desde hace {duration}", @@ -1696,6 +2011,7 @@ "recentHelp": "Cada comprobación de la última hora (en memoria); color según su estado.", "aggregateHelp": "Media y p95 de los agregados guardados.", "noData": "Aún no hay tiempos de respuesta en este periodo." - } + }, + "created": "Monitor creado" } } diff --git a/src/lib/monitoring/format.ts b/src/lib/monitoring/format.ts index 7e07ae3b..517db362 100644 --- a/src/lib/monitoring/format.ts +++ b/src/lib/monitoring/format.ts @@ -38,40 +38,40 @@ export const STATUS_STYLES: Record< { dot: string; text: string; badge: string; bar: string } > = { up: { - dot: 'bg-emerald-400', - text: 'text-emerald-400', - badge: 'border-emerald-500/30 bg-emerald-500/10 text-emerald-300', - bar: 'bg-emerald-500 hover:bg-emerald-400', + dot: 'bg-ok', + text: 'text-ok', + badge: 'k-badge-ok', + bar: 'bg-ok/75 hover:bg-ok', }, degraded: { - dot: 'bg-amber-400', - text: 'text-amber-400', - badge: 'border-amber-500/30 bg-amber-500/10 text-amber-300', - bar: 'bg-amber-500 hover:bg-amber-400', + dot: 'bg-warn', + text: 'text-warn', + badge: 'k-badge-warn', + bar: 'bg-warn/80 hover:bg-warn', }, down: { - dot: 'bg-rose-500', - text: 'text-rose-400', - badge: 'border-rose-500/30 bg-rose-500/10 text-rose-300', - bar: 'bg-rose-500 hover:bg-rose-400', + dot: 'bg-danger', + text: 'text-red-400', + badge: 'k-badge-danger', + bar: 'bg-danger/85 hover:bg-danger', }, pending: { - dot: 'bg-sky-400', - text: 'text-sky-300', - badge: 'border-sky-500/30 bg-sky-500/10 text-sky-300', - bar: 'bg-slate-700 hover:bg-slate-600', + dot: 'bg-info', + text: 'text-info', + badge: 'k-badge-info', + bar: 'bg-white/8 hover:bg-white/14', }, paused: { - dot: 'bg-slate-500', - text: 'text-slate-400', - badge: 'border-slate-500/30 bg-slate-500/10 text-slate-300', - bar: 'bg-slate-700 hover:bg-slate-600', + dot: 'bg-fg-subtle', + text: 'text-fg-muted', + badge: '', + bar: 'bg-white/8 hover:bg-white/14', }, none: { - dot: 'bg-slate-600', - text: 'text-slate-500', - badge: 'border-slate-600/30 bg-slate-600/10 text-slate-400', - bar: 'bg-slate-800 hover:bg-slate-700', + dot: 'bg-ink-500', + text: 'text-fg-subtle', + badge: '', + bar: 'bg-white/5 hover:bg-white/10', }, }; @@ -81,8 +81,8 @@ export function statusStyle(status: string | null | undefined) { /** Text color for an uptime figure: green from the SLO, amber close to it, red below. */ export function uptimeTone(ratio: number | null | undefined): string { - if (ratio === null || ratio === undefined) return 'text-slate-500'; - if (ratio >= 0.999) return 'text-emerald-400'; - if (ratio >= 0.99) return 'text-amber-400'; - return 'text-rose-400'; + if (ratio === null || ratio === undefined) return 'text-fg-subtle'; + if (ratio >= 0.999) return 'text-ok'; + if (ratio >= 0.99) return 'text-warn'; + return 'text-red-400'; } diff --git a/src/lib/navigation.ts b/src/lib/navigation.ts new file mode 100644 index 00000000..a54a1437 --- /dev/null +++ b/src/lib/navigation.ts @@ -0,0 +1,437 @@ +// Árbol de navegación de la app: categoría > módulo > elementos. +// Lo consumen el sidebar (AppSidebar) y la búsqueda global (CommandPalette del layout), +// así ambos muestran exactamente las mismas rutas según los permisos del usuario. +import type { Component } from 'svelte'; +import { + Activity, + BarChart3, + BellRing, + Building2, + Database, + FolderKanban, + GitBranch, + Info, + KeyRound, + Layers, + LayoutDashboard, + Plug, + ScrollText, + Settings, + Shield, + ShieldAlert, + Users, +} from '@lucide/svelte'; + +export type NavIcon = Component; +export type NavItem = { label: string; href: string; icon: NavIcon }; +// Un módulo es una entrada del sidebar. Si tiene varios `items`, el layout los pinta como pestañas +// encima del contenido. `base` es su espacio de URLs: lo mantiene activo en cualquier subruta. +export type NavModule = { + id: string; + name: string; + icon: NavIcon; + items: NavItem[]; + base?: string; +}; +// `sidebar: false`: solo en la búsqueda y en las pestañas (p. ej. ajustes de GitOps, que van en el +// menú de cuenta) +export type NavCategory = { name: string; modules: NavModule[]; sidebar?: boolean }; + +export type NavProject = { + slug: string; + modules?: { vault: boolean; codereport: boolean; stateiac: boolean; monitoring?: boolean }; +}; + +export type NavAccess = { + canAccessClusterSettings?: boolean; + canManageOrganization?: boolean; + canManageProject?: boolean; + canReadOrgProjects?: boolean; + canReadOrgUsers?: boolean; + canReadOrgRoles?: boolean; + canReadOrgGlobal?: boolean; + canReadOrgBackups?: boolean; + canReadOrgServerKeys?: boolean; + canReadOrgAudit?: boolean; + canReadOrgEvents?: boolean; + canReadOrganizationAlerts?: boolean; + canReadProjectInfo?: boolean; + canReadProjectUsers?: boolean; + canReadProjectRoles?: boolean; + canReadProjectServerKeys?: boolean; + canReadProjectAudit?: boolean; + canReadProjectAlerts?: boolean; + canReadProjectVault?: boolean; + canReadProjectCodeReport?: boolean; + canReadProjectStateIac?: boolean; + canReadProjectMonitoring?: boolean; +}; + +export type NavContext = { + organizationSlug: string | null; + currentProjectSlug: string | null; + projects: NavProject[]; + access: NavAccess; +}; + +type Translate = (id: string) => string; + +function visibleItems(items: (NavItem & { visible?: boolean })[]): NavItem[] { + return items.filter((item) => item.visible).map(({ visible: _visible, ...item }) => item); +} + +export function buildNavigation( + { organizationSlug, currentProjectSlug, projects, access }: NavContext, + t: Translate, +): NavCategory[] { + const project = projects.find((p) => p.slug === currentProjectSlug) ?? null; + const projectBase = `/org/${organizationSlug}/projects/${currentProjectSlug}`; + const categories: NavCategory[] = []; + + // Proyecto: el dashboard y los productos activos, directamente + if (organizationSlug && project) { + const modules: NavModule[] = [ + { + id: 'project-dashboard', + name: t('sidebar.items.projectDashboard'), + icon: LayoutDashboard, + items: [ + { + label: t('sidebar.items.projectDashboard'), + href: `${projectBase}/overview`, + icon: LayoutDashboard, + }, + ], + }, + ]; + + if (project.modules?.codereport && access.canReadProjectCodeReport) { + modules.push({ + id: 'code-report', + name: t('sidebar.modules.codeReport'), + icon: BarChart3, + base: `${projectBase}/code-report`, + items: [ + { + label: t('sidebar.items.dashboard'), + href: `${projectBase}/code-report/dashboard`, + icon: LayoutDashboard, + }, + { + label: t('sidebar.items.services'), + href: `${projectBase}/code-report/services`, + icon: Layers, + }, + { + label: t('sidebar.items.cves'), + href: `${projectBase}/code-report/cves`, + icon: ShieldAlert, + }, + { + label: t('sidebar.items.securityPolicies'), + href: `${projectBase}/code-report/security-policy`, + icon: Shield, + }, + { + label: t('sidebar.items.history'), + href: `${projectBase}/code-report/history`, + icon: GitBranch, + }, + { + label: t('sidebar.items.settings'), + href: `${projectBase}/code-report/settings`, + icon: Settings, + }, + ], + }); + } + + if (project.modules?.vault && access.canReadProjectVault) { + modules.push({ + id: 'vault', + name: t('sidebar.modules.vault'), + icon: Shield, + base: `${projectBase}/vault`, + items: [ + { label: 'Secrets', href: `${projectBase}/vault`, icon: Shield }, + { label: 'Integrations', href: `${projectBase}/vault/integrations`, icon: Plug }, + { label: 'Settings', href: `${projectBase}/vault/settings`, icon: Settings }, + ], + }); + } + + if (project.modules?.stateiac && access.canReadProjectStateIac) { + modules.push({ + id: 'state-iac', + name: t('sidebar.modules.stateIac'), + icon: GitBranch, + base: `${projectBase}/state-iac`, + items: [ + { + label: t('sidebar.modules.stateIac'), + href: `${projectBase}/state-iac`, + icon: GitBranch, + }, + ], + }); + } + + if (project.modules?.monitoring && access.canReadProjectMonitoring) { + modules.push({ + id: 'monitoring', + name: t('sidebar.modules.monitoring'), + icon: Activity, + base: `${projectBase}/monitoring`, + items: [ + { + label: t('sidebar.items.dashboard'), + href: `${projectBase}/monitoring/dashboard`, + icon: LayoutDashboard, + }, + { + label: t('sidebar.items.monitors'), + href: `${projectBase}/monitoring/monitors`, + icon: Activity, + }, + ], + }); + } + + if (access.canManageProject) { + const items = visibleItems([ + { + label: t('sidebar.items.information'), + href: `${projectBase}/settings/overview`, + icon: Info, + visible: access.canReadProjectInfo, + }, + { + label: t('sidebar.items.accessControl'), + href: `${projectBase}/settings/access-control`, + icon: Users, + visible: access.canReadProjectUsers, + }, + { + label: t('sidebar.items.rolesAndPermissions'), + href: `${projectBase}/settings/roles-permissions`, + icon: Shield, + visible: access.canReadProjectRoles, + }, + { + label: t('sidebar.items.audit'), + href: `${projectBase}/settings/audit`, + icon: ScrollText, + visible: access.canReadProjectAudit, + }, + { + label: t('sidebar.items.alerts'), + href: `${projectBase}/settings/alerts`, + icon: BellRing, + visible: access.canReadProjectAlerts, + }, + { + label: t('sidebar.items.serverKeys'), + href: `${projectBase}/settings/server-access-keys`, + icon: KeyRound, + visible: access.canReadProjectServerKeys, + }, + ]); + if (items.length > 0) { + modules.push({ + id: 'project-settings', + name: t('sidebar.items.settings'), + icon: Settings, + base: `${projectBase}/settings`, + items, + }); + } + } + + categories.push({ name: t('sidebar.categories.proyecto'), modules }); + } + + // Organización + const orgModules: NavModule[] = []; + if (organizationSlug) { + const orgBase = `/org/${organizationSlug}/settings`; + orgModules.push( + { + id: 'org-overview', + name: t('sidebar.items.overview'), + icon: FolderKanban, + items: [ + { + label: t('sidebar.items.overview'), + href: `/org/${organizationSlug}/overview`, + icon: FolderKanban, + }, + ], + }, + { + id: 'org-cves', + name: t('sidebar.items.cves'), + icon: ShieldAlert, + items: [ + { + label: t('sidebar.items.cves'), + href: `/org/${organizationSlug}/cves`, + icon: ShieldAlert, + }, + ], + }, + ); + + if (access.canManageOrganization) { + const items = visibleItems([ + { + label: t('sidebar.items.projects'), + href: `${orgBase}/projects`, + icon: FolderKanban, + visible: access.canReadOrgProjects, + }, + { + label: t('sidebar.items.global'), + href: `${orgBase}/global`, + icon: Shield, + visible: access.canReadOrgGlobal, + }, + { + label: t('sidebar.items.accessControl'), + href: `${orgBase}/access-control`, + icon: Users, + visible: access.canReadOrgUsers, + }, + { + label: t('sidebar.items.rolesAndPermissions'), + href: `${orgBase}/roles-permissions`, + icon: Users, + visible: access.canReadOrgRoles, + }, + { + label: t('sidebar.items.systemAndBackup'), + href: `${orgBase}/system-backup`, + icon: Database, + visible: access.canReadOrgBackups, + }, + { + label: t('sidebar.items.serverAccessKeys'), + href: `${orgBase}/server-access-keys`, + icon: KeyRound, + visible: access.canReadOrgServerKeys, + }, + { + label: t('sidebar.items.audit'), + href: `${orgBase}/audit`, + icon: ScrollText, + visible: access.canReadOrgAudit, + }, + { + label: t('sidebar.items.events'), + href: `${orgBase}/events`, + icon: Activity, + visible: access.canReadOrgEvents, + }, + { + label: t('sidebar.items.alerts'), + href: `${orgBase}/alerts`, + icon: BellRing, + visible: access.canReadOrganizationAlerts, + }, + ]); + if (items.length > 0) { + orgModules.push({ + id: 'org-settings', + name: t('sidebar.items.settings'), + icon: Settings, + base: orgBase, + items, + }); + } + } + } else { + orgModules.push({ + id: 'select-organization', + name: t('sidebar.items.selectOrganization'), + icon: Building2, + items: [ + { + label: t('sidebar.items.selectOrganization'), + href: '/gitops-settings/orgs', + icon: Building2, + }, + ], + }); + } + categories.push({ name: t('sidebar.categories.organization'), modules: orgModules }); + + // Ajustes de GitOps: en el menú de cuenta, no en el sidebar + if (access.canAccessClusterSettings) { + categories.push({ + name: t('sidebar.categories.gitops'), + sidebar: false, + modules: [ + { + id: 'cluster-settings', + name: t('sidebar.modules.clusterSettings'), + icon: Building2, + base: '/gitops-settings', + items: [ + { + label: t('sidebar.items.organizations'), + href: '/gitops-settings/orgs', + icon: Building2, + }, + { + label: t('sidebar.items.rolesAndPermissions'), + href: '/gitops-settings/roles-permissions', + icon: Shield, + }, + { + label: t('sidebar.items.accessControl'), + href: '/gitops-settings/access-control', + icon: Users, + }, + { + label: t('sidebar.items.registration'), + href: '/gitops-settings/registration', + icon: KeyRound, + }, + { + label: t('sidebar.items.database'), + href: '/gitops-settings/database', + icon: Database, + }, + { + label: t('sidebar.items.auditLog'), + href: '/gitops-settings/audit', + icon: ScrollText, + }, + ], + }, + ], + }); + } + + return categories; +} + +export function isItemActive(pathname: string, href: string) { + // los href con query (CVEs filtradas por proyecto) nunca coinciden con el pathname, a propósito: + // así la página de CVEs solo marca el módulo de Inicio + return pathname.startsWith(href); +} + +/** El elemento del módulo que corresponde a la ruta: el de href más largo que la contiene. */ +export function activeItem(pathname: string, navModule: NavModule): NavItem | null { + let best: NavItem | null = null; + for (const item of navModule.items) { + if (isItemActive(pathname, item.href) && item.href.length > (best?.href.length ?? -1)) + best = item; + } + return best; +} + +export function isModuleActive(pathname: string, navModule: NavModule) { + if (navModule.base && pathname.startsWith(navModule.base)) return true; + return navModule.items.some((item) => isItemActive(pathname, item.href)); +} diff --git a/src/lib/server/alerts/page.ts b/src/lib/server/alerts/page.ts index 38938202..830fbcee 100644 --- a/src/lib/server/alerts/page.ts +++ b/src/lib/server/alerts/page.ts @@ -6,6 +6,11 @@ import { type AlertLocation, type AlertRow, } from '#modules/alerts'; +import { + ALERT_CHANNELS, + emptyRecipients, + type AlertChannel, +} from '#modules/alerts/domain/alert.domain'; import { organizationService } from '#modules/organization'; import { projectService } from '#modules/projects'; import { @@ -84,7 +89,11 @@ async function recipientOptions(location: AlertLocation) { return { users: members .filter((member) => !member.disabled) - .map((member) => ({ id: member.userId, label: member.username })) + .map((member) => ({ + id: member.userId, + label: member.username, + ...(member.email ? { hint: member.email } : {}), + })) .sort((a, b) => a.label.localeCompare(b.label)), roles: roles.map((role) => ({ id: role.id, label: role.name })), }; @@ -139,6 +148,8 @@ export async function loadAlertList( referenceOptions: references, users: recipients.users, roles: recipients.roles, + recipientUsers: own.users, + recipientRoles: own.roles, mailConfigured: isMailConfigured(), canCreate: allowed.canCreate, canUpdate: allowed.canUpdate, @@ -154,7 +165,8 @@ function emptyDraft(eventType: string | null): AlertDraft { eventType: eventType ?? '', match: 'all', conditions: [], - recipients: { userIds: [], roleIds: [] }, + channels: ['mail'], + recipients: emptyRecipients(), throttleMinutes: 0, }; } @@ -171,7 +183,8 @@ function toDraft(alert: AlertRow): AlertDraft { operator: condition.operator, value: condition.value === undefined ? '' : condition.value, })), - recipients: { ...alert.recipients }, + channels: [...alert.channels], + recipients: { ...emptyRecipients(), ...alert.recipients }, throttleMinutes: alert.throttleMinutes, }; } @@ -218,12 +231,24 @@ export async function loadAlertEditor( referenceOptions: references, users: recipients.users, roles: recipients.roles, + recipientUsers: recipients.users, + recipientRoles: recipients.roles, mailConfigured: isMailConfigured(), canSave: alert ? allowed.canUpdate : allowed.canCreate, canDelete: Boolean(alert) && allowed.canDelete, }; } +/** A list field: repeated inputs, or one text input with comma/newline-separated values (no-JS + * editor). */ +function listField(form: FormData, name: string): string[] { + return form + .getAll(name) + .flatMap((value) => String(value).split(/[\n,]/)) + .map((value) => value.trim()) + .filter(Boolean); +} + /** `conditions..` names → condition list; rows without a field are dropped. */ export function parseAlertForm(form: FormData): AlertDraft { const indices = new Set(); @@ -258,9 +283,23 @@ export function parseAlertForm(form: FormData): AlertDraft { eventType: String(form.get('eventType') ?? ''), match: form.get('match') === 'any' ? 'any' : 'all', conditions, + channels: (() => { + const channels = form + .getAll('channels') + .map(String) + .filter((channel): channel is AlertChannel => + (ALERT_CHANNELS as readonly string[]).includes(channel), + ); + // the editor always posts at least `mail`; older clients post nothing + return channels.length > 0 ? [...new Set(channels)] : ['mail']; + })(), recipients: { userIds: form.getAll('userIds').map(String), roleIds: form.getAll('roleIds').map(String), + emails: listField(form, 'emails'), + slackChannels: listField(form, 'slackChannels'), + googleChatSpaces: listField(form, 'googleChatSpaces'), + webhookUrls: listField(form, 'webhookUrls'), }, throttleMinutes: Number(form.get('throttleMinutes') ?? 0) || 0, }; diff --git a/src/lib/server/code-report/cves.ts b/src/lib/server/code-report/cves.ts new file mode 100644 index 00000000..9fde2101 --- /dev/null +++ b/src/lib/server/code-report/cves.ts @@ -0,0 +1,221 @@ +/** + * Datos de las vistas de CVEs (listado y detalle), compartidos por el nivel de proyecto y el de + * organización. Parten del último análisis Trivy completado de cada servicio. + */ +import { error } from '@sveltejs/kit'; +import { cancanService } from '#modules/auth'; +import { codeReportCveService, type OrganizationCveOccurrence } from '#modules/code-report'; +import { projectService } from '#modules/projects'; +import { + highestCvssScore, + highestEpssPercentile, + highestEpssScore, + highestSeverity, +} from '#lib/code-report/cve-aggregation'; +import type { VulnerabilityFinding } from '#lib/code-report/analysis-summary'; + +export type CveProject = { id: string; slug: string; name: string }; + +type Severity = VulnerabilityFinding['severity']; + +const RANK: Record = { critical: 4, high: 3, medium: 2, low: 1, unknown: 0 }; + +export type CveListItem = { + id: string; + title: string; + severity: Severity; + cvssScore: number | null; + epssScore: number | null; + /** Algún servicio tiene versión corregida disponible. */ + fixable: boolean; + packages: string[]; + services: { slug: string; name: string; projectSlug: string; projectName: string }[]; + projectSlugs: string[]; + occurrenceCount: number; + publishedDate: string | null; +}; + +export type CveDetailData = { + cve: { + id: string; + title: string; + description: string; + severity: Severity; + cvssScore: number | null; + epssScore: number | null; + epssPercentile: number | null; + primaryUrl: string; + cveUrl: string; + cweIds: string[]; + references: string[]; + publishedDate: string | null; + lastModifiedDate: string | null; + }; + remediations: { + packageName: string; + installedVersions: string[]; + fixedVersion: string; + serviceCount: number; + }[]; + affected: { + serviceSlug: string; + serviceName: string; + projectSlug: string; + projectName: string; + packageName: string; + installedVersion: string; + fixedVersion: string; + target: string; + severity: Severity; + status: string; + scannedAt: string | null; + }[]; +}; + +type SessionUser = App.Locals['user']; + +/** Los CVEs de un proyecto se ven con permiso de informes o de vulnerabilidades. */ +export async function requireProjectCveAccess( + project: { id: string; organization?: { id: string } | null }, + user: SessionUser, +) { + const scope = { + scope: 'project' as const, + projectId: project.id, + organizationId: project.organization?.id, + }; + const [reports, vulnerabilities] = await Promise.all([ + cancanService.canSessionUser(user, 'project:codereport:reports:read', scope), + cancanService.canSessionUser(user, 'project:codereport:vulnerabilities:read', scope), + ]); + if (!reports && !vulnerabilities) throw error(403, 'Forbidden'); +} + +/** Proyectos activos con Code Report de la organización, para la vista global. */ +export async function organizationCveProjects( + organizationId: string, + user: SessionUser, +): Promise { + const canRead = await cancanService.canSessionUser(user, 'organization:projects:read', { + scope: 'organization', + organizationId, + }); + if (!canRead) throw error(403, 'Forbidden'); + + return (await projectService.listProjectsByOrganization(organizationId)) + .filter((project) => project.status === 'active' && project.modules?.codereport) + .map((project) => ({ id: project.id, slug: project.slug ?? '', name: project.name })); +} + +/** Ocurrencias de cada CVE en los proyectos indicados (uno, o todos los de una organización). */ +export function loadCveOccurrences( + projects: CveProject[], +): Promise> { + return codeReportCveService.getOrganizationCveOccurrences(projects); +} + +export function buildCveList( + occurrencesByCve: Map, +): CveListItem[] { + return [...occurrencesByCve.entries()] + .map(([id, occurrences]) => { + const services = new Map(); + for (const occurrence of occurrences) { + services.set(`${occurrence.projectSlug}/${occurrence.serviceSlug}`, { + slug: occurrence.serviceSlug, + name: occurrence.serviceName, + projectSlug: occurrence.projectSlug, + projectName: occurrence.projectName, + }); + } + return { + id, + title: occurrences.find((occurrence) => occurrence.finding.title)?.finding.title ?? '', + severity: highestSeverity(occurrences), + cvssScore: highestCvssScore(occurrences), + epssScore: highestEpssScore(occurrences), + fixable: occurrences.some((occurrence) => Boolean(occurrence.finding.fixedVersion)), + packages: [...new Set(occurrences.map((occurrence) => occurrence.finding.packageName))], + services: [...services.values()], + projectSlugs: [...new Set(occurrences.map((occurrence) => occurrence.projectSlug))], + occurrenceCount: occurrences.length, + publishedDate: + occurrences.map((occurrence) => occurrence.finding.publishedDate).find(Boolean) ?? null, + }; + }) + .sort( + (left, right) => + RANK[right.severity] - RANK[left.severity] || + (right.cvssScore ?? 0) - (left.cvssScore ?? 0) || + right.services.length - left.services.length, + ); +} + +export function buildCveDetail( + id: string, + occurrences: OrganizationCveOccurrence[], +): CveDetailData { + const findings = occurrences.map((occurrence) => occurrence.finding); + const first = findings.find((finding) => finding.description) ?? findings[0]; + + const remediations = new Map< + string, + CveDetailData['remediations'][number] & { keys: Set } + >(); + for (const occurrence of occurrences) { + const { packageName, installedVersion, fixedVersion } = occurrence.finding; + const key = `${packageName}@${fixedVersion}`; + const entry = remediations.get(key) ?? { + packageName, + installedVersions: [], + fixedVersion, + serviceCount: 0, + keys: new Set(), + }; + if (!entry.installedVersions.includes(installedVersion)) + entry.installedVersions.push(installedVersion); + entry.keys.add(`${occurrence.projectSlug}/${occurrence.serviceSlug}`); + entry.serviceCount = entry.keys.size; + remediations.set(key, entry); + } + + return { + cve: { + id, + title: first?.title ?? '', + description: first?.description ?? '', + severity: highestSeverity(occurrences), + cvssScore: highestCvssScore(occurrences), + epssScore: highestEpssScore(occurrences), + epssPercentile: highestEpssPercentile(occurrences), + primaryUrl: findings.find((finding) => finding.primaryUrl)?.primaryUrl ?? '', + cveUrl: first?.cveUrl ?? '', + cweIds: [...new Set(findings.flatMap((finding) => finding.cweIds))], + references: [...new Set(findings.flatMap((finding) => finding.references))], + publishedDate: findings.map((finding) => finding.publishedDate).find(Boolean) ?? null, + lastModifiedDate: findings.map((finding) => finding.lastModifiedDate).find(Boolean) ?? null, + }, + remediations: [...remediations.values()] + .map(({ keys: _keys, ...entry }) => entry) + .sort((left, right) => right.serviceCount - left.serviceCount), + affected: occurrences + .map((occurrence) => ({ + serviceSlug: occurrence.serviceSlug, + serviceName: occurrence.serviceName, + projectSlug: occurrence.projectSlug, + projectName: occurrence.projectName, + packageName: occurrence.finding.packageName, + installedVersion: occurrence.finding.installedVersion, + fixedVersion: occurrence.finding.fixedVersion, + target: occurrence.finding.packagePath || occurrence.finding.target, + severity: occurrence.finding.severity, + status: occurrence.finding.status, + scannedAt: occurrence.scannedAt, + })) + .sort( + (left, right) => + left.projectName.localeCompare(right.projectName) || + left.serviceName.localeCompare(right.serviceName), + ), + }; +} diff --git a/src/lib/server/dashboard/project-health.test.ts b/src/lib/server/dashboard/project-health.test.ts new file mode 100644 index 00000000..ae20eaf8 --- /dev/null +++ b/src/lib/server/dashboard/project-health.test.ts @@ -0,0 +1,91 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const listKeys = vi.fn(); + +vi.mock('#modules/auth', () => ({ + apiKeysService: { listActiveApiKeysByProject: (projectId: string) => listKeys(projectId) }, +})); +vi.mock('#modules/code-report', () => ({ codeReportService: {}, codeReportAnalysisService: {} })); +vi.mock('#modules/monitoring', () => ({ monitorService: {}, monitoringRuntime: {} })); +vi.mock('#modules/vault', () => ({ vaultService: {} })); + +const { DAY_MS, keyHealth } = await import('./project-health'); + +const NOW = Date.parse('2026-11-24T12:00:00.000Z'); +const daysAgo = (days: number) => new Date(NOW - days * DAY_MS).toISOString(); +const inDays = (days: number) => new Date(NOW + days * DAY_MS).toISOString(); + +function key(overrides: Record) { + return { + id: String(overrides.name), + name: 'key', + keyPrefix: 'gk_abc', + userId: null, + projectId: 'project-1', + roleId: null, + createdByUserId: null, + expiresAt: inDays(60), + lastUsedAt: daysAgo(1), + revokedAt: null, + rotatedAt: null, + createdAt: daysAgo(10), + ...overrides, + }; +} + +describe('keyHealth', () => { + beforeEach(() => listKeys.mockReset()); + + it('flags each risk and leaves healthy keys out', async () => { + listKeys.mockResolvedValue([ + key({ name: 'healthy' }), + key({ name: 'expired', expiresAt: daysAgo(1) }), + key({ name: 'expiring', expiresAt: inDays(5) }), + key({ name: 'no-expiry', expiresAt: null }), + key({ name: 'old', createdAt: daysAgo(200) }), + key({ name: 'idle', lastUsedAt: daysAgo(45) }), + key({ name: 'revoked', revokedAt: daysAgo(2), expiresAt: daysAgo(1) }), + ]); + + const health = await keyHealth('project-1', NOW); + + expect(health.active).toBe(6); + const risks = Object.fromEntries(health.atRisk.map((entry) => [entry.name, entry.risks])); + expect(risks).toEqual({ + expired: ['expired'], + expiring: ['expiring'], + 'no-expiry': ['noExpiry'], + old: ['notRotated'], + idle: ['unused'], + }); + expect(health.atRisk[0].name).toBe('expired'); + expect(health.counts).toEqual({ + expired: 1, + expiring: 1, + noExpiry: 1, + notRotated: 1, + unused: 1, + }); + }); + + it('counts rotation from the last regeneration, not from creation', async () => { + listKeys.mockResolvedValue([ + key({ name: 'rotated', createdAt: daysAgo(400), rotatedAt: daysAgo(3) }), + ]); + + const health = await keyHealth('project-1', NOW); + + expect(health.atRisk).toEqual([]); + }); + + it('treats a never-used key as unused once it is older than the threshold', async () => { + listKeys.mockResolvedValue([ + key({ name: 'fresh', lastUsedAt: null, createdAt: daysAgo(5) }), + key({ name: 'forgotten', lastUsedAt: null, createdAt: daysAgo(40) }), + ]); + + const health = await keyHealth('project-1', NOW); + + expect(health.atRisk.map((entry) => entry.name)).toEqual(['forgotten']); + }); +}); diff --git a/src/lib/server/dashboard/project-health.ts b/src/lib/server/dashboard/project-health.ts new file mode 100644 index 00000000..c78eb485 --- /dev/null +++ b/src/lib/server/dashboard/project-health.ts @@ -0,0 +1,286 @@ +/** + * Salud de un proyecto por producto, para los dashboards. Cada función lee un producto y + * devuelve solo conteos y metadatos: nunca valores de secretos, tokens ni resultados completos. + * Quien llama comprueba antes que el producto está activo y que el usuario puede leerlo. + */ +import { apiKeysService } from '#modules/auth'; +import { codeReportAnalysisService, codeReportService } from '#modules/code-report'; +import { monitorService, monitoringRuntime } from '#modules/monitoring'; +import { vaultService } from '#modules/vault'; +import { extractSecrets, summarizeAnalysisResult } from '#lib/code-report/analysis-summary'; +import { riskLevel, type RiskLevel } from '#lib/code-report/severity-ui'; + +export const DAY_MS = 24 * 60 * 60 * 1000; + +/** Umbrales de lo que el dashboard considera "a revisar". */ +export const HEALTH_THRESHOLDS = { + /** Un servicio sin analizar en este tiempo está desactualizado. */ + staleScanDays: 30, + /** Una clave que no se ha rotado en este tiempo. */ + keyRotationDays: 90, + /** Una clave que caduca en menos de esto. */ + keyExpiringDays: 14, + /** Una clave sin usar en este tiempo (o nunca usada tras este tiempo). */ + keyUnusedDays: 30, + /** Un secreto del vault que no ha cambiado en este tiempo. */ + secretRotationDays: 180, +} as const; + +export type Severity = { + critical: number; + high: number; + medium: number; + low: number; + unknown: number; +}; + +type LevelKey = RiskLevel['key']; + +/** Puntos de un servicio según su nivel de riesgo (mismos rangos que los ajustes de Code Report). */ +const LEVEL_POINTS: Record = { + none: 100, + low: 90, + medium: 65, + high: 35, + critical: 10, +}; +/** Un servicio con secretos expuestos no puntúa más de esto, sea cual sea su nivel. */ +const EXPOSED_SECRETS_CAP = 20; + +const time = (value: unknown) => new Date(value as string | Date).getTime(); + +export type CodeReportHealth = { + score: number | null; + totals: Severity; + services: number; + scanned: number; + staleServices: number; + exposedSecrets: number; + lastScanAt: string | null; +}; + +export async function codeReportHealth( + projectId: string, + now = Date.now(), +): Promise { + const [services, riskWeights] = await Promise.all([ + codeReportService.listByProject(projectId), + codeReportService.getRiskWeightsByProjectId(projectId), + ]); + const analyses = await codeReportAnalysisService.listByProject( + services.map((service) => service.id), + ); + + // último análisis completado de cada herramienta por servicio + const latestScan = new Map(); + const latestSecrets = new Map(); + const lastAnalysisAt = new Map(); + for (const analysis of analyses) { + const at = time(analysis.createdAt); + lastAnalysisAt.set( + analysis.serviceId, + Math.max(lastAnalysisAt.get(analysis.serviceId) ?? 0, at), + ); + if (analysis.status !== 'completed') continue; + if (analysis.tool === 'trivy' && at >= (latestScan.get(analysis.serviceId)?.at ?? 0)) { + latestScan.set(analysis.serviceId, { + at, + severity: summarizeAnalysisResult(analysis.result).vulnerabilities as Severity, + }); + } + if (analysis.tool === 'gitleaks' && at >= (latestSecrets.get(analysis.serviceId)?.at ?? 0)) { + latestSecrets.set(analysis.serviceId, { at, count: extractSecrets(analysis.result).length }); + } + } + + const totals: Severity = { critical: 0, high: 0, medium: 0, low: 0, unknown: 0 }; + for (const scan of latestScan.values()) { + for (const key of Object.keys(totals) as (keyof Severity)[]) totals[key] += scan.severity[key]; + } + + let points = 0; + for (const service of services) { + const scan = latestScan.get(service.id); + if (!scan) continue; + const level = riskLevel( + codeReportService.calculateRiskScore(scan.severity, riskWeights), + scan.severity.critical, + ).key; + const servicePoints = LEVEL_POINTS[level]; + const exposed = (latestSecrets.get(service.id)?.count ?? 0) > 0; + points += exposed ? Math.min(servicePoints, EXPOSED_SECRETS_CAP) : servicePoints; + } + + const staleCutoff = now - HEALTH_THRESHOLDS.staleScanDays * DAY_MS; + const last = Math.max(0, ...lastAnalysisAt.values()); + + return { + score: latestScan.size ? Math.round(points / latestScan.size) : null, + totals, + services: services.length, + scanned: latestScan.size, + staleServices: services.filter((service) => (lastAnalysisAt.get(service.id) ?? 0) < staleCutoff) + .length, + exposedSecrets: [...latestSecrets.values()].reduce((sum, entry) => sum + entry.count, 0), + lastScanAt: last ? new Date(last).toISOString() : null, + }; +} + +export type MonitoringHealth = { + total: number; + up: number; + down: number; + degraded: number; + paused: number; + uptime24h: number | null; + /** Monitores caídos o degradados, primero los caídos. */ + failing: { id: string; name: string; status: 'down' | 'degraded'; since: string | null }[]; +}; + +export async function monitoringHealth(projectId: string): Promise { + const [monitors, records] = await Promise.all([ + monitorService.listByProject(projectId), + monitorService.listRecordsByProject(projectId), + ]); + const stats = await monitoringRuntime.stats(records).catch(() => []); + const statsById = new Map(stats.map((entry) => [entry.monitorId, entry])); + + const rows = monitors.map((monitor) => { + const entry = statsById.get(monitor.id); + return { + id: monitor.id, + name: monitor.name, + status: (monitor.enabled ? (entry?.status ?? 'pending') : 'paused') as string, + since: entry?.since ? new Date(entry.since).toISOString() : null, + uptime24h: entry?.uptime.h24 ?? null, + }; + }); + const count = (status: string) => rows.filter((row) => row.status === status).length; + const uptimes = rows + .map((row) => row.uptime24h) + .filter((value): value is number => typeof value === 'number'); + + return { + total: rows.length, + up: count('up'), + down: count('down'), + degraded: count('degraded'), + paused: count('paused'), + uptime24h: uptimes.length + ? uptimes.reduce((sum, value) => sum + value, 0) / uptimes.length + : null, + failing: rows + .filter((row) => row.status === 'down' || row.status === 'degraded') + .sort((left, right) => (left.status === 'down' ? 0 : 1) - (right.status === 'down' ? 0 : 1)) + .map((row) => ({ + id: row.id, + name: row.name, + status: row.status as 'down' | 'degraded', + since: row.since, + })), + }; +} + +export type VaultHealth = { + secrets: number; + environments: number; + /** Valores vacíos: secretos que no tienen valor en algún entorno. */ + missingValues: number; + /** Secretos sin cambios desde hace más de `secretRotationDays`. */ + staleSecrets: number; +}; + +export async function vaultHealth(projectId: string, now = Date.now()): Promise { + const vault = await vaultService.getProjectVault(projectId); + const secrets = vault.secrets as { + values?: Record; + updatedAt?: unknown; + createdAt?: unknown; + }[]; + const environments = vault.environments as { slug: string }[]; + const cutoff = now - HEALTH_THRESHOLDS.secretRotationDays * DAY_MS; + + return { + secrets: secrets.length, + environments: environments.length, + missingValues: secrets.reduce( + (sum, secret) => + sum + environments.filter((environment) => !secret.values?.[environment.slug]).length, + 0, + ), + staleSecrets: secrets.filter((secret) => { + const changed = time(secret.updatedAt ?? secret.createdAt); + return Number.isFinite(changed) && changed < cutoff; + }).length, + }; +} + +export type KeyRisk = 'expired' | 'expiring' | 'noExpiry' | 'notRotated' | 'unused'; + +export type KeyHealth = { + active: number; + /** Claves con algún riesgo, la de mayor riesgo primero. */ + atRisk: { + id: string; + name: string; + keyPrefix: string; + risks: KeyRisk[]; + expiresAt: string | null; + lastUsedAt: string | null; + rotatedAt: string; + }[]; + counts: Record; +}; + +const KEY_RISK_ORDER: KeyRisk[] = ['expired', 'expiring', 'notRotated', 'noExpiry', 'unused']; + +export async function keyHealth(projectId: string, now = Date.now()): Promise { + const keys = (await apiKeysService.listActiveApiKeysByProject(projectId)).filter( + (key) => !key.revokedAt, + ); + const counts: Record = { + expired: 0, + expiring: 0, + noExpiry: 0, + notRotated: 0, + unused: 0, + }; + + const atRisk = keys + .map((key) => { + const risks: KeyRisk[] = []; + const expiresAt = key.expiresAt ? time(key.expiresAt) : null; + const rotatedAt = time(key.rotatedAt ?? key.createdAt); + const lastUsed = key.lastUsedAt ? time(key.lastUsedAt) : null; + + if (expiresAt !== null && expiresAt <= now) risks.push('expired'); + else if (expiresAt !== null && expiresAt - now < HEALTH_THRESHOLDS.keyExpiringDays * DAY_MS) + risks.push('expiring'); + if (expiresAt === null) risks.push('noExpiry'); + if (now - rotatedAt > HEALTH_THRESHOLDS.keyRotationDays * DAY_MS) risks.push('notRotated'); + if ( + now - (lastUsed ?? rotatedAt) > HEALTH_THRESHOLDS.keyUnusedDays * DAY_MS && + !risks.includes('expired') + ) + risks.push('unused'); + + for (const risk of risks) counts[risk] += 1; + return { + id: key.id, + name: key.name, + keyPrefix: key.keyPrefix, + risks, + expiresAt: key.expiresAt, + lastUsedAt: key.lastUsedAt, + rotatedAt: new Date(rotatedAt).toISOString(), + }; + }) + .filter((key) => key.risks.length > 0) + .sort( + (left, right) => + Math.min(...left.risks.map((risk) => KEY_RISK_ORDER.indexOf(risk))) - + Math.min(...right.risks.map((risk) => KEY_RISK_ORDER.indexOf(risk))), + ); + + return { active: keys.length, atRisk, counts }; +} diff --git a/src/lib/server/monitoring/page.ts b/src/lib/server/monitoring/page.ts index ca4ef672..55c836e5 100644 --- a/src/lib/server/monitoring/page.ts +++ b/src/lib/server/monitoring/page.ts @@ -2,7 +2,10 @@ import { error, fail, redirect, type RequestEvent } from '@sveltejs/kit'; import { cancanService } from '#modules/auth'; import { codeReportService } from '#modules/code-report'; import { projectService } from '#modules/projects'; +import { MONITOR_METHODS } from '#lib/monitoring/types'; import { + MONITOR_DEFAULTS, + MONITOR_INTERVAL_OPTIONS, MonitorNotFoundError, MonitorValidationError, monitorService, @@ -93,6 +96,29 @@ export async function loadMonitorsWithStats(projectId: string) { }; } +/** Valores iniciales del formulario de alta (página /monitors/new y modal "Nuevo monitor"). */ +export function newMonitorForm(services: ServiceOption[], presetServiceId = '') { + return { + methods: MONITOR_METHODS, + intervals: MONITOR_INTERVAL_OPTIONS, + values: { + name: '', + url: '', + method: MONITOR_DEFAULTS.method, + serviceId: services.some((service) => service.id === presetServiceId) ? presetServiceId : '', + headers: [] as { name: string; value: string }[], + body: '', + intervalSeconds: String(MONITOR_DEFAULTS.intervalSeconds), + timeoutMs: String(MONITOR_DEFAULTS.timeoutMs), + expectedStatus: MONITOR_DEFAULTS.expectedStatus, + degradedThresholdMs: String(MONITOR_DEFAULTS.degradedThresholdMs), + confirmations: String(MONITOR_DEFAULTS.confirmations), + followRedirects: MONITOR_DEFAULTS.followRedirects, + enabled: true, + }, + }; +} + /** Form fields → service input. `editing`: an empty secret field keeps the stored value. */ export function parseMonitorForm(form: FormData, editing: boolean): MonitorInput { const names = form.getAll('headerName').map(String); diff --git a/src/lib/styles/brand.css b/src/lib/styles/brand.css new file mode 100644 index 00000000..9c865959 --- /dev/null +++ b/src/lib/styles/brand.css @@ -0,0 +1,480 @@ +/* + * Kettu brand — base del rediseño UI v3. + * Paleta tomada de https://kettu.studio (naranja zorro + superficies ink). + * Las utilidades `brand-*` / `ink-*` las genera Tailwind a partir de @theme. + * Las clases `k-*` son componentes base; se van iterando en /brand. + */ + +@theme { + --font-sans: + 'Inter', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, + sans-serif; + --font-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; + + /* Marca: naranja zorro */ + --color-brand-50: #fff4ec; + --color-brand-100: #ffe6d4; + --color-brand-200: #ffc9a8; + --color-brand-300: #ffa470; + --color-brand-400: #ff7a38; + --color-brand-500: #f95d11; + --color-brand-600: #e14607; + --color-brand-700: #ba3208; + --color-brand-800: #94290e; + --color-brand-900: #78240f; + + /* Fondo y superficies */ + --color-ink-950: #0a0a0d; + --color-ink-900: #101014; + --color-ink-800: #17171d; + --color-ink-700: #212129; + --color-ink-600: #2c2c36; + --color-ink-500: #3a3a46; + + /* Blanco puro. Usa bg-snow en vez de bg-white: app.css (UI v2) sobrescribe .bg-white */ + --color-snow: #ffffff; + + /* Texto */ + --color-fg: #e7e7ea; + --color-fg-muted: #a9a9b3; + --color-fg-subtle: #72727e; + + /* Estado (reservados, siempre con icono + texto) */ + --color-ok: #22c55e; + --color-warn: #f59e0b; + --color-danger: #ef4444; + --color-info: #60a5fa; + + /* Series para gráficas (orden fijo, validado CVD sobre ink-900) */ + --color-series-1: #e14607; + --color-series-2: #3b82f6; + --color-series-3: #0d9488; + --color-series-4: #a855f7; + --color-series-5: #b8860b; +} + +/* + * Componentes en @layer components: las utilidades de Tailwind (pl-8, h-9, w-full…) pueden + * ajustarlos, y sus !important ganan a los del CSS antiguo de app.css, que no está en capa. + */ +@layer components { + /* ---------- Texto ---------- */ + + .k-text-gradient { + background: linear-gradient(180deg, #ffffff 30%, #a9a9b3 100%); + -webkit-background-clip: text; + background-clip: text; + color: transparent; + } + + .k-text-gradient-brand { + background: linear-gradient(90deg, #ff7a38 0%, #ffb37a 100%); + -webkit-background-clip: text; + background-clip: text; + color: transparent; + } + + /* ---------- Fondos decorativos ---------- */ + + .k-hero-glow { + background: + radial-gradient(60% 50% at 50% 0%, rgba(249, 93, 17, 0.14) 0%, transparent 70%), + radial-gradient(40% 40% at 80% 10%, rgba(255, 122, 56, 0.06) 0%, transparent 70%); + } + + .k-bg-grid { + background-image: + linear-gradient(to right, rgba(255, 255, 255, 0.035) 1px, transparent 1px), + linear-gradient(to bottom, rgba(255, 255, 255, 0.035) 1px, transparent 1px); + background-size: 64px 64px; + mask-image: radial-gradient(ellipse 80% 60% at 50% 0%, black 40%, transparent 100%); + } + + /* ---------- Superficies ---------- */ + + .k-card { + border-radius: 1rem; + border: 1px solid rgb(255 255 255 / 0.1); + background: rgb(255 255 255 / 0.02); + } + + .k-card-hover { + transition: + border-color 150ms, + background-color 150ms; + } + .k-card-hover:hover { + border-color: rgb(249 93 17 / 0.4); + background: rgb(255 255 255 / 0.035); + } + + .k-panel { + border-radius: 0.75rem; + border: 1px solid rgb(255 255 255 / 0.08); + background: var(--color-ink-900); + } + + .k-popover { + border-radius: 0.75rem; + border: 1px solid rgb(255 255 255 / 0.1); + background: var(--color-ink-800); + box-shadow: + 0 20px 50px -12px rgb(0 0 0 / 0.7), + 0 0 0 1px rgb(0 0 0 / 0.3); + } + + /* ---------- Botones ---------- */ + + .k-btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 0.5rem; + height: 2.5rem; + padding: 0 1rem; + border-radius: 0.625rem; + border: 1px solid transparent; + font-size: 0.875rem; + font-weight: 600; + line-height: 1; + white-space: nowrap; + transition: + background-color 150ms, + border-color 150ms, + color 150ms, + box-shadow 150ms; + cursor: pointer; + } + .k-btn:focus-visible { + outline: none; + box-shadow: 0 0 0 3px rgb(249 93 17 / 0.35); + } + .k-btn:disabled { + opacity: 0.45; + cursor: not-allowed; + } + + .k-btn-sm { + height: 2rem; + padding: 0 0.75rem; + font-size: 0.8125rem; + border-radius: 0.5rem; + } + .k-btn-lg { + height: 3rem; + padding: 0 1.5rem; + font-size: 0.9375rem; + border-radius: 0.75rem; + } + .k-btn-icon { + width: 2.5rem; + padding: 0; + } + .k-btn-sm.k-btn-icon { + width: 2rem; + } + + .k-btn-primary { + background: var(--color-brand-500); + color: #fff; + box-shadow: 0 8px 24px -8px rgb(249 93 17 / 0.55); + } + .k-btn-primary:hover:not(:disabled) { + background: var(--color-brand-400); + } + .k-btn-primary:active:not(:disabled) { + background: var(--color-brand-600); + } + + .k-btn-secondary { + background: rgb(255 255 255 / 0.04); + border-color: rgb(255 255 255 / 0.12); + color: var(--color-fg); + } + .k-btn-secondary:hover:not(:disabled) { + background: rgb(255 255 255 / 0.08); + border-color: rgb(255 255 255 / 0.2); + } + + .k-btn-ghost { + background: transparent; + color: var(--color-fg-muted); + } + .k-btn-ghost:hover:not(:disabled) { + background: rgb(255 255 255 / 0.06); + color: #fff; + } + + .k-btn-outline-brand { + background: rgb(249 93 17 / 0.06); + border-color: rgb(249 93 17 / 0.4); + color: var(--color-brand-300); + } + .k-btn-outline-brand:hover:not(:disabled) { + background: rgb(249 93 17 / 0.12); + border-color: var(--color-brand-500); + } + + .k-btn-danger { + background: rgb(239 68 68 / 0.1); + border-color: rgb(239 68 68 / 0.35); + color: #fca5a5; + } + .k-btn-danger:hover:not(:disabled) { + background: var(--color-danger); + border-color: var(--color-danger); + color: #fff; + } + + /* ---------- Formularios ---------- */ + + .k-input { + width: 100%; + height: 2.5rem; + padding: 0 0.875rem; + border-radius: 0.625rem; + border: 1px solid rgb(255 255 255 / 0.1); + background: var(--color-ink-900); + color: var(--color-fg); + font-size: 0.875rem; + transition: + border-color 150ms, + box-shadow 150ms; + } + textarea.k-input { + height: auto; + padding: 0.625rem 0.875rem; + resize: vertical; + } + .k-input::placeholder { + color: var(--color-fg-subtle); + } + .k-input:hover { + border-color: rgb(255 255 255 / 0.18); + } + .k-input:focus { + outline: none; + border-color: var(--color-brand-500); + box-shadow: 0 0 0 3px rgb(249 93 17 / 0.2); + } + .k-input[aria-invalid='true'] { + border-color: rgb(239 68 68 / 0.7); + } + .k-input::placeholder, + textarea.k-input::placeholder { + color: var(--color-fg-subtle) !important; + } + /* + * app.css (UI v2) fuerza `input, select, textarea { background: #071323 !important }`. + * Un !important dentro de una capa gana a uno fuera de capa, así que estos prevalecen. + * Quitar este bloque cuando se eliminen las reglas antiguas de app.css. + */ + .k-input { + background-color: var(--color-ink-900) !important; + color: var(--color-fg) !important; + border-color: rgb(255 255 255 / 0.1) !important; + } + .k-input:hover { + border-color: rgb(255 255 255 / 0.18) !important; + } + .k-input:focus { + border-color: var(--color-brand-500) !important; + } + .k-input[aria-invalid='true'] { + border-color: rgb(239 68 68 / 0.7) !important; + } + + /* Input sin caja, para buscadores dentro de popovers */ + .k-input-bare, + .k-input-bare:hover, + .k-input-bare:focus { + background-color: transparent !important; + border-color: transparent !important; + box-shadow: none !important; + /* va dentro de un contenedor que ya marca el foco (paleta, selector, buscador del Select) */ + outline: none; + } + .k-input:disabled { + opacity: 0.5; + cursor: not-allowed; + } + + .k-label { + display: block; + margin-bottom: 0.375rem; + font-size: 0.8125rem; + font-weight: 500; + color: var(--color-fg); + } + + .k-help { + margin-top: 0.375rem; + font-size: 0.75rem; + color: var(--color-fg-subtle); + } + + .k-checkbox { + appearance: none; + width: 1.125rem; + height: 1.125rem; + flex-shrink: 0; + border-radius: 0.3rem; + border: 1px solid rgb(255 255 255 / 0.2); + background: var(--color-ink-900); + display: grid; + place-content: center; + cursor: pointer; + } + .k-checkbox[type='radio'] { + border-radius: 999px; + } + .k-checkbox { + background-color: var(--color-ink-900) !important; + border-color: rgb(255 255 255 / 0.2) !important; + } + .k-checkbox:hover { + border-color: rgb(255 255 255 / 0.35) !important; + } + .k-checkbox:checked { + background-color: var(--color-brand-500) !important; + border-color: var(--color-brand-500) !important; + } + .k-checkbox:checked::after { + content: ''; + width: 0.55rem; + height: 0.55rem; + background: #fff; + clip-path: polygon(14% 44%, 0 65%, 50% 100%, 100% 16%, 80% 0%, 43% 62%); + } + .k-checkbox[type='radio']:checked::after { + width: 0.4rem; + height: 0.4rem; + border-radius: 999px; + clip-path: none; + } + .k-checkbox:focus-visible { + outline: none; + box-shadow: 0 0 0 3px rgb(249 93 17 / 0.3); + } + + /* ---------- Badges ---------- */ + + .k-badge { + display: inline-flex; + align-items: center; + gap: 0.375rem; + height: 1.5rem; + padding: 0 0.5rem; + border-radius: 999px; + border: 1px solid rgb(255 255 255 / 0.1); + background: rgb(255 255 255 / 0.04); + font-size: 0.75rem; + font-weight: 500; + color: var(--color-fg-muted); + white-space: nowrap; + } + .k-badge-brand { + border-color: rgb(249 93 17 / 0.35); + background: rgb(249 93 17 / 0.1); + color: var(--color-brand-300); + } + .k-badge-ok { + border-color: rgb(34 197 94 / 0.3); + background: rgb(34 197 94 / 0.08); + color: #86efac; + } + .k-badge-warn { + border-color: rgb(245 158 11 / 0.3); + background: rgb(245 158 11 / 0.08); + color: #fcd34d; + } + .k-badge-danger { + border-color: rgb(239 68 68 / 0.35); + background: rgb(239 68 68 / 0.08); + color: #fca5a5; + } + .k-badge-info { + border-color: rgb(96 165 250 / 0.3); + background: rgb(96 165 250 / 0.08); + color: #93c5fd; + } + + .k-kbd { + display: inline-flex; + align-items: center; + height: 1.25rem; + padding: 0 0.375rem; + border-radius: 0.3rem; + border: 1px solid rgb(255 255 255 / 0.12); + border-bottom-width: 2px; + background: var(--color-ink-800); + font-family: var(--font-mono); + font-size: 0.6875rem; + color: var(--color-fg-muted); + } + + /* ---------- Navegación ---------- */ + + .k-nav-item { + display: flex; + align-items: center; + gap: 0.625rem; + height: 2.25rem; + padding: 0 0.625rem; + border-radius: 0.5rem; + font-size: 0.875rem; + font-weight: 500; + color: var(--color-fg-muted); + transition: + background-color 120ms, + color 120ms; + } + .k-nav-item:hover { + background: rgb(255 255 255 / 0.05); + color: #fff; + } + .k-nav-item[aria-current='page'] { + background: rgb(249 93 17 / 0.1); + color: #fff; + box-shadow: inset 2px 0 0 var(--color-brand-500); + } + .k-nav-item[aria-current='page'] :is(svg) { + color: var(--color-brand-400); + } + + .k-nav-heading { + padding: 0 0.625rem; + margin-bottom: 0.375rem; + font-size: 0.6875rem; + font-weight: 600; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--color-fg-subtle); + } + + .k-menu-item { + display: flex; + width: 100%; + align-items: center; + gap: 0.625rem; + padding: 0.5rem 0.625rem; + border-radius: 0.5rem; + font-size: 0.875rem; + color: var(--color-fg); + text-align: left; + cursor: pointer; + } + .k-menu-item:hover, + .k-menu-item:focus-visible { + outline: none; + background: rgb(255 255 255 / 0.06); + } + .k-menu-item[aria-selected='true'] { + color: #fff; + } + + .k-divider { + height: 1px; + background: rgb(255 255 255 / 0.08); + } +} diff --git a/src/modules/alerts/application/alert-engine.test.ts b/src/modules/alerts/application/alert-engine.test.ts index bacd0a72..52c09f93 100644 --- a/src/modules/alerts/application/alert-engine.test.ts +++ b/src/modules/alerts/application/alert-engine.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { emptyRecipients } from '../domain/alert.domain'; import type { AnyDomainEvent } from '#lib/server/events'; import { InProcessEventBus } from '#lib/server/events'; import type { CodeReportAnalysisCompletedPayload } from '#lib/events/domain-events'; @@ -109,7 +110,7 @@ function alertRow(overrides: Partial = {}): AlertRow { eventType: 'code_report.analysis.completed', match: 'all', conditions: [{ field: 'summary.critical', operator: 'gt', value: 0 }], - recipients: { userIds: [], roleIds: ['project-reporter'] }, + recipients: { ...emptyRecipients(), userIds: [], roleIds: ['project-reporter'] }, channels: ['mail'], throttleMinutes: 0, createdByUserId: 'author', @@ -239,15 +240,29 @@ describe('AlertEngine', () => { it('skips disabled users and users without an email', async () => { repository.rows = [ - alertRow({ recipients: { userIds: ['carl', 'nomail', 'ana'], roleIds: [] } }), + alertRow({ recipients: { ...emptyRecipients(), userIds: ['carl', 'nomail', 'ana'], roleIds: [] } }), ]; await engine.handle(completed()); expect(sentTo()).toEqual(['ana']); }); + it('also emails external addresses, once each', async () => { + repository.rows = [ + alertRow({ + recipients: { + ...emptyRecipients(), + userIds: ['ana'], + emails: ['oncall@example.com', 'ONCALL@example.com'], + }, + }), + ]; + await engine.handle(completed()); + expect(sentTo()).toEqual(['ana', 'email:oncall@example.com']); + }); + it('does not email recipients without the read permission, most-specific-wins included', async () => { repository.rows = [ - alertRow({ recipients: { userIds: ['ana', 'dora', 'eli', 'fran'], roleIds: [] } }), + alertRow({ recipients: { ...emptyRecipients(), userIds: ['ana', 'dora', 'eli', 'fran'], roleIds: [] } }), ]; await engine.handle(completed()); @@ -263,12 +278,12 @@ describe('AlertEngine', () => { it('only fires alerts whose scope covers the event', async () => { repository.rows = [ alertRow({ id: 'p1-alert' }), - alertRow({ id: 'p2-alert', projectId: 'p2', recipients: { userIds: ['pia'], roleIds: [] } }), + alertRow({ id: 'p2-alert', projectId: 'p2', recipients: { ...emptyRecipients(), userIds: ['pia'], roleIds: [] } }), alertRow({ id: 'org-alert', scope: 'organization', projectId: null, - recipients: { userIds: ['eli'], roleIds: [] }, + recipients: { ...emptyRecipients(), userIds: ['eli'], roleIds: [] }, }), alertRow({ id: 'other-org', @@ -295,7 +310,7 @@ describe('AlertEngine', () => { it('throttles an alert and reports the suppressed events in the next email', async () => { repository.rows = [ - alertRow({ throttleMinutes: 30, recipients: { userIds: ['ana'], roleIds: [] } }), + alertRow({ throttleMinutes: 30, recipients: { ...emptyRecipients(), userIds: ['ana'], roleIds: [] } }), ]; await engine.handle(completed({}, undefined, 'e1')); @@ -480,7 +495,7 @@ describe('AlertEngine', () => { scope: 'organization', projectId: null, conditions: [], - recipients: { userIds: ['eli'], roleIds: [] }, + recipients: { ...emptyRecipients(), userIds: ['eli'], roleIds: [] }, }), ]; diff --git a/src/modules/alerts/application/alert-engine.ts b/src/modules/alerts/application/alert-engine.ts index 55054a6d..2abd25d3 100644 --- a/src/modules/alerts/application/alert-engine.ts +++ b/src/modules/alerts/application/alert-engine.ts @@ -1,7 +1,7 @@ import type { Logger } from 'pino'; import { getEventDefinition, isEventType, type EventDefinition } from '#lib/events/catalog'; import type { AnyDomainEvent, EventBus, Unsubscribe } from '#lib/server/events'; -import type { AlertDomain } from '../domain/alert.domain'; +import { DELIVERED_CHANNELS, type AlertDomain } from '../domain/alert.domain'; import { matches } from '../domain/condition-evaluator'; import { getSystemNotification, @@ -159,6 +159,14 @@ export class AlertEngine { const context = eventContext(event.scope); if (!context) return; + const pending = alert.channels.filter((channel) => !DELIVERED_CHANNELS.includes(channel)); + if (pending.length > 0) { + log.debug( + { alertId: alert.id, channels: pending }, + '[alerts] channels without a notifier yet are skipped', + ); + } + const decision = this.throttle.acquire(alert.id, alert.throttleMinutes); if (!decision.send) { log.info( diff --git a/src/modules/alerts/application/alert.service.test.ts b/src/modules/alerts/application/alert.service.test.ts index 4c716667..c52b9219 100644 --- a/src/modules/alerts/application/alert.service.test.ts +++ b/src/modules/alerts/application/alert.service.test.ts @@ -105,7 +105,7 @@ describe('AlertService', () => { const errors = await validationErrors( service.create( projectLocation, - { name: ' ', match: 'some', recipients: {}, throttleMinutes: -1, channels: ['slack'] }, + { name: ' ', match: 'some', recipients: {}, throttleMinutes: -1, channels: ['sms'] }, actor(), ), ); @@ -262,6 +262,77 @@ describe('AlertService', () => { }); }); + describe('channels', () => { + it('keeps the targets of every enabled channel and normalizes them', async () => { + const alert = await service.create( + projectLocation, + guidedExample({ + channels: ['mail', 'slack', 'google_chat', 'webhook'], + recipients: { + roleIds: ['role-project-admin'], + emails: [' Ops@Example.com ', 'ops@example.com'], + slackChannels: ['Alerts', '#alerts'], + googleChatSpaces: ['Incidencias'], + webhookUrls: ['https://hooks.example.com/gitops'], + }, + }), + actor(), + ); + expect(alert.channels).toEqual(['mail', 'slack', 'google_chat', 'webhook']); + expect(alert.recipients).toMatchObject({ + emails: ['ops@example.com'], + slackChannels: ['#alerts'], + googleChatSpaces: ['Incidencias'], + webhookUrls: ['https://hooks.example.com/gitops'], + }); + }); + + it('drops the targets of disabled channels', async () => { + const alert = await service.create( + projectLocation, + guidedExample({ + channels: ['slack'], + recipients: { roleIds: ['role-project-admin'], slackChannels: ['#alerts'] }, + }), + actor(), + ); + expect(alert.recipients.roleIds).toEqual([]); + expect(alert.recipients.slackChannels).toEqual(['#alerts']); + }); + + it('requires a valid target for each enabled channel', async () => { + const errors = await validationErrors( + service.create( + projectLocation, + guidedExample({ + channels: ['mail', 'slack', 'google_chat', 'webhook'], + recipients: { + emails: ['not-an-email'], + slackChannels: ['bad channel!'], + webhookUrls: ['ftp://example.com'], + }, + }), + actor(), + ), + ); + expect(errors).toEqual({ + 'recipients.emails': 'invalid_email', + 'recipients.slackChannels': 'invalid_slack_channel', + 'recipients.googleChatSpaces': 'required', + 'recipients.webhookUrls': 'invalid_url', + }); + }); + + it('accepts external addresses as the only mail targets', async () => { + const alert = await service.create( + projectLocation, + guidedExample({ recipients: { emails: ['oncall@example.com'] } }), + actor(), + ); + expect(alert.recipients.emails).toEqual(['oncall@example.com']); + }); + }); + describe('recipients', () => { it('rejects users and roles outside the location', async () => { const errors = await validationErrors( diff --git a/src/modules/alerts/application/alert.service.ts b/src/modules/alerts/application/alert.service.ts index 00e5e973..3fbb51a5 100644 --- a/src/modules/alerts/application/alert.service.ts +++ b/src/modules/alerts/application/alert.service.ts @@ -21,6 +21,7 @@ import { type AlertMatch, type AlertRecipients, type AlertValidationErrors, + emptyRecipients, } from '../domain/alert.domain'; import type { AlertRepositoryPort } from '../infrastructure/repositories/alert.repository'; import { @@ -34,6 +35,11 @@ const MAX_NAME_LENGTH = 120; const MAX_DESCRIPTION_LENGTH = 1000; const MAX_CONDITIONS = 20; const MAX_LIST_VALUES = 100; +const MAX_TARGETS = 50; + +const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; +const SLACK_CHANNEL_PATTERN = /^#[a-z0-9][a-z0-9._-]{0,79}$/; +const MAX_SPACE_LENGTH = 128; const VALUELESS_OPERATORS = new Set(['is_true', 'is_false', 'exists']); const LIST_OPERATORS = new Set(['in', 'not_in']); @@ -142,10 +148,10 @@ export class AlertService { ? await this.validateConditions(location, definition, input.conditions, errors, references) : []; - const recipients = await this.validateRecipients(location, input.recipients, errors); - const channels = this.validateChannels(input.channels, errors); + const recipients = await this.validateRecipients(location, input.recipients, channels, errors); + const throttleMinutes = Number(input.throttleMinutes ?? 0); if ( !Number.isInteger(throttleMinutes) || @@ -392,34 +398,87 @@ export class AlertService { } } + /** + * Targets of every enabled channel; those of disabled channels are dropped. Each enabled + * channel needs at least one target (`recipients` keeps its historical key for mail). + */ private async validateRecipients( location: AlertLocation, value: unknown, + channels: AlertChannel[], errors: AlertValidationErrors, ): Promise { const raw = (value ?? {}) as Record; - const ids = (list: unknown) => - Array.isArray(list) - ? [...new Set(list.filter((id): id is string => typeof id === 'string' && !!id))] + const list = (key: string, normalize: (item: string) => string = (item) => item.trim()) => + Array.isArray(raw[key]) + ? [ + ...new Set( + (raw[key] as unknown[]) + .filter((item): item is string => typeof item === 'string') + .map(normalize) + .filter(Boolean), + ), + ] : []; - const userIds = ids(raw.userIds); - const roleIds = ids(raw.roleIds); + const recipients = emptyRecipients(); + const tooMany = (key: string, items: string[]) => { + if (items.length > MAX_TARGETS) errors[`recipients.${key}`] = 'too_many'; + }; + + if (channels.includes('mail')) { + recipients.userIds = list('userIds'); + recipients.roleIds = list('roleIds'); + recipients.emails = list('emails', (item) => item.trim().toLowerCase()); + const { userIds, roleIds, emails } = recipients; + if (userIds.length === 0 && roleIds.length === 0 && emails.length === 0) { + errors.recipients = 'required'; + } + if (userIds.length > 0) { + const members = new Set((await this.directory.listMembers(location)).map((m) => m.userId)); + if (userIds.some((id) => !members.has(id))) errors['recipients.userIds'] = 'unknown_user'; + } + if (roleIds.length > 0) { + const roles = new Set((await this.directory.listRoles(location)).map((role) => role.id)); + if (roleIds.some((id) => !roles.has(id))) errors['recipients.roleIds'] = 'unknown_role'; + } + if (emails.some((email) => !EMAIL_PATTERN.test(email))) { + errors['recipients.emails'] = 'invalid_email'; + } + tooMany('emails', emails); + } - if (userIds.length === 0 && roleIds.length === 0) { - errors.recipients = 'required'; - return { userIds, roleIds }; + if (channels.includes('slack')) { + recipients.slackChannels = list('slackChannels', (item) => { + const name = item.trim().toLowerCase(); + return name && !name.startsWith('#') ? `#${name}` : name; + }); + if (recipients.slackChannels.length === 0) errors['recipients.slackChannels'] = 'required'; + else if (recipients.slackChannels.some((name) => !SLACK_CHANNEL_PATTERN.test(name))) { + errors['recipients.slackChannels'] = 'invalid_slack_channel'; + } + tooMany('slackChannels', recipients.slackChannels); } - if (userIds.length > 0) { - const members = new Set((await this.directory.listMembers(location)).map((m) => m.userId)); - if (userIds.some((id) => !members.has(id))) errors['recipients.userIds'] = 'unknown_user'; + if (channels.includes('google_chat')) { + recipients.googleChatSpaces = list('googleChatSpaces'); + if (recipients.googleChatSpaces.length === 0) { + errors['recipients.googleChatSpaces'] = 'required'; + } else if (recipients.googleChatSpaces.some((space) => space.length > MAX_SPACE_LENGTH)) { + errors['recipients.googleChatSpaces'] = 'too_long'; + } + tooMany('googleChatSpaces', recipients.googleChatSpaces); } - if (roleIds.length > 0) { - const roles = new Set((await this.directory.listRoles(location)).map((role) => role.id)); - if (roleIds.some((id) => !roles.has(id))) errors['recipients.roleIds'] = 'unknown_role'; + + if (channels.includes('webhook')) { + recipients.webhookUrls = list('webhookUrls'); + if (recipients.webhookUrls.length === 0) errors['recipients.webhookUrls'] = 'required'; + else if (recipients.webhookUrls.some((url) => !isHttpUrl(url))) { + errors['recipients.webhookUrls'] = 'invalid_url'; + } + tooMany('webhookUrls', recipients.webhookUrls); } - return { userIds, roleIds }; + return recipients; } private validateChannels(value: unknown, errors: AlertValidationErrors): AlertChannel[] { @@ -433,3 +492,12 @@ export class AlertService { return [...new Set(list as AlertChannel[])]; } } + +function isHttpUrl(value: string): boolean { + try { + const url = new URL(value); + return url.protocol === 'https:' || url.protocol === 'http:'; + } catch { + return false; + } +} diff --git a/src/modules/alerts/application/recipient-resolver.ts b/src/modules/alerts/application/recipient-resolver.ts index f14db3dc..85c0038b 100644 --- a/src/modules/alerts/application/recipient-resolver.ts +++ b/src/modules/alerts/application/recipient-resolver.ts @@ -18,7 +18,8 @@ export type ResolvedRecipients = { * Turns an alert's users and roles into the people that get the email: the selected users plus * every member holding one of the roles, restricted to current members of the alert's location * that are enabled and have an email, and finally to those allowed to read the event - * (`readPermission` checked where the event happened, most-specific-wins included). + * (`readPermission` checked where the event happened, most-specific-wins included). External + * addresses (`emails`) are appended as they are. */ export class RecipientResolver { constructor( @@ -56,6 +57,15 @@ export class RecipientResolver { else denied.push(candidate.userId); } + // addresses outside the platform: the alert's author chose them explicitly and could read the + // event when saving it (anti-escalation check), so they are not permission-filtered + const known = new Set(recipients.map((recipient) => recipient.email.toLowerCase())); + for (const email of selection.emails ?? []) { + if (known.has(email.toLowerCase())) continue; + known.add(email.toLowerCase()); + recipients.push({ userId: `email:${email}`, username: email, email }); + } + return { recipients, denied }; } } diff --git a/src/modules/alerts/domain/alert.domain.ts b/src/modules/alerts/domain/alert.domain.ts index 4095ce55..c78c06ae 100644 --- a/src/modules/alerts/domain/alert.domain.ts +++ b/src/modules/alerts/domain/alert.domain.ts @@ -4,9 +4,15 @@ import type { Operator } from '#lib/events/catalog'; export type AlertScope = 'organization' | 'project'; export type AlertMatch = 'all' | 'any'; -/** v1 only sends emails; the field is ready for in-app and Slack (#82). */ -export const ALERT_CHANNELS = ['mail'] as const; +/** + * Where an alert is delivered. An alert can use several channels at once and sends one message to + * each. Only `mail` is delivered today; the others are stored and validated so the UI and the API + * are ready when their notifiers land (#82). + */ +export const ALERT_CHANNELS = ['mail', 'slack', 'google_chat', 'webhook'] as const; export type AlertChannel = (typeof ALERT_CHANNELS)[number]; +/** Channels with a notifier: the rest are skipped by the engine. */ +export const DELIVERED_CHANNELS: readonly AlertChannel[] = ['mail']; export const ALERT_MATCHES = ['all', 'any'] as const; @@ -21,11 +27,33 @@ export type AlertCondition = { value?: string | number | string[]; }; +/** Targets per channel; only the arrays of the alert's enabled channels are kept. */ export type AlertRecipients = { + /** mail: platform users */ userIds: string[]; + /** mail: every member holding one of these roles */ roleIds: string[]; + /** mail: addresses outside the platform */ + emails: string[]; + /** slack: channel names, stored with their `#` */ + slackChannels: string[]; + /** google_chat: space names */ + googleChatSpaces: string[]; + /** webhook: http(s) URLs that receive a JSON POST */ + webhookUrls: string[]; }; +export function emptyRecipients(): AlertRecipients { + return { + userIds: [], + roleIds: [], + emails: [], + slackChannels: [], + googleChatSpaces: [], + webhookUrls: [], + }; +} + /** Where an alert lives: an organization alert has no project. */ export type AlertLocation = { scope: AlertScope; @@ -110,6 +138,10 @@ export class AlertDomain implements AlertRow { this.recipients = { userIds: stringArray(row.recipients?.userIds), roleIds: stringArray(row.recipients?.roleIds), + emails: stringArray(row.recipients?.emails), + slackChannels: stringArray(row.recipients?.slackChannels), + googleChatSpaces: stringArray(row.recipients?.googleChatSpaces), + webhookUrls: stringArray(row.recipients?.webhookUrls), }; const channels = stringArray(row.channels).filter((channel): channel is AlertChannel => (ALERT_CHANNELS as readonly string[]).includes(channel), @@ -153,6 +185,10 @@ export class AlertDomain implements AlertRow { recipients: { userIds: [...this.recipients.userIds], roleIds: [...this.recipients.roleIds], + emails: [...this.recipients.emails], + slackChannels: [...this.recipients.slackChannels], + googleChatSpaces: [...this.recipients.googleChatSpaces], + webhookUrls: [...this.recipients.webhookUrls], }, channels: [...this.channels], throttleMinutes: this.throttleMinutes, diff --git a/src/modules/auth/domain/entities.ts b/src/modules/auth/domain/entities.ts index 93971a78..149bcc86 100644 --- a/src/modules/auth/domain/entities.ts +++ b/src/modules/auth/domain/entities.ts @@ -74,6 +74,8 @@ export type ApiKeyView = { expiresAt: string | null; lastUsedAt: string | null; revokedAt: string | null; + /** Última rotación del secreto (regenerar); null si nunca se ha rotado. */ + rotatedAt?: string | null; createdAt: string; }; diff --git a/src/modules/auth/infrastructure/repositories/apikey.repository.ts b/src/modules/auth/infrastructure/repositories/apikey.repository.ts index 20eaa2f4..6008cc7d 100644 --- a/src/modules/auth/infrastructure/repositories/apikey.repository.ts +++ b/src/modules/auth/infrastructure/repositories/apikey.repository.ts @@ -14,6 +14,7 @@ type ApiKeyRow = { expiresAt: string | null; lastUsedAt: string | null; revokedAt: string | null; + rotatedAt?: string | null; createdAt: string; }; @@ -141,6 +142,7 @@ export class ApiKeyRepository extends Repository { expiresAt: input.expiresAt, revokedAt: null, lastUsedAt: null, + rotatedAt: new Date().toISOString(), }) .where({ id: keyId }); } @@ -157,6 +159,7 @@ export class ApiKeyRepository extends Repository { expiresAt: row.expiresAt, lastUsedAt: row.lastUsedAt, revokedAt: row.revokedAt, + rotatedAt: row.rotatedAt ?? null, createdAt: row.createdAt, }; } diff --git a/src/modules/code-report/index.ts b/src/modules/code-report/index.ts index 59356f9f..03e7fe36 100644 --- a/src/modules/code-report/index.ts +++ b/src/modules/code-report/index.ts @@ -31,3 +31,5 @@ export const codeReportCveService = new CodeReportCveService( codeReportService, codeReportAnalysisService, ); + +export type { OrganizationCveOccurrence } from './application/code-report-cve.service'; diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index c1d5ae68..ac9dbb47 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -1,98 +1,265 @@ -
    - {#if !isBareLayout} +{#if isBareLayout} + +
    + {@render children()} +
    +{:else} +
    (searchOpen = true) : undefined} + menuOpen={mobileMenuOpen} + onmenu={() => (mobileMenuOpen = !mobileMenuOpen)} /> - + + {#if mobileMenuOpen} + + {/if}
    - - -
    - -
    +
    - {:else} - - {/if} - - {#if !isBareLayout} -
    - {/if} -
    + +
    +
    + + {#if crumbs.length > 1} + + {/if} + {#if sectionModule} + + {/if} + {@render children()} +
    +
    + + {#if data.user} + + {/if} + +
    +{/if} diff --git a/src/routes/brand/+page.svelte b/src/routes/brand/+page.svelte new file mode 100644 index 00000000..2c8d2af8 --- /dev/null +++ b/src/routes/brand/+page.svelte @@ -0,0 +1,2188 @@ + + + + Brand · GitOps + + + +{#snippet sectionTitle(id: string, title: string, desc: string, uso: string[] = [])} +
    +

    {title}

    +

    {desc}

    + {#if uso.length} +
    + {#each uso as u} + {u} + {/each} +
    + {/if} +
    +{/snippet} + +
    + +
    + + GitOps + + + + + +
    + + + + + {#snippet trigger(props)} + + {/snippet} + +
    +

    Notificaciones

    + +
    +
    + +
    +
      + {#each notifVisibles as n (n.id)} +
    • + +
    • + {:else} +
    • + +

      Estás al día

      +

      No tienes notificaciones sin leer.

      +
    • + {/each} +
    +
    + Ver todas + +
    +
    + + + + {#snippet trigger(props)} + + {/snippet} +
    +

    Carlos López

    +

    GitOps Admin

    +
    + + Perfil + Ajustes de GitOps + + Cerrar sesión +
    +
    +
    + +
    + + + +
    + +
    +
    +
    +
    + 🦊 Kettu × GitOps · UI v3 +

    + Un sistema visual para + GitOps +

    +

    + Base del rediseño, heredada de la paleta de kettu.studio: fondo ink, acento naranja + zorro y tarjetas con borde sutil. Itera aquí antes de llevarlo a las pantallas. +

    + +
    +
    + +
    + +
    + {@render sectionTitle( + 'logo', + 'Logo', + 'La misma idea de siempre, Git y Ops como dos círculos que se solapan, ahora con la paleta Kettu: Git en neutro, Ops en naranja zorro y la intersección en brand-700. Wordmark en Inter Bold, convertido a trazados.', + )} + +
    +
    +
    + GitOps, versión para fondo oscuro +
    +
    + Fondo oscuro · uso principal + SVG +
    +
    +
    +
    + GitOps, versión para fondo claro +
    +
    + Fondo claro · documentos, emails + SVG +
    +
    +
    + +
    +
    +

    Marca

    +

    Cuando no cabe el wordmark

    +
    + + + +
    +
    + Oscuro + Claro +
    +
    + +
    +

    Icono de app y favicon

    +

    512 · 192 · 180 (Apple) · 32

    +
    + + + + +
    +
    + SVG + PNG 512 +
    +
    + +
    +

    Colores del logo

    +

    Solo estos, sin degradados

    +
      + {#each [['Git (oscuro)', '#e7e7ea', 'fg'], ['Git (claro)', '#0a0a0d', 'ink-950'], ['Ops', '#f95d11', 'brand-500'], ['Intersección', '#ba3208', 'brand-700']] as [label, hex, token]} +
    • + + {label} + {token} · {hex} +
    • + {/each} +
    +
    +
    + +
    +
    +

    + Sí +

    +

    + Margen libre alrededor de, como mínimo, la mitad de un círculo. Tamaño mínimo: 16 px + para la marca y 80 px para el logo completo. +

    +
    +
    +

    + No +

    +

    + Cambiar los colores, añadir sombras o degradados, girarlo o deformarlo. +

    +
    +
    +

    + Ojo +

    +

    + Sobre fotos o fondos naranjas, usa el icono de app (con su cuadrado ink), no la + marca suelta. +

    +
    +
    +
    + + +
    + {@render sectionTitle( + 'paleta', + 'Paleta', + 'Pulsa un color para copiar su hex. Las utilidades Tailwind son bg-brand-500, bg-ink-900, text-fg-muted…', + )} + +
    +

    Brand · naranja zorro

    +
    + {#each brandScale as [step, hex]} + + {/each} +
    +
    + +
    +
    +

    Ink · superficies

    +
    + {#each inkScale as [step, hex, uso]} + + {/each} +
    +
    +
    +

    Texto

    +
    + {#each textTokens as [name, hex, uso]} + + {/each} +
    +
    +
    + +
    +
    +

    Estado

    +

    + Reservados: siempre con icono y texto, nunca como color de serie. +

    +
    + {#each statusTokens as [name, hex, label, Icon]} + + {/each} +
    +
    +
    +

    Series de gráficas

    +

    + Orden fijo, validado para daltonismo sobre ink-900. No ciclar: la 6.ª serie va a + “Otros”. +

    +
    + {#each seriesTokens as hex, i} + + {/each} +
    +
    +
    +
    + + +
    + {@render sectionTitle( + 'tipografia', + 'Tipografía', + 'Inter para la interfaz, JetBrains Mono para código, IDs y hashes. Titulares con tracking ajustado.', + ['.k-text-gradient', '.k-text-gradient-brand', 'font-mono'], + )} +
    + {#each [['Display · 48/700', 'text-5xl font-bold tracking-tight k-text-gradient', 'Infraestructura en Git'], ['H1 · 36/700', 'text-4xl font-bold tracking-tight text-white', 'Proyectos de la organización'], ['H2 · 24/600', 'text-2xl font-semibold tracking-tight text-white', 'Secretos del entorno prod'], ['H3 · 18/600', 'text-lg font-semibold text-white', 'Última analítica de seguridad'], ['Body · 15/400', 'text-[15px] text-fg-muted', 'Cada cambio queda registrado como un commit auditable en tu repositorio GitDB.'], ['Small · 13/400', 'text-[13px] text-fg-subtle', 'Actualizado hace 3 minutos por carlos@kettu.studio'], ['Overline · 11/600', 'text-[11px] font-semibold uppercase tracking-[0.08em] text-brand-400', 'Organización'], ['Mono · 13/400', 'font-mono text-[13px] text-fg', 'gvs_7f3a…c91e · a1b2c3d']] as [meta, cls, sample]} +
    + {meta} + {sample} +
    + {/each} +
    + Gradiente brand + Despliega sin miedo +
    +
    +
    + + +
    + {@render sectionTitle( + 'botones', + 'Botones', + 'Primario naranja para la acción principal (una por vista). Secundario para el resto; ghost en barras y tablas.', + [ + '.k-btn', + '.k-btn-primary', + '.k-btn-secondary', + '.k-btn-outline-brand', + '.k-btn-ghost', + '.k-btn-danger', + '.k-btn-sm', + '.k-btn-lg', + '.k-btn-icon', + ], + )} +
    +
    + + + + + +
    +
    +
    + + + + + + + +
    +
    +
    + + + +
    + + +
    + Enlace de texto +
    +
    +
    + + +
    + {@render sectionTitle( + 'badges', + 'Badges y estados', + 'Pastillas redondeadas con fondo al 8 % del color. Un punto o icono acompaña siempre al estado.', + [ + '.k-badge', + '.k-badge-brand', + '.k-badge-ok', + '.k-badge-warn', + '.k-badge-danger', + '.k-badge-info', + '.k-kbd', + ], + )} +
    +
    + Neutral + Nuevo + Operativo + Degradado + Caído + Beta +
    +
    + CRITICAL · 2 + HIGH · 5 + MEDIUM · 11 + LOW · 23 + + main + a1b2c3d + ⌘K +
    +
    +
    + {#each [['CL', 'from-brand-400 to-brand-700'], ['AM', 'from-sky-400 to-blue-700'], ['JR', 'from-teal-400 to-teal-700'], ['+4', '']] as [ini, grad]} + {ini} + {/each} +
    +
    + 🦊 +
    +

    Kettu Studio

    +

    3 proyectos · 8 miembros

    +
    +
    +
    +
    +
    + + +
    + {@render sectionTitle( + 'formularios', + 'Formularios', + 'Campos sobre ink-900 con foco naranja. Field pone la etiqueta, la ayuda y el error, y los enlaza por aria con el control.', + ['', ' + {/snippet} + + + {#snippet children(control)} + + {/snippet} + + + {#snippet aside()}Opcional{/snippet} + {#snippet children(control)} + + {/snippet} + +
    + + {#snippet children(control)} + + {/snippet} + +
    + + {#snippet children(control)} + + {/snippet} + +
    + +
    +
    +

    Módulos

    + {#each [['sso', 'Google SSO', 'Inicio de sesión con Google Workspace'], ['registro', 'Registro abierto', 'Cualquiera puede crear una cuenta'], ['monitoring', 'Monitoring', 'Monitores HTTP de uptime']] as [key, label, desc]} + {@const k = key as keyof typeof toggles} +
    + + +
    + {/each} +
    + + Tamaño pequeño + + Deshabilitado +
    +
    +
    +
    + Permisos + {#each ['read', 'create', 'update', 'delete'] as p, i} + + {/each} +
    +
    + Entorno + {#each [['dev', 'Desarrollo'], ['staging', 'Staging'], ['prod', 'Producción']] as [id, label]} + + {/each} +
    +
    +
    +
    +
    + + +
    + {@render sectionTitle( + 'dropdowns', + 'Dropdowns', + 'Popovers sobre ink-800. Se cierran con Esc (devolviendo el foco) o con clic fuera, y se recorren con ↑ ↓ Inicio Fin.', + ['', '', ' + + + 4 servicios +
    +
    + + + + + + + + + + + + + {#each servicios as s} + + + + + + + + + {/each} + +
    ServicioEstadoUptimep95Último deploy
    +

    {s.name}

    +

    + {s.branch} +

    +
    {estadoTexto[s.estado]}{s.uptime}{s.p95}{s.deploy}
    +
    +
    +
    + + +
    + {@render sectionTitle( + 'navegacion', + 'Navegación', + 'Tabs con subrayado naranja y control segmentado (se recorren con ← →), breadcrumbs, paginación y pasos.', + ['', ''], + )} +
    + + +
    + +
    + Panel de {tab}. Los paneles los pinta la + página; Tabs solo gestiona la selección, el teclado y los ids. +
    +
    + +
    + ({ value: p, label: p }))} + /> + +
    + + {#each [1, 2, 3, 4, 5] as n} + + {/each} + +
    +
    + +
    + {#each [['Repositorio', true], ['Organización', true], ['Administrador', false], ['Listo', false]] as [label, done], i} +
    + + + {#if done}{:else}{i + 1}{/if} + + {label} + + {#if i < 3}{/if} +
    + {/each} +
    +
    +
    + + +
    + {@render sectionTitle( + 'feedback', + 'Feedback', + 'Banners, toasts, progreso, skeletons y modal.', + ['toast.success()', 'toast.error()', ''], + )} +
    + {#each banners as { icon: Icon, title, body, box, iconCls }} +
    + +
    +

    {title}

    +

    {body}

    +
    + +
    + {/each} +
    + +
    +
    + {#each [['Cuota de almacenamiento', 68, 'bg-brand-500'], ['Cobertura de tests', 84, 'bg-ok'], ['Límite de API keys', 92, 'bg-warn']] as [label, value, color]} +
    +
    + {label}{value} % +
    +
    +
    +
    +
    + {/each} +
    + +
    + +
    + Toasts: toast.success(título, descripción) + + + + +
    +
    + + +
    + {@render sectionTitle( + 'modales', + 'Modales', + 'Fondo negro al 60 % con blur y panel sobre ink-800. Se cierran con Esc, clic fuera o Cancelar; bloquean el scroll, atrapan el foco y lo devuelven al cerrar.', + ['', '', ''], + )} +
    + {#each [{ run: openConfirm, icon: Trash, title: 'Confirmación destructiva', desc: 'role="alertdialog". Hay que escribir el nombre para habilitar el botón.', tone: 'bg-red-500/10 text-red-400' }, { run: openForm, icon: KeyRound, title: 'Formulario', desc: 'Field + validación en vivo. El submit del footer usa form="…".', tone: 'bg-brand-500/10 text-brand-400' }, { run: openDetalle, icon: MessageSquareText, title: 'Detalle grande', desc: 'Cabecera a medida con Tabs, cuerpo con scroll y pie fijo.', tone: 'bg-blue-400/10 text-blue-300' }, { run: () => (drawerOpen = true), icon: PanelRight, title: 'Drawer lateral', desc: 'Detalle sin salir de la lista.', tone: 'bg-teal-500/10 text-teal-300' }, { run: () => (paletteOpen = true), icon: Command, title: 'Búsqueda ⌘K', desc: 'Paleta de comandos con teclado.', tone: 'bg-white/6 text-fg' }] as m} + + {/each} +
    +

    + También puedes pulsar ⌘K (o + CtrlK) desde cualquier punto de la + página. +

    +
    + + +
    + {@render sectionTitle( + 'graficas', + 'Gráficas', + 'Chart.js con líneas de 2 px, rejilla casi invisible y tooltip sobre ink-800. Series en orden fijo; el estado usa sus colores reservados.', + )} + +
    + + +
    + {@render sectionTitle( + 'sidebar', + 'Sidebar', + 'Propuesta para la navegación de la app: selector de contexto arriba, secciones agrupadas y modo colapsado.', + ['.k-nav-item', '.k-nav-heading', 'aria-current="page"'], + )} +
    +
    + + +
    + +
    +

    Dashboard

    +
    + +
    +
    +
    + {#each [['Secretos', '24'], ['Stacks', '6'], ['Monitores', '9']] as [l, v]} +
    +

    {l}

    +

    {v}

    +
    + {/each} +
    +
    + +
    +
    +
    +
    +
    +
    + +
    + Hecho con 🦊 por Kettu Studio · tokens en src/lib/styles/brand.css +
    + +
    + + + + + + {#snippet icon()} + + {/snippet} + + {#snippet children(control)} + + {/snippet} + + {#snippet footer()} + + + {/snippet} + + + + +
    + + {#snippet children(control)} + + {/snippet} + + + {#snippet children(control)} +
    + + +
    + {/snippet} +
    +
    +

    Entorno

    +
    + {#each [['dev', 'Desarrollo'], ['staging', 'Staging'], ['prod', 'Producción']] as [id, label]} + + {/each} +
    +
    + {#if secretEnv === 'prod'} +
    + Los cambios en producción + notifican a los administradores del proyecto. +
    + {/if} +
    + {#snippet footer()} + + + + {/snippet} +
    + + + + {#snippet header(titleId)} +
    +
    +
    +
    + CRITICAL + CVE-2026-31337 +
    +

    + Prototype pollution en lodash +

    +

    billing-worker · lodash 4.17.20 → 4.17.21

    +
    + +
    +
    + +
    +
    + {/snippet} + +
    + {#if detalleTab === 'descripcion'} +
    +

    + Las funciones merge, + mergeWith + y + defaultsDeep permiten modificar + Object.prototype con una entrada manipulada, lo que + puede derivar en ejecución de código o denegación de servicio. +

    +
    + {#each [['CVSS', '9.1'], ['Exploit', 'Público'], ['Fix', 'Disponible']] as [k, v]} +
    +

    {k}

    +

    {v}

    +
    + {/each} +
    +

    + Cómo corregirlo +

    +
    # package.json
    +-  "lodash": "4.17.20"
    ++  "lodash": "^4.17.21"
    +
    +$ bun install && bun run test
    + {#each Array(4) as _, i} +

    + Párrafo de relleno {i + 1} para comprobar el scroll del cuerpo: la cabecera con las tabs + y el pie con las acciones se quedan fijos mientras el contenido se desplaza. +

    + {/each} +
    + {:else if detalleTab === 'afectados'} +
      + {#each [['billing-worker', 'release/1.4'], ['checkout-api', 'main'], ['legacy-cron', 'develop']] as [svc, br]} +
    • + {svc}{br} +
    • + {/each} +
    + {:else} +
      + {#each [['Detectada por Open Report', 'hace 25 min'], ['Alerta enviada a 3 personas', 'hace 24 min'], ['Asignada a Carlos López', 'hace 10 min']] as [t, when]} +
    1. + +

      {t}

      +

      {when}

      +
    2. + {/each} +
    + {/if} +
    + + {#snippet footer()} + Ver en NVD + + + {/snippet} +
    + + + +
    +
    + Caído + desde hace 2 min · 3 checks fallidos +
    +
    + {#each [['Uptime 30 d', '99,41 %'], ['p95', '640 ms'], ['Intervalo', '60 s'], ['Timeout', '10 s']] as [k, v]} +
    +

    {k}

    +

    {v}

    +
    + {/each} +
    +
    +

    + Últimos checks +

    +
      + {#each [['503', 'Service Unavailable', 'danger', '12:04:01'], ['503', 'Service Unavailable', 'danger', '12:03:01'], ['504', 'Gateway Timeout', 'danger', '12:02:01'], ['200', 'OK · 212 ms', 'ok', '12:01:01']] as [code, text, tone, at]} +
    • + + {code} + {text} + {at} +
    • + {/each} +
    +
    +
    + {#snippet footer()} + + + {/snippet} +
    + + + +
    diff --git a/src/routes/brand/BrandCharts.svelte b/src/routes/brand/BrandCharts.svelte new file mode 100644 index 00000000..243b7801 --- /dev/null +++ b/src/routes/brand/BrandCharts.svelte @@ -0,0 +1,226 @@ + + +
    +
    +
    +
    +

    Tiempo de respuesta

    +

    api.kettu.studio · últimas 24 h

    +
    +
    + p50 + p95 + +
    +
    +
    + +
    + {#if showTable} +
    + + + + + + {#each hours as h, i} + + {/each} + +
    Horap50p95
    {h}{p50[i]} ms{p95[i]} ms
    +
    + {/if} +
    + +
    +

    Despliegues por día

    +

    Esta semana · 120 en total

    +
    + +
    +
    + +
    +
    +
    +

    Uptime · 90 días

    +

    Monitor HTTP · checkout-api

    +
    + 99,92 % +
    +
    + {#each uptime as estado, i} +
    + +
    + {/each} +
    +
    + Hace 90 díasHoy +
    +
    +
    diff --git a/src/routes/org/[org]/cves/+page.server.ts b/src/routes/org/[org]/cves/+page.server.ts index d16c400c..b399dc8b 100644 --- a/src/routes/org/[org]/cves/+page.server.ts +++ b/src/routes/org/[org]/cves/+page.server.ts @@ -1,46 +1,18 @@ -import { error } from '@sveltejs/kit'; -import { cancanService } from '#modules/auth'; -import { codeReportCveService } from '#modules/code-report'; -import { projectService } from '#modules/projects'; -import { summarizeCves } from '#lib/code-report/cve-aggregation'; +import { + buildCveList, + loadCveOccurrences, + organizationCveProjects, +} from '#lib/server/code-report/cves'; export async function load({ parent, locals, url }) { const { organization } = await parent(); - - const canRead = await cancanService.canSessionUser(locals.user, 'organization:projects:read', { - scope: 'organization', - organizationId: organization.id, - }); - - if (!canRead) { - throw error(403, 'Forbidden'); - } - - const projects = (await projectService.listProjectsByOrganization(organization.id)).filter( - (project) => project.status === 'active' && project.modules?.codereport, - ); - - const occurrencesByCve = await codeReportCveService.getOrganizationCveOccurrences( - projects.map((project) => ({ - id: project.id, - slug: project.slug ?? '', - name: project.name, - })), - ); - - const cves = summarizeCves( - new Map([...occurrencesByCve.entries()].map(([id, occurrences]) => [id, occurrences])), - ).map((cve) => ({ - ...cve, - projectSlugs: [ - ...new Set((occurrencesByCve.get(cve.id) ?? []).map((entry) => entry.projectSlug)), - ], - })); + const projects = await organizationCveProjects(organization.id, locals.user); + const occurrences = await loadCveOccurrences(projects); return { - orgSlug: organization.slug, - cves, - projects: projects.map((project) => ({ slug: project.slug, name: project.name })), - initialProjectFilter: url.searchParams.get('project') ?? 'all', + orgSlug: organization.slug as string, + cves: buildCveList(occurrences), + projects: projects.map(({ slug, name }) => ({ slug, name })), + initialProject: url.searchParams.get('project') ?? 'all', }; } diff --git a/src/routes/org/[org]/cves/+page.svelte b/src/routes/org/[org]/cves/+page.svelte index bf27e950..7d909e85 100644 --- a/src/routes/org/[org]/cves/+page.svelte +++ b/src/routes/org/[org]/cves/+page.svelte @@ -1,35 +1,34 @@ {$_('org.cves.title')} - GitOps - +
    +
    +

    {$_('org.cves.title')}

    +

    {$_('org.cves.infoMessage')}

    +
    + + `/org/${data.orgSlug}/cves/${encodeURIComponent(id)}`} + projects={data.projects} + initialProject={data.initialProject} + emptyMessage={$_('org.cves.emptyMessage')} + /> +
    diff --git a/src/routes/org/[org]/cves/[cve]/+page.server.ts b/src/routes/org/[org]/cves/[cve]/+page.server.ts index 8368af6b..eff52b46 100644 --- a/src/routes/org/[org]/cves/[cve]/+page.server.ts +++ b/src/routes/org/[org]/cves/[cve]/+page.server.ts @@ -1,99 +1,16 @@ import { error } from '@sveltejs/kit'; -import { cancanService } from '#modules/auth'; -import { codeReportCveService } from '#modules/code-report'; -import { projectService } from '#modules/projects'; import { - highestCvssScore, - highestEpssPercentile, - highestEpssScore, - highestSeverity, -} from '#lib/code-report/cve-aggregation'; + buildCveDetail, + loadCveOccurrences, + organizationCveProjects, +} from '#lib/server/code-report/cves'; export async function load({ parent, locals, params }) { const { organization } = await parent(); + const projects = await organizationCveProjects(organization.id, locals.user); - const canRead = await cancanService.canSessionUser(locals.user, 'organization:projects:read', { - scope: 'organization', - organizationId: organization.id, - }); + const occurrences = (await loadCveOccurrences(projects)).get(params.cve); + if (!occurrences?.length) throw error(404, 'CVE not found'); - if (!canRead) { - throw error(403, 'Forbidden'); - } - - const projects = (await projectService.listProjectsByOrganization(organization.id)).filter( - (project) => project.status === 'active' && project.modules?.codereport, - ); - - const occurrencesByCve = await codeReportCveService.getOrganizationCveOccurrences( - projects.map((project) => ({ - id: project.id, - slug: project.slug ?? '', - name: project.name, - })), - ); - - const occurrences = occurrencesByCve.get(params.cve); - - if (!occurrences || occurrences.length === 0) { - throw error(404, 'CVE not found'); - } - - const first = occurrences[0].finding; - const publishedDate = - occurrences.map((occurrence) => occurrence.finding.publishedDate).find(Boolean) ?? null; - const lastModifiedDate = - occurrences.map((occurrence) => occurrence.finding.lastModifiedDate).find(Boolean) ?? null; - - const cve = { - id: params.cve, - title: first.title, - description: first.description, - severity: highestSeverity(occurrences), - cvssScore: highestCvssScore(occurrences), - epssScore: highestEpssScore(occurrences), - epssPercentile: highestEpssPercentile(occurrences), - primaryUrl: first.primaryUrl, - cveUrl: first.cveUrl, - cweIds: first.cweIds, - references: [...new Set(occurrences.flatMap((occurrence) => occurrence.finding.references))], - publishedDate, - lastModifiedDate, - }; - - const remediations = [ - ...new Map( - occurrences.map((occurrence) => [ - `${occurrence.projectSlug}:${occurrence.finding.packageName}`, - { - packageName: occurrence.finding.packageName, - installedVersion: occurrence.finding.installedVersion, - fixedVersion: occurrence.finding.fixedVersion, - status: occurrence.finding.status, - }, - ]), - ).values(), - ]; - - const affectedServices = occurrences.map((occurrence) => ({ - serviceId: occurrence.serviceId, - serviceSlug: occurrence.serviceSlug, - serviceName: occurrence.serviceName, - projectName: occurrence.projectName, - projectSlug: occurrence.projectSlug, - packageName: occurrence.finding.packageName, - installedVersion: occurrence.finding.installedVersion, - fixedVersion: occurrence.finding.fixedVersion, - target: occurrence.finding.target, - severity: occurrence.finding.severity, - status: occurrence.finding.status, - scannedAt: occurrence.scannedAt, - })); - - return { - orgSlug: organization.slug, - cve, - remediations, - affectedServices, - }; + return { orgSlug: organization.slug as string, ...buildCveDetail(params.cve, occurrences) }; } diff --git a/src/routes/org/[org]/cves/[cve]/+page.svelte b/src/routes/org/[org]/cves/[cve]/+page.svelte index 9f0423a8..bf10e0a4 100644 --- a/src/routes/org/[org]/cves/[cve]/+page.svelte +++ b/src/routes/org/[org]/cves/[cve]/+page.svelte @@ -1,58 +1,32 @@ - {data.cve.id} - Organization CVEs - GitOps + {data.cve.id} - CVEs - GitOps + `/org/${data.orgSlug}/projects/${service.projectSlug}/code-report/services/${service.serviceSlug}`} /> diff --git a/src/routes/org/[org]/overview/+page.server.ts b/src/routes/org/[org]/overview/+page.server.ts index 95e39de1..55963fef 100644 --- a/src/routes/org/[org]/overview/+page.server.ts +++ b/src/routes/org/[org]/overview/+page.server.ts @@ -1,6 +1,148 @@ import { error } from '@sveltejs/kit'; +import { cancanService, userAccessService } from '#modules/auth'; +import { alertService } from '#modules/alerts'; import { projectService } from '#modules/projects'; -import { cancanService } from '#modules/auth'; +import { eventLog } from '#lib/server/events'; +import { + HEALTH_THRESHOLDS, + codeReportHealth, + keyHealth, + monitoringHealth, + vaultHealth, + type CodeReportHealth, + type KeyHealth, + type MonitoringHealth, + type VaultHealth, +} from '#lib/server/dashboard/project-health'; +import { createEventVisibility } from '../settings/events/event-view'; + +/** + * Dashboard de la organización: estado de todos sus proyectos y lo que hay que revisar. + * Cada métrica de un proyecto se calcula solo si el producto está activo y el usuario puede + * leerlo en ese proyecto; un fallo en una no tumba el resto. Al cliente solo llegan conteos. + */ + +type Project = { + id: string; + slug: string | null; + name: string; + description?: string | null; + status: string; + modules?: { vault?: boolean; codereport?: boolean; monitoring?: boolean }; +}; + +export type AttentionSeverity = 'critical' | 'warning' | 'info'; + +export type AttentionKind = + | 'monitorsDown' + | 'exposedSecrets' + | 'criticalVulns' + | 'keysExpired' + | 'monitorsDegraded' + | 'keysExpiring' + | 'keysNotRotated' + | 'keysNoExpiry' + | 'keysUnused' + | 'staleScans' + | 'vaultMissing' + | 'vaultStale' + | 'invitedUsers' + | 'pendingEvents'; + +export type AttentionItem = { + severity: AttentionSeverity; + kind: AttentionKind; + count: number; + project: { slug: string; name: string } | null; + href: string; + /** Nombres concretos (monitores, claves) para dar contexto; nunca secretos. */ + names?: string[]; +}; + +export type ProjectHealthStatus = 'critical' | 'warning' | 'ok' | 'unknown'; + +const PENDING_EVENTS_SCAN = 500; + +async function safely( + logger: App.Locals['logger'] | undefined, + label: string, + task: () => Promise, +): Promise { + try { + return await task(); + } catch (err) { + logger?.error({ err }, `organization dashboard: ${label} failed`); + return null; + } +} + +function attentionFor( + project: { slug: string; name: string }, + base: string, + health: { + codeReport: CodeReportHealth | null; + monitoring: MonitoringHealth | null; + vault: VaultHealth | null; + keys: KeyHealth | null; + }, +): AttentionItem[] { + const items: AttentionItem[] = []; + const push = ( + severity: AttentionSeverity, + kind: AttentionKind, + count: number, + href: string, + names?: string[], + ) => { + if (count > 0) items.push({ severity, kind, count, project, href, names }); + }; + const { codeReport, monitoring, vault, keys } = health; + + if (monitoring) { + const down = monitoring.failing.filter((monitor) => monitor.status === 'down'); + const degraded = monitoring.failing.filter((monitor) => monitor.status === 'degraded'); + push( + 'critical', + 'monitorsDown', + down.length, + `${base}/monitoring/monitors`, + down.map((m) => m.name), + ); + push( + 'warning', + 'monitorsDegraded', + degraded.length, + `${base}/monitoring/monitors`, + degraded.map((m) => m.name), + ); + } + if (codeReport) { + push('critical', 'exposedSecrets', codeReport.exposedSecrets, `${base}/code-report/services`); + push('critical', 'criticalVulns', codeReport.totals.critical, `${base}/code-report/dashboard`); + push('warning', 'staleScans', codeReport.staleServices, `${base}/code-report/services`); + } + if (keys) { + const keysHref = `${base}/settings/server-access-keys`; + const named = (risk: keyof KeyHealth['counts']) => + keys.atRisk.filter((key) => key.risks.includes(risk)).map((key) => key.name); + push('critical', 'keysExpired', keys.counts.expired, keysHref, named('expired')); + push('warning', 'keysExpiring', keys.counts.expiring, keysHref, named('expiring')); + push('warning', 'keysNotRotated', keys.counts.notRotated, keysHref, named('notRotated')); + push('info', 'keysNoExpiry', keys.counts.noExpiry, keysHref, named('noExpiry')); + push('info', 'keysUnused', keys.counts.unused, keysHref, named('unused')); + } + if (vault) { + push('warning', 'vaultMissing', vault.missingValues, `${base}/vault`); + push('info', 'vaultStale', vault.staleSecrets, `${base}/vault`); + } + return items; +} + +function statusOf(items: AttentionItem[], hasData: boolean): ProjectHealthStatus { + if (items.some((item) => item.severity === 'critical')) return 'critical'; + if (items.some((item) => item.severity === 'warning')) return 'warning'; + return hasData ? 'ok' : 'unknown'; +} export async function load({ locals, parent }) { const { organization } = await parent(); @@ -9,8 +151,200 @@ export async function load({ locals, parent }) { throw error(403, 'Forbidden'); } - const projects = await projectService.listProjectsByOrganization(organization.id); - const activeProjects = projects.filter((project) => project.status === 'active'); + const logger = locals.logger; + const orgScope = { scope: 'organization' as const, organizationId: organization.id }; + const canOrg = (permission: string) => + cancanService.canSessionUser(locals.user, permission, orgScope); + + const [allProjects, canReadUsers, canReadEvents, canReadAlerts] = await Promise.all([ + projectService.listProjectsByOrganization(organization.id) as Promise, + canOrg('organization:users:read'), + canOrg('organization:events:read'), + canOrg('organization:alerts:read'), + ]); + const activeProjects = allProjects.filter((project) => project.status === 'active'); + const orgBase = `/org/${organization.slug}`; + + const projects = await Promise.all( + activeProjects.map(async (project) => { + const slug = project.slug ?? project.id; + const base = `${orgBase}/projects/${slug}`; + const modules = project.modules ?? {}; + const scope = { + scope: 'project' as const, + projectId: project.id, + organizationId: organization.id, + }; + const can = (permission: string) => + cancanService.canSessionUser(locals.user, permission, scope); + + const [canCodeReport, canMonitoring, canVault, canKeys] = await Promise.all([ + modules.codereport ? can('project:codereport:reports:read') : false, + modules.monitoring ? can('project:monitoring:monitors:read') : false, + modules.vault ? can('project:vault:secrets:read') : false, + can('project:server-keys:read'), + ]); + + const [codeReport, monitoring, vault, keys] = await Promise.all([ + canCodeReport ? safely(logger, 'code report', () => codeReportHealth(project.id)) : null, + canMonitoring ? safely(logger, 'monitoring', () => monitoringHealth(project.id)) : null, + canVault ? safely(logger, 'vault', () => vaultHealth(project.id)) : null, + canKeys ? safely(logger, 'keys', () => keyHealth(project.id)) : null, + ]); + + const attention = attentionFor({ slug, name: project.name }, base, { + codeReport, + monitoring, + vault, + keys, + }); + + return { + id: project.id, + slug, + name: project.name, + description: project.description ?? null, + modules: { + codereport: Boolean(modules.codereport), + vault: Boolean(modules.vault), + monitoring: Boolean(modules.monitoring), + }, + status: statusOf(attention, Boolean(codeReport || monitoring || vault || keys)), + issues: { + critical: attention.filter((item) => item.severity === 'critical').length, + warning: attention.filter((item) => item.severity === 'warning').length, + }, + codeReport: codeReport && { + score: codeReport.score, + critical: codeReport.totals.critical, + high: codeReport.totals.high, + services: codeReport.services, + scanned: codeReport.scanned, + exposedSecrets: codeReport.exposedSecrets, + lastScanAt: codeReport.lastScanAt, + }, + monitoring: monitoring && { + total: monitoring.total, + up: monitoring.up, + down: monitoring.down, + degraded: monitoring.degraded, + uptime24h: monitoring.uptime24h, + }, + vault: vault && { secrets: vault.secrets, missingValues: vault.missingValues }, + keys: keys && { active: keys.active, atRisk: keys.atRisk.length }, + attention, + }; + }), + ); + + // nivel organización + const [users, pendingEvents, alerts] = await Promise.all([ + canReadUsers + ? safely(logger, 'users', async () => { + const rows = await userAccessService.listUsers('organization', organization.id); + return { + total: rows.length, + active: rows.filter((row) => row.status === 'active' && !row.disabled).length, + invited: rows.filter((row) => row.status === 'invited').length, + disabled: rows.filter((row) => row.disabled).length, + }; + }) + : null, + canReadEvents + ? safely(logger, 'events', async () => { + const isVisible = createEventVisibility(organization.id, (permission, context) => + cancanService.canSessionUser(locals.user, permission, context), + ); + const candidates = eventLog.list({ + organizationId: organization.id, + acked: false, + limit: PENDING_EVENTS_SCAN, + }); + let count = 0; + for (const entry of candidates) if (await isVisible(entry)) count += 1; + return count; + }) + : null, + canReadAlerts + ? safely(logger, 'alerts', async () => { + const list = await alertService.list({ + organizationId: organization.id, + projectId: null, + }); + return { total: list.length, enabled: list.filter((alert) => alert.enabled).length }; + }) + : null, + ]); + + const orgAttention: AttentionItem[] = []; + if (users?.invited) { + orgAttention.push({ + severity: 'info', + kind: 'invitedUsers', + count: users.invited, + project: null, + href: `${orgBase}/settings/access-control`, + }); + } + if (pendingEvents) { + orgAttention.push({ + severity: 'info', + kind: 'pendingEvents', + count: pendingEvents, + project: null, + href: `${orgBase}/settings/events?status=pending`, + }); + } + + const severityRank: Record = { critical: 0, warning: 1, info: 2 }; + const attention = [...projects.flatMap((project) => project.attention), ...orgAttention].sort( + (left, right) => + severityRank[left.severity] - severityRank[right.severity] || right.count - left.count, + ); + + const sum = (pick: (project: (typeof projects)[number]) => number | null | undefined) => + projects.reduce((total, project) => total + (pick(project) ?? 0), 0); + const scores = projects + .map((project) => project.codeReport?.score) + .filter((score): score is number => typeof score === 'number'); + const uptimes = projects + .map((project) => project.monitoring?.uptime24h) + .filter((value): value is number => typeof value === 'number'); - return { projects: activeProjects }; + return { + dashboard: { + generatedAt: new Date().toISOString(), + thresholds: HEALTH_THRESHOLDS, + projects: projects.map(({ attention: _attention, ...project }) => project), + archivedProjects: allProjects.length - activeProjects.length, + attention, + users, + alerts, + pendingEvents, + totals: { + securityScore: scores.length + ? Math.round(scores.reduce((total, score) => total + score, 0) / scores.length) + : null, + critical: sum((project) => project.codeReport?.critical), + high: sum((project) => project.codeReport?.high), + exposedSecrets: sum((project) => project.codeReport?.exposedSecrets), + services: sum((project) => project.codeReport?.services), + monitors: sum((project) => project.monitoring?.total), + monitorsUp: sum((project) => project.monitoring?.up), + monitorsFailing: sum( + (project) => (project.monitoring?.down ?? 0) + (project.monitoring?.degraded ?? 0), + ), + uptime24h: uptimes.length + ? uptimes.reduce((total, value) => total + value, 0) / uptimes.length + : null, + secrets: sum((project) => project.vault?.secrets), + keys: sum((project) => project.keys?.active), + keysAtRisk: sum((project) => project.keys?.atRisk), + }, + can: { + createProject: await canOrg('organization:projects:create'), + manageUsers: canReadUsers, + }, + }, + }; } diff --git a/src/routes/org/[org]/overview/+page.svelte b/src/routes/org/[org]/overview/+page.svelte index a65de462..464ffd51 100644 --- a/src/routes/org/[org]/overview/+page.svelte +++ b/src/routes/org/[org]/overview/+page.svelte @@ -1,186 +1,778 @@ - {$_('org.overview.title')} - GitOps + {$_('org.dashboard.title')} - GitOps
    -
    -

    {$_('org.overview.title')}

    -

    {$_('org.overview.welcome')}

    -
    +
    +
    +

    + {data.organization.name ?? $_('org.dashboard.title')} +

    +

    {$_('org.dashboard.subtitle')}

    +
    +

    + + {$_('org.dashboard.updatedAt', { values: { time: formatTime(dashboard.generatedAt) } })} +

    +
    -
    - {#each guides as guide (guide.label)} - +
    + + +

    + {$_('org.dashboard.kpi.projects')} +

    +

    + {dashboard.projects.length} +

    +
    + {#if dashboard.projects.length > 0} + + {/if} +

    + {$_('org.dashboard.kpi.projectsDetail', { + values: { + critical: statusCounts.critical, + warning: statusCounts.warning, + ok: statusCounts.ok, + }, + })} +

    +
    +
    + + +
    +

    + {$_('org.dashboard.kpi.security')} +

    +

    + {totals.securityScore ?? '—'} + {#if totals.securityScore !== null}/100{/if} +

    +

    + 0 ? 'font-medium text-red-400' : ''} + >{$_('org.dashboard.kpi.criticalCount', { values: { count: totals.critical } })} + · {$_('org.dashboard.kpi.highCount', { values: { count: totals.high } })} +

    +
    + + +
    +

    + {$_('org.dashboard.kpi.uptime')} +

    +

    -

    +

    + {#if totals.monitors === 0} + {$_('org.dashboard.kpi.noMonitors')} + {:else} + 0 ? 'font-medium text-red-400' : ''} + >{$_('org.dashboard.kpi.monitorsFailing', { + values: { count: totals.monitorsFailing }, + })} + · {$_('org.dashboard.kpi.monitorsTotal', { values: { count: totals.monitors } })} + {/if} +

    +
    + + + +

    + {$_('org.dashboard.kpi.users')} +

    + {#if dashboard.users} +

    + {dashboard.users.total} +

    +

    + {$_('org.dashboard.kpi.usersDetail', { + values: { active: dashboard.users.active, invited: dashboard.users.invited }, + })} + {#if dashboard.users.disabled > 0} + · {$_('org.dashboard.kpi.usersDisabled', { + values: { count: dashboard.users.disabled }, + })} + {/if} +

    + {:else} +

    —

    +

    {$_('org.dashboard.noAccess')}

    + {/if} +
    + + +
    +

    + {$_('org.dashboard.kpi.keys')} +

    +

    + {totals.keysAtRisk} - + {$_('org.dashboard.kpi.keysAtRiskOf', { values: { count: totals.keys } })} +

    +

    + {$_('org.dashboard.kpi.secrets', { values: { count: formatNumber(totals.secrets) } })} +

    +
    +
    + +
    + +
    +
    +
    +

    + {$_('org.dashboard.attention.title')} +

    +

    {$_('org.dashboard.attention.description')}

    +
    + {#if dashboard.attention.length > 0} +
    + {#each ['critical', 'warning', 'info'] as const as severity (severity)} + {#if attentionCounts[severity] > 0} + {@const style = severityStyle[severity]} + + {attentionCounts[severity]} + {$_(`org.dashboard.severity.${severity}`)} + + {/if} + {/each} +
    + {/if} +
    + + {#if dashboard.attention.length === 0} +
    + + + +

    {$_('org.dashboard.attention.emptyTitle')}

    +

    + {$_('org.dashboard.attention.emptyDescription')} +

    -
    -
    -

    {guide.label}

    - {#if !guide.href} + {:else} +
      + {#each visibleAttention as item, index (`${item.kind}-${item.project?.slug ?? 'org'}-${index}`)} + {@const style = severityStyle[item.severity]} +
    • + + + +
      + + {$_(`org.dashboard.attention.kinds.${item.kind}.title`)} + +

      + {#if item.project} + {item.project.name} · + {/if} + {#if item.names?.length} + {item.names.slice(0, 3).join(', ')}{#if item.names.length > 3} +{item.names.length - 3}{/if} + {:else} + {$_(`org.dashboard.attention.kinds.${item.kind}.description`, { + values: { days: attentionDays(item.kind) }, + })} + {/if} +

      +
      {formatNumber(item.count)} - {$_('org.overview.comingSoon')} - - {/if} + +
    • + {/each} +
    + {#if dashboard.attention.length > ATTENTION_PREVIEW} +
    +
    -

    {guide.description}

    -
    - {#if guide.href} - {/if} - - {/each} -
    - -
    -

    {$_('org.overview.projectsTitle')}

    -

    {$_('org.overview.projectsDescription')}

    -
    + {/if} +
    -
    - - -
    +
    + +
    +

    + {$_('org.dashboard.keys.title')} +

    +

    + {$_('org.dashboard.keys.description', { + values: { days: dashboard.thresholds.keyRotationDays }, + })} +

    + {#if totals.keys === 0} +

    {$_('org.dashboard.keys.empty')}

    + {:else} +
      + {#each keyRisks as risk (risk.kind)} +
    • +
      + 0 ? 'text-fg' : 'text-fg-subtle'} + >{$_(`org.dashboard.attention.kinds.${risk.kind}.title`)} + {risk.count} +
      +
      +
      +
      +
    • + {/each} +
    + {/if} +
    - {#if filteredProjects.length === 0} -
    - {data.projects.length === 0 ? $_('org.overview.noActiveProjects') : $_('org.overview.noProjectMatches')} -
    - {:else} -
    - {#each filteredProjects as project (project.id)} + +
    + {#if dashboard.pendingEvents !== null} + + + + + + {$_('org.dashboard.pendingEvents')} + {$_('org.dashboard.pendingEventsDescription')} + + {dashboard.pendingEvents} + + {/if} + {#if dashboard.alerts} + + + + + + {$_('org.dashboard.alerts')} + {$_('org.dashboard.alertsDescription', { + values: { total: dashboard.alerts.total }, + })} + + {dashboard.alerts.enabled} + + {/if} + {#if dashboard.users && dashboard.users.invited > 0} + + + + + + {$_('org.dashboard.attention.kinds.invitedUsers.title')} + {$_('org.dashboard.attention.kinds.invitedUsers.description')} + + {dashboard.users.invited} + + {/if} -
    -
    - -

    {project.name}

    -
    - {#if project.description} -

    {project.description}

    - {/if} -
    + + + + + {$_('org.dashboard.cves')} + {$_('org.dashboard.cvesDescription')} + + +
    +
    +
    +
    -
    - - {$_('common.active')} - - +
    +
    +
    +

    + {$_('org.dashboard.projects.title')} +

    +

    + {$_('org.dashboard.projects.description')} + {#if dashboard.archivedProjects > 0} + · {$_('org.dashboard.projects.archived', { + values: { count: dashboard.archivedProjects }, + })} + {/if} +

    +
    + {#if dashboard.projects.length > 0} +
    +
    + +
    - - {/each} -
    - {/if} + (projectFilter = value as typeof projectFilter)} + items={[ + { + value: 'all', + label: $_('org.dashboard.projects.all'), + count: dashboard.projects.length, + }, + { + value: 'critical', + label: $_('org.dashboard.status.critical'), + count: statusCounts.critical, + }, + { + value: 'warning', + label: $_('org.dashboard.status.warning'), + count: statusCounts.warning, + }, + { value: 'ok', label: $_('org.dashboard.status.ok'), count: statusCounts.ok }, + ]} + /> +
    + {/if} +
    + + {#if dashboard.projects.length === 0} +
    + + + +

    {$_('org.overview.noActiveProjects')}

    + {#if dashboard.can.createProject} + {$_('orgSettings.projects.new')} + {/if} +
    + {:else if filteredProjects.length === 0} +
    + {$_('org.overview.noProjectMatches')} +
    + {:else} + + {/if} +
    diff --git a/src/routes/org/[org]/projects/[slug]/+layout.svelte b/src/routes/org/[org]/projects/[slug]/+layout.svelte index d6abc18a..ab892a64 100644 --- a/src/routes/org/[org]/projects/[slug]/+layout.svelte +++ b/src/routes/org/[org]/projects/[slug]/+layout.svelte @@ -1,108 +1,10 @@ + -
    -
    -
    - - {project.name} - - - {currentTab.label} -
    - -

    {currentTab.subtitle}

    -
    - - +
    + {@render children()}
    diff --git a/src/routes/org/[org]/projects/[slug]/+page.server.ts b/src/routes/org/[org]/projects/[slug]/+page.server.ts index a4cc12a7..a50b6acc 100644 --- a/src/routes/org/[org]/projects/[slug]/+page.server.ts +++ b/src/routes/org/[org]/projects/[slug]/+page.server.ts @@ -1,5 +1,5 @@ import { redirect } from '@sveltejs/kit'; export function load({ params }) { - throw redirect(302, `/org/${params.org}/projects/${params.slug}/settings/overview`); + throw redirect(302, `/org/${params.org}/projects/${params.slug}/overview`); } diff --git a/src/routes/org/[org]/projects/[slug]/code-report/+layout.svelte b/src/routes/org/[org]/projects/[slug]/code-report/+layout.svelte index 98e64f51..4fc25737 100644 --- a/src/routes/org/[org]/projects/[slug]/code-report/+layout.svelte +++ b/src/routes/org/[org]/projects/[slug]/code-report/+layout.svelte @@ -1,21 +1,9 @@
    - - + {@render children()}
    diff --git a/src/routes/org/[org]/projects/[slug]/code-report/cves/+page.server.ts b/src/routes/org/[org]/projects/[slug]/code-report/cves/+page.server.ts index 8e0c3164..dbcb51bd 100644 --- a/src/routes/org/[org]/projects/[slug]/code-report/cves/+page.server.ts +++ b/src/routes/org/[org]/projects/[slug]/code-report/cves/+page.server.ts @@ -1,5 +1,15 @@ -import { redirect } from '@sveltejs/kit'; +import { + buildCveList, + loadCveOccurrences, + requireProjectCveAccess, +} from '#lib/server/code-report/cves'; -export async function load({ params }) { - throw redirect(307, `/org/${params.org}/cves`); +export async function load({ parent, locals }) { + const { project } = await parent(); + await requireProjectCveAccess(project, locals.user); + + const occurrences = await loadCveOccurrences([ + { id: project.id, slug: project.slug ?? '', name: project.name }, + ]); + return { cves: buildCveList(occurrences) }; } diff --git a/src/routes/org/[org]/projects/[slug]/code-report/cves/+page.svelte b/src/routes/org/[org]/projects/[slug]/code-report/cves/+page.svelte index 1896b78a..fd43530c 100644 --- a/src/routes/org/[org]/projects/[slug]/code-report/cves/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/code-report/cves/+page.svelte @@ -1,32 +1,35 @@ - {$_('codeReport.cves.title')} - GitOps + CVEs - Code Report - GitOps - +
    +
    +

    CVEs del proyecto

    +

    + Vulnerabilidades conocidas en el último análisis de cada servicio, agrupadas por CVE. +

    +
    + + `${base}/${encodeURIComponent(id)}`} + emptyMessage="Ningún servicio del proyecto tiene CVEs en su último análisis de vulnerabilidades." + /> +
    diff --git a/src/routes/org/[org]/projects/[slug]/code-report/cves/[cve]/+page.server.ts b/src/routes/org/[org]/projects/[slug]/code-report/cves/[cve]/+page.server.ts index cf9d563c..8761b6dd 100644 --- a/src/routes/org/[org]/projects/[slug]/code-report/cves/[cve]/+page.server.ts +++ b/src/routes/org/[org]/projects/[slug]/code-report/cves/[cve]/+page.server.ts @@ -1,5 +1,18 @@ -import { redirect } from '@sveltejs/kit'; +import { error } from '@sveltejs/kit'; +import { + buildCveDetail, + loadCveOccurrences, + requireProjectCveAccess, +} from '#lib/server/code-report/cves'; -export async function load({ params }) { - throw redirect(307, `/org/${params.org}/cves/${params.cve}`); +export async function load({ parent, locals, params }) { + const { project } = await parent(); + await requireProjectCveAccess(project, locals.user); + + const occurrences = ( + await loadCveOccurrences([{ id: project.id, slug: project.slug ?? '', name: project.name }]) + ).get(params.cve); + if (!occurrences?.length) throw error(404, 'CVE not found'); + + return buildCveDetail(params.cve, occurrences); } diff --git a/src/routes/org/[org]/projects/[slug]/code-report/cves/[cve]/+page.svelte b/src/routes/org/[org]/projects/[slug]/code-report/cves/[cve]/+page.svelte index 9c926925..79f56f92 100644 --- a/src/routes/org/[org]/projects/[slug]/code-report/cves/[cve]/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/code-report/cves/[cve]/+page.svelte @@ -1,48 +1,23 @@ @@ -52,8 +27,8 @@ + `/org/${orgSlug}/projects/${service.projectSlug}/code-report/services/${service.serviceSlug}`} /> diff --git a/src/routes/org/[org]/projects/[slug]/code-report/dashboard/+page.server.ts b/src/routes/org/[org]/projects/[slug]/code-report/dashboard/+page.server.ts index d31a2a65..cf77b1da 100644 --- a/src/routes/org/[org]/projects/[slug]/code-report/dashboard/+page.server.ts +++ b/src/routes/org/[org]/projects/[slug]/code-report/dashboard/+page.server.ts @@ -8,10 +8,14 @@ import { } from '#modules/code-report'; import { extractSecrets, summarizeAnalysisResult } from '#lib/code-report/analysis-summary'; import { summarizeCves } from '#lib/code-report/cve-aggregation'; +import { riskLevel } from '#lib/code-report/severity-ui'; import type { PolicyComplianceReport } from '#lib/code-report/policy-evaluation'; import { mergeComplianceReports } from '#lib/code-report/policy-evaluation'; const STALE_AFTER_DAYS = 30; +const TOP_CVES = 10; +const TOP_PACKAGES = 6; +const RECENT_ANALYSES = 6; export async function load({ parent, locals }) { const { project } = await parent(); @@ -72,6 +76,7 @@ export async function load({ parent, locals }) { id: service.id, slug: service.slug, name: service.name, + violatesPolicy: report?.status === 'violated', scanned: trivyAnalysis !== null, severity: summary.vulnerabilities, exposedSecrets, @@ -110,15 +115,125 @@ export async function load({ parent, locals }) { }); const riskiestServices = serviceStats - .map((service) => ({ - ...service, - riskScore: codeReportService.calculateRiskScore(service.severity, riskWeights), + .map((service) => { + const riskScore = codeReportService.calculateRiskScore(service.severity, riskWeights); + return { + ...service, + riskScore, + level: riskLevel(riskScore, service.severity.critical).key, + }; + }) + .filter((service) => service.riskScore > 0 || service.exposedSecrets > 0) + .sort( + (left, right) => + right.riskScore - left.riskScore || right.exposedSecrets - left.exposedSecrets, + ) + .slice(0, 6); + + // CVEs únicos por severidad (un CVE en varios servicios cuenta una vez) + const cvesBySeverity = { critical: 0, high: 0, medium: 0, low: 0, unknown: 0 }; + for (const cve of cves) cvesBySeverity[cve.severity] += 1; + + // críticos y altos, con lo necesario para actuar: paquete, versión con corrección y servicios + const topCves = cves + .filter((cve) => cve.severity === 'critical' || cve.severity === 'high') + .slice(0, TOP_CVES) + .map((cve) => { + const occurrences = occurrencesByCve.get(cve.id) ?? []; + const first = occurrences[0]?.finding; + const services = [ + ...new Map( + occurrences.map((occurrence) => [ + occurrence.serviceSlug, + { slug: occurrence.serviceSlug, name: occurrence.serviceName }, + ]), + ).values(), + ]; + return { + ...cve, + packageName: first?.packageName ?? '', + installedVersion: first?.installedVersion ?? '', + fixedVersion: + occurrences.find((occurrence) => occurrence.finding.fixedVersion)?.finding.fixedVersion ?? + '', + services, + }; + }); + + // paquetes que más CVEs críticos/altos arrastran: actualizar uno arregla varios + const packageMap = new Map< + string, + { + name: string; + cves: Set; + critical: Set; + high: Set; + fixable: Set; + services: Set; + } + >(); + for (const [cveId, occurrences] of occurrencesByCve) { + for (const occurrence of occurrences) { + const name = occurrence.finding.packageName || '—'; + const entry = packageMap.get(name) ?? { + name, + cves: new Set(), + critical: new Set(), + high: new Set(), + fixable: new Set(), + services: new Set(), + }; + entry.cves.add(cveId); + if (occurrence.finding.severity === 'critical') entry.critical.add(cveId); + if (occurrence.finding.severity === 'high') entry.high.add(cveId); + if (occurrence.finding.fixedVersion) entry.fixable.add(cveId); + entry.services.add(occurrence.serviceId); + packageMap.set(name, entry); + } + } + const topPackages = [...packageMap.values()] + .filter((entry) => entry.critical.size + entry.high.size > 0) + .map((entry) => ({ + name: entry.name, + cves: entry.cves.size, + critical: entry.critical.size, + high: entry.high.size, + fixable: entry.fixable.size, + services: entry.services.size, })) - .filter((service) => service.riskScore > 0) - .sort((left, right) => right.riskScore - left.riskScore) - .slice(0, 5); + .sort( + (left, right) => + right.critical - left.critical || right.high - left.high || right.cves - left.cves, + ) + .slice(0, TOP_PACKAGES); + + const secretsByService = serviceStats + .filter((service) => service.exposedSecrets > 0) + .sort((left, right) => right.exposedSecrets - left.exposedSecrets) + .map((service) => ({ + slug: service.slug, + name: service.name, + exposedSecrets: service.exposedSecrets, + })); - const topCves = cves.slice(0, 8); + const serviceById = new Map(services.map((service) => [service.id, service])); + const recentAnalyses = ( + await codeReportAnalysisService + .listByProject(services.map((service) => service.id)) + .catch(() => []) + ) + .slice(0, RECENT_ANALYSES) + .map((analysis) => ({ + id: analysis.id, + tool: analysis.tool, + status: analysis.status, + createdAt: new Date(analysis.createdAt).toISOString(), + serviceName: serviceById.get(analysis.serviceId)?.name ?? null, + critical: + analysis.tool === 'trivy' && analysis.status === 'completed' + ? summarizeAnalysisResult(analysis.result).vulnerabilities.critical + : null, + })); const evaluatedServices = policyEvaluations.filter( (entry) => entry.report.status === 'compliant' || entry.report.status === 'violated', @@ -154,6 +269,10 @@ export async function load({ parent, locals }) { criticalCount: severityBreakdown.critical, highCount: severityBreakdown.high, exposedSecrets: serviceStats.reduce((total, service) => total + service.exposedSecrets, 0), + criticalCves: cvesBySeverity.critical, + highCves: cvesBySeverity.high, + servicesWithSecrets: secretsByService.length, + remediableCves, remediationCoveragePercent: cves.length > 0 ? Math.round((remediableCves / cves.length) * 100) : null, staleServicesCount: staleServices.length, @@ -171,8 +290,18 @@ export async function load({ parent, locals }) { violatedPolicies: [...violatedPolicies.values()], }, severityBreakdown, + cvesBySeverity, topCves, + topPackages, riskiestServices, - staleServices: staleServices.slice(0, 5), + secretsByService: secretsByService.slice(0, 6), + recentAnalyses, + staleServices: staleServices.slice(0, 5).map((service) => ({ + id: service.id, + slug: service.slug, + name: service.name, + scanned: service.scanned, + lastScanAt: service.lastScanAt ? new Date(service.lastScanAt).toISOString() : null, + })), }; } diff --git a/src/routes/org/[org]/projects/[slug]/code-report/dashboard/+page.svelte b/src/routes/org/[org]/projects/[slug]/code-report/dashboard/+page.svelte index aa547b32..b32a86bd 100644 --- a/src/routes/org/[org]/projects/[slug]/code-report/dashboard/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/code-report/dashboard/+page.svelte @@ -1,58 +1,44 @@ + Code Report - Dashboard - GitOps +{#snippet kpi( + href: string, + icon: Component, + label: string, + value: string | number, + detail: string, + tone: string, +)} + {@const Icon = icon} + +

    + {label} + +

    +

    {value}

    +

    {detail}

    +
    +{/snippet} +
    -
    -
    -
    - Servicios -
    -

    {data.kpis.totalServices}

    -

    - {data.kpis.scannedServices} con al menos un análisis completado +

    +
    +

    Code Report

    +

    + Vulnerabilidades, secretos y cumplimiento según el último análisis de cada servicio.

    - -
    -
    - CVEs críticos + altos -
    -

    - {data.kpis.criticalCount + data.kpis.highCount} -

    -

    de {data.kpis.totalCves} CVEs detectados en total

    + +
    -
    -
    - Secretos expuestos -
    -

    {data.kpis.exposedSecrets}

    -

    detectados en los últimos análisis de gitleaks

    -
    + +
    + {@render kpi( + `${base}/services`, + Boxes, + 'Servicios', + `${k.scannedServices}/${k.totalServices}`, + k.staleServicesCount > 0 + ? `${k.staleServicesCount} sin análisis en 30 días` + : 'Analizados y al día', + k.staleServicesCount > 0 ? 'text-amber-300' : 'text-white', + )} + {@render kpi( + cvesHref(), + ShieldAlert, + 'CVEs críticos', + k.criticalCves, + `${k.criticalCount} ${k.criticalCount === 1 ? 'hallazgo' : 'hallazgos'} en servicios`, + k.criticalCves > 0 ? 'text-red-300' : 'text-white', + )} + {@render kpi( + cvesHref(), + TriangleAlert, + 'CVEs altos', + k.highCves, + `${k.highCount} ${k.highCount === 1 ? 'hallazgo' : 'hallazgos'} en servicios`, + k.highCves > 0 ? 'text-brand-300' : 'text-white', + )} + {@render kpi( + `${base}/services`, + KeyRound, + 'Secretos expuestos', + k.exposedSecrets, + k.servicesWithSecrets > 0 + ? `en ${k.servicesWithSecrets} ${k.servicesWithSecrets === 1 ? 'servicio' : 'servicios'}` + : 'Ninguno detectado', + k.exposedSecrets > 0 ? 'text-red-300' : 'text-white', + )} + {@render kpi( + cvesHref(), + Wrench, + 'Con corrección', + k.remediationCoveragePercent !== null ? `${k.remediationCoveragePercent}%` : '—', + `${k.remediableCves} de ${k.totalCves} CVEs tienen versión corregida`, + 'text-white', + )} + {@render kpi( + `${base}/security-policy`, + policyState === 'violated' ? ShieldAlert : ShieldCheck, + 'Políticas', + policyState === 'none' + ? '—' + : policyState === 'pending' + ? '…' + : `${policies.compliantServices}/${policies.evaluatedServices}`, + policyState === 'none' + ? 'Sin políticas activas' + : policyState === 'violated' + ? `${policies.failingServices} ${policies.failingServices === 1 ? 'servicio incumple' : 'servicios incumplen'}` + : policyState === 'pending' + ? 'Pendiente de análisis' + : 'Todos los servicios cumplen', + policyState === 'violated' + ? 'text-red-300' + : policyState === 'compliant' + ? 'text-ok' + : 'text-white', + )} +
    -
    -
    - Cobertura de remediación + +
    +
    +
    +
    +

    CVEs importantes

    +

    Críticos y altos, del más grave al menos

    +
    + Ver todos
    -

    - {data.kpis.remediationCoveragePercent !== null - ? `${data.kpis.remediationCoveragePercent}%` - : '—'} -

    -

    CVEs con una versión corregida disponible

    -
    -
    + {#if data.topCves.length === 0} +
    + Ningún CVE crítico ni alto en el último análisis. +
    + {:else} +
    + + + + + + + + + + + + {#each data.topCves as cve (cve.id)} + + + + + + + + {/each} + +
    CVEPaqueteCorrecciónServiciosCVSS
    + + + {SEVERITY_LABEL[cve.severity]} + {cve.id} + + {#if cve.title} + {cve.title} + {/if} + + +

    {cve.packageName || '—'}

    + {#if cve.installedVersion} +

    {cve.installedVersion}

    + {/if} +
    + {#if cve.fixedVersion} + → {cve.fixedVersion} + {:else} + Sin corrección + {/if} + +
    + {#each cve.services.slice(0, 3) as service (service.slug)} + {service.name} + {/each} + {#if cve.services.length > 3} + +{cve.services.length - 3} + {/if} +
    +
    + {cve.cvssScore !== null ? cve.cvssScore.toFixed(1) : '—'} +
    +
    + {/if} + -
    -
    -
    -

    Distribución de severidad

    -

    Vulnerabilidades del último análisis de cada servicio.

    - {#if totalSeverity === 0} -

    No se han detectado vulnerabilidades.

    +
    +
    +

    Severidad

    +

    + {totalFindings} + {totalFindings === 1 ? 'hallazgo' : 'hallazgos'} · {k.totalCves} CVEs distintos +

    + {#if totalFindings === 0} +

    + Sin vulnerabilidades detectadas. +

    {:else} -
    -
    - -
    - {totalSeverity} - Total -
    -
    -
      - {#each Object.entries(severityColors) as [key, color] (key)} -
    • - - - {key} - - {data.severityBreakdown[key as keyof SeverityCounts]} -
    • - {/each} -
    + +
    + {#each SEVERITIES as key (key)} +
    +
    + {SEVERITY_LABEL[ + key + ]} +
    +
    + {data.severityBreakdown[key]} + ({data.cvesBySeverity[key]} CVEs) +
    +
    + {/each} +
    {/if}
    -
    -
    -

    - {#if policyState === 'violated'} - - {:else if policyState === 'compliant'} - - {:else} - - {/if} - Security Policy -

    -

    - {data.securityPolicies.active} políticas activas sobre {data.securityPolicies - .evaluatedServices} servicios evaluados. -

    -
    - +

    + {#if policyState === 'violated'}{:else}{/if} + Security Policy +

    +
    Gestionar - Gestionar -
    - {#if policyState === 'violated'} -

    - {data.securityPolicies.failingServices} -

    -

    - servicios incumpliendo · {data.securityPolicies.totalViolations} reglas superadas +

    + {policies.failingServices} + {policies.failingServices === 1 ? 'servicio incumple' : 'servicios incumplen'} · + {policies.totalViolations} reglas superadas

    -
      - {#each data.securityPolicies.violatedPolicies as policy (policy.id)} -
    • + {:else if policyState === 'compliant'} -

      OK

      -

      - {data.securityPolicies.compliantServices} servicios cumplen todas las políticas +

      + + {policies.compliantServices} + {policies.compliantServices === 1 ? 'servicio cumple' : 'servicios cumplen'} las {policies.active} + políticas activas.

      {:else} -
      +

      {#if policyState === 'none'} - Todavía no hay políticas activas. - Crea la primera + Sin políticas activas. + Crea la primera {:else} - Sin análisis suficientes para evaluar las políticas activas. + Hay {policies.active} políticas activas, pendientes de un análisis para evaluarse. {/if} -

      +

      {/if}
    +
    -
    -

    - CVEs más críticos -

    - {#if data.topCves.length === 0} -

    No se han detectado CVEs en este proyecto.

    + +
    +
    +
    +

    Servicios con más riesgo

    + Ver todos +
    + {#if data.riskiestServices.length === 0} +
    + Ningún servicio tiene vulnerabilidades ni secretos + expuestos. +
    {:else} -
    + +
    +
    +

    Paquetes a actualizar

    +

    Los que más CVEs críticos y altos acumulan

    +
    + {#if data.topPackages.length === 0} +

    + Ningún paquete con CVEs críticos o altos. +

    + {:else} +
      + {#each data.topPackages as pkg (pkg.name)} +
    • + + + {pkg.name} + + {pkg.cves} CVEs · {pkg.services} + {pkg.services === 1 ? 'servicio' : 'servicios'} + {#if pkg.fixable > 0}· {pkg.fixable} con corrección{/if} + + + + {#if pkg.critical > 0}C {pkg.critical}{/if} + {#if pkg.high > 0}H {pkg.high}{/if} + +
    • + {/each} +
    {/if}
    -
    -
    -

    - Servicios con más riesgo -

    - {#if data.riskiestServices.length === 0} -

    Ningún servicio tiene vulnerabilidades detectadas.

    + +
    +
    +
    +

    + Secretos expuestos +

    +

    Detectados por Gitleaks en el último análisis

    +
    + {#if data.secretsByService.length === 0} +

    + Ningún secreto expuesto. +

    {:else} -
    -
    -

    - Servicios sin análisis recientes -

    -

    Sin un escaneo completado en los últimos 30 días.

    +
    +
    +

    + Sin + análisis recientes +

    +

    Sin escaneo completado en 30 días

    +
    {#if data.staleServices.length === 0} -

    Todos los servicios tienen análisis recientes.

    +

    + Todos los servicios están al día. +

    {:else} -
    + +
    +
    +

    Últimos análisis

    + Historial +
    + {#if data.recentAnalyses.length === 0} +

    + Aparecerán cuando tu pipeline envíe el primero. +

    + {:else} +
      + {#each data.recentAnalyses as analysis (analysis.id)} +
    • + - {service.name} - - Último escaneo: {formatDate(service.lastScanAt)} + + + {analysis.serviceName ?? $_('codeReport.history.serviceDeleted')} + {relative(analysis.createdAt)} + {#if analysis.status === 'failed'} + {$_('codeReport.history.failed')} + {:else if analysis.status === 'in_progress'} + {$_('codeReport.history.inProgress')} + {:else if analysis.critical !== null && analysis.critical > 0} + C {analysis.critical} + {:else} + + {/if}
    • {/each} diff --git a/src/routes/org/[org]/projects/[slug]/code-report/history/+page.svelte b/src/routes/org/[org]/projects/[slug]/code-report/history/+page.svelte index fd548c95..12bae556 100644 --- a/src/routes/org/[org]/projects/[slug]/code-report/history/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/code-report/history/+page.svelte @@ -1,242 +1,252 @@ {$_('codeReport.history.title')} - GitOps +
      - {$_('codeReport.history.backToServices')} -
      -

      Code Report

      -

      Histórico de análisis

      -

      - Consulta todos los informes del proyecto y abre cualquier ejecución. -

      -
      -
      - -
      - - {#if openDropdown === 'service'} -
      - - {#each data.services as service} - - {/each} -
      +
      +

      + {$_('codeReport.history.title')} +

      +

      {$_('codeReport.history.description')}

      +
      + +
      +
      + +
      + + +
      + + {#if hasFilters} + {/if} + + {filteredRows.length} + {filteredRows.length === 1 + ? $_('codeReport.history.reportSingular') + : $_('codeReport.history.reportPlural')} +
      -
      - - {#if openDropdown === 'status'} -
      - {#each statusOptions as option} - + {/if} +
      + {:else} +
      - {/if} -
      - -
      -

      - {filteredAnalyses.length} informe{filteredAnalyses.length === 1 ? '' : 's'} -

      -
    + {/if}
    diff --git a/src/routes/org/[org]/projects/[slug]/code-report/history/[analysisID]/+page.server.ts b/src/routes/org/[org]/projects/[slug]/code-report/history/[analysisID]/+page.server.ts index bb84a587..7be2c887 100644 --- a/src/routes/org/[org]/projects/[slug]/code-report/history/[analysisID]/+page.server.ts +++ b/src/routes/org/[org]/projects/[slug]/code-report/history/[analysisID]/+page.server.ts @@ -23,6 +23,8 @@ export async function load({ parent, params, locals }) { service, analysis, riskWeights, - analysisHistory: await codeReportAnalysisService.listByService(service.id), + // solo resúmenes: la gráfica de evolución no necesita el resultado completo de cada análisis + analysisHistory: (await codeReportAnalysisService.getServiceOverview(service.id)) + .analysisHistory, }; } diff --git a/src/routes/org/[org]/projects/[slug]/code-report/history/[analysisID]/+page.svelte b/src/routes/org/[org]/projects/[slug]/code-report/history/[analysisID]/+page.svelte index 09261d5f..25eba01a 100644 --- a/src/routes/org/[org]/projects/[slug]/code-report/history/[analysisID]/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/code-report/history/[analysisID]/+page.svelte @@ -1,43 +1,92 @@ {data.service.name} - {$_('codeReport.history.title')} +
    - {$_('codeReport.history.backToHistory')} -
    -

    {$_('codeReport.history.reportViewed')}

    -

    {data.service.name}

    -
    - {data.analysis.id}{new Date(data.analysis.createdAt).toLocaleString()}{data.analysis.status} + {$_('codeReport.history.backToHistory')} + + +
    +
    + +
    +

    + {$_('codeReport.history.reportViewed')} +

    +

    + {data.service.name} +

    +
    + + {#if status} + {$_( + `codeReport.history.${status.key}`, + )} + {:else} + {data.analysis.status} + {/if} + {createdAt} + {data.analysis.id} +
    +
    -
    + +
    diff --git a/src/routes/org/[org]/projects/[slug]/code-report/services/+page.svelte b/src/routes/org/[org]/projects/[slug]/code-report/services/+page.svelte index 4fbaca32..1f616a67 100644 --- a/src/routes/org/[org]/projects/[slug]/code-report/services/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/code-report/services/+page.svelte @@ -1,8 +1,10 @@ @@ -105,86 +149,123 @@
    -
    -
    - - +
    +
    +

    + {$_('codeReport.servicesTitle')} +

    +

    + Vulnerabilidades, dependencias y secretos expuestos del último análisis de cada servicio. +

    {#if data.canCreate} - {/if} -
    + + + {#if data.services.length > 0} +
    + + + {filteredServices.length} / {data.services.length} + +
    + {/if} - {#if filteredServices.length === 0} + {#if data.services.length === 0}
    - -

    - {data.services.length === 0 - ? $_('codeReport.services.empty') - : $_('codeReport.services.emptySearch')} + 🦊 +

    {$_('codeReport.services.empty')}

    +

    + Crea un servicio y envía su primer análisis desde tu pipeline de CI.

    + {#if data.canCreate} + + {/if} +
    + {:else if filteredServices.length === 0} +
    + + + +

    {$_('codeReport.services.emptySearch')}

    {:else} -
    +
    {#each filteredServices as service (service.id)} - -

    {service.name}

    -

    {service.slug}

    +
    +
    + +
    +

    {service.name}

    +

    {service.slug}

    +
    + +
    + {#if service.description} -

    {service.description}

    +

    {service.description}

    {/if} + {#if service.tags.length > 0}
    - {#each service.tags as tag} - - {tag} - + {#each service.tags as tag (tag)} + {tag} {/each}
    {/if} -
    -{#if modalOpen} -
    -
    -
    -

    {$_('codeReport.services.addService')}

    - -
    - -
    { - submitting = true; - return async ({ update }) => { - await update(); - submitting = false; - }; - }} - class="mt-4 space-y-4" - > - {#if form?.error} -

    {form.error}

    - {/if} - -
    - - -
    - -
    - + + + + {#snippet children(control)} + + {/snippet} + + + {#snippet children(control)} + + {/snippet} + + + {#snippet children(control)} + + {/snippet} + + + {#snippet children(control)} +
    + {#each tags as tag (tag)} + + {tag} + + + {/each}
    - -
    - - -
    - -
    - -
    - {#each tags as tag (tag)} - - {tag} - - - {/each} - -
    - {#each tags as tag (tag)} - - {/each} -
    - -
    - - -
    - -
    -
    -{/if} + {/snippet} + + {#each tags as tag (tag)} + + {/each} + {#if form?.error} + + {/if} + + {#snippet footer()} + + + {/snippet} + diff --git a/src/routes/org/[org]/projects/[slug]/code-report/services/[serviceSlug]/+page.svelte b/src/routes/org/[org]/projects/[slug]/code-report/services/[serviceSlug]/+page.svelte index 7b7598b7..2d165a03 100644 --- a/src/routes/org/[org]/projects/[slug]/code-report/services/[serviceSlug]/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/code-report/services/[serviceSlug]/+page.svelte @@ -1,74 +1,99 @@ {data.service.name} - Code Report - GitOps
    -
    - - {$_('codeReport.serviceDetail.backToServices')} - -
    - + {$_('codeReport.serviceDetail.backToServices')} + + +
    +
    + +
    +

    + {data.service.name} +

    +
    + {data.service.slug} + {#each data.service.tags ?? [] as tag (tag)} + {tag} + {/each} +
    + {#if data.service.description} +

    {data.service.description}

    + {/if} +
    +
    +
    + {$_('codeReport.serviceDetail.viewHistory')} {#if data.canDelete} {/if}
    -
    - - {#if data.monitoring} - - {/if} + + securityPoliciesHref={`${codeReportBase}/security-policy`} + > + {#snippet aside()} + {#if data.monitoring} + + {/if} + {/snippet} +
    -{#if deleteModalOpen} -
    -
    -
    -

    {$_('codeReport.serviceDetail.deleteTitle')}

    - -
    -

    - {$_('codeReport.serviceDetail.deleteDescriptionStart')} {data.service.name} - {$_('codeReport.serviceDetail.deleteDescriptionEnd')} -

    - {#if deleteError}

    - {deleteError} -

    {/if} -
    { - deleting = true; - return async ({ update }) => { - await update(); - deleting = false; - }; - }} - class="mt-5 flex justify-end gap-2" +{#if data.canDelete} + + {#snippet icon()} + - - - -
    -
    + {/snippet} +
    { + deleting = true; + const name = data.service.name; + return async ({ result, update }) => { + deleting = false; + if (result.type === 'redirect' || result.type === 'success') { + deleteOpen = false; + toast.success('Servicio borrado', name); + } else if (result.type === 'failure') { + toast.error( + 'No se pudo borrar el servicio', + result.data?.error ? String(result.data.error) : undefined, + ); + return; + } + await update(); + }; + }} + > + + {#snippet children(control)} + + {/snippet} + +
    + {#snippet footer()} + + + {/snippet} + {/if} diff --git a/src/routes/org/[org]/projects/[slug]/code-report/settings/+layout.svelte b/src/routes/org/[org]/projects/[slug]/code-report/settings/+layout.svelte deleted file mode 100644 index 788cfca0..00000000 --- a/src/routes/org/[org]/projects/[slug]/code-report/settings/+layout.svelte +++ /dev/null @@ -1,84 +0,0 @@ - - -
    -
    -
    -

    {$_('codeReport.settings.title')}

    -
    - {#each tabs as tab} - {#if tab.soon} - - {:else} - - - {tab.label} - - {/if} - {/each} -
    -
    - -
    - -
    -
    -
    - - diff --git a/src/routes/org/[org]/projects/[slug]/code-report/settings/+page.server.ts b/src/routes/org/[org]/projects/[slug]/code-report/settings/+page.server.ts index 534e85f4..37589c2e 100644 --- a/src/routes/org/[org]/projects/[slug]/code-report/settings/+page.server.ts +++ b/src/routes/org/[org]/projects/[slug]/code-report/settings/+page.server.ts @@ -2,6 +2,38 @@ import { error, fail } from '@sveltejs/kit'; import { cancanService } from '#modules/auth'; import { projectService } from '#modules/projects'; +const DEFAULT_CODE_REPORT_TOOLS = [ + { + id: 'trivy', + name: 'Vulnerabilidades', + description: 'Escaneo de vulnerabilidades y severidad de dependencias con Trivy.', + enabled: true, + scanner: 'trivy', + }, + { + id: 'syft', + name: 'Dependencias, SBOM y Licencias', + description: 'Inventario de dependencias, generación de SBOM y análisis de licencias con Syft.', + enabled: true, + scanner: 'syft', + }, + { + id: 'gitleaks', + name: 'Secretos Expuestos', + description: 'Detección de secretos expuestos en el repositorio con Gitleaks.', + enabled: true, + scanner: 'gitleaks', + }, + { + id: 'code-coverage', + name: 'Code Coverage', + description: 'Métricas de cobertura de código por servicio.', + enabled: false, + scanner: 'code-coverage', + soon: true, + }, +]; + export async function load({ params, locals }) { const project = await projectService.getProjectBySlug(params.slug); if (!project) { @@ -41,8 +73,25 @@ export async function load({ params, locals }) { }, }; + const persistedSettings = project.settings?.['code-report'] || {}; + const persistedTools = Array.isArray(persistedSettings.tools) ? persistedSettings.tools : []; + const persistedById = new Map( + persistedTools + .filter((tool: any) => tool && typeof tool.id === 'string') + .map((tool: any) => [tool.id, tool]), + ); + + const tools = DEFAULT_CODE_REPORT_TOOLS.map((tool) => { + const persisted = persistedById.get(tool.id); + return { + ...tool, + enabled: persisted?.enabled ?? tool.enabled, + }; + }); + return { settings: codeReportSettings, + tools, canUpdate, }; } @@ -93,4 +142,47 @@ export const actions = { return { success: true }; }, + + updateTools: async ({ request, params, locals }) => { + const project = await projectService.getProjectBySlug(params.slug); + + const canUpdate = await cancanService.canSessionUser( + locals.user, + 'project:codereport:reports:update', + { + scope: 'project', + projectId: project.id, + organizationId: project.organization?.id, + }, + ); + + if (!canUpdate) { + return fail(403, { error: 'Forbidden' }); + } + + const data = await request.formData(); + const enabledToolIds = data.getAll('tools'); + + const currentSettings = project.settings || {}; + const codeReportSettings = currentSettings['code-report'] || {}; + const enabledSet = new Set(enabledToolIds.map((id) => String(id))); + const updatedTools = DEFAULT_CODE_REPORT_TOOLS.map((tool) => ({ + ...tool, + enabled: tool.soon ? false : enabledSet.has(tool.id), + })); + + const updatedSettings = { + ...currentSettings, + 'code-report': { + ...codeReportSettings, + tools: updatedTools, + }, + }; + + await projectService.updateProject(project.id, { + settings: updatedSettings, + }); + + return { success: true }; + }, }; diff --git a/src/routes/org/[org]/projects/[slug]/code-report/settings/+page.svelte b/src/routes/org/[org]/projects/[slug]/code-report/settings/+page.svelte index c30a7832..43d68b78 100644 --- a/src/routes/org/[org]/projects/[slug]/code-report/settings/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/code-report/settings/+page.svelte @@ -1,93 +1,235 @@ + let { + data, + }: { + data: { + settings: { securityRiskMultipliers?: Multipliers }; + tools: AnalysisTool[]; + canUpdate: boolean; + }; + } = $props(); - - {$_('codeReport.settings.generalTitle')} - Code Report - + // si solo se han guardado herramientas, el proyecto aún no tiene multiplicadores + const DEFAULTS: Multipliers = { critical: 10, high: 6, medium: 3, low: 1 }; + const saved = $derived({ ...DEFAULTS, ...data.settings.securityRiskMultipliers }); -
    -
    -
    - -

    {$_('codeReport.settings.generalTitle')}

    -
    -

    {$_('codeReport.settings.generalDescription')}

    -
    - -
    { - loading = true; - return async ({ update }) => { + let values = $state(untrack(() => ({ ...saved }))); + let saving = $state(false); + + const dirty = $derived( + (Object.keys(values) as (keyof Multipliers)[]).some( + (key) => Number(values[key]) !== Number(saved[key]), + ), + ); + + // mismo código de color que /brand: critical = danger, high = brand, medium = warn, low = neutro + const severities: { key: keyof Multipliers; dot: string }[] = [ + { key: 'critical', dot: 'bg-red-400' }, + { key: 'high', dot: 'bg-brand-400' }, + { key: 'medium', dot: 'bg-amber-400' }, + { key: 'low', dot: 'bg-fg-subtle' }, + ]; + + const submit: SubmitFunction = () => { + saving = true; + return async ({ result, update }) => { + saving = false; + if (result.type === 'success') { + toast.success('Multiplicadores guardados'); + await update({ reset: false }); + } else if (result.type === 'failure') { + toast.error( + 'No se pudieron guardar los ajustes', + result.data?.error ? String(result.data.error) : undefined, + ); + } else { await update(); - loading = false; - }; - }} - class="space-y-6" - > -
    -
    - -

    {$_('codeReport.settings.riskMultipliers')}

    -
    + } + }; + }; + let enabled = $state>( + untrack(() => Object.fromEntries(data.tools.map((tool) => [tool.id, tool.enabled]))), + ); + let savingTools = $state(false); -

    {$_('codeReport.settings.formulaDescription')}

    + const toolsDirty = $derived( + data.tools.some((tool) => !tool.soon && enabled[tool.id] !== tool.enabled), + ); -
    - + const submitTools: SubmitFunction = () => { + savingTools = true; + return async ({ result, update }) => { + savingTools = false; + if (result.type === 'success') { + toast.success('Herramientas guardadas'); + await update({ reset: false }); + } else if (result.type === 'failure') { + toast.error( + 'No se pudieron guardar las herramientas', + result.data?.error ? String(result.data.error) : undefined, + ); + } else { + await update(); + } + }; + }; + - + + {$_('codeReport.settings.title')} - Code Report + - +
    +
    +

    + {$_('codeReport.settings.title')} +

    +

    {$_('codeReport.settings.generalDescription')}

    +
    - + +
    + +
    +

    {$_('codeReport.settings.riskMultipliers')}

    +

    {$_('codeReport.settings.formulaDescription')}

    +
    -
    -
    - -
    -

    {$_('codeReport.settings.example')}

    -

    {$_('codeReport.settings.ranges')}

    +
    +
    + {#each severities as severity (severity.key)} +
    + +
    + × + +
    + {/each} +
    + +
    + +
    +

    + (Critical × {values.critical}) + (High × {values.high}) + (Medium × {values.medium}) + + (Low × {values.low}) +

    +

    {$_('codeReport.settings.ranges')}

    -
    +
    + + {#if data.canUpdate} +
    + {#if dirty}Cambios sin guardar{/if} + +
    + {/if} + + +
    +
    +

    {$_('codeReport.settings.toolsTitle')}

    +

    + {$_('codeReport.settings.toolsDescription')} +

    +
    -
    -

    {$_('codeReport.settings.moreSettings')}

    -

    {$_('codeReport.settings.moreSettingsDescription')}

    -
    +
      + {#each data.tools as tool (tool.id)} +
    • + +
    • + {/each} +
    - {#if canUpdate} -
    -
    {/if} diff --git a/src/routes/org/[org]/projects/[slug]/code-report/settings/tools/+page.server.ts b/src/routes/org/[org]/projects/[slug]/code-report/settings/tools/+page.server.ts deleted file mode 100644 index 51bb1019..00000000 --- a/src/routes/org/[org]/projects/[slug]/code-report/settings/tools/+page.server.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { error, fail } from '@sveltejs/kit'; -import { cancanService } from '#modules/auth'; -import { projectService } from '#modules/projects'; - -const DEFAULT_CODE_REPORT_TOOLS = [ - { - id: 'trivy', - name: 'Vulnerabilidades', - description: 'Escaneo de vulnerabilidades y severidad de dependencias con Trivy.', - enabled: true, - scanner: 'trivy', - }, - { - id: 'syft', - name: 'Dependencias, SBOM y Licencias', - description: 'Inventario de dependencias, generación de SBOM y análisis de licencias con Syft.', - enabled: true, - scanner: 'syft', - }, - { - id: 'gitleaks', - name: 'Secretos Expuestos', - description: 'Detección de secretos expuestos en el repositorio con Gitleaks.', - enabled: true, - scanner: 'gitleaks', - }, - { - id: 'code-coverage', - name: 'Code Coverage', - description: 'Métricas de cobertura de código por servicio.', - enabled: false, - scanner: 'code-coverage', - soon: true, - }, -]; - -export async function load({ params, locals }) { - const project = await projectService.getProjectBySlug(params.slug); - - const canRead = await cancanService.canSessionUser( - locals.user, - 'project:codereport:reports:read', - { - scope: 'project', - projectId: project.id, - organizationId: project.organization?.id, - }, - ); - - if (!canRead) { - throw error(403, 'Forbidden'); - } - - const canUpdate = await cancanService.canSessionUser( - locals.user, - 'project:codereport:reports:update', - { - scope: 'project', - projectId: project.id, - organizationId: project.organization?.id, - }, - ); - - const codeReportSettings = project.settings?.['code-report'] || {}; - const persistedTools = Array.isArray(codeReportSettings.tools) ? codeReportSettings.tools : []; - const persistedById = new Map( - persistedTools - .filter((tool: any) => tool && typeof tool.id === 'string') - .map((tool: any) => [tool.id, tool]), - ); - - const tools = DEFAULT_CODE_REPORT_TOOLS.map((tool) => { - const persisted = persistedById.get(tool.id); - return { - ...tool, - enabled: persisted?.enabled ?? tool.enabled, - }; - }); - - return { - tools, - canUpdate, - }; -} - -export const actions = { - updateTools: async ({ request, params, locals }) => { - const project = await projectService.getProjectBySlug(params.slug); - - const canUpdate = await cancanService.canSessionUser( - locals.user, - 'project:codereport:reports:update', - { - scope: 'project', - projectId: project.id, - organizationId: project.organization?.id, - }, - ); - - if (!canUpdate) { - return fail(403, { error: 'Forbidden' }); - } - - const data = await request.formData(); - const enabledToolIds = data.getAll('tools'); - - const currentSettings = project.settings || {}; - const codeReportSettings = currentSettings['code-report'] || {}; - const enabledSet = new Set(enabledToolIds.map((id) => String(id))); - const updatedTools = DEFAULT_CODE_REPORT_TOOLS.map((tool) => ({ - ...tool, - enabled: tool.soon ? false : enabledSet.has(tool.id), - })); - - const updatedSettings = { - ...currentSettings, - 'code-report': { - ...codeReportSettings, - tools: updatedTools, - }, - }; - - await projectService.updateProject(project.id, { - settings: updatedSettings, - }); - - return { success: true }; - }, -}; diff --git a/src/routes/org/[org]/projects/[slug]/code-report/settings/tools/+page.svelte b/src/routes/org/[org]/projects/[slug]/code-report/settings/tools/+page.svelte deleted file mode 100644 index 6c32ef0d..00000000 --- a/src/routes/org/[org]/projects/[slug]/code-report/settings/tools/+page.svelte +++ /dev/null @@ -1,87 +0,0 @@ - - - - {$_('codeReport.settings.tools')} - Code Report - - -
    -
    -
    - -

    {$_('codeReport.settings.toolsTitle')}

    -
    -

    {$_('codeReport.settings.toolsDescription')}

    -
    - - { - loading = true; - return async ({ update }) => { - await update(); - loading = false; - }; - }} - > -
    - {#each localTools as tool} -
    -
    - -
    -
    - -

    {tool.description}

    -
    -
    - {/each} -
    - - {#if canUpdate} -
    - -
    - {/if} - -
    diff --git a/src/routes/org/[org]/projects/[slug]/monitoring/dashboard/+page.server.ts b/src/routes/org/[org]/projects/[slug]/monitoring/dashboard/+page.server.ts index 23c5bc10..85b684c0 100644 --- a/src/routes/org/[org]/projects/[slug]/monitoring/dashboard/+page.server.ts +++ b/src/routes/org/[org]/projects/[slug]/monitoring/dashboard/+page.server.ts @@ -1,6 +1,11 @@ -import { loadMonitorsWithStats } from '#lib/server/monitoring/page'; +import { newMonitorForm, loadMonitorsWithStats } from '#lib/server/monitoring/page'; export async function load({ parent }) { const { project } = await parent(); - return { ...(await loadMonitorsWithStats(project.id)), loadedAt: new Date().toISOString() }; + const loaded = await loadMonitorsWithStats(project.id); + return { + ...loaded, + newMonitor: newMonitorForm(loaded.services), + loadedAt: new Date().toISOString(), + }; } diff --git a/src/routes/org/[org]/projects/[slug]/monitoring/dashboard/+page.svelte b/src/routes/org/[org]/projects/[slug]/monitoring/dashboard/+page.svelte index 489b28b8..5626ca33 100644 --- a/src/routes/org/[org]/projects/[slug]/monitoring/dashboard/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/monitoring/dashboard/+page.svelte @@ -5,12 +5,22 @@ import { _ } from '#lib/i18n'; import { formatLatency, formatUptime, secondsSince, uptimeTone } from '#lib/monitoring/format'; import MonitorRow from '#lib/components/monitoring/MonitorRow.svelte'; + import { Tabs, tabId, tabPanelId } from '#lib/components/ui'; import StatusDot from '#lib/components/monitoring/StatusDot.svelte'; import type { MonitorRowData, ServiceOption } from '#lib/components/monitoring/types'; + import NewMonitorModal from '#lib/components/monitoring/NewMonitorModal.svelte'; import type { PageData } from './$types'; let { data }: { data: PageData } = $props(); + let newOpen = $state(false); + // el enlace sigue llevando a /monitors/new (nueva pestaña, sin JavaScript); un clic normal abre el modal + function openNew(event: MouseEvent) { + if (event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0) return; + event.preventDefault(); + newOpen = true; + } + const REFRESH_MS = 30_000; let range = $state<'hour' | 'day'>('day'); let query = $state(''); @@ -72,39 +82,43 @@ let updatedAgo = $derived(Math.round(secondsSince(data.loadedAt, now) ?? 0)); const filters = ['all', 'down', 'degraded', 'up', 'paused'] as const; + let filterTabs = $derived( + filters.map((option) => ({ + value: option, + label: option === 'all' ? $_('monitoring.dashboard.all') : $_(`monitoring.status.${option}`), + })), + ); + let rangeTabs = $derived([ + { value: 'hour', label: '24 h' }, + { value: 'day', label: $_('monitoring.dashboard.days', { values: { count: 60 } }) }, + ]); + + const glow: Record = { + down: 'bg-danger/20', + degraded: 'bg-warn/15', + up: 'bg-ok/10', + none: 'bg-brand-500/10', + }; {$_('monitoring.dashboard.title')} - {data.project.name}
    -
    +
    -
    +
    -

    - {$_('monitoring.dashboard.eyebrow')} -

    -

    +

    {$_('monitoring.dashboard.eyebrow')}

    +

    {#if overall === 'down'} {$_('monitoring.dashboard.headlineDown', { values: { count: counts.down } })} {:else if overall === 'degraded'} @@ -115,7 +129,7 @@ {$_('monitoring.dashboard.headlineEmpty')} {/if}

    -

    +

    {$_('monitoring.dashboard.updated', { values: { seconds: updatedAgo } })}

    @@ -123,7 +137,8 @@ {#if data.monitoringPermissions.canCreate} {$_('monitoring.newMonitor')} @@ -132,63 +147,53 @@
    -
    -

    +

    +

    {$_('monitoring.dashboard.monitors')}

    -

    {data.monitors.length}

    -

    - {counts.up} up - {#if counts.degraded}{data.monitors.length}

    +

    + {counts.up} up + {#if counts.degraded}{counts.degraded} {$_('monitoring.status.degraded').toLowerCase()}{/if} - {#if counts.down}{counts.down} down{/if} + {#if counts.down}{counts.down} down{/if} {#if counts.paused}{counts.paused} {$_('monitoring.status.paused').toLowerCase()}{/if}

    -
    -

    +

    +

    {$_('monitoring.uptime.h24')}

    -

    +

    {formatUptime(uptime24)}

    -
    -

    +

    +

    {$_('monitoring.uptime.d30')}

    -

    +

    {formatUptime(uptime30)}

    -
    -

    +

    +

    {$_('monitoring.dashboard.avgLatency')}

    -

    +

    {formatLatency(latency === null ? null : Math.round(latency))}

    -
    -

    +

    +

    {$_('monitoring.dashboard.openIncidents')}

    {counts.down + counts.degraded} @@ -199,95 +204,85 @@

    -
    - +
    -
    - {#each filters as option (option)} - - {/each} -
    -
    - - -
    + + filter, (next) => (filter = next as typeof filter)} + /> + range, (next) => (range = next as typeof range)} + />
    - {#if data.monitors.length === 0} -
    - -

    - {$_('monitoring.dashboard.emptyTitle')} -

    -

    - {$_('monitoring.dashboard.emptyDescription')} -

    - {#if data.monitoringPermissions.canCreate} - + {#if data.monitors.length === 0} + - {:else if visible.length === 0} -

    - {$_('monitoring.dashboard.noMatches')} -

    - {:else} -
    - {#each visible as row (row.monitor.id)} - - {/each} -
    - {/if} + + +

    + {$_('monitoring.dashboard.emptyTitle')} +

    +

    + {$_('monitoring.dashboard.emptyDescription')} +

    + {#if data.monitoringPermissions.canCreate} + + {$_('monitoring.newMonitor')} + + {/if} +
    + {:else if visible.length === 0} +

    + {$_('monitoring.dashboard.noMatches')} +

    + {:else} +
    + {#each visible as row (row.monitor.id)} + + {/each} +
    + {/if} +
    -
    @@ -304,7 +299,7 @@ })} {#if data.info.scheduler.overdue > 0} - {$_('monitoring.dashboard.overdue', { values: { count: data.info.scheduler.overdue }, })} -
    +
    + +{#if data.monitoringPermissions.canCreate} + +{/if} diff --git a/src/routes/org/[org]/projects/[slug]/monitoring/monitors/+page.server.ts b/src/routes/org/[org]/projects/[slug]/monitoring/monitors/+page.server.ts index ddc7f289..06bc673c 100644 --- a/src/routes/org/[org]/projects/[slug]/monitoring/monitors/+page.server.ts +++ b/src/routes/org/[org]/projects/[slug]/monitoring/monitors/+page.server.ts @@ -1,8 +1,9 @@ -import { loadMonitorsWithStats, monitorActions } from '#lib/server/monitoring/page'; +import { newMonitorForm, loadMonitorsWithStats, monitorActions } from '#lib/server/monitoring/page'; export async function load({ parent }) { const { project } = await parent(); - return loadMonitorsWithStats(project.id); + const loaded = await loadMonitorsWithStats(project.id); + return { ...loaded, newMonitor: newMonitorForm(loaded.services) }; } export const actions = { toggle: monitorActions.toggle, delete: monitorActions.delete }; diff --git a/src/routes/org/[org]/projects/[slug]/monitoring/monitors/+page.svelte b/src/routes/org/[org]/projects/[slug]/monitoring/monitors/+page.svelte index b2fbd615..46553660 100644 --- a/src/routes/org/[org]/projects/[slug]/monitoring/monitors/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/monitoring/monitors/+page.svelte @@ -4,12 +4,28 @@ import { _ } from '#lib/i18n'; import { formatLatency, formatUptime, statusStyle, uptimeTone } from '#lib/monitoring/format'; import StatusDot from '#lib/components/monitoring/StatusDot.svelte'; + import DeleteMonitorModal from '#lib/components/monitoring/DeleteMonitorModal.svelte'; + import NewMonitorModal from '#lib/components/monitoring/NewMonitorModal.svelte'; import type { PageData } from './$types'; let { data }: { data: PageData } = $props(); + let newOpen = $state(false); + // el enlace sigue llevando a /monitors/new (nueva pestaña, sin JavaScript); un clic normal abre el modal + function openNew(event: MouseEvent) { + if (event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0) return; + event.preventDefault(); + newOpen = true; + } + let query = $state(''); let confirmDelete = $state<{ id: string; name: string } | null>(null); + let deleteOpen = $state(false); + + function askDelete(monitor: { id: string; name: string }) { + confirmDelete = { id: monitor.id, name: monitor.name }; + deleteOpen = true; + } let serviceNames = $derived(new Map(data.services.map((service) => [service.id, service.name]))); let rows = $derived( @@ -37,169 +53,162 @@
    -

    {$_('monitoring.monitorsTitle')}

    -

    {$_('monitoring.monitorsSubtitle')}

    +

    + {$_('monitoring.monitorsTitle')} +

    +

    {$_('monitoring.monitorsSubtitle')}

    {#if perms.canCreate} - + {$_('monitoring.newMonitor')} {/if}
    -
    - - -
    +
    +
    + + + {rows.length} / {data.monitors.length} + +
    -
    - - - - - - - - - - - - - - {#each rows as { monitor, stats } (monitor.id)} - {@const status = monitor.enabled ? (stats?.status ?? 'pending') : 'paused'} - - + + {:else} + + {/each} + +
    {$_('monitoring.table.monitor')}{$_('monitoring.table.service')}{$_('monitoring.table.interval')}{$_('monitoring.uptime.h24')}{$_('monitoring.uptime.d30')}{$_('monitoring.table.latency')}{$_('monitoring.table.actions')}
    - + + + + + + + + + + + + + + {#each rows as { monitor, stats } (monitor.id)} + {@const status = monitor.enabled ? (stats?.status ?? 'pending') : 'paused'} + + + + + - - - {monitor.name} - {monitor.method} - {monitor.displayUrl}{formatUptime(stats?.uptime.d30)} + + - - - - - - - - {:else} - - {/each} - -
    {$_('monitoring.table.monitor')}{$_('monitoring.table.service')}{$_('monitoring.table.interval')}{$_('monitoring.uptime.h24')}{$_('monitoring.uptime.d30')}{$_('monitoring.table.latency')}{$_('monitoring.table.actions')}
    + + + + {monitor.name} + {monitor.method} + {monitor.displayUrl} + + + {serviceNames.get(monitor.serviceId ?? '') ?? '—'}{interval(monitor.intervalSeconds)}{formatUptime(stats?.uptime.h24)}{formatLatency(stats?.latency24h.avg)} +
    + {$_(`monitoring.status.${status}`)} - - -
    {serviceNames.get(monitor.serviceId ?? '') ?? '—'}{interval(monitor.intervalSeconds)}{formatUptime(stats?.uptime.h24)}{formatUptime(stats?.uptime.d30)}{formatLatency(stats?.latency24h.avg)} -
    - {$_(`monitoring.status.${status}`)} - {#if perms.canUpdate} -
    - - + {#if perms.canUpdate} + + + + +
    + + {/if} + {#if perms.canDelete} - - - {/if} - {#if perms.canDelete} - - {/if} -
    -
    {data.monitors.length - ? $_('monitoring.dashboard.noMatches') - : $_('monitoring.dashboard.emptyTitle')}
    + {/if} + +
    {data.monitors.length + ? $_('monitoring.dashboard.noMatches') + : $_('monitoring.dashboard.emptyTitle')}
    +
    {#if confirmDelete} - + +{/if} + +{#if data.monitoringPermissions.canCreate} + {/if} diff --git a/src/routes/org/[org]/projects/[slug]/monitoring/monitors/[id]/+page.svelte b/src/routes/org/[org]/projects/[slug]/monitoring/monitors/[id]/+page.svelte index fce9288f..58bf7d38 100644 --- a/src/routes/org/[org]/projects/[slug]/monitoring/monitors/[id]/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/monitoring/monitors/[id]/+page.svelte @@ -12,6 +12,7 @@ Play, ShieldCheck, Trash2, + TriangleAlert, } from '@lucide/svelte'; import { _, locale } from '#lib/i18n'; import { @@ -26,6 +27,7 @@ import TestResultPanel from '#lib/components/monitoring/TestResultPanel.svelte'; import UptimeBars from '#lib/components/monitoring/UptimeBars.svelte'; import LatencyChart from '#lib/components/monitoring/LatencyChart.svelte'; + import DeleteMonitorModal from '#lib/components/monitoring/DeleteMonitorModal.svelte'; import type { TestResult } from '#lib/components/monitoring/types'; import type { ActionData, PageData } from './$types'; @@ -63,6 +65,12 @@ : $_('monitoring.form.everyMinutes', { values: { count: seconds / 60 } }); } + const glow: Record = { + down: 'bg-danger/20', + degraded: 'bg-warn/15', + up: 'bg-ok/10', + }; + let uptimes = $derived([ { key: 'h24', label: $_('monitoring.uptime.h24'), value: stats?.uptime.h24 }, { key: 'd7', label: $_('monitoring.uptime.d7'), value: stats?.uptime.d7 }, @@ -76,49 +84,39 @@
    {$_('monitoring.backToDashboard')} - -
    + +
    -

    {monitor.name}

    -

    - {monitor.method}{monitor.displayUrl} +

    + {monitor.name} +

    +

    + {monitor.method} + {monitor.displayUrl}

    - + {$_(`monitoring.status.${status}`)} {#if since !== null && status !== 'paused' && status !== 'pending'} - {$_('monitoring.detail.since', { values: { duration: formatDuration(since) }, })} {data.service.name} {/if} {#if stats?.lastCheck} - {$_('monitoring.detail.lastCheck', { values: { ago: formatDuration(secondsSince(stats.lastCheck.startedAt, now)) }, })} - - + {$_('monitoring.actions.edit')} {/if} {#if perms.canDelete}
    {#if stats?.openIncident} + {@const tone = stats.openIncident.status === 'down' ? 'danger' : 'warn'}
    - {$_(`monitoring.detail.openIncident.${stats.openIncident.status}`)} - — {stats.openIncident.cause ? $_(`monitoring.causes.${stats.openIncident.cause}`) : ''} - {#if stats.openIncident.httpStatus}(HTTP {stats.openIncident.httpStatus}){/if} - {#if stats.openIncident.error}· {stats.openIncident.error}{/if} + +

    + {$_(`monitoring.detail.openIncident.${stats.openIncident.status}`)} + — {stats.openIncident.cause ? $_(`monitoring.causes.${stats.openIncident.cause}`) : ''} + {#if stats.openIncident.httpStatus}(HTTP {stats.openIncident.httpStatus}){/if} + {#if stats.openIncident.error}· {stats.openIncident.error}{/if} +

    {/if}
    @@ -220,43 +221,39 @@
    {#each uptimes as item (item.key)} -
    -

    {item.label}

    -

    +

    +

    {item.label}

    +

    {formatUptime(item.value)}

    {/each} -
    -

    - {$_('monitoring.detail.avgLatency')} -

    -

    +

    +

    {$_('monitoring.detail.avgLatency')}

    +

    {formatLatency(stats?.latency24h.avg)}

    -
    -

    p95 · 24 h

    -

    +

    +

    p95 · 24 h

    +

    {formatLatency(stats?.latency24h.p95)}

    - + {#if stats} -
    +
    -

    {$_('monitoring.detail.last90Days')}

    - {$_('monitoring.detail.last90Days')} + {formatUptime(stats.uptime.d90)}
    -
    +
    {$_('monitoring.bars.daysAgo', { values: { count: 90 } })}{$_('monitoring.bars.today')} @@ -264,15 +261,13 @@
    -

    - {$_('monitoring.detail.last24Hours')} -

    - {$_('monitoring.detail.last24Hours')} + {formatUptime(stats.uptime.h24)}
    -
    +
    {$_('monitoring.bars.hoursAgo', { values: { count: 24 } })}{$_('monitoring.bars.now')} @@ -283,7 +278,6 @@
    - - -
    -

    + +
    +

    {$_('monitoring.detail.incidents')}

    {#if data.incidents.length === 0} -

    - {$_('monitoring.detail.noIncidents')} +

    + {$_('monitoring.detail.noIncidents')}

    {:else} -
      +
        {#each data.incidents as incident (incident.id)} {@const duration = incident.endedAt ? (Date.parse(incident.endedAt) - Date.parse(incident.startedAt)) / 1000 : secondsSince(incident.startedAt, now)}
      • - {$_(`monitoring.status.${incident.status}`)} - {incident.cause ? $_(`monitoring.causes.${incident.cause}`) : '—'}{incident.httpStatus ? ` · HTTP ${incident.httpStatus}` : ''} - {dateTime(incident.startedAt)} + {dateTime(incident.startedAt)} {incident.endedAt ? formatDuration(duration) : $_('monitoring.detail.ongoing')} @@ -333,88 +325,58 @@

    - - +
    -{#if confirmDelete} - -{/if} + diff --git a/src/routes/org/[org]/projects/[slug]/monitoring/monitors/[id]/edit/+page.svelte b/src/routes/org/[org]/projects/[slug]/monitoring/monitors/[id]/edit/+page.svelte index e146ed3f..7adedf21 100644 --- a/src/routes/org/[org]/projects/[slug]/monitoring/monitors/[id]/edit/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/monitoring/monitors/[id]/edit/+page.svelte @@ -22,11 +22,11 @@
    {data.monitor.name} -

    {$_('monitoring.editMonitor')}

    +

    {$_('monitoring.editMonitor')}

    service.id === presetService) ? presetService : '', - headers: [], - body: '', - intervalSeconds: String(MONITOR_DEFAULTS.intervalSeconds), - timeoutMs: String(MONITOR_DEFAULTS.timeoutMs), - expectedStatus: MONITOR_DEFAULTS.expectedStatus, - degradedThresholdMs: String(MONITOR_DEFAULTS.degradedThresholdMs), - confirmations: String(MONITOR_DEFAULTS.confirmations), - followRedirects: MONITOR_DEFAULTS.followRedirects, - enabled: true, - }, - }; + return { services, ...newMonitorForm(services, url.searchParams.get('serviceId') ?? '') }; } export const actions = { save: monitorActions.save, test: monitorActions.test }; diff --git a/src/routes/org/[org]/projects/[slug]/monitoring/monitors/new/+page.svelte b/src/routes/org/[org]/projects/[slug]/monitoring/monitors/new/+page.svelte index 0c60713d..dec4e093 100644 --- a/src/routes/org/[org]/projects/[slug]/monitoring/monitors/new/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/monitoring/monitors/new/+page.svelte @@ -18,12 +18,12 @@
    {$_('monitoring.backToMonitors')} -

    {$_('monitoring.newMonitor')}

    -

    {$_('monitoring.form.intro')}

    +

    {$_('monitoring.newMonitor')}

    +

    {$_('monitoring.form.intro')}

    = { + none: 100, + low: 90, + medium: 65, + high: 35, + critical: 10, +}; +/** Un servicio con secretos expuestos no puntúa más de esto, sea cual sea su nivel. */ +const EXPOSED_SECRETS_CAP = 20; +const DAY_MS = 24 * 60 * 60 * 1000; + +type Severity = { critical: number; high: number; medium: number; low: number; unknown: number }; + +type Project = { + id: string; + slug: string; + name: string; + description?: string | null; + status?: string; + modules?: { vault?: boolean; codereport?: boolean; stateiac?: boolean; monitoring?: boolean }; + organization?: { id: string; slug?: string | null; name?: string | null } | null; +}; + +async function safely( + logger: App.Locals['logger'] | undefined, + label: string, + task: () => Promise, +): Promise { + try { + return await task(); + } catch (err) { + logger?.error({ err }, `project dashboard: ${label} failed`); + return null; + } +} + +function toTime(value: unknown): number { + return new Date(value as string | Date).getTime(); +} + +async function loadCodeReport(projectId: string) { + const [services, riskWeights] = await Promise.all([ + codeReportService.listByProject(projectId), + codeReportService.getRiskWeightsByProjectId(projectId), + ]); + const analyses = await codeReportAnalysisService.listByProject( + services.map((service) => service.id), + ); + const serviceById = new Map(services.map((service) => [service.id, service])); + + // análisis de vulnerabilidades completados, del más antiguo al más reciente, ya resumidos + const scans = analyses + .filter((analysis) => analysis.tool === 'trivy' && analysis.status === 'completed') + .map((analysis) => ({ + serviceId: analysis.serviceId, + at: toTime(analysis.createdAt), + severity: summarizeAnalysisResult(analysis.result).vulnerabilities as Severity, + })) + .sort((left, right) => left.at - right.at); + + const latestScan = new Map(); + for (const scan of scans) latestScan.set(scan.serviceId, scan); + + const latestSecrets = new Map(); + for (const analysis of [...analyses].reverse()) { + if (analysis.tool === 'gitleaks' && analysis.status === 'completed') { + latestSecrets.set(analysis.serviceId, extractSecrets(analysis.result).length); + } + } + + const totals: Severity = { critical: 0, high: 0, medium: 0, low: 0, unknown: 0 }; + for (const scan of latestScan.values()) { + for (const key of Object.keys(totals) as (keyof Severity)[]) totals[key] += scan.severity[key]; + } + + const staleCutoff = Date.now() - STALE_AFTER_DAYS * DAY_MS; + const serviceRows = services.map((service) => { + const scan = latestScan.get(service.id) ?? null; + const lastAnalysis = analyses.find((analysis) => analysis.serviceId === service.id); + const riskScore = scan ? codeReportService.calculateRiskScore(scan.severity, riskWeights) : 0; + return { + slug: service.slug, + name: service.name, + severity: scan?.severity ?? null, + riskScore, + level: scan ? riskLevel(riskScore, scan.severity.critical).key : null, + exposedSecrets: latestSecrets.get(service.id) ?? 0, + lastScanAt: lastAnalysis ? new Date(lastAnalysis.createdAt).toISOString() : null, + }; + }); + + // puntuación 0-100: media de los servicios analizados según su nivel de riesgo + const scored = serviceRows.filter((service) => service.level !== null); + const score = scored.length + ? Math.round( + scored.reduce((sum, service) => { + const points = LEVEL_POINTS[service.level as LevelKey]; + return ( + sum + (service.exposedSecrets > 0 ? Math.min(points, EXPOSED_SECRETS_CAP) : points) + ); + }, 0) / scored.length, + ) + : null; + const levels: Record = { none: 0, low: 0, medium: 0, high: 0, critical: 0 }; + for (const service of scored) levels[service.level as LevelKey] += 1; + + // críticas abiertas ahora frente a hace 7 días (último análisis de cada servicio a esa fecha) + const criticalAt = (until: number) => { + const latest = new Map(); + for (const scan of scans) if (scan.at <= until) latest.set(scan.serviceId, scan.severity); + if (latest.size === 0) return null; + return [...latest.values()].reduce((sum, severity) => sum + severity.critical, 0); + }; + const before = criticalAt(Date.now() - DELTA_DAYS * DAY_MS); + const criticalDelta = before === null ? null : totals.critical - before; + + return { + totals, + services: { + total: services.length, + scanned: latestScan.size, + stale: serviceRows.filter( + (service) => !service.lastScanAt || toTime(service.lastScanAt) < staleCutoff, + ).length, + }, + exposedSecrets: [...latestSecrets.values()].reduce((sum, count) => sum + count, 0), + score, + levels, + criticalDelta, + riskiest: serviceRows + .filter((service) => service.riskScore > 0 || service.exposedSecrets > 0) + .sort((left, right) => right.riskScore - left.riskScore) + .slice(0, 5), + recent: analyses.slice(0, 6).map((analysis) => { + const service = serviceById.get(analysis.serviceId); + return { + id: analysis.id, + tool: analysis.tool, + status: analysis.status, + createdAt: new Date(analysis.createdAt).toISOString(), + serviceName: service?.name ?? null, + critical: + analysis.tool === 'trivy' && analysis.status === 'completed' + ? summarizeAnalysisResult(analysis.result).vulnerabilities.critical + : null, + }; + }), + }; +} + +async function loadVault(projectId: string) { + const vault = await vaultService.getProjectVault(projectId); + const secrets = vault.secrets as { values?: Record }[]; + const environments = (vault.environments as { slug: string; name: string; order?: number }[]) + .slice() + .sort((left, right) => (left.order ?? 0) - (right.order ?? 0)); + + return { + secrets: secrets.length, + folders: vault.folders.length, + environments: environments.map((environment) => { + const filled = secrets.filter((secret) => Boolean(secret.values?.[environment.slug])).length; + return { + slug: environment.slug, + name: environment.name, + filled, + missing: secrets.length - filled, + }; + }), + }; +} + +async function loadMonitoring(projectId: string) { + const [monitors, records] = await Promise.all([ + monitorService.listByProject(projectId), + monitorService.listRecordsByProject(projectId), + ]); + const stats = await monitoringRuntime.stats(records).catch(() => []); + const statsById = new Map(stats.map((entry) => [entry.monitorId, entry])); + + const rows = monitors.map((monitor) => { + const entry = statsById.get(monitor.id); + return { + id: monitor.id, + name: monitor.name, + url: monitor.displayUrl, + status: (monitor.enabled ? (entry?.status ?? 'pending') : 'paused') as string, + since: entry?.since ?? null, + uptime24h: entry?.uptime.h24 ?? null, + uptime30d: entry?.uptime.d30 ?? null, + latencyP95: entry?.latency24h.p95 ?? null, + hourlyBars: entry?.hourlyBars ?? [], + }; + }); + + const count = (status: string) => rows.filter((row) => row.status === status).length; + const average = (values: (number | null)[]) => { + const known = values.filter((value): value is number => typeof value === 'number'); + return known.length ? known.reduce((sum, value) => sum + value, 0) / known.length : null; + }; + + // primero lo que está caído o degradado + const order: Record = { down: 0, degraded: 1, pending: 2, up: 3, paused: 4 }; + return { + total: rows.length, + up: count('up'), + down: count('down'), + degraded: count('degraded'), + paused: count('paused'), + pending: count('pending'), + uptime24h: average(rows.map((row) => row.uptime24h)), + uptime30d: average(rows.map((row) => row.uptime30d)), + latencyP95: average(rows.map((row) => row.latencyP95)), + monitors: rows + .sort((left, right) => (order[left.status] ?? 9) - (order[right.status] ?? 9)) + .slice(0, 5), + }; +} + +export async function load({ parent, locals }) { + const { project } = (await parent()) as { project: Project }; + const modules = project.modules ?? {}; + const scope = { + scope: 'project' as const, + projectId: project.id, + organizationId: project.organization?.id, + }; + const can = (permission: string) => cancanService.canSessionUser(locals.user, permission, scope); + + const [ + canReadVault, + canReadCodeReport, + canReadMonitoring, + canReadAlerts, + canCreateSecret, + canCreateService, + canCreateMonitor, + canCreateAlert, + canManageMembers, + canManageKeys, + canUpdateProject, + ] = await Promise.all([ + can('project:vault:secrets:read'), + can('project:codereport:reports:read'), + can('project:monitoring:monitors:read'), + can('project:alerts:read'), + can('project:vault:secrets:create'), + can('project:codereport:reports:create'), + can('project:monitoring:monitors:create'), + can('project:alerts:create'), + can('project:users:invite'), + can('project:server-keys:create'), + can('project:project:update'), + ]); + + const logger = locals.logger; + const [codeReport, vault, monitoring, alerts] = await Promise.all([ + modules.codereport && canReadCodeReport + ? safely(logger, 'code report', () => loadCodeReport(project.id)) + : null, + modules.vault && canReadVault ? safely(logger, 'vault', () => loadVault(project.id)) : null, + modules.monitoring && canReadMonitoring + ? safely(logger, 'monitoring', () => loadMonitoring(project.id)) + : null, + canReadAlerts + ? safely(logger, 'alerts', async () => { + const list = await alertService.list({ + organizationId: project.organization?.id ?? '', + projectId: project.id, + }); + return { total: list.length, enabled: list.filter((alert) => alert.enabled).length }; + }) + : null, + ]); + + return { + dashboard: { + modules: { + vault: Boolean(modules.vault), + codereport: Boolean(modules.codereport), + monitoring: Boolean(modules.monitoring), + stateiac: Boolean(modules.stateiac), + }, + access: { + vault: canReadVault, + codereport: canReadCodeReport, + monitoring: canReadMonitoring, + }, + codeReport, + vault, + monitoring, + alerts, + can: { + createSecret: canCreateSecret, + createService: canCreateService, + createMonitor: canCreateMonitor, + createAlert: canCreateAlert, + manageMembers: canManageMembers, + manageKeys: canManageKeys, + updateProject: canUpdateProject, + }, + generatedAt: new Date().toISOString(), + }, + }; +} diff --git a/src/routes/org/[org]/projects/[slug]/overview/+page.svelte b/src/routes/org/[org]/projects/[slug]/overview/+page.svelte index d3a47865..59409b63 100644 --- a/src/routes/org/[org]/projects/[slug]/overview/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/overview/+page.svelte @@ -3,216 +3,910 @@ Activity, ArrowRight, BarChart3, - FolderKanban, + Bell, + Boxes, + CircleCheck, + Clock, + FileSearch, GitBranch, KeyRound, - Shield, + LockKeyhole, + Plus, + Settings, + ShieldAlert, + TriangleAlert, UserPlus, } from '@lucide/svelte'; - import { createPageStore } from '#lib/page-store'; - import { _ } from '#lib/i18n'; - - type ProjectModules = { - vault: boolean; - codereport: boolean; - stateiac: boolean; - monitoring?: boolean; - }; + import type { Component } from 'svelte'; + import UptimeBars from '#lib/components/monitoring/UptimeBars.svelte'; + import CodeReportToolBadge from '#lib/components/code-report/CodeReportToolBadge.svelte'; + import { formatUptime, statusStyle, uptimeTone } from '#lib/monitoring/format'; + import { _, locale } from '#lib/i18n'; - type ProjectRow = { - id: string; - name: string; - slug: string; - description?: string | null; - status: 'active' | 'inactive'; - modules: ProjectModules; + type Severity = { critical: number; high: number; medium: number; low: number; unknown: number }; + type LevelKey = 'none' | 'low' | 'medium' | 'high' | 'critical'; + type Bar = { + start: string; + end: string; + status: 'up' | 'degraded' | 'down' | 'none'; + uptime: number | null; + checks: number; + downSeconds: number; + degradedSeconds: number; + latencyAvg: number | null; }; - type ModuleInfo = { - key: keyof ProjectModules; - label: string; - description: string; - href: string; - guideHref: string; - icon: typeof Shield; + type Dashboard = { + modules: { vault: boolean; codereport: boolean; monitoring: boolean; stateiac: boolean }; + access: { vault: boolean; codereport: boolean; monitoring: boolean }; + codeReport: { + totals: Severity; + services: { total: number; scanned: number; stale: number }; + exposedSecrets: number; + score: number | null; + levels: Record; + criticalDelta: number | null; + riskiest: { + slug: string; + name: string; + severity: Severity | null; + riskScore: number; + level: LevelKey | null; + exposedSecrets: number; + }[]; + recent: { + id: string; + tool: string; + status: string; + createdAt: string; + serviceName: string | null; + critical: number | null; + }[]; + } | null; + vault: { + secrets: number; + folders: number; + environments: { slug: string; name: string; filled: number; missing: number }[]; + } | null; + monitoring: { + total: number; + up: number; + down: number; + degraded: number; + paused: number; + pending: number; + uptime24h: number | null; + uptime30d: number | null; + latencyP95: number | null; + monitors: { + id: string; + name: string; + url: string; + status: string; + uptime24h: number | null; + hourlyBars: Bar[]; + }[]; + } | null; + alerts: { total: number; enabled: number } | null; + can: { + createSecret: boolean; + createService: boolean; + createMonitor: boolean; + createAlert: boolean; + manageMembers: boolean; + manageKeys: boolean; + updateProject: boolean; + }; }; - export let data: { project: ProjectRow }; - - $: project = data.project; - $: orgSlug = $page?.params?.org ?? ''; - - $: moduleInfo = [ - { - key: 'vault', - label: 'Vault', - description: $_('project.vault.description'), - href: `/org/${orgSlug}/projects/${project.slug}/vault`, - guideHref: 'https://getgitops.com/docs/vault', - icon: Shield, - }, - { - key: 'codereport', - label: 'Code Report', - description: $_('project.layout.codeReportSubtitle'), - href: `/org/${orgSlug}/projects/${project.slug}/code-report`, - guideHref: 'https://getgitops.com/docs/code-report', - icon: BarChart3, - }, - { - key: 'monitoring', - label: 'Monitoring', - description: $_('monitoring.moduleDescription'), - href: `/org/${orgSlug}/projects/${project.slug}/monitoring`, - guideHref: 'https://getgitops.com/docs/monitoring', - icon: Activity, - }, - { - key: 'stateiac', - label: 'State IaC', - description: $_('project.layout.stateIacSubtitle'), - href: `/org/${orgSlug}/projects/${project.slug}/state-iac`, - guideHref: 'https://getgitops.com/docs/state-iac', - icon: GitBranch, - }, - ] satisfies ModuleInfo[]; - - $: activeModules = moduleInfo.filter((module) => project.modules[module.key]); - - $: quickActions = [ - { - label: $_('project.overview.inviteMembers'), - description: $_('project.overview.inviteMembersDescription'), - href: `/org/${orgSlug}/projects/${project.slug}/settings/access-control`, - icon: UserPlus, - }, - { - label: $_('project.overview.addSecretToken'), - description: $_('project.overview.addSecretTokenDescription'), - href: `/org/${orgSlug}/projects/${project.slug}/settings/server-access-keys`, - icon: KeyRound, - }, + let { + data, + }: { + data: { + project: { + id: string; + name: string; + slug: string; + description?: string | null; + status: 'active' | 'inactive'; + organization?: { slug?: string | null; name?: string | null } | null; + }; + dashboard: Dashboard; + }; + } = $props(); + + const project = $derived(data.project); + const d = $derived(data.dashboard); + const base = $derived(`/org/${project.organization?.slug ?? ''}/projects/${project.slug}`); + + const showCodeReport = $derived(d.modules.codereport && d.access.codereport && !!d.codeReport); + const showVault = $derived(d.modules.vault && d.access.vault && !!d.vault); + const showMonitoring = $derived(d.modules.monitoring && d.access.monitoring && !!d.monitoring); + + const vaultMissing = $derived( + d.vault?.environments.reduce((sum, environment) => sum + environment.missing, 0) ?? 0, + ); + + // ---------- salud ---------- + + type Grade = { letter: string; label: string; text: string; stroke: string }; + function gradeOf(score: number): Grade { + if (score >= 90) return { letter: 'A', label: 'Excelente', text: 'text-ok', stroke: '#22c55e' }; + if (score >= 75) return { letter: 'B', label: 'Bien', text: 'text-ok', stroke: '#22c55e' }; + if (score >= 60) + return { letter: 'C', label: 'Mejorable', text: 'text-warn', stroke: '#f59e0b' }; + if (score >= 40) + return { letter: 'D', label: 'En riesgo', text: 'text-brand-300', stroke: '#f95d11' }; + return { letter: 'F', label: 'Crítico', text: 'text-red-300', stroke: '#ef4444' }; + } + + // de menos a más riesgo, con el código de color de /brand + const LEVELS: { key: LevelKey; label: string; fill: string; badge: string }[] = [ + { key: 'none', label: 'Sin riesgo', fill: 'bg-ok', badge: 'k-badge-ok' }, + { key: 'low', label: 'Bajo', fill: 'bg-white/35', badge: '' }, + { key: 'medium', label: 'Medio', fill: 'bg-amber-400', badge: 'k-badge-warn' }, + { key: 'high', label: 'Alto', fill: 'bg-brand-500', badge: 'k-badge-brand' }, + { key: 'critical', label: 'Crítico', fill: 'bg-red-500', badge: 'k-badge-danger' }, + ]; + const levelMeta = (key: LevelKey | null) => LEVELS.find((level) => level.key === key); + + const monitoringState = $derived.by(() => { + const mon = d.monitoring; + if (!mon || mon.total === 0) return null; + if (mon.down > 0) + return { + tone: 'danger', + title: `${mon.down} ${mon.down === 1 ? 'monitor caído' : 'monitores caídos'}`, + }; + if (mon.degraded > 0) + return { + tone: 'warn', + title: `${mon.degraded} ${mon.degraded === 1 ? 'monitor degradado' : 'monitores degradados'}`, + }; + if (mon.up === 0) return { tone: 'neutral', title: 'Sin datos todavía' }; + return { tone: 'ok', title: 'Todo operativo' }; + }); + + function formatMs(value: number | null) { + if (value === null) return '—'; + return value >= 1000 ? `${(value / 1000).toFixed(2)} s` : `${Math.round(value)} ms`; + } + + // ---------- qué requiere atención ---------- + + type Issue = { tone: 'danger' | 'warn'; text: string; href: string; icon: Component }; + + const issues = $derived.by(() => { + const list: Issue[] = []; + const cr = showCodeReport ? d.codeReport : null; + const mon = showMonitoring ? d.monitoring : null; + if (mon && mon.down > 0) + list.push({ + tone: 'danger', + text: `${mon.down} ${mon.down === 1 ? 'monitor caído' : 'monitores caídos'}`, + href: `${base}/monitoring/monitors`, + icon: Activity, + }); + if (cr && cr.totals.critical > 0) + list.push({ + tone: 'danger', + text: `${cr.totals.critical} ${cr.totals.critical === 1 ? 'vulnerabilidad crítica' : 'vulnerabilidades críticas'}`, + href: `${base}/code-report/dashboard`, + icon: ShieldAlert, + }); + if (cr && cr.exposedSecrets > 0) + list.push({ + tone: 'danger', + text: `${cr.exposedSecrets} ${cr.exposedSecrets === 1 ? 'secreto expuesto' : 'secretos expuestos'} en el código`, + href: `${base}/code-report/services`, + icon: KeyRound, + }); + if (mon && mon.degraded > 0) + list.push({ + tone: 'warn', + text: `${mon.degraded} ${mon.degraded === 1 ? 'monitor degradado' : 'monitores degradados'}`, + href: `${base}/monitoring/monitors`, + icon: Activity, + }); + if (showVault && vaultMissing > 0) { + const envs = d.vault!.environments.filter((environment) => environment.missing > 0); + list.push({ + tone: 'warn', + text: `${vaultMissing} ${vaultMissing === 1 ? 'valor sin rellenar' : 'valores sin rellenar'} en ${envs.map((environment) => environment.name).join(', ')}`, + href: `${base}/vault/${envs[0].slug}`, + icon: LockKeyhole, + }); + } + if (cr && cr.services.stale > 0) + list.push({ + tone: 'warn', + text: `${cr.services.stale} ${cr.services.stale === 1 ? 'servicio sin analizar' : 'servicios sin analizar'} en 30 días`, + href: `${base}/code-report/services`, + icon: Clock, + }); + return list; + }); + + // ---------- accesos rápidos ---------- + + const quickActions = $derived( + [ + { + visible: showVault && d.can.createSecret, + label: 'Nuevo secreto', + href: `${base}/vault`, + icon: LockKeyhole, + }, + { + visible: showCodeReport && d.can.createService, + label: 'Añadir servicio', + href: `${base}/code-report/services`, + icon: Boxes, + }, + { + visible: showMonitoring && d.can.createMonitor, + label: 'Nuevo monitor', + href: `${base}/monitoring/monitors/new`, + icon: Activity, + }, + { + visible: d.can.createAlert, + label: 'Nueva alerta', + href: `${base}/settings/alerts/new`, + icon: Bell, + }, + { + visible: d.can.manageMembers, + label: $_('project.overview.inviteMembers'), + href: `${base}/settings/access-control`, + icon: UserPlus, + }, + { + visible: d.can.manageKeys, + label: $_('project.overview.addSecretToken'), + href: `${base}/settings/server-access-keys`, + icon: KeyRound, + }, + ].filter((action) => action.visible), + ); + + const inactiveModules = $derived( + [ + { key: 'codereport', label: 'Code Report', icon: BarChart3 }, + { key: 'vault', label: 'Vault', icon: LockKeyhole }, + { key: 'monitoring', label: 'Monitoring', icon: Activity }, + { key: 'stateiac', label: 'State IaC', icon: GitBranch }, + ].filter((module) => !d.modules[module.key as keyof Dashboard['modules']]), + ); + + // ---------- formato ---------- + + function relative(iso: string) { + const seconds = (new Date(iso).getTime() - Date.now()) / 1000; + const rtf = new Intl.RelativeTimeFormat($locale ?? 'es', { numeric: 'auto' }); + const units: [Intl.RelativeTimeFormatUnit, number][] = [ + ['day', 86_400], + ['hour', 3_600], + ['minute', 60], + ]; + for (const [unit, size] of units) { + if (Math.abs(seconds) >= size) return rtf.format(Math.round(seconds / size), unit); + } + return rtf.format(Math.round(seconds), 'second'); + } + + function percent(part: number, total: number) { + return total > 0 ? Math.round((part / total) * 100) : 100; + } + + const severityChips: { key: keyof Severity; letter: string; className: string }[] = [ + { key: 'critical', letter: 'C', className: 'k-badge-danger' }, + { key: 'high', letter: 'H', className: 'k-badge-brand' }, + { key: 'medium', letter: 'M', className: 'k-badge-warn' }, + { key: 'low', letter: 'L', className: '' }, ]; - const page = createPageStore(); {$_('project.layout.overview')} - {project.name} +{#snippet kpi( + href: string, + icon: Component, + label: string, + value: string | number, + detail: string, + tone = 'text-white', +)} + {@const Icon = icon} + +

    + {label} + +

    +

    {value}

    +

    {detail}

    +
    +{/snippet} +
    -
    -
    -
    - -
    -

    {project.name}

    -

    {$_('common.slug')}: {project.slug}

    -
    + +
    +
    +
    +

    {project.name}

    + + + {project.status === 'active' ? $_('common.active') : $_('common.inactive')} +
    - - - {project.status === 'active' ? $_('common.active') : $_('common.inactive')} - +

    + {project.description || $_('project.overview.noDescription')} +

    + + Ajustes del proyecto + +
    -
    -

    {$_('project.overview.description')}

    -

    {project.description || $_('project.overview.noDescription')}

    -
    -
    + + {#if showCodeReport || showMonitoring} +
    + {#if showCodeReport && d.codeReport} + {@const cr = d.codeReport} + {@const grade = cr.score !== null ? gradeOf(cr.score) : null} + {@const scanned = LEVELS.reduce((sum, level) => sum + cr.levels[level.key], 0)} +
    + {#if grade} +
    + {/if} +
    +

    + Seguridad del código +

    + Code Report +
    -
    -

    {$_('project.overview.activeModules')}

    + {#if grade && cr.score !== null} +
    + +
    + +
    + + {cr.score} + de 100 + +
    +
    +
    +

    + {grade.letter} · {grade.label} +

    +

    + {cr.totals.critical > 0 + ? `${cr.totals.critical} ${cr.totals.critical === 1 ? 'vulnerabilidad crítica abierta' : 'vulnerabilidades críticas abiertas'}` + : cr.exposedSecrets > 0 + ? `${cr.exposedSecrets} ${cr.exposedSecrets === 1 ? 'secreto expuesto' : 'secretos expuestos'} en el código` + : 'Sin vulnerabilidades críticas ni secretos expuestos'} +

    +

    + Media de {scanned} + {scanned === 1 ? 'servicio analizado' : 'servicios analizados'} según su nivel de riesgo. +

    +
    +
    - {#if activeModules.length === 0} -
    - {$_('project.overview.noActiveModules')} -
    - {:else} -
    + {/if} + + {#if showMonitoring && d.monitoring} + {@const mon = d.monitoring} +
    + {#if monitoringState} +
    + {/if} +
    +

    + Disponibilidad +

    + Monitoring +
    + + {#if monitoringState} +
    + + {#if monitoringState.tone === 'ok'}{:else if monitoringState.tone === 'neutral'}{:else}{/if} + +
    +

    {monitoringState.title}

    +

    + {mon.up} de {mon.total} operativos{#if mon.paused > 0} + · {mon.paused} en pausa{/if} +

    +
    - - - {/each} -
    - {/if} -
    - -
    -

    {$_('project.overview.guides')}

    -

    {$_('project.overview.guidesDescription')}

    - -
    + {/if} + + + {#if showCodeReport || showVault || showMonitoring || d.alerts} +
    + {#if showCodeReport && d.codeReport} + {@const cr = d.codeReport} + {@render kpi( + `${base}/code-report/dashboard`, + ShieldAlert, + 'Críticas', + cr.totals.critical, + cr.criticalDelta === null || cr.criticalDelta === 0 + ? 'Sin cambios en 7 días' + : `${cr.criticalDelta > 0 ? '+' : ''}${cr.criticalDelta} en 7 días`, + cr.totals.critical > 0 ? 'text-red-300' : 'text-white', + )} + {@render kpi( + `${base}/code-report/dashboard`, + TriangleAlert, + 'Altas', + cr.totals.high, + `${cr.totals.medium} medias · ${cr.totals.low} bajas`, + cr.totals.high > 0 ? 'text-brand-300' : 'text-white', + )} + {@render kpi( + `${base}/code-report/services`, + KeyRound, + 'Secretos expuestos', + cr.exposedSecrets, + 'Detectados en el código', + cr.exposedSecrets > 0 ? 'text-red-300' : 'text-white', + )} + {@render kpi( + `${base}/code-report/services`, + Boxes, + 'Servicios analizados', + `${cr.services.scanned}/${cr.services.total}`, + cr.services.stale > 0 ? `${cr.services.stale} sin analizar en 30 días` : 'Todos al día', + cr.services.stale > 0 ? 'text-amber-300' : 'text-white', + )} + {/if} + {#if showVault && d.vault} + {@render kpi( + `${base}/vault`, + LockKeyhole, + 'Secretos en Vault', + d.vault.secrets, + vaultMissing > 0 + ? `${vaultMissing} valores sin rellenar` + : `${d.vault.environments.length} entornos completos`, + vaultMissing > 0 ? 'text-amber-300' : 'text-white', + )} + {/if} + {#if d.alerts} + {@render kpi( + `${base}/settings/alerts`, + Bell, + 'Alertas activas', + `${d.alerts.enabled}/${d.alerts.total}`, + d.alerts.total === 0 ? 'Ninguna configurada' : 'Avisan por email y más canales', + )} + {/if} +
    + {/if} + + +
    +
    + {#if showCodeReport && d.codeReport} +
    +
    +

    Servicios con más riesgo

    + Ver todos
    -
    -

    {$_('project.overview.guidePrefix')} {module.label}

    -

    {module.description}

    + {#if d.codeReport.riskiest.length === 0} +
    + Ningún servicio tiene vulnerabilidades + abiertas. +
    + {:else} + {@const top = Math.max(...d.codeReport.riskiest.map((service) => service.riskScore), 1)} + + {/if} +
    + {/if} + + {#if showMonitoring && d.monitoring && d.monitoring.monitors.length > 0} +
    +
    +

    Monitores

    + Ver todos +
    +
      + {#each d.monitoring.monitors as monitor (monitor.id)} + {@const style = statusStyle(monitor.status)} +
    • + + + {monitor.name} + +
      + {#if monitor.hourlyBars.length > 0} + + {/if} +
      +
      + {formatUptime(monitor.uptime24h)} + {$_(`monitoring.status.${monitor.status}`)} +
      +
    • + {/each} +
    +
    + {/if} + + {#if showVault && d.vault && d.vault.secrets > 0} +
    +
    +

    Secretos por entorno

    + Abrir Vault
    - - - {/each} + +
    + {/if}
    -
    - -
    -

    {$_('project.overview.quickAccess')}

    - -
    + {/if} + + {#if showCodeReport && d.codeReport} +
    +
    +

    Últimos análisis

    + Historial
    - - - {/each} -
    -
    + {#if d.codeReport.recent.length === 0} +

    + Los análisis aparecerán aquí cuando tu pipeline envíe el primero. +

    + {:else} + + {/if} + + {/if} + +
    +

    + {$_('project.overview.quickAccess')} +

    + {#if quickActions.length === 0} +

    + No tienes acciones disponibles en este proyecto. +

    + {:else} + + {/if} +
    + +
    + + + {#if inactiveModules.length > 0 && d.can.updateProject} +
    +
    +

    Productos sin activar

    +

    Actívalos desde los ajustes del proyecto.

    +
    +
    + {#each inactiveModules as module (module.key)} + {module.label} + {/each} +
    + Activar +
    + {/if}
    diff --git a/src/routes/org/[org]/projects/[slug]/settings/alerts/[id]/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/alerts/[id]/+page.svelte index f35bb4a6..87b53708 100644 --- a/src/routes/org/[org]/projects/[slug]/settings/alerts/[id]/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/settings/alerts/[id]/+page.svelte @@ -1,25 +1,8 @@ - - {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} - GitOps - - -
    -
    -

    - {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} -

    -

    {$_('alerts.editor.subtitle')}

    -
    - {#key data.alertId} - - {/key} -
    + diff --git a/src/routes/org/[org]/projects/[slug]/settings/alerts/new/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/alerts/new/+page.svelte index f35bb4a6..87b53708 100644 --- a/src/routes/org/[org]/projects/[slug]/settings/alerts/new/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/settings/alerts/new/+page.svelte @@ -1,25 +1,8 @@ - - {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} - GitOps - - -
    -
    -

    - {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} -

    -

    {$_('alerts.editor.subtitle')}

    -
    - {#key data.alertId} - - {/key} -
    + diff --git a/src/routes/org/[org]/projects/[slug]/settings/audit/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/audit/+page.svelte index 8a0fcfe5..d3af036e 100644 --- a/src/routes/org/[org]/projects/[slug]/settings/audit/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/settings/audit/+page.svelte @@ -8,16 +8,23 @@
    -
    -

    {$_('projectSettings.audit.title')}

    -

    {$_('projectSettings.audit.description')}

    -
    +
    +

    + {$_('projectSettings.audit.title')} +

    +

    {$_('projectSettings.audit.description')}

    +
    -
    - -

    {$_('projectSettings.audit.comingSoon')}

    -

    {$_('projectSettings.audit.comingSoonDescription')}

    +
    + + + +

    + {$_('projectSettings.audit.comingSoon')} + {$_('common.comingSoon')} +

    +

    + {$_('projectSettings.audit.comingSoonDescription')} +

    diff --git a/src/routes/org/[org]/projects/[slug]/settings/overview/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/overview/+page.svelte index 4c825209..dead24b3 100644 --- a/src/routes/org/[org]/projects/[slug]/settings/overview/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/settings/overview/+page.svelte @@ -1,23 +1,27 @@ {$_('projectSettings.overview.title')} - {project.name} -
    - {#if error} -
    - {error} -
    - {/if} - - {#if success} -
    - {success} +
    +
    +
    +
    +

    {project.name}

    + {#if isArchived} + {$_('projectSettings.overview.archivedBadge')} + {/if} +
    +

    {$_('projectSettings.overview.subtitle')}

    - {/if} + +
    -
    + -
    - {#if isArchived} - - - {$_('projectSettings.overview.archivedBadge')} - - {/if} - -
    - -
    -
    -
    - - {#if canUpdate} - - {:else} -

    - {project.name} -

    - {/if} -
    - -
    - - {#if canUpdate} - - {:else} -

    - {project.slug} -

    - {/if} -
    + +
    +
    +

    {$_('projectSettings.overview.general')}

    +

    + {$_('projectSettings.overview.generalDescription')} +

    - -
    - +
    {#if canUpdate} - - {:else} -

    + {#snippet children(control)} + + {/snippet} + + + {#snippet children(control)} + + {/snippet} + + - {project.description || $_('projectSettings.overview.optionalDescription')} -

    + {#snippet children(control)} + + {/snippet} + + {:else} +
    +
    +
    {$_('common.name')}
    +
    {project.name}
    +
    +
    +
    {$_('common.slug')}
    +
    {project.slug}
    +
    +
    +
    {$_('common.description')}
    +
    + {project.description || $_('projectSettings.overview.noDescription')} +
    +
    +
    {/if}
    -
    - -
    -

    {$_('projectSettings.overview.modules')}

    -

    - {$_('projectSettings.overview.modulesDescription')} -

    +
    -
    + +
    +
    +

    {$_('projectSettings.overview.modules')}

    +

    + {$_('projectSettings.overview.modulesDescription')} +

    +
    +
      {#each moduleOptions as option (option.key)} - {@const moduleEnabled = editModules[option.key] && !option.soon} -
    -
    + + {#if canUpdate} -
    - + {/if} +
    {/if} -
    -
    -

    + +
    +
    +

    {$_('projectSettings.overview.integrations')} -

    -

    +

    +

    {$_('projectSettings.overview.integrationsDescription')}

    - -
    + {#if canUpdate || data.canDelete} -
    -
    -

    +
    +
    + +

    {$_('projectSettings.overview.dangerZone')} -

    +

    - -
    +
      {#if canUpdate} -
      +
    • -

      +

      {$_('projectSettings.overview.transferToOrganization')}

      -

      +

      {$_('projectSettings.overview.transferDescription')}

      -
    • - -
      + +
    • -

      +

      {isArchived ? $_('projectSettings.overview.activateProject') : $_('projectSettings.overview.archiveProject')}

      -

      +

      {isArchived ? $_('projectSettings.overview.activateDescription') : $_('projectSettings.overview.archiveDescription')} @@ -524,165 +449,131 @@

      -
    • + {/if} - {#if data.canDelete} -
      +
    • -

      +

      {$_('projectSettings.overview.deleteProject')}

      -

      +

      {$_('projectSettings.overview.deleteDescription')}

      -
    • + {/if} -
    +
    {/if}
    -{#if archiveModalOpen} - -
    - -
    -{/if} - -{#if deleteModalOpen} - -
    - -
    -{/if} + + {/snippet} + + + + {#snippet icon()} + + {/snippet} +
    + + + {#snippet children(control)} + + {/snippet} + +
    + {#snippet footer()} + + + {/snippet} +
    diff --git a/src/routes/org/[org]/projects/[slug]/settings/server-access-keys/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/server-access-keys/+page.svelte index 9c68eb76..790cc2fc 100644 --- a/src/routes/org/[org]/projects/[slug]/settings/server-access-keys/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/settings/server-access-keys/+page.svelte @@ -1,5 +1,18 @@ @@ -75,213 +150,347 @@
    -
    -
    -
    -

    - {$_('projectSettings.serverAccessKeys.title')} -

    -

    - {$_('projectSettings.serverAccessKeys.descriptionPrefix')} - POST /api/code-report/analyse-result. -

    -
    - {#if data.canCreate} - - {/if} +
    +
    +

    + {$_('projectSettings.serverAccessKeys.title')} +

    +

    + {$_('projectSettings.serverAccessKeys.descriptionPrefix')} + {ENDPOINT}. +

    -
    + {#if data.canCreate} + + {/if} + {#if form?.error} -

    {form.error}

    - {/if} - - {#if form?.createdKey} -
    -
    -
    -

    {$_('projectSettings.serverAccessKeys.copyTokenNow')}

    - {form.createdKey} -
    - -
    -
    + {/if} -
    - {#if data.apiKeys.length === 0} -
    - -

    +

    + {#if keys.length === 0} +
    + + + +

    {$_('projectSettings.serverAccessKeys.noKeys')}

    +

    + {$_('projectSettings.serverAccessKeys.emptyHelp')} +

    + {#if data.canCreate} + + {/if}
    {:else} - {#each data.apiKeys as key (key.id)} -
    -
    -

    {key.name}

    -

    - {$_('projectSettings.serverAccessKeys.prefix')}: {key.keyPrefix} · {$_( - 'projectSettings.serverAccessKeys.created', - )} - {formatDateTime(key.createdAt)} · {$_('projectSettings.serverAccessKeys.expires')} - {formatDateTime(key.expiresAt)} -

    -

    - {$_('projectSettings.serverAccessKeys.role')}: {(key.roleId && - roleNameById.get(key.roleId)) ?? - '—'} · {$_('projectSettings.serverAccessKeys.lastUsed')}: {formatDateTime( - key.lastUsedAt, - )} -

    -

    - {$_('projectSettings.serverAccessKeys.state')}: {keyState(key)} -

    -
    - - {#if !key.revokedAt && (data.canUpdate || data.canDelete)} -
    - {#if data.canUpdate} -
    - - -
    - {/if} - {#if data.canDelete} -
    - -
    {/if}
    -{#if createModalOpen} -
    -
    -

    - {$_('projectSettings.serverAccessKeys.createServerAccessKeyShort')} -

    - -
    -
    - - -
    - -
    - - + {/snippet} + + + {#snippet children(control)} + -

    - {$_('projectSettings.serverAccessKeys.roleHint')} -

    -
    - -
    - - -
    + {/each} +
    + {#if expiresInDays === ''} +

    + {$_('projectSettings.serverAccessKeys.neverWarning')} +

    + {/if} + + + {#snippet footer()} + + + {/snippet} + -
    - - -
    - + + + {#snippet icon()} + + {/snippet} +
    +
    + event.currentTarget.select()} + /> + +
    +
    +

    {$_('projectSettings.serverAccessKeys.usage')}

    +
    curl -X POST "$GITOPS_URL/api/code-report/analyse-result" \
    +  -H "Authorization: Bearer $GITOPS_TOKEN" \
    +  -H "Content-Type: application/json" \
    +  -d @report.json
    -{/if} + {#snippet footer()} + + {/snippet} +
    + + + + {#snippet icon()} + + {/snippet} + {#snippet footer()} + + + {/snippet} + + + + + {#snippet icon()} + + {/snippet} + {#snippet footer()} + + + {/snippet} + diff --git a/src/routes/org/[org]/projects/[slug]/vault/+page.svelte b/src/routes/org/[org]/projects/[slug]/vault/+page.svelte index 77b4e54a..96c26336 100644 --- a/src/routes/org/[org]/projects/[slug]/vault/+page.svelte +++ b/src/routes/org/[org]/projects/[slug]/vault/+page.svelte @@ -1,27 +1,29 @@ Vault - GitOps - -
    - {#if success} -
    - {success} +
    +
    +

    Secretos

    +

    + Variables cifradas por entorno de {data.project?.name ?? projectSlug}. Cada cambio queda + como un commit en GitDB. +

    - {/if} -
    -
    - - - - - - {data.project?.name ?? projectSlug} - - - / - -
    - - - {#if environmentMenuOpen} -
      - {#each data.environments as environment (environment.id)} -
    • - -
    • - {/each} -
    - {/if} -
    +
    + + - {#if currentPath !== '/'} - / - {currentPath.replace(/^\//, '')} + {#if data.canManageSecrets} +
    + + + {#snippet trigger(props)} + + {/snippet} + Nueva carpeta + Enlazar carpeta + Importar .env + Copiar desde otro entorno + +
    {/if}
    +
    + +
    +
    + {#if data.environments.length > 0} +
    + ({ + value: candidate.slug, + label: candidate.name, + }))} + onchange={selectEnvironment} + /> +
    + {/if} -
    -
    - - -
    - -
    - - + {/each} + +
    + +
    + + +
    +
    + {#if isProduction && data.canManageSecrets} +
    + Estás editando el entorno + {environmentName}: los cambios afectan a producción. +
    + {/if} + +
    + {#if isEmpty && !currentFolderId} +
    + 🦊 +

    Aún no hay secretos en {environmentName}

    +

    + {#if data.canManageSecrets} + Crea el primero, arrastra aquí un archivo .env o copia los + valores de otro entorno. + {:else} + Cuando alguien del proyecto añada secretos, aparecerán aquí. + {/if} +

    {#if data.canManageSecrets} -
    - - - {#if actionsMenuOpen} - + Copiar de otro entorno + {/if}
    {/if}
    -
    - -
    + {:else}
    - - - - - - +
    KeyValue
    + + + + + - - {#if filteredFolders.length === 0 && filteredSecrets.length === 0} - - + {#if currentFolderId} + goToFolder(parentFolder)} + > + - {:else} - {#if currentFolderId} - goToFolder(parentFolder)} - > - goToFolder(folder)} + > + - - - - {/if} - {#each filteredFolders as folder (folder.id)} - goToFolder(folder)} - > - + + + {/each} + + {#each filteredSecrets as secret (secret.id)} + {@const value = secret.values?.[environmentSlug]} + {@const shown = revealed[revealKey(secret)]} + + - - - - {/each} - {#each filteredSecrets as secret (secret.id)} - - - + - + - - {/each} + + + + {/each} + + {#if filteredFolders.length === 0 && filteredSecrets.length === 0} + + + {/if}
    ClaveValor · {environmentSlug}Acciones
    - No hay carpetas ni secretos en esta vista. +
    + event.stopPropagation()} + > + + .. +
    + {/if} + + {#each filteredFolders as folder (folder.id)} + {@const linkTarget = folder.linkedFolderId ? linkedPath(folder) : null} +
    + event.stopPropagation()} + > - - .. + {#if folder.linkedFolderId}{:else}{/if} - - -
    - {folder.name} + {#if linkTarget} + → {linkTarget} + {/if} + + +
    + {#if data.canDeleteSecrets} + + {/if} + +
    +
    +

    {secret.key}

    + {#if secret.description} +

    - {#if folder.linkedFolderId} - - {:else} - - {/if} - {folder.name} - -

    -
    - {#if data.canDeleteSecrets} - - {/if} - -
    -
    - -

    {secret.key}

    - {#if secret.description} - - - - {secret.description} - - - - {/if} -
    -
    + {secret.description} +

    + {/if} +
    + {#if !value} + Sin valor + {:else} - + {/if} + +
    + {#if value} + + + {/if} {#if data.canManageSecrets} {/if} {#if data.canDeleteSecrets} {/if} -
    + {query + ? `Nada coincide con «${searchQuery.trim()}».` + : 'Esta carpeta está vacía.'} +
    -
    - {#if data.canManageSecrets} -
    (dropActive = true)} - on:dragover|preventDefault|stopPropagation={() => (dropActive = true)} - on:dragleave|preventDefault|stopPropagation={handleDragLeave} - on:drop|preventDefault|stopPropagation={handleDrop} - class="flex min-h-40 flex-col items-center justify-center rounded-md border-2 border-dashed px-4 py-16 text-center transition {dropActive - ? 'border-slate-400 bg-slate-50' - : 'border-slate-200 bg-white'}" - > -

    - Drag and drop .env, or - -

    -

    - OR + {#if data.canManageSecrets} +

    + + Arrastra aquí un archivo .env, o fileInput?.click()}>elígelo -

    - {#if dropError} -

    {dropError}

    - {/if} -
    + {#if otherEnvironments.length > 0} + · + {/if} +
    + {/if} + {/if} + + {#if dropActive} +

    + Suelta el archivo para importarlo en {environmentName} +

    {/if} - +
    + + {#if data.canManageSecrets} + + {/if}
    -{#if createSecretOpen} -
    -
    + + + ['Secreto creado', `${newSecretKey} · ${environmentSlug}`])} + > + + -

    Crear secreto

    - {#if formError}

    - {formError} -

    {/if} - -
    - -
    -{/if} - -{#if editingSecret} -
    + {/if} + + {#snippet footer()} + + + + {/snippet} + + + + {#if editingSecret}
    ['Secreto guardado', `${editSecretKey} · ${environmentSlug}`])} > - - {#each data.environments as environment (environment.id)} - {#if environment.slug !== selectedEnvironmentSlug} - - {/if} + + {#each otherEnvironments as other (other.id)} + {/each} -

    Detalle del secreto

    - {#if formError}

    - {formError} -

    {/if} -
    - - - -
    -
    - -
    + {...control}> + {/snippet} +
    -
    -{/if} - -{#if deletingSecret} -
    + {/if} + {#snippet footer()} + + + {/snippet} + + + + {#snippet icon()} + + {/snippet} + {#snippet footer()} -
    -{/if} - -{#if deletingFolder} -
    + + + {/snippet} + + + + {#snippet icon()} + + {/snippet} + {#snippet footer()} -
    -{/if} - -{#if createFolderOpen} -
    -
    (deleteFolderOpen = false)} + >Cancelar -

    Crear carpeta

    - {#if formError}

    - {formError} -

    {/if} - -
    - -

    - Se creara en {currentPath} -

    -
    -
    - -
    -
    -
    -{/if} - -{#if linkFolderOpen} -
    -
    Borrar carpeta -

    Enlazar carpeta

    - {#if formError}

    - {formError} -

    {/if} - -
    - -
    -
    - -
    -
    -
    -{/if} - -{#if importOpen} -
    -
    + + + ['Carpeta creada', newFolderName])} + > + + + {#snippet children(control)} + + {/snippet} + + + {#snippet footer()} + -

    Importar secretos

    -

    - Pega el contenido de un archivo .env para el entorno {selectedEnvironment?.name ?? - selectedEnvironmentSlug}. -

    - {#if formError}

    - {formError} -

    {/if} - - - -
    - -
    - -
    -{/if} - -{#if copyEnvOpen} -
    -
    Crear carpeta -

    Copiar desde otro entorno

    -

    - Copia los valores de los secretos de {currentPath} hacia - {selectedEnvironment?.name ?? selectedEnvironmentSlug}. -

    - {#if formError}

    - {formError} -

    {/if} - -