From 5c94c45b69be666d96987f39852d1c44b27223e6 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 21:53:43 -0500 Subject: [PATCH] fix(convex): stop leaking song file paths and gate library queries (#99) --- .../app/(app)/library/artists/[id]/page.tsx | 11 +-- apps/web/app/api/album/[id]/cover/route.ts | 4 +- apps/web/app/api/artist/[id]/cover/route.ts | 4 +- apps/web/app/api/playlist/[id]/cover/route.ts | 4 +- apps/web/app/api/song/[id]/play/hls/route.ts | 8 +- .../[id]/play/hls/segment/[segment]/route.ts | 17 ++-- apps/web/app/api/song/[id]/play/route.ts | 8 +- apps/web/lib/server-hls.ts | 11 ++- apps/web/lib/server-song.ts | 23 ++++++ apps/web/proxy.ts | 2 +- packages/convex/convex/library.ts | 77 +++++++++++++++++-- packages/convex/convex/playlists.ts | 11 ++- 12 files changed, 131 insertions(+), 49 deletions(-) create mode 100644 apps/web/lib/server-song.ts diff --git a/apps/web/app/(app)/library/artists/[id]/page.tsx b/apps/web/app/(app)/library/artists/[id]/page.tsx index 289e0e2..862ad7b 100644 --- a/apps/web/app/(app)/library/artists/[id]/page.tsx +++ b/apps/web/app/(app)/library/artists/[id]/page.tsx @@ -1,6 +1,7 @@ import { fetchQuery } from "convex/nextjs" import { convexServerOptions } from "@/lib/convex-server" import { api } from "@otunes/convex/_generated/api" +import type { Id } from "@otunes/convex/_generated/dataModel" import { Metadata } from "next" interface PageProps { @@ -11,12 +12,12 @@ export async function generateMetadata({ params, }: PageProps): Promise { const { id } = await params - const artists = await fetchQuery( - api.library.browseArtists, - {}, + const detail = await fetchQuery( + api.library.browseArtistDetail, + { id: id as Id<"artists"> }, convexServerOptions() - ) - const selectedArtist = artists.find((artist) => artist.id === id) + ).catch(() => null) + const selectedArtist = detail?.artist return { title: `${selectedArtist ? `${selectedArtist.name}` : "oTunes"}`, diff --git a/apps/web/app/api/album/[id]/cover/route.ts b/apps/web/app/api/album/[id]/cover/route.ts index 358cbf5..0bcacd3 100644 --- a/apps/web/app/api/album/[id]/cover/route.ts +++ b/apps/web/app/api/album/[id]/cover/route.ts @@ -10,10 +10,10 @@ export async function GET( const { id } = await params try { - const album = await getConvexClient().query(api.library.getAlbum, { + const cover = await getConvexClient().query(api.library.getAlbumCover, { id: id as Id<"albums">, }) - return serveCoverFile(album?.cover, request) + return serveCoverFile(cover, request) } catch { return new Response("Not found", { status: 404 }) } diff --git a/apps/web/app/api/artist/[id]/cover/route.ts b/apps/web/app/api/artist/[id]/cover/route.ts index 5cc988f..f038486 100644 --- a/apps/web/app/api/artist/[id]/cover/route.ts +++ b/apps/web/app/api/artist/[id]/cover/route.ts @@ -10,10 +10,10 @@ export async function GET( const { id } = await params try { - const artist = await getConvexClient().query(api.library.getArtist, { + const cover = await getConvexClient().query(api.library.getArtistCover, { id: id as Id<"artists">, }) - return serveCoverFile(artist?.cover, request) + return serveCoverFile(cover, request) } catch { return new Response("Not found", { status: 404 }) } diff --git a/apps/web/app/api/playlist/[id]/cover/route.ts b/apps/web/app/api/playlist/[id]/cover/route.ts index 1fab4b8..5cb6d26 100644 --- a/apps/web/app/api/playlist/[id]/cover/route.ts +++ b/apps/web/app/api/playlist/[id]/cover/route.ts @@ -9,10 +9,10 @@ export async function GET( ) { const { id } = await params try { - const playlist = await getConvexClient().query(api.library.getPlaylist, { + const cover = await getConvexClient().query(api.library.getPlaylistCover, { id: id as Id<"playlists">, }) - return serveCoverFile(playlist?.cover, request) + return serveCoverFile(cover, request) } catch { return new Response("Not found", { status: 404 }) } diff --git a/apps/web/app/api/song/[id]/play/hls/route.ts b/apps/web/app/api/song/[id]/play/hls/route.ts index 103b9f0..b256834 100644 --- a/apps/web/app/api/song/[id]/play/hls/route.ts +++ b/apps/web/app/api/song/[id]/play/hls/route.ts @@ -1,6 +1,4 @@ -import { api } from "@otunes/convex/_generated/api" -import type { Id } from "@otunes/convex/_generated/dataModel" -import { getConvexClient } from "@/lib/convex-server" +import { getSongSource } from "@/lib/server-song" import { ensureHlsJob, HLS_SEGMENT_SECONDS } from "@/lib/server-hls" import { NextRequest } from "next/server" @@ -17,9 +15,7 @@ export async function GET( const { id } = await params try { - const song = (await getConvexClient().query(api.library.getSong, { - id: id as Id<"songs">, - }))! + const song = await getSongSource(id) const quality = request.nextUrl.searchParams.get("quality") const preferAtmos = diff --git a/apps/web/app/api/song/[id]/play/hls/segment/[segment]/route.ts b/apps/web/app/api/song/[id]/play/hls/segment/[segment]/route.ts index 0346b57..597f68d 100644 --- a/apps/web/app/api/song/[id]/play/hls/segment/[segment]/route.ts +++ b/apps/web/app/api/song/[id]/play/hls/segment/[segment]/route.ts @@ -1,6 +1,4 @@ -import { api } from "@otunes/convex/_generated/api" -import type { Id } from "@otunes/convex/_generated/dataModel" -import { getConvexClient } from "@/lib/convex-server" +import { getSongSource } from "@/lib/server-song" import { ensureHlsJob, getExistingHlsJob, @@ -36,16 +34,11 @@ export async function GET( const quality = request.nextUrl.searchParams.get("quality") const preferAtmos = request.nextUrl.searchParams.get("preferAtmos") === "true" - const existingJob = getExistingHlsJob(id, quality, preferAtmos) + // Resolve the source even when a job is cached so every segment is authorized. + const song = await getSongSource(id) const job = - existingJob ?? - (await ensureHlsJob( - (await getConvexClient().query(api.library.getSong, { - id: id as Id<"songs">, - }))!, - quality, - preferAtmos - )) + getExistingHlsJob(id, quality, preferAtmos) ?? + (await ensureHlsJob(song, quality, preferAtmos)) if (segmentIndex >= job.segmentCount) { return new Response("Segment not found", { status: 404 }) } diff --git a/apps/web/app/api/song/[id]/play/route.ts b/apps/web/app/api/song/[id]/play/route.ts index 0c5e73e..b757658 100644 --- a/apps/web/app/api/song/[id]/play/route.ts +++ b/apps/web/app/api/song/[id]/play/route.ts @@ -1,8 +1,6 @@ -import { api } from "@otunes/convex/_generated/api" -import type { Id } from "@otunes/convex/_generated/dataModel" import { audioContentTypeForPath } from "@/lib/audio-content-type" import { seekableLosslessFile } from "@/lib/server-lossless" -import { getConvexClient } from "@/lib/convex-server" +import { getSongSource } from "@/lib/server-song" import { audioInfo } from "@/lib/server-audio-info" import { ffmpegToReadableStream, streamFile } from "@/lib/server-audio-stream" import { spawnFfmpeg } from "@/lib/server-ffmpeg" @@ -118,9 +116,7 @@ export async function GET( const { browser } = userAgent(request) try { - const song = (await getConvexClient().query(api.library.getSong, { - id: id as Id<"songs">, - }))! + const song = await getSongSource(id) const quality = request.nextUrl.searchParams.get("quality") as "low" | "medium" | "high" | "lossless" | null diff --git a/apps/web/lib/server-hls.ts b/apps/web/lib/server-hls.ts index 4e9682d..50d84d1 100644 --- a/apps/web/lib/server-hls.ts +++ b/apps/web/lib/server-hls.ts @@ -15,6 +15,9 @@ import { spawnFfmpeg, type FfmpegProcess } from "@/lib/server-ffmpeg" export const HLS_SEGMENT_SECONDS = 6 const HLS_MAX_IDLE_MS = 30 * 60 * 1000 +/** The server-only slice of a song needed to transcode it. */ +export type SongSource = Pick, "_id" | "files" | "length"> + type HlsJob = { key: string lookupKey: string @@ -60,7 +63,7 @@ export function qualityKbps(quality: string | null) { } export function selectHlsSourceCodec( - song: Doc<"songs">, + song: SongSource, quality: string | null, preferAtmos: boolean ) { @@ -83,7 +86,7 @@ function hlsLookupKey( } async function hlsJobKey( - song: Doc<"songs">, + song: SongSource, sourcePath: string, kbps: number ) { @@ -250,7 +253,7 @@ function startTranscode(job: HlsJob, sourcePath: string, kbps: number) { } async function createHlsJob( - song: Doc<"songs">, + song: SongSource, sourcePath: string, kbps: number, key: string, @@ -296,7 +299,7 @@ async function createHlsJob( } export async function ensureHlsJob( - song: Doc<"songs">, + song: SongSource, quality: string | null, preferAtmos: boolean ): Promise { diff --git a/apps/web/lib/server-song.ts b/apps/web/lib/server-song.ts new file mode 100644 index 0000000..d0ff651 --- /dev/null +++ b/apps/web/lib/server-song.ts @@ -0,0 +1,23 @@ +import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server" +import { api } from "@otunes/convex/_generated/api" +import type { Id } from "@otunes/convex/_generated/dataModel" +import { fetchQuery } from "convex/nextjs" +import { convexServerOptions } from "@/lib/convex-server" +import type { SongSource } from "@/lib/server-hls" + +/** + * Loads a song's file paths as the requesting listener, so Convex enforces auth + * even if the proxy is bypassed. Throws when signed out or the song is missing. + */ +export async function getSongSource(id: string): Promise { + const token = await convexAuthNextjsToken() + const song = await fetchQuery( + api.library.getSongSource, + { id: id as Id<"songs"> }, + convexServerOptions(token) + ) + if (!song) { + throw new Error("Song not found") + } + return song +} diff --git a/apps/web/proxy.ts b/apps/web/proxy.ts index 342af0d..f9ad380 100644 --- a/apps/web/proxy.ts +++ b/apps/web/proxy.ts @@ -12,7 +12,7 @@ const isPublic = createRouteMatcher([ "/api/playlist/:id/cover", "/album/:id", "/artist/:id", - "/artists/:id", + "/library/artists/:id", "/playlist/:id", ]) diff --git a/packages/convex/convex/library.ts b/packages/convex/convex/library.ts index 65a2a23..acb9970 100644 --- a/packages/convex/convex/library.ts +++ b/packages/convex/convex/library.ts @@ -39,6 +39,20 @@ export type { SidebarPlaylists, } from "./types" +const EMPTY_PAGE = { page: [], isDone: true, continueCursor: "" } + +/** Reactive queries return empty data when signed out so sign-out doesn't throw mid-render. */ +export async function isSignedIn(ctx: QueryCtx) { + return (await getAuthUserId(ctx)) !== null +} + +/** Imperative lookups throw instead, so callers that cache results don't cache an empty one. */ +export async function requireSignedIn(ctx: QueryCtx) { + if (!(await isSignedIn(ctx))) { + throw new ConvexError("Not authenticated") + } +} + function getSongArtistNames(artist: string | string[]): string[] { if (Array.isArray(artist)) { return artist.map((name) => name.trim()).filter((name) => name.length > 0) @@ -200,6 +214,9 @@ function toBrowseSong( export const browseAlbums = query({ args: {}, handler: async (ctx) => { + if (!(await isSignedIn(ctx))) { + return [] + } const artistMap = await loadArtistMap(ctx) const albums = await ctx.db.query("albums").collect() @@ -215,6 +232,9 @@ export const browseAlbums = query({ export const browseArtists = query({ args: {}, handler: async (ctx) => { + if (!(await isSignedIn(ctx))) { + return [] + } const artists = await ctx.db.query("artists").collect() return artists .map(toBrowseArtist) @@ -242,6 +262,9 @@ function paginateSlice( export const browseArtistsPaginated = query({ args: { paginationOpts: paginationOptsValidator }, handler: async (ctx, args) => { + if (!(await isSignedIn(ctx))) { + return EMPTY_PAGE + } const result = await ctx.db .query("artists") .withIndex("by_name") @@ -258,6 +281,9 @@ export const browseArtistsPaginated = query({ export const browseAlbumsPaginated = query({ args: { paginationOpts: paginationOptsValidator }, handler: async (ctx, args) => { + if (!(await isSignedIn(ctx))) { + return EMPTY_PAGE + } const result = await ctx.db .query("albums") .withIndex("by_name") @@ -458,6 +484,9 @@ export const browseSongsPaginated = query({ sortDirection: songsSortDirectionValidator, }, handler: async (ctx, args) => { + if (!(await isSignedIn(ctx))) { + return EMPTY_PAGE + } if (args.sortKey === "title") { return paginateSongsByTitle(ctx, args.paginationOpts, args.sortDirection) } @@ -477,6 +506,7 @@ export const browseSortedSongIds = query({ sortDirection: songsSortDirectionValidator, }, handler: async (ctx, args) => { + await requireSignedIn(ctx) return getSortedLibrarySongIds(ctx, args.sortKey, args.sortDirection) }, }) @@ -486,6 +516,7 @@ const MAX_SONGS_BY_IDS = 200 export const browseSongsByIds = query({ args: { ids: v.array(v.id("songs")) }, handler: async (ctx, args): Promise => { + await requireSignedIn(ctx) if (args.ids.length > MAX_SONGS_BY_IDS) { throw new ConvexError(`Request at most ${MAX_SONGS_BY_IDS} songs`) } @@ -493,6 +524,7 @@ export const browseSongsByIds = query({ }, }) +/** Public: shared /album links render this without a session. */ export const browseAlbumDetail = query({ args: { id: v.id("albums") }, handler: async (ctx, args): Promise => { @@ -522,6 +554,7 @@ export const browseAlbumDetail = query({ }, }) +/** Public: shared /artist links render this without a session. */ export const browseArtistDetail = query({ args: { id: v.id("artists") }, handler: async (ctx, args) => { @@ -575,7 +608,7 @@ export const searchLibrary = query({ args: { query: v.string() }, handler: async (ctx, args) => { const queryText = args.query.trim().toLowerCase() - if (!queryText) { + if (!queryText || !(await isSignedIn(ctx))) { return { topResults: [], artists: [], @@ -677,6 +710,9 @@ export const searchLibrary = query({ export const browseRecentlyAdded = query({ args: { limit: v.optional(v.number()) }, handler: async (ctx, args) => { + if (!(await isSignedIn(ctx))) { + return [] + } const albumQuery = ctx.db.query("albums").order("desc") const albums = args.limit ? await albumQuery.take(args.limit) @@ -696,6 +732,9 @@ export const browseRecentlyAdded = query({ export const browseRecentlyAddedPaginated = query({ args: { paginationOpts: paginationOptsValidator }, handler: async (ctx, args) => { + if (!(await isSignedIn(ctx))) { + return EMPTY_PAGE + } const result = await ctx.db .query("albums") .order("desc") @@ -826,31 +865,53 @@ export const getSongs = internalQuery({ }, }) -export const getArtist = query({ +/** Public: share-link previews load covers without a session. */ +export const getArtistCover = query({ args: { id: v.id("artists") }, handler: async (ctx, args) => { - return await ctx.db.get("artists", args.id) + return (await ctx.db.get("artists", args.id))?.cover ?? null }, }) -export const getAlbum = query({ +/** Public: share-link previews load covers without a session. */ +export const getAlbumCover = query({ args: { id: v.id("albums") }, handler: async (ctx, args) => { - return await ctx.db.get("albums", args.id) + return (await ctx.db.get("albums", args.id))?.cover ?? null }, }) -export const getPlaylist = query({ +/** Public: share-link previews load covers without a session. */ +export const getPlaylistCover = query({ args: { id: v.id("playlists") }, handler: async (ctx, args) => { - return await ctx.db.get("playlists", args.id) + return (await ctx.db.get("playlists", args.id))?.cover ?? null }, }) +/** Public: share-link previews read song metadata without a session. Never returns file paths. */ export const getSong = query({ args: { id: v.id("songs") }, handler: async (ctx, args) => { - return await ctx.db.get("songs", args.id) + const song = await ctx.db.get("songs", args.id) + if (!song) { + return null + } + const { files: _files, ...clientSong } = song + return clientSong + }, +}) + +/** Returns absolute file paths. Only the web streaming routes call this, as the listener. */ +export const getSongSource = query({ + args: { id: v.id("songs") }, + handler: async (ctx, args) => { + await requireSignedIn(ctx) + const song = await ctx.db.get("songs", args.id) + if (!song) { + return null + } + return { _id: song._id, files: song.files, length: song.length } }, }) diff --git a/packages/convex/convex/playlists.ts b/packages/convex/convex/playlists.ts index c763a67..dd34f42 100644 --- a/packages/convex/convex/playlists.ts +++ b/packages/convex/convex/playlists.ts @@ -10,7 +10,11 @@ import type { PlaylistSummary, SidebarPlaylists, } from "./library" -import { browseSongsFromIds, compareAlbumSongs } from "./library" +import { + browseSongsFromIds, + compareAlbumSongs, + requireSignedIn, +} from "./library" function toPlaylistSummary( playlist: Doc<"playlists">, @@ -108,6 +112,7 @@ async function browsePlaylistSummaryHandler( } } +/** Public: shared /playlist links render this without a session. */ export const browsePlaylistDetail = query({ args: { id: v.id("playlists") }, handler: async (ctx, args): Promise => { @@ -267,6 +272,7 @@ export const listAllPlaylists = query({ export const getAlbumSongIds = query({ args: { albumId: v.id("albums") }, handler: async (ctx, args) => { + await requireSignedIn(ctx) const songs = await ctx.db .query("songs") .withIndex("by_album", (q) => q.eq("album", args.albumId)) @@ -279,6 +285,7 @@ export const getAlbumSongIds = query({ export const getArtistSongIds = query({ args: { artistId: v.id("artists") }, handler: async (ctx, args) => { + await requireSignedIn(ctx) const songs = await ctx.db .query("songs") .withIndex("by_artist", (q) => q.eq("albumArtist", args.artistId)) @@ -290,6 +297,7 @@ export const getArtistSongIds = query({ export const getOrderedArtistSongIds = query({ args: { artistId: v.id("artists") }, handler: async (ctx, args) => { + await requireSignedIn(ctx) const songs = await ctx.db .query("songs") .withIndex("by_artist", (q) => q.eq("albumArtist", args.artistId)) @@ -320,6 +328,7 @@ export const getOrderedArtistSongIds = query({ export const getPlaylistSongIds = query({ args: { playlistId: v.id("playlists") }, handler: async (ctx, args) => { + await requireSignedIn(ctx) const playlist = await ctx.db.get("playlists", args.playlistId) return playlist?.songs ?? [] },