diff --git a/design/security.md b/design/security.md index 5335ca85..8295461a 100644 --- a/design/security.md +++ b/design/security.md @@ -13,6 +13,20 @@ What keeps a hostile package in its place: entry names, `untrusted` and the cont can never carry `..` to the worker — the URL parser collapses `..` and `%2e%2e` alike before the request is made. `normalizeRequestPath` still decodes before validating, as defence in depth, but the attack it is named for arrives through the central directory. +- **An entry inflates no further than the size its archive declares, and the worker parses no JSON + over 16 MB.** zip.js refuses an entry that runs past its declared size. The native + `DecompressionStream` knows none, and extractions, the warm and an archive still downloading + inflate with it: `inflated` counts the output, a stored entry's too, and fails it with + `bad-archive` (`heldTo`). Unheld, 65 kB inflates to 64 MB under a declared 10 bytes and is + stored as complete; without end, it fills the store, and each refused write evicts another idle + package. `PackageReader.json` refuses, unread, an `h5p.json` or `library.json` that declares or + carries more than `PARSED_MAX_SIZE`, since parsing holds it whole in the Service Worker and a + few kB inflate to gigabytes; a `content.json` over it is treated as one that cannot be parsed, + and the addon scan passes over such a `library.json`, as over one that does not parse. The + largest `content.json` of 89 real packages is 150 kB. Not bounded: the archive's index, which + zip.js reads whole whatever its entry count, and an entry of an honest, enormous size, which is + a large package like any other and evicts idle ones to fit. `tests/unit/declared-size.test.ts` + holds each path, and `jobs-worker.test.ts` the extraction through the real worker. - **An untrusted package plays as data.** This matches what lets the CMS plugins accept packages from authors: they install library code from an upload only for a user who may update libraries, keep `content/` to a list of file types, and filter every field against the diff --git a/packages/player/src/jobs/jobs-worker.ts b/packages/player/src/jobs/jobs-worker.ts index db0da7db..f2c5e76e 100644 --- a/packages/player/src/jobs/jobs-worker.ts +++ b/packages/player/src/jobs/jobs-worker.ts @@ -399,7 +399,7 @@ async function extractEntry( const stopReporting = reportRunning(handle, pkgId, entryName) try { - await inflated(streamSpan(handle, { start, end }), location.method, location.compressedSize).pipeTo( + await inflated(streamSpan(handle, { start, end }), { ...location, name: entryName }).pipeTo( createChunkWriter({ store, entry: entryName, diff --git a/packages/player/src/jobs/warm.ts b/packages/player/src/jobs/warm.ts index 686e5459..c1acd523 100644 --- a/packages/player/src/jobs/warm.ts +++ b/packages/player/src/jobs/warm.ts @@ -3,7 +3,7 @@ import { WARM_ENTRY, WARM_STALL_MS } from '../shared/constants.js' import { QuotaError, type ChunkStore } from '../shared/chunk-store.js' import { DEFLATE, LOCAL_HEADER_FIXED_SIZE, STORED, localHeaderDataStart } from '../shared/local-header.js' import { contentTypeOf } from '../shared/mime.js' -import type { WarmSpan } from '../shared/protocol.js' +import type { WarmEntry, WarmSpan } from '../shared/protocol.js' import type { SourceHandle } from '../shared/source.js' /** @@ -58,7 +58,7 @@ export async function warmPackage( result.skipped += 1 } else { try { - await store.putWhole(entry.name, () => bodyOf(compressed, entry.method), contentTypeOf(entry.name), entry.size) + await store.putWhole(entry.name, () => bodyOf(compressed, entry), contentTypeOf(entry.name), entry.size) result.stored += 1 } catch (error) { // No room is the end of it: the store is full for the rest of the spans too. @@ -86,8 +86,8 @@ export async function warmPackage( return result } -function bodyOf(compressed: Uint8Array, method: number): ReadableStream { - return inflated(new Blob([compressed]).stream(), method, compressed.length) +function bodyOf(compressed: Uint8Array, entry: WarmEntry): ReadableStream { + return inflated(new Blob([compressed]).stream(), entry) } /** diff --git a/packages/player/src/shared/constants.ts b/packages/player/src/shared/constants.ts index 9b21e41b..ff3b4107 100644 --- a/packages/player/src/shared/constants.ts +++ b/packages/player/src/shared/constants.ts @@ -43,6 +43,12 @@ export const INLINE_MAX_SIZE = 16 * 1024 * 1024 */ export const MEDIA_INLINE_MAX_SIZE = 1024 * 1024 +/** + * The largest JSON entry the Service Worker parses, as parsing holds it whole: a larger one is + * refused unread. Of 89 real packages, the largest `content.json` is 150 kB. + */ +export const PARSED_MAX_SIZE = 16 * 1024 * 1024 + /** * A large span is pulled as ranged requests of this size, `SEGMENT_CONCURRENCY` at once, in order. * Up to 16 MB is held, a deliberate loosening of one chunk in memory, so 4 MB and not 8. diff --git a/packages/player/src/shared/stream-utils.ts b/packages/player/src/shared/stream-utils.ts index 4b74edb6..5571c5b7 100644 --- a/packages/player/src/shared/stream-utils.ts +++ b/packages/player/src/shared/stream-utils.ts @@ -1,4 +1,5 @@ import { STORED } from './local-header.js' +import { PlayerError } from './protocol.js' import type { ByteRange } from './range.js' /** @@ -67,8 +68,27 @@ export function deferredStream(open: () => Promise>): * An entry's bytes as stored, inflated when deflated, by the native codec zip.js would use. The lib * types its input as `BufferSource`, stricter than the views it gets, so the one cast is here. */ -export function inflated(stored: ReadableStream, method: number, compressedSize: number): ReadableStream { - if (method === STORED || compressedSize === 0) return stored +export function inflated( + stored: ReadableStream, + entry: { name: string; method: number; compressedSize: number; size: number } +): ReadableStream { + const held = heldTo(entry.size, entry.name) + if (entry.method === STORED || entry.compressedSize === 0) return stored.pipeThrough(held) const inflate = new DecompressionStream('deflate-raw') as unknown as ReadableWritablePair - return stored.pipeThrough(inflate) + return stored.pipeThrough(inflate).pipeThrough(held) +} + +/** + * Fails a stream that runs past `size`, as zip.js does for what it reads: the native codec knows + * no declared size, and a few MB that inflate without end would fill the store and evict the rest. + */ +function heldTo(size: number, name: string): TransformStream { + let seen = 0 + return new TransformStream({ + transform(chunk, controller) { + seen += chunk.length + if (seen > size) throw new PlayerError('bad-archive', `${name} is longer than the ${size} bytes its archive declares`) + controller.enqueue(chunk) + } + }) } diff --git a/packages/player/src/sw/mount.ts b/packages/player/src/sw/mount.ts index 9f450008..1908a27d 100644 --- a/packages/player/src/sw/mount.ts +++ b/packages/player/src/sw/mount.ts @@ -931,8 +931,7 @@ class VirtualServer { /** An entry's JSON, from the cache when it is there, as every library's is after the warm. */ private async readJson({ reader, entry }: LocatedEntry): Promise { - const cached = await new ChunkStore(reader.pkgId).getWhole(entry.name) - return (cached ?? new Response(reader.inflate(entry))).json() + return reader.json(entry, await new ChunkStore(reader.pkgId).getWhole(entry.name)) } /** Asks the page for a `File` the worker lost on restart, and waits for it to arrive. */ diff --git a/packages/player/src/sw/package-reader.ts b/packages/player/src/sw/package-reader.ts index 27b676bf..f9f6393b 100644 --- a/packages/player/src/sw/package-reader.ts +++ b/packages/player/src/sw/package-reader.ts @@ -1,5 +1,5 @@ import { ZipReader, type Entry, type FileEntry } from '@zip.js/zip.js' -import { BLOCK_CACHE_MAX_READ, INLINE_MAX_SIZE, MEDIA_INLINE_MAX_SIZE, WARM_ENTRY_MAX_SIZE, WARM_GAP, WARM_MAX_BYTES } from '../shared/constants.js' +import { BLOCK_CACHE_MAX_READ, INLINE_MAX_SIZE, MEDIA_INLINE_MAX_SIZE, PARSED_MAX_SIZE, WARM_ENTRY_MAX_SIZE, WARM_GAP, WARM_MAX_BYTES } from '../shared/constants.js' import { indexEntryNames, normalizeEntryName } from '../shared/entry-names.js' import { extensionOf, isMediaEntry, isTextEntry } from '../shared/mime.js' import { DEFLATE, LOCAL_HEADER_FIXED_SIZE, STORED, readDataStart } from '../shared/local-header.js' @@ -681,7 +681,7 @@ export class PackageReader { if (this.contentJson) return this.contentJson const located = this.locate('content/content.json') if (!located || located.reader !== this) return Promise.resolve(undefined) - this.contentJson = new Response(this.inflate(located.entry)).json().catch(() => undefined) + this.contentJson = this.json(located.entry).catch(() => undefined) return this.contentJson } @@ -703,7 +703,7 @@ export class PackageReader { const newest = folders.reduce((a, b) => (b.major > a.major || (b.major === a.major && b.minor > a.minor) ? b : a)) const entry = this.entries.get(`${newest.folder}/library.json`) if (!entry) continue - const patterns = addonPatterns(await new Response(this.inflate(entry)).json().catch(() => null)) + const patterns = addonPatterns(await this.json(entry).catch(() => null)) if (patterns.length > 0) addons.push({ machineName, majorVersion: newest.major, minorVersion: newest.minor, patterns }) } return addons @@ -796,6 +796,18 @@ export class PackageReader { return kept } + /** + * An entry parsed as JSON, from the `cached` copy when there is one. Parsing holds it whole, so + * one over `PARSED_MAX_SIZE` is refused unread: a few kB can inflate to gigabytes. + */ + async json(entry: IndexedEntry, cached?: Response): Promise { + const bytes = parsedSize(entry) + if (bytes > PARSED_MAX_SIZE) { + throw new PlayerError('bad-archive', `${entry.name} is ${bytes} bytes, and the player reads a JSON file of at most ${PARSED_MAX_SIZE}`) + } + return (cached ?? new Response(this.inflate(entry))).json() + } + /** * Inflates an entry into a stream for `cache.put()` or a `Response`, so it is never whole in * memory. A forward entry has no zip.js object behind it, so `DecompressionStream` inflates it. @@ -871,7 +883,7 @@ export class PackageReader { if (entry.compressedSize === 0) return new Blob([]).stream() const raw = deferredStream(() => this.sliceStream(entry, { start: 0, end: entry.compressedSize - 1 })) - return inflated(raw, entry.method, entry.compressedSize) + return inflated(raw, entry) } private async readDataRange(entry: IndexedEntry): Promise { @@ -949,15 +961,25 @@ function topFolderOf(name: string): string | null { return slash < 0 ? null : name.slice(0, slash) } +/** + * What parsing an entry could hold: the larger of what it declares and what the archive carries for + * it, as a stored entry that understates itself has its bytes in the archive all the same. + */ +function parsedSize(entry: IndexedEntry): number { + return Math.max(entry.size, entry.compressedSize) +} + /** `h5p.json` parsed; an unreadable one, or one that is not an object, is a `bad-archive` error. */ async function readManifest(reader: PackageReader): Promise { const { entry } = reader.get('h5p.json')! try { - const parsed = (await new Response(reader.inflate(entry)).json()) as PackageManifest + const parsed = (await reader.json(entry)) as PackageManifest if (!parsed || typeof parsed !== 'object') throw new Error('not an object') return parsed } catch (error) { + // One refused for its size says so itself. + if (error instanceof PlayerError && parsedSize(entry) > PARSED_MAX_SIZE) throw error throw new PlayerError('bad-archive', 'h5p.json is not readable JSON', { cause: error }) } } diff --git a/packages/player/tests/browser/jobs-worker.test.ts b/packages/player/tests/browser/jobs-worker.test.ts index 86c708b2..4b156140 100644 --- a/packages/player/tests/browser/jobs-worker.test.ts +++ b/packages/player/tests/browser/jobs-worker.test.ts @@ -1,7 +1,7 @@ import { FIXTURES } from './utils' import { afterAll, describe, expect, it } from 'vitest' import jobsWorkerSource from 'virtual:h5p-jobs-worker' -import { cacheNameFor } from '../../src/shared/chunk-store' +import { ChunkStore, cacheNameFor } from '../../src/shared/chunk-store' import type { EntryLocation, FromJobsMessage, SourceDescriptor, ToJobsMessage } from '../../src/shared/protocol' import { openSource } from '../../src/shared/source' import { PackageReader, locationOf } from '../../src/sw/package-reader' @@ -134,6 +134,28 @@ describe('the Jobs worker', () => { } }) + it('fails an entry that inflates past the size its archive declares, and keeps none of it', { timeout: 30_000 }, async () => { + const pkgId = 'jobs-worker-declared-size-test' + await caches.delete(cacheNameFor(pkgId)) + const packaged = await rangeSource(FIXTURES.largeDeflated) + const big = 'content/media/big.bin' + const { [big]: location } = await locate(pkgId, packaged, [big]) + const jobs = spawn() + try { + const ended = jobs.next((message) => message.pkgId === pkgId && message.type !== 'progress') + // What the server would say of an archive whose index understates the entry. + jobs.post({ type: 'extract', pkgId, entry: big, location: { ...location, size: 1024 * 1024 }, source: packaged }) + + expect(await ended).toMatchObject({ type: 'failed', entry: big, code: 'bad-archive', message: expect.stringContaining(big) }) + const store = new ChunkStore(pkgId) + expect(await store.getMeta(big)).toMatchObject({ available: 0, complete: false, error: { code: 'bad-archive' } }) + expect(await store.getChunk(big, 0)).toBeUndefined() + } finally { + jobs.dispose() + await caches.delete(cacheNameFor(pkgId)) + } + }) + it('stores a picked File whole when asked to download it, for a Service Worker that cannot read it (#309)', async () => { const pkgId = 'jobs-worker-file-copy-test' await caches.delete(cacheNameFor(pkgId)) diff --git a/packages/player/tests/unit/declared-size.test.ts b/packages/player/tests/unit/declared-size.test.ts new file mode 100644 index 00000000..3a3d6d1f --- /dev/null +++ b/packages/player/tests/unit/declared-size.test.ts @@ -0,0 +1,206 @@ +import { beforeAll, describe, expect, it } from 'vitest' +import { createChunkWriter } from '../../src/jobs/chunk-writer' +import type { ChunkStore } from '../../src/shared/chunk-store' +import { PARSED_MAX_SIZE } from '../../src/shared/constants' +import { LocalHeaderScanner } from '../../src/shared/forward-index' +import { inflated } from '../../src/shared/stream-utils' +import { PackageReader } from '../../src/sw/package-reader' +import { declaring, manifest, memoryHandle, zipOf, type Files } from './helpers/archives' + +/** + * A hostile archive's sizes: an entry that inflates past the size it declares, on each path that + * inflates one, and a JSON file too large to parse in the worker's memory. + */ + +const MB = 1024 * 1024 +const packageWith = (extra: Files) => + zipOf({ + 'h5p.json': manifest('H5P.A', [['H5P.A', 1, 0]]), + 'H5P.A-1.0/library.json': '{}', + 'content/content.json': '{}', + ...extra + }) + +/** Bytes deflated raw, with the web's codec: the file then needs none of Node's types. */ +const deflated = async (bytes: Uint8Array) => + new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(new CompressionStream('deflate-raw'))).arrayBuffer()) + +/** Bytes a stream gave before it ended or failed, and the failure. */ +async function drained(stream: ReadableStream) { + const reader = stream.getReader() + let bytes = 0 + try { + for (;;) { + const { done, value } = await reader.read() + if (done) return { bytes, error: null } + bytes += value.length + } + } catch (error) { + return { bytes, error: error as Error } + } +} + +describe('an entry that inflates past the size it declares', () => { + let bomb: Uint8Array + let lying: { name: string; method: number; compressedSize: number; size: number } + beforeAll(async () => { + bomb = await deflated(new Uint8Array(64 * MB).fill(97)) + lying = { name: 'content/videos/v.mp4', method: 8, compressedSize: bomb.length, size: MB } + }) + + it('is cut off at that size by the native inflate, which knows none', async () => { + const { bytes, error } = await drained(inflated(new Blob([bomb]).stream(), lying)) + + expect(error).toMatchObject({ code: 'bad-archive', message: expect.stringContaining('content/videos/v.mp4') }) + expect(bytes).toBeLessThanOrEqual(MB) + }) + + it('is cut off as well when it is stored, with more bytes than it declares', async () => { + const stored = { name: 'content/notes.txt', method: 0, compressedSize: 4 * MB, size: 10 } + const { bytes, error } = await drained(inflated(new Blob([new Uint8Array(4 * MB)]).stream(), stored)) + + expect(error).toMatchObject({ code: 'bad-archive', message: expect.stringContaining('content/notes.txt') }) + expect(bytes).toBeLessThanOrEqual(10) + }) + + it('passes whole when it inflates to what it declares', async () => { + const honest = { ...lying, size: 64 * MB } + + expect(await drained(inflated(new Blob([bomb]).stream(), honest))).toEqual({ bytes: 64 * MB, error: null }) + }) + + it('never becomes a complete entry in the chunk store', async () => { + const metas: Array<{ available: number; complete: boolean }> = [] + let stored = 0 + const store = { + putChunk: async (_entry: string, _index: number, bytes: Uint8Array) => void (stored += bytes.length), + setMeta: async (_entry: string, meta: { available: number; complete: boolean }) => void metas.push(meta) + } as unknown as ChunkStore + + await expect( + inflated(new Blob([bomb]).stream(), lying).pipeTo(createChunkWriter({ store, entry: lying.name, totalSize: lying.size })) + ).rejects.toMatchObject({ code: 'bad-archive' }) + expect(metas.some((meta) => meta.complete)).toBe(false) + // Partial chunks are rewritten as they fill, so what was put is about twice what arrived. + expect(stored).toBeLessThanOrEqual(2 * MB) + }) + + it('is refused by a reader over the central directory, where zip.js inflates', async () => { + const bytes = declaring(await packageWith({ 'content/notes.txt': 'a'.repeat(8 * MB) }), 'content/notes.txt', 10) + const reader = await PackageReader.open('pkg', memoryHandle(bytes).handle) + const { entry } = reader.get('content/notes.txt')! + expect(entry.size).toBe(10) + + const { bytes: given, error } = await drained(reader.inflate(entry)) + // zip.js's own refusal: the reader adds no check of its own on this path. + expect(error?.message).toBe('Invalid uncompressed size') + expect(given).toBeLessThanOrEqual(10) + }) + + it('is refused by a reader over an archive still downloading', async () => { + const bytes = declaring(await packageWith({ 'content/notes.txt': 'a'.repeat(8 * MB) }), 'content/notes.txt', 10) + const scanner = new LocalHeaderScanner() + scanner.push(bytes) + const reader = await PackageReader.fromForwardIndex('pkg', memoryHandle(bytes).handle, scanner.snapshot()) + expect(reader.partial).toBe(true) + + const { bytes: given, error } = await drained(reader.inflate(reader.get('content/notes.txt')!.entry)) + expect(error).toMatchObject({ code: 'bad-archive' }) + expect(given).toBeLessThanOrEqual(10) + }) +}) + +describe('a JSON file larger than the worker parses', () => { + const oversized = (json: string) => ' '.repeat(PARSED_MAX_SIZE) + json + + it('fails the package when it is h5p.json, and says the limit', async () => { + const bytes = await zipOf({ + 'h5p.json': oversized(manifest('H5P.A', [['H5P.A', 1, 0]])), + 'H5P.A-1.0/library.json': '{}', + 'content/content.json': '{}' + }) + // A few kB of archive for 16 MB of JSON. + expect(bytes.length).toBeLessThan(64 * 1024) + + await expect(PackageReader.open('pkg', memoryHandle(bytes).handle)).rejects.toMatchObject({ + code: 'bad-archive', + message: expect.stringMatching(/h5p\.json is \d+ bytes.*at most 16777216/) + }) + }) + + it('is refused unread when it is a library.json', async () => { + const bytes = await packageWith({ 'H5P.B-1.0/library.json': oversized('{}') }) + const { handle, streams } = memoryHandle(bytes) + const reader = await PackageReader.open('pkg', handle) + const before = streams.length + + await expect(reader.json(reader.get('H5P.B-1.0/library.json')!.entry)).rejects.toMatchObject({ code: 'bad-archive' }) + expect(streams.length).toBe(before) + }) + + it('leaves the content’s libraries unread when it is content.json, as one that cannot be parsed does', async () => { + const bytes = await zipOf({ + 'h5p.json': manifest('H5P.A', [['H5P.A', 1, 0]]), + 'H5P.A-1.0/library.json': '{}', + 'content/content.json': oversized('{"library":"H5P.B 1.0"}') + }) + const reader = await PackageReader.open('pkg', memoryHandle(bytes).handle) + + expect(await reader.contentParameters()).toBeUndefined() + }) + + it('is read no further than it declares, so a stored one that carries more is refused by either reader', async () => { + const json = '{"a":1}' + const packaged = await zipOf( + { + 'h5p.json': manifest('H5P.A', [['H5P.A', 1, 0]]), + 'H5P.A-1.0/library.json': '{}', + 'content/content.json': '{}', + 'H5P.B-1.0/library.json': json + ' '.repeat(1000) + }, + { stored: ['H5P.B-1.0/library.json'] } + ) + const bytes = declaring(packaged, 'H5P.B-1.0/library.json', json.length) + const scanner = new LocalHeaderScanner() + scanner.push(bytes) + const central = await PackageReader.open('pkg', memoryHandle(bytes).handle) + const partial = await PackageReader.fromForwardIndex('pkg', memoryHandle(bytes).handle, scanner.snapshot()) + + for (const reader of [central, partial]) { + const { entry } = reader.get('H5P.B-1.0/library.json')! + expect(entry).toMatchObject({ method: 0, size: json.length, compressedSize: json.length + 1000 }) + await expect(reader.json(entry)).rejects.toThrow(/uncompressed size|longer than the 7 bytes/) + } + }) + + it('is refused unread when it is stored and carries more than the limit, whatever it declares', async () => { + const packaged = await zipOf( + { + 'h5p.json': manifest('H5P.A', [['H5P.A', 1, 0]]), + 'H5P.A-1.0/library.json': '{}', + 'content/content.json': '{}', + 'H5P.B-1.0/library.json': oversized('{}') + }, + { stored: ['H5P.B-1.0/library.json'] } + ) + const { handle, reads, streams } = memoryHandle(declaring(packaged, 'H5P.B-1.0/library.json', 2)) + const reader = await PackageReader.open('pkg', handle) + const { entry } = reader.get('H5P.B-1.0/library.json')! + expect(entry).toMatchObject({ method: 0, size: 2, compressedSize: PARSED_MAX_SIZE + 2 }) + const before = [reads.length, streams.length] + + await expect(reader.json(entry)).rejects.toMatchObject({ + code: 'bad-archive', + message: expect.stringContaining(`is ${PARSED_MAX_SIZE + 2} bytes`) + }) + expect([reads.length, streams.length]).toEqual(before) + }) + + it('is parsed at the limit', async () => { + const json = '{"a":1}' + const bytes = await packageWith({ 'H5P.B-1.0/library.json': ' '.repeat(PARSED_MAX_SIZE - json.length) + json }) + const reader = await PackageReader.open('pkg', memoryHandle(bytes).handle) + + expect(await reader.json(reader.get('H5P.B-1.0/library.json')!.entry)).toEqual({ a: 1 }) + }) +}) diff --git a/packages/player/tests/unit/helpers/archives.ts b/packages/player/tests/unit/helpers/archives.ts index 71e3be05..3e0bbdb5 100644 --- a/packages/player/tests/unit/helpers/archives.ts +++ b/packages/player/tests/unit/helpers/archives.ts @@ -59,3 +59,22 @@ export const manifest = (mainLibrary: string, deps: Array<[string, number, numbe export const collect = async (stream: ReadableStream) => new Uint8Array(await new Response(stream).arrayBuffer()) + +/** + * The archive with `name` declaring `size` as its inflated size, in its local header and the + * central directory alike: what a corrupt writer, or a hostile one, leaves behind. + */ +export function declaring(bytes: Uint8Array, name: string, size: number): Uint8Array { + const out = bytes.slice() + const view = new DataView(out.buffer) + const wanted = new TextEncoder().encode(name) + for (let at = 0; at + 46 <= out.length; at += 1) { + if (view.getUint32(at, true) !== 0x02014b50) continue + const stored = out.subarray(at + 46, at + 46 + view.getUint16(at + 28, true)) + if (stored.length !== wanted.length || !stored.every((byte, i) => byte === wanted[i])) continue + view.setUint32(at + 24, size, true) + view.setUint32(view.getUint32(at + 42, true) + 22, size, true) + return out + } + throw new Error(`No ${name} in the archive`) +} diff --git a/packages/player/tests/unit/warm.test.ts b/packages/player/tests/unit/warm.test.ts index 845c06c5..fa88eeb0 100644 --- a/packages/player/tests/unit/warm.test.ts +++ b/packages/player/tests/unit/warm.test.ts @@ -146,6 +146,19 @@ describe('warmPackage', () => { expect(await store.getWhole(WARM_ENTRY)).toBeUndefined() }) + it('passes over an entry that inflates past the size the index gave, and lands the rest', async () => { + vi.stubGlobal('caches', fakeCaches()) + const { handle, spans } = await indexed() + const store = new ChunkStore('pkg') + spans[0].entries.find((entry) => entry.name === 'H5P.A-1.0/a.js')!.size = 10 + + const result = await warmPackage(handle, spans, store, { signal: new AbortController().signal }) + + expect(result).toEqual({ stored: 6, skipped: 1, complete: true }) + expect(await store.getWhole('H5P.A-1.0/a.js')).toBeUndefined() + expect(await (await store.getWhole('H5P.B-1.0/b.js'))?.text()).toBe(script) + }) + it('abandons a span whose bytes are not where the index said, and writes no marker', async () => { vi.stubGlobal('caches', fakeCaches()) const { handle, spans } = await indexed()