diff --git a/.env.example b/.env.example index 47b7569..dadaa14 100644 --- a/.env.example +++ b/.env.example @@ -3,8 +3,8 @@ # On a server never keep these values: choose your own password and tokens (`openssl rand -hex 32`). # Log in with these while there is no admin to set up the first one (email and own password); ignored after. -ADMIN_EMAIL=admin -ADMIN_PASSWORD=admin-password +ADMIN_EMAIL=exceptic +ADMIN_PASSWORD=exceptic # Sign in with Google: an OAuth client with the redirect URI /auth/google/callback (needs PUBLIC_URL). # GOOGLE_CLIENT_ID= # GOOGLE_CLIENT_SECRET= @@ -17,6 +17,11 @@ API_TOKEN=local-development-token-0123456789 # TRUSTED_PROXIES=127.0.0.1 # reverse proxies, comma-separated, whose X-Forwarded-For/-Proto are believed # LOG_LEVEL=debug +# make dev only (needs systemd): run the server within a container's limits, as --cpus/--memory do. +# The server sizes its memory and its queue by them. Unset: no limits. +# DEV_CPUS=1 +# DEV_MEMORY=512M + # Email notifications (Mailtrap's sandbox for testing). # SMTP_HOST=sandbox.smtp.mailtrap.io # SMTP_PORT=2525 diff --git a/CLAUDE.md b/CLAUDE.md index 11438d8..6e18018 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -29,7 +29,7 @@ go test ./internal/storage/database -run TestUserRules -count=1 # single test go test ./web # checks a built SPA page against what Go expects (skipped when not built) ``` -Do not start the server (`make run`, `docker run`, …) yourself; the user runs it in their own terminal. Check it with `curl localhost:8000/health` and ask the user to start it if it is not reachable. `make run` loads `.env` and `.env.local` (gitignored; template in `.env.example`); without projects (added on the Projects page or by `create_project`) every event is rejected: the start logs a warning, each rejected envelope only a debug line (`LOG_LEVEL=debug`). `.env.example` is a working local setup (an admin `admin`/`admin-password`, an API token; a project is added on the Projects page), short, every variable only in `docs/configuration.md`; real keys and passwords go into `.env.local` and never into it. `go run` does not rebuild on change: after editing Go code (or rebuilding the web app, which is embedded), the user must restart it. +Do not start the server (`make run`, `docker run`, …) yourself; the user runs it in their own terminal. Check it with `curl localhost:8000/health` and ask the user to start it if it is not reachable. `make run` loads `.env` and `.env.local` (gitignored; template in `.env.example`); without projects (added on the Projects page or by `create_project`) every event is rejected: the start logs a warning, each rejected envelope only a debug line (`LOG_LEVEL=debug`). `.env.example` is a working local setup (the first admin set up with `exceptic`/`exceptic`, an API token; a project is added on the Projects page), short, every variable only in `docs/configuration.md`; real keys and passwords go into `.env.local` and never into it. `go run` does not rebuild on change: after editing Go code (or rebuilding the web app, which is embedded), the user must restart it. The image has a writable `/tmp` (scratch has none). CI (`.github/workflows/ci.yml`) runs golangci-lint (pinned version), `make test`, `make vulncheck`, `make web-check web` with `go test ./web`, an amd64 image build with the size check and an arm64 build. `make release` (`tools/release.sh`, as hothost's build.sh: from this machine, no CI secrets; the version from the commits since the last release as semantic-release reads them (AdminForth): a breaking change the major, `feat:` the minor, `fix:`/`perf:` the patch, none of them nothing to release; asked for confirmation; or `VERSION=X.Y.Z`) checks that `main` is clean, pushed and green on CI for that commit (`gh run list`), builds the image with the size check, pushes `devforth/exceptic:X.Y.Z`, `:X.Y` and `:latest` (a pre-release `X.Y.Z-rc.1` only its own) for amd64 and arm64 with the machine's `docker login` (buildx), tags the commit `vX.Y.Z` and makes its GitHub release (`gh release create`, the commits since the previous tag; a pre-release marked so), and for a release replaces the description on Docker Hub with `docs/dockerhub.md` (short, links to GitHub by absolute URL, since Docker Hub resolves no relative link; markers of its copied blocks stripped) when `DOCKERHUB_USERNAME` and `DOCKERHUB_TOKEN` (Read, Write & Delete) are in the environment or `.env.local`. `image-scan.yml` runs Trivy weekly over the published `:latest` (fixable HIGH/CRITICAL fail the run: a patch release with a newer Go or module). `compose.yml` is the example deployment the docs refer to. @@ -84,7 +84,7 @@ Where to look first: - `internal/server`: `net/http` ServeMux with method patterns (`"GET /health"`), wrapped in a request-logging middleware (its `statusRecorder` unwraps, so `http.ResponseController`, the read deadline of ingest bodies, reaches the connection) and `recoverPanics` inside it: a handler's panic is logged with method, path, route and stack and answered as a JSON 500 "internal error" (the connection is dropped if the answer had begun). Built from `server.Options`; depends on small interfaces (`Pinger`, `http.Handler` for ingest, `Routes` for the API and the web app), so tests use fakes. Mounts ingest (open), `/health` (open; 503 when `Store.Ping`, a read of the store, fails), the links that stop emails (`Unsubscribe`, open, signed), the API wrapped in `protectAPI` (IP allowlist first, then API token); MCP, OAuth, the web app (`Web`, every address no other route takes) and its API (`UIAPI`, a `UIRoutes`: routes plus the handler of every other address under `UIAPIPrefix`) use the IP allowlist plus their own authentication. `RESTPrefix` (`/api/v1/`) and `UIAPIPrefix` (`/api/ui/`) are defined here; the one `"/api/"` fallback (`unknownAPI`) sends `/api/ui/...` to the web app's API (a login, then a JSON 404) and anything else to a JSON 404 behind the token. `headers.go`: `ContentSecurityPolicy` (the one builder: script sources such as the page's inline hashes), `SecurityHeaders` (policy, nosniff, `Referrer-Policy: same-origin` (no-referrer would make browsers send `Origin: null` on same-origin POSTs), `X-Frame-Options`), `SameOrigin` (Origin's host is the request's, and https when the request is (`IsHTTPS` with the trusted proxies); oauth compares with PUBLIC_URL on purpose), used by `web` and `api/ui.go`. - `internal/server` (`access.go`): `ClientIP` (uses `X-Forwarded-For` only when the direct peer is in `TRUSTED_PROXIES`, read right to left; entries may carry a port; addresses are compared unmapped and without an IPv6 zone, `comparable`, and IPv4-mapped networks in the settings are stored as IPv4), `FromTrustedProxy`, `RequireAllowedIP` (403, a debug log line with the address seen), `RequireToken` (constant-time; empty `API_TOKEN` closes the REST API). - `internal/server` (`json.go`): `WriteJSON`/`JSONError` for JSON responses (`{"error": ...}`). Ingest keeps its own `writeError` because Sentry SDKs expect `{"detail": ...}` plus `X-Sentry-Error`. -- `internal/api` (the catalog): the one catalog of requests, served as the REST API, as MCP tools and to the web app. `Endpoints(projects, services.All)` lists them in order; handlers reach data only through `services.All` (no store), so tools and pages apply the same rules (with nil arguments it only serves to read the definitions); each is `Define(Endpoint{Name, Description, ReadOnly, Idempotent, Destructive, Confirm, Admin, Transports, OpenWithTemporaryPassword}, handler)` with `handler(ctx, Call, In) (Out, error)`: the input schema comes from `In` (`json` + `jsonschema` tags, `jsonschema.For`) with the enums of `Choices` and the bounds of every `limit` (`DefaultLimit`, `MaxLimit`), `Run` validates the input map against it and decodes it. A new tool or API route = one entry + its handler; nothing else to register. `Call.Access()` is the projects the call sees (all for the REST token, the viewer's otherwise; handlers find projects by name or id through `services.Projects.Find` (`params.go`: `projectIDs` for filters, a missing one 404, a hidden one 403; `projectsField` for a form's field: unknown 400, hidden 403 at the field) and pass the access to services). `Call` has the `Transport` (`TransportREST`, `TransportMCP`, `TransportUI`; a `Call` without one runs nothing), the `Viewer` (the user of the agent or the web app; empty for the REST token), the `Actor` (recorded in the history) and the server `Address` (DSNs); `ForAgent()` is true unless the transport is REST or the web app (fail closed), and then `call.Text` redacts free text with `agentprompt.Redact`. Output is JSON, or `api.Text` written as is (the agent prompt of `get_issue`/`get_event`). Errors are sorted in one place (`OutcomeOf`: the HTTP status, the kind an MCP tool error starts with (`Outcome.ToolText`: `invalid: …`, `forbidden: …`, `not found: …`, `conflict: …`, `unavailable: …`, `internal error`) and the body), which `fail` (REST, the web app, the plain requests) and MCP's `failed` use: `InputError` with its status (`Invalid` 400, `notFound` 404, `conflict` 409, 413, 429 with `Retry-After`, 502 for a destination that refused a test message); `services.Reason` of `services.ErrForbidden` (the role or a rule of who may change whom; `services.Forbidden(reason)`), `services.ErrHidden` (a record of a project outside the viewer's; `services.Hidden(what, ids...)`, which names only what the caller gave, never the record's data) both 403, `store.ErrNotFound` (`services.Missing`) 404, `services.ErrConflict` 409; `services.Refusal` (a form refused as 403 or 409 with its fields, `formError` renames them; a taken project name 409, "This name cannot be used." for a hidden one); `ErrNotFound` 404; anything else logged and reported as "internal error". MCP adds the viewer's project names to a hidden record's refusal (`forbidden: issue k3x9q2mf is not in your projects (frontend, test2)`), which `list_projects` shows them anyway, so an agent tells a deleted issue from a hidden one; a 403 confirms only that an id or name exists. A refused form is `problemsError` (the problem of each field, renamed to the input's names) or `duplicateError` (409, the connection that already sends there, unnamed when hidden): over HTTP the body is `ErrorBody` `{error, fields?, duplicate?}` whatever the status, so a page shows each problem at its field, MCP gets the joined message (`TestInputErrorBody`, `errors_test.go`). Lists: `Page{items, next_cursor}`, 20 rows by default, at most 100, plain-number cursors (offset for issues/projects/deliveries, at most `store.MaxOffset` (`parseOffset`; `ListIssues` clamps too, since offset+limit must not overflow), last id for events/logs; `list_users` and `list_connections` return every row in one page). Every endpoint names its `Transports` (`Define` panics without; `AllTransports`, `ActsAsUser` = MCP and the web app, or one): `Run` refuses what `Refused(call)` names (`AllowedFor` is it being nil): an endpoint its transport does not serve (`ErrNotFound`), for a user without `CanAdminister` an `Admin` one (`services.ErrForbidden`, "your role may not do this"), and in the web app, while the user has a temporary password, anything without `OpenWithTemporaryPassword` (403 "change your password first"); the token runs every REST endpoint. REST only: `get_event_payload` (raw payload), `list_trace` (log attributes), their output must not reach a model provider (the web app reads the payload, indented, inside `get_issue_details`). `ActsAsUser` (`manage.go`, `notifications.go`): account, agents, projects, users, notification connections and email confirmation, acting as the user (`Users` and `Agents` refuse by role with `services.Forbidden` (403: "your role may not change this user" for a user changing an admin, `services.TakeOverProblem` for a user with projects the admin lacks; nobody changes themselves there: "change your own account on /account"); `Projects`, `Connections`, `Verification` and `Deliveries` check no role, only the access (`Projects.Save` keeps the disk share an admin's; `delete_project` is `Admin`)); form rules are shared because tools pass the form's fields as `url.Values` to `services.Projects.Save`/`Connections.Save`, starting from `FormValues` of the stored record so fields not given keep their values. `get_storage` (`session.go`, the web app only): the data the database holds against `MAX_DATABASE_SIZE` (`services.Projects.Storage`, `store.ProjectUsage.Live`, the cleanup's own measure) with the parts of the projects the viewer sees (`ProjectUsage.OnDisk`), other (live minus those projects), the files apart (`files`, `ProjectUsage.Files`), the start and stop percents, `last_received`, `dropped` (per project, `ingest.DropCounter` through `services.Dependencies.Dropped`), for the Projects page. `get_session` (`session.go`, the web app only, `OpenWithTemporaryPassword`): the viewer (`user`, with `display_name`), `can_administer`, `app_name` (`services.All.AppName`), the unresolved count, `project_colors` (the shown color of every project the viewer sees, by name, `services.Projects.ColorsByName`; badges set it with the `style:` directive), `all_projects` (the viewer sees every project, future ones included), `assignable_roles` (`store.User.AssignableRoles`, empty for a user) and `theme` (the user's, `store.User.Theme`, empty until the app records one). `set_theme` (the web app only, `OpenWithTemporaryPassword`, `store.Themes` as `Choices`; `services.Users.SetTheme`, `Store.UpdateUserTheme`) saves the user's theme. The web app's own endpoints (never MCP, mostly because their output is unredacted): `count_issues`, `list_issue_levels`, `list_issue_projects` (the count, level choices and project choices of the issue list (the projects some issue is in, from the tallies, `IssueProjects`: no issue read), from the filters `list_issues` takes, `issueFiltersInput`; `issueOutput.mcp_reference`, `agentprompt.MCPReference`, is filled only for the web app); `list_log_levels` (the level choices of the logs list: the levels some stored log in the viewer's projects has, highest first; no filters); `list_issue_projects` and `list_log_projects` (the project choices: from the issue tallies, `Store.IssueProjects`; one seek per visible project in the logs' project index, `Store.LogProjects`); `get_issue_details` (`issue_details.go`: an issue with its history, its 20 newest events (`next_cursor` for `list_issue_events`, whose items carry `received_at`) and one event (`?event=`, the latest by default) read by `services.Issues.Details`: `event_state` shown, unreadable, missing (not stored, or another issue's) or none (`services.EventState`, generated as a union through `outputSchemas`), the facts, exceptions outermost first with frames newest first, maps as name-sorted pairs, JSON indented by Go, related logs, the stored payload and the agent prompt); `apply_issue_action` (resolve, ignore, reopen or delete 1 to `services.MaxActionIssues` issues, `services.IssueActions` as choices; `ignore_for`/`ignore_until_events` (`ignoreBoundInput`, also on `update_issue_status`) only with ignore, else 400 (`services.ErrBoundWithoutIgnore`); invalid ids 400; deleted ones skipped; delete needs `CanAdminister`, checked by `services.Issues.ApplyAction`, else 403; missing and hidden issues skipped); `delete_logs` (`Admin`, `Destructive`, not for agents, whose logs are for reading: `log_ids`, 1 to `services.MaxActionLogs`, missing ones skipped; `{deleted}`; `list_logs` rows carry their `id`; `count_logs` and `list_logs` say `stopped` and `searched_to` when the search ran out of time, `count_logs` gives `from_id` for `list_logs`, and a stopped `list_logs` has a `next_cursor` that goes on below where it stopped); `list_cleanups` (`services.Projects.Cleanups` → `ShownRun`: `VisibleRun`, the projects outside access as one Other row, sizes from `ShownRun.Left`), `get_project_setup` (every role; `connected`/`connected_at` from the first contact (`services.Projects.Contact`, `store.ProjectUsage.FirstContact`), `received` once something is stored), `get_project_defaults`; `get_user` (`{user, can_manage, can_take_over, access_editable}` with reasons); `get_mcp_setup` (`agents.go`: how to connect an agent); `get_connection` (saved tokens masked by `textutil.MaskSecret`, never whole), `get_connection_defaults`, `test_chat`, `count_deliveries`. `set_connection_active` (also MCP) changes only `active`: a whole-form save would refuse a connection whose tokens cannot be read. `list_users` rows are `get_user`'s; `userOutput` has `display_name` and `created_at`; `list_agents` returns `user_id`, `owners` (whose agents the caller may list, only when more than one) and `connected` per agent; `get_project` gives `shown_color`, and an unknown project is `services.Missing` (404, naming it and pointing to `list_projects`). `create_user`/`update_user` take the roles of `store.AssignableRoles` as `Choices`. `list_projects` gives every role the recorded log levels as an explicit list, highest first (`config.Recording.RecordedLogLevels`, also behind `services.Projects.FormValues`). `typescript_test.go` (`TestTypeScriptCatalog`) generates `web/src/lib/api/catalog.gen.ts` from the endpoints the web app may call: inputs from `InputSchema`, outputs from the handler's output type (`Define` keeps it; `time.Time` → `IsoTime`, `json.RawMessage` → `unknown`), the method and admin/destructive/confirm flags (an endpoint of the web app that answers `Text` fails it: the app reads JSON only), the plain requests (`PlainRequests`, `plainRequests`), `ErrorBody`, `choices`, `levels` (highest first), `shownLevel` (the aliases of `config.EventLevelAliases` too), `apiPrefix`, `maxLimit`, and the values of the server's rules: `limits` (`config.Limits`), `issueStatuses` (with `store.StatusMeanings`), `maxActionIssues` (`services.MaxActionIssues`), `projectPalette` (`config.ProjectPalette`), `personalTokenKind` (`store.GrantToken`), `cleanupSteps` and `cleanupRules` (the cleanup by size), `diskShare` (`store.MinDiskShare`, `MaxDiskShare`, `DiskShareStep`), `roleSummaries`, `help` (`docs.Fields`, and of `docs.Settings` only `shownSettings`: a field or variable the app names that is not generated fails its type check); an unsupported schema keyword fails it, a stale file fails `make test`, `make api-types` rewrites it (excluded from Prettier). Never requests of the catalog, in any transport: logins, changing your own password (the account page asks for the current one, through `session.Auth` and its login limit) and generating personal tokens (`TestCatalogNeverChangesCredentials`, which allows them only in `plain*.go`): they are the plain requests of the web app (`plain.go`, `PlainRequests`: `login_state`, `login`, `setup_admin`, `logout`, `change_password`, `personal_token`, `authorization_request`, `authorization_decision`, each with its method and the Go types of its JSON input and output, `NoContent` for a 204), whose handlers (`LoginRequests` in `plain.go`, `AgentRequests` in `plain_agents.go`, joined in `app.New`) `NewUI` takes by name and mounts on their method inside the same guard; no endpoint takes their names (`TestEndpointNames`). The mount checks no session: each handler reads it itself (`sessionViewer`, the one session check of the catalog's calls and the plain requests) and applies the temporary-password rule where it matters, since `login` and `login_state` must work without one: `login_state` `{app_name, disabled?, redirect?}` (`disabled` the reason nobody can log in, without an admin and `ADMIN_PASSWORD`; redirect = `server.SafeNext(next)` only with a valid session); `login` 503 without an admin and `ADMIN_PASSWORD`, 429 `session.TooManyAttempts` with `Retry-After` (the login window), 401 "Wrong email or password." for a wrong password and an unknown user alike, 200 `{next}`, or `{next, setup: true}` for the env credentials while there is no admin (no session; see Users and roles); `logout` 204 even without a session; `change_password` open with a temporary password, problems as 400 `{error, fields}`, the login limit 429 at `current_password` (`session.ErrTooManyAttempts`); `personal_token` and the consent requests 403 with a temporary password; a body over 64 KiB 413. The description (`ToolDescription`) of a `Destructive` tool, or a `Confirm` one (it changes who may access the server, where errors are sent or what it records), tells the agent to get an explicit confirmation in chat. +- `internal/api` (the catalog): the one catalog of requests, served as the REST API, as MCP tools and to the web app. `Endpoints(projects, services.All)` lists them in order; handlers reach data only through `services.All` (no store), so tools and pages apply the same rules (with nil arguments it only serves to read the definitions); each is `Define(Endpoint{Name, Description, ReadOnly, Idempotent, Destructive, Confirm, Admin, Transports, OpenWithTemporaryPassword}, handler)` with `handler(ctx, Call, In) (Out, error)`: the input schema comes from `In` (`json` + `jsonschema` tags, `jsonschema.For`) with the enums of `Choices` and the bounds of every `limit` (`DefaultLimit`, `MaxLimit`), `Run` validates the input map against it and decodes it. A new tool or API route = one entry + its handler; nothing else to register. `Call.Access()` is the projects the call sees (all for the REST token, the viewer's otherwise; handlers find projects by name or id through `services.Projects.Find` (`params.go`: `projectIDs` for filters, a missing one 404, a hidden one 403; `projectsField` for a form's field: unknown 400, hidden 403 at the field) and pass the access to services). `Call` has the `Transport` (`TransportREST`, `TransportMCP`, `TransportUI`; a `Call` without one runs nothing), the `Viewer` (the user of the agent or the web app; empty for the REST token), the `Actor` (recorded in the history) and the server `Address` (DSNs); `ForAgent()` is true unless the transport is REST or the web app (fail closed), and then `call.Text` redacts free text with `agentprompt.Redact`. Output is JSON, or `api.Text` written as is (the agent prompt of `get_issue`/`get_event`). Errors are sorted in one place (`OutcomeOf`: the HTTP status, the kind an MCP tool error starts with (`Outcome.ToolText`: `invalid: …`, `forbidden: …`, `not found: …`, `conflict: …`, `unavailable: …`, `internal error`) and the body), which `fail` (REST, the web app, the plain requests) and MCP's `failed` use: `InputError` with its status (`Invalid` 400, `notFound` 404, `conflict` 409, 413, 429 with `Retry-After`, 502 for a destination that refused a test message); `services.Reason` of `services.ErrForbidden` (the role or a rule of who may change whom; `services.Forbidden(reason)`), `services.ErrHidden` (a record of a project outside the viewer's; `services.Hidden(what, ids...)`, which names only what the caller gave, never the record's data) both 403, `store.ErrNotFound` (`services.Missing`) 404, `services.ErrConflict` 409; `services.Refusal` (a form refused as 403 or 409 with its fields, `formError` renames them; a taken project name 409, "This name cannot be used." for a hidden one); `ErrNotFound` 404; anything else logged and reported as "internal error". MCP adds the viewer's project names to a hidden record's refusal (`forbidden: issue k3x9q2mf is not in your projects (frontend, test2)`), which `list_projects` shows them anyway, so an agent tells a deleted issue from a hidden one; a 403 confirms only that an id or name exists. A refused form is `problemsError` (the problem of each field, renamed to the input's names) or `duplicateError` (409, the connection that already sends there, unnamed when hidden): over HTTP the body is `ErrorBody` `{error, fields?, duplicate?}` whatever the status, so a page shows each problem at its field, MCP gets the joined message (`TestInputErrorBody`, `errors_test.go`). Lists: `Page{items, next_cursor}`, 20 rows by default, at most 100, plain-number cursors (offset for issues/projects/deliveries, at most `store.MaxOffset` (`parseOffset`; `ListIssues` clamps too, since offset+limit must not overflow), last id for events/logs; `list_users` and `list_connections` return every row in one page). Every endpoint names its `Transports` (`Define` panics without; `AllTransports`, `ActsAsUser` = MCP and the web app, or one): `Run` refuses what `Refused(call)` names (`AllowedFor` is it being nil): an endpoint its transport does not serve (`ErrNotFound`), for a user without `CanAdminister` an `Admin` one (`services.ErrForbidden`, "your role may not do this"), and in the web app, while the user has a temporary password, anything without `OpenWithTemporaryPassword` (403 "change your password first"); the token runs every REST endpoint. REST only: `get_event_payload` (raw payload), `list_trace` (log attributes), their output must not reach a model provider (the web app reads the payload, indented, inside `get_issue_details`). `ActsAsUser` (`manage.go`, `notifications.go`): account, agents, projects, users, notification connections and email confirmation, acting as the user (`Users` and `Agents` refuse by role with `services.Forbidden` (403: "your role may not change this user" for a user changing an admin, `services.TakeOverProblem` for a user with projects the admin lacks; nobody changes themselves there: "change your own account on /account"); `Projects`, `Connections`, `Verification` and `Deliveries` check no role, only the access (`Projects.Save` keeps the disk share an admin's; `delete_project` is `Admin`)); form rules are shared because tools pass the form's fields as `url.Values` to `services.Projects.Save`/`Connections.Save`, starting from `FormValues` of the stored record so fields not given keep their values. `get_storage` (`session.go`, the web app only): the data the database holds against `MAX_DATABASE_SIZE` (`services.Projects.Storage`, `store.ProjectUsage.Live`, the cleanup's own measure) with the parts of the projects the viewer sees (`ProjectUsage.OnDisk`), other (live minus those projects), the files apart (`files`, `ProjectUsage.Files`), the start and stop percents, `last_received`, `dropped` (per project, `ingest.DropCounter` through `services.Dependencies.Dropped`), for the Projects page. `get_session` (`session.go`, the web app only, `OpenWithTemporaryPassword`): the viewer (`user`, with `display_name`), `can_administer`, `app_name` (`services.All.AppName`), the unresolved count, `project_colors` (the shown color of every project the viewer sees, by name, `services.Projects.ColorsByName`; badges set it with the `style:` directive), `all_projects` (the viewer sees every project, future ones included), `assignable_roles` (`store.User.AssignableRoles`, empty for a user) and `theme` (the user's, `store.User.Theme`, empty until the app records one). `set_theme` (the web app only, `OpenWithTemporaryPassword`, `store.Themes` as `Choices`; `services.Users.SetTheme`, `Store.UpdateUserTheme`) saves the user's theme. The web app's own endpoints (never MCP, mostly because their output is unredacted): `count_issues`, `list_issue_levels`, `list_issue_projects` (the count, level choices and project choices of the issue list (the projects some issue is in, from the tallies, `IssueProjects`: no issue read), from the filters `list_issues` takes, `issueFiltersInput`; `issueOutput.mcp_reference`, `agentprompt.MCPReference`, is filled only for the web app); `list_log_levels` (the level choices of the logs list: the levels some stored log in the viewer's projects has, highest first; no filters); `list_issue_projects` and `list_log_projects` (the project choices: from the issue tallies, `Store.IssueProjects`; one seek per visible project in the logs' project index, `Store.LogProjects`); `get_issue_details` (`issue_details.go`: an issue with its history, its 20 newest events (`next_cursor` for `list_issue_events`, whose items carry `received_at`) and one event (`?event=`, the latest by default) read by `services.Issues.Details`: `event_state` shown, unreadable, missing (not stored, or another issue's) or none (`services.EventState`, generated as a union through `outputSchemas`), the facts, exceptions outermost first with frames newest first, maps as name-sorted pairs, JSON indented by Go, related logs, the stored payload and the agent prompt); `apply_issue_action` (resolve, ignore, reopen or delete 1 to `services.MaxActionIssues` issues, `services.IssueActions` as choices; `ignore_for`/`ignore_until_events` (`ignoreBoundInput`, also on `update_issue_status`) only with ignore, else 400 (`services.ErrBoundWithoutIgnore`); invalid ids 400; deleted ones skipped; delete needs `CanAdminister`, checked by `services.Issues.ApplyAction`, else 403; missing and hidden issues skipped); `delete_logs` (`Admin`, `Destructive`, not for agents, whose logs are for reading: `log_ids`, 1 to `services.MaxActionLogs`, missing ones skipped; `{deleted}`; `list_logs` rows carry their `id`; `count_logs` and `list_logs` say `stopped` and `searched_to` when the search ran out of time, `count_logs` gives `from_id` for `list_logs`, and a stopped `list_logs` has a `next_cursor` that goes on below where it stopped); `list_cleanups` (`services.Projects.Cleanups` → `ShownRun`: `VisibleRun`, the projects outside access as one Other row, sizes from `ShownRun.Left`), `get_project_setup` (every role; `connected`/`connected_at` from the first contact (`services.Projects.Contact`, `store.ProjectUsage.FirstContact`), `received` once something is stored), `get_project_defaults`; `get_user` (`{user, can_manage, can_take_over, access_editable}` with reasons); `get_mcp_setup` (`agents.go`: how to connect an agent); `get_connection` (saved tokens masked by `textutil.MaskSecret`, never whole), `get_connection_defaults`, `test_chat`, `count_deliveries`. `set_connection_active` (also MCP) changes only `active`: a whole-form save would refuse a connection whose tokens cannot be read. `list_users` rows are `get_user`'s; `userOutput` has `display_name` and `created_at`; `list_agents` returns `user_id`, `owners` (whose agents the caller may list, only when more than one) and `connected` per agent; `get_project` gives `shown_color`, and an unknown project is `services.Missing` (404, naming it and pointing to `list_projects`). `create_user`/`update_user` take the roles of `store.AssignableRoles` as `Choices`. `list_projects` gives every role the recorded log levels as an explicit list, highest first (`config.Recording.RecordedLogLevels`, also behind `services.Projects.FormValues`). `typescript_test.go` (`TestTypeScriptCatalog`) generates `web/src/lib/api/catalog.gen.ts` from the endpoints the web app may call: inputs from `InputSchema`, outputs from the handler's output type (`Define` keeps it; `time.Time` → `IsoTime`, `json.RawMessage` → `unknown`), the method and admin/destructive/confirm flags (an endpoint of the web app that answers `Text` fails it: the app reads JSON only), the plain requests (`PlainRequests`, `plainRequests`), `ErrorBody`, `choices`, `levels` (highest first), `shownLevel` (the aliases of `config.EventLevelAliases` too), `apiPrefix`, `maxLimit`, and the values of the server's rules: `limits` (`config.Limits`), `issueStatuses` (with `store.StatusMeanings`), `maxActionIssues` (`services.MaxActionIssues`), `projectPalette` (`config.ProjectPalette`), `personalTokenKind` (`store.GrantToken`), `cleanupSteps` and `cleanupRules` (the cleanup by size), `diskShare` (`store.MinDiskShare`, `MaxDiskShare`, `DiskShareStep`), `roleSummaries`, `help` (`docs.Fields`, and of `docs.Settings` only `shownSettings`: a field or variable the app names that is not generated fails its type check); an unsupported schema keyword fails it, a stale file fails `make test`, `make api-types` rewrites it (excluded from Prettier). Never requests of the catalog, in any transport: logins, changing your own password (the account page asks for the current one, through `session.Auth` and its login limit) and generating personal tokens (`TestCatalogNeverChangesCredentials`, which allows them only in `plain*.go`): they are the plain requests of the web app (`plain.go`, `PlainRequests`: `login_state`, `login`, `setup_admin`, `logout`, `change_password`, `personal_token`, `authorization_request`, `authorization_decision`, each with its method and the Go types of its JSON input and output, `NoContent` for a 204), whose handlers (`LoginRequests` in `plain.go`, `AgentRequests` in `plain_agents.go`, joined in `app.New`) `NewUI` takes by name and mounts on their method inside the same guard; no endpoint takes their names (`TestEndpointNames`). The mount checks no session: each handler reads it itself (`sessionViewer`, the one session check of the catalog's calls and the plain requests) and applies the temporary-password rule where it matters, since `login` and `login_state` must work without one: `login_state` `{app_name, redirect?}` (redirect = `server.SafeNext(next)` only with a valid session); `login` 429 `session.TooManyAttempts` with `Retry-After` (the login window), 401 "Wrong email or password." for a wrong password and an unknown user alike, 200 `{next}`, or `{next, setup: true}` for the env credentials while there is no admin (no session; see Users and roles); `logout` 204 even without a session; `change_password` open with a temporary password, problems as 400 `{error, fields}`, the login limit 429 at `current_password` (`session.ErrTooManyAttempts`); `personal_token` and the consent requests 403 with a temporary password; a body over 64 KiB 413. The description (`ToolDescription`) of a `Destructive` tool, or a `Confirm` one (it changes who may access the server, where errors are sent or what it records), tells the agent to get an explicit confirmation in chat. - `internal/api` (`audit.go`): the audit log. Each changing handler records its change after it succeeded (`handler.audit` with an `auditChange`: resource, action, record id and name, projects, and views of the record before and after, `projectAudit`, `userAudit`, `connectionAudit`, `issueAudit`, `logAudit`, of which `services.AuditDiff` keeps the fields that differ and drops secret-named ones; `Replaced` puts `store.AuditReplaced` for a password or chat token that changed; a DSN reset keeps the old and the new DSN, field `dsn`), as `Call.Viewer` (email, role) or the API token, with `Call.Agent` (MCP: the grant's name) and `Call.IP` (`server.ClientIP`). Not recorded: own-account changes, test messages, refusals; an edit that changed nothing. The first admin's setup is recorded by `services.Users.SetupAdmin`. One request is one entry: a request that changed several records keeps them as `Items` (`store.AuditItem`), listed with `item_count` and a `record_name` such as "3 issues" (`itemsName`). `list_audit` (MCP and the web app) and `count_audit` read it through `services.Audit`, `list_audit_choices` (the web app) its filters' choices from tallies per project and resource, action and user (`auditTallies`, recounted once on databases from before them; `services.Audit.Choices`: the viewer's projects, of none only with every project, and the users they see; per project, so a rare entry spanning a project a limited viewer lacks can offer a value that matches nothing), `exists` saying the web app may link the record, and `get_audit_entry` (MCP and the web app) one entry with its items; an entry is seen by `AuditEntry.VisibleTo` (one record: all its projects within access; several: any item within it), trimmed to the viewer's items by `ShownTo` (403 outside it). A viewer who does not administer sees who acted only for the users they see (`AuditFilter.Actors`, `User.SeesUser`; `ShowsActor`): others are "Admin" or "User", without id, email, address or agent, and never found by `query` or `user_id`; agents never get the address. No endpoint changes it (`TestAuditTransports`). `audit_test.go` covers each action, secrets, visibility, actors and transports. - `internal/api` (`rest.go`, `NewREST`): serves the catalog under `/api/v1/` behind `protectAPI`: `GET` with query parameters when `ReadOnly` (converted with `Endpoint.FieldType`; lists repeated or comma-separated; unknown parameters 400), `POST` with a JSON object otherwise (`api.Route(transport, endpoint)`, the prefix from the transport; a body over 64 KiB 413; the other method at an endpoint's path 405 with `Allow`, `wrongMethod`, after the caller is checked). Routes are registered one by one by `register` (a subtree would overlap `/api/{projectID}/envelope/`, so names must never be `envelope`, `TestEndpointNames`); the HTTP transports share `serve` (the caller first, then the role, before the input is read, then the input and the run) and `fail`. Actor "API token" (`store.SourceAPI`). - `internal/api` (`ui.go`, `NewUI`): serves the catalog to the web app under `/api/ui/`, as the user of the login session (`SessionUsers`, the `session.Auth`): no valid session 401 `login required`, a session that could not be checked 500 (never a login loop). `guard` wraps every route and the fallback (`UI.ServeHTTP`: an unknown name 404 after the session check): `SecurityHeaders` with `default-src 'none'; frame-ancestors 'none'; sandbox`, `Cross-Origin-Resource-Policy: same-origin`, `Sec-Fetch-Site` cross-site or same-site 403, a change needs `application/json` (415) and a same-origin `Origin` (403); no CORS ever. The plain requests' handlers sit behind the same `guard` and the IP allowlist (`TestUIPlainRequests`). Actor the user with `store.SourceUI`; text unredacted (the user's own server). The API token, MCP tokens and the session never open each other's transports (`TestUIRequiresSession`). @@ -92,7 +92,7 @@ Where to look first: - `internal/oauth`: how agents sign in to MCP; `server.Options.OAuth` mounts its endpoints. OAuth 2.1 for public clients: discovery (`/.well-known/oauth-protected-resource`, `oauth-authorization-server` and `openid-configuration`, each with or without the MCP path), client identification by a Client ID Metadata Document (`clientmetadata.go`: a `client_id` that is an https URL is the client's published JSON with its name and redirect_uris, fetched at every authorization and never stored; the fetch reaches only public addresses, checked after DNS resolution in the dialer's `Control`, no redirects, no keep-alive, 5 s, 5 KB; the consent page shows the publishing host; `Server.MetadataClient` points tests at a local server) or dynamic registration (`POST /oauth/register`; clients that never connected go after an hour, and a full table (1024) evicts the oldest unused, answering 429 only when every client is in use; the code carries the client name, so the token exchange needs neither), the consent page `/oauth/authorize`, a page of the web app (`routes/(app)/oauth/authorize`): it sends the query as the agent sent it to the plain request `authorization_request` (`CheckRequest`; a refused request answers 400 with its reason and never a redirect; a valid one gives the client, its site, the redirect URI and a form token bound to the session cookie and the exact request, `Auth.FormToken`), then Allow/Deny to `authorization_decision` (the form token checked, the request checked again, the answer the redirect URL with the code or `access_denied`, which the page opens with `location.assign`); it keeps the app's `frame-ancestors 'none'` and `Referrer-Policy: same-origin`, so the agent never gets its address as a referrer, `POST /oauth/token` (code + S256 PKCE; refresh). Access tokens last an hour, refresh tokens 30 days and are replaced at every use; a spent refresh token presented again (theft) revokes the grant (collection `oauth_spent`). Redirects: https or loopback http, matched exactly except a loopback port. Codes and tokens are random 32 bytes, stored only as SHA-256 hashes; nothing is kept in memory, and one `oauth.Server` built in `app.New` is shared by MCP and the web app (through `services.Agents`). Registration and token requests are rate limited per client network (`server.ClientNetwork`: an IPv4 address or an IPv6 /64; 30 and 120 a minute; past 4096 networks a minute new ones share one overflow count of 10 times that, so a flood of networks is limited without locking out those counted), registrations also by a total of 120 a minute (each is a synced write; tokens have none, so connected agents keep refreshing), the client table is capped, and browser requests must come from the server's own origin. A grant is a connected agent or a personal token (one per user, shown once after Generate/Regenerate) and acts for a user (the grant's user id, from the code of the user who allowed it; a grant without a user does not work). Deleting a user or a password reset on the Users page disconnects their agents; changing your own password or the `reset-password` command keeps them. The web app's page `/agents` ("MCP" in the menu; `routes/(app)/agents`, `McpSetup`, `ConnectedApps`) has Claude Code / Codex / Other tabs (`?client=`) from `get_mcp_setup` (`services.Agents.Setup`: the endpoint `Server.ResourceAt(Call.Address)`, the commands, `.mcp.json`, `token_set`, `unencrypted` (`oauth.Unencrypted(address)`: agents would reach the server over plain HTTP from another machine), `ips_restricted`), the viewer's personal token (plain request `personal_token`, `services.Agents.NewPersonalToken`: the token and a setup prompt that has an agent add the server with it at user level and check it with `list_projects`, kept only in the component), and the connected apps of `list_agents` (`connected`, `store.Grant.Connected`: an unused personal token is no app) with Disconnect; admins choose whose apps from `owners` (`?user=`; one they may not take over is a 403 with the reason, an unknown one a 404). - `internal/services`: the rules and every database access of the web app's pages and the agents' tools (the catalog of `internal/api`), built together by `services.New` (`services.All`), once in `app.New` and passed to `api.Endpoints`; every method reading project data takes a `store.Access` after `ctx`, or a record read through one (an issue: `SelectedEvent`, `History`; connections: `DeliveryHealth`, `SetActive`, `SendTest`) (changes where the role matters take the viewer: `Projects.Save`, `Issues.ApplyAction` and `Users` use its `ProjectAccess()`, `Logs.Delete` takes the access beside it), and a record asked for outside it is `services.ErrHidden` (403), a missing one `store.ErrNotFound` (`Projects.Check`/`Find`, `Issues.Get`, `Connections.Get`; lists only leave it out: `Access.Restrict`: a filter that cannot match answers empty without the store, whose empty project filter means any; `services.Visible`: a connection whose projects are all within access, one for every project or none only with every project; `Deliveries` only of visible connections and about projects within access, a hidden `connection_id` 403; a duplicate destination of a hidden connection is refused without naming it); a change of several steps (a chat destination plus its connection, a replaced secret plus the save, find-or-create an email destination) is one service method. `Issues` (list/count/get/get many, events, recent events, `SelectedEvent`, `Details` (the issue page, `issue_details.go`), `ApplyAction`/`SetStatus`/`Delete`, related logs, agent prompt), `Logs` (list/count, issues of logs, `Delete`, `ErrForbidden` without `CanAdminister`), `Projects` (names, DSN, color, `ColorsByName`, unresolved counts, database size and each project's part, setup code per platform (`project_setup.go`, the one source); `Get`/`Save`/`Delete` and `FormValues`, the project form's rules in `project_form.go`), `Connections` (list, delivery health, get, `Save` (create or update from the form, `connection_form.go`: rule fields, chat secrets, availability, the confirmed address, duplicates, default name), `New` (a new connection's defaults), `FormValues`, `SetActive`/`SendTest` (`store.ErrNotVerified` for an unconfirmed address), `TestChat`, `RetryNow`, `Delete`), `Deliveries` (the outbox for the delivery log), `Verification` (email destinations, `StartEmail` (also to send a code again)/`ConfirmCode`, codes, `ResendCooldown`), `Users` (`SetupAdmin`, the first admin, and `LogSetup`, create with a temporary password, update, reset password, delete, own name; each checks the viewer's role and returns `ErrForbidden` with its reason, a role the viewer may not give or access they may not change a `Refusal` at the field; `DeviceStamp` for the login's known device), `Agents` (`Setup`, `Page`: whose agents to list; `NewPersonalToken` with its setup prompt; disconnect; consent: `CheckRequest`/`Decide`), `Sessions` (the logins, for `session.Auth`), `Audit` (`Record`: a failed write is logged, never the change's error; `List`/`Count` within an access; `AuditFields`/`AuditDiff`). Package tests use a real temp database. - `internal/session`: the login of the web app, `session.Auth`, built once in `app.New` and passed to `api.NewUI` and the plain requests (sessions of users, `CookieName`, `User` (`store.ErrNotFound` without a valid session, other errors as they are), `SessionUser`, `ChangePassword` (own password: the current password counts against the login limit, `withCurrentPassword`), `Login` returning `LoginOK`/`LoginWrongCredentials`/`LoginBlocked` with the login limit inside, `EndSession`, `Disabled` (no admin), `FormToken`/`ValidFormToken` (the consent page's, bound to the session cookie and an action); sessions are stored through `services.Sessions`), the login limit (`loginLimiter`: an attempt is counted before its password is checked, under one lock, so concurrent attempts cannot pass it; a known device (cookie `exceptic_device`: any browser the user logged in from, holding the last user who logged in there; `expires.user.stamp`, HMACs of the expiry with the email, checked before the database is read so a made-up cookie tells nothing by timing, and with `services.Users.DeviceStamp` (a hash of the user's ID, role and password hash, so a password change or reset, a role change or deletion ends it; the hash never leaves services) under a key derived from `SECRET_KEY`/`secret.key`, set at every login and own password change) gets 10 per 15 minutes per network and email and 30 per email from all networks, so strangers cannot lock its owner out; any other attempt counts per client network (`server.ClientNetwork`) and per email, 10 each; the right password clears the network's count only when all its attempts in the window were at that email, otherwise it takes only itself off (an insider cannot reset guesses at others); the counters live in memory, a key for its 15-minute window (swept every minute), and past 10k keys (`maxLimiterKeys`) a new network or email is refused until windows end, with a warning once per window, while known devices go on; at most half the cores (at least one) run password checks plus one place for known devices (`waitForCheck`), and an attempt waits at most 5 s (`passwordCheckWait`) before it is refused as `LoginBlocked`; `docs/deployment.md`, Securing it). Passwords are checked by `services.Users` (`Authenticate`, which checks unknown emails and users without a password hash against a dummy hash, for equal timing, and opens neither, and `ChangeOwnPassword`); the password primitives stay private to `services`, so nothing outside it can set a password without the role checks of `Users`. -- Users and roles: nothing creates users at start (`app.New` only logs, `services.Users.LogSetup`, how to set up an admin while there is none). While there is no admin, a login with `ADMIN_EMAIL`/`ADMIN_PASSWORD` (`session.Auth.Login`: through the same login limit and password-check places, after `Authenticate` fails; both compared in constant time and the admins read whatever was typed, `setupLogin`) starts no session but answers `LoginOutput.setup` and sets `exceptic_setup` (`internal/session/setup.go`: HttpOnly, SameSite=Strict, path `/api/ui/setup_admin`, 10 minutes, HMAC of its expiry and the env credentials under the device key), which opens the plain request `setup_admin` (`{email, password, confirm_password}`, problems at fields; without a valid cookie 403 `ErrSetupExpired`): `services.Users.SetupAdmin` (a real email, the password rules, not `ADMIN_PASSWORD`) and `store.CreateFirstAdmin`, which checks in the insert's batch that there is still no admin (`store.ErrAdminExists`, 403 `AdminExistsProblem`), then a new session; the login page swaps to `SetupAdminForm`. Once an admin exists the env credentials are a wrong login like any other; with none and no `ADMIN_PASSWORD` the UI is disabled (`login_state.disabled`). What each role may do is the methods of `store.User`, enforced by the catalog (`Admin`, `AllowedFor`) and services and shown by the web app from `get_session`'s `can_administer` and the rows' `can_manage`: admin everything (every project, other admins too, deleting projects, issues and logs, the disk share); user projects, notifications, the users of the role user they see (docs/ui.md Users), issue statuses, logs and their own MCP agents, each within their project access (a user sees and changes only the part of another user's access within his own: outputs show `Access.Shown`, `get_user` and `list_users` rows have `can_take_over`/`take_over_reason` (`store.User.CanTakeOver`: email, name, role, password, deleting and agents only of a user whose projects he all has, else the email, name and role are field problems, a reset, delete or agent request 403 with `services.TakeOverProblem`; the Users page shows such a row with its actions disabled with the reason (`menu.ts` `unavailable`), its page with only the projects editable) and `access_editable`/`access_reason`; `create_user`/`update_user` take `all_projects` and `projects`, a new user gets the creator's access by default; `store.RoleSummaries`, which deployment.md and the Users page show, says the same). The Users page adds users by email (`config.ParseEmail`, lowercase; no confirmation) with a temporary password shown once (`must_change_password`), changes email, name and role, resets the password, deletes; nobody changes themselves there: `/account` changes your own name and password; the email is set once when the user is added (no endpoint changes it) (the current one required; other sessions end). Session cookie (`HttpOnly`, `SameSite=Lax`, `Secure` behind HTTPS or always with an https `PUBLIC_URL` (`Auth.secure`, so TRUSTED_PROXIES is needed only for client addresses), valid `SESSION_LIFETIME`), its SHA-256 stored in `session` with the user; a login always issues a new session and deletes the one the browser had. Full-server tests add users with `webUser` (`internal/api/ui_test.go`, a session without a password check) and an admin who logs in with `startLoginServer`/`seedAdmin` (`login_test.go`, which lowers `services.PasswordIterations` for the package); `setup_test.go` drives the first-admin setup. +- Users and roles: nothing creates users at start (`app.New` only logs, `services.Users.LogSetup`, how to set up an admin while there is none). While there is no admin, a login with `ADMIN_EMAIL`/`ADMIN_PASSWORD` (`session.Auth.Login`: through the same login limit and password-check places, after `Authenticate` fails; both compared in constant time and the admins read whatever was typed, `setupLogin`) starts no session but answers `LoginOutput.setup` and sets `exceptic_setup` (`internal/session/setup.go`: HttpOnly, SameSite=Strict, path `/api/ui/setup_admin`, 10 minutes, HMAC of its expiry and the env credentials under the device key), which opens the plain request `setup_admin` (`{email, password, confirm_password}`, problems at fields; without a valid cookie 403 `ErrSetupExpired`): `services.Users.SetupAdmin` (a real email, the password rules, not `ADMIN_PASSWORD`) and `store.CreateFirstAdmin`, which checks in the insert's batch that there is still no admin (`store.ErrAdminExists`, 403 `AdminExistsProblem`), then a new session; the login page swaps to `SetupAdminForm`. Once an admin exists the env credentials are a wrong login like any other. Unset, they are `exceptic`/`exceptic` (`config.DefaultAdminEmail`, `DefaultAdminPassword`); `ADMIN_PASSWORD` takes any length, the admin's own password follows the rules. What each role may do is the methods of `store.User`, enforced by the catalog (`Admin`, `AllowedFor`) and services and shown by the web app from `get_session`'s `can_administer` and the rows' `can_manage`: admin everything (every project, other admins too, deleting projects, issues and logs, the disk share); user projects, notifications, the users of the role user they see (docs/ui.md Users), issue statuses, logs and their own MCP agents, each within their project access (a user sees and changes only the part of another user's access within his own: outputs show `Access.Shown`, `get_user` and `list_users` rows have `can_take_over`/`take_over_reason` (`store.User.CanTakeOver`: email, name, role, password, deleting and agents only of a user whose projects he all has, else the email, name and role are field problems, a reset, delete or agent request 403 with `services.TakeOverProblem`; the Users page shows such a row with its actions disabled with the reason (`menu.ts` `unavailable`), its page with only the projects editable) and `access_editable`/`access_reason`; `create_user`/`update_user` take `all_projects` and `projects`, a new user gets the creator's access by default; `store.RoleSummaries`, which deployment.md and the Users page show, says the same). The Users page adds users by email (`config.ParseEmail`, lowercase; no confirmation) with a temporary password shown once (`must_change_password`), changes email, name and role, resets the password, deletes; nobody changes themselves there: `/account` changes your own name and password; the email is set once when the user is added (no endpoint changes it) (the current one required; other sessions end). Session cookie (`HttpOnly`, `SameSite=Lax`, `Secure` behind HTTPS or always with an https `PUBLIC_URL` (`Auth.secure`, so TRUSTED_PROXIES is needed only for client addresses), valid `SESSION_LIFETIME`), its SHA-256 stored in `session` with the user; a login always issues a new session and deletes the one the browser had. Full-server tests add users with `webUser` (`internal/api/ui_test.go`, a session without a password check) and an admin who logs in with `startLoginServer`/`seedAdmin` (`login_test.go`, which lowers `services.PasswordIterations` for the package); `setup_test.go` drives the first-admin setup. - Google sign-in (`internal/session/google.go`, `GOOGLE_CLIENT_ID`/`GOOGLE_CLIENT_SECRET` with `PUBLIC_URL`, `config.Google`; no library): `GET /auth/google` sends the browser to Google with state, nonce and a PKCE S256 challenge whose secrets stay in a cookie signed with the device key (`exceptic_google`, path `/auth/google`, Lax, 10 minutes); `config.GoogleRedirectPath` checks the state, exchanges the code (client secret by HTTP Basic, no redirects followed), checks the ID token's claims (iss, aud, exp, nonce, `email_verified`; no signature check: it comes straight from Google over TLS, OIDC Core 3.1.3.7) and starts a session, or goes to `/login?error=` (`login.ts` `googleRefusal`). `services.Users.GoogleSignIn`: the user linked by `sub` (unique `google` index), else the user of the verified email, linked then by `Store.LinkGoogle`, which checks in its batch that the email is still theirs, no other account is linked (`ErrGoogleLinked`, result `not_linked`) and Google was not unlinked (`User.GoogleLinkOff`, `ErrGoogleOff`, result `unlinked`, cleared by a password sign-in, `RecordLogin`). `unlink_google` drops the link and disconnects the sessions opened through Google (`deleteGoogleSessions`, the viewer's own kept); an email never changes, so nothing else unlinks. Any Google-verified email links, Workspace and other domains too (the risk is in docs/deployment.md, the user's decision). Sessions record method, address, browser and last activity (`TouchSession` at most every `store.SessionActiveEvery`, also `User.LastActiveAt`; `Auth.touched` capped). The sign-in log (collection `signin`, `store.SignIn`): every attempt at an existing user, the newest `store.SignInsKept` sign-ins and as many refusals apart, so refusals never push a sign-in out; refusals are written apart from the answer (timing), at most `maxRecording` at once (more dropped), a blocked attempt once per network and email in a window (`loginLimiter.firstBlock`); rows of a user deleted meanwhile are not written. `get_activity`/`end_session`/`unlink_google` (`api/activity.go`, the web app only): viewing needs `CanManage` (or oneself), changing `CanTakeOver`; nobody disconnects the session they use (`Call.Session`, `store.SessionID`). `get_session` answers a temporary password without the projects' data (no unresolved count or colors). - Logs are tied to an error by span, not by trace (a browser keeps one trace for the whole tab, so every request from it shares the trace): a log belongs to an event if it has the same `trace_id` and its `span_id` (from the `sentry.trace.parent_span_id` attribute) is the event's `span_id` or `parent_span_id`. Without a span match the issue page (`get_issue_details`) falls back to logs of the same trace within a minute of the error, by the server's time or the device's (log batches without `sent_at` keep it), and says so (`logsAround`: one search over both, since dates also bound a search by arrival, keeping only the logs near either time; `ClockDrift` is 0 for a time ingest replaced). - `web/` (repo root): the web UI, a SvelteKit 3 + Tailwind 4 SPA. The folder is both the Node project (pnpm, version in `packageManager`; Kit 3 keeps its config in `vite.config.ts`, the `#lib` alias is a package.json import) and Go package `web` (`web.go`): `//go:embed all:dist` with a committed `dist/.gitkeep`, so Go builds and tests need no Node, and adapter-static writes `dist/spa` (an SPA: `ssr = false`, fallback `200.html`). `main` builds it (`web.New`; without a build it warns and no web UI is served) and passes it to `app.New` as `Options.Web`; full-server tests pass `fixtures.WebApp`, a stand-in build. The app (`web.App.Register`, the `/` pattern, behind the IP allowlist) takes every address no other route does; other methods than GET/HEAD there answer 404. `App.serve`: files under `_app/immutable/` cached for good, other built files `no-cache`, a missing `_app/` file 404, any other address the page (`no-store`). Strict CSP: Go hashes the page's inline scripts at start (SvelteKit boots with one, whose text changes every build) into `script-src`; no inline styles, so `app.html` uses classes and the inline style of Kit's `#svelte-announcer` is removed by `web/patches/@sveltejs__kit.patch` (`pnpm patch`; an update it no longer applies to fails the install), the element styled in `layout.css`. TypeScript 6: the npm package of TypeScript 7 has no compiler API, which svelte-check, Kit and typescript-eslint need (checked 2026-11-20). `make dev` (`tools/dev.sh`) puts Vite on PORT (8000) and the Go server on the next port (`EXCEPTIC_URL`); Vite proxies the server's own addresses (`/api/`, `/mcp`, `/health`, `/oauth/token|register|jwks`, `/.well-known/`, `/unsubscribe/`) to it without changing Host, so DSNs, OAuth and the Origin check see :8000. diff --git a/README.md b/README.md index 9cdf813..c579af8 100644 --- a/README.md +++ b/README.md @@ -20,11 +20,10 @@ Your apps send errors and logs with the official Sentry SDKs: just give the SDK ```sh docker run -d --name exceptic -p 8000:8000 -v exceptic-data:/data --memory 512m --stop-timeout 30 \ - -e ADMIN_PASSWORD='' \ devforth/exceptic:latest ``` -Open http://localhost:8000 and log in as `admin` with that password, then set up the first admin with your email and a password of your own. On the **Projects** page add a project and copy its DSN. +Open http://localhost:8000 and log in as `exceptic` with the password `exceptic`, then set up the first admin with your email and a password of your own. On the **Projects** page add a project and copy its DSN. For a server use [compose.yml](compose.yml) behind HTTPS: [Deployment](docs/deployment.md). diff --git a/cmd/exceptic/main.go b/cmd/exceptic/main.go index 58df400..891e82c 100644 --- a/cmd/exceptic/main.go +++ b/cmd/exceptic/main.go @@ -320,7 +320,7 @@ func resetPassword(args []string) error { case err != nil: return err case len(admins) == 0: - return errors.New("no admin yet: set ADMIN_PASSWORD, start the server and log in with ADMIN_EMAIL and it to set one up") + return errors.New("no admin yet: start the server and log in with ADMIN_EMAIL and ADMIN_PASSWORD to set one up") case len(admins) > 1: return fmt.Errorf("%d admins: name the one, exceptic reset-password ", len(admins)) } diff --git a/docs/configuration.md b/docs/configuration.md index 6f62f3d..a163533 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -24,8 +24,8 @@ Projects are added on the Projects page (or by a coding agent with `create_proje | Variable | Default | | |---|---|---| -| `ADMIN_EMAIL` | `admin` | Login for setting up the first admin: an email, up to 254 characters. | -| `ADMIN_PASSWORD` | | 12 to 256 characters. While there is no admin, log in with `ADMIN_EMAIL` and this password to create the first admin with your own email and password. After that both are ignored. | +| `ADMIN_EMAIL` | `exceptic` | Login for setting up the first admin: an email, up to 254 characters. | +| `ADMIN_PASSWORD` | `exceptic` | Any password up to 256 characters. While there is no admin, log in with `ADMIN_EMAIL` and this password to create the first admin with your own email and password. After that both are ignored. On a server others can reach, set your own: until the first admin exists, whoever logs in with these sets it up. | | `SESSION_LIFETIME` | `1d` | How long a login lasts. | | `GOOGLE_CLIENT_ID` | | With `GOOGLE_CLIENT_SECRET` and `PUBLIC_URL`: [Sign in with Google](deployment.md#sign-in-with-google). | | `GOOGLE_CLIENT_SECRET` | | The secret of that Google client. | diff --git a/docs/deployment.md b/docs/deployment.md index 5eb7a4c..f9cfeca 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -14,14 +14,14 @@ Image tags: `latest` (newest release), `X.Y` (newest patch of a minor version), ```sh PUBLIC_URL=https://errors.example.com - ADMIN_PASSWORD= + ADMIN_PASSWORD= SECRET_KEY= # encrypts chat tokens; generated into /data when not set ``` With an `https://` `PUBLIC_URL` the login works only over HTTPS: set up the proxy first ([HTTPS and a reverse proxy](#https-and-a-reverse-proxy)). To try it on plain http, use `PUBLIC_URL=http://:8000` and publish `"8000:8000"`. -3. Run `docker compose up -d`, open `https://errors.example.com` and log in as `admin`. The password is `ADMIN_PASSWORD`. A form opens where you create the first admin with your email and your own password. +3. Run `docker compose up -d`, open `https://errors.example.com` and log in as `exceptic`. The password is `ADMIN_PASSWORD`. A form opens where you create the first admin with your email and your own password. 4. On the **Projects** page add a project and give its DSN to your app: [Connecting apps](sdk.md). The container runs as an unprivileged user (uid 65534). A bind-mounted data folder must be writable by it: `sudo chown 65534:65534 ./data`. A named volume, as in the example, needs nothing. @@ -90,13 +90,14 @@ server { Give the container 512 MB: `compose.yml` sets `mem_limit: 512m`, with `docker run` add `--memory 512m`. The server sizes its memory and its queue by that limit, and needs no more; without a limit it keeps to a smaller default whatever the machine has ([`GOMEMLIMIT`](configuration.md#server), [Ingest](configuration.md#ingest)). -How much the server can take at most, by CPU, in a 512 MB container: the most errors it stored while 10 processes of the official Node.js SDK sent them without pause. Each error was about 16 KB (a stack trace, 10 breadcrumbs, user, tags). Normal use is far below this. +How much the server can store at most, by CPU, in a 512 MB container: the most errors a minute it kept storing for 10 minutes without falling behind. Each error was about 16 KB (a stack trace with source, 10 breadcrumbs, user, tags, request). This is close to the worst case: 3 in 4 errors were new. Repeated errors cost less: an issue stores up to 10 of its errors a minute and only counts the rest. -| CPU | 2 | 4 | +| CPU | 1 | 2 | |---|---|---| -| Errors a minute, all projects together | 35,600 | 54,100 | -| Data a minute | 555 MB | 845 MB | -| A full database, the cleanup deleting meanwhile | 19,900 errors, 310 MB | 31,500 errors, 490 MB | +| Errors a minute, all projects together | 20,000 | 40,000 | +| Data a minute | 315 MB | 630 MB | + +Memory does not change these numbers: with 1 CPU, 256 MB stored as much as 512 MB. It matters once the database is full and the cleanup compacts it: writes wait meanwhile and envelopes are held in memory, so a smaller container refuses sooner ([Ingest](configuration.md#ingest)). Logs sent along take their share: with 5 logs per error, about a quarter fewer errors. diff --git a/docs/dockerhub.md b/docs/dockerhub.md index 4ddca14..9ca4ba3 100644 --- a/docs/dockerhub.md +++ b/docs/dockerhub.md @@ -9,11 +9,10 @@ Source and full documentation: https://github.com/devforth/exceptic ```sh docker run -d --name exceptic -p 8000:8000 -v exceptic-data:/data --memory 512m --stop-timeout 30 \ - -e ADMIN_PASSWORD='' \ devforth/exceptic:latest ``` -Open http://localhost:8000 and log in as `admin` with that password, then set up the first admin with your email and a password of your own. On the **Projects** page add a project and copy its DSN. +Open http://localhost:8000 and log in as `exceptic` with the password `exceptic`, then set up the first admin with your email and a password of your own. On the **Projects** page add a project and copy its DSN. For a server use Docker Compose behind HTTPS: [compose.yml](https://github.com/devforth/exceptic/blob/main/compose.yml) with an `.env` next to it: @@ -21,7 +20,7 @@ For a server use Docker Compose behind HTTPS: [compose.yml](https://github.com/d ```sh PUBLIC_URL=https://errors.example.com -ADMIN_PASSWORD= +ADMIN_PASSWORD= SECRET_KEY= # encrypts chat tokens; generated into /data when not set ``` diff --git a/docs/values_test.go b/docs/values_test.go index c11ed4e..c1548b3 100644 --- a/docs/values_test.go +++ b/docs/values_test.go @@ -48,8 +48,8 @@ func TestDocsValues(t *testing.T) { value{Phrase: "| `GOMEMLIMIT` | {}% of the", Value: config.ContainerMemoryPercent}, value{Phrase: "memory limit, else `{}MiB` |", Value: config.DefaultMemoryLimit >> 20}, value{Phrase: "| `ADMIN_EMAIL` | `{}` |", Value: config.DefaultAdminEmail}, - value{Phrase: "| `ADMIN_PASSWORD` | | {} to ", Value: config.MinPasswordLength}, - value{Phrase: " to {} characters. While there is no admin", Value: config.MaxPasswordLength}, + value{Phrase: "| `ADMIN_PASSWORD` | `{}` |", Value: config.DefaultAdminPassword}, + value{Phrase: "| Any password up to {} characters.", Value: config.MaxPasswordLength}, value{Phrase: "| `SESSION_LIFETIME` | `{}` |", Value: days(config.DefaultSessionLifetime)}, value{Phrase: "REST API](api.md), at least {} characters", Value: config.MinAPITokenLength}, value{Phrase: "| `RATE_LIMIT_EVENTS_PER_MINUTE` | `{}` |", Value: config.DefaultRateLimitEventsPerMinute}, @@ -122,7 +122,6 @@ func TestDocsValues(t *testing.T) { value{Phrase: "files of {} MB (`json-file`)", Value: logSize}, value{Phrase: "`--log-opt max-size={}m ", Value: logSize}, value{Phrase: "--log-opt max-file={}`", Value: logFiles}, - value{Phrase: "ADMIN_PASSWORD=", Value: config.MinPasswordLength}, value{Phrase: "open `https://errors.example.com` and log in as `{}`.", Value: config.DefaultAdminEmail}, value{Phrase: "request bodies up to {} MB", Value: ingest.MaxBodyBytes >> 20}, value{Phrase: "max_size {}MB", Value: ingest.MaxBodyBytes >> 20}, @@ -147,13 +146,12 @@ func TestDocsValues(t *testing.T) { ) fixtures.DocValues(t, "README.md", - value{Phrase: "ADMIN_PASSWORD=''", Value: config.MinPasswordLength}, - value{Phrase: "log in as `{}` with that password", Value: config.DefaultAdminEmail}, + value{Phrase: "log in as `{}` with the password", Value: config.DefaultAdminEmail}, + value{Phrase: "with the password `{}`, then", Value: config.DefaultAdminPassword}, value{Phrase: "--stop-timeout {} \\", Value: grace}, value{Phrase: "--memory {}m --stop-timeout", Value: memory}, ) fixtures.DocValues(t, "skills/exceptic/SKILL.md", - value{Phrase: "`ADMIN_PASSWORD` ({}+ characters)", Value: config.MinPasswordLength}, value{Phrase: "Tell the user to log in as `{}`", Value: config.DefaultAdminEmail}, value{Phrase: "sends only `{}`, so", Value: notifyLevels}, ) diff --git a/internal/api/login_test.go b/internal/api/login_test.go index f8dfe21..24476c7 100644 --- a/internal/api/login_test.go +++ b/internal/api/login_test.go @@ -360,7 +360,7 @@ func TestUILoginRedirectStaysOnSite(t *testing.T) { var state api.LoginState if err := json.Unmarshal(server.browser().call(http.MethodGet, "login_state?next=/logs", nil).Body.Bytes(), &state); err != nil || - state.Redirect != "" || state.Disabled != "" || state.AppName != server.app.Services.AppName { + state.Redirect != "" || state.AppName != server.app.Services.AppName { t.Errorf("login_state without a session: %+v", state) } } @@ -539,22 +539,6 @@ func TestUISecureCookiesFromPublicURL(t *testing.T) { } } -// Without an admin nobody can log in; the login page says why. -func TestUIDisabledWithoutPassword(t *testing.T) { - server := startLoginServer(t, storetest.Open(t), "admin", "") - client := server.browser() - - var state api.LoginState - - if err := json.Unmarshal(client.call(http.MethodGet, "login_state", nil).Body.Bytes(), &state); err != nil || !strings.Contains(state.Disabled, "ADMIN_PASSWORD") { - t.Fatalf("login_state: %+v %v", state, err) - } - - if response := client.login("admin", ""); response.Code != http.StatusServiceUnavailable || !strings.Contains(response.Body.String(), "ADMIN_PASSWORD") { - t.Fatalf("login: %d %s", response.Code, response.Body) - } -} - // Sessions survive restarts, and a restart with any ADMIN_EMAIL and // ADMIN_PASSWORD creates no user once an admin exists. func TestUISessionsSurviveRestart(t *testing.T) { diff --git a/internal/api/plain.go b/internal/api/plain.go index b20f6a6..0ec5132 100644 --- a/internal/api/plain.go +++ b/internal/api/plain.go @@ -47,9 +47,7 @@ type LoginStateInput struct { // LoginState is what the login page shows; Redirect (a local path) when the // browser is logged in already. type LoginState struct { - AppName string `json:"app_name"` - // Disabled says why nobody can log in (no ADMIN_PASSWORD); empty otherwise. - Disabled string `json:"disabled,omitempty"` + AppName string `json:"app_name"` Redirect string `json:"redirect,omitempty"` // Google: the page offers to sign in with Google. Google bool `json:"google,omitempty"` @@ -92,9 +90,6 @@ type PersonalToken struct { // wrongLogin is the answer to a wrong password and to an unknown email alike. const wrongLogin = "Wrong email or password." -// loginDisabled is why nobody can log in to a server without an admin. -const loginDisabled = "The web UI is disabled: set ADMIN_PASSWORD to enable it." - // LoginRequests are the handlers of the login's plain requests (login_state, // login, setup_admin, logout, change_password) for NewUI. Every password check goes // through auth, so the login's limits apply to each. @@ -107,10 +102,6 @@ func LoginRequests(logger *slog.Logger, auth *session.Auth, appName string) map[ "login_state": http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { state := LoginState{AppName: appName, Google: auth.GoogleEnabled()} - if auth.Disabled(r.Context()) { - state.Disabled = loginDisabled - } - // Logged in already: straight on. if _, ok := auth.SessionUser(r); ok { state.Redirect = server.SafeNext(r.URL.Query().Get("next")) @@ -126,13 +117,6 @@ func LoginRequests(logger *slog.Logger, auth *session.Auth, appName string) map[ return } - // Not a refusal of this user: the server has none yet. - if auth.Disabled(r.Context()) { - server.JSONError(w, http.StatusServiceUnavailable, loginDisabled) - - return - } - result, err := auth.Login(w, r, input.Email, input.Password) switch { diff --git a/internal/api/setup_test.go b/internal/api/setup_test.go index 05926e7..39de989 100644 --- a/internal/api/setup_test.go +++ b/internal/api/setup_test.go @@ -76,7 +76,7 @@ func TestSetupAdmin(t *testing.T) { var state api.LoginState - if err := json.Unmarshal(client.call(http.MethodGet, "login_state", nil).Body.Bytes(), &state); err != nil || state.Disabled != "" { + if err := json.Unmarshal(client.call(http.MethodGet, "login_state", nil).Body.Bytes(), &state); err != nil || state.AppName == "" { t.Fatalf("login_state: %+v %v", state, err) } diff --git a/internal/app/app.go b/internal/app/app.go index dd86d5c..0f04c85 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -83,7 +83,7 @@ func New(ctx context.Context, options Options) (*App, error) { }) // Nothing creates users at start: the first admin is set up on the login page. - if err := all.Users.LogSetup(ctx, settings.AdminPassword); err != nil { + if err := all.Users.LogSetup(ctx); err != nil { _ = notifier.Close(ctx) return nil, err diff --git a/internal/platform/config/config.go b/internal/platform/config/config.go index c28b72c..6def0e8 100644 --- a/internal/platform/config/config.go +++ b/internal/platform/config/config.go @@ -118,8 +118,7 @@ func validAdminEmail(value string) bool { return isEmail || (len(value) <= MaxEmail && adminLoginRe.MatchString(value)) } -// ValidPasswordLength is the length rule of every password, ADMIN_PASSWORD -// included, in characters. +// ValidPasswordLength is the length rule of every user's password, in characters. func ValidPasswordLength(password string) bool { length := utf8.RuneCountInString(password) @@ -179,8 +178,7 @@ type Config struct { TrustedProxies Proxies // AdminEmail and AdminPassword, typed on the login page while there is // no admin, open the form that sets up the first one; later they are not - // used. AdminEmail is the login as typed, an email or not. An empty - // password keeps the UI closed until then. + // used. AdminEmail is the login as typed, an email or not. AdminEmail string AdminPassword string // SessionLifetime (SESSION_LIFETIME) is how long a UI login lasts; it @@ -208,7 +206,9 @@ const ( SDKLogBatch = 100 DefaultMemoryLimit = 200 << 20 // GOMEMLIMIT outside a container with a memory limit - DefaultAdminEmail = "admin" + // The login that opens the first admin's setup, unless ADMIN_EMAIL and ADMIN_PASSWORD are set. + DefaultAdminEmail = "exceptic" + DefaultAdminPassword = "exceptic" DefaultSessionLifetime = 24 * time.Hour @@ -254,6 +254,7 @@ func loadFrom(getenv func(string) string) (*Config, error) { RateLimitEventsPerMinute: DefaultRateLimitEventsPerMinute, RateLimitLogsPerMinute: DefaultRateLimitLogsPerMinute, AdminEmail: DefaultAdminEmail, + AdminPassword: DefaultAdminPassword, SessionLifetime: DefaultSessionLifetime, } @@ -324,8 +325,9 @@ func loadFrom(getenv func(string) string) (*Config, error) { } if value := getenv("ADMIN_PASSWORD"); value != "" { - if !ValidPasswordLength(value) { - return nil, fmt.Errorf("ADMIN_PASSWORD: must be %d to %d characters", MinPasswordLength, MaxPasswordLength) + // Any length: it only opens the first admin's setup, whose own password follows the rules. + if utf8.RuneCountInString(value) > MaxPasswordLength { + return nil, fmt.Errorf("ADMIN_PASSWORD: at most %d characters", MaxPasswordLength) } config.AdminPassword = value diff --git a/internal/platform/config/config_test.go b/internal/platform/config/config_test.go index aef6d98..d9f76d4 100644 --- a/internal/platform/config/config_test.go +++ b/internal/platform/config/config_test.go @@ -24,7 +24,7 @@ func TestLoadDefaults(t *testing.T) { if config.Port != DefaultPort || config.DataDir != DefaultDataDir || config.LogLevel != DefaultLogLevel || config.APIToken != "" || config.AllowedIPs != nil || config.RateLimitEventsPerMinute != 10000 || config.RateLimitLogsPerMinute != 10000 || - config.AdminEmail != DefaultAdminEmail || config.AdminPassword != "" || config.SessionLifetime != 24*time.Hour { + config.AdminEmail != DefaultAdminEmail || config.AdminPassword != DefaultAdminPassword || config.SessionLifetime != 24*time.Hour { t.Fatalf("unexpected defaults: %+v", config) } } @@ -133,8 +133,7 @@ func TestLoadErrors(t *testing.T) { {"negative events rate limit", "RATE_LIMIT_EVENTS_PER_MINUTE", "-1", "RATE_LIMIT_EVENTS_PER_MINUTE"}, {"bad logs rate limit", "RATE_LIMIT_LOGS_PER_MINUTE", "10k", "RATE_LIMIT_LOGS_PER_MINUTE"}, {"short api token", "API_TOKEN", "secret", "at least"}, - {"short admin password", "ADMIN_PASSWORD", "short-pass", "12 to 256"}, - {"long admin password", "ADMIN_PASSWORD", strings.Repeat("p", MaxPasswordLength+1), "12 to 256"}, + {"long admin password", "ADMIN_PASSWORD", strings.Repeat("p", MaxPasswordLength+1), "at most 256"}, {"admin email with a space", "ADMIN_EMAIL", "john doe", "ADMIN_EMAIL"}, {"long admin email", "ADMIN_EMAIL", strings.Repeat("a", MaxEmail+1), "ADMIN_EMAIL"}, {"former admin variable with a space", "ADMIN_USERNAME", "john doe", "ADMIN_USERNAME"}, @@ -254,3 +253,12 @@ func TestAdminEmail(t *testing.T) { }) } } + +// ADMIN_PASSWORD only opens the first admin's setup, so a short one is accepted. +func TestShortAdminPassword(t *testing.T) { + config, err := loadFrom(env(map[string]string{"ADMIN_EMAIL": "exceptic", "ADMIN_PASSWORD": "exceptic"})) + + if err != nil || config.AdminPassword != "exceptic" { + t.Fatalf("config %+v, err %v", config, err) + } +} diff --git a/internal/services/users.go b/internal/services/users.go index 10f1827..f1b17c7 100644 --- a/internal/services/users.go +++ b/internal/services/users.go @@ -34,15 +34,13 @@ func NewUsers(logger *slog.Logger, database store.Store) *Users { } // LogSetup says at start, while there is no admin, how to set one up. -func (users *Users) LogSetup(ctx context.Context, adminPassword string) error { +func (users *Users) LogSetup(ctx context.Context) error { admins, err := users.store.Admins(ctx) switch { case err != nil: return err case len(admins) > 0: - case adminPassword == "": - users.logger.Warn("no admin yet: set ADMIN_PASSWORD (and ADMIN_EMAIL), the UI is closed until then") default: users.logger.Info("no admin yet: log in with ADMIN_EMAIL and ADMIN_PASSWORD to set one up") } diff --git a/internal/session/session.go b/internal/session/session.go index d6a039b..b8f7043 100644 --- a/internal/session/session.go +++ b/internal/session/session.go @@ -387,14 +387,6 @@ func (auth *Auth) waitForCheck(ctx context.Context, knownDevice bool) (done func } } -// Disabled: there is no admin yet and no ADMIN_PASSWORD to set one up -// with, so nobody can log in. -func (auth *Auth) Disabled(ctx context.Context) bool { - open, err := auth.open(ctx) - - return err == nil && !open && auth.adminPassword == "" -} - // open reports whether an admin exists. func (auth *Auth) open(ctx context.Context) (bool, error) { if auth.opened.Load() { diff --git a/skills/exceptic/SKILL.md b/skills/exceptic/SKILL.md index e31c61a..8097705 100644 --- a/skills/exceptic/SKILL.md +++ b/skills/exceptic/SKILL.md @@ -29,9 +29,9 @@ Read the page for the task before acting, rather than relying on memory: it matc ## Deploy the server 1. Read deployment.md and configuration.md. Ask where it runs (this machine for a try, or a server with a domain) and whether a reverse proxy with HTTPS already exists. -2. Use the `compose.yml` from deployment.md and an `.env` next to it with at least `ADMIN_PASSWORD` (12+ characters) and, on a server, `SECRET_KEY` (otherwise generated into the data directory), `PUBLIC_URL=https://` with the port published on `127.0.0.1` (as `compose.yml` does) and a reverse proxy with HTTPS on the same machine; `TRUSTED_PROXIES` only in the cases of deployment.md, Other setups. Let the user choose the admin password or tell them where it is stored; do not print it. +2. Use the `compose.yml` from deployment.md and an `.env` next to it with at least `ADMIN_PASSWORD` and, on a server, `SECRET_KEY` (otherwise generated into the data directory), `PUBLIC_URL=https://` with the port published on `127.0.0.1` (as `compose.yml` does) and a reverse proxy with HTTPS on the same machine; `TRUSTED_PROXIES` only in the cases of deployment.md, Other setups. Let the user choose the admin password or tell them where it is stored; do not print it. 3. Start it with `docker compose up -d` (or let the user start it if they prefer), then check `curl -fsS /health`. -4. Tell the user to log in as `admin` with `ADMIN_PASSWORD`, set up the first admin with their own email and a new password in the form that opens, and add a project per service on the **Projects** page. +4. Tell the user to log in as `exceptic` with `ADMIN_PASSWORD`, set up the first admin with their own email and a new password in the form that opens, and add a project per service on the **Projects** page. ## Connect this agent (MCP) diff --git a/web/src/lib/api/catalog.gen.ts b/web/src/lib/api/catalog.gen.ts index 9041fdd..0c02774 100644 --- a/web/src/lib/api/catalog.gen.ts +++ b/web/src/lib/api/catalog.gen.ts @@ -1427,7 +1427,6 @@ export interface PlainRequests { }; out: { app_name: string; - disabled?: string; redirect?: string; google?: boolean; }; diff --git a/web/src/routes/login/LoginPage.svelte b/web/src/routes/login/LoginPage.svelte index 60388b2..439ea6a 100644 --- a/web/src/routes/login/LoginPage.svelte +++ b/web/src/routes/login/LoginPage.svelte @@ -70,9 +70,7 @@ to go after it (a local path only); a full load opens that page with a fresh ses

{data.state.app_name}

- {#if data.state.disabled} - {data.state.disabled} - {:else if setup} + {#if setup} {:else}
diff --git a/web/src/routes/login/login.test.ts b/web/src/routes/login/login.test.ts index 3577997..d1082bb 100644 --- a/web/src/routes/login/login.test.ts +++ b/web/src/routes/login/login.test.ts @@ -22,8 +22,8 @@ afterEach(() => { mocks.assign.mockReset(); }); -function renderLogin(disabled?: string) { - render(LoginPage, { data: { state: { app_name: 'Exceptic', disabled } } } as never); +function renderLogin() { + render(LoginPage, { data: { state: { app_name: 'Exceptic' } } } as never); } const field = (name: string) => screen.getByLabelText(name); @@ -100,11 +100,4 @@ describe('the login page', () => { }); await waitFor(() => expect(mocks.assign).toHaveBeenCalledWith('/')); }); - - it('says why nobody can log in without an admin', () => { - renderLogin('The web UI is disabled: set ADMIN_PASSWORD to enable it.'); - - expect(screen.getByText(/The web UI is disabled/)).toBeTruthy(); - expect(screen.queryByRole('button', { name: 'Log in' })).toBeNull(); - }); });