build(android): upgrade toolchain and migrate Room to KSP
Lint / Lint (push) Successful in 1m29s
Security / Secrets (gitleaks) (push) Successful in 1m11s
Security / Dependencies (Trivy) (push) Successful in 1m59s
Tests / Dashboard checks (push) Successful in 1m49s
Security / Code (Semgrep) (push) Successful in 3m8s
Tests / Go backend (push) Successful in 2m50s
Docker / Docker Build & Push (push) Successful in 8m42s

- Target API 37 and use build-tools 37 for release signature checks
- Adjust list pagination spacing and clarify shared backend docs
This commit is contained in:
Gabriel20xx committed 2026-11-01 21:48:05 +01:00
1 parent 7150ebd13e
commit 0fd1805502
40 files changed
+912 -690

No files matched your search

+1 -1
View File
@@ -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.
+35
View File
@@ -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)
}
@@ -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
}
@@ -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:
//
+15 -20
View File
@@ -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 {
+1 -3
View File
@@ -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
@@ -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", "")), &registered)
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
}
+109
View File
@@ -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})
}
@@ -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")
}
}
@@ -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", "")), &registered)
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
}
@@ -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)
}
}
}
@@ -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,
+46
View File
@@ -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")
}
}
@@ -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)
}
}
+41
View File
@@ -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)
}
}
}
+74
View File
@@ -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`,
}
+24
View File
@@ -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)
}
}
+87
View File
@@ -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})
}
@@ -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)
}
}
}
@@ -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 }
@@ -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)
}
}
+15
View File
@@ -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
}
}
+7 -9
View File
@@ -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()