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