From db0ec027106502b6d6b0b5e89f85f75f9fe87e57 Mon Sep 17 00:00:00 2001 From: Ivan Husev Date: Fri, 4 Dec 2026 13:45:12 +0200 Subject: [PATCH 1/3] feat: typed inputs for the project and connection forms instead of url.Values DevFo-OSS/17 --- CLAUDE.md | 4 +- internal/api/endpoint.go | 24 ++-- internal/api/manage.go | 59 +++------- internal/api/notifications.go | 104 +++++------------ internal/api/notifications_ui_test.go | 13 +++ internal/api/params.go | 2 +- internal/api/plain.go | 4 +- internal/api/transport_test.go | 2 +- internal/services/connection_form.go | 155 +++++++++++++------------ internal/services/project_form.go | 101 ++++++++-------- internal/services/project_form_test.go | 46 ++++---- internal/services/projects.go | 13 +-- internal/services/services_test.go | 3 +- 13 files changed, 234 insertions(+), 296 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 6e18018..cb2f6e8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -84,13 +84,13 @@ 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, 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` (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, keyed by the input's names; 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, by 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`)); the handlers pass their typed input to `services.Projects.Save`/`Connections.Save` as a `services.ProjectChange`/`ConnectionChange` (a nil field keeps the stored value, an empty list clears it; the kept values are checked again too), whose problems are keyed by the input's names. `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 `get_project_defaults`). `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`). - `internal/api` (`mcp.go`, `NewMCP`): MCP server for coding agents at `/mcp` (official `github.com/modelcontextprotocol/go-sdk`, Streamable HTTP, stateless, JSON responses; `run` recovers a panicking tool (`logging.PanicError`) into "internal error", since the SDK runs tools in goroutines without a recover; the SDK's localhost protection is off because a reverse proxy on the same host would trip it, and a token is required anyway). Behind `ALLOWED_IPS`, then `oauth.Protect` (OAuth access token or the personal token; `API_TOKEN` is the REST API's only). Tools are the catalog endpoints an agent's user may use, plus `fetch_skill` (agent only, `skills.go`), registered with `Server.AddTool` and the endpoint's schema: one `sdk.Server` per role, built at startup; `withCaller` (after `oauth.Protect`) reads the grant's user from the store at every request, so a role change applies at once (a deleted user 401 as an invalid token, `oauth.RefuseToken`; a failed read 500), and puts the `api.Call` into the context, which picks the server and reaches the tool handlers. `list_issues`, `get_issue` (latest or given event as the full agent prompt, `agentprompt.Build(services.AgentInput(...))` with up to 20 related logs), `get_issues` (`missing_issue_ids` apart from `forbidden_issue_ids`, other projects') and `update_issue_status` (1–100 IDs, `store.NormalizeIssueIDs`; the update is atomic: a hidden ID (403, checked first) or a missing one (404, named) changes nothing; recorded in the history as the grant's user, the call's `Actor`, found through `oauth.GrantOf(auth.TokenInfoFromContext(...))`, since `oauth.Protect` hands the grant to the SDK as its `auth.TokenInfo`), `delete_issue` (admins, destructive; also REST), `list_issue_events`, `get_event`, `list_logs` (`trace_id` for one request; a search that ran out of time says `stopped` and goes on by `next_cursor`), `list_projects` (with each project's `dsn`: `withCaller` puts the server address, `server.PublicURL`, into `Call.Address` and `config.Project.DSN` builds it, the same function as the Projects page), `fetch_skill`. Output goes to the agent's model provider: text is redacted (`ForAgent()`), raw payloads and log attributes are never returned. `instructions.md` (sent with every connection, kept short) gives the workflow and lists the skills; `skills/*/SKILL.md` are loaded on demand by `fetch_skill` (their names and descriptions come from their front matter), one topic each, no rule repeated between them and the instructions. Notifications carry ` MCP: get_issue {"issue_id":"k3x9q2mf"}` (`notify.mcpReference`, built by `agentprompt.MCPReference`). - `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/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`, the project form's rules in `project_form.go` (`ProjectChange`)), `Connections` (list, delivery health, get, `Save` (create or update from a `ConnectionChange`, `connection_form.go`: rule fields, chat secrets, availability, the confirmed address, duplicates, default name), `New` (a new connection's defaults), `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. 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). diff --git a/internal/api/endpoint.go b/internal/api/endpoint.go index 88104b0..c192e36 100644 --- a/internal/api/endpoint.go +++ b/internal/api/endpoint.go @@ -10,6 +10,7 @@ import ( "encoding/json" "errors" "fmt" + "maps" "net/http" "net/url" "reflect" @@ -408,38 +409,33 @@ func duplicateError(duplicate services.Duplicate, what string) error { const hiddenDuplicate = "Another connection already sends there." // problemsError reports the field errors of a form as one InputError -// ("name: ...; levels: ..."), nil when there are none. fields renames form -// fields to the tool's input names. -func problemsError(problems map[string]string, fields map[string]string) error { +// ("name: ...; levels: ..."), nil when there are none. +func problemsError(problems map[string]string) error { if len(problems) == 0 { return nil } - var lines []string - - named := make(map[string]string, len(problems)) + lines := make([]string, 0, len(problems)) for field, problem := range problems { - name := cmp.Or(fields[field], field) - named[name] = problem - lines = append(lines, name+": "+problem) + lines = append(lines, field+": "+problem) } slices.Sort(lines) - return InputError{message: strings.Join(lines, "; "), fields: named} + return InputError{message: strings.Join(lines, "; "), fields: maps.Clone(problems)} } // formError is the error of a form: a services.Refusal with its status -// (403 or 409) and its fields renamed, err as it is otherwise. -func formError(err error, fields map[string]string) error { +// (403 or 409) and its fields, err as it is otherwise. +func formError(err error) error { var refusal services.Refusal if !errors.As(err, &refusal) { return err } - input, _ := problemsError(refusal.Problems, fields).(InputError) + input, _ := problemsError(refusal.Problems).(InputError) input.status = refusalStatus(refusal.Kind) return input @@ -500,7 +496,7 @@ func OutcomeOf(err error) Outcome { outcome.Status, outcome.RetryAfter, outcome.Hidden = cmp.Or(input.status, http.StatusBadRequest), input.retryAfter, input.hidden outcome.Body = ErrorBody{Error: input.message, Fields: input.fields, Duplicate: input.duplicate} case errors.As(err, &refusal): - return OutcomeOf(formError(refusal, nil)) + return OutcomeOf(formError(refusal)) case errors.As(err, &reason): outcome.Status, outcome.Body.Error = refusalStatus(reason.Kind), reason.Text case errors.Is(err, ErrNotFound): diff --git a/internal/api/manage.go b/internal/api/manage.go index 9a5438f..ea69f17 100644 --- a/internal/api/manage.go +++ b/internal/api/manage.go @@ -3,8 +3,6 @@ package api import ( "context" "errors" - "net/url" - "strconv" "time" "github.com/devforth/exceptic/internal/platform/config" @@ -213,7 +211,7 @@ func (handler *handlers) updateAccountName(ctx context.Context, call Call, input return userOutput{}, err } - if err := problemsError(problems, nil); err != nil { + if err := problemsError(problems); err != nil { return userOutput{}, err } @@ -366,11 +364,10 @@ type projectDefaults struct { } func (handler *handlers) getProjectDefaults(ctx context.Context, call Call, _ noInput) (projectDefaults, error) { - defaults := handler.services.Projects.FormValues(store.Project{}) storage, err := handler.services.Projects.Storage(ctx, call.Access(), []int{}) return projectDefaults{ - ShownColor: handler.services.Projects.Color(store.Project{}), LogLevels: defaults["log_level"], DiskShare: store.Project{}.Share(), + ShownColor: handler.services.Projects.Color(store.Project{}), LogLevels: handler.services.Projects.RecordedLogLevels(config.Project{}), DiskShare: store.Project{}.Share(), AllowedOrigins: []string{}, LimitBytes: storage.LimitBytes, Limit: storage.Limit, Used: storage.Used, }, err } @@ -465,42 +462,24 @@ type projectFields struct { var projectChoices = map[string][]string{"log_levels": config.LogLevels} -// apply writes the given fields over the form. -func (fields projectFields) apply(form url.Values) { - if fields.Color != nil { - form.Set("color", *fields.Color) - } - - if fields.LogLevels != nil { - form["log_level"] = *fields.LogLevels - } - - if fields.DiskShare != nil { - form.Set("disk_share", strconv.Itoa(*fields.DiskShare)) - } - - if fields.AllowedOrigins != nil { - // An empty list still sends the field, so it clears them. - form["allowed_origin"] = append([]string{""}, *fields.AllowedOrigins...) - } +// change is the services' change of these fields and name. +func (fields projectFields) change(name *string) services.ProjectChange { + return services.ProjectChange{Name: name, Color: fields.Color, LogLevels: fields.LogLevels, DiskShare: fields.DiskShare, AllowedOrigins: fields.AllowedOrigins} } -// projectFormFields names the form's fields as the tools do. -var projectFormFields = map[string]string{"log_level": "log_levels", "allowed_origin": "allowed_origins"} - type createProjectInput struct { Name string `json:"name" jsonschema:"Lowercase letters, digits, '-' and '_', starting with a letter or digit, not digits only (that reads as an ID): backend, frontend, worker."` projectFields } -func (handler *handlers) saveProject(ctx context.Context, call Call, form url.Values, project store.Project) (projectSettings, error) { - saved, problems, err := handler.services.Projects.Save(ctx, call.Viewer, form, project) +func (handler *handlers) saveProject(ctx context.Context, call Call, change services.ProjectChange, project store.Project) (projectSettings, error) { + saved, problems, err := handler.services.Projects.Save(ctx, call.Viewer, change, project) if err != nil { - return projectSettings{}, formError(err, projectFormFields) + return projectSettings{}, formError(err) } - if err := problemsError(problems, projectFormFields); err != nil { + if err := problemsError(problems); err != nil { return projectSettings{}, err } @@ -522,11 +501,7 @@ func (handler *handlers) saveProject(ctx context.Context, call Call, form url.Va } func (handler *handlers) createProject(ctx context.Context, call Call, input createProjectInput) (projectSettings, error) { - form := handler.services.Projects.FormValues(store.Project{}) - form.Set("name", input.Name) - input.apply(form) - - return handler.saveProject(ctx, call, form, store.Project{}) + return handler.saveProject(ctx, call, input.change(&input.Name), store.Project{}) } type updateProjectInput struct { @@ -542,15 +517,7 @@ func (handler *handlers) updateProject(ctx context.Context, call Call, input upd return projectSettings{}, err } - form := handler.services.Projects.FormValues(project) - - if input.Name != nil { - form.Set("name", *input.Name) - } - - input.apply(form) - - return handler.saveProject(ctx, call, form, project) + return handler.saveProject(ctx, call, input.change(input.Name), project) } func (handler *handlers) deleteProject(ctx context.Context, call Call, input projectInput) (doneOutput, error) { @@ -649,7 +616,7 @@ func (handler *handlers) createUser(ctx context.Context, call Call, input create return passwordOutput{}, err } - if err := problemsError(problems, nil); err != nil { + if err := problemsError(problems); err != nil { return passwordOutput{}, err } @@ -709,7 +676,7 @@ func (handler *handlers) updateUser(ctx context.Context, call Call, input update return userOutput{}, err } - if err := problemsError(problems, nil); err != nil { + if err := problemsError(problems); err != nil { return userOutput{}, err } diff --git a/internal/api/notifications.go b/internal/api/notifications.go index 17cc9e7..043b6f5 100644 --- a/internal/api/notifications.go +++ b/internal/api/notifications.go @@ -4,7 +4,6 @@ import ( "context" "errors" "net/http" - "net/url" "strconv" "time" @@ -409,86 +408,47 @@ func (chat chatFields) replaced() []string { return nil } -// set writes the filled chat fields over the form. -func (chat chatFields) set(form url.Values) { - for name, value := range map[string]string{ - "bot_token": chat.BotToken, "chat_id": chat.ChatID, "webhook_url": chat.WebhookURL, - "slack_bot_token": chat.SlackBotToken, "slack_channel": chat.SlackChannel, - } { - if value != "" { - form.Set(name, value) - } - } -} - -// setCheckbox: a checkbox of the form as given; nil keeps it. -func setCheckbox(form url.Values, name string, value *bool) { - switch { - case value == nil: - case *value: - form.Set(name, "on") - default: - form.Del(name) +// tokens are the services' chat tokens of these fields. +func (chat chatFields) tokens() services.ChatTokens { + return services.ChatTokens{ + BotToken: chat.BotToken, ChatID: chat.ChatID, WebhookURL: chat.WebhookURL, SlackBotToken: chat.SlackBotToken, SlackChannel: chat.SlackChannel, } } -// applyConnection writes the given fields over the form (projects: +// connectionPatch is the services' change of the given fields (projects: // projectsField's refusals). -func (handler *handlers) applyConnection(call Call, form url.Values, fields connectionFields, chat chatFields) error { - if fields.Name != nil { - form.Set("name", *fields.Name) +func (handler *handlers) connectionPatch(call Call, fields connectionFields, chat chatFields) (services.ConnectionChange, error) { + change := services.ConnectionChange{ + Name: fields.Name, AllProjects: fields.AllProjects, Levels: fields.Levels, Active: fields.Active, IncludeIssueLink: fields.IncludeIssueLink, Chat: chat.tokens(), } if fields.Projects != nil { ids, err := handler.projectsField(call, "projects", *fields.Projects) if err != nil { - return err + return change, err } - form.Del("project") - - for _, id := range ids { - form.Add("project", strconv.Itoa(id)) - } - } - - switch { - case fields.AllProjects != nil: - setCheckbox(form, "all_projects", fields.AllProjects) - case fields.Projects != nil: - all := len(*fields.Projects) == 0 - setCheckbox(form, "all_projects", &all) + change.ProjectIDs = &ids } - if fields.Levels != nil { - form["level"] = *fields.Levels - } - - setCheckbox(form, "active", fields.Active) - setCheckbox(form, "include_issue_link", fields.IncludeIssueLink) - chat.set(form) - - return nil + return change, nil } -// connectionFormFields names the form's fields as the tools do. -var connectionFormFields = map[string]string{"address": "email"} - -// saveConnection saves the form over connection (none: a new one); replaced -// names the secrets the form replaces, for the audit log. -func (handler *handlers) saveConnection(ctx context.Context, call Call, form url.Values, connection store.Connection, replaced []string) (connectionOutput, error) { - saved, err := handler.services.Connections.Save(ctx, call.Access(), form, connection) +// saveConnection saves change over connection (none: a new one); replaced +// names the secrets it replaces, for the audit log. +func (handler *handlers) saveConnection(ctx context.Context, call Call, change services.ConnectionChange, connection store.Connection, replaced []string) (connectionOutput, error) { + saved, err := handler.services.Connections.Save(ctx, call.Access(), change, connection) if err != nil { - return connectionOutput{}, formError(err, connectionFormFields) + return connectionOutput{}, formError(err) } if saved.Duplicate != nil { return connectionOutput{}, duplicateError(*saved.Duplicate, "sends there") } - if err := problemsError(saved.Problems, connectionFormFields); err != nil { + if err := problemsError(saved.Problems); err != nil { return connectionOutput{}, err } @@ -518,9 +478,7 @@ type createConnectionInput struct { } func (handler *handlers) createConnection(ctx context.Context, call Call, input createConnectionInput) (connectionOutput, error) { - // A new connection starts as in the UI (store.NewConnection). - form := handler.services.Connections.FormValues(handler.services.Connections.New(input.Type, call.Access())) - form.Set("type", input.Type) + destinationID := "" if input.Type == config.ChannelEmail { destination, ok, err := handler.services.Verification.FindDestination(ctx, input.Email) @@ -533,14 +491,19 @@ func (handler *handlers) createConnection(ctx context.Context, call Call, input return connectionOutput{}, unconfirmed("email", "confirm "+strconv.Quote(input.Email)+" first with start_email_verification and confirm_email") } - form.Set("destination_id", destination.ID) + destinationID = destination.ID } - if err := handler.applyConnection(call, form, input.connectionFields, input.chatFields); err != nil { + // A new connection starts from Connections.New, as in the UI. + change, err := handler.connectionPatch(call, input.connectionFields, input.chatFields) + + if err != nil { return connectionOutput{}, err } - return handler.saveConnection(ctx, call, form, store.Connection{}, nil) + change.Type, change.DestinationID = input.Type, destinationID + + return handler.saveConnection(ctx, call, change, store.Connection{}, nil) } type connectionInput struct { @@ -560,13 +523,13 @@ func (handler *handlers) updateConnection(ctx context.Context, call Call, input return connectionOutput{}, err } - form := handler.services.Connections.FormValues(connection) + change, err := handler.connectionPatch(call, input.connectionFields, input.chatFields) - if err := handler.applyConnection(call, form, input.connectionFields, input.chatFields); err != nil { + if err != nil { return connectionOutput{}, err } - return handler.saveConnection(ctx, call, form, connection, input.replaced()) + return handler.saveConnection(ctx, call, change, connection, input.replaced()) } type setConnectionActiveInput struct { @@ -632,11 +595,8 @@ func (handler *handlers) testChat(ctx context.Context, call Call, input testChat existing, channelType = connection, connection.Type } - form := url.Values{"name": {input.Name}} - setCheckbox(form, "include_issue_link", &input.IncludeIssueLink) - input.set(form) - - result := handler.services.Connections.TestChat(ctx, form, channelType, existing) + settings := services.ChatSettings{Type: channelType, Name: input.Name, IncludeIssueLink: input.IncludeIssueLink, Chat: input.tokens()} + result := handler.services.Connections.TestChat(ctx, settings, existing) return chatTestOutput{Sent: result.Sent, Message: result.Message}, nil } @@ -664,7 +624,7 @@ func (handler *handlers) sendTestMessage(ctx context.Context, call Call, input c // unconfirmed refuses at field what an unconfirmed address may not do (409). func unconfirmed(field, problem string) error { - input, _ := problemsError(map[string]string{field: problem}, nil).(InputError) + input, _ := problemsError(map[string]string{field: problem}).(InputError) input.status = http.StatusConflict return input diff --git a/internal/api/notifications_ui_test.go b/internal/api/notifications_ui_test.go index 8546d12..1b9e368 100644 --- a/internal/api/notifications_ui_test.go +++ b/internal/api/notifications_ui_test.go @@ -641,6 +641,19 @@ func TestUIConnectionFieldErrors(t *testing.T) { t.Errorf("projects: %+v", details) } + // Levels alone keep the projects; an empty project list alone is every project. + server.must("update_connection", map[string]any{"connection_id": id, "levels": []string{"fatal"}}, nil) + + if details, _ := server.details(id); details.AllProjects || len(details.ProjectIDs) != 2 || details.Name != "Chat" { + t.Errorf("levels alone: %+v", details) + } + + server.must("update_connection", map[string]any{"connection_id": id, "projects": []string{}}, nil) + + if details, _ := server.details(id); !details.AllProjects || len(details.ProjectIDs) != 0 || !slices.Equal(details.Levels, []string{"fatal"}) { + t.Errorf("an empty project list: %+v", details) + } + if body := server.refusedWith(http.StatusConflict, "create_connection", map[string]any{"type": "slack", "webhook_url": hook.url}); body.Duplicate == nil || body.Duplicate.ID != id || body.Duplicate.Name != "Chat" { t.Errorf("the same webhook again: %+v", body) } diff --git a/internal/api/params.go b/internal/api/params.go index ae43714..157e9cc 100644 --- a/internal/api/params.go +++ b/internal/api/params.go @@ -93,7 +93,7 @@ func (handler *handlers) projectsField(call Call, field string, namesOrIDs []str } problem := strings.Replace(reason.Text, "not found: project", "unknown project", 1) - input, _ := problemsError(map[string]string{field: problem}, nil).(InputError) + input, _ := problemsError(map[string]string{field: problem}).(InputError) if errors.Is(reason, services.ErrHidden) { input.status, input.hidden = http.StatusForbidden, true diff --git a/internal/api/plain.go b/internal/api/plain.go index 0ec5132..f1a6c9d 100644 --- a/internal/api/plain.go +++ b/internal/api/plain.go @@ -146,7 +146,7 @@ func LoginRequests(logger *slog.Logger, auth *session.Auth, appName string) map[ if errors.Is(err, session.ErrTooManyAttempts) { err = tooManyAttempts(nil) } else if err == nil { - err = problemsError(problems, nil) + err = problemsError(problems) } if err != nil { @@ -194,7 +194,7 @@ func answerPasswordChecked(w http.ResponseWriter, r *http.Request, name string, case errors.Is(err, session.ErrTooManyAttempts): err = tooManyAttempts(map[string]string{"current_password": session.TooManyAttempts}) case err == nil: - err = problemsError(problems, nil) + err = problemsError(problems) } if err != nil { diff --git a/internal/api/transport_test.go b/internal/api/transport_test.go index 90fa2b2..c8e9abc 100644 --- a/internal/api/transport_test.go +++ b/internal/api/transport_test.go @@ -226,7 +226,7 @@ func TestInputErrorBody(t *testing.T) { text string }{ "fields": { - problemsError(map[string]string{"name": "taken", "log_level": "unknown level"}, projectFormFields), http.StatusBadRequest, + problemsError(map[string]string{"name": "taken", "log_levels": "unknown level"}), http.StatusBadRequest, ErrorBody{Error: "log_levels: unknown level; name: taken", Fields: map[string]string{"name": "taken", "log_levels": "unknown level"}}, "invalid: log_levels: unknown level; name: taken", }, diff --git a/internal/services/connection_form.go b/internal/services/connection_form.go index e75ffb3..be3adf7 100644 --- a/internal/services/connection_form.go +++ b/internal/services/connection_form.go @@ -5,10 +5,8 @@ import ( "context" "fmt" "maps" - "net/url" "regexp" "slices" - "strconv" "strings" "time" @@ -17,13 +15,37 @@ import ( "github.com/devforth/exceptic/internal/storage/store" ) -// Save applies the connection form (built by the catalog from a request's -// input, under the form's field names) to connection and stores it, choosing -// among the projects of access (a connection outside it is ErrHidden; -// what the viewer may not choose or an unconfirmed address a Refusal): a new one when its ID is empty (the type comes from the form; an email connection needs the -// destination_id of a confirmed address), the stored one otherwise (an -// empty chat field keeps the stored token). -func (service *Connections) Save(ctx context.Context, access store.Access, form url.Values, connection store.Connection) (SavedConnection, error) { +// ConnectionChange is what a save sets on a connection; a nil field keeps +// the stored value (a new connection's: New). +type ConnectionChange struct { + // Type and DestinationID (an email connection's confirmed address) are a new connection's. + Type string + DestinationID string + Name *string + // AllProjects not given follows ProjectIDs when they are: an empty list is every project. + AllProjects *bool + ProjectIDs *[]int + Levels *[]string + Active *bool + IncludeIssueLink *bool + Chat ChatTokens +} + +// ChatTokens are the tokens of a chat; an empty one keeps the stored token. +type ChatTokens struct { + BotToken string + ChatID string + WebhookURL string + SlackBotToken string + SlackChannel string +} + +// Save applies change to connection and stores it, choosing among the +// projects of access (a connection outside it is ErrHidden; what the viewer +// may not choose or an unconfirmed address a Refusal): a new one when its +// ID is empty (an email connection needs the DestinationID of a confirmed +// address), the stored one otherwise (an empty chat token keeps the stored one). +func (service *Connections) Save(ctx context.Context, access store.Access, change ConnectionChange, connection store.Connection) (SavedConnection, error) { isNew := connection.ID == "" if !isNew && !Visible(access, connection) { @@ -31,10 +53,10 @@ func (service *Connections) Save(ctx context.Context, access store.Access, form } if isNew { - connection = store.Connection{Type: strings.TrimSpace(form.Get("type"))} + connection = service.New(strings.TrimSpace(change.Type), access) } - problems := readConnectionForm(form, &connection, access.Visible(service.projects.List())) + problems := applyConnectionChange(change, &connection, access.Visible(service.projects.List())) // What the viewer may not choose, and what the stored records refuse. forbidden, conflicts := Problems{}, Problems{} @@ -55,19 +77,19 @@ func (service *Connections) Save(ctx context.Context, access store.Access, form switch { case isNew && connection.Type == config.ChannelEmail: // The address must have been confirmed first (Verification.StartEmail, Verification.ConfirmCode). - destination, err := emailDestination(ctx, service.store, form.Get("destination_id")) + destination, err := emailDestination(ctx, service.store, change.DestinationID) if err != nil || !destination.Verified { - conflicts["address"] = confirmFirst + conflicts["email"] = confirmFirst } else { connection.DestinationID, connection.Address, connection.Verified = destination.ID, destination.Address, true chat.Key = destination.Address } case isNew: - chat = readChatSecret(form, service.factory, connection.Type, "", formValid) + chat = readChatSecret(change.Chat, service.factory, connection.Type, "", formValid) maps.Copy(problems, chat.Problems) default: - chat = readChatSecret(form, service.factory, connection.Type, connection.Secret, formValid) + chat = readChatSecret(change.Chat, service.factory, connection.Type, connection.Secret, formValid) maps.Copy(problems, chat.Problems) if connection.Active && !connection.Verified { @@ -123,15 +145,23 @@ func (service *Connections) Save(ctx context.Context, access store.Access, form // confirmFirst refuses an unconfirmed address what needs a confirmed one. const confirmFirst = "Confirm the email address first." -// TestChat sends a test message with the chat settings of the form before -// they are saved. existing is the stored connection, if any: its empty -// fields keep the stored tokens. -func (service *Connections) TestChat(ctx context.Context, form url.Values, channelType string, existing store.Connection) ChatTest { +// ChatSettings are what a chat test sends with: the form's values before they are saved. +type ChatSettings struct { + Type, Name string + IncludeIssueLink bool + Chat ChatTokens +} + +// TestChat sends a test message with chat settings before they are saved. +// existing is the stored connection, if any: an empty token keeps its stored one. +func (service *Connections) TestChat(ctx context.Context, settings ChatSettings, existing store.Connection) ChatTest { + channelType := settings.Type + if channelType != config.ChannelTelegram && channelType != config.ChannelSlack { return ChatTest{Message: "Choose Telegram or Slack."} } - secret := readChatSecret(form, service.factory, channelType, existing.Secret, true) + secret := readChatSecret(settings.Chat, service.factory, channelType, existing.Secret, true) if len(secret.Problems) > 0 { problems := slices.Sorted(maps.Values(secret.Problems)) @@ -139,8 +169,8 @@ func (service *Connections) TestChat(ctx context.Context, form url.Values, chann return ChatTest{Message: strings.Join(problems, " ")} } - name := cmp.Or(strings.TrimSpace(form.Get("name")), existing.Name, "new connection") - connection := store.Connection{Type: channelType, Name: name, Secret: secret.Secret, HideIssueLink: form.Get("include_issue_link") != "on"} + name := cmp.Or(strings.TrimSpace(settings.Name), existing.Name, "new connection") + connection := store.Connection{Type: channelType, Name: name, Secret: secret.Secret, HideIssueLink: !settings.IncludeIssueLink} if err := service.sendTest(ctx, connection); err != nil { return ChatTest{Message: "Not delivered: " + err.Error()} @@ -177,27 +207,31 @@ var ( // anchored matches the whole value, as a pattern attribute does. func anchored(pattern string) *regexp.Regexp { return regexp.MustCompile(`^(?:` + pattern + `)$`) } -// readConnectionForm applies the rule fields (name, projects, levels, -// active) to connection and returns the field errors; projects are those -// that may be chosen, others are left out. -func readConnectionForm(form url.Values, connection *store.Connection, projects config.Projects) Problems { +// applyConnectionChange applies the rule fields (name, projects, levels, +// active, issue link) of change to connection and checks every value, the +// stored ones it keeps too; projects are those that may be chosen, others are left out. +func applyConnectionChange(change ConnectionChange, connection *store.Connection, projects config.Projects) Problems { problems := Problems{} // An empty name is filled in on save (see Connections.defaultName). - connection.Name = strings.TrimSpace(form.Get("name")) + connection.Name = strings.TrimSpace(keepOr(change.Name, connection.Name)) if len([]rune(connection.Name)) > config.MaxConnectionName { problems["name"] = fmt.Sprintf("Enter a name of up to %d characters, or leave it empty.", config.MaxConnectionName) } - connection.AllProjects = form.Get("all_projects") == "on" + chosen := keepOr(change.ProjectIDs, connection.ProjectIDs) + connection.AllProjects = keepOr(change.AllProjects, connection.AllProjects) + + if change.AllProjects == nil && change.ProjectIDs != nil { + connection.AllProjects = len(chosen) == 0 + } + connection.ProjectIDs = nil if !connection.AllProjects { - for _, value := range form["project"] { - projectID, err := strconv.Atoi(value) - - if _, ok := projects.ByID(projectID); err == nil && ok { + for _, projectID := range chosen { + if _, ok := projects.ByID(projectID); ok { connection.ProjectIDs = append(connection.ProjectIDs, projectID) } } @@ -207,10 +241,11 @@ func readConnectionForm(form url.Values, connection *store.Connection, projects } } + levels := keepOr(change.Levels, connection.Levels) connection.Levels = nil for _, level := range config.Levels { - if slices.Contains(form["level"], level) { + if slices.Contains(levels, level) { connection.Levels = append(connection.Levels, level) } } @@ -219,29 +254,28 @@ func readConnectionForm(form url.Values, connection *store.Connection, projects problems["levels"] = "Select at least one level." } - connection.Active = form.Get("active") == "on" - - connection.HideIssueLink = form.Get("include_issue_link") != "on" + connection.Active = keepOr(change.Active, connection.Active) + connection.HideIssueLink = !keepOr(change.IncludeIssueLink, !connection.HideIssueLink) return problems } -// chatSecret is what readChatSecret read from the form. +// chatSecret is what readChatSecret read from the tokens. type chatSecret struct { - // Secret is the encrypted tokens, to store; empty when the form has problems. + // Secret is the encrypted tokens, to store; empty when the change has problems. Secret string // Key is the chat's identity (what services.Connections compares to find - // duplicates); empty when the form has problems. + // duplicates); empty when the change has problems. Key string // Problems are the field errors of the chat fields. Problems Problems } // readChatSecret reads the tokens of a chat. existing is the stored secret: -// an empty field keeps its value. formValid tells whether the rest of the -// form is valid: only then is the secret encrypted and its key given, since -// a form with problems is shown again without being saved or compared. -func readChatSecret(form url.Values, factory notify.Factory, channelType, existing string, formValid bool) chatSecret { +// an empty token keeps its value. formValid tells whether the rest of the +// change is valid: only then is the secret encrypted and its key given, +// since a change with problems is neither saved nor compared. +func readChatSecret(given ChatTokens, factory notify.Factory, channelType, existing string, formValid bool) chatSecret { var ( tokens any key string @@ -258,11 +292,11 @@ func readChatSecret(form url.Values, factory notify.Factory, channelType, existi _ = factory.DecryptSecret(existing, &telegram) } - if value := strings.TrimSpace(form.Get("bot_token")); value != "" { + if value := strings.TrimSpace(given.BotToken); value != "" { telegram.BotToken, changed = value, true } - if value := strings.TrimSpace(form.Get("chat_id")); value != "" { + if value := strings.TrimSpace(given.ChatID); value != "" { telegram.ChatID, changed = value, true } @@ -282,11 +316,11 @@ func readChatSecret(form url.Values, factory notify.Factory, channelType, existi _ = factory.DecryptSecret(existing, &slack) } - webhook := strings.TrimSpace(form.Get("webhook_url")) - botToken := strings.TrimSpace(form.Get("slack_bot_token")) - channel := strings.TrimSpace(form.Get("slack_channel")) + webhook := strings.TrimSpace(given.WebhookURL) + botToken := strings.TrimSpace(given.SlackBotToken) + channel := strings.TrimSpace(given.SlackChannel) - // A new webhook alone replaces a stored bot (the form posts its channel back), a new bot token alone a stored webhook. + // A new webhook alone replaces a stored bot (a channel sent with it is dropped), a new bot token alone a stored webhook. switch { case webhook != "" && botToken == "": slack.BotToken, slack.Channel, channel = "", "", "" @@ -345,26 +379,3 @@ func readChatSecret(form url.Values, factory notify.Factory, channelType, existi return result } - -// FormValues is connection as its form would post it unchanged (chat -// fields empty: the stored tokens are kept), for a tool that changes some -// fields. -func (service *Connections) FormValues(connection store.Connection) url.Values { - form := url.Values{"name": {connection.Name}, "level": append([]string{}, connection.Levels...)} - - checkbox := func(name string, checked bool) { - if checked { - form.Set(name, "on") - } - } - - checkbox("all_projects", connection.AllProjects) - checkbox("active", connection.Active) - checkbox("include_issue_link", !connection.HideIssueLink) - - for _, id := range connection.ProjectIDs { - form.Add("project", strconv.Itoa(id)) - } - - return form -} diff --git a/internal/services/project_form.go b/internal/services/project_form.go index 8bec3bc..562ef9b 100644 --- a/internal/services/project_form.go +++ b/internal/services/project_form.go @@ -2,78 +2,80 @@ package services import ( "fmt" - "net/url" "slices" - "strconv" "strings" "github.com/devforth/exceptic/internal/platform/config" "github.com/devforth/exceptic/internal/storage/store" ) -// readProjectForm applies the project form (built by the catalog from a -// request's input, under the form's field names) to project and returns the field errors. +// ProjectChange is what a save sets on a project; a nil field keeps the +// stored value, a pointer to an empty list clears it. +type ProjectChange struct { + Name *string + // Color: #rrggbb, or empty for the palette color. + Color *string + LogLevels *[]string + DiskShare *int + AllowedOrigins *[]string +} + +// applyProjectChange applies change to project and checks every value, +// the stored ones it keeps too, returning the problems by input field. // paletteColor is the color the project has without its own one; empty for // a new project, which keeps the color chosen. -func readProjectForm(form url.Values, project *store.Project, recording config.Recording, paletteColor string) Problems { +func applyProjectChange(change ProjectChange, project *store.Project, recording config.Recording, paletteColor string) Problems { problems := Problems{} - project.Name = strings.TrimSpace(form.Get("name")) + project.Name = strings.TrimSpace(keepOr(change.Name, project.Name)) if !config.ValidProjectName(project.Name) { problems["name"] = "Use lowercase letters, digits, '-' and '_', starting with a letter or digit, not digits only." } // The palette color is stored as "" so the project keeps following the - // palette; any other color is stored as chosen. An empty one returns to - // the palette, a missing one keeps the color. - if form.Has("color") { - color := strings.ToLower(strings.TrimSpace(form.Get("color"))) - - switch { - case color == "": - project.Color = "" - case !config.ValidColor(color): - problems["color"] = "Choose a color." - case paletteColor != "" && color == paletteColor: - project.Color = "" - default: - project.Color = color - } + // palette; any other color is stored as chosen. An empty one returns to the palette. + switch color := strings.ToLower(strings.TrimSpace(keepOr(change.Color, project.Color))); { + case color == "": + project.Color = "" + case !config.ValidColor(color): + problems["color"] = "Choose a color." + case paletteColor != "" && color == paletteColor: + project.Color = "" + default: + project.Color = color } - // The log levels to record. The whole list is sent with the form, so - // nothing checked means record nothing; the default is stored as "use the + // An empty list records nothing; the default is stored as "use the // default", so a project follows RECORD_LOG_LEVELS until it differs. - project.LogLevels = chosenLevels(form["log_level"], config.LogLevels, recording.LogLevels) + project.LogLevels = chosenLevels(keepOr(change.LogLevels, recording.RecordedLogLevels(project.LogLevels)), config.LogLevels, recording.LogLevels) - // A missing share keeps the stored one (forms without the field). - if form.Has("disk_share") { - share, err := strconv.Atoi(strings.TrimSpace(form.Get("disk_share"))) + if share := keepOr(change.DiskShare, project.Share()); share < store.MinDiskShare || share > store.MaxDiskShare || share%store.DiskShareStep != 0 { + problems["disk_share"] = fmt.Sprintf("Choose %d%% to %d%% in steps of %d%%.", store.MinDiskShare, store.MaxDiskShare, store.DiskShareStep) + } else { + project.DiskShare = share + } - if err != nil || share < store.MinDiskShare || share > store.MaxDiskShare || share%store.DiskShareStep != 0 { - problems["disk_share"] = fmt.Sprintf("Choose %d%% to %d%% in steps of %d%%.", store.MinDiskShare, store.MaxDiskShare, store.DiskShareStep) - } else { - project.DiskShare = share - } + if origins, problem := allowedOrigins(keepOr(change.AllowedOrigins, project.AllowedOrigins)); problem != "" { + problems["allowed_origins"] = problem + } else { + project.AllowedOrigins = origins } - // The allowed origins, one per value; a missing field keeps them. - if form.Has("allowed_origin") { - origins, problem := allowedOrigins(form["allowed_origin"]) + return problems +} - if problem != "" { - problems["allowed_origin"] = problem - } else { - project.AllowedOrigins = origins - } +// keepOr is the value given, or stored when none is. +func keepOr[T any](given *T, stored T) T { + if given != nil { + return *given } - return problems + return stored } -// allowedOrigins reads the form's origins (empty values skipped, the same -// one once) or says what is wrong. +// allowedOrigins reads the origins (empty values skipped, the same one +// once) or says what is wrong. func allowedOrigins(values []string) ([]string, string) { origins := []string{} @@ -104,7 +106,7 @@ func allowedOrigins(values []string) ([]string, string) { return origins, "" } -// chosenLevels keeps the known levels of the form; nil when they are the +// chosenLevels keeps the known levels chosen; nil when they are the // defaults (nil defaults: every level). func chosenLevels(values, known, defaults []string) *[]string { levels := config.InLevelOrder(values, known) @@ -119,14 +121,3 @@ func chosenLevels(values, known, defaults []string) *[]string { return &levels } - -// FormValues is project as the form would post it unchanged: a tool that -// changes some fields starts from these, so the others keep their values. -func (service *Projects) FormValues(project store.Project) url.Values { - form := url.Values{"name": {project.Name}, "color": {project.Color}, "disk_share": {strconv.Itoa(project.Share())}} - - form["log_level"] = service.recording.RecordedLogLevels(project.LogLevels) - form["allowed_origin"] = append([]string{}, project.AllowedOrigins...) - - return form -} diff --git a/internal/services/project_form_test.go b/internal/services/project_form_test.go index b283aeab..c38feaa 100644 --- a/internal/services/project_form_test.go +++ b/internal/services/project_form_test.go @@ -1,7 +1,6 @@ package services import ( - "net/url" "slices" "testing" @@ -14,9 +13,7 @@ func TestProjectFormLevels(t *testing.T) { var project store.Project - problems := readProjectForm(url.Values{ - "name": {"api"}, "log_level": {"fatal", "warn", "error"}, - }, &project, recording, "#2563eb") + problems := applyProjectChange(ProjectChange{Name: new("api"), LogLevels: &[]string{"fatal", "warn", "error"}}, &project, recording, "#2563eb") if len(problems) > 0 { t.Fatalf("problems = %v", problems) @@ -27,14 +24,21 @@ func TestProjectFormLevels(t *testing.T) { } // Levels the list does not know are dropped. - readProjectForm(url.Values{"name": {"api"}, "log_level": {"info", "bogus"}}, &project, recording, "#2563eb") + applyProjectChange(ProjectChange{LogLevels: &[]string{"info", "bogus"}}, &project, recording, "#2563eb") if project.LogLevels == nil || !slices.Equal(*project.LogLevels, []string{"info"}) { t.Errorf("log levels = %v, want [info]", project.LogLevels) } - // Nothing checked records nothing. - readProjectForm(url.Values{"name": {"api"}}, &project, recording, "#2563eb") + // Levels not given keep the stored ones. + applyProjectChange(ProjectChange{}, &project, recording, "#2563eb") + + if project.LogLevels == nil || !slices.Equal(*project.LogLevels, []string{"info"}) { + t.Errorf("log levels = %v, want [info] kept", project.LogLevels) + } + + // An empty list records nothing. + applyProjectChange(ProjectChange{LogLevels: &[]string{}}, &project, recording, "#2563eb") if project.LogLevels == nil || len(*project.LogLevels) != 0 { t.Errorf("log levels = %v, want an empty list (record none)", project.LogLevels) @@ -43,9 +47,7 @@ func TestProjectFormLevels(t *testing.T) { func TestProjectFormValidation(t *testing.T) { project := store.Project{Name: "backend", Color: "#123456"} - problems := readProjectForm(url.Values{ - "name": {"backend"}, "color": {"#2563EB"}, - }, &project, config.Recording{}, "#2563eb") + problems := applyProjectChange(ProjectChange{Color: new("#2563EB")}, &project, config.Recording{}, "#2563eb") if len(problems) > 0 { t.Errorf("problems = %v", problems) @@ -58,39 +60,39 @@ func TestProjectFormValidation(t *testing.T) { // Digits only would read as a project ID wherever a name or ID is taken. for _, name := range []string{"Not Valid", "3", "-web"} { - if problems := readProjectForm(url.Values{"name": {name}}, &project, config.Recording{}, ""); problems["name"] == "" { + if problems := applyProjectChange(ProjectChange{Name: &name}, &project, config.Recording{}, ""); problems["name"] == "" { t.Errorf("invalid name %q accepted", name) } } for _, name := range []string{"web", "3d", "1_api", "v2-api"} { - if problems := readProjectForm(url.Values{"name": {name}}, &project, config.Recording{}, ""); problems["name"] != "" { + if problems := applyProjectChange(ProjectChange{Name: &name}, &project, config.Recording{}, ""); problems["name"] != "" { t.Errorf("valid name %q refused: %s", name, problems["name"]) } } } -// The disk share takes 5% to 100% in steps of 5%; a form without it keeps the stored one. +// The disk share takes 5% to 100% in steps of 5%; a change without it keeps the stored one. func TestProjectFormDiskShare(t *testing.T) { project := store.Project{Name: "backend", DiskShare: 40} - if problems := readProjectForm(url.Values{"name": {"backend"}}, &project, config.Recording{}, ""); len(problems) > 0 || project.DiskShare != 40 { + if problems := applyProjectChange(ProjectChange{}, &project, config.Recording{}, ""); len(problems) > 0 || project.DiskShare != 40 { t.Fatalf("without the field: share %d, problems %v", project.DiskShare, problems) } - for value, want := range map[string]int{"5": 5, "35": 35, "100": 100} { - if problems := readProjectForm(url.Values{"name": {"backend"}, "disk_share": {value}}, &project, config.Recording{}, ""); len(problems) > 0 || project.DiskShare != want { - t.Errorf("%s: share %d, problems %v", value, project.DiskShare, problems) + for _, want := range []int{5, 35, 100} { + if problems := applyProjectChange(ProjectChange{DiskShare: &want}, &project, config.Recording{}, ""); len(problems) > 0 || project.DiskShare != want { + t.Errorf("%d: share %d, problems %v", want, project.DiskShare, problems) } } - for _, value := range []string{"0", "3", "42", "105", "half", ""} { - if problems := readProjectForm(url.Values{"name": {"backend"}, "disk_share": {value}}, &project, config.Recording{}, ""); problems["disk_share"] == "" { - t.Errorf("%q accepted", value) + for _, value := range []int{0, 3, 42, 105, -5} { + if problems := applyProjectChange(ProjectChange{DiskShare: &value}, &project, config.Recording{}, ""); problems["disk_share"] == "" { + t.Errorf("%d accepted", value) } } - if values := (&Projects{}).FormValues(store.Project{}); values.Get("disk_share") != "100" { - t.Errorf("a new project's share: %q, want 100", values.Get("disk_share")) + if fresh := (store.Project{Name: "backend"}); len(applyProjectChange(ProjectChange{}, &fresh, config.Recording{}, "")) > 0 || fresh.DiskShare != 100 { + t.Errorf("a new project's share: %d, want 100", fresh.DiskShare) } } diff --git a/internal/services/projects.go b/internal/services/projects.go index 1fd7971..271fde5 100644 --- a/internal/services/projects.go +++ b/internal/services/projects.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "maps" - "net/url" "slices" "strconv" "strings" @@ -96,19 +95,19 @@ func (service *Projects) Find(access store.Access, nameOrID string) (config.Proj // diskShareProblem: a user may change the rest of a project's settings. const diskShareProblem = "Only an admin changes the disk share." -// Save applies the form to project and stores it as viewer: a new one when +// Save applies change to project and stores it as viewer: a new one when // its ID is 0 (it joins a limited viewer's access), the stored one // otherwise (ErrHidden outside viewer's access). A taken name is // ErrConflict, a Refusal at its field. -// It returns the project as read from the form (with its id once saved) and -// the field errors when nothing was saved. -func (service *Projects) Save(ctx context.Context, viewer store.User, form url.Values, project store.Project) (store.Project, Problems, error) { +// It returns the project as changed (with its id once saved) and the +// field errors when nothing was saved. +func (service *Projects) Save(ctx context.Context, viewer store.User, change ProjectChange, project store.Project) (store.Project, Problems, error) { if project.ID != 0 && !viewer.ProjectAccess().Sees(project.ID) { return project, nil, Hidden("project", strconv.Itoa(project.ID)) } // A new project's id is random, so its palette color is not known yet: - // the color the form showed is stored as chosen. + // the color its form showed is stored as chosen. paletteColor := "" if project.ID != 0 { @@ -116,7 +115,7 @@ func (service *Projects) Save(ctx context.Context, viewer store.User, form url.V } share := project.Share() - problems := readProjectForm(form, &project, service.recording, paletteColor) + problems := applyProjectChange(change, &project, service.recording, paletteColor) access := viewer.ProjectAccess() if len(problems) > 0 { diff --git a/internal/services/services_test.go b/internal/services/services_test.go index 359abe4..c6fb0d3 100644 --- a/internal/services/services_test.go +++ b/internal/services/services_test.go @@ -5,7 +5,6 @@ import ( "errors" "io" "log/slog" - "net/url" "slices" "strings" "testing" @@ -356,7 +355,7 @@ func TestNewProjectKeepsTheShownColor(t *testing.T) { service := newProjects(database, registry, &config.Config{}, nil) shown := service.Color(store.Project{}) - saved, problems, err := service.Save(ctx, store.User{}, url.Values{"name": {"worker"}, "color": {shown}}, store.Project{}) + saved, problems, err := service.Save(ctx, store.User{}, ProjectChange{Name: new("worker"), Color: &shown}, store.Project{}) if err != nil || len(problems) > 0 { t.Fatal(err, problems) From 24ac74834f2c7dd727d197164d26928d48476f76 Mon Sep 17 00:00:00 2001 From: Ivan Husev Date: Fri, 4 Dec 2026 13:45:12 +0200 Subject: [PATCH 2/3] fix: deleting a project returns at once, its data purged by the woken background job DevFo-OSS/17 --- CLAUDE.md | 4 +- docs/ui.md | 2 +- internal/storage/database/cleanup.go | 2 +- internal/storage/database/log_head_test.go | 2 +- internal/storage/database/projects.go | 33 +++++++++++---- internal/storage/database/store.go | 6 ++- internal/storage/database/store_test.go | 48 ++++++++++++++++++++++ internal/storage/projects/projects.go | 10 ++--- internal/storage/projects/projects_test.go | 6 ++- internal/storage/store/store.go | 3 +- 10 files changed, 91 insertions(+), 25 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index cb2f6e8..8af69c3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -116,8 +116,8 @@ Where to look first: - `Close` on shutdown writes the in-memory queue and pending summaries to the outbox and sends what is due; messages waiting for a retry are sent after the next start. Only a killed process loses the in-memory part, apart from what `Notify` drops while the queue (`QueueSize`, 1000) is full: counted, one warning with the count a minute and at `Close` (`warnDropped`); a notice dropped so logs its own warning. - `Factory` builds channels from connections (decrypting secrets with the `Box`), sends test messages (`SendTest`) and is shared with services. Channels implement `Send`/`SendSummary`: `Slack` (incoming webhook, `{"text"}`, also Mattermost/Rocket.Chat, so text outside code goes through `slackText`, which also breaks `@all` mentions and Markdown images; or a bot: `SlackSecret.BotToken` + `Channel` posts through `chat.postMessage` and puts the agent prompt as a code block in a thread under each error (cut to a Slack message by `agentprompt.BuildWithin`, which shortens only the error data, so the end marker and the reminder stay), since a webhook does not return the message timestamp; a failed thread post is dropped so the message is not sent twice), `Telegram` (bot API, HTML parse mode; errors must not include the URL, it holds the token; an error is one message: the agent prompt as a `.md` file via `sendDocument` with the alert as its HTML caption (max 1024 characters, so details are capped), since a message holds 4096 characters and a `copy_text` button 256; a refused file falls back to a plain message, a rate limit is retried as usual; test messages and summaries stay `sendMessage`) and `Email` (plain SMTP via net/smtp, no provider SDK: STARTTLS, or TLS on port 465; multipart text + HTML from `templates/email.html`, styles inline for mail clients; `SendVerificationCode` for new addresses). A message carries the event's id (`Notification.EventID`), not the event: each attempt reads the stored one (`notifier.storedEvent`; deleted meanwhile, it goes out without details), so the outbox, which the size limit does not count, never holds copies of events. Email shows at most 10 exceptions, 15 frames with 5 source lines around the throwing one and 30 tags, every text cut (`fieldLength`; values and messages 2000 characters); every prompt (`Build`: `get_issue`, the issue page, Telegram and email) is cut to `agentprompt.MaxLength` (100000 characters) in its error data, the Slack thread to a Slack message (`maxSlackText`). Short formats share `format.go`; stack reading uses `sentry` methods (`OutermostFirst`, `NewestFirst`, `IsInApp`, `SourceLines`) like the issue page does. `Factory.TelegramURL` points to a fake Telegram API in tests, so no test reaches api.telegram.org. Tests use fake HTTP and SMTP servers (`fixtures.FakeSMTP`) and a real database; assertions do not depend on timing (`waitFor`). - `internal/agentprompt`: `Build` (instructions + `Describe`) writes a prompt that asks a coding agent to reproduce and explain an error with evidence, without changing code or calling tools that change the monitor (the developer checks it and asks for the fix); the error data comes from anyone who can send errors and a copied prompt reaches the agent as the developer's own message, so it sits between `=== BEGIN/END ERROR DATA