fix(convex): stop leaking song file paths and gate library queries

getSong stays public for share-link previews but no longer returns
files. Streaming routes load paths through getSongSource, which
requires auth and runs with the listener's token. Library browse,
search, and song-ID queries now require a session; album, artist,
and playlist detail plus cover lookups stay public for share links.
Fixes the stale /artists/:id public route in proxy.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
joshuafhigginsandClaude Opus 5.5 committed 2026-11-16 14:10:44 -05:00 Verified
1 parent dce66b7697
commit b8970ce56f
12 files changed
+154 -61

No files matched your search

@@ -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<Metadata> {
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"}`,
+2 -2
View File
@@ -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 })
}
+2 -2
View File
@@ -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 })
}
@@ -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 })
}
+2 -6
View File
@@ -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 =
@@ -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 })
}
+2 -6
View File
@@ -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 { ffmpegToReadableStream, streamFile } from "@/lib/server-audio-stream"
import { NextRequest, NextResponse, userAgent } from "next/server"
import { spawn } from "node:child_process"
@@ -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
+13 -11
View File
@@ -8,6 +8,9 @@ import * as music from "music-metadata"
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<Doc<"songs">, "_id" | "files" | "length">
type HlsJob = {
key: string
lookupKey: string
@@ -36,7 +39,7 @@ export function qualityKbps(quality: string | null) {
}
export function selectHlsSourceCodec(
song: Doc<"songs">,
song: SongSource,
quality: string | null,
preferAtmos: boolean
) {
@@ -62,11 +65,7 @@ function hlsLookupKey(
return `${songId}:${quality ?? ""}:${preferAtmos ? "1" : "0"}`
}
async function hlsJobKey(
song: Doc<"songs">,
sourcePath: string,
kbps: number
) {
async function hlsJobKey(song: SongSource, sourcePath: string, kbps: number) {
const stat = await fs.stat(sourcePath)
return crypto
.createHash("sha256")
@@ -83,14 +82,17 @@ async function hlsJobKey(
}
export function hlsSegmentPath(job: HlsJob, segmentIndex: number) {
return path.join(job.dir, `segment_${segmentIndex.toString().padStart(5, "0")}.ts`)
return path.join(
job.dir,
`segment_${segmentIndex.toString().padStart(5, "0")}.ts`
)
}
async function touchHlsJob(job: HlsJob) {
job.lastTouchedAt = Date.now()
await fs.utimes(job.dir, new Date(job.lastTouchedAt), new Date(job.lastTouchedAt)).catch(
() => {}
)
await fs
.utimes(job.dir, new Date(job.lastTouchedAt), new Date(job.lastTouchedAt))
.catch(() => {})
}
function forgetJob(job: HlsJob) {
@@ -158,7 +160,7 @@ export async function waitForHlsSegment(
}
export async function ensureHlsJob(
song: Doc<"songs">,
song: SongSource,
quality: string | null,
preferAtmos: boolean
) {
+23
View File
@@ -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<SongSource> {
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
}
+1 -1
View File
@@ -12,7 +12,7 @@ const isPublic = createRouteMatcher([
"/api/playlist/:id/cover",
"/album/:id",
"/artist/:id",
"/artists/:id",
"/library/artists/:id",
"/playlist/:id",
])
+79 -11
View File
@@ -41,6 +41,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)
@@ -202,6 +216,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()
@@ -217,6 +234,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)
@@ -244,6 +264,9 @@ export function paginateSlice<T>(
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")
@@ -260,6 +283,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")
@@ -283,6 +309,9 @@ export const browseAlbumsPaginated = query({
export const browseSongs = query({
args: {},
handler: async (ctx) => {
if (!(await isSignedIn(ctx))) {
return []
}
const artistMap = await loadArtistMap(ctx)
const albums = await ctx.db.query("albums").collect()
const albumMap = new Map(albums.map((album) => [album._id, album]))
@@ -481,6 +510,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)
}
@@ -500,6 +532,7 @@ export const browseSortedSongIds = query({
sortDirection: songsSortDirectionValidator,
},
handler: async (ctx, args) => {
await requireSignedIn(ctx)
return getSortedLibrarySongIds(ctx, args.sortKey, args.sortDirection)
},
})
@@ -509,6 +542,7 @@ const MAX_SONGS_BY_IDS = 200
export const browseSongsByIds = query({
args: { ids: v.array(v.id("songs")) },
handler: async (ctx, args): Promise<BrowseSong[]> => {
await requireSignedIn(ctx)
if (args.ids.length > MAX_SONGS_BY_IDS) {
throw new ConvexError(`Request at most ${MAX_SONGS_BY_IDS} songs`)
}
@@ -516,6 +550,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<BrowseAlbumDetail | null> => {
@@ -580,7 +615,8 @@ async function browseAlbumSummaryHandler(
export const browseAlbumSummary = query({
args: { id: v.id("albums") },
handler: async (ctx, args) => browseAlbumSummaryHandler(ctx, args.id),
handler: async (ctx, args) =>
(await isSignedIn(ctx)) ? browseAlbumSummaryHandler(ctx, args.id) : null,
})
export const browseAlbumTracksPaginated = query({
@@ -589,14 +625,17 @@ export const browseAlbumTracksPaginated = query({
paginationOpts: paginationOptsValidator,
},
handler: async (ctx, args) => {
if (!(await isSignedIn(ctx))) {
return EMPTY_PAGE
}
const album = await ctx.db.get("albums", args.albumId)
if (!album) {
return { page: [], isDone: true, continueCursor: "" }
return EMPTY_PAGE
}
const artist = await ctx.db.get("artists", album.artist)
if (!artist) {
return { page: [], isDone: true, continueCursor: "" }
return EMPTY_PAGE
}
const songs = await ctx.db
@@ -611,6 +650,7 @@ export const browseAlbumTracksPaginated = query({
},
})
/** Public: shared /artist links render this without a session. */
export const browseArtistDetail = query({
args: { id: v.id("artists") },
handler: async (ctx, args) => {
@@ -664,7 +704,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: [],
@@ -766,6 +806,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)
@@ -785,6 +828,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")
@@ -945,10 +991,11 @@ export const getSongsInAlbum = 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
},
})
@@ -962,10 +1009,11 @@ export const getArtistByName = internalQuery({
},
})
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
},
})
@@ -991,17 +1039,37 @@ export const getAlbumByAll = internalQuery({
},
})
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 }
},
})
+17 -3
View File
@@ -11,7 +11,13 @@ import type {
PlaylistSummary,
SidebarPlaylists,
} from "./library"
import { browseSongsFromIds, compareAlbumSongs, paginateSlice } from "./library"
import {
browseSongsFromIds,
compareAlbumSongs,
isSignedIn,
paginateSlice,
requireSignedIn,
} from "./library"
function toPlaylistSummary(
playlist: Doc<"playlists">,
@@ -111,9 +117,11 @@ async function browsePlaylistSummaryHandler(
export const browsePlaylistSummary = query({
args: { id: v.id("playlists") },
handler: async (ctx, args) => browsePlaylistSummaryHandler(ctx, args.id),
handler: async (ctx, args) =>
(await isSignedIn(ctx)) ? browsePlaylistSummaryHandler(ctx, args.id) : null,
})
/** Public: shared /playlist links render this without a session. */
export const browsePlaylistDetail = query({
args: { id: v.id("playlists"), includeSongs: v.optional(v.boolean()) },
handler: async (ctx, args): Promise<BrowsePlaylistDetail | null> => {
@@ -145,7 +153,9 @@ export const browsePlaylistSongsPaginated = query({
paginationOpts: paginationOptsValidator,
},
handler: async (ctx, args) => {
const playlist = await ctx.db.get("playlists", args.id)
const playlist = (await isSignedIn(ctx))
? await ctx.db.get("playlists", args.id)
: null
if (!playlist) {
return { page: [], isDone: true, continueCursor: "" }
}
@@ -297,6 +307,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))
@@ -309,6 +320,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))
@@ -320,6 +332,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))
@@ -350,6 +363,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 ?? []
},