All files / web/src/lib/kid-songs audio.ts

0% Statements 0/18
0% Branches 0/1
0% Functions 0/1
0% Lines 0/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19                                     
import { createHash } from 'node:crypto'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { isValidId } from './eligibility'

export const SONGS_DIR = join(process.cwd(), 'data', 'audio', 'songs')

export interface HashedSong {
  bytes: Buffer
  sha256: string
}

export async function readAndHashSong(songId: string): Promise<HashedSong> {
  if (!isValidId(songId)) throw new Error('Invalid song ID')
  // The ID guard is the path-traversal boundary for this ID-derived path.
  const bytes = await readFile(join(SONGS_DIR, `${songId}.mp3`))
  return { bytes, sha256: createHash('sha256').update(bytes).digest('hex') }
}