Compiling user's code - the right way

Hi, so I have been trying to create some kind of a leetcode like app for JS code only in my SvelteKit app. I run into a problem that I have no clue how to actually do that right. I have already been able to create something using 'isolated-vm' but it does not look like the best way to do it.
import { json } from "@sveltejs/kit"
import ivm from "isolated-vm"

export const POST = async ({ request }) => {
const { code } = await request.json()
console.log(code)
if (!code) throw new Error('No code provided');

const isolate = new ivm.Isolate();
const context = await isolate.createContext();

try {
const result = await (await isolate.compileScript(code)).run(context);
console.log(result)
if (result === undefined) return json('undefined');
return json(result.toString());
} catch (error) {
throw new Error(error);
} finally {
await isolate.dispose();
}
}
import { json } from "@sveltejs/kit"
import ivm from "isolated-vm"

export const POST = async ({ request }) => {
const { code } = await request.json()
console.log(code)
if (!code) throw new Error('No code provided');

const isolate = new ivm.Isolate();
const context = await isolate.createContext();

try {
const result = await (await isolate.compileScript(code)).run(context);
console.log(result)
if (result === undefined) return json('undefined');
return json(result.toString());
} catch (error) {
throw new Error(error);
} finally {
await isolate.dispose();
}
}
So that's it I guess, hope someone smart will come by this, thanks for any help :).
2 Replies
Matvey
Matvey14mo ago
Why don't run the untrusted code in the user's browser
Zikado
ZikadoOP14mo ago
Thanks for the response, do you have any idea about correct implementation? I have read something about web workers or iframes doing the job connected with some sandboxing library.
Want results from more Discord servers?
Add your server