From 75c08beec676fa0f71243ce64e6f9356dcd05f4d Mon Sep 17 00:00:00 2001 From: Gabriel Date: Sun, 1 Nov 2026 21:50:47 +0100 Subject: [PATCH] refactor(backend): rename mediacore package to media --- .changeset/pagination-spacing.md | 5 + .github/workflows/tests.yml | 2 +- README.md | 6 +- backend/README.md | 2 +- backend/auth/account_routes.go | 35 ++ backend/auth/account_routes_test.go | 64 +++ .../auth/platform_users_integration_test.go | 4 +- backend/auth/proxy.go | 35 +- backend/authproxy/authproxy.go | 4 +- backend/carriernodeclient/settings_urls.go | 55 +++ backend/files/files.go | 109 +++++ .../paths_test.go => files/files_test.go} | 43 +- .../mediacore.go => media/media.go} | 442 +++--------------- .../mediacore_test.go => media/media_test.go} | 57 +-- backend/{mediacore => media}/migrate.go | 60 +-- backend/media/paths_test.go | 46 ++ .../{mediacore => media}/routes_db_test.go | 39 +- backend/media/routes_test.go | 41 ++ backend/settings/settings.go | 74 +++ backend/settings/settings_test.go | 24 + backend/syncsocket/routes.go | 87 ++++ backend/syncsocket/sync_gate_test.go | 50 ++ backend/syncsocket/sync_helpers_test.go | 18 + .../sync_routes_test.go} | 75 +-- backend/syncsocket/sync_scalar.go | 15 + backend/syncsocket/syncsocket.go | 16 +- packages/node-backend/README.md | 2 +- packages/web-ui/src/lib/styles.css | 28 +- scripts/media/audit-inline-layout.mjs | 4 +- scripts/media/clean-test-artifacts.mjs | 2 +- scripts/media/lint-all-json.mjs | 4 +- scripts/media/lint-all.mjs | 4 +- scripts/sync-consumers.ps1 | 13 +- shared-styles.css | 28 +- 34 files changed, 837 insertions(+), 656 deletions(-) create mode 100644 .changeset/pagination-spacing.md create mode 100644 backend/auth/account_routes.go create mode 100644 backend/auth/account_routes_test.go create mode 100644 backend/carriernodeclient/settings_urls.go create mode 100644 backend/files/files.go rename backend/{mediacore/paths_test.go => files/files_test.go} (59%) rename backend/{mediacore/mediacore.go => media/media.go} (68%) rename backend/{mediacore/mediacore_test.go => media/media_test.go} (68%) rename backend/{mediacore => media}/migrate.go (73%) create mode 100644 backend/media/paths_test.go rename backend/{mediacore => media}/routes_db_test.go (89%) create mode 100644 backend/media/routes_test.go create mode 100644 backend/settings/settings.go create mode 100644 backend/settings/settings_test.go create mode 100644 backend/syncsocket/routes.go create mode 100644 backend/syncsocket/sync_gate_test.go create mode 100644 backend/syncsocket/sync_helpers_test.go rename backend/{mediacore/routes_test.go => syncsocket/sync_routes_test.go} (66%) create mode 100644 backend/syncsocket/sync_scalar.go diff --git a/.changeset/pagination-spacing.md b/.changeset/pagination-spacing.md new file mode 100644 index 0000000..608ca8a --- /dev/null +++ b/.changeset/pagination-spacing.md @@ -0,0 +1,5 @@ +--- +"@gabriel20xx/web-ui": patch +--- + +`Pagination` no longer adds a 1rem top margin, so it sits evenly inside whichever container holds it. Its page-size select now shows its arrow at the same text size as the count, the controls line up with the select, and on phones the count sits on its own centred line above the page size and buttons. diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 4f49db1..09c1706 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -55,7 +55,7 @@ jobs: run: working-directory: backend # A throwaway PostgreSQL for the tests that need a real database (the auth store, the - # platform-user SQL, mediacore's routes and the migrate package). Without these two + # platform-user SQL, the media routes and the migrate package). Without these two # variables those tests skip themselves. services: postgres: diff --git a/README.md b/README.md index 9f5d275..c708ace 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # shared -The single source of truth for code reused across every project in this workspace: a Svelte design system and application shell, and backend helpers (Postgres access, config, auth/session persistence, an AuthGuard client, log shipping) in four languages. Every project that consumes this repo — including the media-family services (CarrierNode, ContentScanner, CraftStudio, MediaViewer, KioskDisplay, ModerationHub, ProjectConfigurator) — is its own independent frontend/backend; none of them share a generic multi-flavor binary or app anymore. +The single source of truth for code reused across every project in this workspace: a Svelte design system and application shell, and backend helpers (Postgres access, config, auth/session persistence, an AuthGuard client, log shipping) in four languages. Every project that consumes this repo — for example CarrierNode, ContentScanner, CraftStudio, MediaViewer, KioskDisplay, ModerationHub and ProjectConfigurator — is its own independent frontend/backend; none of them share a generic multi-flavor binary or app anymore. --- @@ -21,7 +21,7 @@ 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. | -| `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`). | +| `repos.gfranz.ch/Gabriel20xx/shared/backend` | Go | Env config, `pgx` pools/transactions, auth persistence, an AuthGuard client (`authclient`), log shipping (`logshipper`), embedded Goose migrations, the `settings` table helpers, the `files` path-safety helpers, the `media` library routes, the `syncsocket` sync routes, the `carriernodeclient` client, and the account routes (TOTP and profile) on `auth`. | | `@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. | | `com.gabriel20xx.shared.auth` | Java | An AuthGuard client, mirroring the Go/Node/Python ones. | @@ -136,7 +136,7 @@ go test ./... go vet ./... ``` -Go tests that need PostgreSQL skip themselves unless a scratch database is named: `DATABASE_URL` for the auth store tests, `SHARED_TEST_DATABASE_URL` for the platform-user, mediacore and migrate tests. They create tables and delete rows, so never point either at a real database. CI runs them against a throwaway PostgreSQL service (`go test -p 1 ./...`). +Go tests that need PostgreSQL skip themselves unless a scratch database is named: `DATABASE_URL` for the auth store tests, `SHARED_TEST_DATABASE_URL` for the platform-user, media and migrate tests. They create tables and delete rows, so never point either at a real database. CI runs them against a throwaway PostgreSQL service (`go test -p 1 ./...`). `contract/auth-contract.json` holds fixtures (password hashes, TOTP codes, client addresses, and the internal-secret rule: minimum length and example placeholders) that the Go, Node and Python test suites all load, so the runtimes cannot drift apart unnoticed. diff --git a/backend/README.md b/backend/README.md index 2f9624b..a26acfc 100644 --- a/backend/README.md +++ b/backend/README.md @@ -10,7 +10,7 @@ services, not application-specific SQL or HTTP handlers. - `migrate` — embedded filesystem adapter for Goose migrations. - `logshipper` — client adapter for OmniLogger (Web/OmniLogger): batches and ships log entries centrally while mirroring the same human-readable output and Debug/Info/Warn/Error/Critical/Audit/*Ctx method surface as each project's local internal/logging package. -Run `go test ./...` and `go vet ./...` from this directory. Tests that need PostgreSQL skip themselves unless `DATABASE_URL` (auth store) or `SHARED_TEST_DATABASE_URL` (platform users, mediacore, migrate) names a scratch database; use `go test -p 1 ./...` when both are set. The module path is +Run `go test ./...` and `go vet ./...` from this directory. Tests that need PostgreSQL skip themselves unless `DATABASE_URL` (auth store) or `SHARED_TEST_DATABASE_URL` (platform users, media, migrate) names a scratch database; use `go test -p 1 ./...` when both are set. The module path is `repos.gfranz.ch/Gabriel20xx/shared/backend`; change it if the shared folder is hosted under a different repository path. diff --git a/backend/auth/account_routes.go b/backend/auth/account_routes.go new file mode 100644 index 0000000..3aae0b3 --- /dev/null +++ b/backend/auth/account_routes.go @@ -0,0 +1,35 @@ +package auth + +import ( + "encoding/json" + "net/http" + + "github.com/go-chi/chi/v5" +) + +// MountAccountRoutes mounts the signed-in account routes onto r: the TOTP enrollment and +// verification routes, which require a session, and GET /profile, which reports the session's +// user or null. A project that signs users in through AuthGuard mounts these alongside its own +// routes. +func (s *Service) MountAccountRoutes(r chi.Router) { + r.With(s.Require).Get("/security/totp/status", s.TOTPStatus) + r.With(s.Require).Get("/security/totp/initiate", s.TOTPInitiate) + r.With(s.Require).Post("/security/totp/verify", s.TOTPVerify) + r.With(s.Require).Post("/security/totp/disable", s.TOTPDisable) + r.With(s.Optional).Get("/profile", profile) +} + +func profile(w http.ResponseWriter, r *http.Request) { + user := UserFromContext(r.Context()) + if user == nil { + writeAccountJSON(w, http.StatusOK, map[string]any{"user": nil}) + return + } + writeAccountJSON(w, http.StatusOK, map[string]any{"user": user}) +} + +func writeAccountJSON(w http.ResponseWriter, status int, value any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(value) +} diff --git a/backend/auth/account_routes_test.go b/backend/auth/account_routes_test.go new file mode 100644 index 0000000..86e1dcf --- /dev/null +++ b/backend/auth/account_routes_test.go @@ -0,0 +1,64 @@ +package auth + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/go-chi/chi/v5" +) + +func TestProfileReportsTheSessionUser(t *testing.T) { + guard := newRoleAuthGuard(t) + auth := NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject") + router := chi.NewRouter() + auth.MountAccountRoutes(router) + + anonymous := httptest.NewRecorder() + router.ServeHTTP(anonymous, httptest.NewRequest(http.MethodGet, "/profile", nil)) + if anonymous.Code != http.StatusOK || strings.TrimSpace(anonymous.Body.String()) != `{"user":null}` { + t.Fatalf("anonymous profile = %d %s, want a null user", anonymous.Code, anonymous.Body.String()) + } + + request := httptest.NewRequest(http.MethodGet, "/profile", nil) + request.AddCookie(&http.Cookie{Name: "auth_session", Value: "viewer-token"}) + known := httptest.NewRecorder() + router.ServeHTTP(known, request) + var body struct{ User map[string]any } + if err := json.Unmarshal(known.Body.Bytes(), &body); err != nil || body.User["username"] != "tester" || body.User["role"] != "user" { + t.Fatalf("profile = %s, %v", known.Body.String(), err) + } +} + +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 } + +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 +} diff --git a/backend/auth/platform_users_integration_test.go b/backend/auth/platform_users_integration_test.go index a351007..4914af7 100644 --- a/backend/auth/platform_users_integration_test.go +++ b/backend/auth/platform_users_integration_test.go @@ -11,7 +11,7 @@ import ( ) // platformUsersSchema holds the test's own `users` table, so it never meets the fuller table that -// mediacore's migration creates in the same database. +// the media package's migration creates in the same database. const platformUsersSchema = "platform_users_test" // withSearchPath returns databaseURL with its search_path set to schema. @@ -29,7 +29,7 @@ func withSearchPath(t *testing.T, databaseURL, schema string) string { // TestPlatformUserSQL runs the moderatable platform-user methods (CreateUser, ListUsers, // UpdateUser, SetPassword, DeleteUser) against a real database. The `users` table normally comes -// from mediacore's migration, which this package cannot import, so the test creates the columns it +// from the media package's migration, which this package cannot import, so the test creates the columns it // needs in a schema of its own. It is skipped unless SHARED_TEST_DATABASE_URL points at a scratch // database, for example: // diff --git a/backend/auth/proxy.go b/backend/auth/proxy.go index 1623f98..a91fae0 100644 --- a/backend/auth/proxy.go +++ b/backend/auth/proxy.go @@ -1,10 +1,7 @@ -// This file holds the shared media-backend family's /auth/... and /api/auth/... -// handlers, proxied to AuthGuard. Promoted from each service's own -// internal/auth into this shared library so all 7 independent media-family -// backends (CarrierNode, ModerationHub, ProjectConfigurator, KioskDisplay, -// MediaViewer, ContentScanner, CraftStudio) use one copy instead of -// duplicating it. Originally its own "mediaauth" package; merged into this -// package (2026-09-13) since it is no longer media-specific - see "Unified +// This file holds the /auth/... and /api/auth/... handlers, proxied to AuthGuard. Promoted from +// each service's own internal/auth into this shared library so every project that signs users in +// through AuthGuard uses one copy instead of duplicating it. It was merged here from a separate +// package (2026-09-13) since it is not specific to any one project - see "Unified // auth proxy" below - and "auth" is the more accurate name for what it now // is. ProxyUser/ProxyStore/Service/New/NewWithStore below are this file's // exports; everything else in this package (Store, User, Role, TOTP, @@ -13,9 +10,8 @@ // // Unified auth proxy // ================== -// This file used to be its own package, specific to the 7 media-family -// backends (each built via New, wired directly to their own shared Postgres -// `settings` table). It is now the ONE shared auth-proxy engine for every +// This file used to be its own package, built around New and wired directly to the shared +// Postgres `settings` table. It is now the ONE shared auth-proxy engine for every // project in this workspace that centralizes identity through AuthGuard - // GameStream, Bitmagnet, and OmniLogger, which each used to independently // reimplement this same session/login/TOTP/admin-user proxy against their @@ -23,7 +19,7 @@ // ProxyStore adapter over whatever local table they already used for their // "login required" toggle and one-time setup-claim flag (see the ProxyStore // interface below), instead of duplicating this file's logic. New (the -// original media-family constructor) is unchanged and is really just +// original constructor) is unchanged and is really just // NewWithStore plus pgSettingsStore, the default ProxyStore implementation // backed by the shared `settings` table. // @@ -44,7 +40,7 @@ // // It now proxies every auth operation to AuthGuard (Web/Core/AuthGuard), // a centralized identity service other projects in this workspace share, -// via the `authclient` package (Web/Core/shared/backend/authclient). This +// via the `authclient` package (shared/backend/authclient). This // service's own /auth/... and /api/auth/... URL paths and JSON response // shapes are UNCHANGED - the frontend (webui) was not touched - only // what backs them changed. This mirrors the migration @@ -257,7 +253,7 @@ var adminProfile = ProxyUser{ID: 0, Username: "Admin", Email: "", Role: string(R // AuthGuard migration - see the package doc comment's second paragraph) and // the one-time "has this deployment's setup screen been completed" claim // flag (see the "Setup flow" section below). pgSettingsStore is the -// implementation New builds automatically over the media family's shared +// implementation New builds automatically over the shared // `settings` table; NewWithStore accepts any other implementation, letting a // project with its own storage (GameStream's/Bitmagnet's/OmniLogger's own // tables) reuse this package without adopting that generic table. @@ -272,7 +268,7 @@ type ProxyStore interface { type Service struct { // db backs only the "moderatable platform users" section at the bottom // of this file (CreateUser/ListUsers/UpdateUser/SetPassword/DeleteUser), - // a media-family-specific concept unrelated to AuthGuard identity - see + // a concept specific to the platform-users table, unrelated to AuthGuard identity - see // that section's own doc comment. nil for a Service built via // NewWithStore; those methods are simply never called by a project with // no such local platform-user table. @@ -351,7 +347,7 @@ func WithTrustedProxies(networks []*net.IPNet) ServiceOption { return func(o *serviceOptions) { o.trustedProxies = networks } } -// New constructs a Service backed by the media family's shared `settings` +// New constructs a Service backed by the shared `settings` // table (pgSettingsStore) for the login-required toggle and setup-claim // flag, and by db directly for the unrelated "moderatable platform users" // section. cookieName/secureCookies are retained only for clearing the @@ -373,7 +369,7 @@ func New(db *pgxpool.Pool, cookieName string, secureCookies bool, authGuardURL, // NewWithStore constructs a Service against any ProxyStore implementation, // for a project whose login-required toggle and setup-claim flag live in -// its own storage rather than the media family's shared `settings` table. +// its own storage rather than the shared `settings` table. // Its resulting Service has no db (the "moderatable platform users" section // is unavailable - a project adopting this package fresh has no such // feature to preserve). @@ -410,9 +406,8 @@ func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authG } } -// pgSettingsStore is the default ProxyStore New builds over the media -// family's shared `settings` key/value table (see mediacore.SettingValue/ -// SaveSetting) - unchanged behavior from before this package accepted a +// pgSettingsStore is the default ProxyStore New builds over the shared +// `settings` key/value table (see settings.Value/settings.Save) - unchanged behavior from before this package accepted a // pluggable ProxyStore. type pgSettingsStore struct { db *pgxpool.Pool @@ -1629,7 +1624,7 @@ func normalizePlatformRole(role string) string { // idURLParam extracts the "{id}" path segment from ManagedUpdateUser's/ // ManagedDeleteUser's route regardless of which router mounted it: chi's -// URLParam for the (7) media-family services that route through chi, or the +// URLParam for services that route through chi, or the // standard library's 1.22+ ServeMux PathValue (what GameStream, OmniLogger, // and other non-chi consumers of this package use) when chi reports none. func idURLParam(r *http.Request) string { diff --git a/backend/authproxy/authproxy.go b/backend/authproxy/authproxy.go index 2a5a1cc..1822e7d 100644 --- a/backend/authproxy/authproxy.go +++ b/backend/authproxy/authproxy.go @@ -6,9 +6,7 @@ // Three services independently reimplemented the same handful of pieces // below before this package existed (Fork/Bitmagnet/backend/internal/auth/service.go, // Original/GameStream/backend/cmd/gamestreamd/auth.go, -// this same module's own mediaauth/auth.go, formerly -// Core/shared/media-backend/internal/auth/auth.go before that generic -// multi-service binary was split up — read any one of their top-of-file +// this same module's own auth/proxy.go — read any one of their top-of-file // doc comments for the fuller AuthGuard-migration // rationale: session cookie forwarding, the local one-time setup-claim // flag, "auth disabled" mode, etc.). Those pieces stay project-specific diff --git a/backend/carriernodeclient/settings_urls.go b/backend/carriernodeclient/settings_urls.go new file mode 100644 index 0000000..b640433 --- /dev/null +++ b/backend/carriernodeclient/settings_urls.go @@ -0,0 +1,55 @@ +package carriernodeclient + +import ( + "context" + "encoding/json" + "regexp" + "strings" + + "github.com/jackc/pgx/v5/pgxpool" + + "repos.gfranz.ch/Gabriel20xx/shared/backend/settings" +) + +// carrierNodeInstancePattern matches a registered project key naming a CarrierNode instance: the +// base "carriernode" itself, or a numbered peer like "carriernode_2" - see +// ProjectConfigurator/backend/cmd/projectconfigurator/settings.go's identical pattern (kept in +// sync manually since one is the sender's copy and this is the direct-DB-read receiver's copy of +// the same convention, not literally shared code). +var carrierNodeInstancePattern = regexp.MustCompile(`^carriernode(_\d+)?$`) + +// URLsFromSettings returns every CarrierNode instance registered in ProjectConfigurator's Projects +// workspace ("carriernode_url", "carriernode_2_url", ...), read directly from the shared +// `settings` table in registration order, dropping any instance with no URL set. This is for +// CarrierNode instances that share this database directly instead of going through +// ProjectConfigurator's coreconfig push (see ProjectConfigurator/README.md's "Pushing core service +// info to other projects" section) - wire it as a carriernodeclient.Client's BaseURLs: +// +// carriernodeclient.NewMulti(secret, func(ctx context.Context) []string { +// return carriernodeclient.URLsFromSettings(ctx, db, fallback) +// }) +// +// Returns fallback if no carriernode* instance is registered (or none has a URL) yet. +func URLsFromSettings(ctx context.Context, db *pgxpool.Pool, fallback []string) []string { + var registered []string + _ = json.Unmarshal([]byte(settings.ValueOrFallback(ctx, db, "configured_central", "")), ®istered) + var urls []string + for _, project := range registered { + key := strings.ToLower(strings.TrimSpace(project)) + if !carrierNodeInstancePattern.MatchString(key) { + continue + } + if url := strings.TrimSpace(settings.ValueOrFallback(ctx, db, key+"_url", "")); url != "" { + urls = append(urls, url) + } + } + if len(urls) == 0 { + if url := strings.TrimSpace(settings.ValueOrFallback(ctx, db, "carriernode_url", "")); url != "" { + urls = []string{url} + } + } + if len(urls) == 0 { + return fallback + } + return urls +} diff --git a/backend/files/files.go b/backend/files/files.go new file mode 100644 index 0000000..88e99d9 --- /dev/null +++ b/backend/files/files.go @@ -0,0 +1,109 @@ +// Package files holds the path-safety helpers for serving files from configured media roots: +// relative-path checks, root containment (including symlink escapes), and range-aware file serving. +package files + +import ( + "encoding/json" + "errors" + "mime" + "net/http" + "os" + "path/filepath" + "strings" +) + +// SafeRelative reports whether value is a relative path with no `..` +// traversal or absolute-path escape (Windows drive letters included). +func SafeRelative(value string) bool { + value = strings.TrimSpace(value) + windowsAbsolute := len(value) >= 2 && value[1] == ':' + return value != "" && !strings.ContainsRune(value, 0) && !filepath.IsAbs(value) && !strings.HasPrefix(value, "/") && !strings.HasPrefix(value, `\`) && !windowsAbsolute && filepath.Clean(value) != "." && filepath.Clean(value) != ".." && !strings.HasPrefix(filepath.Clean(value), ".."+string(filepath.Separator)) && !strings.Contains(value, "../") && !strings.Contains(value, `..\`) +} + +// WithinRoot reports whether candidate is (non-strictly) inside root. +func WithinRoot(root, candidate string) bool { + rel, err := filepath.Rel(root, candidate) + return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && !filepath.IsAbs(rel) +} + +// SameRealRoot reports whether candidate's symlink-resolved real path is +// still inside root's symlink-resolved real path (guards against a symlink +// planted inside root pointing outside it). +func SameRealRoot(root, candidate string) bool { + realRoot, err := filepath.EvalSymlinks(root) + if err != nil { + return false + } + realCandidate, err := filepath.EvalSymlinks(candidate) + if err != nil { + return false + } + realRoot, err = filepath.Abs(realRoot) + if err != nil { + return false + } + realCandidate, err = filepath.Abs(realCandidate) + return err == nil && WithinRoot(realRoot, realCandidate) +} + +// ResolveUnderRoots resolves value (a "/media/"-prefixed or bare relative +// path) against each of roots in order, returning the first root it +// actually exists under as a real file (not a directory, and not merely a +// symlink escape - see SameRealRoot). Returns os.ErrNotExist if no root +// matches. +func ResolveUnderRoots(value string, roots []string) (string, error) { + value = strings.TrimSpace(strings.TrimPrefix(value, "/media/")) + value = strings.TrimPrefix(value, "/") + if value == "" || strings.ContainsRune(value, 0) { + return "", errors.New("empty path") + } + for _, root := range roots { + rootAbs, err := filepath.Abs(root) + if err != nil { + continue + } + candidate := value + if !filepath.IsAbs(candidate) { + candidate = filepath.Join(rootAbs, filepath.FromSlash(candidate)) + } + candidate, err = filepath.Abs(candidate) + if err != nil || !WithinRoot(rootAbs, candidate) { + continue + } + info, err := os.Stat(candidate) + if err == nil && !info.IsDir() && SameRealRoot(rootAbs, candidate) { + return candidate, nil + } + } + return "", os.ErrNotExist +} + +// ServeFile serves fullPath (an already-resolved, already-safety-checked +// path) with the correct Content-Type and range-request support. +func ServeFile(w http.ResponseWriter, r *http.Request, fullPath string) { + file, err := os.Open(fullPath) + if err != nil { + writeError(w, http.StatusNotFound, "file not found") + return + } + defer file.Close() + info, err := file.Stat() + if err != nil || info.IsDir() { + writeError(w, http.StatusNotFound, "file not found") + return + } + if contentType := mime.TypeByExtension(filepath.Ext(fullPath)); contentType != "" { + w.Header().Set("Content-Type", contentType) + } + http.ServeContent(w, r, filepath.Base(fullPath), info.ModTime(), file) +} + +func writeJSON(w http.ResponseWriter, status int, value any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(value) +} + +func writeError(w http.ResponseWriter, status int, message string) { + writeJSON(w, status, map[string]string{"error": message, "message": message}) +} diff --git a/backend/mediacore/paths_test.go b/backend/files/files_test.go similarity index 59% rename from backend/mediacore/paths_test.go rename to backend/files/files_test.go index 5bd9592..6cd585a 100644 --- a/backend/mediacore/paths_test.go +++ b/backend/files/files_test.go @@ -1,4 +1,4 @@ -package mediacore +package files import ( "errors" @@ -58,44 +58,3 @@ func TestResolveUnderRootsStaysInsideTheRoots(t *testing.T) { t.Errorf("missing file error = %v, want os.ErrNotExist", err) } } - -func TestUpstreamMediaPathRefusesQueryFragmentAndTraversal(t *testing.T) { - for _, stored := range []string{"x?y.mp4", "a#b.mp4", "../x.mp4", "media/../../x.mp4", `..\x.mp4`} { - if _, ok := upstreamMediaPath(stored); ok { - t.Errorf("upstreamMediaPath(%q) accepted, want refused", stored) - } - } -} - -func TestUpstreamMediaPathEscapesEachSegment(t *testing.T) { - cases := map[string]string{ - "clips/clip.mp4": "clips/clip.mp4", - "my clip.mp4": "my%20clip.mp4", - "100%.mp4": "100%25.mp4", - "media/a b/c.mp4": "a%20b/c.mp4", - "/leading.mp4": "leading.mp4", - } - for stored, want := range cases { - got, ok := upstreamMediaPath(stored) - if !ok || got != want { - t.Errorf("upstreamMediaPath(%q) = %q, %v; want %q", stored, got, ok, want) - } - } -} - -func TestCanonicalMediaIDAcceptsOnlyCanonicalDecimals(t *testing.T) { - for _, value := range []string{"", "007", "+1", "-1", "4a", " 4", "4 ", "99999999999999999999"} { - if id, ok := canonicalMediaID(value); ok { - t.Errorf("canonicalMediaID(%q) = %d, want refused", value, id) - } - } - if id, ok := canonicalMediaID("42"); !ok || id != 42 { - t.Errorf("canonicalMediaID(42) = %d, %v; want 42, true", id, ok) - } - if mediaIDArg("abc") != nil { - t.Error("mediaIDArg(non-numeric) is not NULL") - } - if mediaIDArg("42") != int64(42) { - t.Error("mediaIDArg(42) is not 42") - } -} diff --git a/backend/mediacore/mediacore.go b/backend/media/media.go similarity index 68% rename from backend/mediacore/mediacore.go rename to backend/media/media.go index 72ef275..f8c04b8 100644 --- a/backend/mediacore/mediacore.go +++ b/backend/media/media.go @@ -1,96 +1,73 @@ -// Package mediacore is the media-backend family's cross-service HTTP surface: -// media like/save/view stats, tags, playlists, cross-device playback sync -// state, and profile - the routes every media-family service mounts -// regardless of its own specialty (MediaViewer's own library/browse routes, -// CraftStudio's generator/downloader/converter, ContentScanner's AI -// pipeline, etc. are NOT here; each service owns those itself). -// -// Promoted from each service's own internal/server mountSharedRoutes/media.go -// into this shared library so all 7 independent media-family backends use -// one copy instead of duplicating it. Behavior is unchanged from the -// pre-split monolith - this is a mechanical extraction, not a rewrite. +// Package media is the shared media library API: media likes, saves and view stats, tags and tag +// votes, playlists, and the stream and thumbnail routes. A service that serves media from its own +// library mounts these routes with Mount. A service without a media library mounts none of them. // // A service wires this up as: // -// core := mediacore.New(mediacore.Config{ +// svc := media.New(media.Config{ // DB: pool, // Auth: authService, -// Sync: syncsocket.NewHub(), // CarrierNode: carrierNodeClient, // ServiceName: "CarrierNode", // cfg.ServiceName -// MediaRoots: func(ctx context.Context) []string { return cfg.MediaRoots }, // }) -// if err := core.Migrate(ctx); err != nil { ... } +// if err := svc.Migrate(ctx); err != nil { ... } // router.Route("/api", func(r chi.Router) { -// core.Mount(r) +// svc.Mount(r) // // ... the service's own routes ... // }) -package mediacore +package media import ( "context" "encoding/json" - "errors" "io" - "mime" + "math" "net/http" "net/url" - "os" "path/filepath" - "regexp" "strconv" "strings" "time" "github.com/go-chi/chi/v5" - "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" "repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient" - "repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket" + "repos.gfranz.ch/Gabriel20xx/shared/backend/files" ) // maxPlaylistReorderItems caps one reorder request. The reorder runs as a single statement, so the // cap bounds its size; a playlist longer than this is reordered in more than one request. const maxPlaylistReorderItems = 10000 -// Config wires a Core to the rest of one service's dependencies. +// Config wires a Service to the rest of one service's dependencies. type Config struct { DB *pgxpool.Pool Auth *sharedauth.Service - Sync *syncsocket.Hub CarrierNode *carriernodeclient.Client // ServiceName is recorded on mutations that track which app produced // them (e.g. media_stats.app) - a service's own cfg.ServiceName. ServiceName string } -// Core mounts the shared media/tags/playlists/sync/profile routes and holds -// what they need to run. -type Core struct { +// Service mounts the shared media routes and holds what they need to run. +type Service struct { db *pgxpool.Pool auth *sharedauth.Service - sync *syncsocket.Hub carrierNode *carriernodeclient.Client serviceName string } -// New returns a Core ready to Mount and Migrate. -func New(cfg Config) *Core { - return &Core{db: cfg.DB, auth: cfg.Auth, sync: cfg.Sync, carrierNode: cfg.CarrierNode, serviceName: cfg.ServiceName} +// New returns a Service ready to Mount and Migrate. +func New(cfg Config) *Service { + return &Service{db: cfg.DB, auth: cfg.Auth, carrierNode: cfg.CarrierNode, serviceName: cfg.ServiceName} } -// Mount wires the shared routes onto r, exactly matching the pre-split -// monolith's mountSharedRoutes route table. -func (c *Core) Mount(r chi.Router) { - r.With(c.auth.Require).Get("/security/totp/status", c.auth.TOTPStatus) - r.With(c.auth.Require).Get("/security/totp/initiate", c.auth.TOTPInitiate) - 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.Require).Put("/sync", c.putSyncState) +// Mount wires the media routes onto r. Sync, profile and the TOTP routes are not media routes: +// mount them with syncsocket.MountRoutes and auth.Service.MountAccountRoutes. +func (c *Service) Mount(r chi.Router) { 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) @@ -117,55 +94,6 @@ func (c *Core) Mount(r chi.Router) { r.With(c.auth.Require).Delete("/playlists/{id}/items", c.deletePlaylistItem) r.With(c.auth.Optional).Get("/playlists/{id}/random", c.randomPlaylistItem) r.With(c.auth.Require).Patch("/playlists/{id}/items/reorder", c.reorderPlaylist) - - r.With(c.auth.Optional).Get("/profile", c.profile) -} - -func (c *Core) getSyncState(w http.ResponseWriter, r *http.Request) { - sessionID := boundedSyncString(firstNonEmpty(r.URL.Query().Get("sessionId"), "default")) - writeJSON(w, http.StatusOK, c.sync.HTTPState(sessionID)) -} - -func (c *Core) putSyncState(w http.ResponseWriter, r *http.Request) { - var input map[string]any - if err := decodeRequestJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - clientID := boundedSyncString(syncString(input, "clientId")) - if clientID == "" { - 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": mediaID, - "timeMs": syncInt(input, "timeMs", 0), - "paused": syncBool(input, "paused"), - "fps": syncFPS(input), - "frame": syncInt(input, "frame", 0), - "fromClientId": clientID, - "updatedAt": time.Now().UTC().Format(time.RFC3339Nano), - } - if value, ok := input["playAt"]; ok { - 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) - // Broadcast queues immutable messages without waiting for network writes, so a slow - // websocket peer does not hold this response or create one goroutine per request. - c.sync.Broadcast(sessionID) - writeJSON(w, http.StatusOK, map[string]any{"success": true, "state": state}) } // MediaRecord is one row of the shared `media` table. @@ -191,11 +119,11 @@ type MediaRecord struct { ModifiedAt time.Time } -func (c *Core) streamMediaByQuery(w http.ResponseWriter, r *http.Request) { +func (c *Service) streamMediaByQuery(w http.ResponseWriter, r *http.Request) { c.streamMediaIdentifier(w, r, firstNonEmpty(r.URL.Query().Get("mediaKey"), r.URL.Query().Get("id"))) } -func (c *Core) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) { +func (c *Service) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) { record, err := c.findMedia(r.Context(), identifier, canSeeHidden(r)) if err != nil { writeError(w, http.StatusNotFound, "media not found") @@ -209,13 +137,13 @@ func (c *Core) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, ide c.carrierNode.Proxy(w, r, "/media/"+upstream) } -func (c *Core) thumbnailMediaByQuery(w http.ResponseWriter, r *http.Request) { +func (c *Service) thumbnailMediaByQuery(w http.ResponseWriter, r *http.Request) { c.thumbnailMediaIdentifier(w, r, firstNonEmpty(r.URL.Query().Get("mediaKey"), r.URL.Query().Get("id"))) } -func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) { +func (c *Service) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request, identifier string) { id := identifier - if !SafeRelative(id) { + if !files.SafeRelative(id) { writeError(w, http.StatusBadRequest, "invalid media id") return } @@ -236,7 +164,7 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request, JOIN media m ON m.id = t.media_id OR t.source_path = COALESCE(NULLIF(m.file_path, ''), m.media_key) WHERE m.media_key=$1 OR m.id=$2 ORDER BY t.created_at DESC - LIMIT 1`, id, mediaIDArg(id)).Scan(&thumbnailID); err == nil && SafeRelative(thumbnailID) { + LIMIT 1`, id, mediaIDArg(id)).Scan(&thumbnailID); err == nil && files.SafeRelative(thumbnailID) { // A row whose file CarrierNode no longer has falls through to the original image below, // rather than proxying CarrierNode's 404. if c.carrierNode.ProxyThumbnail(w, r, c.serviceName, thumbnailID) { @@ -256,7 +184,7 @@ func (c *Core) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request, c.carrierNode.Proxy(w, r, "/media/"+upstream) } -func (c *Core) mediaState(w http.ResponseWriter, r *http.Request) { +func (c *Service) mediaState(w http.ResponseWriter, r *http.Request) { key := strings.TrimSpace(firstNonEmpty(r.URL.Query().Get("mediaKey"), chi.URLParam(r, "id"))) if key == "" { writeError(w, http.StatusBadRequest, "missing mediaKey") @@ -279,15 +207,15 @@ func (c *Core) mediaState(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": data, "mediaKey": key, "likes": likes, "saves": saves, "views": views}) } -func (c *Core) mediaLike(w http.ResponseWriter, r *http.Request) { +func (c *Service) mediaLike(w http.ResponseWriter, r *http.Request) { c.mediaStatMutation(w, r, "like") } -func (c *Core) mediaSave(w http.ResponseWriter, r *http.Request) { +func (c *Service) mediaSave(w http.ResponseWriter, r *http.Request) { c.mediaStatMutation(w, r, "save") } -func (c *Core) mediaStatMutation(w http.ResponseWriter, r *http.Request, statType string) { +func (c *Service) mediaStatMutation(w http.ResponseWriter, r *http.Request, statType string) { user := sharedauth.UserFromContext(r.Context()) if user == nil { writeError(w, http.StatusUnauthorized, "not authenticated") @@ -330,7 +258,7 @@ func (c *Core) mediaStatMutation(w http.ResponseWriter, r *http.Request, statTyp writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"mediaKey": key, "enabled": enabled}}) } -func (c *Core) mediaView(w http.ResponseWriter, r *http.Request) { +func (c *Service) mediaView(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) var input struct { MediaKey string `json:"mediaKey"` @@ -366,7 +294,7 @@ func (c *Core) mediaView(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": map[string]any{"ok": true}}) } -func (c *Core) mediaViewSession(w http.ResponseWriter, r *http.Request) { +func (c *Service) mediaViewSession(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) var input struct { MediaKey string `json:"mediaKey"` @@ -409,14 +337,14 @@ func (c *Core) mediaViewSession(w http.ResponseWriter, r *http.Request) { const maxViewSessionDurationMs int64 = 24 * 60 * 60 * 1000 -func (c *Core) mediaExists(ctx context.Context, identifier string) (bool, error) { +func (c *Service) mediaExists(ctx context.Context, identifier string) (bool, error) { var exists bool err := c.db.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM media WHERE media_key=$1 OR id=$2)`, identifier, mediaIDArg(identifier)).Scan(&exists) return exists, err } -func (c *Core) mediaLiked(w http.ResponseWriter, r *http.Request) { +func (c *Service) mediaLiked(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) rows, err := c.db.Query(r.Context(), `SELECT media_key, created_at FROM media_stats WHERE user_id = $1 AND stat_type = 'like' ORDER BY created_at DESC`, user.ID) if err != nil { @@ -435,7 +363,7 @@ func (c *Core) mediaLiked(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"success": true, "data": items, "items": items}) } -func (c *Core) mediaTags(w http.ResponseWriter, r *http.Request) { +func (c *Service) mediaTags(w http.ResponseWriter, r *http.Request) { key := strings.TrimSpace(chi.URLParam(r, "id")) rows, err := c.db.Query(r.Context(), ` SELECT mt.tag, COALESCE(SUM(mv.vote), 0) AS score @@ -457,7 +385,7 @@ func (c *Core) mediaTags(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"tags": tags}) } -func (c *Core) addMediaTag(w http.ResponseWriter, r *http.Request) { +func (c *Service) addMediaTag(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) var input struct { Tag string `json:"tag"` @@ -480,7 +408,7 @@ func (c *Core) addMediaTag(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusCreated, map[string]any{"tag": tag}) } -func (c *Core) voteMediaTag(w http.ResponseWriter, r *http.Request) { +func (c *Service) voteMediaTag(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) var input struct { Vote int `json:"vote"` @@ -506,8 +434,12 @@ func (c *Core) voteMediaTag(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"tag": tag, "vote": input.Vote}) } -func (c *Core) tagSuggestions(w http.ResponseWriter, r *http.Request) { - limit := optionalInt(r.URL.Query().Get("limit"), 50, 1, 1000) +func (c *Service) tagSuggestions(w http.ResponseWriter, r *http.Request) { + // Without a limit every tag comes back. A NULL LIMIT is no limit in Postgres. + var limit any + if value := r.URL.Query().Get("limit"); value != "" { + limit = optionalInt(value, 50, 1, math.MaxInt) + } rows, err := c.db.Query(r.Context(), `SELECT tag, COUNT(*) AS frequency FROM media_tags GROUP BY tag ORDER BY frequency DESC, LOWER(tag) LIMIT $1`, limit) if err != nil { writeJSON(w, http.StatusOK, map[string]any{"tags": []any{}}) @@ -525,12 +457,22 @@ func (c *Core) tagSuggestions(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"tags": tags}) } -func (c *Core) tagMedia(w http.ResponseWriter, r *http.Request) { +func (c *Service) tagMedia(w http.ResponseWriter, r *http.Request) { tag := strings.ToLower(strings.TrimSpace(chi.URLParam(r, "tag"))) pageNumber := optionalInt(r.URL.Query().Get("page"), 1, 1, 1000000) limit := optionalInt(r.URL.Query().Get("limit"), 24, 1, 100) offset := (pageNumber - 1) * limit - rows, err := c.db.Query(r.Context(), `SELECT DISTINCT media_key FROM media_tags WHERE LOWER(tag) = $1 ORDER BY media_key LIMIT $2 OFFSET $3`, tag, limit, offset) + // Only media the library lists. A tag keeps its rows after its media is hidden or leaves the + // library, and a hidden item's thumbnail is not found for a viewer, so those would show as + // broken tag examples. + const libraryMedia = `FROM media_tags mt JOIN media m ON m.media_key = mt.media_key + WHERE LOWER(mt.tag) = $1 AND m.active AND m.content_scanner_processed` + var total int64 + if err := c.db.QueryRow(r.Context(), `SELECT COUNT(DISTINCT m.media_key) `+libraryMedia, tag).Scan(&total); err != nil { + writeError(w, http.StatusInternalServerError, "tag media unavailable") + return + } + rows, err := c.db.Query(r.Context(), `SELECT DISTINCT m.media_key `+libraryMedia+` ORDER BY m.media_key LIMIT $2 OFFSET $3`, tag, limit, offset) if err != nil { writeError(w, http.StatusInternalServerError, "tag media unavailable") return @@ -543,10 +485,12 @@ func (c *Core) tagMedia(w http.ResponseWriter, r *http.Request) { items = append(items, map[string]any{"mediaKey": key, "url": mediaStreamURL(key), "thumbnail": mediaThumbnailURL(key), "name": filepath.Base(urlPath(key))}) } } - writeJSON(w, http.StatusOK, map[string]any{"data": items, "items": items, "media": items, "page": pageNumber}) + totalPages := max(1, int((total+int64(limit)-1)/int64(limit))) + pagination := map[string]any{"page": pageNumber, "pageSize": limit, "total": total, "totalPages": totalPages} + writeJSON(w, http.StatusOK, map[string]any{"data": items, "items": items, "media": items, "page": pageNumber, "pagination": pagination}) } -func (c *Core) playlists(w http.ResponseWriter, r *http.Request) { +func (c *Service) playlists(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) rows, err := c.db.Query(r.Context(), `SELECT id, name, created_at FROM playlists WHERE user_id=$1 ORDER BY created_at DESC`, user.ID) if err != nil { @@ -566,7 +510,7 @@ func (c *Core) playlists(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, success(map[string]any{"playlists": items}, "Playlists")) } -func (c *Core) playlistSummary(w http.ResponseWriter, r *http.Request) { +func (c *Service) playlistSummary(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) if user == nil { writeJSON(w, http.StatusOK, success(map[string]any{"playlists": []any{}}, "No playlists")) @@ -590,7 +534,7 @@ func (c *Core) playlistSummary(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, success(map[string]any{"playlists": items}, "Playlists summary")) } -func (c *Core) playlist(w http.ResponseWriter, r *http.Request) { +func (c *Service) playlist(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil || user == nil { @@ -606,7 +550,7 @@ func (c *Core) playlist(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, success(map[string]any{"playlist": map[string]any{"id": id, "name": name, "createdAt": created}}, "Playlist")) } -func (c *Core) createPlaylist(w http.ResponseWriter, r *http.Request) { +func (c *Service) createPlaylist(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) var input struct { Name string `json:"name"` @@ -630,7 +574,7 @@ func (c *Core) createPlaylist(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusCreated, success(map[string]any{"playlist": map[string]any{"id": id, "name": name, "createdAt": created}}, "Playlist created")) } -func (c *Core) deletePlaylist(w http.ResponseWriter, r *http.Request) { +func (c *Service) deletePlaylist(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil { @@ -645,7 +589,7 @@ func (c *Core) deletePlaylist(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist deleted")) } -func (c *Core) playlistItems(w http.ResponseWriter, r *http.Request) { +func (c *Service) playlistItems(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil || user == nil { @@ -676,7 +620,7 @@ func (c *Core) playlistItems(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, success(map[string]any{"items": items}, "Playlist items")) } -func (c *Core) addPlaylistItem(w http.ResponseWriter, r *http.Request) { +func (c *Service) addPlaylistItem(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil { @@ -709,7 +653,7 @@ func (c *Core) addPlaylistItem(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusCreated, success(map[string]any{"mediaKey": key}, "Playlist item added")) } -func (c *Core) deletePlaylistItem(w http.ResponseWriter, r *http.Request) { +func (c *Service) deletePlaylistItem(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil { @@ -733,7 +677,7 @@ func (c *Core) deletePlaylistItem(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist item deleted")) } -func (c *Core) randomPlaylistItem(w http.ResponseWriter, r *http.Request) { +func (c *Service) randomPlaylistItem(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) if user == nil { writeError(w, http.StatusNotFound, "playlist not found") @@ -752,7 +696,7 @@ func (c *Core) randomPlaylistItem(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, success(map[string]any{"mediaKey": key, "url": mediaStreamURL(key), "thumbnail": mediaThumbnailURL(key)}, "Random playlist media")) } -func (c *Core) reorderPlaylist(w http.ResponseWriter, r *http.Request) { +func (c *Service) reorderPlaylist(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) if err != nil { @@ -800,15 +744,6 @@ func (c *Core) reorderPlaylist(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, success(map[string]any{"ok": true}, "Playlist reordered")) } -func (c *Core) profile(w http.ResponseWriter, r *http.Request) { - user := sharedauth.UserFromContext(r.Context()) - if user == nil { - writeJSON(w, http.StatusOK, map[string]any{"user": nil}) - return - } - writeJSON(w, http.StatusOK, map[string]any{"user": user}) -} - // 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 { @@ -817,7 +752,7 @@ func canSeeHidden(r *http.Request) bool { // 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 { +func (c *Service) 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 id=$2))`, @@ -836,7 +771,7 @@ type MediaLookupOptions struct { // FindMedia looks up one media item by media key or numeric id. Shared media routes // preserve moderator access to hidden items; ContentScanner-backed consumers can also // request the same processed-only filtering used by MediaViewer's library routes. -func (c *Core) FindMedia(ctx context.Context, identifier string, options MediaLookupOptions) (MediaRecord, error) { +func (c *Service) FindMedia(ctx context.Context, identifier string, options MediaLookupOptions) (MediaRecord, error) { identifier = strings.TrimSpace(identifier) var record MediaRecord row := c.db.QueryRow(ctx, ` @@ -892,14 +827,14 @@ func (c *Core) FindMedia(ctx context.Context, identifier string, options MediaLo return record, nil } -// findMedia keeps the shared routes on the same lookup implementation used by -// media-family applications that need ContentScanner's processed-only filter. -func (c *Core) findMedia(ctx context.Context, identifier string, includeHidden bool) (MediaRecord, error) { +// findMedia keeps the media routes on the same lookup implementation used by +// applications that need ContentScanner's processed-only filter. +func (c *Service) findMedia(ctx context.Context, identifier string, includeHidden bool) (MediaRecord, error) { return c.FindMedia(ctx, identifier, MediaLookupOptions{IncludeHidden: includeHidden}) } // ToJSON is the shared wire shape for a media record, matching every -// mediacore route's own response shape (id/mediaKey/filename/url/thumbnail/ +// media route's own response shape (id/mediaKey/filename/url/thumbnail/ // etc.) - services with their own media listing routes (e.g. MediaViewer's // mountViewerRoutes) should use this too, for a consistent shape. func (record MediaRecord) ToJSON() map[string]any { @@ -923,180 +858,8 @@ func (record MediaRecord) ToJSON() map[string]any { } } -// SettingValue reads one key from the shared `settings` table. An absent or empty -// setting returns fallback; database errors are returned to the caller. -func SettingValue(ctx context.Context, db *pgxpool.Pool, key, fallback string) (string, error) { - var value string - err := db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key=$1`, key).Scan(&value) - if errors.Is(err, pgx.ErrNoRows) { - return fallback, nil - } - if err != nil { - return "", err - } - if value == "" { - return fallback, nil - } - return value, nil -} - -// SettingValueOrFallback preserves the old fallback-on-error behavior for callers -// whose API cannot return a read error. New request paths should use SettingValue. -func SettingValueOrFallback(ctx context.Context, db *pgxpool.Pool, key, fallback string) string { - value, err := SettingValue(ctx, db, key, fallback) - if err != nil { - return fallback - } - return value -} - -// SettingBool reads a boolean-ish setting ("1"/"true"/"yes"/"on" are true, -// anything else is fallback). -func SettingBool(ctx context.Context, db *pgxpool.Pool, key string, fallback bool) bool { - value := strings.ToLower(strings.TrimSpace(SettingValueOrFallback(ctx, db, key, ""))) - if value == "" { - return fallback - } - return value == "1" || value == "true" || value == "yes" || value == "on" -} - -// SaveSetting upserts one key in the shared `settings` table. -func SaveSetting(ctx context.Context, db *pgxpool.Pool, key, value string) error { - _, err := db.Exec(ctx, `INSERT INTO settings (key, value, updated_at) VALUES ($1,$2,NOW()) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_at=NOW()`, key, value) - return err -} - -// carrierNodeInstancePattern matches a registered project key naming a CarrierNode instance: the -// base "carriernode" itself, or a numbered peer like "carriernode_2" - see -// ProjectConfigurator/backend/cmd/projectconfigurator/settings.go's identical pattern (kept in -// sync manually since one is the sender's copy and this is the direct-DB-read receiver's copy of -// the same convention, not literally shared code). -var carrierNodeInstancePattern = regexp.MustCompile(`^carriernode(_\d+)?$`) - -// CarrierNodeURLs returns every CarrierNode instance registered in ProjectConfigurator's Projects -// workspace ("carriernode_url", "carriernode_2_url", ...), read directly from the shared -// `settings` table in registration order, dropping any instance with no URL set. This is for the -// 7 MEDIA_SERVICE instances that share this database directly instead of going through -// ProjectConfigurator's coreconfig push (see ProjectConfigurator/README.md's "Pushing core service -// info to other projects" section) - wire it as a carriernodeclient.Client's BaseURLs: -// -// carriernodeclient.NewMulti(secret, func(ctx context.Context) []string { -// return mediacore.CarrierNodeURLs(ctx, db, fallback) -// }) -// -// Returns fallback if no carriernode* instance is registered (or none has a URL) yet. -func CarrierNodeURLs(ctx context.Context, db *pgxpool.Pool, fallback []string) []string { - var registered []string - _ = json.Unmarshal([]byte(SettingValueOrFallback(ctx, db, "configured_central", "")), ®istered) - var urls []string - for _, project := range registered { - key := strings.ToLower(strings.TrimSpace(project)) - if !carrierNodeInstancePattern.MatchString(key) { - continue - } - if url := strings.TrimSpace(SettingValueOrFallback(ctx, db, key+"_url", "")); url != "" { - urls = append(urls, url) - } - } - if len(urls) == 0 { - if url := strings.TrimSpace(SettingValueOrFallback(ctx, db, "carriernode_url", "")); url != "" { - urls = []string{url} - } - } - if len(urls) == 0 { - return fallback - } - return urls -} - // --- path-safety helpers (generic, no Core dependency) --- -// SafeRelative reports whether value is a relative path with no `..` -// traversal or absolute-path escape (Windows drive letters included). -func SafeRelative(value string) bool { - value = strings.TrimSpace(value) - windowsAbsolute := len(value) >= 2 && value[1] == ':' - return value != "" && !strings.ContainsRune(value, 0) && !filepath.IsAbs(value) && !strings.HasPrefix(value, "/") && !strings.HasPrefix(value, `\`) && !windowsAbsolute && filepath.Clean(value) != "." && filepath.Clean(value) != ".." && !strings.HasPrefix(filepath.Clean(value), ".."+string(filepath.Separator)) && !strings.Contains(value, "../") && !strings.Contains(value, `..\`) -} - -// WithinRoot reports whether candidate is (non-strictly) inside root. -func WithinRoot(root, candidate string) bool { - rel, err := filepath.Rel(root, candidate) - return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && !filepath.IsAbs(rel) -} - -// SameRealRoot reports whether candidate's symlink-resolved real path is -// still inside root's symlink-resolved real path (guards against a symlink -// planted inside root pointing outside it). -func SameRealRoot(root, candidate string) bool { - realRoot, err := filepath.EvalSymlinks(root) - if err != nil { - return false - } - realCandidate, err := filepath.EvalSymlinks(candidate) - if err != nil { - return false - } - realRoot, err = filepath.Abs(realRoot) - if err != nil { - return false - } - realCandidate, err = filepath.Abs(realCandidate) - return err == nil && WithinRoot(realRoot, realCandidate) -} - -// ResolveUnderRoots resolves value (a "/media/"-prefixed or bare relative -// path) against each of roots in order, returning the first root it -// actually exists under as a real file (not a directory, and not merely a -// symlink escape - see SameRealRoot). Returns os.ErrNotExist if no root -// matches. -func ResolveUnderRoots(value string, roots []string) (string, error) { - value = strings.TrimSpace(strings.TrimPrefix(value, "/media/")) - value = strings.TrimPrefix(value, "/") - if value == "" || strings.ContainsRune(value, 0) { - return "", errors.New("empty path") - } - for _, root := range roots { - rootAbs, err := filepath.Abs(root) - if err != nil { - continue - } - candidate := value - if !filepath.IsAbs(candidate) { - candidate = filepath.Join(rootAbs, filepath.FromSlash(candidate)) - } - candidate, err = filepath.Abs(candidate) - if err != nil || !WithinRoot(rootAbs, candidate) { - continue - } - info, err := os.Stat(candidate) - if err == nil && !info.IsDir() && SameRealRoot(rootAbs, candidate) { - return candidate, nil - } - } - return "", os.ErrNotExist -} - -// ServeFile serves fullPath (an already-resolved, already-safety-checked -// path) with the correct Content-Type and range-request support. -func ServeFile(w http.ResponseWriter, r *http.Request, fullPath string) { - file, err := os.Open(fullPath) - if err != nil { - writeError(w, http.StatusNotFound, "file not found") - return - } - defer file.Close() - info, err := file.Stat() - if err != nil || info.IsDir() { - writeError(w, http.StatusNotFound, "file not found") - return - } - if contentType := mime.TypeByExtension(filepath.Ext(fullPath)); contentType != "" { - w.Header().Set("Content-Type", contentType) - } - http.ServeContent(w, r, filepath.Base(fullPath), info.ModTime(), file) -} - // InferMediaType guesses a media type from a filename's extension. func InferMediaType(value string) string { switch strings.ToLower(filepath.Ext(value)) { @@ -1138,7 +901,7 @@ func urlPath(value string) string { // that CarrierNode would read as the end of the path. func upstreamMediaPath(filePath string) (string, bool) { relative := urlPath(filePath) - if !SafeRelative(relative) || strings.ContainsAny(relative, "?#") { + if !files.SafeRelative(relative) || strings.ContainsAny(relative, "?#") { return "", false } // Escape each segment so percent-escapes and other reserved characters in a stored name @@ -1237,62 +1000,3 @@ func writeJSON(w http.ResponseWriter, status int, value any) { func writeError(w http.ResponseWriter, status int, message string) { writeJSON(w, status, map[string]string{"error": message, "message": message}) } - -// --- sync-message helpers (shared with syncsocket's own copies; duplicated -// here rather than exported from syncsocket, since these are trivially small -// and this keeps mediacore and syncsocket independently buildable) --- - -func syncString(message map[string]any, key string) string { - value, _ := message[key].(string) - return strings.TrimSpace(value) -} - -func boundedSyncString(value string) string { - const maxSyncIdentifier = 128 - value = strings.TrimSpace(value) - if len(value) > maxSyncIdentifier { - return value[:maxSyncIdentifier] - } - return value -} - -func syncBool(message map[string]any, key string) bool { - value, _ := message[key].(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 { - return fallback - } - if value < 0 { - return 0 - } - return int64(value) -} - -func syncFPS(message map[string]any) int64 { - fps := syncInt(message, "fps", 30) - if fps < 1 { - return 1 - } - if fps > 240 { - return 240 - } - return fps -} diff --git a/backend/mediacore/mediacore_test.go b/backend/media/media_test.go similarity index 68% rename from backend/mediacore/mediacore_test.go rename to backend/media/media_test.go index a41b10d..4c1a8bb 100644 --- a/backend/mediacore/mediacore_test.go +++ b/backend/media/media_test.go @@ -1,4 +1,4 @@ -package mediacore +package media import ( "context" @@ -9,28 +9,11 @@ import ( "testing" "github.com/go-chi/chi/v5" - "github.com/jackc/pgx/v5/pgxpool" sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient" ) -func TestSettingValueReturnsDatabaseErrors(t *testing.T) { - db, err := pgxpool.New(context.Background(), "postgres://nobody@127.0.0.1:1/none?sslmode=disable&connect_timeout=1") - if err != nil { - t.Fatalf("pgxpool.New: %v", err) - } - defer db.Close() - - value, err := SettingValue(context.Background(), db, "example", "fallback") - if err == nil || value != "" { - t.Fatalf("SettingValue() = %q, %v; want empty value and database error", value, err) - } - if got := SettingValueOrFallback(context.Background(), db, "example", "fallback"); got != "fallback" { - t.Fatalf("SettingValueOrFallback() = %q, want fallback on error", got) - } -} - // loginRequiredStore is a ProxyStore that always requires login, so the auth gate can be // exercised without a database. type loginRequiredStore struct{} @@ -141,41 +124,3 @@ func TestOnlyModeratorsCanSeeHiddenMedia(t *testing.T) { } } } - -// 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) - } - } -} diff --git a/backend/mediacore/migrate.go b/backend/media/migrate.go similarity index 73% rename from backend/mediacore/migrate.go rename to backend/media/migrate.go index 74fa384..a99fd50 100644 --- a/backend/mediacore/migrate.go +++ b/backend/media/migrate.go @@ -1,25 +1,24 @@ -package mediacore +package media -import "context" +import ( + "context" -// Migrate creates every table (and its indexes) mediacore's shared routes -// read or write, using CREATE TABLE/INDEX IF NOT EXISTS so whichever -// media-family service starts first against a fresh database creates them -// and every other service's own startup is a no-op. Statements are copied -// verbatim from the pre-split monolith's -// internal/database/migrations/001_initial.sql, limited to the tables -// mediacore itself owns (media, media_stats, media_view_sessions, -// media_tags, media_tag_votes, settings, playlists, playlist_items, -// workflow_jobs, thumbnails) plus `users`, which several of those -// reference via foreign key even though identity itself now lives in -// AuthGuard (see mediaauth's package doc comment) - the column is kept for -// FK integrity, not queried by mediacore. + "repos.gfranz.ch/Gabriel20xx/shared/backend/settings" +) + +// Migrate creates the settings table, then every table (and index) the media routes read or +// write. Statements use CREATE TABLE/INDEX IF NOT EXISTS, so whichever service starts first +// against a fresh database creates them and every other service's own startup is a no-op. // -// Each per-service backend additionally runs its own migration for tables -// it exclusively owns (e.g. ContentScanner's media_worker_jobs/ -// media_analysis_tasks, CraftStudio's generated_media/downloaded_media) - -// those are NOT run here. -func (c *Core) Migrate(ctx context.Context) error { +// users is created because several media tables reference it by foreign key. Identity itself lives +// in AuthGuard, so the column is kept for foreign-key integrity and is not queried here. +// +// A service runs its own migration for any tables it alone owns (for example ContentScanner's +// media_worker_jobs and CraftStudio's generated_media); those are not run here. +func (c *Service) Migrate(ctx context.Context) error { + if err := settings.Migrate(ctx, c.db); err != nil { + return err + } for _, statement := range migrationStatements { if _, err := c.db.Exec(ctx, statement); err != nil { return err @@ -154,29 +153,6 @@ var migrationStatements = []string{ UNIQUE (playlist_id, media_key) )`, - `CREATE TABLE IF NOT EXISTS settings ( - key TEXT PRIMARY KEY, - value TEXT, - updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() - )`, - `INSERT INTO settings (key, value) VALUES ('auth_required', 'true') ON CONFLICT (key) DO NOTHING`, - - `CREATE TABLE IF NOT EXISTS workflow_jobs ( - id TEXT PRIMARY KEY, - service TEXT NOT NULL, - tool TEXT NOT NULL, - status TEXT NOT NULL DEFAULT 'queued', - progress INT NOT NULL DEFAULT 0, - request JSONB NOT NULL DEFAULT '{}'::jsonb, - result JSONB NOT NULL DEFAULT '{}'::jsonb, - error_message TEXT, - user_id BIGINT REFERENCES users(id) ON DELETE SET NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - started_at TIMESTAMPTZ, - finished_at TIMESTAMPTZ - )`, - `CREATE INDEX IF NOT EXISTS workflow_jobs_service_idx ON workflow_jobs (service, created_at DESC)`, - `CREATE TABLE IF NOT EXISTS thumbnails ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), media_id BIGINT REFERENCES media(id) ON DELETE SET NULL, diff --git a/backend/media/paths_test.go b/backend/media/paths_test.go new file mode 100644 index 0000000..52c4db8 --- /dev/null +++ b/backend/media/paths_test.go @@ -0,0 +1,46 @@ +package media + +import ( + "testing" +) + +func TestUpstreamMediaPathRefusesQueryFragmentAndTraversal(t *testing.T) { + for _, stored := range []string{"x?y.mp4", "a#b.mp4", "../x.mp4", "media/../../x.mp4", `..\x.mp4`} { + if _, ok := upstreamMediaPath(stored); ok { + t.Errorf("upstreamMediaPath(%q) accepted, want refused", stored) + } + } +} + +func TestUpstreamMediaPathEscapesEachSegment(t *testing.T) { + cases := map[string]string{ + "clips/clip.mp4": "clips/clip.mp4", + "my clip.mp4": "my%20clip.mp4", + "100%.mp4": "100%25.mp4", + "media/a b/c.mp4": "a%20b/c.mp4", + "/leading.mp4": "leading.mp4", + } + for stored, want := range cases { + got, ok := upstreamMediaPath(stored) + if !ok || got != want { + t.Errorf("upstreamMediaPath(%q) = %q, %v; want %q", stored, got, ok, want) + } + } +} + +func TestCanonicalMediaIDAcceptsOnlyCanonicalDecimals(t *testing.T) { + for _, value := range []string{"", "007", "+1", "-1", "4a", " 4", "4 ", "99999999999999999999"} { + if id, ok := canonicalMediaID(value); ok { + t.Errorf("canonicalMediaID(%q) = %d, want refused", value, id) + } + } + if id, ok := canonicalMediaID("42"); !ok || id != 42 { + t.Errorf("canonicalMediaID(42) = %d, %v; want 42, true", id, ok) + } + if mediaIDArg("abc") != nil { + t.Error("mediaIDArg(non-numeric) is not NULL") + } + if mediaIDArg("42") != int64(42) { + t.Error("mediaIDArg(42) is not 42") + } +} diff --git a/backend/mediacore/routes_db_test.go b/backend/media/routes_db_test.go similarity index 89% rename from backend/mediacore/routes_db_test.go rename to backend/media/routes_db_test.go index 6c7327b..3459c57 100644 --- a/backend/mediacore/routes_db_test.go +++ b/backend/media/routes_db_test.go @@ -1,4 +1,4 @@ -package mediacore +package media import ( "context" @@ -25,7 +25,7 @@ import ( // CarrierNode. They create the media tables and a few rows, so they are skipped unless // SHARED_TEST_DATABASE_URL points at a scratch database, for example: // -// SHARED_TEST_DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./mediacore/ +// SHARED_TEST_DATABASE_URL=postgres://user:pass@localhost:5432/scratch?sslmode=disable go test ./media/ const ( aliceID = 9101 @@ -108,7 +108,6 @@ func newDBHarness(t *testing.T) *dbHarness { core := New(Config{ DB: pool, Auth: auth, - Sync: hub, CarrierNode: carriernodeclient.New("", func(context.Context) string { return carrierServer.URL }), ServiceName: "routes-test", }) @@ -353,9 +352,41 @@ func TestTagsAgainstPostgres(t *testing.T) { if len(suggestions) == 0 { t.Fatal("suggestions are empty") } + // A tag keeps its rows after its media is hidden or leaves the library. Only the library's + // media is listed for the tag, so a tag's examples never point at a thumbnail that is not found. + h.insertMedia(t, "rt-tags", "video", "tagged/clip.mp4", true) + h.insertMedia(t, "rt-tags-hidden", "video", "tagged/hidden.mp4", false) + h.insertMedia(t, "rt-tags-new", "video", "tagged/new.mp4", true) + if _, err := h.pool.Exec(context.Background(), `UPDATE media SET content_scanner_processed = TRUE WHERE media_key IN ('rt-tags', 'rt-tags-hidden')`); err != nil { + t.Fatalf("mark media processed: %v", err) + } + h.do(http.MethodPost, "/media/rt-tags-hidden/tags", "alice-token", `{"tag":"Funny"}`) + h.do(http.MethodPost, "/media/rt-tags-new/tags", "alice-token", `{"tag":"Funny"}`) listed := decode(t, h.do(http.MethodGet, "/tags/funny/media?limit=10", "", ""))["items"].([]any) if len(listed) != 1 || listed[0].(map[string]any)["mediaKey"] != "rt-tags" { - t.Fatalf("media for the tag = %v, want rt-tags (the tag matches ignoring case)", listed) + t.Fatalf("media for the tag = %v, want only rt-tags (the hidden and unprocessed items are not listed)", listed) + } + + // Without a limit, suggestions list every tag, not only the first 1000. + if _, err := h.pool.Exec(context.Background(), `INSERT INTO media_tags (media_key, tag, user_id) SELECT 'rt-many', 'bulk ' || g, NULL FROM generate_series(1, 1001) AS g`); err != nil { + t.Fatalf("insert many tags: %v", err) + } + every := decode(t, h.do(http.MethodGet, "/tags/suggestions", "", ""))["tags"].([]any) + if len(every) <= 1000 { + t.Fatalf("suggestions without a limit = %d tags, want every tag (more than 1000)", len(every)) + } + + // The tag's media is paged, and the pagination reports the whole count so the page can reach every page. + if _, err := h.pool.Exec(context.Background(), `INSERT INTO media (media_key, media_type, file_path, active, content_scanner_processed) SELECT 'rt-page-' || g, 'video', 'paged/' || g || '.mp4', TRUE, TRUE FROM generate_series(1, 30) AS g`); err != nil { + t.Fatalf("insert paged media: %v", err) + } + if _, err := h.pool.Exec(context.Background(), `INSERT INTO media_tags (media_key, tag, user_id) SELECT 'rt-page-' || g, 'Paged', NULL FROM generate_series(1, 30) AS g`); err != nil { + t.Fatalf("tag paged media: %v", err) + } + pageTwo := decode(t, h.do(http.MethodGet, "/tags/paged/media?page=2&limit=24", "", "")) + pagination, _ := pageTwo["pagination"].(map[string]any) + if items := pageTwo["items"].([]any); len(items) != 6 || pagination["total"] != float64(30) || pagination["totalPages"] != float64(2) || pagination["page"] != float64(2) { + t.Fatalf("page 2 at 24 per page = %d items, pagination %v; want 6 items on page 2 of 2, total 30", len(items), pagination) } } diff --git a/backend/media/routes_test.go b/backend/media/routes_test.go new file mode 100644 index 0000000..61674ea --- /dev/null +++ b/backend/media/routes_test.go @@ -0,0 +1,41 @@ +package media + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/go-chi/chi/v5" + + sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" +) + +// TestMediaRoutesRefuseAnonymousRequests walks the media route table: every route mounted behind +// Require answers 401 to a caller with no session, before any handler runs. The Service has no +// database or CarrierNode client, so a request that got past the gate would panic. +func TestMediaRoutesRefuseAnonymousRequests(t *testing.T) { + auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject") + router := chi.NewRouter() + New(Config{Auth: auth}).Mount(router) + + for _, route := range []struct{ method, target string }{ + {http.MethodPost, "/media/like"}, + {http.MethodPost, "/media/save"}, + {http.MethodGet, "/media/liked"}, + {http.MethodPost, "/media/7/tags"}, + {http.MethodPost, "/media/7/tags/funny/vote"}, + {http.MethodGet, "/playlists"}, + {http.MethodPost, "/playlists"}, + {http.MethodDelete, "/playlists/3"}, + {http.MethodPost, "/playlists/3/items"}, + {http.MethodDelete, "/playlists/3/items"}, + {http.MethodPatch, "/playlists/3/items/reorder"}, + } { + response := httptest.NewRecorder() + router.ServeHTTP(response, httptest.NewRequest(route.method, route.target, strings.NewReader(`{}`))) + if response.Code != http.StatusUnauthorized { + t.Errorf("%s %s status = %d, want 401", route.method, route.target, response.Code) + } + } +} diff --git a/backend/settings/settings.go b/backend/settings/settings.go new file mode 100644 index 0000000..b6aee2d --- /dev/null +++ b/backend/settings/settings.go @@ -0,0 +1,74 @@ +// Package settings reads and writes the shared `settings` key/value table, which holds small +// per-deployment values such as the login-required toggle. +package settings + +import ( + "context" + "errors" + "strings" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +// Value reads one key from the shared `settings` table. An absent or empty +// setting returns fallback; database errors are returned to the caller. +func Value(ctx context.Context, db *pgxpool.Pool, key, fallback string) (string, error) { + var value string + err := db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key=$1`, key).Scan(&value) + if errors.Is(err, pgx.ErrNoRows) { + return fallback, nil + } + if err != nil { + return "", err + } + if value == "" { + return fallback, nil + } + return value, nil +} + +// ValueOrFallback preserves the old fallback-on-error behavior for callers +// whose API cannot return a read error. New request paths should use Value. +func ValueOrFallback(ctx context.Context, db *pgxpool.Pool, key, fallback string) string { + value, err := Value(ctx, db, key, fallback) + if err != nil { + return fallback + } + return value +} + +// Bool reads a boolean-ish setting ("1"/"true"/"yes"/"on" are true, +// anything else is fallback). +func Bool(ctx context.Context, db *pgxpool.Pool, key string, fallback bool) bool { + value := strings.ToLower(strings.TrimSpace(ValueOrFallback(ctx, db, key, ""))) + if value == "" { + return fallback + } + return value == "1" || value == "true" || value == "yes" || value == "on" +} + +// Save upserts one key in the shared `settings` table. +func Save(ctx context.Context, db *pgxpool.Pool, key, value string) error { + _, err := db.Exec(ctx, `INSERT INTO settings (key, value, updated_at) VALUES ($1,$2,NOW()) ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_at=NOW()`, key, value) + return err +} + +// Migrate creates the settings table and its default login-required row. It is idempotent. +func Migrate(ctx context.Context, db *pgxpool.Pool) error { + for _, statement := range migrationStatements { + if _, err := db.Exec(ctx, statement); err != nil { + return err + } + } + return nil +} + +var migrationStatements = []string{ + `CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + )`, + `INSERT INTO settings (key, value) VALUES ('auth_required', 'true') ON CONFLICT (key) DO NOTHING`, +} diff --git a/backend/settings/settings_test.go b/backend/settings/settings_test.go new file mode 100644 index 0000000..0c128c9 --- /dev/null +++ b/backend/settings/settings_test.go @@ -0,0 +1,24 @@ +package settings + +import ( + "context" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" +) + +func TestSettingValueReturnsDatabaseErrors(t *testing.T) { + db, err := pgxpool.New(context.Background(), "postgres://nobody@127.0.0.1:1/none?sslmode=disable&connect_timeout=1") + if err != nil { + t.Fatalf("pgxpool.New: %v", err) + } + defer db.Close() + + value, err := Value(context.Background(), db, "example", "fallback") + if err == nil || value != "" { + t.Fatalf("Value() = %q, %v; want empty value and database error", value, err) + } + if got := ValueOrFallback(context.Background(), db, "example", "fallback"); got != "fallback" { + t.Fatalf("ValueOrFallback() = %q, want fallback on error", got) + } +} diff --git a/backend/syncsocket/routes.go b/backend/syncsocket/routes.go new file mode 100644 index 0000000..fbf3664 --- /dev/null +++ b/backend/syncsocket/routes.go @@ -0,0 +1,87 @@ +package syncsocket + +import ( + "encoding/json" + "io" + "net/http" + "time" + + "github.com/go-chi/chi/v5" +) + +// MountRoutes wires the cross-device sync HTTP routes onto r. GET /sync returns a session's +// current state and PUT /sync replaces it and broadcasts the change to that session's websocket +// peers. optional and required are the caller's auth middleware (an auth.Service's Optional and +// Require): GET runs with optional and PUT with required. +func MountRoutes(r chi.Router, hub *Hub, optional, required func(http.Handler) http.Handler) { + r.With(optional).Get("/sync", func(w http.ResponseWriter, r *http.Request) { + getState(hub, w, r) + }) + r.With(required).Put("/sync", func(w http.ResponseWriter, r *http.Request) { + putState(hub, w, r) + }) +} + +func getState(hub *Hub, w http.ResponseWriter, r *http.Request) { + sessionID := boundedSyncString(firstNonEmpty(r.URL.Query().Get("sessionId"), "default")) + writeJSON(w, http.StatusOK, hub.HTTPState(sessionID)) +} + +func putState(hub *Hub, w http.ResponseWriter, r *http.Request) { + var input map[string]any + if err := decodeRequestJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + clientID := boundedSyncString(syncString(input, "clientId")) + if clientID == "" { + 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": mediaID, + "timeMs": syncInt(input, "timeMs", 0), + "paused": syncBool(input, "paused"), + "fps": syncFPS(input), + "frame": syncInt(input, "frame", 0), + "fromClientId": clientID, + "updatedAt": time.Now().UTC().Format(time.RFC3339Nano), + } + if value, ok := input["playAt"]; ok { + playAt, valid := syncScalar(value) + if !valid { + writeError(w, http.StatusBadRequest, "playAt must be a string, a number or null") + return + } + state["playAt"] = playAt + } + hub.SetHTTPState(sessionID, state) + // Broadcast queues immutable messages without waiting for network writes, so a slow + // websocket peer does not hold this response or create one goroutine per request. + hub.Broadcast(sessionID) + writeJSON(w, http.StatusOK, map[string]any{"success": true, "state": state}) +} + +func decodeRequestJSON(r *http.Request, target any) error { + defer r.Body.Close() + decoder := json.NewDecoder(io.LimitReader(r.Body, 512*1024)) + decoder.DisallowUnknownFields() + return decoder.Decode(target) +} + +func writeJSON(w http.ResponseWriter, status int, value any) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(value) +} + +func writeError(w http.ResponseWriter, status int, message string) { + writeJSON(w, status, map[string]string{"error": message, "message": message}) +} diff --git a/backend/syncsocket/sync_gate_test.go b/backend/syncsocket/sync_gate_test.go new file mode 100644 index 0000000..5197b25 --- /dev/null +++ b/backend/syncsocket/sync_gate_test.go @@ -0,0 +1,50 @@ +package syncsocket + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/go-chi/chi/v5" + + sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" +) + +// TestSyncWriteRequiresLogin checks that an anonymous PUT /sync is refused before it can change +// shared playback state. +func TestSyncWriteRequiresLogin(t *testing.T) { + auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject") + router := chi.NewRouter() + MountRoutes(router, NewHub(), auth.Optional, auth.Require) + + 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) + } + } +} diff --git a/backend/syncsocket/sync_helpers_test.go b/backend/syncsocket/sync_helpers_test.go new file mode 100644 index 0000000..72bc2b7 --- /dev/null +++ b/backend/syncsocket/sync_helpers_test.go @@ -0,0 +1,18 @@ +package syncsocket + +import ( + "context" +) + +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 } diff --git a/backend/mediacore/routes_test.go b/backend/syncsocket/sync_routes_test.go similarity index 66% rename from backend/mediacore/routes_test.go rename to backend/syncsocket/sync_routes_test.go index eb72fba..57c7763 100644 --- a/backend/mediacore/routes_test.go +++ b/backend/syncsocket/sync_routes_test.go @@ -1,4 +1,4 @@ -package mediacore +package syncsocket import ( "context" @@ -13,49 +13,14 @@ import ( "github.com/go-chi/chi/v5" sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" - "repos.gfranz.ch/Gabriel20xx/shared/backend/syncsocket" ) -// TestSessionRoutesRefuseAnonymousRequests walks the route table: every route mounted behind -// Require answers 401 to a caller with no session, before any handler runs. The Core has no -// database, sync hub or CarrierNode client, so a request that got past the gate would panic. -func TestSessionRoutesRefuseAnonymousRequests(t *testing.T) { - auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, "", "testproject") - router := chi.NewRouter() - New(Config{Auth: auth}).Mount(router) - - for _, route := range []struct{ method, target string }{ - {http.MethodGet, "/security/totp/status"}, - {http.MethodGet, "/security/totp/initiate"}, - {http.MethodPost, "/security/totp/verify"}, - {http.MethodPost, "/security/totp/disable"}, - {http.MethodPut, "/sync"}, - {http.MethodPost, "/media/like"}, - {http.MethodPost, "/media/save"}, - {http.MethodGet, "/media/liked"}, - {http.MethodPost, "/media/7/tags"}, - {http.MethodPost, "/media/7/tags/funny/vote"}, - {http.MethodGet, "/playlists"}, - {http.MethodPost, "/playlists"}, - {http.MethodDelete, "/playlists/3"}, - {http.MethodPost, "/playlists/3/items"}, - {http.MethodDelete, "/playlists/3/items"}, - {http.MethodPatch, "/playlists/3/items/reorder"}, - } { - response := httptest.NewRecorder() - router.ServeHTTP(response, httptest.NewRequest(route.method, route.target, strings.NewReader(`{}`))) - if response.Code != http.StatusUnauthorized { - t.Errorf("%s %s status = %d, want 401", route.method, route.target, response.Code) - } - } -} - -// syncRouter mounts the sync routes on a Core with no database. Auth is disabled, so every caller -// is the placeholder administrator. -func syncRouter(hub *syncsocket.Hub) chi.Router { +// syncRouter mounts the sync routes on hub. Auth is disabled, so every caller is the placeholder +// administrator. +func syncRouter(hub *Hub) chi.Router { auth := sharedauth.NewWithStore(loginOffStore{}, "session", false, "", "testproject", sharedauth.Disabled()) router := chi.NewRouter() - New(Config{Auth: auth, Sync: hub}).Mount(router) + MountRoutes(router, hub, auth.Optional, auth.Require) return router } @@ -66,7 +31,7 @@ func putSync(router http.Handler, target, body string) *httptest.ResponseRecorde } func TestPutSyncRejectsBadInput(t *testing.T) { - router := syncRouter(syncsocket.NewHub()) + router := syncRouter(NewHub()) for name, body := range map[string]string{ "not JSON": `nope`, "missing clientId": `{"mediaId":"m1"}`, @@ -84,7 +49,7 @@ func TestPutSyncRejectsBadInput(t *testing.T) { } func TestPutSyncStoresBoundedStateThatGetSyncReturns(t *testing.T) { - hub := syncsocket.NewHub() + hub := NewHub() router := syncRouter(hub) response := putSync(router, "/sync?sessionId=room-1", `{"clientId":"c1","mediaId":42,"timeMs":-5,"paused":true,"fps":100000,"frame":9,"playAt":"2026-10-19T10:00:00Z"}`) @@ -122,7 +87,7 @@ func TestPutSyncStoresBoundedStateThatGetSyncReturns(t *testing.T) { } func TestPutSyncBoundsAnOversizedSessionAndClientID(t *testing.T) { - router := syncRouter(syncsocket.NewHub()) + router := syncRouter(NewHub()) long := strings.Repeat("s", 300) response := putSync(router, "/sync", `{"clientId":"`+strings.Repeat("c", 300)+`","mediaId":null,"sessionId":"`+long+`"}`) if response.Code != http.StatusOK { @@ -143,7 +108,7 @@ func TestPutSyncBoundsAnOversizedSessionAndClientID(t *testing.T) { // TestPutSyncBroadcastsToThePeersOfThatSession checks the HTTP write reaches websocket peers in // the session, and only those. func TestPutSyncBroadcastsToThePeersOfThatSession(t *testing.T) { - hub := syncsocket.NewHub() + hub := NewHub() router := syncRouter(hub) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { hub.ServeWebSocket(w, r, "") @@ -203,25 +168,3 @@ func readFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, want str } } } - -func TestProfileReportsTheSessionUser(t *testing.T) { - guard := newRoleAuthGuard(t) - auth := sharedauth.NewWithStore(loginRequiredStore{}, "session", false, guard.URL, "testproject") - router := chi.NewRouter() - New(Config{Auth: auth}).Mount(router) - - anonymous := httptest.NewRecorder() - router.ServeHTTP(anonymous, httptest.NewRequest(http.MethodGet, "/profile", nil)) - if anonymous.Code != http.StatusOK || strings.TrimSpace(anonymous.Body.String()) != `{"user":null}` { - t.Fatalf("anonymous profile = %d %s, want a null user", anonymous.Code, anonymous.Body.String()) - } - - request := httptest.NewRequest(http.MethodGet, "/profile", nil) - request.AddCookie(&http.Cookie{Name: "auth_session", Value: "viewer-token"}) - known := httptest.NewRecorder() - router.ServeHTTP(known, request) - var body struct{ User map[string]any } - if err := json.Unmarshal(known.Body.Bytes(), &body); err != nil || body.User["username"] != "tester" || body.User["role"] != "user" { - t.Fatalf("profile = %s, %v", known.Body.String(), err) - } -} diff --git a/backend/syncsocket/sync_scalar.go b/backend/syncsocket/sync_scalar.go new file mode 100644 index 0000000..aecd20e --- /dev/null +++ b/backend/syncsocket/sync_scalar.go @@ -0,0 +1,15 @@ +package syncsocket + +// 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 + } +} diff --git a/backend/syncsocket/syncsocket.go b/backend/syncsocket/syncsocket.go index 9525fb0..6c5e37b 100644 --- a/backend/syncsocket/syncsocket.go +++ b/backend/syncsocket/syncsocket.go @@ -1,9 +1,7 @@ -// Package syncsocket is the media-backend family's cross-device playback-sync -// websocket hub: multiple clients viewing the same media session (identified -// by a caller-chosen sessionId) see each other's play/pause/seek/remote-control -// state live. Promoted unchanged from each service's own internal sync.go into -// this shared library so the 6 media-family backends that mount it (every one -// except KioskDisplay) use one copy instead of duplicating it. +// Package syncsocket is a cross-device playback-sync websocket hub: multiple clients viewing the +// same media session (identified by a caller-chosen sessionId) see each other's +// play/pause/seek/remote-control state live. It is shared so every project that offers live sync +// uses one copy instead of duplicating it. // // A service wires this up as: // @@ -12,7 +10,7 @@ // hub.ServeWebSocket(w, r, cfg.AllowedOrigin) // }) // -// and mediacore's shared GET/PUT /sync HTTP routes call hub.HTTPState/ +// and MountRoutes' GET/PUT /sync HTTP routes call hub.HTTPState/ // SetHTTPState/Broadcast to read and mutate the same session state the // websocket peers see. package syncsocket @@ -204,7 +202,7 @@ func (h *Hub) stateLocked(sessionID string) map[string]any { } // HTTPState returns the current playback state for a session, as seen by the -// GET /sync HTTP endpoint (mounted by mediacore). +// GET /sync HTTP endpoint (mounted by MountRoutes). func (h *Hub) HTTPState(sessionID string) map[string]any { h.mu.Lock() defer h.mu.Unlock() @@ -212,7 +210,7 @@ func (h *Hub) HTTPState(sessionID string) map[string]any { } // SetHTTPState overwrites a session's playback state, as driven by the -// PUT /sync HTTP endpoint (mounted by mediacore) - callers should follow this +// PUT /sync HTTP endpoint (mounted by MountRoutes) - callers should follow this // with Broadcast to notify connected websocket peers. func (h *Hub) SetHTTPState(sessionID string, state map[string]any) { h.mu.Lock() diff --git a/packages/node-backend/README.md b/packages/node-backend/README.md index ab1ad7f..7953308 100644 --- a/packages/node-backend/README.md +++ b/packages/node-backend/README.md @@ -11,7 +11,7 @@ Shared Node.js backend infrastructure for services that use PostgreSQL: The package does not depend on Express. Each service keeps its own routes, cookies, roles, validation policy, and domain repositories. Existing -`MediaShared` code can be migrated into this package incrementally; keep the +media-related code can be migrated into this package incrementally; keep the legacy package as a compatibility layer until every consumer has moved. Pass a service-specific `tableName` to `runMigrations` when multiple services diff --git a/packages/web-ui/src/lib/styles.css b/packages/web-ui/src/lib/styles.css index c1880be..e05d89e 100644 --- a/packages/web-ui/src/lib/styles.css +++ b/packages/web-ui/src/lib/styles.css @@ -745,26 +745,33 @@ html[data-wide-layout='true'] .sc-main { display: flex; flex-wrap: wrap; align-items: center; - justify-content: space-between; - gap: 0.75rem; - margin-top: 1rem; + gap: 0.75rem 1rem; } -.sc-pagination-page-size { +/* Nested under .sc-pagination so it outranks `.sc-root select { font: inherit }` and keeps the 0.8rem size. */ +.sc-pagination .sc-pagination-page-size { + flex: 0 0 auto; width: auto; height: 2.5rem; - padding: 0.375rem 0.6rem; + padding: 0 2rem 0 0.75rem; color: var(--sc-fg); background: var(--sc-bg); border: 1px solid var(--sc-border); border-radius: var(--sc-radius-sm); font-size: 0.8rem; + cursor: pointer; +} + +.sc-pagination .sc-pagination-page-size:focus-visible { + outline: 3px solid color-mix(in srgb, var(--sc-ring) 45%, transparent); + outline-offset: 2px; } .sc-pagination-info { margin: 0; color: var(--sc-muted-fg); font-size: 0.8rem; + font-variant-numeric: tabular-nums; white-space: nowrap; } @@ -807,12 +814,11 @@ html[data-wide-layout='true'] .sc-main { } @media (max-width: 620px) { - .sc-pagination { - justify-content: center; - } - - .sc-pagination-controls { - margin-left: 0; + /* On phones the count gets its own centred line, with the page size and buttons on the row below. */ + .sc-pagination-info { + order: -1; + flex-basis: 100%; + text-align: center; } } diff --git a/scripts/media/audit-inline-layout.mjs b/scripts/media/audit-inline-layout.mjs index 3e742b6..f8e1a39 100644 --- a/scripts/media/audit-inline-layout.mjs +++ b/scripts/media/audit-inline-layout.mjs @@ -50,9 +50,9 @@ function collectMatches(content, regex, type) { const allFiles = await walk(repoRoot); const violations = []; -// After folding media-backend/webui directly into the shared repo, this filter targets +// This filter targets // the frontend directories where inline HTML/CSS layout violations are actually possible -// (the plain Go backend/ and Go media-backend/ have none; there is no more nested shared/). +// (the Go backend/ has none; there is no nested shared/). const includedTopLevelDirs = ['webui/', 'scripts/media/']; for (const filePath of allFiles) { diff --git a/scripts/media/clean-test-artifacts.mjs b/scripts/media/clean-test-artifacts.mjs index e9b47e0..2a7ba18 100644 --- a/scripts/media/clean-test-artifacts.mjs +++ b/scripts/media/clean-test-artifacts.mjs @@ -100,7 +100,7 @@ fallbackRemoved += removeFallbackDirs(repoRoot); // NOTE: no top-level tests/ dir currently exists and no embedded-postgres JS test tooling was // found anywhere in this repo — this sweep is a harmless no-op today but kept for forward // compatibility / parity with the source script. The former sweep of a nested shared/tests/ -// was dropped: after folding media-backend/webui directly into the shared repo (no more +// was dropped: after the webui was folded directly into the shared repo (no more // vendored shared/ copy), there is no longer a nested "shared" subdirectory to sweep. const pgSweepDirs = [path.join(repoRoot, 'tests')]; let pgArtifactsRemoved = 0; diff --git a/scripts/media/lint-all-json.mjs b/scripts/media/lint-all-json.mjs index f2b4a24..2374b04 100644 --- a/scripts/media/lint-all-json.mjs +++ b/scripts/media/lint-all-json.mjs @@ -5,8 +5,8 @@ * machine parsing. Exit code is non-zero if any package reports errors or warnings (configurable). * * Shared extraction note: the monorepo version of this script discovered the monorepo root by - * walking up for a MediaShared/package.json marker and iterated MediaShared/MediaModerator/ - * MediaViewer/MediaTools using a shared root eslint.config.mjs. None of those sibling packages or + * walking up for a root package.json marker and iterated the sibling packages + * using a shared root eslint.config.mjs. None of those sibling packages or * the root config exist in this repo — webui/ is the only JS/TS package here, and it already * ships its own local eslint.config.js (picked up automatically, no --config override needed). */ diff --git a/scripts/media/lint-all.mjs b/scripts/media/lint-all.mjs index cba341e..b5c14f7 100644 --- a/scripts/media/lint-all.mjs +++ b/scripts/media/lint-all.mjs @@ -4,9 +4,9 @@ * Exits non‑zero if any package fails its lint step. * * Shared extraction note: the monorepo version of this script discovered the monorepo root - * by walking up for a MediaShared/package.json marker, iterated nine sibling Media* packages + * by walking up for a root package.json marker, iterated the sibling packages * against a shared root eslint.config.mjs/.stylelintrc.json, and ran Prettier/Stylelint out of - * MediaShared/node_modules (npm workspace hoisting). Here the only JS/TS package with a lint + * the root node_modules (npm workspace hoisting). Here the only JS/TS package with a lint * target is packages/web-ui, linted with the root eslint.config.js (ESLint is a root * devDependency, so `npx eslint` resolves it). Prettier is checked through the root * `format:check` script, which covers only the files written to the Prettier style (see diff --git a/scripts/sync-consumers.ps1 b/scripts/sync-consumers.ps1 index f2a6b9a..a631637 100644 --- a/scripts/sync-consumers.ps1 +++ b/scripts/sync-consumers.ps1 @@ -28,11 +28,9 @@ function New-ConsumerProject { # Destination defaults to 'shared' (the snapshot folder name every consumer # uses) - originally a git submodule, converted to this vendored-copy pattern # for consistency and to drop the private-submodule checkout auth dependency -# in CI. The media-family services (CarrierNode, ContentScanner, CraftStudio, -# MediaViewer, KioskDisplay, ModerationHub, ProjectConfigurator) used to mount -# a shared multi-flavor webui/media-backend at a separate 'engine' folder -# instead; each is now its own independent frontend/backend and vendors this -# snapshot the same way as every other consumer below. +# in CI. Some consumers used to mount a shared multi-flavor webui at a separate 'engine' +# folder; each is now its own independent frontend/backend and vendors this snapshot the same +# way as every other consumer below. $consumerProjects = @( New-ConsumerProject 'Original/MediaDesktop' New-ConsumerProject 'Original/AutoCode' @@ -255,9 +253,8 @@ $sourceRoot = Resolve-FullPath $sourceRepositoryRoot # The workspace root is the ancestor directory that contains both 'Original' # and 'Fork' (every consumer project lives under one of those, or under # 'Core' for the central infrastructure services). Walk up from the shared -# repo instead of assuming a fixed nesting depth, since shared/ has moved -# before (e.g. Web/shared -> Web/Central/shared -> Web/Core/shared, with -# 'Forks' renamed to singular 'Fork' at the same time) and may move again. +# repo instead of assuming a fixed nesting depth, since the workspace layout has +# changed before and may change again. $workspaceRoot = Split-Path -Parent $sourceRoot while ($workspaceRoot -and -not ((Test-Path -LiteralPath (Join-Path $workspaceRoot 'Original') -PathType Container) -and (Test-Path -LiteralPath (Join-Path $workspaceRoot 'Fork') -PathType Container))) { $parent = Split-Path -Parent $workspaceRoot diff --git a/shared-styles.css b/shared-styles.css index dfa20e0..a26f89f 100644 --- a/shared-styles.css +++ b/shared-styles.css @@ -745,26 +745,33 @@ html[data-wide-layout='true'] .sc-main { display: flex; flex-wrap: wrap; align-items: center; - justify-content: space-between; - gap: 0.75rem; - margin-top: 1rem; + gap: 0.75rem 1rem; } -.sc-pagination-page-size { +/* Nested under .sc-pagination so it outranks `.sc-root select { font: inherit }` and keeps the 0.8rem size. */ +.sc-pagination .sc-pagination-page-size { + flex: 0 0 auto; width: auto; height: 2.5rem; - padding: 0.375rem 0.6rem; + padding: 0 2rem 0 0.75rem; color: var(--sc-fg); background: var(--sc-bg); border: 1px solid var(--sc-border); border-radius: var(--sc-radius-sm); font-size: 0.8rem; + cursor: pointer; +} + +.sc-pagination .sc-pagination-page-size:focus-visible { + outline: 3px solid color-mix(in srgb, var(--sc-ring) 45%, transparent); + outline-offset: 2px; } .sc-pagination-info { margin: 0; color: var(--sc-muted-fg); font-size: 0.8rem; + font-variant-numeric: tabular-nums; white-space: nowrap; } @@ -807,12 +814,11 @@ html[data-wide-layout='true'] .sc-main { } @media (max-width: 620px) { - .sc-pagination { - justify-content: center; - } - - .sc-pagination-controls { - margin-left: 0; + /* On phones the count gets its own centred line, with the page size and buttons on the row below. */ + .sc-pagination-info { + order: -1; + flex-basis: 100%; + text-align: center; } }