From b9af44bfdedbd480912b29b6ad16ab7918c37b76 Mon Sep 17 00:00:00 2001 From: Nicholas Husher Date: Tue, 10 Oct 2023 12:55:15 -0400 Subject: [PATCH] Transpile backtick characters (`) correctly into JS In Lua they don't (appear?) to be syntactically relevant, but in JS they very much are, especially with the way that the Lua syntax is compiled into JS. For example: ```lua return "This is a `string with backticks` in it" ``` Is compiled to JS as: ``` return [`This is a `string with backticks` in it`] ``` Where "string with backticks" is evaluated as literal JS code. This is _potentially_ a security issue because a specially-formatted string could evaluate arbitrary JS code. More annoyingly, though, it means that any string with backticks in it is probably going to cause the JS interpeter to crash. This commit fixes that by escaping backtick characters with a \, so the compiled JS above would instead look like: ``` return [`This is a \`string with backticks\` in it`] ``` Much better! --- src/parser.ts | 1 + tests/test.js | 13 +++++++++++++ 2 files changed, 14 insertions(+) diff --git a/src/parser.ts b/src/parser.ts index 8aac376..a5dcac0 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -223,6 +223,7 @@ const generate = (node: luaparse.Node): string | MemExpr => { const S = node.value .replace(/([^\\])?\\(\d{1,3})/g, (_, pre, dec) => `${pre || ''}${String.fromCharCode(dec)}`) .replace(/\\/g, '\\\\') + .replace(/`/g, '\\`') return `\`${S}\`` } diff --git a/tests/test.js b/tests/test.js index 062c99d..9406ea5 100644 --- a/tests/test.js +++ b/tests/test.js @@ -40,4 +40,17 @@ let exitCode = 0 } } +{ + const luaEnv = luainjs.createEnv() + let str + try { + str = luaEnv.parse('return "Backtick `literals` in strings work"').exec() + } catch (e) { + throw Error('Backticks in strings transpile into invalid code!') + } + if (str !== 'Backtick `literals` in strings work') { + throw Error('Backticks in strings transpile incorrectly!') + } +} + process.exit(exitCode)