Skip to content

Commit

Permalink
fix: apply limits to metadata values
Browse files Browse the repository at this point in the history
  • Loading branch information
maxakuru committed Aug 28, 2024
1 parent 7e08916 commit 7bfdf28
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 10 deletions.
28 changes: 18 additions & 10 deletions src/html2md.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,19 @@ function toGridTable(title, data) {
]);
}

function validateJSON(str) {
return JSON.stringify(JSON.parse(str.trim()));
function assertValidJSON(str) {
try {
return JSON.stringify(JSON.parse(str.trim()));
} catch {
throw Error('invalid json-ld');
}
}

function assertMetaSizeLimit(str, limit = 128_000) {
if (str && str.length > limit) {
throw Error('metadata size limit exceeded');
}
return str;
}

function addMetadata(hast, mdast) {
Expand All @@ -86,22 +97,19 @@ function addMetadata(hast, mdast) {
const head = select('head', hast);
for (const child of head.children) {
if (child.tagName === 'title') {
meta.set(text('title'), text(toString(child)));
meta.set(text('title'), text(assertMetaSizeLimit(toString(child))));
} else if (child.tagName === 'meta') {
const { name, content } = child.properties;
if (name && !HELIX_META.has(name) && !name.startsWith('twitter:')) {
if (name === 'image') {
meta.set(text(name), image(content));
meta.set(text(name), image(assertMetaSizeLimit(content)));
} else {
meta.set(text(name), text(content));
meta.set(text(name), text(assertMetaSizeLimit(content)));
}
}
} else if (child.tagName === 'script' && child.properties.type === 'application/ld+json') {
try {
meta.set(text('json-ld'), text(validateJSON(toString(child))));
} catch {
throw Error('invalid json-ld');
}
const str = assertMetaSizeLimit(assertValidJSON(toString(child)));
meta.set(text('json-ld'), text(str));
}
}

Expand Down
17 changes: 17 additions & 0 deletions test/fixtures/json-ld-too-large.html

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions test/html2md.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ describe('html2md Tests', () => {
it('throws meaningful error when json-ld is invalid', async () => {
await assert.rejects(() => test('json-ld-invalid'), Error('invalid json-ld'));
});

it('throws meaningful error when json-ld is too large', async () => {
await assert.rejects(() => test('json-ld-too-large'), Error('metadata size limit exceeded'));
});
});

describe('className to block type tests', () => {
Expand Down

0 comments on commit 7bfdf28

Please sign in to comment.