Skip to content

Latest commit

 

History

History
825 lines (740 loc) · 63.5 KB

CLAUDE.md

File metadata and controls

825 lines (740 loc) · 63.5 KB

CLAUDE.md

Guidance for working on GitOps, an open source internal developer platform built with SvelteKit.

Product

GitOps combines identity and access management, organizations and projects, Open Report security analysis, and Pulumi State visibility. The Vault route is currently a UI foundation and does not yet provide a complete secrets backend. SAML settings are configuration only.

Google SSO is system-wide and configured only through environment variables (GOOGLE_SSO_CLIENT_ID, GOOGLE_SSO_CLIENT_SECRET, optional GOOGLE_SSO_ALLOWED_DOMAINS and GOOGLE_SSO_AUTO_PROVISION), read on every request by readGoogleSsoConfig() from src/modules/auth/infrastructure/config/google-sso.config.ts into a GoogleSsoConfig domain object; nothing is persisted in GitDB. When both credentials are set and the config is valid, /auth/login shows "Continue with Google" next to the password form, and each organization's /org/<org>/settings/global shows Google SSO as enabled (read-only status, credentials never exposed). A misconfigured provider (missing credential, invalid domain, inconsistent auto-provision settings) silently counts as disabled and logs the reason; the UI never breaks. ssoService in $modules/auth runs Authorization Code + PKCE through /auth/sso/google/start and /auth/sso/google/callback (both allow unauthenticated access in hooks.server.ts), verifies the ID token against Google's JWKS via GoogleOidcClient, and signs in any existing, non-disabled user found by Google sub or verified email, linking the sub in user.authProviders[] and accepting pending invitations on first sign-in. Allowed domains are checked against the Workspace hd claim, not the email suffix. With GOOGLE_SSO_AUTO_PROVISION=true (requires at least one allowed domain), an unknown Workspace account of an allowed domain gets an active GitOps User (cluster-user) account with no organization membership through userAccessService.provisionClusterUser(); organizations still have to invite it. user.disabled is currently enforced only by Google sign-in.

Self-service registration (/auth/registration) lets a visitor create a plain GitOps User (cluster-user) account with no organization membership. It is gated by a system-wide toggle managed at /gitops-settings/registration (persisted via clusterSettingsService in $modules/config, off by default) and re-checked server-side on submit so it can't be bypassed while disabled. Once registered and signed in, the user lands on /org, where the cluster:organization:create permission (granted to cluster-user by default) surfaces a "New Organization" action that creates the organization, provisions its default roles, and grants the creator the org-admin role so they can manage what they just created.

Password recovery: /auth/recover-password accepts an email and, via passwordResetService in $modules/auth, emails a time-limited reset link (password-reset template, 1 hour TTL, hashed token stored on the user) without revealing whether the address is registered. The link lands on /auth/reset-password?token=..., which sets a new password and redirects back to /auth/login.

The roadmap is in IDEAS.md. Do not describe roadmap items as implemented features.

Stack and commands

  • SvelteKit 2, Svelte 5, Vite 8, TypeScript 6 strict mode
  • Tailwind CSS 4 and @lucide/svelte
  • Internationalization via Paraglide JS (Spanish and English)
  • Bun package manager; do not use npm or yarn
  • GitDB (@getgitops/gitdb) as the only persistence layer
  • Vitest, ESLint, and Prettier
  • Playwright for RBAC end-to-end tests (e2e/)

Environment variables are declared in src/env.ts and documented in .env.example; Google SSO uses the GOOGLE_SSO_* variables described above, "Add to Slack" uses SLACK_CLIENT_ID / SLACK_CLIENT_SECRET, and the /gitops Slack command also needs SLACK_SIGNING_SECRET. GITOPS_ENVIRONMENT (local | development | production) picks the favicon (static/favicons/), see src/lib/server/app-environment.ts.

Email notification templates (src/notifications/) are read from disk at runtime; the Docker image copies them so emails can be sent from the container.

bun install
bun run dev
bun run build
bun run check
bun run lint
bun run test
bun run test:e2e
bun run test:e2e:ui
bun run format:check

Tests use Vitest through bun run test. Do not use the native bun test runner: it does not load the Vite/SvelteKit aliases and plugins used by this project.

Import aliases (tsconfig.json): Use $modules for business logic modules, $lib for shared components and utilities, and relative paths for route-local imports. Examples: import { userService } from '$modules/auth' (not ../../modules/auth), import Button from '$lib/components/Button.svelte'.

bun run test:e2e runs the Playwright RBAC suite under e2e/ (requires bunx playwright install --with-deps chromium once). e2e/global-setup.ts creates its own throwaway local GitDB repository, seeds every persona the permission matrix needs, and starts the dev server against it — it never touches the repository configured in .env. Session cookies are 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 (<a>, <button type="submit">…), so do not wrap them in components. They live in @layer components, so Tailwind utilities can adjust them (k-input h-9 pl-9).
  • Anything with behavior, focus or ARIA → #lib/components/ui (import from the index): Modal, Drawer, DropdownMenu + MenuItem, Select, Field, Switch, Tabs (underline / segmented), TagInput, CommandPalette, toast + Toaster. Never hand-roll outside click, Esc, focus trapping or scroll locking in a page; ui/overlay.ts already does it (Esc only closes the top-most overlay).
  • Every form control goes inside Field (label, help and error wired with aria-describedby / aria-invalid); spread the snippet argument on the control: <input class="k-input" {...control} />.
  • A submit button in a Modal footer lives outside the <form>: give the form an id and the button form="that-id". Put data-autofocus on the field that should get the initial focus.
  • Select and Switch accept name and add a hidden input, but they need JavaScript. Forms that must work without JS keep a native <select class="k-input"> / <input type="checkbox" class="k-checkbox">.
  • Creating something from a list opens a Modal instead of navigating; keep the /new route for direct links and no-JS, and post the modal form to that route's actions with local result handling (see monitoring/NewMonitorModal.svelte + MonitorForm variant="modal").
  • Page pattern (see project settings): <header> with h1.text-2xl + text-fg-muted description and the primary action on the right; content in k-cards; success/error feedback with toast, not inline banners; every destructive action (delete, revoke, rotate, remove access) confirms in a Modal (role="alertdialog"), and deleting a top-level entity asks to type its name.
  • Floating panels (DropdownMenu, Select, TagInput suggestions) render in <body> through floating in ui/overlay.ts, so no overflow (tables, modal bodies) clips them.
  • Alerts: email targets live in recipients (userIds/roleIds/emails) and chat or webhook targets in channelIds (notification channels); channels is derived on save. Create/edit happens in AlertWizard (modal); the /new and /[id] pages keep the no-JS editor (AlertEditor), so new alert fields must be added to both.
  • toast.* is client-only (module state): call it from event handlers, never during SSR.
  • Tokens: bg-ink-950…500, brand-50…900, text text-fg|fg-muted|fg-subtle, status ok|warn|danger|info (always with an icon or text, never as a chart series), chart series series-1…5 in that fixed order. Use bg-snow for pure white: legacy app.css overrides .bg-white, .bg-white/15|70|80|90, .border-white/15|60, .text-slate-*, .shadow-sm|md|xl with !important, so avoid those classes in v3 code.
  • App shell (migrated to v3): +layout.svelte renders AppNavbar (logo, ⌘K search, docs, account menu with "Ajustes de GitOps" for cluster admins) and AppSidebar as in the /brand mock: context switcher (projects grouped by organization, with search, and one "Ver todos los proyectos" link for the selected organization), flat sections (Proyecto: Dashboard + each enabled product + Ajustes; Organización), and SidebarFooter (version, GitDB status, collapse). There is no page footer. A module with several pages shows them as tabs (#section-nav) above the content. The tree lives in #lib/navigation.ts (buildNavigation) and feeds the sidebar, the tabs and the search: add new routes there with their permission flag (sidebar: false keeps a category out of the sidebar). The same tree builds the breadcrumbs above the tabs (org › project › module › page); project pages have no header of their own. The layout mounts CommandPalette and Toaster once; do not add another in a page. Collapsed mode is stored in localStorage (gitops-sidebar-collapsed); below md the sidebar is off-canvas. Auth, bootstrap and /brand keep the bare layout. The sidebar must stay the first <aside> in the DOM (sidebar-visibility.spec.ts). Pages inside the shell are still v2 until migrated one by one.
  • Logo files are in static/brand/ (gitops-logo-dark|light.svg, gitops-mark-*.svg, gitops-icon.svg and PNGs). The navbar uses the new logo; the old gitops_logo*.png, icono_*.png and favicon.png are still used elsewhere (favicon, auth pages).
  • Legacy: #lib/components/Dropdown.svelte and the btn-* / field-input classes are v2; replace them with the v3 equivalents when a screen is migrated, not piecemeal.
  • e2e/specs/brand-ui.spec.ts covers keyboard, focus and closing behavior of the UI components; extend it when you change them.

Architecture

Business logic lives in src/modules/<module>/:

 domain/                    entities, business rules, and data constants
 application/               use cases and services
 infrastructure/            repositories and adapters
 index.ts                   public API and composition root

Domain layers include entity classes (e.g., *.domain.ts) and centralized data files (e.g., *.data.ts) for configuration constants: role permissions, default project settings, risk weights, and tool policy mappings.

Current modules include auth, config, organization, projects, state-iac, code-report, vault, audit, alerts, monitoring, and notifications. The notifications module handles external email recipients of alerts (allowed domains, verification tokens, unsubscribe tracking). Shared infrastructure lives in src/lib/. Routes should import module APIs from their index.ts, not internal layers.

GitDB is the single source of truth. Users, roles, API keys, organizations, projects, storage metadata, and code reports are GitDB entities in the repository configured by GITDB_REPOSITORY_URL. Writes become auditable Git commits. Use getGitDb() and the schemas in src/lib/database/schemas.ts; do not add another database or persistence backend without an architecture discussion and migration plan. The client behind getGitDb() is one per process (kept on globalThis): in dev the server code is evaluated by more than one Vite module runner, and a second client would keep its own cache over the same clone.

GITDB_REPOSITORY_URL supports both HTTPS and SSH URLs (e.g., git@github.com:user/repo.git). The Docker image includes openssh-client and pre-configures the SSH key fingerprints for GitHub, Bitbucket, and GitLab; in production, ensure SSH authentication credentials are available via SSH_AUTH_SOCK or a mounted SSH directory.

ORIGIN environment variable pins the application's public origin (e.g., http://localhost:3000). SvelteKit's CSRF Origin check depends on this value instead of deriving it from the incoming Host header, preventing bypasses when running behind a proxy that rewrites Host headers. It is also the origin of the absolute links in emails (absoluteUrl()); only under vite dev do those links use the origin of the requests the dev server receives instead (rememberDevOrigin() in hooks.server.ts), so they work on port 5173 whatever ORIGIN says.

State IaC

$modules/state-iac reads IaC state from the buckets where teams keep it; design and Pulumi DIY layout in docs/adr/0003-state-iac.md, anonymized real buckets in test/fixtures/state-iac/ (load them with fixtureStore() from application/testing.ts). GitDB only stores configuration: state_backends (one bucket/prefix per row, per organization; credentials AES-GCM encrypted with the backend id as AAD, never returned, only hasCredentials) and state_bindings (one per Pulumi project of a backend → a GitOps project of the same organization; stacks empty = all). Bindings go with their backend and with their GitOps project (registerStateIac() listens to project.deleted). Buckets are only read through ObjectStore (GcsObjectStore, S3ObjectStore, InMemoryObjectStore in tests): never add a write. Org settings page /org/<org>/settings/state-iac and /api/state-iac/backends/** check organization:stateiac:backends:<action> (actions include test); a backend of another organization answers 404. Read failures are stored as short codes in lastError (access_denied, bucket_not_found…), never the provider message.

Reading states: stateIacService uses a StateEngine (PulumiStateEngine: both layouts, .gz) that turns checkpoints and history into the normalized model in domain/iac.model.ts; secrets are replaced by { $iac: 'secret' } while parsing (pulumi-state.ts), and secrets_providers, emails and local paths never leave it. A project sees only the stacks its bindings cover (any other stack is a 404) with project:stateiac:stacks:read, and resources/outputs need project:stateiac:states:read; the project page /org/<org>/projects/<slug>/state-iac is a per-stack dashboard (?stack=<backend>/<project>/<stack>). The organization has no stacks page for now, but GET /api/state-iac/stacks?organizationId= lists every stack with organization:stateiac:stacks:read. Listings are cached for STATE_IAC_CACHE_SECONDS and states by object version, so an unchanged state is read once; ?refresh=1 skips the cache. States over STATE_IAC_MAX_STATE_MB fail with too_large. In e2e the dev server reads the fixtures through a local S3 endpoint (e2e/fixtures/fake-s3.ts, seeded backend e2e-shared-state: acme-infra → primary project, acme-platform → secondary project). History and diff: stateIacService.history() pages *.history.json (project:stateiac:history:read); diff() compares two snapshot sources (current, history:<ns>, backup:<ns>, retained:<ns>, previous, version:<object version> from ObjectStore.listVersions) with diffSnapshots() in application/state-diff.service.ts (project:stateiac:states:read), by default the last update against the one before. Two secrets always compare equal (Pulumi re-encrypts them on every write); provider-only changes are flagged providerOnly. Past sources are cached for good, the current one by object version. Periodic scans and state_iac.stack.* events are not built (ADR 0003, deferred).

Domain events

Services announce what happened on an in-process event bus in #lib/server/events; the design is in docs/adr/0001-event-bus-and-alerts.md.

  • Names: <module>.<resource>.<action>, snake_case, past participle (code_report.analysis.completed, vault.secret.created, access.granted). Declare each type and its payload in DomainEventMap (src/lib/events/domain-events.ts, shared with the client).
  • Every event needs an EventDefinition in the catalog (src/lib/events/catalog/, one <module>.events.ts per module): scope, readPermission, alertable and its filterable fields. EVENT_CATALOG is exhaustive and field keys without derive are checked against the payload at compile time. Labels are i18n keys (events.<type>.label, .description, .fields.<key>, events.options.<group>.<value>) and must exist in es.json and en.json (enforced by a test).
  • Publish only after the GitDB write succeeded, with the right scope (organizationId / projectId). publish() returns immediately; handlers run asynchronously, in order per subscriber, and a failing handler is only logged. Use publishAfterWrite (#lib/server/events/publish) so resolving the scope or publishing can never fail a write that already succeeded; resolveProjectScope adds the organization to project events.
  • Delivery is at-most-once and per process; events are not persisted.
  • The actor comes from the request context (userId / apiKeyId set in hooks.server.ts), falling back to system.
  • Inject EventBus through the service constructor from the module's index.ts; only composition roots import the eventBus singleton. In unit tests use RecordingEventBus from #lib/server/events/testing.
  • Payloads never contain secrets (vault values, invitation/reset tokens or URLs, hashes, API keys), and alert recipients are always filtered with cancanService.
  • eventLog (#lib/server/events) keeps recent events in memory for /org/<org>/settings/events, where users with organization:events:read see the events they are allowed to read (each definition's readPermission, checked in the event's project or organization) and, with organization:events:update, acknowledge them. Only the default Organization Admin role gets organization:events:all; existing roles are not migrated (enable it from the role editor). Retention: GITOPS_EVENTS_EXPIRATION (default 7d). It is per process and cleared on restart.

Alerts

$modules/alerts turns domain events into emails.

  • AlertEntity (GitDB alerts): an alert watches one eventType from an organization (scope: 'organization', covers every project of it) or a project. conditions ({ field, operator, value }) use the catalog fields, combined with match: 'all' | 'any'; an empty list always matches. Organization alerts on project events also get a projectId field (listAlertFields, value taken from the event scope). Email recipients are in recipients (users, roles, external emails); chat and webhook targets are in channelIds (references to NotificationChannelEntity), not in recipients (a channel delivers to its configured destination, not to individual recipients).

  • AlertService validates every write against the catalog and the location and throws AlertValidationError with field-level codes (conditions.0.operator: 'invalid_operator'): alertable event compatible with the scope, operators of the field, typed values, references and recipients (users, roles, emails) inside the location, channels in the location, and anti-escalation (the author must hold the event's readPermission).

  • AlertEngine subscribes to '*' once per process (registerAlertEngine() in hooks.server.ts, HMR-safe). Per event: fixed system notifications first (system-notifications.data.ts: access granted/updated/revoked to the affected user, new personal API keys to their owner, a self-disabled notification channel to its creator, never to the actor, invitations skipped), then the enabled alerts of that type (cached 60 s, invalidated by the service) whose location covers the event and whose conditions match. A per-alert in-memory throttle (throttleMinutes) suppresses repeats and the next email reports how many were skipped.

  • Recipients = selected users ∪ members with the selected roles, minus disabled users and users without an email, then filtered with cancanService.can(userId, readPermission, event scope) (most-specific-wins applies). One email per recipient (AlertMailNotifier); a failed email only affects that recipient. An organization alert and a project alert on the same event fire independently.

  • Email (#lib/server/infra/notifications): every email is wrapped by renderEmail() in src/notifications/email/_layout.html (header, content, footer with the reason and a manage link). Alerts use alert.html (field table built from the catalog) unless the definition sets mailTemplate (alert-code-report-analysis.html); link(context) gives the app path of the resource and mailSummary(payload) the subject summary ([GitOps] <alert>: <summary>). System notices use system-access-changed.html / system-security-notice.html. Escape every user or event value with {{ }}; {{{ }}} only for HTML built internally with renderTemplateString. Texts are alerts.email.*, in the recipient's locale or English. Links are absolute with ORIGIN (absoluteUrl()), omitted without it. These functions never reach the client: the catalog endpoint strips them.

  • Sending: alert and system emails go through mailQueue (concurrency 3, withRetry 4 attempts 1 s → 4 s → 16 s with jitter, only for isRetryableMailError: network errors and 4xx replies). Definitive failures are logged by createLogger('mail') with the alert, the event and a recipient hash, never the content or the address. registerMailShutdown() drains it on sveltekit:shutdown (10 s). Invitations and password resets call notify() directly: their tokens must not travel through the bus or the queue. Without SMTP (isMailConfigured()), the engine skips emails and system notifications (debug log) but still posts to channels, warns once at startup and the alert pages show a banner. MailQueue is a DeliveryQueue (#lib/server/infra/notifications/delivery-queue.ts), the generic queue channels reuse.

  • HTTP: #lib/server/alerts (access.ts for permissions/location/actor, operations.ts shared by the API and form actions). Routes: GET /api/events/catalog, GET|POST /api/alerts, GET|PATCH|DELETE /api/alerts/[id], POST /api/alerts/[id]/test and POST /api/alerts/test (dry runs that never touch the throttle; with send: true, AlertEngine.sendTest() also emails the recipients a real event would reach, members filtered by cancan and verified externals only, with a [Test] subject, and posts to the alert's channels; needs SMTP unless the alert has channels (then only they get it), test messages never count toward a channel's failure streak, and it is limited to 5 per caller every 10 minutes, in memory. It also registers the draft's new external addresses, so they get the confirmation email and receive the next test once confirmed, before the alert is saved). Project API keys only reach their project.

  • External email recipients ($modules/notifications, #99): recipients.emails holds normalized addresses outside GitOps. Each address is an ExternalRecipientEntity (GitDB external_recipients) shared by every alert of the organization: pending → verified (the owner clicked the confirmation link) → unsubscribed, or blocked when its domain leaves allowedExternalEmailDomains (notification_settings, one row per organization, empty by default = no externals; exact domain match, *.example.com for subdomains, punycode). AlertService rejects not allowed or invalid addresses (domain_not_allowed, invalid_email, also per address as recipients.emails.<i>) and requires <scope>:notifications:update to add addresses (forbidden_external; keeping or removing existing ones does not need it); after the save, register() creates them as pending and emails external-recipient-verify directly through notify() (token in the link: random, stored hashed, 7 days, single use, rate limited 3/h per address and 30/h per organization per process via src/lib/server/infra/rate-limit.ts and tokens.ts). RecipientResolver only resolves members; the engine adds the deliverable() addresses: verified, allowed domain and with an unsubscribe link, so nothing goes to externals without ORIGIN. They skip the cancan filter (no account) and never get system notifications. Their email is the reduced alert template: no sensitive catalog fields, no links into the app, an unsubscribe footer link and a List-Unsubscribe header. The unsubscribe link is a stateless HMAC token (signToken from src/lib/server/infra/tokens.ts, GITDB_ENCRYPTION_KEY, 90 days) made single use by unsubscribeVersion. Public pages /notifications/verify and /notifications/unsubscribe (allowed without session in hooks.server.ts, no app shell) only act on POST, so mail scanners opening the link change nothing. List-Unsubscribe-Post (RFC 8058 one-click) is not sent: providers POST without an Origin header and SvelteKit's CSRF check would reject it.

  • Alert settings (#lib/server/notifications/settings.ts): allowed domains (read with organization:settings:read or organization:notifications:read, changed with organization:settings:update) and the external recipients status (organization:notifications:read; resend a confirmation, or remove a pending address added by mistake, with organization:notifications:update: removing deletes the recipient, so its link stops working, and alertService.removeEmail() drops it from every alert of the organization). The "Settings" button of the organization alert list opens a modal (AlertSettingsPanel) with three tabs (Integraciones / Canales / Email externo; without JavaScript all sections stack vertically): (1) Integraciones shows Slack (status: available with "Add to Slack" button if credentials set, disabled if only SLACK_CLIENT_ID / SLACK_CLIENT_SECRET or only SLACK_SIGNING_SECRET, coming_soon for Google Chat) and an install button for the /gitops command when SLACK_SIGNING_SECRET is set; (2) Canales (organization-only, NotificationChannelEntity), created in a separate modal, with options to test, rotate secret and delete; (3) Email externo (allowed domains and external recipient management). Forms post to /org/<org>/settings/alerts/settings actions. Projects have no notification settings of their own (#119): the project alert list shows a "?" icon (instead of a "Settings" button) whose tooltip says they are managed from the organization, and /org/<org>/projects/<slug>/settings/alerts/settings redirects to the organization's page (404 for who can't open it). Alert pages get data.external (ExternalRecipientsEditorData), data.channels (channel options for the location's alerts), and data.configPath.

  • Notification channels ($modules/notifications): NotificationChannelEntity (GitDB notification_channels), owned by an organization only and usable by alerts of the organization and of all its projects. Projects have no channels of their own (#119): create() refuses a project location (scope: 'project_channels_unsupported'), listChannels() for projects returns the usable organization channels (calling listUsable()), and purgeProjectChannels() (from $modules/alerts, run in the background at startup in hooks.server.ts) deletes any project rows left from before and drops them from alerts with alertService.removeChannels() (an alert left without channels falls back to email). Project alert pages show a "?" hint instead of a settings button, and /org/<org>/projects/<slug>/settings/alerts/settings redirects to the organization's page (404 for who can't open it).

    type is webhook, slack or google-chat; a type is available only once its transport is registered with registerChatTransport() (#lib/server/infra/notifications/chat-notification.ts) in the composition root ($modules/notifications/index.ts); today webhook and slack are, and tests use FakeChatTransport. canCreateType (service option) switches a built type off for new channels: Slack needs SLACK_CLIENT_ID / SLACK_CLIENT_SECRET (slackConnectService.isConfigured()), otherwise it is refused (type_disabled) and left out of the new channel type picker, and the existing Slack channels count as disconnected (integration_disabled) and deliver nothing until the variables are back. availableTypes() lists types that can be created (transport registered and type enabled, organization-only), while registeredTypes() lists types with a transport. Providers with incoming webhooks on a fixed host (Slack, Google Chat) only write a formatter: createFixedHostChatTransport({ rule, format }) (chat-webhook.transport.ts) does the URL rule, guarded fetch and postJson; truncateText (chat-format.ts) is shared for provider length limits.

    UI components (#lib/components/notifications/): IntegrationsSection (integration cards with status and install/setup links), ChannelForm (create/edit modal), ChannelList (list with actions), and channel-ui.ts (helpers for integration cards and error messages).

    A ChatTransport implements send() and validateDestination() (sync or async), the anti-SSRF check run before saving and again before every send: validateWebhookUrl() for providers with a fixed host (https, no credentials, no IP literal, default port, allowed host and path), validateOpenWebhookUrl() for free URLs (resolves DNS and refuses private, loopback, link-local, CGNAT, multicast and metadata addresses, IPv4-mapped IPv6 included). Send through createGuardedFetch() (#lib/server/infra/http/guarded-fetch.ts): it connects only to the checked address (no DNS rebinding), never follows redirects and drains at most 64 KB of the answer. The destination (webhookUrl) is encrypted with GITDB_ENCRYPTION_KEY (channel-cipher.ts, AES-GCM bound to the channel id and the value's purpose) and only ever leaves the server masked (https://hooks.slack.com/…/••••1a2b); changing it means typing it again. enabled flag can disable delivery without deleting the channel; disabledReason: 'failures' means the platform disabled it after 20 consecutive failures.

  • Channel connection: notificationChannelService.connection(channel) (ChannelConnection in #lib/notifications/channel-connection.ts) says whether a channel delivers now or why not:

    • connected: deliverable
    • disabled: manually disabled by a person
    • failures: auto-disabled by the platform after 20 consecutive delivery failures
    • integration_disabled: its type is off in the environment (Slack without SLACK_CLIENT_ID/SECRET), or the organization disconnected it (e.g., last Slack workspace was removed)
    • unavailable: no transport registered

    It is computed, never stored. When an organization removes its last Slack workspace (removeSlackWorkspace()), disableForIntegration() disables all enabled Slack channels with disabledReason: 'integration'; when Slack is installed again, restoreForIntegration() enables only those back (ones manually disabled or failed stay as they are). deliver() only sends to connected channels, the views (toView(), alert channel options) carry it, and the settings list badges integration_disabled.

  • Paused alerts and delivery status: alertDelivery() (#lib/alerts/delivery.ts, shared with the client) says whether an alert is live: it has email recipients or at least one connected channel. It computes disconnectedTypes (types of the alert's disconnected channels without repeats, or ['unknown'] if none exist). Nothing is stored: an enabled alert that is not live shows as paused ("Pausada") in the list with an Unplug icon and reason (e.g. "Slack desconectado"), and resumes by itself when a channel is connected again or email recipients are added. AlertService refuses to add a disconnected channel to a draft (channel_disconnected) and to create or switch on an alert that is not live (no_active_destination); other edits of a paused alert (name, conditions, recipients) are allowed. The alert list shows paused alerts with a warning badge, disables the toggle, and shows the disconnected channel types. The wizard locks a channel type whose integration is off (disconnectedTypes in the alert page data) or whose channels are all disconnected ("Desconectado" + "Reconectar" link to settings), and both the wizard and the no-JS editor prevent a disconnected channel from being ticked.

  • Channel language: NotificationChannelEntity.locale (es | en, rows without it read as en, CHANNEL_LOCALES in chat-types.ts), set in the channel forms and the API (locale, invalid → invalid_locale). The engine passes deliver() a builder (locale) => ChannelMessage (ChannelMessageSource) so each channel gets its own language; the test message uses it too.

  • Signed channels: webhook is a signed type. The service generates a signing secret on create (whsec_ + 32 random bytes, encrypted in signingSecret) and returns it in clear only once from createChannel() or POST /api/notification-channels/[id]/rotate-secret (never readable again). Rotation keeps the previous secret in previousSigningSecret for 24 h (previousSecretExpiresAt); both are handed to send() in ChatNotification.signingSecrets with a stable deliveryId per message so receivers can deduplicate retries. The signature is X-GitOps-Signature: t=<unix>,v1=<hash>[,v1=<old-hash>] using HMAC-SHA256(secret, "<timestamp>.<raw body>") on the JSON sent (not encoded).

  • Slack (#lib/server/infra/notifications/slack/): Incoming Webhook, URL limited to https://hooks.slack.com/services/ only (SLACK_WEBHOOK_RULE), unsigned. buildSlackPayload() turns the ChannelMessage into Block Kit in the channel's language only: header (alert name, plain_text), the summary only when it differs from the event label, a fields section with the organization of a project event (organization), location (Project/Organization: name) and the date (slackDate(), <!date^…>, reader's time zone), a divider and a *Changes* title (labels.changes), then one section per change (*Label* / Before: … / New: …, labels.empty for a null side, only the label when both are null), remaining field sections of 10, "View in GitOps" button, and note as context. Every mrkdwn value goes through escapeSlackText() (&, <, >) so event or user data can't mention or link. Texts are cut to Block Kit limits. The Slack channel is fixed by the webhook: one GitOps channel per Slack webhook. 4xx responses (revoked webhook, archived or deleted channel) are not retried and show as the channel's last error.

  • Add to Slack (slackConnectService in $modules/notifications, #97): OAuth v2 install (SlackConnectService, SlackOAuthClient) with only the incoming-webhook scope, so Slack asks for the workspace and channel and returns its webhook URL, saved as a normal slack channel (same transport, same SLACK_WEBHOOK_RULE). The "Add to Slack" button appears in the new channel modal when SLACK_CLIENT_ID and SLACK_CLIENT_SECRET are both set (readSlackAppConfig(); half set counts as disabled); without them only the manual webhook URL fields show and the Slack type remains available (users can paste URLs directly). The action needs <scope>:notifications:create and a session, not an API key; it sets the gitops_slack_flow cookie (signToken, 10 min, bound to the user, location, locale and a return path) and redirects to Slack; /notifications/slack/callback (fixed: it is the app's redirect URL, needs the same session) checks the state, exchanges the code (Basic auth), creates the channel through createChannel() (permission checked again) and goes back with ?slack=connected|<error> (notifications.errors.slack_*). Self-hosted admins create the app from /gitops-settings/slack (prefilled manifest link, redirect URL, status); a hosted GitOps uses the official app's credentials the same way. A central OAuth broker for self-hosted installations is not implemented.

  • /gitops command (slackAppService in $modules/notifications): the same Slack app with the commands scope, enabled only when both SLACK_CLIENT_ID / SLACK_CLIENT_SECRET and SLACK_SIGNING_SECRET are set. Without SLACK_SIGNING_SECRET, the Slack integration card shows as Desactivado: GitOps admins see a link to /gitops-settings/slack to configure it, others see a note to ask an admin. An organization installs the app from its channels page (installSlack action, OAuth with only commands, flow kind: 'install'): slack_workspaces (GitDB) keeps one row per (Slack team, organization): several organizations can install the same workspace (each keeps its own row: teamId + organizationId unique pair), and each one removes only its own row. The bot token is shared by every row of a team (a new install re-encrypts it in all of them), encrypted (ChannelCipher purpose slack-bot-token; only used to open forms, views.open). /api/slack/commands and /api/slack/interactions have no session or API key: they verify X-Slack-Signature (verifySlackSignature, 5 min window) on the raw body and act as the GitOps user linked to the Slack user (authProviders entry slack = <team>:<user>, findByExternalIdentity), refusing disabled users and checking organization:notifications:create every time. /gitops login answers with a signed 10-minute link to /notifications/slack/link (needs a session: hooks.server.ts remembers it in gitops_return_to and the password and Google logins come back to it, #lib/server/return-to; the user must belong to at least one organization of the workspace). /gitops channel opens a modal with name, locale and an organization picker (listing only the workspace's organizations where the account has organization:notifications:create); with one, it goes in private_metadata and skips the picker; checked again on submit. Its submission answers with a signed link to /notifications/slack/connect (no session), which starts Slack's channel picker (flow kind: 'command', bound to the Slack team and user: the callback refuses another one with slack_wrong_workspace). /notifications/slack/callback then accepts requests without a session (only command flows can finish without one), creates the channel through createChannel() as the linked user (runWithActor), posts a test message and ends on /notifications/slack/done. /gitops status lists the linked account and, per each organization of the workspace the account can see, its Slack channels (unlinked users see nothing). Replies use the locale picked at the workspace's first install.

  • CSRF: SvelteKit's origin check is disabled in the framework (csrf.trustedOrigins: ['*']) and done by csrfGuard in hooks.server.ts with the same rule (#lib/server/csrf), because Slack posts forms without an Origin header. Only CSRF_EXEMPT_PATHS (the two signed Slack endpoints) skip it; never add a path there that does not authenticate its requests by other means.

    Local development of Slack OAuth flows requires HTTPS (Slack refuses http:// redirect URLs). Set DEV_HTTPS=true and create a self-signed certificate:

    mkdir -p .certs && openssl req -x509 -newkey rsa:2048 -nodes -days 365 -subj /CN=localhost \
      -addext subjectAltName=DNS:localhost -keyout .certs/localhost-key.pem -out .certs/localhost.pem

    Then open https://localhost:5173 and register https://localhost:5173/notifications/slack/callback in the test Slack app. See .env.example for details.

  • ChannelMessage (built by buildAlertChannelMessage(input, locale)): fields leave out what the message says elsewhere: occurredAt, location (project or organization, and any field with that name), and changedFields when changes (translated label + before/after) exists. labels carries the translated Date/Changes/Before/New/empty, and text only adds the summary when it differs from the event label, so nothing is said twice in two languages. note is the translated side note (test send, throttled count); the raw suppressed count is still there. occurredAt and location are always present; organization is added when the location is a project (shows the organization name as an extra field for context); changes only for update events; labels only when any of occurredAt, location or changes is used by the transport.

  • Update events carry changes?: FieldChange[] ({ field, before, after }, plain text cut to 200 chars by fieldChange() in #lib/events/field-changes.ts, null when empty or not shown): project.updated (modules as the enabled list, organization by name, settings without values) and organization.updated. Never put secrets in them; vault.secret.updated has none. FieldChange is defined in src/lib/events/domain-events.ts with the type parameter for field names and is used by channels (Slack shows before/after) and by the update events in payloads.

  • Generic webhook (#lib/server/infra/notifications/webhook/): POST with the versioned WebhookPayload (version, deliveryId, test, alert, event with the raw non-sensitive catalog fields from ChannelMessage.event.fields, link), headers X-GitOps-Event, X-GitOps-Delivery, X-GitOps-Signature (HMAC-SHA256 of the timestamp and body) and User-Agent: GitOps-Webhooks/1. All webhooks are signed: createChannel() and rotateChannelSecret() return the secret in signingSecret once; the service encrypts it after and never shows it again. Receiver docs and the verification example are in docs/webhooks/ (the example is unit-tested and must stay identical in the README). NOTIFICATIONS_WEBHOOK_ALLOW_HTTP / NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETS relax the rules for local development and e2e only.

  • Failure streaks: every definitive delivery failure of a real message (not tests, not unavailable types) increments consecutiveFailures (one commit each per channel); a success resets it. At 20 (MAX_CONSECUTIVE_FAILURES) the channel disables itself (enabled: false, disabledReason: 'failures') and publishes notifications.channel.disabled (system actor, organization alertable event with organization:notifications:read, payload includes channel name, type, failure count and last error). The channel creator gets emailed the channel_disabled system notice. Re-enabling resets the streak.

  • Channel delivery: alerts store channelIds (references to NotificationChannelEntity). Adding a channel needs <scope>:notifications:update (forbidden_channel), and a channel must be usable from the alert's location (unknown_channel). The engine emails each recipient and posts one message per channel in parallel; a failing channel never affects the emails or the other channels, and system notifications never go to channels. The message is a provider-neutral ChannelMessage (buildAlertChannelMessage(): default language, no sensitive fields, "View in GitOps" link, throttled count); transports format it. Deliveries go through the process-wide channelQueue (concurrency 3; postJson() from #lib/server/infra/http/webhook-request.ts with a 5 s timeout and no redirects; withRetry only on network errors, 429 honoring Retry-After, and 5xx). A permanent failure (4xx, invalid or undecryptable destination, type without transport) sets lastError; a success clears it. lastDeliveryAt is only refreshed hourly, since each write is a commit. Logs carry the channel id and type, never the URL nor the message.

  • Channels HTTP: #lib/server/notifications/channels.ts (permission-first with <scope>:notifications:read|create|update|delete; a channel the caller can't read is a 404). Routes: GET|POST /api/notification-channels (organizationId or projectId), GET|PATCH|DELETE /api/notification-channels/[id], POST /api/notification-channels/[id]/test (posts a test even to a disabled channel) and POST /api/notification-channels/[id]/rotate-secret (update permission, returns the new secret once). Form actions for the settings pages live in #lib/server/notifications/channels-page.ts; the UI is ChannelsSection (#lib/components/notifications/), and the alert editors pick channels from data.channels (the alert's draft has channelIds: string[], not direct recipients by channel type).

  • UI: /org/<org>/settings/alerts and /org/<org>/projects/<slug>/settings/alerts (list, new, [id]), thin routes over #lib/server/alerts/page.ts (loaders and form actions draft, save, test, toggle, delete; everything works without JavaScript). Components live in #lib/components/alerts/: ConditionBuilder renders fields, operators and inputs only from the CatalogEntry it receives (tested with svelte/server in ConditionBuilder.test.ts; Vitest compiles .svelte through vitest.config.ts). Project pages also list the inherited organization alerts, read-only. Error codes map to alerts.errors.<code>.

Making an event alertable:

  1. Declare the payload in DomainEventMap and publish it with publishAfterWrite and the right scope.
  2. Add its EventDefinition with alertable: true, the correct scope and readPermission, and the fields people will filter on (reference fields need a case in PlatformDirectory).
  3. Add the events.<type>.* translations in es.json and en.json.
  4. Nothing else: the catalog endpoint, the validation, the engine and the UI pick it up.

Monitoring

$modules/monitoring runs HTTP uptime monitors; the design is in docs/adr/0002-http-monitoring.md.

  • Configuration: MonitorEntity (main GitDB monitors), per project, optional serviceId of a Code Report service of the same project (unlinked when that service is deleted). Header values and the body are encrypted together (monitor-secrets.ts, vault key material, AAD = monitor id); only headerNames and hasBody reach the UI. A header row with an empty value keeps the stored value. MonitorService returns field-level codes in MonitorValidationError (monitoring.errors.<code>).
  • Metrics: never one row per check. monitoring_incidents (written at once on every status change), monitoring_current (hour in progress, every MONITORING_FLUSH_SECONDS), monitoring_hourly, monitoring_daily (hours past MONITORING_HOURLY_RETENTION_DAYS). They go to MONITORING_GITDB_REPOSITORY_URL when set (startSecondaryGitDb, #lib/server/gitdb/secondary), to the main GitDB otherwise; the audit views skip monitoring_* (isSystemMetricsEntity). Uptime is time-based from incidents (domain/aggregates.ts); status and uptime are never written to monitors.
  • Runtime (MonitoringRuntime, one per process on globalThis, started by startMonitoring() in hooks.server.ts after GitDB; a failure only disables monitoring): in-memory MonitorScheduler (stable offsets, leases of timeout + 15 s, 2 attempts, results accepted once per lease), status-tracker.ts (confirmations failing checks open an incident that starts at the first of them; one good check closes it), events monitoring.monitor.down|degraded|recovered (alertable, readPermission project:monitoring:monitors:read, display URL only).
  • Workers: #lib/monitoring/* is framework-free (no aliases, .ts import extensions, erasable TypeScript only) because src/worker/monitoring-worker.ts runs on plain Node (bun run worker, copied into the Docker image). Keep it that way. The embedded worker (MONITORING_EMBEDDED_WORKER, default on) uses the runtime as its transport; dedicated workers use POST /api/internal/monitoring/lease|results, authenticated in hooks.server.ts by verifyWorkerRequest (MONITORING_WORKER_TOKEN, optional MONITORING_INTERNAL_HOSTS), never by API keys or sessions. Both log every finished check (info up, warn degraded/down; display URL only, never header values) unless MONITORING_CHECK_LOGS=false.
  • SSRF: runHttpCheck checks the connected address in the DNS lookup hook and the hostname before that (target-guard.ts); the form rejects private literals too. Only MONITORING_ALLOW_PRIVATE_TARGETS=true lifts it (the e2e suite sets it). Errors and events never contain the URL query, credentials or header values.
  • Permissions: project:monitoring:monitors:{read,create,update,delete,test,all}; Project Admin all, Developer read/create/update/test, Viewer read. The project module flag is modules.monitoring (off by default). UI: /org/<org>/projects/<slug>/monitoring/{dashboard, monitors, monitors/new, monitors/[id], monitors/[id]/edit}, thin routes over #lib/server/monitoring/page.ts; components in #lib/components/monitoring/; the Code Report service page shows its monitors (service-monitors.ts).
  • Public API (/api/monitoring/{monitors,monitors/[id],monitors/[id]/test,status}, ADR 0005, logic in #lib/server/monitoring/api.ts): permission-first (404 unreadable project/monitor, 403 no action, 409 module_disabled). Responses only carry headerNames/hasHeaders/hasBody, never header values or the body, and URLs are the display URL. An mcp key sending headers or body on create gets 400 mcp_monitor_secrets_not_allowed; other keys and sessions are unchanged.

CVE feed

$modules/cve-feed follows the CVEs of public sources for the technologies an organization chooses (/org/<org>/cves, tab "CVEs por tecnología"); design in docs/adr/0004-cve-feed.md.

  • Off unless CVE_FEED_ENABLED=true: with false no timer starts and no external call is ever made (the "Sincronizar ahora" action refuses too). Pages only read GitDB, never a source. Other variables (all documented in .env.example): CVE_FEED_SYNC_INTERVAL (2h, min 15m), CVE_FEED_MIN_SEVERITY (global floor, an organization can only raise it), CVE_FEED_EPSS_THRESHOLD, CVE_FEED_RETENTION, CVE_FEED_BACKFILL, NVD_API_KEY (optional, 5 -> 50 requests / 30 s) and CVE_FEED_GITDB_* (dedicated repository, recommended in production).
  • Tables ($lib/database/schemas.ts): cve_watchlists (main GitDB, one per organization), cve_advisories, cve_org_matches (dedup state) and cve_feed_state (cursors, etags, lease, backfilled technologies) in the feed repository when configured. Storage rules: never the full feed (filter + retention), trimmed rows, one delete + one insert per table and sync, a row is rewritten only when its fingerprint changes (the sync without news writes nothing), volatile status stays in memory. Keep them in any new source.
  • Sources implement CveSource (infrastructure/sources/: OSV, NVD, KEV, EPSS) over the shared HttpClient (retries, backoff, injectable fetch) and never write; CveFeedRuntime does, behind a best-effort lease in cve_feed_state. Technologies are defined in the catalog $lib/cves/technologies.data.ts or as custom OSV/CPE entries. A technology new to the feed is backfilled silently (no events).
  • Read side: cveFeedQueryService (per-organization memoized view; "Te afecta" correlates with the scans of the projects the user can see, memoized per organization + project set and dropped on code_report.analysis.completed), cveWatchlistService (suggestions from Trivy/SBOM packages; never added without confirmation).
  • Permissions: organization:cves:feed:{read,update,all}; Organization Admin gets all (existing roles are not migrated). read sees the tab and the feed data of the detail (404 for others); update edits the watchlist and runs "Sincronizar ahora". "Te afecta", the occurrences and the suggestions additionally need organization:projects:read.
  • Public API (/api/cves/{watchlist,feed,[cve]}, logic in $lib/server/cve-feed/api.ts, ADR 0005): reads only cveFeedQueryService (GitDB, never a source). No organization:cves:feed:read or an unknown organization is a 404; affectsMe (filter and field) needs organization:projects:read too (the filter is a 403 without it, the field is omitted). With the feed off the feed and the detail answer empty with feedEnabled: false; the watchlist is still read from GitDB.
  • Events cve_feed.advisory.published|escalated|fix_available|affects_project (alertable, readPermission organization:cves:feed:read): one per organization x CVE x change (x project for affects_project), the dedup state is written before publishing.

Authorization

Permission grants are always scope-prefixed and match the catalog in src/lib/config/permissions.ts exactly: <scope>:<resource path>:<action>, where scope is cluster, organization or project (project:vault:secrets:read, organization:projects:create, cluster:users:invite). A <resource>:all grant covers every action on that resource. Grants stored before this convention are upgraded on read by normalizePermissionGrant in $lib/permissions.

Use the helpers exported by $modules/auth:

import { cancanService } from '$modules/auth';

const allowed = await cancanService.canSessionUser(locals.user, 'project:stateiac:stacks:read', {
  scope: 'project',
  projectId: project.id,
  organizationId: project.organization?.id,
});

if (!allowed) {
  return json({ error: 'Forbidden' }, { status: 403 });
}

UI permission gating: In route loaders, use cancanService.canSessionUser() to check specific action permissions and pass them to components as props (canCreate, canUpdate, canDelete) to conditionally render actions in the UI. This prevents users from seeing actions they cannot perform:

const canCreate = await cancanService.canSessionUser(locals.user, 'project:roles:create', {
  scope: 'project',
  projectId: project.id,
  organizationId: project.organization?.id,
});
return { roles, canCreate };

The root layout (+layout.server.ts) calculates granular read permissions for each settings section and passes them to the AppSidebar component, which filters sidebar items based on specific resource permissions:

  • Project level: project:project:read, project:users:read, project:roles:read, project:server-keys:read, project:audit:read, project:alerts:read, project:notifications:read, plus module-specific permissions: project:vault:secrets:read, project:vault:environments:read, project:codereport:reports:read, project:codereport:dependencies:read, project:codereport:vulnerabilities:read, project:stateiac:stacks:read, project:stateiac:states:read, project:stateiac:history:read. High-level read flags combine granular permissions with OR logic (e.g., canReadProjectVault = canReadProjectVaultSecrets || canReadProjectVaultEnvironments)
  • Organization level: organization:projects:read, organization:users:read, organization:roles:read, organization:settings:read, organization:backups:read, organization:server-keys:read, organization:audit:read, organization:events:read, organization:alerts:read, organization:notifications:read

This ensures the UI only displays navigation items for sections the user has permission to view.

Default roles and permissions are centralized in src/modules/auth/domain/role-permissions.data.ts. Permissions always include their scope as a prefix (e.g., organization:projects:read, project:vault:secrets:all) and are stored verbatim—there is no scope-stripping transformation:

  • GitOps Admin (cluster-admin) — grants vault, openreport, stateiac full access
  • GitOps User (cluster-user) — no inherent permissions; base role for system-level access
  • Organization Admin — all org-level permissions: projects, users, roles, settings, backups, server-keys, audit, events, alerts, notifications
  • Organization Developer — read/create/update projects only
  • Project Admin — all project-level permissions: project metadata, users, roles, server-keys, audit, alerts, notifications; plus all module permissions: vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history
  • Project Developer — read/create/update project resources; no deletion or admin; granular module access; reads alerts
  • Project Viewer — read-only: project metadata, alerts, all modules, vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history

Module resources have granular sub-permissions: project:vault:secrets:read, project:vault:environments:read, project:codereport:reports:read, project:codereport:dependencies:read, project:codereport:vulnerabilities:read, project:stateiac:stacks:read, project:stateiac:states:read, project:stateiac:history:read. These allow fine-grained access control within each module.

Organization-level permissions cascade into their projects only when no explicit project-level assignment exists for that user. A user with organization:projects:read can satisfy a project:project:read check on any project in that organization—but if they have a project-specific role assignment, that assignment is authoritative and organization permissions do not apply (most-specific-wins rule). This allows coarse-grained org roles to delegate authority downward, while still permitting per-project restrictions.

Two helpers distinguish organization visibility from management: canManageOrganization() gates the /settings area, while canViewOrganization() also includes users whose only access is to a project under that organization (they see the org overview, but cannot perform org-scope actions).

When creating an organization (via bootstrap or /gitops-settings), roleService.createDefaultOrganizationRoles() is automatically invoked. When creating a project, roleService.createDefaultProjectRoles() is automatically invoked. Both operations initialize their respective default roles. Keep authorization tests beside changes to permission behavior. Machine-to-machine requests authenticate with Authorization: Bearer gvs_...; hooks.server.ts resolves them into locals.apiKey and cancanService.canApiKey() confines a project key to its own project.

API keys have an audience (api by default, or mcp). An mcp key is always personal (project keys are always api) and is meant for AI agents (ADR 0005): canApiKey() (async) resolves it with the permissions of its user in every organization and project (canForUser, most-specific-wins, cluster admin included). Personal api keys still have no role and no permissions. Vault is closed to mcp keys twice: hooks.server.ts answers 403 on /api/vault/** and canApiKey() denies any *:vault:* permission. Calls run as actor mcp:<key name> and are rate limited per key (MCP_RATE_LIMIT_PER_MINUTE, default 120; 429 + Retry-After). Always await canApiKey().

GitOps is also an OAuth 2.1 Authorization Server for the Claude.ai MCP connector (ADR 0006), only when MCP_OAUTH_RESOURCES lists the allowed MCP URLs (otherwise every endpoint is 404). oauthService in #modules/auth serves /.well-known/oauth-authorization-server, /oauth/register (dynamic public clients, oauth_clients), /oauth/authorize (consent page with session; the authorization code is a signed stateless token, single use per process), /oauth/token and /oauth/revoke. A token is a personal audience: 'mcp' API key with oauthClientId, 1 h life and a gvr_ refresh token (sha256 in refreshHash, 30 days sliding, rotated on every use), so it goes through the normal Bearer path of hooks.server.ts. The four public endpoints read no cookie and are CSRF exempt; OAuth keys cannot be regenerated, only revoked from the profile. GET /api/whoami tells who a credential is.

organization:notifications:read and organization:notifications:update gate external email recipients at the organization level; project:notifications:update lets project alerts add them. Existing roles are not migrated: enable them from the role editor.

Unauthenticated public routes for external alert recipients: /notifications/verify and /notifications/unsubscribe accept POST requests with tokens (confirmations and unsubscribes). They are allowed without a session in hooks.server.ts and validate their tokens rather than checking permissions.

Read API for discovery and Code Report (GET /api/projects, /api/code-report/services[/id[/vulnerabilities]], logic in #lib/server/code-report/api.ts): permission-first through callerCan (sessions and keys). A project or service the caller cannot read is a 404; 403 only when the project is readable (project:project:read or a Code Report read) but the action (reports:read, vulnerabilities:read) is not. Lists use limit/cursor; CVE titles are cut to 300 characters and the SBOM or raw scanner output is never returned.

locals.user.role is a session role object, not the string admin. Use isAdmin() or the can* helpers. Keep authorization tests beside changes to permission behavior.

Security rules

  • Keep .env, API keys, Git credentials, session secrets, and repository credentials out of Git.
  • Use a strong production GITDB_ENCRYPTION_KEY; the development example is not suitable for production.
  • Preserve the existing scrypt password hashing, HMAC session signing, and timing-safe checks.
  • Never return raw secrets from an API.
  • Review organization, project, role, and access changes for privilege escalation.

Code and tests

Follow the existing naming patterns: *.domain.ts, *.service.ts, *.repository.ts, and *.test.ts. Prefer dependency injection and in-memory fakes in unit tests. Keep API handlers permission-first and normalize errors consistently.

Before finishing a change, run the relevant checks. Do not silently fix unrelated bugs or rewrite generated files. Update README.md, CONTRIBUTING.md, and this file when architecture or public commands change.

Known behavior

i18n imports from notifications: #lib/server/infra/notifications/index.ts does not re-export the email i18n helpers (DEFAULT_MAIL_LOCALE, mailLocale, translator…): they load Paraglide messages (a Vite requirement), and the notifications index is imported by $modules/auth, which runs outside Vite during e2e tests. Import them from #lib/server/infra/notifications/i18n. For the same reason e2e/fixtures/seed.ts seeds allowed domains through NotificationSettingsRepository, not $modules/notifications.

Server startup and readiness: The auth guard in hooks.server.ts checks readiness via getServerReadyState() before processing any request. During startup, browsers receive a self-reloading "GitOps is starting" landing page, while API requests get a 503 response with retry-after: 3 header. If startup fails, both receive 503 Service Unavailable (HTML landing page for browsers, JSON for APIs with "Server failed to start" message). The /health endpoint (used by e2e and infrastructure probes) returns 200 only after startup completes. This applies in both development (where Vite loads the module on the first request) and production (where no infrastructure probe guarantees traffic is held back during startup). The bootstrap state is only meaningful after startup completes.