From 24ae2b6fa63af38fdedffa77b04a5a68dc7ce0f5 Mon Sep 17 00:00:00 2001 From: Cohee <18619528+Cohee1207@users.noreply.github.com> Date: Tue, 25 Jun 2024 22:15:40 +0300 Subject: [PATCH] Add sanitation of macro values --- public/scripts/macros.js | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/public/scripts/macros.js b/public/scripts/macros.js index ef6ffec71..c3c35232e 100644 --- a/public/scripts/macros.js +++ b/public/scripts/macros.js @@ -42,7 +42,8 @@ export class MacrosParser { } if (typeof value !== 'string' && typeof value !== 'function') { - throw new Error('Macro value must be a string or a function that returns a string'); + console.warn(`Macro value for "${key}" will be converted to a string`); + value = this.sanitizeMacroValue(value); } if (this.#macros.has(key)) { @@ -72,6 +73,27 @@ export class MacrosParser { env[key] = value; } } + + /** + * Performs a type-check on the macro value and returns a sanitized version of it. + * @param {any} value Value returned by a macro + * @returns {string} Sanitized value + */ + static sanitizeMacroValue(value) { + if (typeof value === 'string') { + return value; + } + + if (value === null || value === undefined) { + return ''; + } + + if (typeof value === 'object') { + return JSON.stringify(value); + } + + return String(value); + } } /** @@ -384,7 +406,7 @@ export function evaluateMacros(content, env) { if (!Object.hasOwn(env, varName)) continue; const param = env[varName]; - const value = typeof param === 'function' ? param() : param; + const value = MacrosParser.sanitizeMacroValue(typeof param === 'function' ? param() : param); content = content.replace(new RegExp(`{{${escapeRegex(varName)}}}`, 'gi'), value); }