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

+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 }
@@ -0,0 +1,170 @@
package syncsocket
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/coder/websocket"
"github.com/go-chi/chi/v5"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
)
// 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()
MountRoutes(router, hub, auth.Optional, auth.Require)
return router
}
func putSync(router http.Handler, target, body string) *httptest.ResponseRecorder {
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodPut, target, strings.NewReader(body)))
return response
}
func TestPutSyncRejectsBadInput(t *testing.T) {
router := syncRouter(NewHub())
for name, body := range map[string]string{
"not JSON": `nope`,
"missing clientId": `{"mediaId":"m1"}`,
"blank clientId": `{"clientId":" ","mediaId":"m1"}`,
"object mediaId": `{"clientId":"c1","mediaId":{"a":1}}`,
"boolean mediaId": `{"clientId":"c1","mediaId":true}`,
"array playAt": `{"clientId":"c1","mediaId":"m1","playAt":[1]}`,
"object playAt": `{"clientId":"c1","mediaId":"m1","playAt":{"a":1}}`,
"clientId not text": `{"clientId":5,"mediaId":"m1"}`,
} {
if response := putSync(router, "/sync", body); response.Code != http.StatusBadRequest {
t.Errorf("%s: status = %d, want 400 (body %s)", name, response.Code, response.Body.String())
}
}
}
func TestPutSyncStoresBoundedStateThatGetSyncReturns(t *testing.T) {
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"}`)
if response.Code != http.StatusOK {
t.Fatalf("PUT status = %d, body %s", response.Code, response.Body.String())
}
var written struct {
Success bool `json:"success"`
State map[string]any `json:"state"`
}
if err := json.Unmarshal(response.Body.Bytes(), &written); err != nil || !written.Success {
t.Fatalf("PUT body = %s, %v", response.Body.String(), err)
}
state := written.State
if state["sessionId"] != "room-1" || state["fromClientId"] != "c1" || state["mediaId"] != float64(42) || state["paused"] != true {
t.Fatalf("state = %v", state)
}
if state["timeMs"] != float64(0) || state["fps"] != float64(240) || state["frame"] != float64(9) || state["playAt"] != "2026-10-19T10:00:00Z" {
t.Fatalf("a negative time was not clamped to 0, or fps to 240: %v", state)
}
get := httptest.NewRecorder()
router.ServeHTTP(get, httptest.NewRequest(http.MethodGet, "/sync?sessionId=room-1", nil))
var read map[string]any
if err := json.Unmarshal(get.Body.Bytes(), &read); err != nil || read["fromClientId"] != "c1" || read["mediaId"] != float64(42) {
t.Fatalf("GET /sync = %s, %v; want the stored state", get.Body.String(), err)
}
other := httptest.NewRecorder()
router.ServeHTTP(other, httptest.NewRequest(http.MethodGet, "/sync?sessionId=room-2", nil))
var empty map[string]any
if err := json.Unmarshal(other.Body.Bytes(), &empty); err != nil || empty["fromClientId"] == "c1" {
t.Fatalf("another session got %s, %v; want it untouched", other.Body.String(), err)
}
}
func TestPutSyncBoundsAnOversizedSessionAndClientID(t *testing.T) {
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 {
t.Fatalf("status = %d, body %s", response.Code, response.Body.String())
}
var written struct{ State map[string]any }
if err := json.Unmarshal(response.Body.Bytes(), &written); err != nil {
t.Fatal(err)
}
if got := written.State["sessionId"].(string); len(got) != 128 {
t.Errorf("sessionId length = %d, want 128", len(got))
}
if got := written.State["fromClientId"].(string); len(got) != 128 {
t.Errorf("fromClientId length = %d, want 128", len(got))
}
}
// TestPutSyncBroadcastsToThePeersOfThatSession checks the HTTP write reaches websocket peers in
// the session, and only those.
func TestPutSyncBroadcastsToThePeersOfThatSession(t *testing.T) {
hub := NewHub()
router := syncRouter(hub)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hub.ServeWebSocket(w, r, "")
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
url := "ws" + strings.TrimPrefix(server.URL, "http")
join := func(session string) (*websocket.Conn, string) {
conn, _, err := websocket.Dial(ctx, url, nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { conn.CloseNow() })
hello := readFrame(t, ctx, conn, "hello")
id := hello["clientId"].(string)
data, _ := json.Marshal(map[string]any{"type": "sync:hello", "clientId": id, "sessionId": session})
if err := conn.Write(ctx, websocket.MessageText, data); err != nil {
t.Fatal(err)
}
readFrame(t, ctx, conn, "sync:state")
return conn, id
}
inRoom, _ := join("room-1")
elsewhere, _ := join("room-2")
if response := putSync(router, "/sync?sessionId=room-1", `{"clientId":"http-client","mediaId":"clip-9","timeMs":1500}`); response.Code != http.StatusOK {
t.Fatalf("PUT status = %d", response.Code)
}
frame := readFrame(t, ctx, inRoom, "sync:state")
state, _ := frame["state"].(map[string]any)
if state["mediaId"] != "clip-9" || state["timeMs"] != float64(1500) {
t.Fatalf("the session peer got %v", frame)
}
short, shortCancel := context.WithTimeout(ctx, 300*time.Millisecond)
defer shortCancel()
if _, _, err := elsewhere.Read(short); err == nil {
t.Fatal("a peer in another session received the broadcast")
}
}
func readFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, want string) map[string]any {
t.Helper()
for {
_, data, err := conn.Read(ctx)
if err != nil {
t.Fatalf("read while waiting for %q: %v", want, err)
}
var message map[string]any
if err := json.Unmarshal(data, &message); err != nil {
t.Fatal(err)
}
if message["type"] == want {
return message
}
}
}
+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()