diff --git a/src/html2md.js b/src/html2md.js index 31b824dd..8bc319b9 100644 --- a/src/html2md.js +++ b/src/html2md.js @@ -33,6 +33,8 @@ import { } from './mdast-table-handler.js'; import formatPlugin from './markdownFormatPlugin.js'; +export class ConstraintsError extends Error {} + const HELIX_META = { viewport: true, }; @@ -80,13 +82,13 @@ function toGridTable(title, data) { /** * @param {string} str * @returns {string} - * @throws {Error} + * @throws {ConstraintsError} when it is not valid JSON */ function assertValidJSON(str) { try { return JSON.stringify(JSON.parse(str.trim())); } catch { - throw Error('invalid json-ld'); + throw new ConstraintsError('invalid json-ld'); } } @@ -94,11 +96,11 @@ function assertValidJSON(str) { * @param {string} str * @param {number} [limit] * @returns {string} - * @throws {Error} + * @throws {ConstraintsError} when metadata size limit is exceeded */ function assertMetaSizeLimit(str, limit = 128_000) { if (str && str.length > limit) { - throw Error('metadata size limit exceeded'); + throw new ConstraintsError('metadata size limit exceeded'); } return str; } diff --git a/src/index.js b/src/index.js index c59d7733..a57c5c2b 100644 --- a/src/index.js +++ b/src/index.js @@ -21,7 +21,7 @@ import { import { cleanupHeaderValue } from '@adobe/helix-shared-utils'; import { MediaHandler } from '@adobe/helix-mediahandler'; import pkgJson from './package.cjs'; -import { html2md } from './html2md.js'; +import { ConstraintsError, html2md } from './html2md.js'; import { TooManyImagesError } from './mdast-process-images.js'; /* c8 ignore next 7 */ @@ -213,6 +213,9 @@ async function run(request, ctx) { if (e instanceof TooManyImagesError) { return error(`error fetching resource at ${sourceUrl}: ${e.message}`, 409); } + if (e instanceof ConstraintsError) { + return error(`error fetching resource at ${sourceUrl}: ${e.message}`, 400); + } /* c8 ignore next 3 */ log.debug(e.stack); return error(`error fetching resource at ${sourceUrl}: ${e.message}`, 500); diff --git a/test/index.test.js b/test/index.test.js index 3e439aa7..7c78c2d9 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -252,6 +252,38 @@ describe('Index Tests', () => { }); } + it('returns 400 for invalid metadata', async () => { + const html = ` + + + + + +
+
+

Hello, World.

+
+
+ + + +`; + nock('https://www.example.com') + .get('/') + .reply(200, html); + + const result = await main(reqUrl('/'), { log: console, env: {} }); + assert.strictEqual(result.status, 400); + assert.strictEqual(await result.text(), ''); + assert.deepStrictEqual(result.headers.plain(), { + 'cache-control': 'no-store, private, must-revalidate', + 'content-type': 'text/plain; charset=utf-8', + 'x-error': 'error fetching resource at https://www.example.com/: invalid json-ld', + }); + }); + it('returns 409 for too many different images', async () => { let html = '
'; for (let i = 0; i < 101; i += 1) {