Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"@types/react": "^16.7.22",
"react": "^15.4.1",
"schema-dts": ">=0.4.0",
"typescript": ">=3.1.6"
"typescript": "^3.8.3"
},
"dependencies": {},
"peerDependencies": {
Expand Down
54 changes: 52 additions & 2 deletions src/json-ld.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2019 Google LLC
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -44,8 +44,58 @@ export class JsonLd<T extends Thing> extends React.Component<{
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(this.props.item) }}
dangerouslySetInnerHTML={{
__html: JSON.stringify(this.props.item, safeJsonLdReplacer)
}}
/>
);
}
}

type JsonValueScalar = string | boolean | number;
type JsonValue =
| JsonValueScalar
| Array<JsonValue>
| { [key: string]: JsonValue };
type JsonReplacer = (_: string, value: JsonValue) => JsonValue | undefined;

/**
* A replacer for JSON.stringify to strip JSON-LD of illegal HTML entities
* per https://www.w3.org/TR/json-ld11/#restrictions-for-contents-of-json-ld-script-elements
*/
const safeJsonLdReplacer: JsonReplacer = (() => {
// Replace per https://www.w3.org/TR/json-ld11/#restrictions-for-contents-of-json-ld-script-elements
// Solution from https://stackoverflow.com/a/5499821/864313
const entities = Object.freeze({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&apos;"
});
const replace = (t: string): string =>
entities[t as keyof typeof entities] || t;

return (_: string, value: JsonValue): JsonValue | undefined => {
switch (typeof value) {
case "object":
return value; // JSON.stringify will recursively call replacer.
case "number":
case "boolean":
case "bigint":
return value; // These values are not risky.
case "string":
return value.replace(/[&<>'"]/g, replace);
default: {
// We shouldn't expect other types.
isNever(value);

// JSON.stringify will remove this element.
return undefined;
}
}
};
})();

// Utility: Assert never
function isNever(_: never): void {}