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:
Gabriel20xxandClaude Haiku 5.5 committed 2026-10-19 07:48:07 +00:00
1 parent 7dd0d34383
commit a84a36349b
31 files changed
+653 -6055

No files matched your search

@@ -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
View File
@@ -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.
+57 -10
View File
@@ -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 {
+164
View File
@@ -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)
}
}
}
+29 -5
View File
@@ -31,8 +31,9 @@ import (
)
const (
maxSyncIdentifier = 128
maxSyncSessions = 1000
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")
}
}
-8
View File
@@ -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",
-1
View File
@@ -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",
@@ -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 "";
}
}
}
@@ -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 }]
}
}
-16
View File
@@ -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}
-6
View File
@@ -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 {
-142
View File
@@ -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;
+2 -15
View File
@@ -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();
-142
View File
@@ -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;