Fix critical and high audit findings
Fixed findings from the audit reports (SECURITY, QUALITY, PERFORMANCE): - P-001 · Dashboard re-downloads the entire dataset every 5 seconds Re-synced the vendored shared/ snapshot from shared commit 199a5ef. Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7dd0d34383
commit
a84a36349b
31 files changed
+651
-6053
No files matched your search
+12
-9
@@ -6,33 +6,36 @@
|
||||
- **Commit:** 6aec03f on main
|
||||
- **Working tree:** clean (no uncommitted changes, no untracked files)
|
||||
- **Stack:** Go 1.26 (net/http, pgx v5) API server; PostgreSQL; SvelteKit 2 / Svelte 5 static SPA (Vite 8, TanStack Query) embedded in the Go binary; Android client (Kotlin, Room, Retrofit) with offline sync; Docker multi-stage image on `scratch`; GitHub Actions.
|
||||
- **Updated:** 2026-10-19 — Critical and High findings handled in the working tree (not committed).
|
||||
- **Scope:** Read all first-party backend code (`backend/*.go`, including tests), `docker/Dockerfile`, `.dockerignore`, `.github/workflows/*`, the frontend data layer, list components, routes and Vite config, the Android API client, preferences and sync repository, and the shared auth, postgres and authclient code that CollabTable calls. Excluded: `node_modules`, `frontend/.svelte-kit`, the Gradle wrapper, lock files (read for versions only), build output, and the rest of `shared/` (node, python and java packages, which CollabTable does not use). Tracked SQLite files were inspected read-only from a copy (schema and row counts only). No tests, builds or linters were run; the analysis is static.
|
||||
|
||||
## Summary
|
||||
|
||||
| Severity | Count |
|
||||
|---|---:|
|
||||
| Critical | 0 |
|
||||
| High | 2 |
|
||||
| Medium | 5 |
|
||||
| Low | 3 |
|
||||
| Info | 1 |
|
||||
| Severity | Count | Fixed | Not reproduced | Open |
|
||||
|---|---:|---:|---:|---:|
|
||||
| Critical | 0 | 0 | 0 | 0 |
|
||||
| High | 2 | 1 | 0 | 1 |
|
||||
| Medium | 5 | 0 | 0 | 5 |
|
||||
| Low | 3 | 0 | 0 | 3 |
|
||||
| Info | 1 | 0 | 0 | 1 |
|
||||
|
||||
Two structural costs dominate: the dashboard re-downloads the full database every 5 seconds, and sync writes row by row with several round trips per value inside one long transaction. Missing indexes and pagination will make both worse as data grows.
|
||||
|
||||
## Issues
|
||||
|
||||
### P-001 · Dashboard re-downloads the entire dataset every 5 seconds · **High**
|
||||
### P-001 · Dashboard re-downloads the entire dataset every 5 seconds · **High** · Fixed
|
||||
- **Location:** `backend/web.go:9-29` (four unpaginated queries), `backend/data.go:68-204` (no LIMIT in any query builder), `backend/web.go:74-76` (`no-store`), `frontend/src/lib/features/lists/listsData.svelte.js:4,10`, `frontend/src/lib/api.js:27-29`
|
||||
- **Description:** `createOverviewData()` polls `/web/data` with `refetchInterval: 5000`. Each response contains every non-deleted list, every field, every item and every item value, with no pagination, no `since` filter and no HTTP caching (`Cache-Control: no-store`). The server already computes per-list effective update times (`web.go:31-72`), but the client has no way to use them to skip unchanged data. TanStack Query's default is to poll only while the tab is visible, so each open dashboard pays this cost.
|
||||
- **Impact:** Transfer, JSON encoding and client re-rendering all scale with total data size rather than with the amount of change. With a few thousand items and several viewers this is continuous multi-megabyte traffic and repeated full re-renders.
|
||||
- **Recommendation:** Serve changes incrementally with a `since` cursor (as sync already does), or add an ETag derived from the maximum `updatedat` and answer `304` when nothing changed, dropping `no-store` for that path. Compress the response (see P-006). Consider a longer interval or server push for the dashboard.
|
||||
- **Status:** Fixed 2026-10-19 — `/web/data` now sends a weak ETag over the response data (the per-request timestamp is excluded), answers `304` when `If-None-Match` matches, and uses `Cache-Control: private, no-cache` instead of `no-store`, so an unchanged poll sends no body. A `max(updatedat)` validator was rejected because client-supplied timestamps can move backwards and hard deletes leave no trace. Residual: changed data is still sent in full, the server still runs the four queries on every poll, and browsers may now keep a private on-disk copy of the dashboard data, which `no-store` previously prevented. Files: `backend/web.go`, `backend/data.go` (stable tie-break order), `backend/web_test.go`.
|
||||
|
||||
### P-002 · Sync issues several statements per row inside one long transaction · **High**
|
||||
### P-002 · Sync issues several statements per row inside one long transaction · **High** · Open
|
||||
- **Location:** `backend/sync.go:61-209` (the transaction closure). For item values, `sync.go:172-207`: `listid` lookup (`:175`), `EXISTS` on items (`:185`), optional stub insert (`:193`), upsert (`:198`) and a notification insert (`:206`). Per-row upserts at `sync.go:64-79`, `:104-126`, `:149-164`. Request size is capped at 50 MB by `backend/server.go:253-259`.
|
||||
- **Description:** Every list, field, item and value in a request is processed one at a time with separate statements. Each item value needs four to five round trips, plus a notification row per change, and the whole batch holds row locks until commit. There is no cap on the number of rows per request.
|
||||
- **Impact:** An initial sync or a large offline push (potentially thousands of rows) becomes thousands of sequential round trips. The transaction stays open for the whole batch, and the 60-second `WriteTimeout` (`server.go:123`) can cut the request off. The device then retries and repeats the same work, and concurrent devices contend on the same rows.
|
||||
- **Recommendation:** Batch the writes, using `pgx.Batch` or multi-row `INSERT ... SELECT FROM unnest(...)` upserts per table. Load the field-to-list map once per request instead of once per value. Insert notifications as one multi-row statement per request. Cap rows per request, return `413` above the cap, and have clients chunk their pushes.
|
||||
- **Status:** Open 2026-10-19 — partly addressed: `backend/sync.go` now resolves each request's fields and items in two statements (`valueReferences`) instead of up to two lookups per value, which removes the per-value reads. Still needed: the list, field, item and value upserts and their notification inserts still run one statement at a time inside one transaction, so this needs `pgx.Batch` or `unnest` bulk upserts; the per-request row cap with `413` is a client-facing change and needs CollabTableAndroid to chunk pushes first. Not measured against PostgreSQL, since none is available in this environment.
|
||||
|
||||
### P-003 · No index on `updatedat`, so every delta query scans the table · **Medium**
|
||||
- **Location:** `backend/db.go:40-189` (indexes exist only on `fields.listid`, `items.listid`, `item_values.itemid`, `item_values.fieldid`, and notifications `createdat` and `listid`, at `:83-86` and `:97-98`). Queries filtering on `updatedat`: `backend/data.go:75`, `:108`, `:145`, `:178`; sync calls at `backend/sync.go:220-235`.
|
||||
|
||||
+4
-4
@@ -79,7 +79,7 @@ func (d *DB) queryLists(ctx context.Context, includeDeleted bool, since *int64)
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += " ORDER BY updatedat DESC"
|
||||
query += " ORDER BY updatedat DESC, id"
|
||||
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
@@ -116,7 +116,7 @@ func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64,
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += ` ORDER BY "order" ASC`
|
||||
query += ` ORDER BY "order" ASC, id`
|
||||
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
@@ -152,7 +152,7 @@ func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64,
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += " ORDER BY updatedat DESC"
|
||||
query += " ORDER BY updatedat DESC, id"
|
||||
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
@@ -185,7 +185,7 @@ func (d *DB) queryValues(ctx context.Context, since *int64, itemID string) ([]It
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += " ORDER BY updatedat ASC"
|
||||
query += " ORDER BY updatedat ASC, id"
|
||||
|
||||
rows, err := d.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
|
||||
+62
-12
@@ -1,7 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
@@ -42,6 +42,55 @@ func normalizeEntityTimestamps(createdAt, updatedAt, now int64) (int64, int64) {
|
||||
return created, updated
|
||||
}
|
||||
|
||||
// valueReferences returns the list ID of each field and the existence of each
|
||||
// item that the values refer to, using one statement per table.
|
||||
func valueReferences(ctx context.Context, tx pgx.Tx, values []ItemValue) (map[string]string, map[string]bool, error) {
|
||||
fieldLists := make(map[string]string)
|
||||
existingItems := make(map[string]bool)
|
||||
if len(values) == 0 {
|
||||
return fieldLists, existingItems, nil
|
||||
}
|
||||
fieldIDs := make([]string, 0, len(values))
|
||||
itemIDs := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
fieldIDs = append(fieldIDs, value.FieldID)
|
||||
itemIDs = append(itemIDs, value.ItemID)
|
||||
}
|
||||
|
||||
fieldRows, err := tx.Query(ctx, `SELECT id, listid FROM fields WHERE id = ANY($1)`, fieldIDs)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer fieldRows.Close()
|
||||
for fieldRows.Next() {
|
||||
var fieldID, listID string
|
||||
if err := fieldRows.Scan(&fieldID, &listID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
fieldLists[fieldID] = listID
|
||||
}
|
||||
if err := fieldRows.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
itemRows, err := tx.Query(ctx, `SELECT id FROM items WHERE id = ANY($1)`, itemIDs)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer itemRows.Close()
|
||||
for itemRows.Next() {
|
||||
var itemID string
|
||||
if err := itemRows.Scan(&itemID); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
existingItems[itemID] = true
|
||||
}
|
||||
if err := itemRows.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return fieldLists, existingItems, nil
|
||||
}
|
||||
|
||||
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
var request SyncRequest
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
@@ -169,23 +218,23 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve the fields and items the values refer to once per request, not once
|
||||
// per value. Items are read after the item loop above, so this request's own
|
||||
// item inserts are visible.
|
||||
fieldLists, existingItems, err := valueReferences(r.Context(), tx, request.ItemValues)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, value := range request.ItemValues {
|
||||
updatedAt := normalizeTimestamp(int64(value.UpdatedAt), now, now)
|
||||
var listID string
|
||||
fieldErr := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, value.FieldID).Scan(&listID)
|
||||
if errors.Is(fieldErr, pgx.ErrNoRows) {
|
||||
listID, ok := fieldLists[value.FieldID]
|
||||
if !ok {
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
|
||||
continue
|
||||
}
|
||||
if fieldErr != nil {
|
||||
return fieldErr
|
||||
}
|
||||
|
||||
var itemExists bool
|
||||
if err := tx.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM items WHERE id = $1)`, value.ItemID).Scan(&itemExists); err != nil {
|
||||
return err
|
||||
}
|
||||
if !itemExists {
|
||||
if !existingItems[value.ItemID] {
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
|
||||
VALUES ($1, $2, $3, $3, 0)
|
||||
@@ -194,6 +243,7 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
|
||||
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
|
||||
continue
|
||||
}
|
||||
existingItems[value.ItemID] = true
|
||||
}
|
||||
if _, err := tx.Exec(r.Context(), `
|
||||
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
|
||||
|
||||
+40
-6
@@ -1,8 +1,12 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -71,10 +75,7 @@ func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
|
||||
webLists = append(webLists, webList{List: list, EffectiveUpdatedAt: effective})
|
||||
}
|
||||
|
||||
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
|
||||
w.Header().Set("Pragma", "no-cache")
|
||||
w.Header().Set("Expires", "0")
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
payload := map[string]any{
|
||||
"lists": webLists,
|
||||
"fields": fields,
|
||||
"items": items,
|
||||
@@ -85,8 +86,41 @@ func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
|
||||
"items": len(items),
|
||||
"values": len(values),
|
||||
},
|
||||
"timestamp": time.Now().UnixMilli(),
|
||||
})
|
||||
}
|
||||
// The ETag covers the data only; the timestamp is added after hashing because
|
||||
// it changes on every request.
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
|
||||
return
|
||||
}
|
||||
digest := sha256.Sum256(body)
|
||||
etag := `W/"` + hex.EncodeToString(digest[:]) + `"`
|
||||
// Browsers may keep this per-user response, but revalidate it on every poll,
|
||||
// so an unchanged dashboard gets a 304 instead of the full body.
|
||||
w.Header().Set("Cache-Control", "private, no-cache")
|
||||
w.Header().Set("ETag", etag)
|
||||
if etagMatches(r.Header.Get("If-None-Match"), etag) {
|
||||
w.WriteHeader(http.StatusNotModified)
|
||||
return
|
||||
}
|
||||
payload["timestamp"] = time.Now().UnixMilli()
|
||||
writeJSON(w, http.StatusOK, payload)
|
||||
}
|
||||
|
||||
// etagMatches reports whether an If-None-Match header matches etag under the
|
||||
// weak comparison of RFC 9110, which ignores the W/ prefix.
|
||||
func etagMatches(ifNoneMatch, etag string) bool {
|
||||
if strings.TrimSpace(ifNoneMatch) == "*" {
|
||||
return true
|
||||
}
|
||||
want := strings.TrimPrefix(etag, "W/")
|
||||
for _, candidate := range strings.Split(ifNoneMatch, ",") {
|
||||
if strings.TrimPrefix(strings.TrimSpace(candidate), "W/") == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Server) handleNotificationPoll(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestEtagMatchesUsesWeakComparison(t *testing.T) {
|
||||
const etag = `W/"abc"`
|
||||
cases := []struct {
|
||||
name string
|
||||
ifNoneMatch string
|
||||
want bool
|
||||
}{
|
||||
{name: "missing header", ifNoneMatch: "", want: false},
|
||||
{name: "same weak tag", ifNoneMatch: `W/"abc"`, want: true},
|
||||
{name: "strong form of same tag", ifNoneMatch: `"abc"`, want: true},
|
||||
{name: "one of several tags", ifNoneMatch: `"x", W/"abc"`, want: true},
|
||||
{name: "different tag", ifNoneMatch: `W/"def"`, want: false},
|
||||
{name: "wildcard", ifNoneMatch: "*", want: true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := etagMatches(tc.ifNoneMatch, etag); got != tc.want {
|
||||
t.Fatalf("etagMatches(%q) = %v, want %v", tc.ifNoneMatch, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"@gabriel20xx/web-ui": minor
|
||||
---
|
||||
|
||||
`UserManagement` accepts an optional `roles` prop (`KnownRole[]`) in place of the `projects` prop it replaces: when present, each account gets a role picker (checkboxes in the add and edit rows, the role names in the read-only row), and `onCreate`/`onUpdate` receive a `roleIds: number[]` field. An account's projects now come from its roles, so per-account project checkboxes are gone. `ManagedUser` carries `roleIds` instead of `projects`. Only AuthGuard's own admin UI passes this prop today; every other consumer is unaffected.
|
||||
+49
-20
@@ -21,7 +21,6 @@ The single source of truth for code reused across every project in this workspac
|
||||
|---|---|---|
|
||||
| `@gabriel20xx/design-tokens` | CSS | Colors, typography, spacing, radii, shadows, light/dark theme variables. |
|
||||
| `@gabriel20xx/web-ui` | Svelte | Shared application shell and reusable UI components. The complete public component inventory is documented below. |
|
||||
| `@gabriel20xx/legacy-assets` | Browser JS/CSS | Legacy client-side assets, kept for a handful of older pages. |
|
||||
| `repos.gfranz.ch/Gabriel20xx/shared/backend` | Go | Env config, `pgx` pools/transactions, auth persistence, an AuthGuard client (`authclient`), log shipping (`logshipper`), embedded Goose migrations, and the media-family's shared route/table surface (`mediaauth`, `mediacore`, `carriernodeclient`, `syncsocket`). |
|
||||
| `@gabriel20xx/node-backend` | Node.js | `pg` pool/config/transactions/migrations, auth/session persistence, an AuthGuard client. |
|
||||
| `gabriel20xx-shared-backend` | Python | `asyncpg` pool/config, auth/session persistence, an AuthGuard client. |
|
||||
@@ -29,34 +28,64 @@ The single source of truth for code reused across every project in this workspac
|
||||
|
||||
### Public `web-ui` components
|
||||
|
||||
These are the complete Svelte component exports from `packages/web-ui/src/lib/index.ts` (22 components):
|
||||
These are the complete Svelte component exports from `packages/web-ui/src/lib/index.ts` (22 components), grouped by purpose.
|
||||
|
||||
#### Layout and navigation
|
||||
|
||||
| Component | Includes |
|
||||
|---|---|
|
||||
| `AppShell` | Application layout that composes the header, notification stack, theme, and primary-color handling. |
|
||||
| `Header` | Branded application header with navigation, icons, actions, profile/settings menus, and logout. |
|
||||
|
||||
#### Buttons and controls
|
||||
|
||||
| Component | Includes |
|
||||
|---|---|
|
||||
| `Button` | Button with primary, secondary, outline, ghost, and danger variants; multiple sizes and full-width mode. |
|
||||
| `Pagination` | Page navigation and page-size selection with total/item counts. |
|
||||
| `PrimaryColorPicker` | Per-project primary-color selector backed by the shared color persistence helpers. |
|
||||
|
||||
#### Dialogs
|
||||
|
||||
| Component | Includes |
|
||||
|---|---|
|
||||
| `AboutDialog` | About modal with application branding, description, version, links, and custom content. |
|
||||
| `AppShell` | Application layout that composes the header, notification stack, theme, and primary-color handling. |
|
||||
| `AuthPage` | Login, first-time setup, password-reset, and optional TOTP authentication flows. |
|
||||
| `Badge` | Small inline label with default, primary, success, warning, and danger variants. |
|
||||
| `Button` | Button with primary, secondary, outline, ghost, and danger variants; multiple sizes and full-width mode. |
|
||||
| `Card` | Styled content section for grouping application content. |
|
||||
| `Dialog` | Generic modal dialog with title, description, body, footer, and bindable open state. |
|
||||
| `EmptyState` | Empty-content message with an inbox icon, title, and description. |
|
||||
| `Header` | Branded application header with navigation, icons, actions, profile/settings menus, and logout. |
|
||||
| `MediaPlayer` | Audio/video player with playback, seeking, volume, quality, fullscreen, keyboard controls, and custom end controls. |
|
||||
| `MediaPlayerControls` | Reusable media controls for playback, seeking, volume, quality, fullscreen, optional graph toggling, and custom end controls. |
|
||||
| `Metric` | Labeled metric/value display with optional detail and semantic variants. |
|
||||
| `NotificationStack` | Global stack of dismissible success, error, warning, and informational notifications. |
|
||||
| `Pagination` | Page navigation and page-size selection with total/item counts. |
|
||||
| `PrimaryColorPicker` | Per-project primary-color selector backed by the shared color persistence helpers. |
|
||||
| `ProfileDialog` | Profile username/email/password editing and TOTP settings. |
|
||||
| `SectionTitle` | Section heading with optional description. |
|
||||
| `SettingsDialog` | Generic settings modal with custom content or a default empty-settings message. |
|
||||
|
||||
#### Content and data display
|
||||
|
||||
| Component | Includes |
|
||||
|---|---|
|
||||
| `Badge` | Small inline label with default, primary, success, warning, and danger variants. |
|
||||
| `Card` | Styled content section for grouping application content. |
|
||||
| `EmptyState` | Empty-content message with an inbox icon, title, and description. |
|
||||
| `Metric` | Labeled metric/value display with optional detail and semantic variants. |
|
||||
| `SectionTitle` | Section heading with optional description. |
|
||||
|
||||
#### Feedback and status
|
||||
|
||||
| Component | Includes |
|
||||
|---|---|
|
||||
| `NotificationStack` | Global stack of dismissible success, error, warning, and informational notifications. |
|
||||
| `StatusDialog` | Detailed service health/readiness status modal with refresh support. |
|
||||
| `StatusWidget` | Header-friendly health/readiness indicator that polls `/healthz` and `/ready` and opens `StatusDialog`. |
|
||||
| `TotpSettings` | TOTP status, setup, enable, and disable controls. |
|
||||
| `UserManagement` | Role-aware user administration with listing, creation, editing, deletion, role assignment, and pagination. |
|
||||
|
||||
This inventory describes the public component API only; the package also exports notification helpers, primary-color helpers, and TypeScript types. When a public component is added, removed, renamed, or materially changes responsibility, update this table in the same change as `packages/web-ui/src/lib/index.ts`. Keep the table aligned with that barrel file, and do not add internal or generated components to it.
|
||||
#### Media
|
||||
|
||||
| Component | Includes |
|
||||
|---|---|
|
||||
| `MediaPlayer` | Audio/video player with playback, seeking, volume, quality, fullscreen, keyboard controls, and custom end controls. |
|
||||
|
||||
#### Accounts and access
|
||||
|
||||
| Component | Includes |
|
||||
|---|---|
|
||||
| `AuthPage` | Login, first-time setup, password-reset, and optional TOTP authentication flows. |
|
||||
| `ProfileDialog` | Profile username/email/password editing and TOTP settings. |
|
||||
| `TotpSettings` | TOTP status, setup, enable, and disable controls. |
|
||||
|
||||
This inventory describes the public component API only; the package also exports notification helpers, primary-color helpers, and TypeScript types. When a public component is added, removed, renamed, or materially changes responsibility, update the matching category table in the same change as `packages/web-ui/src/lib/index.ts`. Keep the tables aligned with that barrel file, place each component in the category that matches its primary purpose, and do not add internal or generated components to them.
|
||||
|
||||
The `web-ui` components don't import `$app/state`, `$lib` stores, or a project-specific API — applications provide those through props and callbacks.
|
||||
|
||||
|
||||
@@ -85,16 +85,16 @@ func (c *Core) Mount(r chi.Router) {
|
||||
r.With(c.auth.Require).Post("/security/totp/verify", c.auth.TOTPVerify)
|
||||
r.With(c.auth.Require).Post("/security/totp/disable", c.auth.TOTPDisable)
|
||||
r.With(c.auth.Optional).Get("/sync", c.getSyncState)
|
||||
r.With(c.auth.Optional).Put("/sync", c.putSyncState)
|
||||
r.With(c.auth.Require).Put("/sync", c.putSyncState)
|
||||
r.With(c.auth.Optional).Get("/media/state", c.mediaState)
|
||||
r.With(c.auth.Require).Post("/media/like", c.mediaLike)
|
||||
r.With(c.auth.Require).Post("/media/save", c.mediaSave)
|
||||
r.With(c.auth.Optional).Post("/media/view", c.mediaView)
|
||||
r.With(c.auth.Optional).Post("/media/view-session", c.mediaViewSession)
|
||||
r.With(c.auth.Require).Get("/media/liked", c.mediaLiked)
|
||||
r.Get("/media/stream", c.streamMediaByQuery)
|
||||
r.Head("/media/stream", c.streamMediaByQuery)
|
||||
r.Get("/media/thumb", c.thumbnailMediaByQuery)
|
||||
r.With(c.auth.RequireIfLoginRequired).Get("/media/stream", c.streamMediaByQuery)
|
||||
r.With(c.auth.RequireIfLoginRequired).Head("/media/stream", c.streamMediaByQuery)
|
||||
r.With(c.auth.RequireIfLoginRequired).Get("/media/thumb", c.thumbnailMediaByQuery)
|
||||
|
||||
r.With(c.auth.Optional).Get("/media/{id}/tags", c.mediaTags)
|
||||
r.With(c.auth.Require).Post("/media/{id}/tags", c.addMediaTag)
|
||||
@@ -132,10 +132,15 @@ func (c *Core) putSyncState(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusBadRequest, "clientId is required")
|
||||
return
|
||||
}
|
||||
mediaID, ok := syncScalar(input["mediaId"])
|
||||
if !ok {
|
||||
writeError(w, http.StatusBadRequest, "mediaId must be a string, a number or null")
|
||||
return
|
||||
}
|
||||
sessionID := boundedSyncString(firstNonEmpty(syncString(input, "sessionId"), r.URL.Query().Get("sessionId"), "default"))
|
||||
state := map[string]any{
|
||||
"sessionId": sessionID,
|
||||
"mediaId": input["mediaId"],
|
||||
"mediaId": mediaID,
|
||||
"timeMs": syncInt(input, "timeMs", 0),
|
||||
"paused": syncBool(input, "paused"),
|
||||
"fps": syncFPS(input),
|
||||
@@ -144,7 +149,12 @@ func (c *Core) putSyncState(w http.ResponseWriter, r *http.Request) {
|
||||
"updatedAt": time.Now().UTC().Format(time.RFC3339Nano),
|
||||
}
|
||||
if value, ok := input["playAt"]; ok {
|
||||
state["playAt"] = value
|
||||
playAt, valid := syncScalar(value)
|
||||
if !valid {
|
||||
writeError(w, http.StatusBadRequest, "playAt must be a string, a number or null")
|
||||
return
|
||||
}
|
||||
state["playAt"] = playAt
|
||||
}
|
||||
c.sync.SetHTTPState(sessionID, state)
|
||||
c.sync.Broadcast(sessionID)
|
||||
@@ -179,7 +189,7 @@ func (c *Core) streamMediaByQuery(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (c *Core) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) {
|
||||
record, err := c.findMedia(r.Context(), identifier)
|
||||
record, err := c.findMedia(r.Context(), identifier, canSeeHidden(r))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "media not found")
|
||||
return
|
||||
@@ -197,6 +207,11 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
|
||||
writeError(w, http.StatusBadRequest, "invalid media id")
|
||||
return
|
||||
}
|
||||
includeHidden := canSeeHidden(r)
|
||||
if !includeHidden && c.isHiddenMedia(r.Context(), id) {
|
||||
writeError(w, http.StatusNotFound, "thumbnail not found")
|
||||
return
|
||||
}
|
||||
if !strings.Contains(id, string(filepath.Separator)) && !strings.Contains(id, "/") {
|
||||
if c.carrierNode.ProxyThumbnail(w, r, c.serviceName, id) {
|
||||
return
|
||||
@@ -216,7 +231,7 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request,
|
||||
return
|
||||
}
|
||||
}
|
||||
record, err := c.findMedia(r.Context(), id)
|
||||
record, err := c.findMedia(r.Context(), id, includeHidden)
|
||||
if err != nil || !isImagePath(record.FilePath) {
|
||||
writeError(w, http.StatusNotFound, "thumbnail not found")
|
||||
return
|
||||
@@ -723,7 +738,25 @@ func (c *Core) profile(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"user": user})
|
||||
}
|
||||
|
||||
func (c *Core) findMedia(ctx context.Context, identifier string) (MediaRecord, error) {
|
||||
// canSeeHidden reports whether the caller is a moderator, who may stream and view media that has
|
||||
// been hidden (active = FALSE). Everyone else gets hidden media as not found.
|
||||
func canSeeHidden(r *http.Request) bool {
|
||||
return sharedauth.IsAdmin(sharedauth.UserFromContext(r.Context()))
|
||||
}
|
||||
|
||||
// isHiddenMedia reports whether identifier names a media item that has been hidden. A lookup
|
||||
// error counts as hidden, so a database fault never exposes hidden media.
|
||||
func (c *Core) isHiddenMedia(ctx context.Context, identifier string) bool {
|
||||
var hidden bool
|
||||
err := c.db.QueryRow(ctx, `
|
||||
SELECT EXISTS (SELECT 1 FROM media WHERE NOT active AND (media_key=$1 OR CAST(id AS TEXT)=$1))`,
|
||||
strings.TrimSpace(identifier)).Scan(&hidden)
|
||||
return err != nil || hidden
|
||||
}
|
||||
|
||||
// findMedia looks up one media item by media key or numeric id. Hidden media is only returned
|
||||
// when includeHidden is set.
|
||||
func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden bool) (MediaRecord, error) {
|
||||
identifier = strings.TrimSpace(identifier)
|
||||
var record MediaRecord
|
||||
row := c.db.QueryRow(ctx, `
|
||||
@@ -732,7 +765,7 @@ func (c *Core) findMedia(ctx context.Context, identifier string) (MediaRecord, e
|
||||
COALESCE(width, 0), COALESCE(height, 0), COALESCE(duration_ms, 0), COALESCE(size_bytes, 0),
|
||||
COALESCE(is_vr, FALSE), COALESCE(has_funscript, FALSE), funscript_action_count,
|
||||
funscript_avg_speed, funscript_max_speed, COALESCE(speed, 0), COALESCE(modified_at, created_at)
|
||||
FROM media WHERE media_key=$1 OR CAST(id AS TEXT)=$1 LIMIT 1`, identifier)
|
||||
FROM media WHERE (media_key=$1 OR CAST(id AS TEXT)=$1) AND (active OR $2) LIMIT 1`, identifier, includeHidden)
|
||||
var title, description string
|
||||
var width, height int
|
||||
var duration, size int64
|
||||
@@ -1084,6 +1117,20 @@ func syncBool(message map[string]any, key string) bool {
|
||||
return value
|
||||
}
|
||||
|
||||
// syncScalar keeps a client-supplied sync value to what sync state holds: null, a number or a
|
||||
// bounded string. Objects, arrays and booleans are refused so arbitrary JSON is never stored as
|
||||
// shared session state.
|
||||
func syncScalar(value any) (any, bool) {
|
||||
switch typed := value.(type) {
|
||||
case nil, float64:
|
||||
return typed, true
|
||||
case string:
|
||||
return boundedSyncString(typed), true
|
||||
default:
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
func syncInt(message map[string]any, key string, fallback int64) int64 {
|
||||
value, ok := message[key].(float64)
|
||||
if !ok {
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
package mediacore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
|
||||
"repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
|
||||
)
|
||||
|
||||
// loginRequiredStore is a ProxyStore that always requires login, so the auth gate can be
|
||||
// exercised without a database.
|
||||
type loginRequiredStore struct{}
|
||||
|
||||
func (loginRequiredStore) LoginRequired(context.Context) (bool, error) { return true, nil }
|
||||
func (loginRequiredStore) SetLoginRequired(context.Context, bool) error { return nil }
|
||||
func (loginRequiredStore) IsSetupClaimed(context.Context) (bool, error) { return true, nil }
|
||||
func (loginRequiredStore) TryClaimSetup(context.Context) (bool, error) { return false, nil }
|
||||
func (loginRequiredStore) UnclaimSetup(context.Context) error { return nil }
|
||||
|
||||
// loginOffStore is loginRequiredStore with login switched off for the whole application.
|
||||
type loginOffStore struct{ loginRequiredStore }
|
||||
|
||||
func (loginOffStore) LoginRequired(context.Context) (bool, error) { return false, nil }
|
||||
|
||||
// TestMediaStreamAndThumbnailRequireLogin checks that anonymous requests to the media stream and
|
||||
// thumbnail routes are refused when login is required, before any database lookup or CarrierNode
|
||||
// call. The Core in this test has no database and no CarrierNode client, so reaching either would
|
||||
// panic.
|
||||
func TestMediaStreamAndThumbnailRequireLogin(t *testing.T) {
|
||||
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject")
|
||||
router := chi.NewRouter()
|
||||
New(Config{Auth: auth}).Mount(router)
|
||||
|
||||
for _, request := range []struct{ method, target string }{
|
||||
{http.MethodGet, "/media/stream?mediaKey=1"},
|
||||
{http.MethodHead, "/media/stream?mediaKey=1"},
|
||||
{http.MethodGet, "/media/thumb?mediaKey=1"},
|
||||
} {
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httptest.NewRequest(request.method, request.target, nil))
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s %s status = %d, want %d", request.method, request.target, response.Code, http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestMediaGateAllowsAnonymousWhenLoginIsOff checks the gate the media stream and thumbnail routes
|
||||
// use: with login disabled an anonymous request reaches the handler, as it does for the rest of
|
||||
// the application. The handler here is a stub, so no database or CarrierNode call is made.
|
||||
func TestMediaGateAllowsAnonymousWhenLoginIsOff(t *testing.T) {
|
||||
auth := sharedauth.NewWithStore(loginOffStore{}, "session", false, "", "testproject")
|
||||
reached := false
|
||||
gate := auth.RequireIfLoginRequired(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
reached = true
|
||||
}))
|
||||
for _, target := range []string{"/media/stream?mediaKey=1", "/media/thumb?mediaKey=1"} {
|
||||
reached = false
|
||||
response := httptest.NewRecorder()
|
||||
gate.ServeHTTP(response, httptest.NewRequest(http.MethodGet, target, nil))
|
||||
if !reached || response.Code != http.StatusOK {
|
||||
t.Errorf("GET %s with login off: reached = %v, status = %d; want reached and 200", target, reached, response.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// newRoleAuthGuard stands in for AuthGuard's GET /api/me. Each bearer token maps to one role, so a
|
||||
// test can act as a viewer, a moderator or an admin without a database.
|
||||
func newRoleAuthGuard(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
roles := map[string]string{"viewer-token": "user", "moderator-token": "moderator", "admin-token": "admin"}
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
role, ok := roles[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]
|
||||
if !ok || r.URL.Path != "/api/me" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
fmt.Fprintf(w, `{"user":{"id":1,"username":"tester","role":%q}}`, role)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server
|
||||
}
|
||||
|
||||
// TestOnlyModeratorsCanSeeHiddenMedia checks which callers get hidden media looked up at all.
|
||||
// Anonymous callers and viewers may not; moderators and admins may. With login off every caller
|
||||
// is the placeholder superadmin, as for the rest of the application. The active = FALSE filter
|
||||
// itself needs a database and is not exercised here.
|
||||
func TestOnlyModeratorsCanSeeHiddenMedia(t *testing.T) {
|
||||
guard := newRoleAuthGuard(t)
|
||||
login := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject")
|
||||
loginOff := sharedauth.NewWithStore(loginOffStore{}, "session", false, guard.URL, "testproject")
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
auth *sharedauth.Service
|
||||
token string
|
||||
want string
|
||||
}{
|
||||
{"anonymous with login required", login, "", "false"},
|
||||
{"viewer", login, "viewer-token", "false"},
|
||||
{"moderator", login, "moderator-token", "true"},
|
||||
{"admin", login, "admin-token", "true"},
|
||||
{"anonymous with login off", loginOff, "", "true"},
|
||||
} {
|
||||
router := chi.NewRouter()
|
||||
router.With(tc.auth.Optional).Get("/probe", func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, canSeeHidden(r))
|
||||
})
|
||||
request := httptest.NewRequest(http.MethodGet, "/probe", nil)
|
||||
if tc.token != "" {
|
||||
request.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: tc.token})
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if got := response.Body.String(); got != tc.want {
|
||||
t.Errorf("%s: canSeeHidden = %q, want %q", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncWriteRequiresLogin checks that an anonymous PUT /sync is refused before it can change
|
||||
// shared playback state. The Core has no sync hub, so reaching the handler would panic.
|
||||
func TestSyncWriteRequiresLogin(t *testing.T) {
|
||||
auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject")
|
||||
router := chi.NewRouter()
|
||||
New(Config{Auth: auth}).Mount(router)
|
||||
|
||||
request := httptest.NewRequest(http.MethodPut, "/sync", strings.NewReader(`{"clientId":"c1","mediaId":"m1"}`))
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Errorf("PUT /sync status = %d, want %d", response.Code, http.StatusUnauthorized)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSyncScalarKeepsOnlyScalars checks that sync values are limited to null, numbers and
|
||||
// bounded strings, so objects, arrays and booleans are never stored as session state.
|
||||
func TestSyncScalarKeepsOnlyScalars(t *testing.T) {
|
||||
if value, ok := syncScalar(nil); !ok || value != nil {
|
||||
t.Errorf("syncScalar(nil) = %v, %v; want nil, true", value, ok)
|
||||
}
|
||||
if value, ok := syncScalar(float64(7)); !ok || value != float64(7) {
|
||||
t.Errorf("syncScalar(7) = %v, %v; want 7, true", value, ok)
|
||||
}
|
||||
if value, ok := syncScalar(" media-1 "); !ok || value != "media-1" {
|
||||
t.Errorf("syncScalar(string) = %v, %v; want media-1, true", value, ok)
|
||||
}
|
||||
long, ok := syncScalar(strings.Repeat("x", 500))
|
||||
if text, isText := long.(string); !ok || !isText || len(text) != 128 {
|
||||
t.Errorf("syncScalar(long string) = %v, %v; want a 128-byte string, true", long, ok)
|
||||
}
|
||||
for _, refused := range []any{map[string]any{"a": 1}, []any{1}, true} {
|
||||
if _, ok := syncScalar(refused); ok {
|
||||
t.Errorf("syncScalar(%#v) accepted a non-scalar value", refused)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,7 @@ import (
|
||||
const (
|
||||
maxSyncIdentifier = 128
|
||||
maxSyncSessions = 1000
|
||||
maxSyncConnections = 1000
|
||||
)
|
||||
|
||||
type peer struct {
|
||||
@@ -73,10 +74,15 @@ func NewHub() *Hub {
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) add(p *peer) {
|
||||
// add registers a peer, or reports false when the hub already holds maxSyncConnections peers.
|
||||
func (h *Hub) add(p *peer) bool {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if len(h.peers) >= maxSyncConnections {
|
||||
return false
|
||||
}
|
||||
h.peers[p] = struct{}{}
|
||||
h.mu.Unlock()
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *Hub) remove(p *peer) string {
|
||||
@@ -300,7 +306,10 @@ func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrig
|
||||
userAgent: firstNonEmpty(r.Header.Get("User-Agent"), "Unknown"),
|
||||
ipAddress: firstNonEmpty(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0], r.RemoteAddr, "Unknown"),
|
||||
}
|
||||
h.add(p)
|
||||
if !h.add(p) {
|
||||
_ = conn.Close(websocket.StatusTryAgainLater, "too many sync connections")
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
sessionID := h.remove(p)
|
||||
_ = conn.Close(websocket.StatusNormalClosure, "")
|
||||
@@ -453,6 +462,9 @@ func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) {
|
||||
if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 {
|
||||
h.capturedAtMs[sessionID] = captured
|
||||
}
|
||||
trimSessionMap(h.playAt)
|
||||
trimSessionMap(h.playAtLocalMs)
|
||||
trimSessionMap(h.capturedAtMs)
|
||||
if toClientID == "" {
|
||||
h.states[sessionID] = cloneMap(state)
|
||||
if len(h.states) > maxSyncSessions {
|
||||
@@ -571,6 +583,18 @@ func cloneMap(value map[string]any) map[string]any {
|
||||
return result
|
||||
}
|
||||
|
||||
// trimSessionMap keeps a per-session map within maxSyncSessions by dropping entries, the same
|
||||
// bound the states map uses. Session IDs come from clients, so without it each map would grow
|
||||
// for every ID ever seen.
|
||||
func trimSessionMap[V any](values map[string]V) {
|
||||
for len(values) > maxSyncSessions {
|
||||
for key := range values {
|
||||
delete(values, key)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package syncsocket
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestSessionTimingMapsStayBounded checks that fresh client-chosen session IDs cannot grow the
|
||||
// per-session timing maps past maxSyncSessions.
|
||||
func TestSessionTimingMapsStayBounded(t *testing.T) {
|
||||
hub := NewHub()
|
||||
p := &peer{clientID: "client-1"}
|
||||
for i := 0; i < maxSyncSessions+100; i++ {
|
||||
hub.handleSyncUpdate(p, map[string]any{
|
||||
"clientId": "client-1",
|
||||
"sessionId": fmt.Sprintf("session-%d", i),
|
||||
"paused": false,
|
||||
"playAt": "2026-10-19T10:00:00Z",
|
||||
"playAtLocalMs": float64(1),
|
||||
"capturedAtLocalMs": float64(1),
|
||||
})
|
||||
}
|
||||
if n := len(hub.playAt); n > maxSyncSessions {
|
||||
t.Errorf("playAt holds %d sessions, want at most %d", n, maxSyncSessions)
|
||||
}
|
||||
if n := len(hub.playAtLocalMs); n > maxSyncSessions {
|
||||
t.Errorf("playAtLocalMs holds %d sessions, want at most %d", n, maxSyncSessions)
|
||||
}
|
||||
if n := len(hub.capturedAtMs); n > maxSyncSessions {
|
||||
t.Errorf("capturedAtMs holds %d sessions, want at most %d", n, maxSyncSessions)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHubRefusesPeersBeyondTheConnectionCap checks that the hub stops registering connections
|
||||
// once it holds maxSyncConnections peers.
|
||||
func TestHubRefusesPeersBeyondTheConnectionCap(t *testing.T) {
|
||||
hub := NewHub()
|
||||
for i := 0; i < maxSyncConnections; i++ {
|
||||
if !hub.add(&peer{}) {
|
||||
t.Fatalf("add refused peer %d, below the cap", i)
|
||||
}
|
||||
}
|
||||
if hub.add(&peer{}) {
|
||||
t.Fatal("add accepted a peer beyond maxSyncConnections")
|
||||
}
|
||||
}
|
||||
Generated
-8
@@ -742,10 +742,6 @@
|
||||
"resolved": "packages/design-tokens",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@gabriel20xx/legacy-assets": {
|
||||
"resolved": "packages/legacy-assets",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@gabriel20xx/node-backend": {
|
||||
"resolved": "packages/node-backend",
|
||||
"link": true
|
||||
@@ -3109,10 +3105,6 @@
|
||||
"version": "0.1.1",
|
||||
"license": "MIT"
|
||||
},
|
||||
"packages/legacy-assets": {
|
||||
"name": "@gabriel20xx/legacy-assets",
|
||||
"version": "3.0.0"
|
||||
},
|
||||
"packages/node-backend": {
|
||||
"name": "@gabriel20xx/node-backend",
|
||||
"version": "0.1.1",
|
||||
|
||||
@@ -50,7 +50,6 @@
|
||||
"media:audit:layout": "node scripts/media/audit-inline-layout.mjs",
|
||||
"media:audit:layout:strict": "node scripts/media/audit-inline-layout.mjs --strict",
|
||||
"media:clean:test-artifacts": "node scripts/media/clean-test-artifacts.mjs",
|
||||
"media:enforce:css-design-system": "node scripts/media/enforce-design-system-css.mjs",
|
||||
"media:enforce:js-mapping": "node scripts/media/enforce-js-mapping.mjs",
|
||||
"media:enforce:no-skipped-tests": "node scripts/media/enforce-no-skipped-tests.mjs",
|
||||
"media:lint:all": "node scripts/media/lint-all.mjs",
|
||||
|
||||
+5
-1
@@ -715,9 +715,13 @@ public final class AuthClient {
|
||||
if (candidate.startsWith(prefix)) {
|
||||
String value = candidate.substring(prefix.length());
|
||||
try {
|
||||
return URLDecoder.decode(value, StandardCharsets.UTF_8.name());
|
||||
// URLDecoder would turn a literal "+" into a space; escape it first so it survives, as in Node.
|
||||
return URLDecoder.decode(value.replace("+", "%2B"), StandardCharsets.UTF_8.name());
|
||||
} catch (UnsupportedEncodingException ex) {
|
||||
return value;
|
||||
} catch (IllegalArgumentException ex) {
|
||||
// A malformed escape such as a bare "%" is not a usable token, so treat the cookie as absent.
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+28
@@ -218,6 +218,34 @@ class AuthClientTest {
|
||||
assertEquals("right", token);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractTokenKeepsALiteralPlusSignInTheCookieValue() {
|
||||
AuthClient client = new AuthClient("https://auth.example.com");
|
||||
|
||||
String token = client.extractToken(name -> null, "auth_session=ab+cd%2Bef");
|
||||
|
||||
assertEquals("ab+cd+ef", token);
|
||||
}
|
||||
|
||||
@Test
|
||||
void extractTokenTreatsAMalformedCookieEscapeAsNoToken() {
|
||||
AuthClient client = new AuthClient("https://auth.example.com");
|
||||
|
||||
String token = client.extractToken(name -> null, "auth_session=bad%zz; other=1");
|
||||
|
||||
assertEquals("", token);
|
||||
}
|
||||
|
||||
@Test
|
||||
void middlewareFailsClosedOnAMalformedCookieInsteadOfThrowing() throws Exception {
|
||||
AuthClient client = new AuthClient("https://auth.example.com");
|
||||
|
||||
String result = client.middleware(name -> null, "auth_session=100%",
|
||||
user -> "authenticated", () -> "unauthorized");
|
||||
|
||||
assertEquals("unauthorized", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void middlewareFailsClosedAndDoesNotInvokeTheHandlerOnAnInvalidSession() throws Exception {
|
||||
server = fakeAuthGuard(401, "{\"valid\":false}");
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"extends": ["stylelint-config-standard"],
|
||||
"ignoreFiles": ["public/css/index.css", "**/*.min.css"],
|
||||
"rules": {
|
||||
"at-rule-no-unknown": [true, { "ignoreAtRules": ["layer", "apply", "config"] }],
|
||||
"selector-class-pattern": null,
|
||||
"keyframes-name-pattern": null,
|
||||
"custom-property-pattern": null,
|
||||
"no-descending-specificity": null,
|
||||
"import-notation": null,
|
||||
"comment-empty-line-before": null,
|
||||
"declaration-property-value-no-unknown": null,
|
||||
"value-keyword-case": ["lower", { "camelCaseSvgKeywords": true }]
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
# @gabriel20xx/legacy-assets
|
||||
|
||||
This package now contains exactly one file: `public/css/index.css`, a static (pre-Tailwind-v4)
|
||||
theme stylesheet. Its only remaining consumer is `Original/MediaDesktop`'s Electron renderer,
|
||||
which still uses the old `--color-*` utility-class theme rather than the current `--sc-*`
|
||||
design-token system in `packages/design-tokens`. It's a `file:` dependency there
|
||||
(`scripts/copy-assets.mjs` copies `index.css` into `MediaDesktop/public/` at build time) - do not
|
||||
delete this package without first migrating MediaDesktop off the old stylesheet.
|
||||
|
||||
Everything else that used to live here (the pre-SvelteKit `public/js/*` auth/layout/media
|
||||
utilities, an orphaned `MediaDesktop/assets/icon.png` copy, and the broken monorepo-era
|
||||
`build:theme` script) was removed: nothing else in the workspace referenced any of it.
|
||||
|
||||
Originally `MediaCollection/MediaShared`, moved here to centralize shared components. Both the
|
||||
`MediaCollection` and `MediaShared` umbrella names are retired - everything here is just part of
|
||||
`shared` now, workspace-wide.
|
||||
@@ -1,13 +0,0 @@
|
||||
{
|
||||
"name": "@gabriel20xx/legacy-assets",
|
||||
"version": "3.0.0",
|
||||
"private": true,
|
||||
"description": "Legacy pre-SvelteKit theme CSS, kept only for MediaDesktop's Electron renderer (file: dependency)",
|
||||
"scripts": {
|
||||
"lint:css": "stylelint \"public/**/*.css\""
|
||||
},
|
||||
"exports": {
|
||||
"./index.css": "./public/css/index.css"
|
||||
},
|
||||
"files": ["public/**"]
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -211,9 +211,8 @@ export class AuthClient {
|
||||
*/
|
||||
middleware() {
|
||||
return async (req, res, next) => {
|
||||
const token = this.tokenFromRequest(req);
|
||||
try {
|
||||
req.authUser = await this.validate(token);
|
||||
req.authUser = await this.validate(this.tokenFromRequest(req));
|
||||
next();
|
||||
} catch {
|
||||
// Fail closed on both an invalid session and a transport/decoding
|
||||
@@ -236,7 +235,14 @@ export class AuthClient {
|
||||
.split(';')
|
||||
.map(part => part.trim())
|
||||
.find(part => part.startsWith(`${this.cookieName}=`));
|
||||
if (match) return decodeURIComponent(match.slice(this.cookieName.length + 1));
|
||||
if (match) {
|
||||
// A malformed escape such as a bare "%" is not a usable token, so treat the cookie as absent.
|
||||
try {
|
||||
return decodeURIComponent(match.slice(this.cookieName.length + 1));
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
@@ -125,6 +125,29 @@ test('tokenFromRequest falls back to the auth_session cookie', () => {
|
||||
assert.equal(client.tokenFromRequest(req), 'cookie-token');
|
||||
});
|
||||
|
||||
test('tokenFromRequest treats a malformed cookie escape as no token', () => {
|
||||
const client = new AuthClient('https://auth.example.com');
|
||||
const req = { headers: { cookie: 'auth_session=bad%zz; other=1' } };
|
||||
assert.equal(client.tokenFromRequest(req), '');
|
||||
});
|
||||
|
||||
test('middleware answers 401 instead of rejecting on a malformed cookie', async () => {
|
||||
const client = new AuthClient('https://auth.example.com', {
|
||||
fetchImpl: fakeFetch([{ status: 401, body: { valid: false } }]),
|
||||
});
|
||||
let statusCode = null;
|
||||
const res = {
|
||||
status(code) {
|
||||
statusCode = code;
|
||||
return { json: () => {} };
|
||||
},
|
||||
};
|
||||
await client.middleware()({ headers: { cookie: 'auth_session=100%' } }, res, () => {
|
||||
throw new Error('next should not be called');
|
||||
});
|
||||
assert.equal(statusCode, 401);
|
||||
});
|
||||
|
||||
test('middleware attaches authUser on success and 401s on failure', async () => {
|
||||
const okClient = new AuthClient('https://auth.example.com', {
|
||||
fetchImpl: fakeFetch([{ status: 200, body: { valid: true, user_id: 1, username: 'a', role: 'user' } }]),
|
||||
|
||||
@@ -94,6 +94,7 @@ ERR_FEATURE_REQUIRES_AUTHGUARD = "This feature requires AUTHGUARD_URL to be conf
|
||||
# rather than a generic "internal error" indistinguishable from any other bug.
|
||||
ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please try again shortly."
|
||||
ERR_SECRET_NOT_SET = "SECRET environment variable is not set."
|
||||
ERR_ADMIN_REQUIRED = "Administrator access required."
|
||||
|
||||
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
|
||||
# authentication is disabled, either because AUTHGUARD_URL is disabled or
|
||||
@@ -338,6 +339,23 @@ def build_auth_router(
|
||||
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
|
||||
return token
|
||||
|
||||
async def require_admin(
|
||||
request: Request,
|
||||
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
|
||||
) -> PublicUser:
|
||||
"""FastAPI dependency gating a route behind an administrator session
|
||||
(the Python counterpart of Go's RequireAdmin). Unlike require_session it
|
||||
never falls back to _LOCAL_PROFILE, so a route that changes the
|
||||
login-required flag cannot be called anonymously, even while login is
|
||||
already disabled."""
|
||||
if not _enabled(client):
|
||||
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
|
||||
assert client is not None
|
||||
profile, _ = await _current_profile_or_401(request, client)
|
||||
if not can_manage_users(profile.role):
|
||||
raise HTTPException(status_code=403, detail=ERR_ADMIN_REQUIRED)
|
||||
return profile
|
||||
|
||||
# --- status / me -------------------------------------------------------
|
||||
|
||||
@router.get("/me")
|
||||
@@ -561,6 +579,7 @@ def build_auth_router(
|
||||
async def update_access_settings(
|
||||
req: UpdateAccessRequest,
|
||||
store: ProxyStore = Depends(get_store), # noqa: B008
|
||||
_admin: PublicUser = Depends(require_admin), # noqa: B008
|
||||
) -> dict[str, bool]:
|
||||
nonlocal login_required_override
|
||||
await store.set_login_required(req.loginRequired)
|
||||
|
||||
@@ -4,7 +4,13 @@ from fastapi import FastAPI, Request
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from shared_backend import authproxy as ap
|
||||
from shared_backend.authclient import APIError, AuthClient, PublicUser, SessionResult
|
||||
from shared_backend.authclient import (
|
||||
DEFAULT_COOKIE_NAME,
|
||||
APIError,
|
||||
AuthClient,
|
||||
PublicUser,
|
||||
SessionResult,
|
||||
)
|
||||
|
||||
|
||||
class _FakeStore(ap.ProxyStore):
|
||||
@@ -113,14 +119,32 @@ class AuthDisabledModeTests(unittest.TestCase):
|
||||
|
||||
|
||||
class AccessSettingsTests(unittest.TestCase):
|
||||
def test_get_and_put_round_trip_through_the_store(self) -> None:
|
||||
def test_get_is_public_and_put_requires_an_admin_session(self) -> None:
|
||||
store = _FakeStore(login_required=True)
|
||||
client = TestClient(_build_app(store))
|
||||
client = TestClient(_build_app(store, _RoleClient()))
|
||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||
|
||||
response = client.put("/api/auth/access", json={"loginRequired": False})
|
||||
self.assertEqual(response.status_code, 401)
|
||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||
|
||||
client.cookies.set(DEFAULT_COOKIE_NAME, "user-token")
|
||||
response = client.put("/api/auth/access", json={"loginRequired": False})
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||
|
||||
client.cookies.set(DEFAULT_COOKIE_NAME, "admin-token")
|
||||
response = client.put("/api/auth/access", json={"loginRequired": False})
|
||||
self.assertEqual(response.json(), {"loginRequired": False})
|
||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": False})
|
||||
|
||||
def test_anonymous_put_is_refused_when_authguard_is_not_configured(self) -> None:
|
||||
store = _FakeStore(login_required=True)
|
||||
client = TestClient(_build_app(store))
|
||||
response = client.put("/api/auth/access", json={"loginRequired": False})
|
||||
self.assertEqual(response.status_code, 401)
|
||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": True})
|
||||
|
||||
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
|
||||
store = _FakeStore(login_required=True)
|
||||
client = TestClient(
|
||||
@@ -180,6 +204,16 @@ class _FakeClient(AuthClient):
|
||||
return ["auth_session=; Path=/; Max-Age=0"]
|
||||
|
||||
|
||||
class _RoleClient(_FakeClient):
|
||||
"""Resolves two fixed session tokens to an administrator and an ordinary user."""
|
||||
|
||||
async def me(self, token: str) -> PublicUser:
|
||||
roles = {"admin-token": "superadmin", "user-token": "user"}
|
||||
if token not in roles:
|
||||
raise APIError(401, "unauthenticated")
|
||||
return PublicUser(id=1, username="a", email="a@b.com", role=roles[token])
|
||||
|
||||
|
||||
class EnabledModeSetupAndLoginTests(unittest.TestCase):
|
||||
"""Exercises the real (client is not None) path, including the
|
||||
setup-claim flag's interaction with the store."""
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
<!--
|
||||
Internal to MediaPlayer. Not exported from the package barrel; do not re-export.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { Maximize2, Minimize2, Pause, Play, Settings, Volume2, VolumeX } from '@lucide/svelte'
|
||||
import { onMount } from 'svelte'
|
||||
|
||||
@@ -1,286 +0,0 @@
|
||||
<script lang="ts">
|
||||
import type {
|
||||
KnownRole,
|
||||
ManagedUser,
|
||||
UserCreateInput,
|
||||
UserCreateRequest,
|
||||
UserDeleteRequest,
|
||||
UserId,
|
||||
UserListRequest,
|
||||
UserRole,
|
||||
UserUpdateInput,
|
||||
UserUpdateRequest
|
||||
} from '../types';
|
||||
import Button from './Button.svelte';
|
||||
import Pagination from './Pagination.svelte';
|
||||
|
||||
let {
|
||||
currentRole = 'user',
|
||||
currentUserId,
|
||||
onCreate,
|
||||
onDelete,
|
||||
onList,
|
||||
onUpdate,
|
||||
roles
|
||||
}: {
|
||||
currentRole?: UserRole;
|
||||
currentUserId?: UserId;
|
||||
onCreate?: UserCreateRequest;
|
||||
onDelete?: UserDeleteRequest;
|
||||
onList?: UserListRequest;
|
||||
onUpdate?: UserUpdateRequest;
|
||||
/**
|
||||
* The custom roles an account can be placed in (AuthGuard's role-based
|
||||
* project access: a role decides which projects its members may log into).
|
||||
* Only AuthGuard's own admin UI passes this - every other project's
|
||||
* UserManagement usage omits it, and the whole role section of this
|
||||
* component simply doesn't render.
|
||||
*/
|
||||
roles?: KnownRole[];
|
||||
} = $props();
|
||||
|
||||
let users = $state<ManagedUser[]>([]);
|
||||
let loading = $state(false);
|
||||
let saving = $state(false);
|
||||
let error = $state('');
|
||||
let notice = $state('');
|
||||
let loaded = $state(false);
|
||||
let newUser = $state<UserCreateInput>({ username: '', email: '', password: '', role: 'user' });
|
||||
let editingId = $state<UserId | null>(null);
|
||||
let editUser = $state<UserUpdateInput>({});
|
||||
let page = $state(1);
|
||||
let pageSize = $state(24);
|
||||
|
||||
const canManage = $derived(currentRole === 'admin' || currentRole === 'superadmin');
|
||||
const canAssignAdmin = $derived(currentRole === 'superadmin');
|
||||
const pageCount = $derived(Math.max(1, Math.ceil(users.length / pageSize)));
|
||||
const currentPage = $derived(Math.min(page, pageCount));
|
||||
const pagedUsers = $derived(
|
||||
users.slice((currentPage - 1) * pageSize, (currentPage - 1) * pageSize + pageSize)
|
||||
);
|
||||
|
||||
function roleForForm(role: UserRole | undefined): UserRole {
|
||||
return canAssignAdmin && role ? role : 'user';
|
||||
}
|
||||
|
||||
function formatLastLogin(value: string | null | undefined): string {
|
||||
if (!value) return 'Never';
|
||||
const parsed = new Date(value);
|
||||
return Number.isNaN(parsed.getTime()) ? 'Never' : parsed.toLocaleString();
|
||||
}
|
||||
|
||||
async function loadUsers(): Promise<void> {
|
||||
if (!onList || !canManage) return;
|
||||
loading = true;
|
||||
error = '';
|
||||
try {
|
||||
users = await onList();
|
||||
loaded = true;
|
||||
} catch (caught) {
|
||||
error = caught instanceof Error ? caught.message : 'Unable to load users.';
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
if (canManage && onList && !loaded) void loadUsers();
|
||||
});
|
||||
|
||||
async function createUser(event: SubmitEvent): Promise<void> {
|
||||
event.preventDefault();
|
||||
if (!onCreate) return;
|
||||
if (!newUser.username.trim() && !newUser.email.trim()) {
|
||||
error = 'A username or email is required.';
|
||||
return;
|
||||
}
|
||||
saving = true;
|
||||
error = '';
|
||||
notice = '';
|
||||
try {
|
||||
await onCreate({ ...newUser, role: roleForForm(newUser.role) });
|
||||
newUser = { username: '', email: '', password: '', role: 'user' };
|
||||
notice = 'User created.';
|
||||
await loadUsers();
|
||||
} catch (caught) {
|
||||
error = caught instanceof Error ? caught.message : 'Unable to create user.';
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
function startEditing(user: ManagedUser): void {
|
||||
editingId = user.id;
|
||||
editUser = { username: user.username, email: user.email, role: roleForForm(user.role) };
|
||||
if (roles && roles.length > 0) editUser.roleIds = [...(user.roleIds ?? [])];
|
||||
error = '';
|
||||
notice = '';
|
||||
}
|
||||
|
||||
function toggleEditRole(id: number, checked: boolean): void {
|
||||
const current = editUser.roleIds ?? [];
|
||||
editUser.roleIds = checked ? [...current, id] : current.filter((roleId) => roleId !== id);
|
||||
}
|
||||
|
||||
function toggleNewRole(id: number, checked: boolean): void {
|
||||
const current = newUser.roleIds ?? [];
|
||||
newUser.roleIds = checked ? [...current, id] : current.filter((roleId) => roleId !== id);
|
||||
}
|
||||
|
||||
// Names the roles an account is in, in the order the roles are listed. An account in none of
|
||||
// them keeps every project.
|
||||
function roleSummary(user: ManagedUser): string {
|
||||
const names = (roles ?? []).filter((role) => (user.roleIds ?? []).includes(role.id)).map((role) => role.name);
|
||||
return names.length > 0 ? names.join(', ') : 'All projects';
|
||||
}
|
||||
|
||||
function stopEditing(): void {
|
||||
editingId = null;
|
||||
editUser = {};
|
||||
}
|
||||
|
||||
async function updateUser(event: SubmitEvent): Promise<void> {
|
||||
event.preventDefault();
|
||||
if (!onUpdate || editingId === null) return;
|
||||
saving = true;
|
||||
error = '';
|
||||
notice = '';
|
||||
try {
|
||||
const input = { ...editUser, role: roleForForm(editUser.role) };
|
||||
if (!input.password) delete input.password;
|
||||
await onUpdate(editingId, input);
|
||||
stopEditing();
|
||||
notice = 'User updated.';
|
||||
await loadUsers();
|
||||
} catch (caught) {
|
||||
error = caught instanceof Error ? caught.message : 'Unable to update user.';
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteUser(user: ManagedUser): Promise<void> {
|
||||
if (!onDelete || String(user.id) === String(currentUserId)) return;
|
||||
if (!window.confirm(`Delete user ${user.username}?`)) return;
|
||||
saving = true;
|
||||
error = '';
|
||||
notice = '';
|
||||
try {
|
||||
await onDelete(user.id);
|
||||
notice = 'User deleted.';
|
||||
await loadUsers();
|
||||
} catch (caught) {
|
||||
error = caught instanceof Error ? caught.message : 'Unable to delete user.';
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if canManage && onList && onCreate && onUpdate && onDelete}
|
||||
<section class="sc-user-management" aria-labelledby="sc-user-management-title">
|
||||
<div class="sc-user-management-header">
|
||||
<div>
|
||||
<h3 id="sc-user-management-title">User management</h3>
|
||||
<p class="sc-muted">Add, edit, or remove accounts for this project.</p>
|
||||
</div>
|
||||
<Button disabled={loading || saving} size="sm" type="button" variant="secondary" onclick={() => void loadUsers()}>
|
||||
Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<form class="sc-user-form" onsubmit={createUser}>
|
||||
<strong>Add user</strong>
|
||||
<div class="sc-user-grid">
|
||||
<input aria-label="New username" class="sc-input" placeholder="Username (optional if email is set)" type="text" bind:value={newUser.username} />
|
||||
<input aria-label="New email" class="sc-input" placeholder="Email (optional if username is set)" type="email" bind:value={newUser.email} />
|
||||
<input aria-label="New password" class="sc-input" minlength="8" placeholder="Password (optional)" type="password" bind:value={newUser.password} />
|
||||
<select aria-label="New role" class="sc-input" disabled={!canAssignAdmin} bind:value={newUser.role}>
|
||||
<option value="user">User</option>
|
||||
{#if canAssignAdmin}<option value="admin">Admin</option>{/if}
|
||||
</select>
|
||||
</div>
|
||||
{#if roles && roles.length > 0}
|
||||
<fieldset class="sc-user-roles">
|
||||
<legend>Roles (none checked = all projects)</legend>
|
||||
{#each roles as role (role.id)}
|
||||
<label class="sc-user-role-option">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={(newUser.roleIds ?? []).includes(role.id)}
|
||||
onchange={(event) => toggleNewRole(role.id, event.currentTarget.checked)}
|
||||
/>
|
||||
{role.name}
|
||||
</label>
|
||||
{/each}
|
||||
</fieldset>
|
||||
{/if}
|
||||
<div class="sc-form-actions"><Button disabled={saving} type="submit">Add user</Button></div>
|
||||
</form>
|
||||
|
||||
{#if error}<p aria-live="polite" class="sc-error">{error}</p>{/if}
|
||||
{#if notice}<p aria-live="polite" class="sc-success">{notice}</p>{/if}
|
||||
|
||||
{#if loading && users.length === 0}
|
||||
<p class="sc-muted">Loading users...</p>
|
||||
{:else if users.length === 0}
|
||||
<p class="sc-muted">No users found.</p>
|
||||
{:else}
|
||||
<div class="sc-user-list">
|
||||
{#each pagedUsers as user (user.id)}
|
||||
{#if String(editingId) === String(user.id)}
|
||||
<form class="sc-user-row sc-user-edit-row" onsubmit={updateUser}>
|
||||
<input aria-label="Username" class="sc-input" required type="text" bind:value={editUser.username} />
|
||||
<input aria-label="Email" class="sc-input" required type="email" bind:value={editUser.email} />
|
||||
<input aria-label="New password" class="sc-input" minlength="8" placeholder="Keep password" type="password" bind:value={editUser.password} />
|
||||
<select aria-label="Role" class="sc-input" disabled={!canAssignAdmin || user.role === 'superadmin'} bind:value={editUser.role}>
|
||||
<option value="user">User</option>
|
||||
{#if canAssignAdmin}<option value="admin">Admin</option>{/if}
|
||||
{#if user.role === 'superadmin'}<option value="superadmin">Superadmin</option>{/if}
|
||||
</select>
|
||||
{#if roles && roles.length > 0}
|
||||
<fieldset class="sc-user-roles">
|
||||
<legend>Roles (none checked = all projects)</legend>
|
||||
{#each roles as role (role.id)}
|
||||
<label class="sc-user-role-option">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={(editUser.roleIds ?? []).includes(role.id)}
|
||||
onchange={(event) => toggleEditRole(role.id, event.currentTarget.checked)}
|
||||
/>
|
||||
{role.name}
|
||||
</label>
|
||||
{/each}
|
||||
</fieldset>
|
||||
{/if}
|
||||
<div class="sc-user-actions"><Button disabled={saving} size="sm" type="submit">Save</Button><Button disabled={saving} size="sm" type="button" variant="secondary" onclick={stopEditing}>Cancel</Button></div>
|
||||
</form>
|
||||
{:else}
|
||||
<div class="sc-user-row">
|
||||
<div><strong>{user.username}</strong><span>{user.email}</span></div>
|
||||
<span class="sc-user-role">{user.role}</span>
|
||||
<span class="sc-muted sc-user-last-login" title="Last login">{formatLastLogin(user.lastLoginAt)}</span>
|
||||
{#if roles && roles.length > 0}
|
||||
<span class="sc-muted sc-user-roles-summary" title="Roles">{roleSummary(user)}</span>
|
||||
{/if}
|
||||
<div class="sc-user-actions">
|
||||
<Button disabled={saving} size="sm" type="button" variant="secondary" onclick={() => startEditing(user)}>Edit</Button>
|
||||
<Button disabled={saving || String(user.id) === String(currentUserId) || user.role === 'superadmin'} size="sm" type="button" variant="danger" onclick={() => void deleteUser(user)}>Remove</Button>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
<Pagination
|
||||
page={currentPage}
|
||||
{pageSize}
|
||||
pageLength={pagedUsers.length}
|
||||
totalLength={users.length}
|
||||
onPaging={(change) => {
|
||||
page = change.page;
|
||||
pageSize = change.pageSize;
|
||||
}}
|
||||
/>
|
||||
{/if}
|
||||
</section>
|
||||
{/if}
|
||||
@@ -9,7 +9,6 @@ export { default as EmptyState } from './components/EmptyState.svelte';
|
||||
export { default as Header } from './components/Header.svelte';
|
||||
export { default as Metric } from './components/Metric.svelte';
|
||||
export { default as MediaPlayer } from './components/MediaPlayer.svelte';
|
||||
export { default as MediaPlayerControls } from './components/MediaPlayerControls.svelte';
|
||||
export { default as NotificationStack } from './components/NotificationStack.svelte';
|
||||
export { default as Pagination } from './components/Pagination.svelte';
|
||||
export { default as ProfileDialog } from './components/ProfileDialog.svelte';
|
||||
@@ -19,7 +18,6 @@ export { default as SettingsDialog } from './components/SettingsDialog.svelte';
|
||||
export { default as StatusDialog } from './components/StatusDialog.svelte';
|
||||
export { default as StatusWidget } from './components/StatusWidget.svelte';
|
||||
export { default as TotpSettings } from './components/TotpSettings.svelte';
|
||||
export { default as UserManagement } from './components/UserManagement.svelte';
|
||||
export { notifications, notify } from './notifications.svelte';
|
||||
export {
|
||||
PRIMARY_COLOR_PALETTE,
|
||||
@@ -49,13 +47,9 @@ export type {
|
||||
StatusProbe,
|
||||
StatusSnapshot,
|
||||
UserCreateInput,
|
||||
UserCreateRequest,
|
||||
UserDeleteRequest,
|
||||
UserId,
|
||||
UserListRequest,
|
||||
UserRole,
|
||||
UserUpdateInput,
|
||||
UserUpdateRequest,
|
||||
TotpSetupRequest,
|
||||
TotpSetupResponse,
|
||||
TotpStatusRequest,
|
||||
|
||||
@@ -39,9 +39,10 @@ const paletteByName = Object.fromEntries(PRIMARY_COLOR_PALETTE.map((color) => [c
|
||||
string,
|
||||
PaletteColor
|
||||
>
|
||||
const primaryVars = ['--color-primary', '--color-accent', '--color-ring']
|
||||
const foregroundVars = ['--color-primary-fg', '--color-accent-fg']
|
||||
const primaryVars = ['--color-primary', '--color-accent', '--color-ring', '--sc-primary', '--sc-accent', '--sc-ring']
|
||||
const foregroundVars = ['--color-primary-fg', '--color-accent-fg', '--sc-primary-fg', '--sc-accent-fg']
|
||||
const activeUserAttribute = 'data-primary-color-user'
|
||||
const styleElementId = 'sc-primary-color'
|
||||
const activeProjects = new Set<string>()
|
||||
|
||||
function normalizeUserKey(userKey: string): string {
|
||||
@@ -67,19 +68,45 @@ function readStoredColor(projectKey: string): string {
|
||||
}
|
||||
}
|
||||
|
||||
// Moves a #rrggbb color a fraction of the way toward a channel value (0 = black, 255 = white).
|
||||
function mixHex(hex: string, towards: number, weight: number): string {
|
||||
const channels = [1, 3, 5].map((start) => parseInt(hex.slice(start, start + 2), 16))
|
||||
return `#${channels.map((c) => Math.round(c + (towards - c) * weight).toString(16).padStart(2, '0')).join('')}`
|
||||
}
|
||||
|
||||
// The color is written to a stylesheet rather than inline on <html>. Shared and app CSS re-declare these
|
||||
// tokens on every [data-theme] element (the AppShell root, for one), and that declaration hides the value
|
||||
// <html> would pass down, so the choice never reached the app's UI. Targeting [data-theme] elements with
|
||||
// !important makes it win everywhere, and the dark/light split is left to the selectors.
|
||||
function primaryDeclarations(color: PaletteColor, dark: boolean): string {
|
||||
const primary = dark ? color.dark : color.light
|
||||
// Hover is lighter on dark and darker on light, as in the shared theme. It is a hex value, not color-mix(),
|
||||
// because consumers such as the terminal read these tokens as plain colors.
|
||||
const hover = dark ? mixHex(primary, 255, 0.15) : mixHex(primary, 0, 0.15)
|
||||
const foreground = dark ? color.darkFg : '#ffffff'
|
||||
return [
|
||||
...primaryVars.map((name) => `${name}: ${primary} !important;`),
|
||||
`--sc-primary-hover: ${hover} !important;`,
|
||||
...foregroundVars.map((name) => `${name}: ${foreground} !important;`),
|
||||
].join(' ')
|
||||
}
|
||||
|
||||
export function applyPrimaryColor(_projectKey: string, colorName: string): void {
|
||||
if (typeof document === 'undefined') return
|
||||
const color = paletteByName[colorName]
|
||||
const root = document.documentElement.style
|
||||
let style = document.getElementById(styleElementId) as HTMLStyleElement | null
|
||||
if (!color) {
|
||||
for (const name of [...primaryVars, ...foregroundVars]) root.removeProperty(name)
|
||||
style?.remove()
|
||||
return
|
||||
}
|
||||
const dark = document.documentElement.getAttribute('data-theme') === 'dark'
|
||||
const primary = dark ? color.dark : color.light
|
||||
const foreground = dark ? color.darkFg : '#ffffff'
|
||||
for (const name of primaryVars) root.setProperty(name, primary)
|
||||
for (const name of foregroundVars) root.setProperty(name, foreground)
|
||||
if (!style) {
|
||||
style = document.createElement('style')
|
||||
style.id = styleElementId
|
||||
document.head.append(style)
|
||||
}
|
||||
style.textContent = `:root, [data-theme] { ${primaryDeclarations(color, false)} }
|
||||
[data-theme='dark'] { ${primaryDeclarations(color, true)} }
|
||||
`
|
||||
}
|
||||
|
||||
export function setPrimaryColor(projectKey: string, colorName: string): void {
|
||||
@@ -105,11 +132,8 @@ export function initPrimaryColor(projectKey: string, userKey = ''): () => void {
|
||||
if (typeof document === 'undefined') return () => undefined
|
||||
if (userKey) setPrimaryColorUser(userKey)
|
||||
activeProjects.add(projectKey.trim().toLowerCase() || 'application')
|
||||
const stored = readStoredColor(projectKey)
|
||||
applyPrimaryColor(projectKey, stored)
|
||||
const observer = new MutationObserver(() => applyPrimaryColor(projectKey, readStoredColor(projectKey)))
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] })
|
||||
return () => observer.disconnect()
|
||||
applyPrimaryColor(projectKey, readStoredColor(projectKey))
|
||||
return () => undefined
|
||||
}
|
||||
|
||||
export function storedPrimaryColor(projectKey: string): string {
|
||||
|
||||
@@ -746,148 +746,6 @@ html[data-wide-layout='true'] .sc-header {
|
||||
color: var(--sc-success);
|
||||
}
|
||||
|
||||
.sc-user-management {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
margin-top: 1.5rem;
|
||||
padding-top: 1.5rem;
|
||||
border-top: 1px solid var(--sc-border);
|
||||
}
|
||||
|
||||
.sc-user-management-header,
|
||||
.sc-user-row,
|
||||
.sc-user-edit-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.sc-user-management-header {
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.sc-user-management-header h3 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.sc-user-management-header p {
|
||||
margin: 0.25rem 0 0;
|
||||
}
|
||||
|
||||
.sc-user-form,
|
||||
.sc-user-list {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.sc-user-form {
|
||||
padding: 0.9rem;
|
||||
border: 1px solid var(--sc-border);
|
||||
border-radius: 0.6rem;
|
||||
background: var(--sc-surface-raised);
|
||||
}
|
||||
|
||||
.sc-user-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.sc-user-row {
|
||||
min-width: 0;
|
||||
justify-content: space-between;
|
||||
padding: 0.7rem 0;
|
||||
border-bottom: 1px solid var(--sc-border);
|
||||
}
|
||||
|
||||
.sc-user-row > div:first-child {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.sc-user-row > div:first-child span {
|
||||
overflow: hidden;
|
||||
color: var(--sc-muted-fg);
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sc-user-role {
|
||||
color: var(--sc-muted-fg);
|
||||
font-size: 0.8rem;
|
||||
text-transform: capitalize;
|
||||
}
|
||||
|
||||
.sc-user-last-login {
|
||||
flex-shrink: 0;
|
||||
font-size: 0.8rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sc-user-actions {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.sc-user-roles-summary {
|
||||
max-width: 12rem;
|
||||
overflow: hidden;
|
||||
font-size: 0.8rem;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sc-user-roles {
|
||||
display: flex;
|
||||
flex: 1 1 100%;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem 1rem;
|
||||
margin: 0;
|
||||
padding: 0.5rem 0.7rem;
|
||||
border: 1px solid var(--sc-border);
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.sc-user-roles legend {
|
||||
flex-basis: 100%;
|
||||
margin-bottom: 0.3rem;
|
||||
color: var(--sc-muted-fg);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.sc-user-role-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.sc-user-edit-row {
|
||||
align-items: stretch;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.sc-user-edit-row .sc-input {
|
||||
flex: 1 1 10rem;
|
||||
min-width: 8rem;
|
||||
}
|
||||
|
||||
@media (max-width: 620px) {
|
||||
.sc-user-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.sc-user-row {
|
||||
align-items: flex-start;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.sc-user-actions {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.sc-pagination {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
@@ -73,7 +73,7 @@ export interface KnownProject {
|
||||
label: string;
|
||||
}
|
||||
|
||||
/** One custom role an administrator may assign to a user - see UserManagement's `roles` prop. */
|
||||
/** One custom role an administrator may assign to a user. */
|
||||
export interface KnownRole {
|
||||
id: number;
|
||||
name: string;
|
||||
@@ -107,24 +107,11 @@ export interface UserUpdateInput {
|
||||
/**
|
||||
* Replaces the account's full set of custom roles when present (an empty
|
||||
* array removes it from every role); omitted (undefined) leaves them
|
||||
* untouched. Only ever set when UserManagement was given a `roles` prop.
|
||||
* untouched.
|
||||
*/
|
||||
roleIds?: number[];
|
||||
}
|
||||
|
||||
export type UserListRequest = () => ManagedUser[] | Promise<ManagedUser[]>;
|
||||
|
||||
export type UserCreateRequest = (
|
||||
input: UserCreateInput,
|
||||
) => void | Promise<void | ManagedUser>;
|
||||
|
||||
export type UserUpdateRequest = (
|
||||
id: UserId,
|
||||
input: UserUpdateInput,
|
||||
) => void | Promise<void | ManagedUser>;
|
||||
|
||||
export type UserDeleteRequest = (id: UserId) => void | Promise<void>;
|
||||
|
||||
export interface AboutLink {
|
||||
label: string;
|
||||
href: string;
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Enforce design-system CSS constraints for shared theme files.
|
||||
*
|
||||
* Rules enforced:
|
||||
* - Theme CSS must not contain project/service-coupled selector tokens.
|
||||
* - Theme CSS must not contain route-coupled panel IDs in selectors.
|
||||
*
|
||||
* TODO(shared extraction): the original monorepo version of this script also asserted that
|
||||
* MediaShared/public/css/index.css and MediaDesktop/public/index.css stayed byte-for-byte synced.
|
||||
* That check is no longer possible from inside this repo: MediaDesktop is now a fully separate
|
||||
* repo (Original/MediaDesktop) and isn't checked out alongside this one, so there is nothing here
|
||||
* to diff it against. The desktop-vs-shared theme sync check has been dropped rather than pointed
|
||||
* at a nonexistent path; if that guarantee still matters, it belongs in MediaDesktop's own CI
|
||||
* (comparing its vendored shared/ copy's theme file against its own), not here.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = path.resolve(__dirname, '..', '..');
|
||||
|
||||
// MediaShared/public/css/index.css became packages/legacy-assets/public/css/index.css once
|
||||
// media-backend/webui were folded directly into the shared repo (no more vendored copy).
|
||||
const sharedThemePath = path.join(
|
||||
repoRoot,
|
||||
'packages',
|
||||
'legacy-assets',
|
||||
'public',
|
||||
'css',
|
||||
'index.css'
|
||||
);
|
||||
|
||||
const bannedSelectorRules = [
|
||||
{
|
||||
name: 'project-coupled service token',
|
||||
regex: /\b(?:kiosk|viewer|moderator|generator|library|contentscanner|downloader|carriernode)-page\b/i,
|
||||
},
|
||||
{
|
||||
name: 'project-coupled state class token',
|
||||
regex:
|
||||
/\b(?:viewer|kiosk|moderator|generator|library|contentscanner|downloader|carriernode)-(?:home|page|stage|mode|active|panel)\b/i,
|
||||
},
|
||||
{
|
||||
name: 'project-prefixed keyframe name',
|
||||
regex:
|
||||
/@keyframes\s+nc-(?:viewer|kiosk|moderator|generator|library|contentscanner|downloader|carriernode)/i,
|
||||
},
|
||||
{
|
||||
name: 'project-coupled data attribute',
|
||||
regex:
|
||||
/\[data-(?:kiosk|viewer|moderator|generator|library|contentscanner|downloader|carriernode)[^\]]*\]/i,
|
||||
},
|
||||
{
|
||||
name: 'route-coupled panel selector',
|
||||
regex: /#panel-[a-z0-9_-]+/i,
|
||||
},
|
||||
];
|
||||
|
||||
function readUtf8(filePath) {
|
||||
return fs.readFileSync(filePath, 'utf8');
|
||||
}
|
||||
|
||||
function stripCssComments(text) {
|
||||
return text.replace(/\/\*[\s\S]*?\*\//g, '');
|
||||
}
|
||||
|
||||
function findViolations(filePath, content) {
|
||||
const cleaned = stripCssComments(content);
|
||||
const lines = cleaned.split(/\r?\n/);
|
||||
const violations = [];
|
||||
|
||||
for (let i = 0; i < lines.length; i += 1) {
|
||||
const line = lines[i];
|
||||
for (const rule of bannedSelectorRules) {
|
||||
if (rule.regex.test(line)) {
|
||||
violations.push({
|
||||
filePath,
|
||||
line: i + 1,
|
||||
rule: rule.name,
|
||||
snippet: line.trim(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return violations;
|
||||
}
|
||||
|
||||
function main() {
|
||||
if (!fs.existsSync(sharedThemePath)) {
|
||||
console.error('[enforce-design-system-css] Missing expected theme file:');
|
||||
console.error(` - ${path.relative(repoRoot, sharedThemePath)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const sharedTheme = readUtf8(sharedThemePath);
|
||||
|
||||
const allViolations = findViolations(sharedThemePath, sharedTheme);
|
||||
|
||||
if (allViolations.length > 0) {
|
||||
console.error('[enforce-design-system-css] Design-system CSS violations found:');
|
||||
for (const v of allViolations) {
|
||||
const rel = path.isAbsolute(v.filePath) ? path.relative(repoRoot, v.filePath) : v.filePath;
|
||||
console.error(` - ${rel}:${v.line} [${v.rule}] ${v.snippet}`);
|
||||
}
|
||||
console.error('[enforce-design-system-css] Fix violations before running lint/test.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(
|
||||
'[enforce-design-system-css] OK: shared theme is free of project-coupled selectors.'
|
||||
);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -727,148 +727,6 @@ html[data-wide-layout='true'] .sc-header {
|
||||
color: var(--sc-success);
|
||||
}
|
||||
|
||||
.sc-user-management {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
margin-top: 1.5rem;
|
||||
padding-top: 1.5rem;
|
||||
border-top: 1px solid var(--sc-border);
|
||||
}
|
||||
|
||||
.sc-user-management-header,
|
||||
.sc-user-row,
|
||||
.sc-user-edit-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.sc-user-management-header {
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.sc-user-management-header h3 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.sc-user-management-header p {
|
||||
margin: 0.25rem 0 0;
|
||||
}
|
||||
|
||||
.sc-user-form,
|
||||
.sc-user-list {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.sc-user-form {
|
||||
padding: 0.9rem;
|
||||
border: 1px solid var(--sc-border);
|
||||
border-radius: 0.6rem;
|
||||
background: var(--sc-surface-raised);
|
||||
}
|
||||
|
||||
.sc-user-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.sc-user-row {
|
||||
min-width: 0;
|
||||
justify-content: space-between;
|
||||
padding: 0.7rem 0;
|
||||
border-bottom: 1px solid var(--sc-border);
|
||||
}
|
||||
|
||||
.sc-user-row > div:first-child {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.sc-user-row > div:first-child span {
|
||||
overflow: hidden;
|
||||
color: var(--sc-muted-fg);
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sc-user-role {
|
||||
color: var(--sc-muted-fg);
|
||||
font-size: 0.8rem;
|
||||
text-transform: capitalize;
|
||||
}
|
||||
|
||||
.sc-user-last-login {
|
||||
flex-shrink: 0;
|
||||
font-size: 0.8rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sc-user-actions {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.sc-user-roles-summary {
|
||||
max-width: 12rem;
|
||||
overflow: hidden;
|
||||
font-size: 0.8rem;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sc-user-roles {
|
||||
display: flex;
|
||||
flex: 1 1 100%;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem 1rem;
|
||||
margin: 0;
|
||||
padding: 0.5rem 0.7rem;
|
||||
border: 1px solid var(--sc-border);
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.sc-user-roles legend {
|
||||
flex-basis: 100%;
|
||||
margin-bottom: 0.3rem;
|
||||
color: var(--sc-muted-fg);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.sc-user-role-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.sc-user-edit-row {
|
||||
align-items: stretch;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.sc-user-edit-row .sc-input {
|
||||
flex: 1 1 10rem;
|
||||
min-width: 8rem;
|
||||
}
|
||||
|
||||
@media (max-width: 620px) {
|
||||
.sc-user-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.sc-user-row {
|
||||
align-items: flex-start;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.sc-user-actions {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.sc-pagination {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
Reference in new issue
Block a user