mirror of
https://github.com/Kpa-clawbot/meshcore-analyzer.git
synced 2026-10-11 08:17:43 +00:00
Part B of #2128: a logged-in user's settings follow them across devices. Log in on a phone and your own nodes, favorites, customizer and filters are there; a change on one device reaches the others within a minute or when you return to the tab. **This PR builds on #2129.** Until that one is merged, the diff here includes it. The commits for this part start at `docs(specs): settings sync for optional user management (sub-project B)`. ## The situation Everything a visitor sets up lives in one browser's `localStorage` (about 100 keys in `public/`). A second device or a cleared cache starts from zero (#895). ## What this PR adds **Storage.** `users.db` schema v2: one JSON document per user in `user_settings`, with a revision number and a generation id. A write succeeds only when the client's revision and generation match the stored ones, so two devices cannot overwrite each other silently. **Server.** `GET`, `PUT` and `DELETE /api/account/settings`, behind the same session and CSRF checks as the account routes. - The server owns the list of synced keys (61 keys, [`settings_allowlist.go`](https://github.com/efiten/CoreScope/blob/feat/settings-sync/cmd/server/settings_allowlist.go)) and sends it to the client, so the two cannot drift. - A hard denylist, checked first, refuses `meshcore-api-key`, every `corescope_channel_*` key and `live-channel-colors` (#725). The colour map is keyed by channel hash, and for a user-added channel that hash is `user:<name>`, which would expose hashtag channel names. - Documents are capped at 256 KiB, measured like `JSON.stringify`. PUT is limited to 60 requests per hour per user. A stale revision gets 409 with the current document. **Client** ([`settings-sync.js`](https://github.com/efiten/CoreScope/blob/feat/settings-sync/public/settings-sync.js)). Inert unless the feature is on and someone is logged in. - It wraps `localStorage.setItem` and `removeItem` for allowlisted keys only and pushes 2 seconds after the last change. - It pulls on login, page load, tab focus and every 60 seconds while the tab is visible. - **Merge:** three-way, against a per-device baseline that belongs to one user and one document generation. Lists (own nodes, favorites, saved filters) merge per item, so an item added anywhere is kept and an item removed on one device does not come back from another. Single values: the profile wins unless only this device changed it. - Remote changes are written without a push, theme and colour-blind preset are re-applied, and the current page re-renders (skipped on account pages and while the geofilter editor is open). **UI.** - Logout asks: keep my settings on this device (default), remove them from this device, or cancel. Channel keys are never removed: no copy exists anywhere else. - The account page gets a "Settings sync" section: last synced time, "Sync now", what is and is not synced, and "Delete synced settings from my account". ## Not synced Layout and device state (panel and column widths, collapsed panels, map positions, geofilter drafts), channel data (#725), the API key, and all `sessionStorage`. The full list is in the [spec](https://github.com/efiten/CoreScope/blob/feat/settings-sync/docs/specs/2026-10-06-user-settings-sync-design.md). ## Performance - One GET per page load, tab focus and minute while visible; one debounced PUT per burst of changes. - The `setItem` wrapper costs one Set lookup per write for non-synced keys. A synced write reads one small revision key, not the stored document. - The server reads or writes one row per request. ## Verification - `internal/users` and `cmd/server`: `go vet` and `go test` pass locally (22 new Go tests), including a test that every allowlisted key still occurs in `public/`, and denylist tests. - `tests/unit/test-settings-sync.js`: 79 passing (vm, real module). The cases cover the merge table, two tabs sharing one storage, stale answers after a push, delete while a push is in flight, and logout while the final push fails. - `sh test-all.sh` exits 0. - `tests/e2e/test-user-management-e2e.js` (10 steps, 4 of them new) passed locally with two browser contexts as two devices: a favorite and the packet time window travel from device 1 to device 2, a removal does not come back, and "remove from this device" clears the synced keys while a channel key stays. - Checked by hand on a staging instance with a desktop and a phone on one account. ## Not in this PR - On a shared browser where the previous user chose "keep", the next user's first login merges those settings into their own account. The user guide says to choose "remove" on shared computers. - Saved filter expressions are synced as typed, including any channel names written in them. The guide says so. - Realtime push between devices; the minute pull is the sync interval. --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
133 lines
4.1 KiB
Go
133 lines
4.1 KiB
Go
package users
|
|
|
|
import (
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
)
|
|
|
|
// migrations[i] upgrades the schema from version i to i+1. Forward-only:
|
|
// never edit a shipped entry, append a new one.
|
|
var migrations = [][]string{
|
|
{ // v1: sub-project A
|
|
`CREATE TABLE users (
|
|
id INTEGER PRIMARY KEY,
|
|
email TEXT NOT NULL UNIQUE,
|
|
display_name TEXT NOT NULL,
|
|
password_hash TEXT NOT NULL,
|
|
role TEXT NOT NULL DEFAULT 'user' CHECK (role IN ('user','admin')),
|
|
status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','active','disabled')),
|
|
created_at INTEGER NOT NULL,
|
|
activated_at INTEGER,
|
|
activated_by INTEGER,
|
|
last_login_at INTEGER,
|
|
email_bouncing INTEGER NOT NULL DEFAULT 0
|
|
)`,
|
|
`CREATE TABLE sessions (
|
|
id INTEGER PRIMARY KEY,
|
|
token_hash TEXT NOT NULL UNIQUE,
|
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
csrf_token TEXT NOT NULL,
|
|
created_at INTEGER NOT NULL,
|
|
expires_at INTEGER NOT NULL,
|
|
last_seen_at INTEGER NOT NULL,
|
|
user_agent TEXT NOT NULL DEFAULT ''
|
|
)`,
|
|
`CREATE INDEX sessions_user ON sessions(user_id)`,
|
|
`CREATE TABLE tokens (
|
|
token_hash TEXT PRIMARY KEY,
|
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
purpose TEXT NOT NULL CHECK (purpose IN ('activate','reset','email_change')),
|
|
new_email TEXT,
|
|
expires_at INTEGER NOT NULL,
|
|
used_at INTEGER
|
|
)`,
|
|
`CREATE INDEX tokens_user ON tokens(user_id, purpose)`,
|
|
`CREATE TABLE audit_log (
|
|
id INTEGER PRIMARY KEY,
|
|
at INTEGER NOT NULL,
|
|
actor_user_id INTEGER,
|
|
action TEXT NOT NULL,
|
|
target_user_id INTEGER,
|
|
detail TEXT NOT NULL DEFAULT '{}'
|
|
)`,
|
|
`CREATE INDEX audit_target ON audit_log(target_user_id)`,
|
|
`CREATE INDEX audit_actor ON audit_log(actor_user_id)`,
|
|
`CREATE TABLE mail_log (
|
|
id INTEGER PRIMARY KEY,
|
|
user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
|
|
to_email TEXT NOT NULL,
|
|
purpose TEXT NOT NULL,
|
|
provider_message_id TEXT,
|
|
sent_at INTEGER NOT NULL,
|
|
last_event TEXT NOT NULL DEFAULT 'sent',
|
|
last_event_at INTEGER NOT NULL,
|
|
last_reason TEXT NOT NULL DEFAULT ''
|
|
)`,
|
|
`CREATE INDEX mail_user ON mail_log(user_id)`,
|
|
`CREATE UNIQUE INDEX mail_msgid ON mail_log(provider_message_id) WHERE provider_message_id IS NOT NULL`,
|
|
`CREATE TABLE mail_events (
|
|
mail_id INTEGER NOT NULL REFERENCES mail_log(id) ON DELETE CASCADE,
|
|
event TEXT NOT NULL,
|
|
at INTEGER NOT NULL,
|
|
reason TEXT NOT NULL DEFAULT '',
|
|
UNIQUE (mail_id, event, at)
|
|
)`,
|
|
},
|
|
{ // v2: sub-project B, settings sync (one document per user)
|
|
`CREATE TABLE user_settings (
|
|
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
|
|
doc TEXT NOT NULL,
|
|
revision INTEGER NOT NULL,
|
|
generation TEXT NOT NULL,
|
|
updated_at INTEGER NOT NULL
|
|
)`,
|
|
},
|
|
}
|
|
|
|
func (s *Store) migrate() error {
|
|
if _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)`); err != nil {
|
|
return fmt.Errorf("users: schema_version: %w", err)
|
|
}
|
|
v, err := s.SchemaVersion()
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
if _, err := s.db.Exec(`INSERT INTO schema_version (version) VALUES (0)`); err != nil {
|
|
return fmt.Errorf("users: init schema_version: %w", err)
|
|
}
|
|
v = 0
|
|
} else if err != nil {
|
|
return fmt.Errorf("users: read schema_version: %w", err)
|
|
}
|
|
if v > len(migrations) {
|
|
return fmt.Errorf("users: database schema version %d is newer than this binary supports (%d)", v, len(migrations))
|
|
}
|
|
for i := v; i < len(migrations); i++ {
|
|
tx, err := s.db.Begin()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, stmt := range migrations[i] {
|
|
if _, err := tx.Exec(stmt); err != nil {
|
|
tx.Rollback()
|
|
return fmt.Errorf("users: migration %d: %w", i+1, err)
|
|
}
|
|
}
|
|
if _, err := tx.Exec(`UPDATE schema_version SET version = ?`, i+1); err != nil {
|
|
tx.Rollback()
|
|
return fmt.Errorf("users: migration %d: %w", i+1, err)
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
return fmt.Errorf("users: migration %d: %w", i+1, err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// SchemaVersion returns the applied schema version (sql.ErrNoRows on a
|
|
// database that has never been migrated).
|
|
func (s *Store) SchemaVersion() (int, error) {
|
|
var v int
|
|
err := s.db.QueryRow(`SELECT version FROM schema_version`).Scan(&v)
|
|
return v, err
|
|
}
|