Files
meshcore-analyzer/internal/users/mail.go
T
efitenandClaude Opus 5.5 d232072f85 feat: optional user accounts (part A: foundation) (#2129)
Part A of #2128: optional, off-by-default user accounts. With the
feature off nothing changes; with it on, visitors can register and log
in, and admins manage users and use the operator actions without the API
key.

PR #2130 (settings sync) builds on this one. The two are meant to be
merged together.

## The situation

- Operator actions (geofilter save and prune, backup, perf reset) need
the shared `apiKey`. There is no per-person right.
- Nothing in CoreScope knows who a visitor is, so the requests in #2128
that need that (#1835, #2092, #1508, #730) have nothing to build on.

## What this PR adds

**Two new Go modules**
- `internal/users`: a separate `users.db` (SQLite through
`modernc.org/sqlite`) with users, sessions, single-use tokens, an audit
log and a mail log. Passwords use argon2id.
- `internal/mailer`: a `Mailer` interface with a Brevo client (send,
delivery events, webhook parsing) and an in-memory fake for tests.

**Server (`cmd/server`)**, active only with `userManagement.enabled`
- 24 routes, all documented in OpenAPI under the `users` tag
([`auth_routes.go`](https://github.com/efiten/CoreScope/blob/feat/user-management/cmd/server/auth_routes.go)):
  - auth: register, activate, login, logout, me, forgot, reset;
- account: profile, password, email change with confirmation, sessions,
self-delete;
- admin: list, detail, disable, enable, delete, role, resend activation,
manual activation, mail status refresh;
  - a Brevo webhook, registered only when `mail.webhookSecret` is set.
- `requireAdmin` replaces `requireAPIKey` at the 7 operator call sites:
the API key **or** an admin session. With the feature off it is the old
API-key gate (`TestRequireAdminWithoutUserManagementIsAPIKeyGate`).
- `/api/config/client` gets `userManagement: {enabled: true}` only when
the service started; with the feature off the response is
byte-identical.

**Frontend**
- `auth.js` (header account control, request helper that adds the CSRF
header), `account.js` (login, register, activate, forgot, reset, confirm
email, my account), `admin-users.js` (`#/admin/users`, deep-linked
filters), `account.css` (theme tokens only).
- On phones the top-bar control is hidden, so a conditional entry goes
into the bottom-nav "More" sheet and the nav drawer.
- The customizer geofilter tab and the Perf "Reset stats" button use the
admin session when there is one.

**Config.** A `userManagement` block (`config.example.json`,
[`docs/user-guide/accounts.md`](https://github.com/efiten/CoreScope/blob/feat/user-management/docs/user-guide/accounts.md)).
The Brevo key can come from `CORESCOPE_BREVO_API_KEY`. The server
refuses to start when the block is enabled but incomplete.

## Security choices

- Session cookie `cs_session`: HttpOnly, SameSite=Lax, Secure when
`publicBaseUrl` is https. Every cookie-authenticated state change needs
the `X-CS-CSRF` header and a matching Origin.
- Activation needs the token **and** the account password. Without the
password, an attacker who keeps re-registering a known address could get
the owner to activate an account that carries the attacker's password.
- Register, forgot and email change answer identically for known and
unknown addresses. A password reset ends all sessions, a password change
ends all other sessions, and both end outstanding email-change links.
- Rate limits: login 10 per 15 minutes, register and forgot 5 per hour,
per IP and per address. The bucket count is capped. `trustedProxies`
makes the per-IP limits see real client IPs behind a proxy.
- Server logs carry `#<user id>`, never addresses, tokens or passwords;
mail-provider error texts are redacted before logging.

## Performance

No change to an existing hot path with the feature off. With it on:
- One `users.db` lookup per authenticated request (session by token
hash).
- The admin user table rebuilds its `tbody` on each filter change.
`users.List` caps the result at 1000 rows (`internal/users/users.go`),
which bounds the rebuild.
- `map[string]interface{}` in `openapi.go`: 79 before, 78 after.

## Verification

- `internal/users`, `internal/mailer` and `cmd/server`: `go vet` and `go
test -race` pass locally. 121 new Go tests.
- `cmd/server` with `-tags e2etest`: vet and the e2e hook tests pass.
- `sh test-all.sh` exits 0. `tests/unit/test-user-management-ui.js`: 67
passing (vm, real modules).
- `tests/e2e/test-user-management-e2e.js` (6 steps) passed locally
against an `e2etest` build with the fake mailer and against a
feature-off build. CI builds the `e2etest` binary and runs the suite on
a second server (`deploy.yml`).
- On a staging instance with a real Brevo key: register, activation mail
delivered, activate, admin table, "Refresh status" showing sent,
deferred, delivered, opened and clicked.

## Not in this PR

- Settings sync (#2130), the admin dashboard, approval flows and
notifications (parts B to E of #2128).
- A `requireReadAuth` mode (#1835). Sessions from this PR are what such
a mode would accept.
- Binary size and build time with `modernc.org/sqlite` linked next to
`mattn/go-sqlite3` were not measured. Their driver names do not collide.
#1992 discusses the driver choice.
- No Brevo webhook was configured on staging; delivery status there came
from "Refresh status".

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 09:25:29 +02:00

194 lines
5.3 KiB
Go

package users
import (
"database/sql"
"errors"
"time"
)
// MailEvent is one provider delivery event.
type MailEvent struct {
Event string
At time.Time
Reason string
}
// MailRecord is one sent mail with its delivery summary and history.
type MailRecord struct {
ID int64
UserID *int64
ToEmail string
Purpose string
ProviderMessageID string
SentAt time.Time
LastEvent string
LastEventAt time.Time
LastReason string
Events []MailEvent // chronological; filled by MailByID / MailForUser
}
const mailCols = `id, user_id, to_email, purpose, provider_message_id, sent_at, last_event, last_event_at, last_reason`
func scanMail(row rowScanner) (*MailRecord, error) {
var m MailRecord
var uid sql.NullInt64
var msgID sql.NullString
var sent, lastAt int64
if err := row.Scan(&m.ID, &uid, &m.ToEmail, &m.Purpose, &msgID, &sent, &m.LastEvent, &lastAt, &m.LastReason); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
return nil, err
}
if uid.Valid {
v := uid.Int64
m.UserID = &v
}
m.ProviderMessageID = msgID.String
m.SentAt, m.LastEventAt = fromUnix(sent), fromUnix(lastAt)
return &m, nil
}
// LogMail records a sent mail. messageID may be empty if the provider gave none.
func (s *Store) LogMail(userID *int64, to, purpose, messageID string) (int64, error) {
now := unix(s.now())
var mid any
if messageID != "" {
mid = messageID
}
res, err := s.db.Exec(`INSERT INTO mail_log (user_id, to_email, purpose, provider_message_id, sent_at, last_event, last_event_at)
VALUES (?, ?, ?, ?, ?, 'sent', ?)`, nullInt(userID), to, purpose, mid, now, now)
if err != nil {
return 0, err
}
return res.LastInsertId()
}
// RecordMailEvent appends a provider event to the mail with that provider
// message id. Duplicates (same event and time) are ignored; the summary
// columns follow the newest event. found is false for unknown ids.
func (s *Store) RecordMailEvent(messageID, event string, at time.Time, reason string) (userID *int64, found bool, err error) {
tx, err := s.db.Begin()
if err != nil {
return nil, false, err
}
defer tx.Rollback()
var id, lastAt int64
var uid sql.NullInt64
err = tx.QueryRow(`SELECT id, user_id, last_event_at FROM mail_log WHERE provider_message_id = ?`, messageID).
Scan(&id, &uid, &lastAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, false, nil
}
if err != nil {
return nil, false, err
}
if _, err := tx.Exec(`INSERT OR IGNORE INTO mail_events (mail_id, event, at, reason) VALUES (?, ?, ?, ?)`,
id, event, unix(at), reason); err != nil {
return nil, false, err
}
if unix(at) >= lastAt {
if _, err := tx.Exec(`UPDATE mail_log SET last_event = ?, last_event_at = ?, last_reason = ? WHERE id = ?`,
event, unix(at), reason, id); err != nil {
return nil, false, err
}
}
if err := tx.Commit(); err != nil {
return nil, false, err
}
if uid.Valid {
v := uid.Int64
userID = &v
}
return userID, true, nil
}
func (s *Store) eventsFor(mailID int64) ([]MailEvent, error) {
rows, err := s.db.Query(`SELECT event, at, reason FROM mail_events WHERE mail_id = ? ORDER BY at, rowid`, mailID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []MailEvent
for rows.Next() {
var e MailEvent
var at int64
if err := rows.Scan(&e.Event, &at, &e.Reason); err != nil {
return nil, err
}
e.At = fromUnix(at)
out = append(out, e)
}
return out, rows.Err()
}
// MailByID returns one record with its events.
func (s *Store) MailByID(id int64) (*MailRecord, error) {
m, err := scanMail(s.db.QueryRow(`SELECT `+mailCols+` FROM mail_log WHERE id = ?`, id))
if err != nil {
return nil, err
}
if m.Events, err = s.eventsFor(m.ID); err != nil {
return nil, err
}
return m, nil
}
// MailForUser returns a user's mails, newest first, each with its events.
func (s *Store) MailForUser(userID int64, limit int) ([]MailRecord, error) {
if limit <= 0 {
limit = 50
}
rows, err := s.db.Query(`SELECT `+mailCols+` FROM mail_log WHERE user_id = ? ORDER BY sent_at DESC, id DESC LIMIT ?`, userID, limit)
if err != nil {
return nil, err
}
var out []MailRecord
for rows.Next() {
m, err := scanMail(rows)
if err != nil {
rows.Close()
return nil, err
}
out = append(out, *m)
}
rows.Close()
if err := rows.Err(); err != nil {
return nil, err
}
for i := range out {
if out[i].Events, err = s.eventsFor(out[i].ID); err != nil {
return nil, err
}
}
return out, nil
}
// LatestMailByUser maps user id → that user's most recent mail (no events).
func (s *Store) LatestMailByUser() (map[int64]MailRecord, error) {
rows, err := s.db.Query(`SELECT ` + mailCols + ` FROM mail_log m WHERE user_id IS NOT NULL
AND id = (SELECT MAX(id) FROM mail_log WHERE user_id = m.user_id)`)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[int64]MailRecord{}
for rows.Next() {
m, err := scanMail(rows)
if err != nil {
return nil, err
}
out[*m.UserID] = *m
}
return out, rows.Err()
}
// PruneMail deletes mail records (and their events) older than maxAge.
func (s *Store) PruneMail(maxAge time.Duration) (int64, error) {
res, err := s.db.Exec(`DELETE FROM mail_log WHERE sent_at < ?`, unix(s.now())-int64(maxAge/time.Second))
if err != nil {
return 0, err
}
return res.RowsAffected()
}