janja 3.0.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1580,7 +1580,194 @@ ${suggestionText}`;
1580
1580
  }
1581
1581
  }
1582
1582
 
1583
+ const special = /[&<>"']/;
1584
+ const specials = /[&<>"']/g;
1585
+ const entities = {
1586
+ '&': '&amp;',
1587
+ '"': '&#34;',
1588
+ "'": '&#39;',
1589
+ '<': '&lt;',
1590
+ '>': '&gt;',
1591
+ };
1592
+ const entity = (char) => entities[char];
1593
+ function escape(v) {
1594
+ const str = typeof v === 'string' ? v : `${v}`;
1595
+ // Most values contain nothing to escape; they are returned as they are,
1596
+ // without allocating
1597
+ return special.test(str) ? str.replace(specials, entity) : str;
1598
+ }
1599
+
1600
+ class Safe extends String {
1601
+ constructor(value) {
1602
+ super(`${value}`);
1603
+ }
1604
+ }
1605
+
1606
+ /** Defaults and resolved limits used by the compiler and renderer. */
1607
+ function resolveSecurityLimits(security = {}) {
1608
+ return {
1609
+ maxIncludeDepth: security.maxIncludeDepth ?? 100,
1610
+ maxLoopIterations: security.maxLoopIterations,
1611
+ maxCallDepth: security.maxCallDepth,
1612
+ timeoutMs: security.timeoutMs,
1613
+ };
1614
+ }
1615
+ class SecuritySandbox {
1616
+ constructor(options = {}) {
1617
+ Object.defineProperty(this, "allowedGlobals", {
1618
+ enumerable: true,
1619
+ configurable: true,
1620
+ writable: true,
1621
+ value: void 0
1622
+ });
1623
+ Object.defineProperty(this, "cspNonce", {
1624
+ enumerable: true,
1625
+ configurable: true,
1626
+ writable: true,
1627
+ value: void 0
1628
+ });
1629
+ this.allowedGlobals = new Set(options.allowedGlobals || []);
1630
+ this.cspNonce = options.cspNonce;
1631
+ }
1632
+ sanitizeGlobals(globals) {
1633
+ const sanitized = {};
1634
+ for (const [key, value] of Object.entries(globals)) {
1635
+ if (this.allowedGlobals.has(key)) {
1636
+ sanitized[key] = value;
1637
+ }
1638
+ }
1639
+ return sanitized;
1640
+ }
1641
+ validateExpression(expression) {
1642
+ // Prevent access to dangerous globals
1643
+ const dangerousPatterns = [
1644
+ /\bprocess\b/,
1645
+ /\brequire\b/,
1646
+ /\bimport\b/,
1647
+ /\bexport\b/,
1648
+ /\beval\b/,
1649
+ /\bFunction\b/,
1650
+ /\b__proto__\b/,
1651
+ /\bconstructor\b/,
1652
+ ];
1653
+ for (const pattern of dangerousPatterns) {
1654
+ if (pattern.test(expression)) {
1655
+ return false;
1656
+ }
1657
+ }
1658
+ return true;
1659
+ }
1660
+ createSecureContext(globals) {
1661
+ const sanitized = this.sanitizeGlobals(globals);
1662
+ // Add safe utility functions
1663
+ return {
1664
+ ...sanitized,
1665
+ Math,
1666
+ Date,
1667
+ JSON,
1668
+ // Add other safe built-ins as needed
1669
+ };
1670
+ }
1671
+ getCSPNonce() {
1672
+ return this.cspNonce;
1673
+ }
1674
+ generateCSPHeaders() {
1675
+ const headers = {};
1676
+ if (this.cspNonce) {
1677
+ headers['Content-Security-Policy'] =
1678
+ `script-src 'nonce-${this.cspNonce}'`;
1679
+ }
1680
+ return headers;
1681
+ }
1682
+ }
1683
+ function deepEscape(value, seen = new WeakSet()) {
1684
+ if (value === null || value === undefined) {
1685
+ return '';
1686
+ }
1687
+ if (value instanceof Safe) {
1688
+ return `${value}`;
1689
+ }
1690
+ if (typeof value === 'object') {
1691
+ // Guard against circular references
1692
+ if (seen.has(value)) {
1693
+ return '';
1694
+ }
1695
+ seen.add(value);
1696
+ const values = Array.isArray(value)
1697
+ ? value
1698
+ : Object.values(value);
1699
+ return values.map((v) => deepEscape(v, seen)).join('');
1700
+ }
1701
+ return escape(value);
1702
+ }
1703
+ class SecurityAuditor {
1704
+ auditTemplate(template) {
1705
+ const issues = [];
1706
+ // Check for dangerous patterns
1707
+ const dangerousPatterns = [
1708
+ {
1709
+ pattern: /\beval\s*\(/,
1710
+ type: 'dangerous-eval',
1711
+ message: 'Use of eval() is dangerous and should be avoided',
1712
+ severity: 'critical',
1713
+ },
1714
+ {
1715
+ pattern: /\bFunction\s*\(/,
1716
+ type: 'dangerous-function',
1717
+ message: 'Use of Function constructor is dangerous',
1718
+ severity: 'critical',
1719
+ },
1720
+ {
1721
+ pattern: /\brequire\s*\(/,
1722
+ type: 'require-usage',
1723
+ message: 'Direct require() usage in templates is unsafe',
1724
+ severity: 'high',
1725
+ },
1726
+ {
1727
+ pattern: /\bimport\s*\(/,
1728
+ type: 'dynamic-import',
1729
+ message: 'Dynamic import() usage in templates may be unsafe',
1730
+ severity: 'high',
1731
+ },
1732
+ ];
1733
+ for (const { pattern, type, message, severity } of dangerousPatterns) {
1734
+ const match = template.match(pattern);
1735
+ if (match) {
1736
+ issues.push({
1737
+ type,
1738
+ message,
1739
+ location: `at index ${match.index}`,
1740
+ severity,
1741
+ });
1742
+ }
1743
+ }
1744
+ // Calculate overall severity
1745
+ const overallSeverity = this.calculateOverallSeverity(issues);
1746
+ return {
1747
+ issues,
1748
+ severity: overallSeverity,
1749
+ };
1750
+ }
1751
+ calculateOverallSeverity(issues) {
1752
+ if (issues.length === 0) {
1753
+ return 'low';
1754
+ }
1755
+ const severityMap = {
1756
+ critical: 4,
1757
+ high: 3,
1758
+ medium: 2,
1759
+ low: 1,
1760
+ };
1761
+ const maxSeverity = Math.max(...issues.map((issue) => severityMap[issue.severity]));
1762
+ return Object.entries(severityMap).find(([, value]) => value === maxSeverity)[0];
1763
+ }
1764
+ }
1765
+
1583
1766
  const fingerprints = new WeakMap();
1767
+ // How deep includes may nest while rendering. Only templates that include
1768
+ // themselves get anywhere near it; the limit turns a cycle that never ends
1769
+ // into an error instead of a stack overflow.
1770
+ const MAX_INCLUDE_DEPTH = 100;
1584
1771
  // Directives whose body is still the template's own top-level output
1585
1772
  const transparent = new Set(['IF', 'FOR']);
1586
1773
  // The template itself is the key: one string that is hashed once, and two
@@ -1592,6 +1779,8 @@ ${suggestionText}`;
1592
1779
  let fingerprint = fingerprints.get(options);
1593
1780
  if (fingerprint === undefined) {
1594
1781
  const { trimWhitespace, stripComments, commentOpen, commentClose, directiveOpen, directiveClose, outputOpen, outputClose, } = options;
1782
+ // Limits that change the generated code must bust the compile cache
1783
+ const { maxIncludeDepth, maxLoopIterations, maxCallDepth } = resolveSecurityLimits(options.security);
1595
1784
  fingerprint = JSON.stringify([
1596
1785
  trimWhitespace,
1597
1786
  stripComments,
@@ -1601,6 +1790,9 @@ ${suggestionText}`;
1601
1790
  directiveClose,
1602
1791
  outputOpen,
1603
1792
  outputClose,
1793
+ maxIncludeDepth,
1794
+ maxLoopIterations ?? null,
1795
+ maxCallDepth ?? null,
1604
1796
  ]);
1605
1797
  fingerprints.set(options, fingerprint);
1606
1798
  }
@@ -1718,12 +1910,16 @@ ${suggestionText}`;
1718
1910
  this.rootNode = new Parser(this.options).parse(template);
1719
1911
  this.state = {};
1720
1912
  this.start(this.isRoot);
1913
+ if (this.isRoot) {
1914
+ this.pushResourceLimitCounters();
1915
+ }
1721
1916
  await this.parseTemplates();
1722
1917
  if (this.isRoot) {
1723
1918
  if (this.partials.size) {
1724
- this.pushRaw(null, 'const p={');
1919
+ const { maxIncludeDepth } = resolveSecurityLimits(this.options.security);
1920
+ this.pushRaw(null, 'let d_=0;', 'const p={');
1725
1921
  for (const [path, code] of this.partials) {
1726
- this.pushRaw(null, `${JSON.stringify(path)}:async()=>{`, code, '},');
1922
+ this.pushRaw(null, `${JSON.stringify(path)}:async()=>{`, `if(d_>=${maxIncludeDepth})throw new Error(${JSON.stringify(`Includes of ${JSON.stringify(path)} are nested too deeply`)});`, 'd_++;', 'try{return await(async()=>{', code, '})();}finally{d_--;}', '},');
1727
1923
  }
1728
1924
  this.pushRaw(null, '};');
1729
1925
  }
@@ -1772,6 +1968,19 @@ ${suggestionText}`;
1772
1968
  fingerprint() {
1773
1969
  return optionsFingerprint(this.options);
1774
1970
  }
1971
+ /**
1972
+ * Shared counters for optional security limits. Declared once on the root
1973
+ * template so nested includes, macros and loops all see the same budget.
1974
+ */
1975
+ pushResourceLimitCounters() {
1976
+ const { maxLoopIterations, maxCallDepth } = resolveSecurityLimits(this.options.security);
1977
+ if (maxLoopIterations != null) {
1978
+ this.pushRaw(null, 'let li_=0;');
1979
+ }
1980
+ if (maxCallDepth != null) {
1981
+ this.pushRaw(null, 'let cd_=0;');
1982
+ }
1983
+ }
1775
1984
  async isFresh({ sources }) {
1776
1985
  if (!this.revalidate) {
1777
1986
  return true;
@@ -1800,6 +2009,10 @@ ${suggestionText}`;
1800
2009
  throw new CompileError(`Failed to load template from "${path}"`, this.template, node.loc);
1801
2010
  }
1802
2011
  this.sources.set(path, template ?? '');
2012
+ // Reserved before compiling, so that a template that includes itself,
2013
+ // directly or through others, refers to the partial being compiled
2014
+ // instead of compiling it again without end
2015
+ this.partials.set(path, '');
1803
2016
  if (template) {
1804
2017
  await this.compilePartial(path, node, template);
1805
2018
  }
@@ -1889,45 +2102,6 @@ ${suggestionText}`;
1889
2102
  }
1890
2103
  }
1891
2104
 
1892
- function escape(v) {
1893
- const str = typeof v === 'string' ? v : `${v}`;
1894
- // A single scan without regular expressions. Most values contain nothing
1895
- // to escape; they are returned as they are, without allocating.
1896
- let result = '';
1897
- let last = 0;
1898
- for (let i = 0; i < str.length; i++) {
1899
- let entity;
1900
- switch (str.charCodeAt(i)) {
1901
- case 38:
1902
- entity = '&amp;';
1903
- break;
1904
- case 34:
1905
- entity = '&#34;';
1906
- break;
1907
- case 39:
1908
- entity = '&#39;';
1909
- break;
1910
- case 60:
1911
- entity = '&lt;';
1912
- break;
1913
- case 62:
1914
- entity = '&gt;';
1915
- break;
1916
- default:
1917
- continue;
1918
- }
1919
- result += str.slice(last, i) + entity;
1920
- last = i + 1;
1921
- }
1922
- return last === 0 ? str : result + str.slice(last);
1923
- }
1924
-
1925
- class Safe extends String {
1926
- constructor(value) {
1927
- super(`${value}`);
1928
- }
1929
- }
1930
-
1931
2105
  function abs(value = 0) {
1932
2106
  return Math.abs(value);
1933
2107
  }
@@ -2459,6 +2633,10 @@ ${suggestionText}`;
2459
2633
  IF: '',
2460
2634
  ELSE: '',
2461
2635
  };
2636
+ // Names every object inherits (`toString`, `valueOf`, ...). The context is a
2637
+ // plain object, so these are only read from it when it has them itself;
2638
+ // otherwise a name nobody defined would resolve to a built-in function.
2639
+ const inherited = new Set(Object.getOwnPropertyNames(Object.prototype));
2462
2640
  class ExpCompiler {
2463
2641
  constructor() {
2464
2642
  Object.defineProperty(this, "context", {
@@ -2521,15 +2699,38 @@ ${suggestionText}`;
2521
2699
  return `!${this.compileExp(argument)}`;
2522
2700
  }
2523
2701
  compileId({ value, path, args }) {
2524
- let s = `${this.context}.${value}`;
2702
+ let s = inherited.has(value)
2703
+ ? `(Object.hasOwn(${this.context},"${value}")?${this.context}.${value}:undefined)`
2704
+ : `${this.context}.${value}`;
2525
2705
  if (path) {
2526
2706
  s += path.map((p) => `.${p.value}`).join('');
2527
2707
  }
2528
2708
  if (args) {
2529
- s += `(${args.map((arg) => this.compileExp(arg)).join(',')})`;
2709
+ s += `(${this.compileArgs(args).join(',')})`;
2530
2710
  }
2531
2711
  return s;
2532
2712
  }
2713
+ /**
2714
+ * Positional arguments in the order they are written, followed by one
2715
+ * object holding the named ones: `f(1, a=2, b=3)` calls `f(1, {a:2,b:3})`.
2716
+ */
2717
+ compileArgs(args) {
2718
+ const positional = [];
2719
+ const named = [];
2720
+ for (const arg of args) {
2721
+ if (arg.type === 'ASSIGN') {
2722
+ const { left, right } = arg;
2723
+ named.push(`${left.value}:${this.compileExp(right)}`);
2724
+ }
2725
+ else {
2726
+ positional.push(this.compileExp(arg));
2727
+ }
2728
+ }
2729
+ if (named.length) {
2730
+ positional.push(`{${named.join(',')}}`);
2731
+ }
2732
+ return positional;
2733
+ }
2533
2734
  compileLit({ value }) {
2534
2735
  if (value === undefined) {
2535
2736
  return 'undefined';
@@ -2546,7 +2747,7 @@ ${suggestionText}`;
2546
2747
  }
2547
2748
  compilePipe({ left, right }) {
2548
2749
  const { value: name, args = [] } = right;
2549
- const call = `(${this.filters}.${name}||${UNKNOWN_FILTER}("${name}")).call(${[this.context, this.compileExp(left), ...args.map((arg) => (arg.type === 'ASSIGN' ? `${this.context}.${arg.left.value}=${this.compileExp(arg.right)}` : this.compileExp(arg)))].join(',')})`;
2750
+ const call = `(${this.filters}.${name}||${UNKNOWN_FILTER}("${name}")).call(${[this.context, this.compileExp(left), ...this.compileArgs(args)].join(',')})`;
2550
2751
  // Awaiting a plain value still costs a trip through the microtask queue,
2551
2752
  // so only promises returned by async filters are awaited
2552
2753
  return `(${RESULT}=${call},${RESULT} instanceof Promise?await ${RESULT}:${RESULT})`;
@@ -2571,9 +2772,9 @@ ${suggestionText}`;
2571
2772
  }
2572
2773
 
2573
2774
  async function compileCall({ val, body, loc }, compiler) {
2574
- compiler.pushRaw(loc, `await ${new ExpCompiler().compile(val, compiler.context)}(async()=>{`);
2775
+ compiler.pushRaw(loc, `s+=await ${new ExpCompiler().compile(val, compiler.context)}(async()=>{`, 'let s="";');
2575
2776
  await compiler.compileNodes(body);
2576
- compiler.pushRaw(null, '});');
2777
+ compiler.pushRaw(null, 'return s;', '})??"";');
2577
2778
  }
2578
2779
  const compilers$c = {
2579
2780
  CALL: compileCall,
@@ -2770,8 +2971,14 @@ ${suggestionText}`;
2770
2971
  return false;
2771
2972
  }
2772
2973
  seen.add(exp);
2773
- return (exp.type === 'ASSIGN' ||
2774
- Object.values(exp).some((value) => hasAssignment(value, seen)));
2974
+ if (exp.type === 'ASSIGN') {
2975
+ return true;
2976
+ }
2977
+ return Object.entries(exp).some(([key, value]) =>
2978
+ // `f(name=value)` passes a named argument; only its value matters
2979
+ key === 'args' && Array.isArray(value)
2980
+ ? value.some((arg) => hasAssignment(arg.type === 'ASSIGN' ? arg.right : arg, seen))
2981
+ : hasAssignment(value, seen));
2775
2982
  }
2776
2983
  /**
2777
2984
  * Whether nothing in `nodes` can write to, or keep a reference to, the
@@ -2825,13 +3032,19 @@ ${suggestionText}`;
2825
3032
  : [[left.value, 'v_']];
2826
3033
  const scope = compiler.in();
2827
3034
  compiler.pushRaw(loc, 'let i_=0;');
3035
+ const { maxLoopIterations } = resolveSecurityLimits(compiler.options.security);
3036
+ const loopGuard = maxLoopIterations == null
3037
+ ? []
3038
+ : [
3039
+ `if(++li_>${maxLoopIterations})throw new Error(${JSON.stringify(`Loop iteration limit of ${maxLoopIterations} exceeded`)});`,
3040
+ ];
2828
3041
  if (isReadOnly(body)) {
2829
3042
  // Nothing in the body can modify the scope, so a single one is shared by
2830
3043
  // all iterations instead of copying the outer context for each of them
2831
- compiler.pushRaw(loc, `const ${scope}={...${context}};`, 'for(const v_ of a_){', `${scope}.loop={${loop.slice(6)};`, ...variables.map(([name, value]) => `${scope}.${name}=${value};`));
3044
+ compiler.pushRaw(loc, `const ${scope}={...${context}};`, 'for(const v_ of a_){', ...loopGuard, `${scope}.loop={${loop.slice(6)};`, ...variables.map(([name, value]) => `${scope}.${name}=${value};`));
2832
3045
  }
2833
3046
  else {
2834
- compiler.pushRaw(loc, 'for(const v_ of a_){', `const ${scope}={`, `...${context},`, `${loop},`, ...variables.map(([name, value]) => `${name}:${value},`), '};');
3047
+ compiler.pushRaw(loc, 'for(const v_ of a_){', ...loopGuard, `const ${scope}={`, `...${context},`, `${loop},`, ...variables.map(([name, value]) => `${name}:${value},`), '};');
2835
3048
  }
2836
3049
  await compiler.compileNodes(body);
2837
3050
  compiler.out();
@@ -3346,15 +3559,25 @@ ${suggestionText}`;
3346
3559
  async function compileMacro({ val: { value, args }, loc, body }, compiler) {
3347
3560
  const { context } = compiler;
3348
3561
  const expCompiler = new ExpCompiler();
3349
- compiler.pushRaw(loc, `${context}.${value}=(...a_)=>async(_c)=>{`, `const ${compiler.in()}={`, `...${context},`, ...(args ?? []).map((el, i) => el.type === 'ASSIGN'
3562
+ const { maxCallDepth } = resolveSecurityLimits(compiler.options.security);
3563
+ compiler.pushRaw(loc,
3564
+ // A macro collects its own output and returns it, so that it ends up
3565
+ // where the macro is called rather than where it was defined
3566
+ `${context}.${value}=(...a_)=>async(_c)=>{`, ...(maxCallDepth == null
3567
+ ? []
3568
+ : [
3569
+ `if(cd_>=${maxCallDepth})throw new Error(${JSON.stringify(`Macro call depth limit of ${maxCallDepth} exceeded`)});`,
3570
+ 'cd_++;',
3571
+ 'try{',
3572
+ ]), 'let s="";', `const ${compiler.in()}={`, `...${context},`, ...(args ?? []).map((el, i) => el.type === 'ASSIGN'
3350
3573
  ? `${el.left.value}:a_[${i}]===undefined?${expCompiler.compile(el.right)}:a_[${i}],`
3351
3574
  : `${el.value}:a_[${i}],`), '};');
3352
3575
  await compiler.compileNodes(body);
3353
3576
  compiler.out();
3354
- compiler.pushRaw(null, '};');
3577
+ compiler.pushRaw(null, 'return s;', ...(maxCallDepth == null ? [] : ['}finally{cd_--;}']), '};');
3355
3578
  }
3356
3579
  function compileCaller({ loc }, compiler) {
3357
- compiler.pushRaw(loc, 'await _c?.();');
3580
+ compiler.pushRaw(loc, 's+=await _c?.()??"";');
3358
3581
  }
3359
3582
  const compilers$6 = {
3360
3583
  MACRO: compileMacro,
@@ -3883,157 +4106,6 @@ ${suggestionText}`;
3883
4106
  }
3884
4107
  }
3885
4108
 
3886
- class SecuritySandbox {
3887
- constructor(options = {}) {
3888
- Object.defineProperty(this, "allowedGlobals", {
3889
- enumerable: true,
3890
- configurable: true,
3891
- writable: true,
3892
- value: void 0
3893
- });
3894
- Object.defineProperty(this, "cspNonce", {
3895
- enumerable: true,
3896
- configurable: true,
3897
- writable: true,
3898
- value: void 0
3899
- });
3900
- this.allowedGlobals = new Set(options.allowedGlobals || []);
3901
- this.cspNonce = options.cspNonce;
3902
- }
3903
- sanitizeGlobals(globals) {
3904
- const sanitized = {};
3905
- for (const [key, value] of Object.entries(globals)) {
3906
- if (this.allowedGlobals.has(key)) {
3907
- sanitized[key] = value;
3908
- }
3909
- }
3910
- return sanitized;
3911
- }
3912
- validateExpression(expression) {
3913
- // Prevent access to dangerous globals
3914
- const dangerousPatterns = [
3915
- /\bprocess\b/,
3916
- /\brequire\b/,
3917
- /\bimport\b/,
3918
- /\bexport\b/,
3919
- /\beval\b/,
3920
- /\bFunction\b/,
3921
- /\b__proto__\b/,
3922
- /\bconstructor\b/,
3923
- ];
3924
- for (const pattern of dangerousPatterns) {
3925
- if (pattern.test(expression)) {
3926
- return false;
3927
- }
3928
- }
3929
- return true;
3930
- }
3931
- createSecureContext(globals) {
3932
- const sanitized = this.sanitizeGlobals(globals);
3933
- // Add safe utility functions
3934
- return {
3935
- ...sanitized,
3936
- Math,
3937
- Date,
3938
- JSON,
3939
- // Add other safe built-ins as needed
3940
- };
3941
- }
3942
- getCSPNonce() {
3943
- return this.cspNonce;
3944
- }
3945
- generateCSPHeaders() {
3946
- const headers = {};
3947
- if (this.cspNonce) {
3948
- headers['Content-Security-Policy'] =
3949
- `script-src 'nonce-${this.cspNonce}'`;
3950
- }
3951
- return headers;
3952
- }
3953
- }
3954
- function deepEscape(value, seen = new WeakSet()) {
3955
- if (value === null || value === undefined) {
3956
- return '';
3957
- }
3958
- if (value instanceof Safe) {
3959
- return `${value}`;
3960
- }
3961
- if (typeof value === 'object') {
3962
- // Guard against circular references
3963
- if (seen.has(value)) {
3964
- return '';
3965
- }
3966
- seen.add(value);
3967
- const values = Array.isArray(value)
3968
- ? value
3969
- : Object.values(value);
3970
- return values.map((v) => deepEscape(v, seen)).join('');
3971
- }
3972
- return escape(value);
3973
- }
3974
- class SecurityAuditor {
3975
- auditTemplate(template) {
3976
- const issues = [];
3977
- // Check for dangerous patterns
3978
- const dangerousPatterns = [
3979
- {
3980
- pattern: /\beval\s*\(/,
3981
- type: 'dangerous-eval',
3982
- message: 'Use of eval() is dangerous and should be avoided',
3983
- severity: 'critical',
3984
- },
3985
- {
3986
- pattern: /\bFunction\s*\(/,
3987
- type: 'dangerous-function',
3988
- message: 'Use of Function constructor is dangerous',
3989
- severity: 'critical',
3990
- },
3991
- {
3992
- pattern: /\brequire\s*\(/,
3993
- type: 'require-usage',
3994
- message: 'Direct require() usage in templates is unsafe',
3995
- severity: 'high',
3996
- },
3997
- {
3998
- pattern: /\bimport\s*\(/,
3999
- type: 'dynamic-import',
4000
- message: 'Dynamic import() usage in templates may be unsafe',
4001
- severity: 'high',
4002
- },
4003
- ];
4004
- for (const { pattern, type, message, severity } of dangerousPatterns) {
4005
- const match = template.match(pattern);
4006
- if (match) {
4007
- issues.push({
4008
- type,
4009
- message,
4010
- location: `at index ${match.index}`,
4011
- severity,
4012
- });
4013
- }
4014
- }
4015
- // Calculate overall severity
4016
- const overallSeverity = this.calculateOverallSeverity(issues);
4017
- return {
4018
- issues,
4019
- severity: overallSeverity,
4020
- };
4021
- }
4022
- calculateOverallSeverity(issues) {
4023
- if (issues.length === 0) {
4024
- return 'low';
4025
- }
4026
- const severityMap = {
4027
- critical: 4,
4028
- high: 3,
4029
- medium: 2,
4030
- low: 1,
4031
- };
4032
- const maxSeverity = Math.max(...issues.map((issue) => severityMap[issue.severity]));
4033
- return Object.entries(severityMap).find(([, value]) => value === maxSeverity)[0];
4034
- }
4035
- }
4036
-
4037
4109
  // Thrown inside a template to stop rendering a stream nobody reads anymore
4038
4110
  const cancellation = new Error('Stream cancelled');
4039
4111
  class Renderer {
@@ -4069,6 +4141,14 @@ ${suggestionText}`;
4069
4141
  writable: true,
4070
4142
  value: void 0
4071
4143
  });
4144
+ // Compilations in progress, so that renders of the same template that
4145
+ // start together share one instead of each compiling it
4146
+ Object.defineProperty(this, "compiling", {
4147
+ enumerable: true,
4148
+ configurable: true,
4149
+ writable: true,
4150
+ value: new Map()
4151
+ });
4072
4152
  this.options = mergeOptions(renderOptions, {
4073
4153
  filters,
4074
4154
  plugins,
@@ -4077,6 +4157,11 @@ ${suggestionText}`;
4077
4157
  const escapeValue = this.options.security?.deepEscape ? deepEscape : escape;
4078
4158
  const { autoEscape } = this.options;
4079
4159
  this.escape = (v) => {
4160
+ // Strings are by far the most common value, so they are handled before
4161
+ // anything else is checked
4162
+ if (typeof v === 'string') {
4163
+ return autoEscape ? escape(v) : v;
4164
+ }
4080
4165
  if (v === null || v === undefined) {
4081
4166
  return '';
4082
4167
  }
@@ -4111,13 +4196,13 @@ ${suggestionText}`;
4111
4196
  return '';
4112
4197
  }
4113
4198
  }
4114
- const compiler = this.createCompiler();
4199
+ let compiler;
4115
4200
  try {
4116
- await compiler.compile(template);
4201
+ compiler = await this.compile(template);
4117
4202
  return await this.run(compiler.script, globals);
4118
4203
  }
4119
4204
  catch (error) {
4120
- this.options.debug(this.wrapError(error, template, compiler));
4205
+ this.options.debug(this.wrapError(error, template, compiler ?? new SourceMap()));
4121
4206
  }
4122
4207
  return '';
4123
4208
  }
@@ -4162,12 +4247,12 @@ ${suggestionText}`;
4162
4247
  });
4163
4248
  }
4164
4249
  };
4165
- const compiler = this.createCompiler(true);
4250
+ let compiler;
4166
4251
  // Not awaited: `start` returns right away and chunks are enqueued as
4167
4252
  // they are produced
4168
4253
  void (async () => {
4169
4254
  try {
4170
- await compiler.compile(template);
4255
+ compiler = await this.compile(template, true);
4171
4256
  const rest = await this.run(compiler.script, globals, write);
4172
4257
  if (rest && !cancelled) {
4173
4258
  controller.enqueue(rest);
@@ -4179,7 +4264,7 @@ ${suggestionText}`;
4179
4264
  return;
4180
4265
  }
4181
4266
  try {
4182
- this.options.debug(this.wrapError(error, template, compiler));
4267
+ this.options.debug(this.wrapError(error, template, compiler ?? new SourceMap()));
4183
4268
  controller.close();
4184
4269
  }
4185
4270
  catch (reported) {
@@ -4198,8 +4283,16 @@ ${suggestionText}`;
4198
4283
  },
4199
4284
  });
4200
4285
  }
4201
- createCompiler(stream = false) {
4202
- return new Compiler(this.options, this.cache, this.options.cache?.revalidate ?? true, stream);
4286
+ compile(template, stream = false) {
4287
+ const key = templateCacheKey(template, stream);
4288
+ let compiling = this.compiling.get(key);
4289
+ if (!compiling) {
4290
+ compiling = new Compiler(this.options, this.cache, this.options.cache?.revalidate ?? true, stream)
4291
+ .compile(template)
4292
+ .finally(() => this.compiling.delete(key));
4293
+ this.compiling.set(key, compiling);
4294
+ }
4295
+ return compiling;
4203
4296
  }
4204
4297
  wrapError(error, template, sourceMap) {
4205
4298
  if (error?.name === 'CompileError') {
@@ -4226,7 +4319,24 @@ ${suggestionText}`;
4226
4319
  ...globals,
4227
4320
  }
4228
4321
  : { ...this.options.globals, ...globals };
4229
- return script(context, this.escape, this.filters, write);
4322
+ const result = script(context, this.escape, this.filters, write);
4323
+ const { timeoutMs } = this.options.security ?? {};
4324
+ if (timeoutMs == null) {
4325
+ return result;
4326
+ }
4327
+ // The script keeps running after the budget; only the promise rejects.
4328
+ // Use a separate process when templates must be forcibly stopped.
4329
+ let timer;
4330
+ return Promise.race([
4331
+ Promise.resolve(result).finally(() => {
4332
+ clearTimeout(timer);
4333
+ }),
4334
+ new Promise((_, reject) => {
4335
+ timer = setTimeout(() => {
4336
+ reject(new Error(`Render timed out after ${timeoutMs}ms`));
4337
+ }, timeoutMs);
4338
+ }),
4339
+ ]);
4230
4340
  }
4231
4341
  async renderFile(filepath, globals) {
4232
4342
  return this.render(await this.options.loader(filepath), globals);
@@ -5434,12 +5544,15 @@ export default script;
5434
5544
  exports.ExpParser = ExpParser;
5435
5545
  exports.ExpTokenizer = ExpTokenizer;
5436
5546
  exports.I18n = I18n;
5547
+ exports.MAX_INCLUDE_DEPTH = MAX_INCLUDE_DEPTH;
5437
5548
  exports.MixinRegistry = MixinRegistry;
5438
5549
  exports.Parser = Parser;
5439
5550
  exports.RenderError = RenderError;
5440
5551
  exports.Renderer = Renderer;
5441
5552
  exports.RootNode = RootNode;
5442
5553
  exports.Safe = Safe;
5554
+ exports.SecurityAuditor = SecurityAuditor;
5555
+ exports.SecuritySandbox = SecuritySandbox;
5443
5556
  exports.TemplatePipeline = TemplatePipeline;
5444
5557
  exports.TemplateValidator = TemplateValidator;
5445
5558
  exports.Tokenizer = Tokenizer;
@@ -5457,6 +5570,7 @@ export default script;
5457
5570
  exports.createErrorRecovery = createErrorRecovery;
5458
5571
  exports.createFileLoader = createFileLoader;
5459
5572
  exports.createMixin = createMixin;
5573
+ exports.deepEscape = deepEscape;
5460
5574
  exports.defaultErrorHandler = defaultErrorHandler;
5461
5575
  exports.defaultWhitespaceOptions = defaultWhitespaceOptions;
5462
5576
  exports.defineFilters = defineFilters;
@@ -5483,6 +5597,7 @@ export default script;
5483
5597
  exports.renderFile = renderFile;
5484
5598
  exports.renderOptions = renderOptions;
5485
5599
  exports.renderStream = renderStream;
5600
+ exports.resolveSecurityLimits = resolveSecurityLimits;
5486
5601
  exports.templateCacheKey = templateCacheKey;
5487
5602
  exports.validateTemplate = validateTemplate;
5488
5603