UNPKG

twing

Version:

First-class Twig engine for Node.js

75 lines (74 loc) 3.36 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createSandboxSecurityPolicy = void 0; const markup_1 = require("../markup"); const createSandboxSecurityPolicy = (clearances) => { const allowedTags = (clearances === null || clearances === void 0 ? void 0 : clearances.allowedTags) || []; const allowedFilters = (clearances === null || clearances === void 0 ? void 0 : clearances.allowedFilters) || []; const allowedMethods = (clearances === null || clearances === void 0 ? void 0 : clearances.allowedMethods) || new Map(); const allowedProperties = (clearances === null || clearances === void 0 ? void 0 : clearances.allowedProperties) || new Map(); const allowedFunctions = (clearances === null || clearances === void 0 ? void 0 : clearances.allowedFunctions) || []; const policy = { checkMethodAllowed: (candidate, method) => { if ((0, markup_1.isAMarkup)(candidate)) { return; } let allowed = false; for (const [constructorName, methods] of allowedMethods) { if (candidate instanceof constructorName) { allowed = methods.includes(method); break; } } if (!allowed) { const constructorName = candidate.constructor.name || '(anonymous)'; throw new Error(`Calling "${method}" method on an instance of ${constructorName} is not allowed.`); } }, checkPropertyAllowed: (candidate, property) => { let allowed = false; for (let [objectConstructor, properties] of allowedProperties) { if (candidate instanceof objectConstructor) { allowed = properties.includes(property); break; } } if (!allowed) { const constructorName = candidate.constructor.name || '(anonymous)'; throw new Error(`Calling "${property}" property on an instance of ${constructorName} is not allowed.`); } }, checkSecurity: (tags, filters, functions) => { for (const tagName of tags) { if (!allowedTags.includes(tagName)) { return ({ message: `Tag "${tagName}" is not allowed.`, token: tagName, type: "tag" }); } } for (const filterName of filters) { if (!allowedFilters.includes(filterName)) { return ({ message: `Filter "${filterName}" is not allowed.`, token: filterName, type: "filter" }); } } for (const functionName of functions) { if (!allowedFunctions.includes(functionName)) { return ({ message: `Function "${functionName}" is not allowed.`, token: functionName, type: "function" }); } } return null; } }; return policy; }; exports.createSandboxSecurityPolicy = createSandboxSecurityPolicy;