From 6a41077e4558005ead2e794f8ec3463d2a601244 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Wed, 4 Nov 2026 18:58:34 +0100 Subject: [PATCH 1/2] fix: report source options of the wrong type as invalid-source A URI source whose headers, cache, maxAgeMs or cacheKey had the wrong type passed validation and threw inside Nitro's prop conversion. Check them in JS, where PdfView, PdfDocument.open and PdfCache share the source validation, and report invalid-source with the option named. Closes #82 --- docs/guides/sources-and-loading.md | 6 ++- package/src/PdfCache.test.ts | 17 ++++++++ package/src/PdfDocument.test.ts | 13 ++++++ package/src/PdfView.test.tsx | 21 +++++++++ package/src/source.test.ts | 70 ++++++++++++++++++++++++++++++ package/src/source.ts | 42 ++++++++++++++++++ 6 files changed, 168 insertions(+), 1 deletion(-) diff --git a/docs/guides/sources-and-loading.md b/docs/guides/sources-and-loading.md index 8bf7d3a..ad34b0c 100644 --- a/docs/guides/sources-and-loading.md +++ b/docs/guides/sources-and-loading.md @@ -47,7 +47,11 @@ the document. A source must be a `require()` asset number or an object with `uri`, `filePath` or `base64`. Anything else — a raw URL string (e.g. `'https://...'`), an empty object `{}`, property types that do not match (such as `{ uri: 42 }`), or list -items that are not objects (such as `[null]`) — is malformed: +items that are not objects (such as `[null]`) — is malformed. So is a URI +source with an option of the wrong type: `headers` that is not an object of +strings (a header whose value is `undefined` included), `cache` other than +`'session'` or `'persistent'`, `maxAgeMs` that is not a finite number of at +least 0, or `cacheKey` that is not a string. `null` options count as absent. - In `PdfView`: it never throws during render. Nothing is sent to native, and `onError` is called once with `code: 'invalid-source'` and an explanatory diff --git a/package/src/PdfCache.test.ts b/package/src/PdfCache.test.ts index 79b33f6..7575c6d 100644 --- a/package/src/PdfCache.test.ts +++ b/package/src/PdfCache.test.ts @@ -241,4 +241,21 @@ describe('PdfCache', () => { await expect(removePromise!).rejects.toThrow(); } }); + + test('download, getEntry and remove reject options of the wrong type before native code', async () => { + const source = { uri: 'https://x.test/a.pdf', cacheKey: 42 } as never; + const error = await PdfCache.download(source).catch((e: unknown) => e); + expect(error).toBeInstanceOf(PdfDownloadError); + expect(error).toMatchObject({ + code: 'invalid-source', + message: 'source.cacheKey must be a string; got 42', + }); + await expect(PdfCache.getEntry(source)).rejects.toThrow( + 'source.cacheKey must be a string; got 42', + ); + await expect(PdfCache.remove(source)).rejects.toThrow( + 'source.cacheKey must be a string; got 42', + ); + expect(downloads).toEqual([]); + }); }); diff --git a/package/src/PdfDocument.test.ts b/package/src/PdfDocument.test.ts index 33286e0..9d03983 100644 --- a/package/src/PdfDocument.test.ts +++ b/package/src/PdfDocument.test.ts @@ -172,6 +172,19 @@ describe('PdfDocument.open', () => { } }); + test('rejects options of the wrong type before creating the native object', async () => { + const error = await PdfDocument.open({ + uri: 'https://x.test/a.pdf', + cacheKey: 42, + } as never).catch((e: unknown) => e); + expect(error).toBeInstanceOf(PdfOpenError); + expect(error).toMatchObject({ + code: 'invalid-source', + message: 'source.cacheKey must be a string; got 42', + }); + expect(natives).toEqual([]); + }); + test("a source's own password takes precedence over the option", async () => { void PdfDocument.open( { uri: '/docs/a.pdf', password: 'own' }, diff --git a/package/src/PdfView.test.tsx b/package/src/PdfView.test.tsx index 3829b10..6be26f5 100644 --- a/package/src/PdfView.test.tsx +++ b/package/src/PdfView.test.tsx @@ -1162,6 +1162,27 @@ describe('PdfView', () => { ]); }); + test('source options of the wrong type call onError once and send nothing to native', () => { + const errors: unknown[] = []; + render( + errors.push(err)} + />, + ); + expect(hostRenders.length).toBe(0); + expect(errors).toEqual([ + { + code: 'invalid-source', + message: 'source.headers["X-User"] must be a string; got 7', + sourceIndex: 1, + }, + ]); + }); + test('promise methods reject with coded PdfMethodErrors', async () => { const ref = createRef(); render(); diff --git a/package/src/source.test.ts b/package/src/source.test.ts index e0a90ae..8a9533a 100644 --- a/package/src/source.test.ts +++ b/package/src/source.test.ts @@ -87,6 +87,76 @@ describe('validateSourceItem', () => { test('unresolvable assets become an empty uri, which native reports as invalid-source', () => { expect(validatedSource(99)).toEqual({ uri: '' }); }); + + test('null options are absent', () => { + expect( + validatedSource({ + uri: 'https://x.test/a.pdf', + headers: null, + cache: null, + maxAgeMs: null, + cacheKey: null, + }), + ).toEqual({ uri: 'https://x.test/a.pdf' }); + }); + + test('reports options of the wrong type, naming the option', () => { + const uri = 'https://x.test/a.pdf'; + const cases: [Record, string][] = [ + [{ uri, cacheKey: 42 }, 'source.cacheKey must be a string; got 42'], + [ + { uri, headers: 'Authorization: x' }, + 'source.headers must be an object of strings; got a string', + ], + [ + { uri, headers: ['x'] }, + 'source.headers must be an object of strings; got an array', + ], + [ + { uri, headers: { 'X-User': 7 } }, + 'source.headers["X-User"] must be a string; got 7', + ], + [ + { uri, headers: { Authorization: undefined } }, + 'source.headers["Authorization"] must be a string; got undefined', + ], + [ + { uri, headers: { Authorization: null } }, + 'source.headers["Authorization"] must be a string; got null', + ], + [ + { uri, cache: 'Persistent' }, + "source.cache must be 'session' or 'persistent'; got a string", + ], + [ + { uri, cache: true }, + "source.cache must be 'session' or 'persistent'; got true", + ], + [ + { uri, maxAgeMs: '0' }, + 'source.maxAgeMs must be a finite number of at least 0; got a string', + ], + [ + { uri, maxAgeMs: -1 }, + 'source.maxAgeMs must be a finite number of at least 0; got -1', + ], + [ + { uri, maxAgeMs: Number.NaN }, + 'source.maxAgeMs must be a finite number of at least 0; got NaN', + ], + [ + { uri, maxAgeMs: Number.POSITIVE_INFINITY }, + 'source.maxAgeMs must be a finite number of at least 0; got Infinity', + ], + ]; + for (const [source, error] of cases) { + expect(validateSourceItem(source, resolveAsset)).toEqual({ + ok: false, + error, + }); + expect(() => normalizeUriSource(source as never)).toThrow(error); + } + }); }); describe('sourceKey', () => { diff --git a/package/src/source.ts b/package/src/source.ts index 6843cc5..ac46bb4 100644 --- a/package/src/source.ts +++ b/package/src/source.ts @@ -120,6 +120,8 @@ function describeValue(value: unknown): string { return 'a string'; case 'number': return Number.isNaN(value) ? 'NaN' : String(value); + case 'boolean': + return String(value); case 'bigint': return `${value}n`; case 'symbol': @@ -205,6 +207,8 @@ export function validateSourceItem( } if ('uri' in obj) { if (typeof obj.uri === 'string') { + const error = uriOptionError(obj); + if (error !== undefined) return { ok: false, error }; return { ok: true, source: normalizeUriSource(source as PdfUriSource) }; } return { @@ -218,6 +222,42 @@ export function validateSourceItem( }; } +/** + * The first invalid option of a URI source, described for `invalid-source`. + * Checked here because Nitro's converters throw on a value of the wrong + * type. `null` is absent, like `undefined`. + */ +function uriOptionError(source: Record): string | undefined { + const { headers, cache, maxAgeMs, cacheKey } = source; + if (headers != null) { + if (typeof headers !== 'object' || Array.isArray(headers)) { + return `source.headers must be an object of strings; got ${describeValue(headers)}`; + } + for (const [name, value] of Object.entries(headers)) { + if (typeof value !== 'string') { + return `source.headers[${JSON.stringify(name)}] must be a string; got ${describeValue(value)}`; + } + } + } + if (cache != null && cache !== 'session' && cache !== 'persistent') { + return `source.cache must be 'session' or 'persistent'; got ${describeValue(cache)}`; + } + if ( + maxAgeMs != null && + !( + typeof maxAgeMs === 'number' && + Number.isFinite(maxAgeMs) && + maxAgeMs >= 0 + ) + ) { + return `source.maxAgeMs must be a finite number of at least 0; got ${describeValue(maxAgeMs)}`; + } + if (cacheKey != null && typeof cacheKey !== 'string') { + return `source.cacheKey must be a string; got ${describeValue(cacheKey)}`; + } + return undefined; +} + /** * The native shape of a URI source. Copies `headers` so later mutation of * the caller's object cannot leak into native code, and leaves absent @@ -235,6 +275,8 @@ export function normalizeUriSource( `source must be an object with uri; got ${describeSourceType(source, true)}`, ); } + const error = uriOptionError(source as unknown as Record); + if (error !== undefined) throw new Error(error); const normalized: Omit = { uri: source.uri }; if (source.headers != null) normalized.headers = { ...source.headers }; if (source.cache != null) normalized.cache = source.cache; From 1a89a6359b3c47c3c0bf54abb8101c0a79e4a785 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Wed, 4 Nov 2026 19:07:12 +0100 Subject: [PATCH 2/2] fix: reject non-plain headers and read source options once A Map or Headers instance passed as headers was copied to {} and the download went out without them. Require a plain object. Validation and normalization now read each option once, so a getter cannot hand native code a value other than the one that was checked. --- package/src/source.test.ts | 29 +++++++++ package/src/source.ts | 120 ++++++++++++++++++++++--------------- 2 files changed, 102 insertions(+), 47 deletions(-) diff --git a/package/src/source.test.ts b/package/src/source.test.ts index 8a9533a..e74a7ca 100644 --- a/package/src/source.test.ts +++ b/package/src/source.test.ts @@ -112,6 +112,10 @@ describe('validateSourceItem', () => { { uri, headers: ['x'] }, 'source.headers must be an object of strings; got an array', ], + [ + { uri, headers: new Map([['Authorization', 'x']]) }, + 'source.headers must be an object of strings; got a Map', + ], [ { uri, headers: { 'X-User': 7 } }, 'source.headers["X-User"] must be a string; got 7', @@ -157,6 +161,31 @@ describe('validateSourceItem', () => { expect(() => normalizeUriSource(source as never)).toThrow(error); } }); + + test('reads each option once, so a getter cannot change it after the check', () => { + let reads = 0; + const headers = { + get Authorization() { + reads += 1; + return reads === 1 ? 'Bearer 1' : (7 as never); + }, + }; + let headersReads = 0; + const source = { + uri: 'https://x.test/a.pdf', + get headers() { + headersReads += 1; + return headersReads === 1 ? headers : (7 as never); + }, + }; + expect(validateSourceItem(source, resolveAsset)).toEqual({ + ok: true, + source: { + uri: 'https://x.test/a.pdf', + headers: { Authorization: 'Bearer 1' }, + }, + }); + }); }); describe('sourceKey', () => { diff --git a/package/src/source.ts b/package/src/source.ts index ac46bb4..6c3d728 100644 --- a/package/src/source.ts +++ b/package/src/source.ts @@ -128,8 +128,13 @@ function describeValue(value: unknown): string { return value.toString(); case 'function': return 'a function'; - case 'object': - return Array.isArray(value) ? 'an array' : 'an object'; + case 'object': { + if (Array.isArray(value)) return 'an array'; + const name = Object.getPrototypeOf(value)?.constructor?.name; + return typeof name === 'string' && name !== 'Object' + ? `a ${name}` + : 'an object'; + } default: return typeof value; } @@ -206,11 +211,8 @@ export function validateSourceItem( }; } if ('uri' in obj) { - if (typeof obj.uri === 'string') { - const error = uriOptionError(obj); - if (error !== undefined) return { ok: false, error }; - return { ok: true, source: normalizeUriSource(source as PdfUriSource) }; - } + const { uri } = obj; + if (typeof uri === 'string') return uriSourceResult(uri, obj); return { ok: false, error: `source must be a require() result or an object with uri, filePath or base64; got ${describeSourceType(source)}`, @@ -223,66 +225,90 @@ export function validateSourceItem( } /** - * The first invalid option of a URI source, described for `invalid-source`. - * Checked here because Nitro's converters throw on a value of the wrong - * type. `null` is absent, like `undefined`. + * The native shape of a URI source, or why its options are invalid: Nitro's + * converters throw on a value of the wrong type. Reads each option once and + * copies `headers`, so neither a getter nor later mutation of the caller's + * object can change what was checked. `null` options are absent. */ -function uriOptionError(source: Record): string | undefined { +function uriSourceResult( + uri: string, + source: Record, +): + | { ok: true; source: Omit } + | { ok: false; error: string } { const { headers, cache, maxAgeMs, cacheKey } = source; + const normalized: Omit = { uri }; if (headers != null) { - if (typeof headers !== 'object' || Array.isArray(headers)) { - return `source.headers must be an object of strings; got ${describeValue(headers)}`; + const prototype = + typeof headers === 'object' ? Object.getPrototypeOf(headers) : undefined; + if (prototype !== Object.prototype && prototype !== null) { + return { + ok: false, + error: `source.headers must be an object of strings; got ${describeValue(headers)}`, + }; } - for (const [name, value] of Object.entries(headers)) { + const copy: Record = {}; + for (const [name, value] of Object.entries(headers as object)) { if (typeof value !== 'string') { - return `source.headers[${JSON.stringify(name)}] must be a string; got ${describeValue(value)}`; + return { + ok: false, + error: `source.headers[${JSON.stringify(name)}] must be a string; got ${describeValue(value)}`, + }; } + copy[name] = value; } + normalized.headers = copy; } - if (cache != null && cache !== 'session' && cache !== 'persistent') { - return `source.cache must be 'session' or 'persistent'; got ${describeValue(cache)}`; + if (cache != null) { + if (cache !== 'session' && cache !== 'persistent') { + return { + ok: false, + error: `source.cache must be 'session' or 'persistent'; got ${describeValue(cache)}`, + }; + } + normalized.cache = cache; } - if ( - maxAgeMs != null && - !( - typeof maxAgeMs === 'number' && - Number.isFinite(maxAgeMs) && - maxAgeMs >= 0 - ) - ) { - return `source.maxAgeMs must be a finite number of at least 0; got ${describeValue(maxAgeMs)}`; + if (maxAgeMs != null) { + if ( + typeof maxAgeMs !== 'number' || + !Number.isFinite(maxAgeMs) || + maxAgeMs < 0 + ) { + return { + ok: false, + error: `source.maxAgeMs must be a finite number of at least 0; got ${describeValue(maxAgeMs)}`, + }; + } + normalized.maxAgeMs = maxAgeMs; } - if (cacheKey != null && typeof cacheKey !== 'string') { - return `source.cacheKey must be a string; got ${describeValue(cacheKey)}`; + if (cacheKey != null) { + if (typeof cacheKey !== 'string') { + return { + ok: false, + error: `source.cacheKey must be a string; got ${describeValue(cacheKey)}`, + }; + } + normalized.cacheKey = cacheKey; } - return undefined; + return { ok: true, source: normalized }; } -/** - * The native shape of a URI source. Copies `headers` so later mutation of - * the caller's object cannot leak into native code, and leaves absent - * options absent. - */ +/** The native shape of a URI source; throws when it is invalid. */ export function normalizeUriSource( source: PdfUriSource, ): Omit { - if ( - source == null || - typeof source !== 'object' || - typeof (source as { uri?: unknown }).uri !== 'string' - ) { + const uri = (source as { uri?: unknown } | null | undefined)?.uri; + if (source == null || typeof source !== 'object' || typeof uri !== 'string') { throw new Error( `source must be an object with uri; got ${describeSourceType(source, true)}`, ); } - const error = uriOptionError(source as unknown as Record); - if (error !== undefined) throw new Error(error); - const normalized: Omit = { uri: source.uri }; - if (source.headers != null) normalized.headers = { ...source.headers }; - if (source.cache != null) normalized.cache = source.cache; - if (source.maxAgeMs != null) normalized.maxAgeMs = source.maxAgeMs; - if (source.cacheKey != null) normalized.cacheKey = source.cacheKey; - return normalized; + const result = uriSourceResult( + uri, + source as unknown as Record, + ); + if (!result.ok) throw new Error(result.error); + return result.source; } /** The source's own password, if it has one (bundled assets cannot). */