Guidance for working on GitOps, an open source internal developer platform built with SvelteKit.
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.
- 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:checkTests 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.
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 fromsrc/lib/styles/brand.css(imported byapp.css): buttons (k-btn+k-btn-primary|secondary|outline-brand|ghost|danger, sizesk-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-itemwitharia-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.tsalready does it (Esc only closes the top-most overlay). - Every form control goes inside
Field(label, help and error wired witharia-describedby/aria-invalid); spread the snippet argument on the control:<input class="k-input" {...control} />. - A submit button in a
Modalfooter lives outside the<form>: give the form anidand the buttonform="that-id". Putdata-autofocuson the field that should get the initial focus. SelectandSwitchacceptnameand 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
Modalinstead of navigating; keep the/newroute for direct links and no-JS, and post the modal form to that route's actions with local result handling (seemonitoring/NewMonitorModal.svelte+MonitorFormvariant="modal"). - Page pattern (see project settings):
<header>withh1.text-2xl+text-fg-muteddescription and the primary action on the right; content ink-cards; success/error feedback withtoast, not inline banners; every destructive action (delete, revoke, rotate, remove access) confirms in aModal(role="alertdialog"), and deleting a top-level entity asks to type its name. - Floating panels (
DropdownMenu,Select,TagInputsuggestions) render in<body>throughfloatinginui/overlay.ts, so nooverflow(tables, modal bodies) clips them. - Alerts: email targets live in
recipients(userIds/roleIds/emails) and chat or webhook targets inchannelIds(notification channels);channelsis derived on save. Create/edit happens inAlertWizard(modal); the/newand/[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, texttext-fg|fg-muted|fg-subtle, statusok|warn|danger|info(always with an icon or text, never as a chart series), chart seriesseries-1…5in that fixed order. Usebg-snowfor pure white: legacyapp.cssoverrides.bg-white,.bg-white/15|70|80|90,.border-white/15|60,.text-slate-*,.shadow-sm|md|xlwith!important, so avoid those classes in v3 code. - App shell (migrated to v3):
+layout.svelterendersAppNavbar(logo, ⌘K search, docs, account menu with "Ajustes de GitOps" for cluster admins) andAppSidebaras in the/brandmock: 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), andSidebarFooter(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: falsekeeps 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 mountsCommandPaletteandToasteronce; do not add another in a page. Collapsed mode is stored inlocalStorage(gitops-sidebar-collapsed); belowmdthe sidebar is off-canvas. Auth, bootstrap and/brandkeep 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.svgand PNGs). The navbar uses the new logo; the oldgitops_logo*.png,icono_*.pngandfavicon.pngare still used elsewhere (favicon, auth pages). - Legacy:
#lib/components/Dropdown.svelteand thebtn-*/field-inputclasses are v2; replace them with the v3 equivalents when a screen is migrated, not piecemeal. e2e/specs/brand-ui.spec.tscovers keyboard, focus and closing behavior of the UI components; extend it when you change them.
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.
$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).
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 inDomainEventMap(src/lib/events/domain-events.ts, shared with the client). - Every event needs an
EventDefinitionin the catalog (src/lib/events/catalog/, one<module>.events.tsper module): scope,readPermission,alertableand its filterable fields.EVENT_CATALOGis exhaustive and field keys withoutderiveare checked against the payload at compile time. Labels are i18n keys (events.<type>.label,.description,.fields.<key>,events.options.<group>.<value>) and must exist ines.jsonanden.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. UsepublishAfterWrite(#lib/server/events/publish) so resolving the scope or publishing can never fail a write that already succeeded;resolveProjectScopeadds 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/apiKeyIdset inhooks.server.ts), falling back tosystem. - Inject
EventBusthrough the service constructor from the module'sindex.ts; only composition roots import theeventBussingleton. In unit tests useRecordingEventBusfrom#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 withorganization:events:readsee the events they are allowed to read (each definition'sreadPermission, checked in the event's project or organization) and, withorganization:events:update, acknowledge them. Only the default Organization Admin role getsorganization:events:all; existing roles are not migrated (enable it from the role editor). Retention:GITOPS_EVENTS_EXPIRATION(default7d). It is per process and cleared on restart.
$modules/alerts turns domain events into emails.
-
AlertEntity(GitDBalerts): an alert watches oneeventTypefrom an organization (scope: 'organization', covers every project of it) or a project.conditions({ field, operator, value }) use the catalog fields, combined withmatch: 'all' | 'any'; an empty list always matches. Organization alerts on project events also get aprojectIdfield (listAlertFields, value taken from the event scope). Email recipients are inrecipients(users, roles, external emails); chat and webhook targets are inchannelIds(references toNotificationChannelEntity), not in recipients (a channel delivers to its configured destination, not to individual recipients). -
AlertServicevalidates every write against the catalog and the location and throwsAlertValidationErrorwith 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'sreadPermission). -
AlertEnginesubscribes to'*'once per process (registerAlertEngine()inhooks.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 byrenderEmail()insrc/notifications/email/_layout.html(header, content, footer with the reason and a manage link). Alerts usealert.html(field table built from the catalog) unless the definition setsmailTemplate(alert-code-report-analysis.html);link(context)gives the app path of the resource andmailSummary(payload)the subject summary ([GitOps] <alert>: <summary>). System notices usesystem-access-changed.html/system-security-notice.html. Escape every user or event value with{{ }};{{{ }}}only for HTML built internally withrenderTemplateString. Texts arealerts.email.*, in the recipient's locale or English. Links are absolute withORIGIN(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,withRetry4 attempts 1 s → 4 s → 16 s with jitter, only forisRetryableMailError: network errors and 4xx replies). Definitive failures are logged bycreateLogger('mail')with the alert, the event and a recipient hash, never the content or the address.registerMailShutdown()drains it onsveltekit:shutdown(10 s). Invitations and password resets callnotify()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.MailQueueis aDeliveryQueue(#lib/server/infra/notifications/delivery-queue.ts), the generic queue channels reuse. -
HTTP:
#lib/server/alerts(access.tsfor permissions/location/actor,operations.tsshared 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]/testandPOST /api/alerts/test(dry runs that never touch the throttle; withsend: 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.emailsholds normalized addresses outside GitOps. Each address is anExternalRecipientEntity(GitDBexternal_recipients) shared by every alert of the organization:pending→verified(the owner clicked the confirmation link) →unsubscribed, orblockedwhen its domain leavesallowedExternalEmailDomains(notification_settings, one row per organization, empty by default = no externals; exact domain match,*.example.comfor subdomains, punycode).AlertServicerejects not allowed or invalid addresses (domain_not_allowed,invalid_email, also per address asrecipients.emails.<i>) and requires<scope>:notifications:updateto add addresses (forbidden_external; keeping or removing existing ones does not need it); after the save,register()creates them as pending and emailsexternal-recipient-verifydirectly throughnotify()(token in the link: random, stored hashed, 7 days, single use, rate limited 3/h per address and 30/h per organization per process viasrc/lib/server/infra/rate-limit.tsandtokens.ts).RecipientResolveronly resolves members; the engine adds thedeliverable()addresses: verified, allowed domain and with an unsubscribe link, so nothing goes to externals withoutORIGIN. They skip the cancan filter (no account) and never get system notifications. Their email is the reducedalerttemplate: nosensitivecatalog fields, no links into the app, an unsubscribe footer link and aList-Unsubscribeheader. The unsubscribe link is a stateless HMAC token (signTokenfromsrc/lib/server/infra/tokens.ts,GITDB_ENCRYPTION_KEY, 90 days) made single use byunsubscribeVersion. Public pages/notifications/verifyand/notifications/unsubscribe(allowed without session inhooks.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 anOriginheader and SvelteKit's CSRF check would reject it. -
Alert settings (
#lib/server/notifications/settings.ts): allowed domains (read withorganization:settings:readororganization:notifications:read, changed withorganization:settings:update) and the external recipients status (organization:notifications:read; resend a confirmation, or remove apendingaddress added by mistake, withorganization:notifications:update: removing deletes the recipient, so its link stops working, andalertService.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:availablewith "Add to Slack" button if credentials set,disabledif onlySLACK_CLIENT_ID/SLACK_CLIENT_SECRETor onlySLACK_SIGNING_SECRET,coming_soonfor Google Chat) and an install button for the/gitopscommand whenSLACK_SIGNING_SECRETis 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/settingsactions. 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/settingsredirects to the organization's page (404 for who can't open it). Alert pages getdata.external(ExternalRecipientsEditorData),data.channels(channel options for the location's alerts), anddata.configPath. -
Notification channels (
$modules/notifications):NotificationChannelEntity(GitDBnotification_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 (callinglistUsable()), andpurgeProjectChannels()(from$modules/alerts, run in the background at startup inhooks.server.ts) deletes any project rows left from before and drops them from alerts withalertService.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/settingsredirects to the organization's page (404 for who can't open it).typeiswebhook,slackorgoogle-chat; a type is available only once its transport is registered withregisterChatTransport()(#lib/server/infra/notifications/chat-notification.ts) in the composition root ($modules/notifications/index.ts); todaywebhookandslackare, and tests useFakeChatTransport.canCreateType(service option) switches a built type off for new channels: Slack needsSLACK_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), whileregisteredTypes()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 andpostJson;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), andchannel-ui.ts(helpers for integration cards and error messages).A
ChatTransportimplementssend()andvalidateDestination()(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 throughcreateGuardedFetch()(#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 withGITDB_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.enabledflag can disable delivery without deleting the channel;disabledReason: 'failures'means the platform disabled it after 20 consecutive failures. -
Channel connection:
notificationChannelService.connection(channel)(ChannelConnectionin#lib/notifications/channel-connection.ts) says whether a channel delivers now or why not:connected: deliverabledisabled: manually disabled by a personfailures: auto-disabled by the platform after 20 consecutive delivery failuresintegration_disabled: its type is off in the environment (Slack withoutSLACK_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 withdisabledReason: 'integration'; when Slack is installed again,restoreForIntegration()enables only those back (ones manually disabled or failed stay as they are).deliver()only sends toconnectedchannels, the views (toView(), alert channel options) carry it, and the settings list badgesintegration_disabled. -
Paused alerts and delivery status:
alertDelivery()(#lib/alerts/delivery.ts, shared with the client) says whether an alert islive: it has email recipients or at least one connected channel. It computesdisconnectedTypes(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.AlertServicerefuses 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 (disconnectedTypesin 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 asen,CHANNEL_LOCALESinchat-types.ts), set in the channel forms and the API (locale, invalid →invalid_locale). The engine passesdeliver()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 insigningSecret) and returns it in clear only once fromcreateChannel()orPOST /api/notification-channels/[id]/rotate-secret(never readable again). Rotation keeps the previous secret inpreviousSigningSecretfor 24 h (previousSecretExpiresAt); both are handed tosend()inChatNotification.signingSecretswith a stabledeliveryIdper message so receivers can deduplicate retries. The signature isX-GitOps-Signature: t=<unix>,v1=<hash>[,v1=<old-hash>]usingHMAC-SHA256(secret, "<timestamp>.<raw body>")on the JSON sent (not encoded). -
Slack (
#lib/server/infra/notifications/slack/): Incoming Webhook, URL limited tohttps://hooks.slack.com/services/only (SLACK_WEBHOOK_RULE), unsigned.buildSlackPayload()turns theChannelMessageinto 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.emptyfor anullside, only the label when both arenull), remaining field sections of 10, "View in GitOps" button, andnoteas context. Everymrkdwnvalue goes throughescapeSlackText()(&,<,>) 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 (
slackConnectServicein$modules/notifications,#97): OAuth v2 install (SlackConnectService,SlackOAuthClient) with only theincoming-webhookscope, so Slack asks for the workspace and channel and returns its webhook URL, saved as a normalslackchannel (same transport, sameSLACK_WEBHOOK_RULE). The "Add to Slack" button appears in the new channel modal whenSLACK_CLIENT_IDandSLACK_CLIENT_SECRETare 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:createand a session, not an API key; it sets thegitops_slack_flowcookie (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 throughcreateChannel()(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. -
/gitopscommand (slackAppServicein$modules/notifications): the same Slack app with thecommandsscope, enabled only when bothSLACK_CLIENT_ID/SLACK_CLIENT_SECRETandSLACK_SIGNING_SECRETare set. WithoutSLACK_SIGNING_SECRET, the Slack integration card shows as Desactivado: GitOps admins see a link to/gitops-settings/slackto configure it, others see a note to ask an admin. An organization installs the app from its channels page (installSlackaction, OAuth with onlycommands, flowkind: 'install'):slack_workspaces(GitDB) keeps one row per (Slack team, organization): several organizations can install the same workspace (each keeps its own row:teamId+organizationIdunique 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 (ChannelCipherpurposeslack-bot-token; only used to open forms,views.open)./api/slack/commandsand/api/slack/interactionshave no session or API key: they verifyX-Slack-Signature(verifySlackSignature, 5 min window) on the raw body and act as the GitOps user linked to the Slack user (authProvidersentryslack=<team>:<user>,findByExternalIdentity), refusing disabled users and checkingorganization:notifications:createevery time./gitops loginanswers with a signed 10-minute link to/notifications/slack/link(needs a session:hooks.server.tsremembers it ingitops_return_toand 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 channelopens a modal with name, locale and an organization picker (listing only the workspace's organizations where the account hasorganization:notifications:create); with one, it goes inprivate_metadataand 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 (flowkind: 'command', bound to the Slack team and user: the callback refuses another one withslack_wrong_workspace)./notifications/slack/callbackthen accepts requests without a session (onlycommandflows can finish without one), creates the channel throughcreateChannel()as the linked user (runWithActor), posts a test message and ends on/notifications/slack/done./gitops statuslists 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 bycsrfGuardinhooks.server.tswith the same rule (#lib/server/csrf), because Slack posts forms without anOriginheader. OnlyCSRF_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). SetDEV_HTTPS=trueand 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.pemThen open
https://localhost:5173and registerhttps://localhost:5173/notifications/slack/callbackin the test Slack app. See.env.examplefor details. -
ChannelMessage(built bybuildAlertChannelMessage(input, locale)):fieldsleave out what the message says elsewhere:occurredAt,location(project or organization, and any field with that name), andchangedFieldswhenchanges(translated label + before/after) exists.labelscarries the translatedDate/Changes/Before/New/empty, andtextonly adds the summary when it differs from the event label, so nothing is said twice in two languages.noteis the translated side note (test send, throttled count); the rawsuppressedcount is still there.occurredAtandlocationare always present;organizationis added when the location is a project (shows the organization name as an extra field for context);changesonly for update events;labelsonly when any ofoccurredAt,locationorchangesis used by the transport. -
Update events carry
changes?: FieldChange[]({ field, before, after }, plain text cut to 200 chars byfieldChange()in#lib/events/field-changes.ts,nullwhen empty or not shown):project.updated(modules as the enabled list, organization by name, settings without values) andorganization.updated. Never put secrets in them;vault.secret.updatedhas none.FieldChangeis defined insrc/lib/events/domain-events.tswith 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/):POSTwith the versionedWebhookPayload(version,deliveryId,test,alert,eventwith the raw non-sensitive catalogfieldsfromChannelMessage.event.fields,link), headersX-GitOps-Event,X-GitOps-Delivery,X-GitOps-Signature(HMAC-SHA256of the timestamp and body) andUser-Agent: GitOps-Webhooks/1. All webhooks are signed:createChannel()androtateChannelSecret()return the secret insigningSecretonce; the service encrypts it after and never shows it again. Receiver docs and the verification example are indocs/webhooks/(the example is unit-tested and must stay identical in the README).NOTIFICATIONS_WEBHOOK_ALLOW_HTTP/NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETSrelax the rules for local development and e2e only. -
Failure streaks: every definitive delivery failure of a real message (not tests, not
unavailabletypes) incrementsconsecutiveFailures(one commit each per channel); a success resets it. At 20 (MAX_CONSECUTIVE_FAILURES) the channel disables itself (enabled: false,disabledReason: 'failures') and publishesnotifications.channel.disabled(system actor, organization alertable event withorganization:notifications:read, payload includes channel name, type, failure count and last error). The channel creator gets emailed thechannel_disabledsystem notice. Re-enabling resets the streak. -
Channel delivery: alerts store
channelIds(references toNotificationChannelEntity). 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-neutralChannelMessage(buildAlertChannelMessage(): default language, nosensitivefields, "View in GitOps" link, throttled count); transports format it. Deliveries go through the process-widechannelQueue(concurrency 3;postJson()from#lib/server/infra/http/webhook-request.tswith a 5 s timeout and no redirects;withRetryonly on network errors, 429 honoringRetry-After, and 5xx). A permanent failure (4xx, invalid or undecryptable destination, type without transport) setslastError; a success clears it.lastDeliveryAtis 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(organizationIdorprojectId),GET|PATCH|DELETE /api/notification-channels/[id],POST /api/notification-channels/[id]/test(posts a test even to a disabled channel) andPOST /api/notification-channels/[id]/rotate-secret(updatepermission, returns the new secret once). Form actions for the settings pages live in#lib/server/notifications/channels-page.ts; the UI isChannelsSection(#lib/components/notifications/), and the alert editors pick channels fromdata.channels(the alert's draft haschannelIds: string[], not direct recipients by channel type). -
UI:
/org/<org>/settings/alertsand/org/<org>/projects/<slug>/settings/alerts(list,new,[id]), thin routes over#lib/server/alerts/page.ts(loaders and form actionsdraft,save,test,toggle,delete; everything works without JavaScript). Components live in#lib/components/alerts/:ConditionBuilderrenders fields, operators and inputs only from theCatalogEntryit receives (tested withsvelte/serverinConditionBuilder.test.ts; Vitest compiles.sveltethroughvitest.config.ts). Project pages also list the inherited organization alerts, read-only. Error codes map toalerts.errors.<code>.
Making an event alertable:
- Declare the payload in
DomainEventMapand publish it withpublishAfterWriteand the right scope. - Add its
EventDefinitionwithalertable: true, the correctscopeandreadPermission, and the fields people will filter on (referencefields need a case inPlatformDirectory). - Add the
events.<type>.*translations ines.jsonanden.json. - Nothing else: the catalog endpoint, the validation, the engine and the UI pick it up.
$modules/monitoring runs HTTP uptime monitors; the design is in
docs/adr/0002-http-monitoring.md.
- Configuration:
MonitorEntity(main GitDBmonitors), per project, optionalserviceIdof 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); onlyheaderNamesandhasBodyreach the UI. A header row with an empty value keeps the stored value.MonitorServicereturns field-level codes inMonitorValidationError(monitoring.errors.<code>). - Metrics: never one row per check.
monitoring_incidents(written at once on every status change),monitoring_current(hour in progress, everyMONITORING_FLUSH_SECONDS),monitoring_hourly,monitoring_daily(hours pastMONITORING_HOURLY_RETENTION_DAYS). They go toMONITORING_GITDB_REPOSITORY_URLwhen set (startSecondaryGitDb,#lib/server/gitdb/secondary), to the main GitDB otherwise; the audit views skipmonitoring_*(isSystemMetricsEntity). Uptime is time-based from incidents (domain/aggregates.ts); status and uptime are never written tomonitors. - Runtime (
MonitoringRuntime, one per process onglobalThis, started bystartMonitoring()inhooks.server.tsafter GitDB; a failure only disables monitoring): in-memoryMonitorScheduler(stable offsets, leases oftimeout + 15 s, 2 attempts, results accepted once per lease),status-tracker.ts(confirmationsfailing checks open an incident that starts at the first of them; one good check closes it), eventsmonitoring.monitor.down|degraded|recovered(alertable,readPermissionproject:monitoring:monitors:read, display URL only). - Workers:
#lib/monitoring/*is framework-free (no aliases,.tsimport extensions, erasable TypeScript only) becausesrc/worker/monitoring-worker.tsruns 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 usePOST /api/internal/monitoring/lease|results, authenticated inhooks.server.tsbyverifyWorkerRequest(MONITORING_WORKER_TOKEN, optionalMONITORING_INTERNAL_HOSTS), never by API keys or sessions. Both log every finished check (infoup,warndegraded/down; display URL only, never header values) unlessMONITORING_CHECK_LOGS=false. - SSRF:
runHttpCheckchecks the connected address in the DNS lookup hook and the hostname before that (target-guard.ts); the form rejects private literals too. OnlyMONITORING_ALLOW_PRIVATE_TARGETS=truelifts 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 ismodules.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, 409module_disabled). Responses only carryheaderNames/hasHeaders/hasBody, never header values or the body, and URLs are the display URL. Anmcpkey sendingheadersorbodyon create gets 400mcp_monitor_secrets_not_allowed; other keys and sessions are unchanged.
$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) andCVE_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) andcve_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 sharedHttpClient(retries, backoff, injectablefetch) and never write;CveFeedRuntimedoes, behind a best-effort lease incve_feed_state. Technologies are defined in the catalog$lib/cves/technologies.data.tsor 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 oncode_report.analysis.completed),cveWatchlistService(suggestions from Trivy/SBOM packages; never added without confirmation). - Permissions:
organization:cves:feed:{read,update,all}; Organization Admin getsall(existing roles are not migrated).readsees the tab and the feed data of the detail (404 for others);updateedits the watchlist and runs "Sincronizar ahora". "Te afecta", the occurrences and the suggestions additionally needorganization:projects:read. - Public API (
/api/cves/{watchlist,feed,[cve]}, logic in$lib/server/cve-feed/api.ts, ADR 0005): reads onlycveFeedQueryService(GitDB, never a source). Noorganization:cves:feed:reador an unknown organization is a 404;affectsMe(filter and field) needsorganization:projects:readtoo (the filter is a 403 without it, the field is omitted). With the feed off the feed and the detail answer empty withfeedEnabled: false; the watchlist is still read from GitDB. - Events
cve_feed.advisory.published|escalated|fix_available|affects_project(alertable,readPermissionorganization:cves:feed:read): one per organization x CVE x change (x project foraffects_project), the dedup state is written before publishing.
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.
- 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.
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.
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.