Skip to content

Commit

Permalink
Fix #2911
Browse files Browse the repository at this point in the history
  • Loading branch information
jgonggrijp committed Mar 14, 2021
1 parent ef646cc commit 4c73526
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 14 deletions.
23 changes: 19 additions & 4 deletions modules/template.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ function escapeChar(match) {
return '\\' + escapes[match];
}

// In order to prevent third-party code injection through
// `_.templateSettings.variable`, we test it against the following regular
// expression. It is intentionally a bit more liberal than just matching valid
// identifiers, but still prevents possible loopholes through defaults or
// destructuring assignment.
var bareIdentifier = /^\s*(\w|\$)+\s*$/;

// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
Expand Down Expand Up @@ -59,16 +66,25 @@ export default function template(text, settings, oldSettings) {
});
source += "';\n";

// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
var argument = settings.variable;
if (argument) {
// Insure against third-party code injection.
if (!bareIdentifier.test(argument)) throw new Error(
'variable is not a bare identifier: ' + argument
);
} else {
// If a variable is not specified, place data values in local scope.
source = 'with(obj||{}){\n' + source + '}\n';
argument = 'obj';
}

source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + 'return __p;\n';

var render;
try {
render = new Function(settings.variable || 'obj', '_', source);
render = new Function(argument, '_', source);
} catch (e) {
e.source = source;
throw e;
Expand All @@ -79,7 +95,6 @@ export default function template(text, settings, oldSettings) {
};

// Provide the compiled source as a convenience for precompilation.
var argument = settings.variable || 'obj';
template.source = 'function(' + argument + '){\n' + source + '}';

return template;
Expand Down
23 changes: 19 additions & 4 deletions underscore-esm.js

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

2 changes: 1 addition & 1 deletion underscore-esm.js.map

Large diffs are not rendered by default.

23 changes: 19 additions & 4 deletions underscore.js

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

2 changes: 1 addition & 1 deletion underscore.js.map

Large diffs are not rendered by default.

0 comments on commit 4c73526

Please sign in to comment.