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