Telegram messages · a sandbox for HTML widgets · how it works

widget-sandbox architecture

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.

State 9 October 2026 Platforms web, iOS, macOS, Android, C++ for Telegram Desktop Checks 22 compat, 40 generated, 89 attacks Code 6,300 lines of TypeScript, 1,800 Swift, 1,800 Kotlin, 2,000 C++

The idea in three sentences

Three zones

Sandbox. A dedicated thread; everything inside is treated as hostile quickjs-ng, 8 MB stack, 64 MB memory cap, 500 ms per call, 300 ms of CPU per second, no network objects The widget file as sent script, DOM calls, canvas, localStorage sandbox-bundle.js DOM (linkedom + parse5), browser API shim, network stubs Trusted glue. One copy per platform, one policy for all worker.ts, SandboxEngine.swift, SandboxEngine.kt, sandbox_engine.cpp; CpuBudget in four copies against one fixture Engine glue CPU budget, timers, visibility, kill, Intl from the host validator-bundle.js schema, tag and attribute allowlists, CSS sanitizer, URL policy ops ↓ events and answers ↑ Renderer. Trusted code only, never sees a foreign string strict CSP, every navigation cancelled, network requests blocked by the platform, the test canary must stay silent renderer-bundle.js applies validated operations, returns events and sizes WKWebView · Android WebView · iframe or a native backend where there is no WebView validated ops ↓ events ↑
bot contentshared JS, identical on every platformper platform, swappable

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.

Who does what

PartWhere it livesSizeWhat it doesTrust
Shim and DOMsrc/sandbox/ → sandbox-bundle.js499 KBGives 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
Validatorsrc/host/validator.ts, allowlist.ts, css-sanitizer.ts, url-policy.ts → validator-bundle.js226 KBChecks 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
Renderersrc/renderer/ → renderer-bundle.js17 KBHolds 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
Gluesrc/host/worker.ts, widget-host.ts; Swift, Kotlin, C++400–1,800 lines per platformStarts 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 policycpu-budget.ts, CpuBudget.swift, CpuBudget.kt, cpu_budget.cpp4 copiesA pure function: "how many milliseconds does the next task get". All copies are checked against one fixture, tests/fixtures/cpu-budget.json.trusted
Librarieslibs/chart.umd.js, libs/d3.min.js209 + 280 KBThe widget writes the usual CDN URL, the loader substitutes the bundled copy. Nothing is downloaded.trusted code in the hostile zone

The path of one click

The user tapped a button in the widget. This is what happens in the next few milliseconds.

1. WebView click on node #17 2. Glue "event" task, CPU slice 3. Sandbox the widget's handler changes its DOM, the shim collects a diff 4. Batch of operations text #23 "5", attr #17 class, ins #40 … 5. Validator schema, allowlist, CSS, URL 6. WebView applies, WebKit draws Sync query: getBoundingClientRect, getBBox, measureText. The sandbox thread waits for the answer for at most 3 s; the answer is cached until the next batch of operations.
What flowsFrom → toExamples
Operationssandbox → glue → validator → rendererel, ins, rm, text, attr, style, css, prop, canvas, call
Eventsrenderer → glue → sandboxclick, input with the field value, submit, keys, pointer, scroll, transitionend, visibilitychange, theme
Sync queriesthe sandbox waits, the glue asks the rendererrect, box, cs (computed style), svg (getBBox, getCTM, getTotalLength…), measureText, imageData, matchMedia, elementFromPoint, validity
Ticksglue → sandboxtimers, rAF frames (only while the bubble is visible), viewport, theme
Bridge to the chatsandbox → glue → host appTelegramWidget.sendMessage, openLink through a native dialog, onTheme
Diagnosticsvalidator and glue → panelurl-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.

Lifecycle and limits

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.

Loading boot ≈ 40 ms, first render Visible frames, timers, events Hidden no frames, timers at 1 Hz Frozen runtime killed a limit was broken: 500 ms in one call, 64 MB, sustained quota overrun the last rendered DOM stays on screen with an error badge; on hidden → visible one frame is requested if the shim asked for it
LimitDefaultWhat happens when it is broken
One synchronous call500 ms (cpuLimitMs)the interrupt handler stops the engine, the runtime is killed, the frozen last render stays
CPU per second300 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 memory64 MB (JS_SetMemoryLimit)the allocation throws, the runtime is killed
Timers256 active, delay ≤ 24 han extra timer is refused in the glue even if the shim let it through
Tree size50,000 nodes, text ≤ 2 MB, attribute ≤ 4 MB, 200,000 operations per batchthe batch is rejected by the validator with a diagnostic
Bootup to 5 s, the full cpuLimitMs per taskloading the bundle and the first run of the scripts are not cut by the quota, otherwise every widget would start throttled
Sync query3 sthe answer is {error: 'timeout'}, the widget keeps running

What the widget author sees

Works

  • All the markup and CSS WebKit knows: grid, flex, custom properties, transition, @keyframes, @container, inline SVG, forms, <details>, <dialog>.
  • Inline scripts in document order, ES2023, Promise, timers, rAF, MutationObserver, ResizeObserver, Intl, crypto.randomUUID.
  • DOM API: selectors, innerHTML, classList, dataset, forms with value and checkValidity, size measurements, getComputedStyle.
  • Canvas 2D (no bundled libraries since widget profile 1).
  • The chat theme through prefers-color-scheme, light-dark() and TelegramWidget.onTheme.

Does not work, by design

  • Any network: scripts, images, fonts, stylesheets, fetch, WebSocket, WebRTC. Images and fonts only as data:.
  • WebGL, Web Audio, workers, navigation, 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.

Platforms

The three JS bundles are built once and copied into every port by scripts/build-native-bundles.ts. Only the glue is ported.

PlatformEngine and threadGlueRendererVerified
WebQuickJS-wasm in a Worker; sync via SharedArrayBufferworker.ts, widget-host.tssandboxed iframe, allow-scripts allow-forms, CSPcompat 20/20, generated 40/40 pixel-matched, 89 attacks with 0 hits
iOS and macOSquickjs-ng in C, its own JSThread with an 8 MB stackSandboxEngine.swift, one package, #if canImport(UIKit) branchesWKWebView, navigation cancelled, requests blocked21 tests, generated 40/40 on the simulator and an iPhone, macOS autorun, pause on window occlusion
Androidquickjs-ng via JNI, JSThread.ktSandboxEngine.ktAndroid WebView, shouldInterceptRequest, gesture interception27 instrumented tests, 82 attacks with 0 hits, both corpora on the emulator and a phone
Telegram Desktopquickjs-ng, std::thread with 8 MB, no Qt neededsandbox_engine.cpp, trusted_validatorno WebView in the chat: the Web App window, or a native backend on QPainter over the same operations21 tests, 89 attacks with 0 leaks into validated operations, both corpora load

What this architecture gives

What it costs

How it is tested

89
attack files: network through APIs, markup, CSS and navigation; CPU burn; fallback on kill. The canary on 127.0.0.1:9999 must record 0 requests on every platform
22 + 40
compat widgets and model-generated widgets, each compared with native rendering pixel by pixel and by behaviour after clicks
1 fixture
for four copies of the limit policy; plus the lifecycle test: off screen, frames stop, timers at 1 Hz, visibilitychange arrives

Working 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.