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

fix: add safe filter #9

Merged
merged 2 commits into from
Sep 30, 2024
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
2 changes: 1 addition & 1 deletion demo/_layouts/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<body>
<html-include src="header.html"/>
<main>
{{ content }}
{{ content | safe }}
</main>
<html-include src="footer.html"/>
</body>
Expand Down
19 changes: 16 additions & 3 deletions src/transforms/template-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ const TEMPLATE_REGEX = /\{\{\s*([\w\.\[\]]+)(?:\((.*)\))?(?:\s*\|\s([a-zA-Z*]\w*
const JSON_PATH_REGEX = /^[a-zA-Z_]\w*((?:\.\w+)|(?:\[\d+\]))*$/
const JSON_PATH_TOKEN = /(^[a-zA-Z_]\w*)|(\.[a-zA-Z_]\w*)|(\[\d+\])/g

function mergeMaps(map1, map2) {
return new Map([...map1, ...map2]);
}

function htmlEscape(input) {
return input?.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

/**
* Poor girl's jsonpath
*
Expand Down Expand Up @@ -59,7 +67,11 @@ export function parseArguments(args, data) {
* @returns {(data: any, filters: Map<string, function>) => string} a function that takes a data object and returns the processed template
*/
export function template(str) {
return (data, filters) => {
const defaultFilters = new Map();
let isSafe = false;
defaultFilters.set('safe', (input) => { isSafe = true; return input; })
return (data, providedFilters) => {
const filters = mergeMaps(defaultFilters || new Map(), providedFilters || new Map())
return str.replace(TEMPLATE_REGEX, (_, expr, params, filter, filterParams) => {
let result = dataPath(expr)(data);
const args = parseArguments(params, data);
Expand All @@ -73,7 +85,7 @@ export function template(str) {
const filterArgs = parseArguments(filterParams, data);
result = filters.get(filter)(result, ...filterArgs);
}
return result;
return isSafe ? result : htmlEscape(result);
});
}
}
Expand Down Expand Up @@ -123,11 +135,12 @@ export async function handleTemplateFile(config, data, inputFile) {
const l = await handleTemplateFile(config,
{...fileData, content: fileContent, layout: null}, layoutFilePath);
if (l) {
fileContent = l.content;;
fileContent = l.content;
} else {
throw new Error('Layout not found:' + layoutFilePath);
}
}

return {content: fileContent, filename: outputFile};
}

2 changes: 1 addition & 1 deletion tests/fixtures/smallsite/_layouts/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<body>
<html-include src="header.html"/>
<main>
{{ content }}
{{ content | safe }}
</main>
<html-include src="footer.html"/>
</body>
Expand Down
22 changes: 17 additions & 5 deletions tests/transforms/template-data.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,18 @@ describe('template function', () => {
assert.equal(result, "HELLO");
});

it('should escape angle brackets and ampersands by default', () => {
const result = template('{{ content }}')({content: '<h1>Hello</h1>'});

assert.equal(result, '&lt;h1&gt;Hello&lt;/h1&gt;')
});

it('should not escape angle brackets and ampersands when marked safe', () => {
const result = template('{{ content | safe }}')({content: '<h1>Hello</h1>'});

assert.equal(result, '<h1>Hello</h1>')
});

it('should be able to apply a filter with additional parameters', () => {
const data = { greeting: 'Hello Lea'}
const filters = new Map();
Expand All @@ -108,7 +120,7 @@ describe('template function', () => {
});
});

describe('handleTemplateFile function', {only: true}, () => {
describe('handleTemplateFile function', () => {

const withFrontmatter = (str, data) => `---json\n${JSON.stringify(data)}\n---\n${str}`

Expand Down Expand Up @@ -136,7 +148,7 @@ describe('handleTemplateFile function', {only: true}, () => {

const vFS = new Map();
vFS.set('index.html', withFrontmatter('<h1>{{ title }}</h1>', {layout: 'base.html'}));
vFS.set('_layouts/base.html', '<body>{{ content }}</body>')
vFS.set('_layouts/base.html', '<body>{{ content | safe }}</body>')

config.resolve = (...paths) => {
const resource = path.normalize(path.join(...paths));
Expand All @@ -155,7 +167,7 @@ describe('handleTemplateFile function', {only: true}, () => {

const vFS = new Map();
vFS.set('index.md', withFrontmatter(TEST_MD, {'layout': 'base.html', author: 'Lea Rosema'}));
vFS.set('_layouts/base.html', '<body>{{ content }}</body>');
vFS.set('_layouts/base.html', '<body>{{ content | safe }}</body>');

config.resolve = (...paths) => {
const resource = path.normalize(path.join(...paths));
Expand All @@ -174,7 +186,7 @@ describe('handleTemplateFile function', {only: true}, () => {

const vFS = new Map();
vFS.set('index.md', withFrontmatter(TEST_MD, {'layout': 'base.html', author: 'Lea Rosema'}));
vFS.set('_layouts/base.html', '<body>{{ content }}</body>');
vFS.set('_layouts/base.html', '<body>{{ content | safe }}</body>');

config.resolve = (...paths) => {
const resource = path.normalize(path.join(...paths));
Expand Down Expand Up @@ -206,7 +218,7 @@ describe('handleTemplateFile function', {only: true}, () => {
});
});

it('should throw an error when a non-existant file is specified as layout', {only: true}, async () => {
it('should throw an error when a non-existant file is specified as layout', async () => {
const config = new SissiConfig();
config.addExtension(md);

Expand Down