diff --git a/shared/.github/workflows/security.yml b/shared/.github/workflows/security.yml index cb35fe2..0ca48ca 100644 --- a/shared/.github/workflows/security.yml +++ b/shared/.github/workflows/security.yml @@ -6,13 +6,16 @@ on: pull_request: branches: [main, master] schedule: - # Weekly, so advisories published after the last push still get reported. + # Daily, for the Trivy job, so advisories published after the last push still get reported. + - cron: '23 5 * * *' + # Weekly, for the secrets and code jobs. Each job's if: condition picks the entry that runs it. - cron: '23 5 * * 1' workflow_dispatch: {} jobs: secrets: name: Secrets (gitleaks) + if: github.event_name != 'schedule' || github.event.schedule == '23 5 * * 1' runs-on: ubuntu-latest permissions: contents: read @@ -35,6 +38,7 @@ jobs: code: name: Code (Semgrep) + if: github.event_name != 'schedule' || github.event.schedule == '23 5 * * 1' runs-on: ubuntu-latest permissions: contents: read @@ -55,6 +59,7 @@ jobs: dependencies: name: Dependencies (Trivy) + if: github.event_name != 'schedule' || github.event.schedule == '23 5 * * *' runs-on: ubuntu-latest permissions: contents: read diff --git a/shared/README.md b/shared/README.md index c708ace..52a3b4d 100644 --- a/shared/README.md +++ b/shared/README.md @@ -75,7 +75,7 @@ These are the complete Svelte component exports from `packages/web-ui/src/lib/in | Component | Includes | |---|---| -| `MediaPlayer` | Audio/video player with playback, seeking, volume, quality, fullscreen, keyboard controls, and custom end controls. | +| `MediaPlayer` | Audio/video player with playback, seeking, volume, speed, quality, fullscreen, keyboard controls, custom end controls, and optional resume from the saved position (`storageKey`, per app). With `controls={false}` it is just the element, returned through `element`, for apps that drive playback themselves and set `src` on it. | #### Accounts and access diff --git a/shared/backend/media/media.go b/shared/backend/media/media.go index 21288b3..e92aa66 100644 --- a/shared/backend/media/media.go +++ b/shared/backend/media/media.go @@ -135,7 +135,23 @@ func (c *Service) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, writeError(w, http.StatusNotFound, "media not found") return } - c.carrierNode.Proxy(w, r, "/media/"+upstream) + c.carrierNode.Proxy(w, r, streamUpstreamPath(upstream, r.URL.Query())) +} + +// streamUpstreamPath is the CarrierNode request path for a stream. CarrierNode answers with a live +// H.264 copy when the query carries quality (a height) and start (seconds), which is how browsers get +// containers they cannot decode. Those two parameters are the only ones forwarded. +func streamUpstreamPath(upstream string, query url.Values) string { + forward := url.Values{} + for _, key := range []string{"quality", "start"} { + if value := strings.TrimSpace(query.Get(key)); value != "" { + forward.Set(key, value) + } + } + if len(forward) == 0 { + return "/media/" + upstream + } + return "/media/" + upstream + "?" + forward.Encode() } func (c *Service) thumbnailMediaByQuery(w http.ResponseWriter, r *http.Request) { @@ -911,21 +927,19 @@ func urlPath(value string) string { return value } -// upstreamMediaPath returns the escaped CarrierNode path for a stored file path. It reports false -// when the stored path is not a safe relative path, or when it contains a query or fragment marker -// that CarrierNode would read as the end of the path. +// upstreamMediaPath returns the CarrierNode path for a stored file path. It reports false only when +// the stored path is not a safe relative path. +// +// url.PathEscape would write a comma as %2C, and the request then keeps that escape as a raw path. +// CarrierNode's router matches a raw path literally, so "Hello, World.mp4" would never be found. A +// URL built from Path alone leaves no raw path, so the name reaches CarrierNode decoded. Query and +// fragment markers are escaped the same way, so they no longer need refusing. func upstreamMediaPath(filePath string) (string, bool) { relative := urlPath(filePath) - if !files.SafeRelative(relative) || strings.ContainsAny(relative, "?#") { + if !files.SafeRelative(relative) { return "", false } - // Escape each segment so percent-escapes and other reserved characters in a stored name - // reach CarrierNode as literal text, not as an escape or a traversal it decodes later. - segments := strings.Split(relative, "/") - for i, segment := range segments { - segments[i] = url.PathEscape(segment) - } - return strings.Join(segments, "/"), true + return (&url.URL{Path: relative}).EscapedPath(), true } // canonicalMediaID returns the numeric media id that identifier spells exactly. Leading zeros, signs diff --git a/shared/backend/media/media_test.go b/shared/backend/media/media_test.go index 4c1a8bb..b71a5c0 100644 --- a/shared/backend/media/media_test.go +++ b/shared/backend/media/media_test.go @@ -5,6 +5,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "net/url" "strings" "testing" @@ -124,3 +125,20 @@ func TestOnlyModeratorsCanSeeHiddenMedia(t *testing.T) { } } } + +func TestStreamUpstreamPathForwardsOnlyLiveTranscodeOptions(t *testing.T) { + for _, tc := range []struct { + name string + query url.Values + want string + }{ + {"plain stream", url.Values{"mediaKey": {"abc"}}, "/media/Videos/clip.mp4"}, + {"blank options are dropped", url.Values{"quality": {" "}, "start": {""}}, "/media/Videos/clip.mp4"}, + {"quality and start are forwarded", url.Values{"mediaKey": {"abc"}, "quality": {"1080"}, "start": {" 12.5 "}}, "/media/Videos/clip.mp4?quality=1080&start=12.5"}, + {"quality alone", url.Values{"quality": {"720"}}, "/media/Videos/clip.mp4?quality=720"}, + } { + if got := streamUpstreamPath("Videos/clip.mp4", tc.query); got != tc.want { + t.Errorf("%s: streamUpstreamPath() = %q, want %q", tc.name, got, tc.want) + } + } +} diff --git a/shared/backend/media/paths_test.go b/shared/backend/media/paths_test.go index 52c4db8..13fdf2d 100644 --- a/shared/backend/media/paths_test.go +++ b/shared/backend/media/paths_test.go @@ -1,24 +1,50 @@ package media import ( + "net/http" "testing" ) -func TestUpstreamMediaPathRefusesQueryFragmentAndTraversal(t *testing.T) { - for _, stored := range []string{"x?y.mp4", "a#b.mp4", "../x.mp4", "media/../../x.mp4", `..\x.mp4`} { +func TestUpstreamMediaPathRefusesTraversal(t *testing.T) { + for _, stored := range []string{"../x.mp4", "media/../../x.mp4", `..\x.mp4`} { if _, ok := upstreamMediaPath(stored); ok { t.Errorf("upstreamMediaPath(%q) accepted, want refused", stored) } } } +// CarrierNode's router matches a raw request path literally, so a name must reach it with no raw path: +// a %2C for a comma would never match "Hello, World.mp4". Query and fragment markers are escaped, not refused. +func TestUpstreamMediaPathReachesCarrierNodeAsTheLiteralName(t *testing.T) { + for _, stored := range []string{"Hello, World.mp4", "a;b.mp4", "x?y.mp4", "a#b.mp4", "100%.mp4", "dir one/x y.mp4"} { + upstream, ok := upstreamMediaPath(stored) + if !ok { + t.Fatalf("upstreamMediaPath(%q) refused", stored) + } + request, err := http.NewRequest(http.MethodGet, "http://carrier.example/media/"+upstream, nil) + if err != nil { + t.Fatalf("NewRequest for %q: %v", stored, err) + } + if request.URL.RawPath != "" { + t.Errorf("%q produced raw path %q; CarrierNode would match that instead of the name", stored, request.URL.RawPath) + } + if want := "/media/" + urlPath(stored); request.URL.Path != want { + t.Errorf("%q decodes to %q, want %q", stored, request.URL.Path, want) + } + } +} + 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", + "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", + "Hello, World.mp4": "Hello,%20World.mp4", + "a;b.mp4": "a;b.mp4", + "x?y.mp4": "x%3Fy.mp4", + "a#b.mp4": "a%23b.mp4", } for stored, want := range cases { got, ok := upstreamMediaPath(stored) diff --git a/shared/package-lock.json b/shared/package-lock.json index 2a176f8..889db5c 100644 --- a/shared/package-lock.json +++ b/shared/package-lock.json @@ -1885,9 +1885,9 @@ "peer": true }, "node_modules/@sveltejs/acorn-typescript": { - "version": "1.0.13", - "resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.13.tgz", - "integrity": "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==", + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.11.tgz", + "integrity": "sha512-LFuZUkjJ9iF7JZye/aG5XM0SFcQ5VyL0oVX4WJ9dc0Va3R3s0OauX1BESVCb+YN/ol8TAfqGDDAQsTG627Y5kw==", "license": "MIT", "peerDependencies": { "acorn": "^8.9.0" @@ -2080,6 +2080,12 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT" + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.72.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.0.tgz", @@ -3108,9 +3114,9 @@ } }, "node_modules/esrap": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.4.0.tgz", - "integrity": "sha512-CQPcneEHw/czj32uwQC52nYnax8H4SXt25FCM+LIwGZ49cMIxpOj3bP8wmzcI+Z0HIy5KkClaPhRLfCySzwHPA==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.3.0.tgz", + "integrity": "sha512-GQ/7RN8uOtEfNpzZzBMTzW9JBcX42oaSVtPzdF+6cEL8pqIL094iUpr9jzYGn4O4P/1S60dJ6izyT8F4LYARng==", "license": "MIT", "dependencies": { "@jridgewell/sourcemap-codec": "^1.4.15" @@ -4755,22 +4761,23 @@ } }, "node_modules/svelte": { - "version": "5.57.3", - "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.57.3.tgz", - "integrity": "sha512-5mAftM3SoDV9X0zdF386F9p2pv8iKOwi/KfBS1XnBAkVCKFzVOLHUoa8iGWAt4buoicLmyWVRpuuD5wplXOQsg==", + "version": "5.56.8", + "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.56.8.tgz", + "integrity": "sha512-PY8LOw7xP6c8IOiVqdo0sbbZVYhXRSfklOQLAUyGBKqjTX0wx/z4l/9J+PmBpmlLnxzEb1NqltxQ5/wZme/Cmg==", "license": "MIT", "dependencies": { - "@jridgewell/remapping": "^2.3.5", - "@jridgewell/sourcemap-codec": "^1.6.0", - "@sveltejs/acorn-typescript": "^1.0.13", - "@types/estree": "^1.0.9", - "acorn": "^8.18.0", + "@jridgewell/remapping": "^2.3.4", + "@jridgewell/sourcemap-codec": "^1.5.0", + "@sveltejs/acorn-typescript": "^1.0.10", + "@types/estree": "^1.0.5", + "@types/trusted-types": "^2.0.7", + "acorn": "^8.12.1", "aria-query": "5.3.1", "axobject-query": "^4.1.0", "clsx": "^2.1.1", - "devalue": "^5.9.2", + "devalue": "^5.8.1", "esm-env": "^1.2.1", - "esrap": "^2.3.6", + "esrap": "^2.2.12", "is-reference": "^3.0.3", "locate-character": "^3.0.0", "magic-string": "^0.30.11", @@ -5496,6 +5503,7 @@ "version": "0.1.1", "license": "MIT", "dependencies": { + "@gabriel20xx/design-tokens": "0.1.1", "@lucide/svelte": "1.28.0" }, "devDependencies": { diff --git a/shared/packages/web-ui/src/lib/components/MediaPlayer.svelte b/shared/packages/web-ui/src/lib/components/MediaPlayer.svelte index 1a8bc76..7dc0ee9 100644 --- a/shared/packages/web-ui/src/lib/components/MediaPlayer.svelte +++ b/shared/packages/web-ui/src/lib/components/MediaPlayer.svelte @@ -9,7 +9,7 @@ let { kind = 'video', - src = '', + src, poster = '', title = '', autoplay = false, @@ -35,6 +35,12 @@ onSkip, onQualityChange, onToggleGraph, + storageKey = '', + showSpeed = true, + controls = true, + element = $bindable(null), + preload = 'auto', + crossorigin, endControls, }: { kind?: MediaPlayerKind @@ -66,6 +72,24 @@ onSkip?: (seconds: number) => void onQualityChange?: (value: string) => void onToggleGraph?: () => void + /** + * Turns on resume: the position of each source is saved in localStorage under this prefix and + * restored when the source loads. Give each app its own prefix. Empty (the default) keeps + * playback position out of browser storage. + */ + storageKey?: string + /** Offers the playback speed in the settings menu. */ + showSpeed?: boolean + /** + * False renders the element with no player controls, surface clicks, keyboard handling or + * fullscreen tracking. The caller then drives playback itself, through `element`, and may set + * the element's `src` directly: this component leaves `src` alone when none is passed. + */ + controls?: boolean + /** The media element, once mounted. Cleared when it goes. */ + element?: HTMLMediaElement | null + preload?: 'none' | 'metadata' | 'auto' + crossorigin?: 'anonymous' | 'use-credentials' endControls?: Snippet } = $props() @@ -81,12 +105,19 @@ let orientationLocked = $state(false) let controlsHideTimeout: ReturnType | null = null let orientationLockRequest = 0 + let playbackRate = $state(1) + let lastProgressSaveAt = 0 + const PROGRESS_SAVE_INTERVAL_MS = 1500 const currentTime = $derived(externalCurrentTime ?? internalTime) const duration = $derived(externalDuration ?? internalDuration) const audio = $derived(kind === 'audio') const controlsHideDelay = 2500 + $effect(() => { + element = mediaElement + }) + function clearControlsHideTimer() { if (controlsHideTimeout === null) return clearTimeout(controlsHideTimeout) @@ -195,6 +226,65 @@ skip(event.clientX - bounds.left < bounds.width / 2 ? -10 : 10) } + function progressKey() { + return `${storageKey}:${src}` + } + + function restorePlaybackProgress() { + if (!storageKey || !mediaElement) return + try { + const savedProgress = Number(window.localStorage.getItem(progressKey())) + const length = mediaElement.duration + if ( + Number.isFinite(savedProgress) && + savedProgress > 0 && + Number.isFinite(length) && + length > 0 && + savedProgress < length - 1 + ) { + mediaElement.currentTime = savedProgress + } + } catch { + // Playback remains available when browser storage is disabled or full. + } + } + + function savePlaybackProgress(force = false) { + if (!storageKey || !mediaElement || mediaElement.ended) return + const position = mediaElement.currentTime + if (!Number.isFinite(position)) return + try { + if (position <= 0) { + if (force) window.localStorage.removeItem(progressKey()) + return + } + if (!force && Date.now() - lastProgressSaveAt < PROGRESS_SAVE_INTERVAL_MS) return + lastProgressSaveAt = Date.now() + window.localStorage.setItem(progressKey(), String(position)) + } catch { + // Keep playing when browser storage is disabled or full. + } + } + + function clearPlaybackProgress() { + if (!storageKey) return + try { + window.localStorage.removeItem(progressKey()) + } catch { + // Keep playback completion independent from browser storage. + } + } + + function changeSpeed(value: number) { + if (!Number.isFinite(value) || value <= 0) return + playbackRate = value + if (mediaElement) mediaElement.playbackRate = value + } + + function handleSeeked() { + savePlaybackProgress(true) + } + function handlePlay(event: Event) { playing = true onPlay?.(event) @@ -203,11 +293,13 @@ function handlePause(event: Event) { playing = false controlsVisible = true + savePlaybackProgress(true) onPause?.(event) } function handleTimeUpdate(event: Event) { if (mediaElement) internalTime = mediaElement.currentTime || 0 + savePlaybackProgress() onTimeUpdate?.(event) } @@ -216,13 +308,17 @@ internalDuration = Number.isFinite(mediaElement.duration) ? mediaElement.duration : 0 volume = mediaElement.volume muted = mediaElement.muted || mediaElement.volume === 0 - void syncScreenOrientation(fullscreen) + // Loading a source resets the rate, so the chosen speed is applied again. + mediaElement.playbackRate = playbackRate + restorePlaybackProgress() + if (controls) void syncScreenOrientation(fullscreen) onLoadedMetadata?.(event) } function handleEnded(event: Event) { playing = false controlsVisible = true + clearPlaybackProgress() onEnded?.(event) } @@ -287,6 +383,7 @@ } function handleFullscreenChange() { + if (!controls) return fullscreen = Boolean(document.fullscreenElement) void syncScreenOrientation(fullscreen) } @@ -311,7 +408,7 @@ }) onMount(() => { - if (!playerFrame) return + if (!controls || !playerFrame) return const activityEvents = ['mousemove', 'click', 'keydown', 'focusin', 'touchstart'] as const for (const eventName of activityEvents) playerFrame.addEventListener(eventName, handlePlayerActivity) @@ -329,15 +426,15 @@ -
+
{#if audio}
{#if title}{title}{/if} @@ -346,7 +443,7 @@ bind:this={mediaElement} {src} {autoplay} - preload="auto" + {preload} tabindex="-1" aria-hidden="true" onplay={handlePlay} @@ -355,6 +452,7 @@ onloadedmetadata={handleLoadedMetadata} onended={handleEnded} onvolumechange={handleVolumeChange} + onseeked={handleSeeked} onerror={handleError} > {:else} @@ -366,25 +464,28 @@ {poster} {autoplay} muted={autoplay && autoplayMuted} - preload="auto" + {preload} + {crossorigin} playsinline - tabindex="0" - class={`media-player-video ${mediaClass}`} + tabindex={controls ? 0 : undefined} + class={[controls && 'media-player-video', mediaClass].filter(Boolean).join(' ')} aria-label={title ? `Video player for ${title}` : 'Video player'} - onclick={handleSurfaceClick} - ondblclick={handleVideoDoubleTap} - onkeydown={handleKeydown} + onclick={controls ? handleSurfaceClick : undefined} + ondblclick={controls ? handleVideoDoubleTap : undefined} + onkeydown={controls ? handleKeydown : undefined} onplay={handlePlay} onpause={handlePause} ontimeupdate={handleTimeUpdate} onloadedmetadata={handleLoadedMetadata} onended={handleEnded} onvolumechange={handleVolumeChange} + onseeked={handleSeeked} onerror={handleError} > {/if} + {#if controls} + {/if}