1 import { Segment } from 'p2p-media-loader-core'
2 import { basename } from 'path'
4 function segmentValidatorFactory (segmentsSha256Url: string) {
5 const segmentsJSON = fetchSha256Segments(segmentsSha256Url)
7 return async function segmentValidator (segment: Segment) {
8 const segmentName = basename(segment.url)
10 const hashShouldBe = (await segmentsJSON)[segmentName]
11 if (hashShouldBe === undefined) {
12 throw new Error(`Unknown segment name ${segmentName} in segment validator`)
15 const calculatedSha = bufferToEx(await sha256(segment.data))
16 if (calculatedSha !== hashShouldBe) {
17 throw new Error(`Hashes does not correspond for segment ${segmentName} (expected: ${hashShouldBe} instead of ${calculatedSha})`)
22 // ---------------------------------------------------------------------------
25 segmentValidatorFactory
28 // ---------------------------------------------------------------------------
30 function fetchSha256Segments (url: string) {
32 .then(res => res.json())
34 console.error('Cannot get sha256 segments', err)
39 function sha256 (data?: ArrayBuffer) {
40 if (!data) return undefined
42 return window.crypto.subtle.digest('SHA-256', data)
45 // Thanks: https://stackoverflow.com/a/53307879
46 function bufferToEx (buffer?: ArrayBuffer) {
47 if (!buffer) return ''
50 const h = '0123456789abcdef'
51 const o = new Uint8Array(buffer)
53 o.forEach((v: any) => s += h[ v >> 4 ] + h[ v & 15 ])