A bot sends an ordinary HTML file with a script into the chat. widget-sandbox runs it whole, but in a cage: the script executes in the small QuickJS engine against its own copy of the DOM, with no screen and no network. Everything the script changes in that copy becomes a list of operations, the list is checked against allowlists, and only then does trusted code apply it to the real page in the system WebView. Three zones, one trust boundary, the same three JS files on five platforms.
document, events, timers and canvas. Nothing has to be rewritten.There is one trust boundary: between the first and the second zone. Everything that leaves QuickJS is hostile until the validator says otherwise. The renderer is protected once more in case the validator fails: it refuses forbidden tags on its own, and CSP plus request blocking keep the page off the network even if something slips through.
| Part | Where it lives | Size | What it does | Trust |
|---|---|---|---|---|
| Shim and DOM | src/sandbox/ → sandbox-bundle.js | 499 KB | Gives the widget document, events, forms, styles, canvas as a command stream, in-memory localStorage, timers and rAF through the host. Network APIs throw NetworkDisabledError. Collects mutation diffs into batches. | hostile environment, runs next to the bot's code |
| Validator | src/host/validator.ts, allowlist.ts, css-sanitizer.ts, url-policy.ts → validator-bundle.js | 226 KB | Checks every operation against a strict schema: tags, attributes and CSS properties by allowlist, URLs only data: and #fragment, caps on nodes and sizes. Natively it runs in a second, trusted QuickJS runtime. | trusted, hostile input |
| Renderer | src/renderer/ → renderer-bundle.js | 17 KB | Holds the live DOM in the WebView, applies operations, listens to events at document level, answers size queries, tracks the theme and the height. | trusted, receives no foreign strings |
| Glue | src/host/worker.ts, widget-host.ts; Swift, Kotlin, C++ | 400–1,800 lines per platform | Starts QuickJS on its own thread, accounts the CPU quota, drives timers and frames, knows whether the bubble is visible, kills the runtime, provides Intl and the bridge to the chat. This is the only part that gets ported. | trusted |
| Limit policy | cpu-budget.ts, CpuBudget.swift, CpuBudget.kt, cpu_budget.cpp | 4 copies | A pure function: "how many milliseconds does the next task get". All copies are checked against one fixture, tests/fixtures/cpu-budget.json. | trusted |
| Libraries | libs/chart.umd.js, libs/d3.min.js | 209 + 280 KB | The widget writes the usual CDN URL, the loader substitutes the bundled copy. Nothing is downloaded. | trusted code in the hostile zone |
The user tapped a button in the widget. This is what happens in the next few milliseconds.
| What flows | From → to | Examples |
|---|---|---|
| Operations | sandbox → glue → validator → renderer | el, ins, rm, text, attr, style, css, prop, canvas, call |
| Events | renderer → glue → sandbox | click, input with the field value, submit, keys, pointer, scroll, transitionend, visibilitychange, theme |
| Sync queries | the sandbox waits, the glue asks the renderer | rect, box, cs (computed style), svg (getBBox, getCTM, getTotalLength…), measureText, imageData, matchMedia, elementFromPoint, validity |
| Ticks | glue → sandbox | timers, rAF frames (only while the bubble is visible), viewport, theme |
| Bridge to the chat | sandbox → glue → host app | TelegramWidget.sendMessage, openLink through a native dialog, onTheme |
| Diagnostics | validator and glue → panel | url-blocked, tag-dropped, network-blocked, cpu-throttled, timer-limit-enforced |
Every message is flat JSON that can be logged and replayed in tests. Nodes are addressed by numeric ids handed out by the sandbox; the renderer never receives an HTML string, only "create a div element with id 17". On the web, sync queries go through SharedArrayBuffer and Atomics.wait; natively through a semaphore. The sandbox thread is the one that waits, never the main thread.
Every decision about how much the widget may do is made by the glue, that is by trusted code. The sandbox learns about it after the fact: a frame did not arrive, a timer fired late, an "out of memory" exception.
| Limit | Default | What happens when it is broken |
|---|---|---|
| One synchronous call | 500 ms (cpuLimitMs) | the interrupt handler stops the engine, the runtime is killed, the frozen last render stays |
| CPU per second | 300 ms of 1000 (cpuQuotaMs) | frames and timers are deferred to the next window; the widget animates less often but stays alive; cpu-throttled diagnostic; killing on sustained overrun is enabled by config |
| Runtime memory | 64 MB (JS_SetMemoryLimit) | the allocation throws, the runtime is killed |
| Timers | 256 active, delay ≤ 24 h | an extra timer is refused in the glue even if the shim let it through |
| Tree size | 50,000 nodes, text ≤ 2 MB, attribute ≤ 4 MB, 200,000 operations per batch | the batch is rejected by the validator with a diagnostic |
| Boot | up to 5 s, the full cpuLimitMs per task | loading the bundle and the first run of the scripts are not cut by the quota, otherwise every widget would start throttled |
| Sync query | 3 s | the answer is {error: 'timeout'}, the widget keeps running |
transition, @keyframes, @container, inline SVG, forms, <details>, <dialog>.MutationObserver, ResizeObserver, Intl, crypto.randomUUID.innerHTML, classList, dataset, forms with value and checkValidity, size measurements, getComputedStyle.prefers-color-scheme, light-dark() and TelegramWidget.onTheme.fetch, WebSocket, WebRTC. Images and fonts only as data:.window.open (replaced by a host dialog).localStorage lives only as long as the widget does.preventDefault() from the sandbox is asynchronous: navigation and submit are always cancelled; the first checkbox toggle or text input may show its native behaviour for one frame.Intl.formatToParts is not there yet.This list is published as the runtime profile (docs/widget-runtime-profile.md). A model that gets it in the tool description generates widgets that pass without a single blocked request: 20 of 20 in the test.
The three JS bundles are built once and copied into every port by scripts/build-native-bundles.ts. Only the glue is ported.
| Platform | Engine and thread | Glue | Renderer | Verified |
|---|---|---|---|---|
| Web | QuickJS-wasm in a Worker; sync via SharedArrayBuffer | worker.ts, widget-host.ts | sandboxed iframe, allow-scripts allow-forms, CSP | compat 20/20, generated 40/40 pixel-matched, 89 attacks with 0 hits |
| iOS and macOS | quickjs-ng in C, its own JSThread with an 8 MB stack | SandboxEngine.swift, one package, #if canImport(UIKit) branches | WKWebView, navigation cancelled, requests blocked | 21 tests, generated 40/40 on the simulator and an iPhone, macOS autorun, pause on window occlusion |
| Android | quickjs-ng via JNI, JSThread.kt | SandboxEngine.kt | Android WebView, shouldInterceptRequest, gesture interception | 27 instrumented tests, 82 attacks with 0 hits, both corpora on the emulator and a phone |
| Telegram Desktop | quickjs-ng, std::thread with 8 MB, no Qt needed | sandbox_engine.cpp, trusted_validator | no WebView in the chat: the Web App window, or a native backend on QPainter over the same operations | 21 tests, 89 attacks with 0 leaks into validated operations, both corpora load |
getBoundingClientRect or getBBox is a hop between threads. D3 with hundreds of measurements in a loop is the known bottleneck, covered by a cache until the next mutation, but not free.preventDefault. The sandbox cannot cancel a native action in the same frame. Navigation and submit are always cancelled; the rest by learned cases.SharedArrayBuffer, which may interfere with other embeddings.visibilitychange arrivesWorking rules: the shim is fixed in general, never for one widget; a regression in the corpus is a shim bug until proven otherwise; the invariants (JS only inside QuickJS, everything from the sandbox is hostile, the renderer receives only validated operations, no URLs other than data: and #, no network, defence in depth) are not relaxed without discussion.