Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

escape meta content #78

Merged
merged 1 commit into from
Apr 27, 2023
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
18 changes: 18 additions & 0 deletions __tests__/ssr.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,24 @@ describe('ssr', () => {
]);
});

it('should escape meta-content', () => {
jest.useFakeTimers();
const MyComponent = () => {
useMeta({ property: 'fb:admins', content: "''<>&" });
useMeta({ property: 'fb:something', content: '""' });
return <p>hi</p>;
};

render(<MyComponent />);
jest.runAllTimers();
const { metas } = toStatic();

expect(metas).toEqual([
{ content: '&quot;&quot;', property: 'fb:something' },
{ content: '&#39;&#39;&lt;&gt;&amp;', property: 'fb:admins' },
]);
});

it('should render to string (basic-useHead)', () => {
jest.useFakeTimers();
const MyComponent = () => {
Expand Down
40 changes: 39 additions & 1 deletion src/dispatcher/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,44 @@ export const createDispatcher = () => {
: // istanbul ignore next
undefined,
toStatic: (): StaticPayload => {
const ESCAPED_CHARS = /['"&<>]/;

function escape(str: string) {
if (str.length === 0 || ESCAPED_CHARS.test(str) === false) return str;

let last = 0,
i = 0,
out = '',
ch = '';

for (; i < str.length; i++) {
switch (str.charCodeAt(i)) {
case 34:
ch = '&quot;';
break;
case 38:
ch = '&amp;';
break;
case 39:
ch = '&#39;';
break;
case 60:
ch = '&lt;';
break;
case 62:
ch = '&gt;';
break;
default:
continue;
}

if (i !== last) out += str.slice(last, i);
out += ch;
last = i + 1;
}
if (i !== last) out += str.slice(last, i);
return out;
}
// Will process the two arrays, taking the first title in the array and returning <title>{string}</title>
// Then do a similar for the meta's. (will also need to add links, and add a linkQueue). Note that both queues
// will need a reset to prevent memory leaks.
Expand Down Expand Up @@ -240,7 +278,7 @@ export const createDispatcher = () => {
}
: {
[meta.keyword]: meta[meta.keyword],
content: meta.content,
content: escape(meta.content),
}
),
};
Expand Down