Files
meshcore-analyzer/internal/users/onetime.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

160 lines
4.9 KiB
Go

package users
import (
"database/sql"
"errors"
"time"
)
// Purpose is what a one-time link may be used for.
type Purpose string
const (
PurposeActivate Purpose = "activate"
PurposeReset Purpose = "reset"
PurposeEmailChange Purpose = "email_change"
)
// IssueToken creates a one-time token and invalidates the user's earlier
// unused tokens for the same purpose, so only the newest link works.
// newEmail is stored for PurposeEmailChange and ignored when empty.
func (s *Store) IssueToken(userID int64, p Purpose, ttl time.Duration, newEmail string) (string, error) {
raw, hash, err := NewToken()
if err != nil {
return "", err
}
now := s.now()
tx, err := s.db.Begin()
if err != nil {
return "", err
}
defer tx.Rollback()
if _, err := tx.Exec(`UPDATE tokens SET used_at = ? WHERE user_id = ? AND purpose = ? AND used_at IS NULL`,
unix(now), userID, string(p)); err != nil {
return "", err
}
var ne any
if newEmail != "" {
ne = newEmail
}
if _, err := tx.Exec(`INSERT INTO tokens (token_hash, user_id, purpose, new_email, expires_at) VALUES (?, ?, ?, ?, ?)`,
hash, userID, string(p), ne, unix(now.Add(ttl))); err != nil {
return "", err
}
return raw, tx.Commit()
}
// tokenQuerier is satisfied by *sql.DB and *sql.Tx.
type tokenQuerier interface {
QueryRow(query string, args ...any) *sql.Row
}
// checkToken validates an unused, unexpired token of purpose p by hash
// without changing anything.
func (s *Store) checkToken(q tokenQuerier, hash string, p Purpose) (userID int64, newEmail string, err error) {
var purpose string
var expires int64
var ne sql.NullString
var used sql.NullInt64
err = q.QueryRow(`SELECT user_id, purpose, new_email, expires_at, used_at FROM tokens WHERE token_hash = ?`, hash).
Scan(&userID, &purpose, &ne, &expires, &used)
if errors.Is(err, sql.ErrNoRows) {
return 0, "", ErrTokenInvalid
}
if err != nil {
return 0, "", err
}
if purpose != string(p) || used.Valid {
return 0, "", ErrTokenInvalid
}
if unix(s.now()) >= expires {
return 0, "", ErrTokenExpired
}
return userID, ne.String, nil
}
// TokenUser returns the user a token belongs to with the same checks as
// ConsumeToken, but does not burn it.
func (s *Store) TokenUser(raw string, p Purpose) (int64, error) {
uid, _, err := s.checkToken(s.db, HashToken(raw), p)
return uid, err
}
// ConsumeToken validates and burns a token. A purpose mismatch returns
// ErrTokenInvalid without burning it. Expired tokens return ErrTokenExpired.
func (s *Store) ConsumeToken(raw string, p Purpose) (userID int64, newEmail string, err error) {
hash := HashToken(raw)
tx, err := s.db.Begin()
if err != nil {
return 0, "", err
}
defer tx.Rollback()
userID, newEmail, err = s.checkToken(tx, hash, p)
if err != nil {
return 0, "", err
}
if err := expectOne(tx.Exec(`UPDATE tokens SET used_at = ? WHERE token_hash = ? AND used_at IS NULL`, unix(s.now()), hash)); err != nil {
if errors.Is(err, ErrNotFound) {
return 0, "", ErrTokenInvalid
}
return 0, "", err
}
if err := tx.Commit(); err != nil {
return 0, "", err
}
return userID, newEmail, nil
}
// ActivateWithToken burns an activation token of user id and activates the
// account with role in one transaction, but only while the user is still
// pending with verifiedHash, the hash the caller checked the password
// against. Otherwise it returns ErrAccountChanged and burns nothing.
// A token of another purpose or user returns ErrTokenInvalid.
func (s *Store) ActivateWithToken(raw string, id int64, role Role, verifiedHash string) error {
hash := HashToken(raw)
tx, err := s.db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
uid, _, err := s.checkToken(tx, hash, PurposeActivate)
if err != nil {
return err
}
if uid != id {
return ErrTokenInvalid
}
now := unix(s.now())
if err := expectOne(tx.Exec(`UPDATE tokens SET used_at = ? WHERE token_hash = ? AND used_at IS NULL`, now, hash)); err != nil {
if errors.Is(err, ErrNotFound) {
return ErrTokenInvalid
}
return err
}
err = expectOne(tx.Exec(`UPDATE users SET status = 'active', role = ?, activated_at = ?, activated_by = NULL
WHERE id = ? AND status = 'pending' AND password_hash = ?`, string(role), now, id, verifiedHash))
if errors.Is(err, ErrNotFound) {
return ErrAccountChanged
}
if err != nil {
return err
}
return tx.Commit()
}
// InvalidateTokens burns all of a user's unused tokens for purpose p.
func (s *Store) InvalidateTokens(userID int64, p Purpose) error {
_, err := s.db.Exec(`UPDATE tokens SET used_at = ? WHERE user_id = ? AND purpose = ? AND used_at IS NULL`,
unix(s.now()), userID, string(p))
return err
}
// PruneTokens deletes tokens that expired more than keep ago.
func (s *Store) PruneTokens(keep time.Duration) (int64, error) {
res, err := s.db.Exec(`DELETE FROM tokens WHERE expires_at < ?`, unix(s.now())-int64(keep/time.Second))
if err != nil {
return 0, err
}
return res.RowsAffected()
}