Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the basic function of JavaScript sandbox

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to realize the basic functions of JavaScript sandbox". In daily operation, I believe many people have doubts about how to realize the basic functions of JavaScript sandbox. Xiaobian consulted all kinds of materials and sorted out simple and easy operation methods. I hope to help you answer the doubts about "how to realize the basic functions of JavaScript sandbox"! Next, please follow the small series to learn together!

1. Scene

Recently we've been working on something similar to a plug-in system based on the web, so we've had a bit of a js sandbox to execute code for third-party apps.

2. Sandbox basic functions

Before implementation (well, actually after investigating some scenarios), we determined the upper layer functions of sandbox-based event bus communication implementation. The basic interfaces are as follows.

export interface IEventEmitter { /** * surveillance incident * @param channel * @param handle */ on(channel: string, handle: (data: any) => void): void; /** * Cancel listening * @param channel */ offByChannel(channel: string): void; /** * trigger event * @param channel * @param data */ emit(channel: string, data: any): void;}/** * A basic js vm capability */export interface IJavaScriptShadowbox extends IEventEmitter { /** * execute arbitrary code * @param code */ eval(code: string): void; /** * terminate instance */ destroy(): void;}

In addition to the ability to communicate, two additional methods are required:

eval: Execute a piece of JS code

destroy: Destroy the sandbox for internal implementation to handle some cleanup tasks

JavaScript sandbox diagram:

We'll demonstrate how to execute arbitrary js using iframe/web worker/quickjs

3, iframe implementation

To be honest, iframes are probably the first thing that comes to mind when it comes to sandboxes in the web, but it uses html as the entry file, not js, which is not very friendly for scenarios where you want js as the entry without necessarily having to display iframes.

Of course, you can wrap js code in html and execute it

function evalByIframe(code: string) { const html = `$[code]`; const iframe = document.createElement("iframe"); iframe.width = "0"; iframe.height = "0"; iframe.style.display = "none"; document.body.appendChild(iframe); const blob = new Blob([html], { type: "text/html" }); iframe.src = URL.createObjectURL(blob); return iframe;}evalByIframe(`document.body[xss_clean] = 'hello world'console.log('location.href: ', location.href)console.log('localStorage: ',localStorage)`);

But iframe has the following problems:

Almost no different from eval (mainly using Object.createObjectURL leads to homology)-fatal

Access to all browser APIs-we prefer it to only access injected APIs and not allow access to all dom APIs

4. Web worker implementation

Basically, a web worker is a limited JS runtime, with JS as the entry point, similar to iframe communication mechanism.

function evalByWebWorker(code: string) { const blob = new Blob([code], { type: "application/javascript" }); const url = URL.createObjectURL(blob); return new Worker(url);}evalByWebWorker(`console.log('location.href: ', location.href)// console.log('localStorage: ', localStorage)`);

But at the same time, it's actually a little bit better than iframe.

Only a limited number of browser APIs are supported, including localStorage/document APIs, which cannot be accessed. For details, see: [MDN] Functions and classes that Web Workers can use

All injected APIs are asynchronous operations, after all based on postMessage/onMessage

5, quickjs implementation

The main inspiration for using quickjs comes from a blog about figma building plug-in system, quickjs Chinese documentation

What is quickjs? It's a JavaScript runtime, and while our most commonly used runtimes are browser and nodejs, there are many others, and you can find more at Google Chrome Labs/jsvu. Quickjs is one of those lightweight, embedded runtimes that supports compilation to wasm running on browsers, and it supports js features up to es2020 (including favorites Promise and async/await).

async function evalByQuickJS(code: string) { const quickJS = await getQuickJS(); const vm = quickJS.createVm(); const res = vm.dump(vm.unwrapResult(vm.evalCode(code))); vm.dispose(); return res;} console.log(await evalByQuickJS(`1+1`));

Advantages:

In fact, it is unmatched in terms of security, because running on different VMs, it is difficult to present the security problems that existing micro-front ends based on proxies may present.

Although there was no actual testing, figma's blog post pointed out that structured clones of browsers have performance problems with large objects, which quickjs does not.

Disadvantages:

There is no global api, including the common console/setTimeout/setInterval, which is not a feature of js, but is implemented by the browser and nodejs runtime, so it must be manually implemented and injected, which is a significant disadvantage.

Cannot debug using DevTool in browser

Since the underlying implementation uses c, you need to manually manage the release of memory.

At this point, the study of "how to implement the basic functions of JavaScript sandbox" is over, hoping to solve everyone's doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report