janja 4.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,6 +1580,189 @@ ${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();
1584
1767
  // How deep includes may nest while rendering. Only templates that include
1585
1768
  // themselves get anywhere near it; the limit turns a cycle that never ends
@@ -1596,6 +1779,8 @@ ${suggestionText}`;
1596
1779
  let fingerprint = fingerprints.get(options);
1597
1780
  if (fingerprint === undefined) {
1598
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);
1599
1784
  fingerprint = JSON.stringify([
1600
1785
  trimWhitespace,
1601
1786
  stripComments,
@@ -1605,6 +1790,9 @@ ${suggestionText}`;
1605
1790
  directiveClose,
1606
1791
  outputOpen,
1607
1792
  outputClose,
1793
+ maxIncludeDepth,
1794
+ maxLoopIterations ?? null,
1795
+ maxCallDepth ?? null,
1608
1796
  ]);
1609
1797
  fingerprints.set(options, fingerprint);
1610
1798
  }
@@ -1722,12 +1910,16 @@ ${suggestionText}`;
1722
1910
  this.rootNode = new Parser(this.options).parse(template);
1723
1911
  this.state = {};
1724
1912
  this.start(this.isRoot);
1913
+ if (this.isRoot) {
1914
+ this.pushResourceLimitCounters();
1915
+ }
1725
1916
  await this.parseTemplates();
1726
1917
  if (this.isRoot) {
1727
1918
  if (this.partials.size) {
1919
+ const { maxIncludeDepth } = resolveSecurityLimits(this.options.security);
1728
1920
  this.pushRaw(null, 'let d_=0;', 'const p={');
1729
1921
  for (const [path, code] of this.partials) {
1730
- this.pushRaw(null, `${JSON.stringify(path)}:async()=>{`, `if(d_>=${MAX_INCLUDE_DEPTH})throw new Error(${JSON.stringify(`Includes of ${JSON.stringify(path)} are nested too deeply`)});`, 'd_++;', 'try{return await(async()=>{', code, '})();}finally{d_--;}', '},');
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_--;}', '},');
1731
1923
  }
1732
1924
  this.pushRaw(null, '};');
1733
1925
  }
@@ -1776,6 +1968,19 @@ ${suggestionText}`;
1776
1968
  fingerprint() {
1777
1969
  return optionsFingerprint(this.options);
1778
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
+ }
1779
1984
  async isFresh({ sources }) {
1780
1985
  if (!this.revalidate) {
1781
1986
  return true;
@@ -1897,29 +2102,6 @@ ${suggestionText}`;
1897
2102
  }
1898
2103
  }
1899
2104
 
1900
- const special = /[&<>"']/;
1901
- const specials = /[&<>"']/g;
1902
- const entities = {
1903
- '&': '&amp;',
1904
- '"': '&#34;',
1905
- "'": '&#39;',
1906
- '<': '&lt;',
1907
- '>': '&gt;',
1908
- };
1909
- const entity = (char) => entities[char];
1910
- function escape(v) {
1911
- const str = typeof v === 'string' ? v : `${v}`;
1912
- // Most values contain nothing to escape; they are returned as they are,
1913
- // without allocating
1914
- return special.test(str) ? str.replace(specials, entity) : str;
1915
- }
1916
-
1917
- class Safe extends String {
1918
- constructor(value) {
1919
- super(`${value}`);
1920
- }
1921
- }
1922
-
1923
2105
  function abs(value = 0) {
1924
2106
  return Math.abs(value);
1925
2107
  }
@@ -2850,13 +3032,19 @@ ${suggestionText}`;
2850
3032
  : [[left.value, 'v_']];
2851
3033
  const scope = compiler.in();
2852
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
+ ];
2853
3041
  if (isReadOnly(body)) {
2854
3042
  // Nothing in the body can modify the scope, so a single one is shared by
2855
3043
  // all iterations instead of copying the outer context for each of them
2856
- 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};`));
2857
3045
  }
2858
3046
  else {
2859
- 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},`), '};');
2860
3048
  }
2861
3049
  await compiler.compileNodes(body);
2862
3050
  compiler.out();
@@ -3371,15 +3559,22 @@ ${suggestionText}`;
3371
3559
  async function compileMacro({ val: { value, args }, loc, body }, compiler) {
3372
3560
  const { context } = compiler;
3373
3561
  const expCompiler = new ExpCompiler();
3562
+ const { maxCallDepth } = resolveSecurityLimits(compiler.options.security);
3374
3563
  compiler.pushRaw(loc,
3375
3564
  // A macro collects its own output and returns it, so that it ends up
3376
3565
  // where the macro is called rather than where it was defined
3377
- `${context}.${value}=(...a_)=>async(_c)=>{`, 'let s="";', `const ${compiler.in()}={`, `...${context},`, ...(args ?? []).map((el, i) => el.type === 'ASSIGN'
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'
3378
3573
  ? `${el.left.value}:a_[${i}]===undefined?${expCompiler.compile(el.right)}:a_[${i}],`
3379
3574
  : `${el.value}:a_[${i}],`), '};');
3380
3575
  await compiler.compileNodes(body);
3381
3576
  compiler.out();
3382
- compiler.pushRaw(null, 'return s;', '};');
3577
+ compiler.pushRaw(null, 'return s;', ...(maxCallDepth == null ? [] : ['}finally{cd_--;}']), '};');
3383
3578
  }
3384
3579
  function compileCaller({ loc }, compiler) {
3385
3580
  compiler.pushRaw(loc, 's+=await _c?.()??"";');
@@ -3911,157 +4106,6 @@ ${suggestionText}`;
3911
4106
  }
3912
4107
  }
3913
4108
 
3914
- class SecuritySandbox {
3915
- constructor(options = {}) {
3916
- Object.defineProperty(this, "allowedGlobals", {
3917
- enumerable: true,
3918
- configurable: true,
3919
- writable: true,
3920
- value: void 0
3921
- });
3922
- Object.defineProperty(this, "cspNonce", {
3923
- enumerable: true,
3924
- configurable: true,
3925
- writable: true,
3926
- value: void 0
3927
- });
3928
- this.allowedGlobals = new Set(options.allowedGlobals || []);
3929
- this.cspNonce = options.cspNonce;
3930
- }
3931
- sanitizeGlobals(globals) {
3932
- const sanitized = {};
3933
- for (const [key, value] of Object.entries(globals)) {
3934
- if (this.allowedGlobals.has(key)) {
3935
- sanitized[key] = value;
3936
- }
3937
- }
3938
- return sanitized;
3939
- }
3940
- validateExpression(expression) {
3941
- // Prevent access to dangerous globals
3942
- const dangerousPatterns = [
3943
- /\bprocess\b/,
3944
- /\brequire\b/,
3945
- /\bimport\b/,
3946
- /\bexport\b/,
3947
- /\beval\b/,
3948
- /\bFunction\b/,
3949
- /\b__proto__\b/,
3950
- /\bconstructor\b/,
3951
- ];
3952
- for (const pattern of dangerousPatterns) {
3953
- if (pattern.test(expression)) {
3954
- return false;
3955
- }
3956
- }
3957
- return true;
3958
- }
3959
- createSecureContext(globals) {
3960
- const sanitized = this.sanitizeGlobals(globals);
3961
- // Add safe utility functions
3962
- return {
3963
- ...sanitized,
3964
- Math,
3965
- Date,
3966
- JSON,
3967
- // Add other safe built-ins as needed
3968
- };
3969
- }
3970
- getCSPNonce() {
3971
- return this.cspNonce;
3972
- }
3973
- generateCSPHeaders() {
3974
- const headers = {};
3975
- if (this.cspNonce) {
3976
- headers['Content-Security-Policy'] =
3977
- `script-src 'nonce-${this.cspNonce}'`;
3978
- }
3979
- return headers;
3980
- }
3981
- }
3982
- function deepEscape(value, seen = new WeakSet()) {
3983
- if (value === null || value === undefined) {
3984
- return '';
3985
- }
3986
- if (value instanceof Safe) {
3987
- return `${value}`;
3988
- }
3989
- if (typeof value === 'object') {
3990
- // Guard against circular references
3991
- if (seen.has(value)) {
3992
- return '';
3993
- }
3994
- seen.add(value);
3995
- const values = Array.isArray(value)
3996
- ? value
3997
- : Object.values(value);
3998
- return values.map((v) => deepEscape(v, seen)).join('');
3999
- }
4000
- return escape(value);
4001
- }
4002
- class SecurityAuditor {
4003
- auditTemplate(template) {
4004
- const issues = [];
4005
- // Check for dangerous patterns
4006
- const dangerousPatterns = [
4007
- {
4008
- pattern: /\beval\s*\(/,
4009
- type: 'dangerous-eval',
4010
- message: 'Use of eval() is dangerous and should be avoided',
4011
- severity: 'critical',
4012
- },
4013
- {
4014
- pattern: /\bFunction\s*\(/,
4015
- type: 'dangerous-function',
4016
- message: 'Use of Function constructor is dangerous',
4017
- severity: 'critical',
4018
- },
4019
- {
4020
- pattern: /\brequire\s*\(/,
4021
- type: 'require-usage',
4022
- message: 'Direct require() usage in templates is unsafe',
4023
- severity: 'high',
4024
- },
4025
- {
4026
- pattern: /\bimport\s*\(/,
4027
- type: 'dynamic-import',
4028
- message: 'Dynamic import() usage in templates may be unsafe',
4029
- severity: 'high',
4030
- },
4031
- ];
4032
- for (const { pattern, type, message, severity } of dangerousPatterns) {
4033
- const match = template.match(pattern);
4034
- if (match) {
4035
- issues.push({
4036
- type,
4037
- message,
4038
- location: `at index ${match.index}`,
4039
- severity,
4040
- });
4041
- }
4042
- }
4043
- // Calculate overall severity
4044
- const overallSeverity = this.calculateOverallSeverity(issues);
4045
- return {
4046
- issues,
4047
- severity: overallSeverity,
4048
- };
4049
- }
4050
- calculateOverallSeverity(issues) {
4051
- if (issues.length === 0) {
4052
- return 'low';
4053
- }
4054
- const severityMap = {
4055
- critical: 4,
4056
- high: 3,
4057
- medium: 2,
4058
- low: 1,
4059
- };
4060
- const maxSeverity = Math.max(...issues.map((issue) => severityMap[issue.severity]));
4061
- return Object.entries(severityMap).find(([, value]) => value === maxSeverity)[0];
4062
- }
4063
- }
4064
-
4065
4109
  // Thrown inside a template to stop rendering a stream nobody reads anymore
4066
4110
  const cancellation = new Error('Stream cancelled');
4067
4111
  class Renderer {
@@ -4275,7 +4319,24 @@ ${suggestionText}`;
4275
4319
  ...globals,
4276
4320
  }
4277
4321
  : { ...this.options.globals, ...globals };
4278
- 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
+ ]);
4279
4340
  }
4280
4341
  async renderFile(filepath, globals) {
4281
4342
  return this.render(await this.options.loader(filepath), globals);
@@ -5490,6 +5551,8 @@ export default script;
5490
5551
  exports.Renderer = Renderer;
5491
5552
  exports.RootNode = RootNode;
5492
5553
  exports.Safe = Safe;
5554
+ exports.SecurityAuditor = SecurityAuditor;
5555
+ exports.SecuritySandbox = SecuritySandbox;
5493
5556
  exports.TemplatePipeline = TemplatePipeline;
5494
5557
  exports.TemplateValidator = TemplateValidator;
5495
5558
  exports.Tokenizer = Tokenizer;
@@ -5507,6 +5570,7 @@ export default script;
5507
5570
  exports.createErrorRecovery = createErrorRecovery;
5508
5571
  exports.createFileLoader = createFileLoader;
5509
5572
  exports.createMixin = createMixin;
5573
+ exports.deepEscape = deepEscape;
5510
5574
  exports.defaultErrorHandler = defaultErrorHandler;
5511
5575
  exports.defaultWhitespaceOptions = defaultWhitespaceOptions;
5512
5576
  exports.defineFilters = defineFilters;
@@ -5533,6 +5597,7 @@ export default script;
5533
5597
  exports.renderFile = renderFile;
5534
5598
  exports.renderOptions = renderOptions;
5535
5599
  exports.renderStream = renderStream;
5600
+ exports.resolveSecurityLimits = resolveSecurityLimits;
5536
5601
  exports.templateCacheKey = templateCacheKey;
5537
5602
  exports.validateTemplate = validateTemplate;
5538
5603