| 6 | [`packages/ios/`](../packages/ios/README.md) (Swift package `WidgetSandbox` + demo app; the same |
| 7 | package compiles for AppKit, see [`apps/macos/`](../apps/macos/README.md)) and |
| 8 | [`packages/android/`](../packages/android/README.md) (Gradle library `widget-sandbox` + Compose |
| 9 | demo); the Windows / Linux column remains a plan (the official desktop client |
| 10 | would take the C++ core in `packages/desktop/`, see `docs/decisions.md`). |
| 11 |
| 12 | ## Component mapping |
| 13 |
| 14 | | Prototype (web) | iOS / macOS | Android | Desktop (Windows / Linux) | |
| 15 | |---|---|---|---| |
| 16 | | `Worker` + `quickjs-emscripten` | QuickJS-ng (C) on a dedicated `Thread` with a large stack (not a `DispatchQueue`: pool threads hop and have 512 KB stacks — see `docs/decisions.md`) | QuickJS-ng (same vendored C sources, NDK/CMake) through a 300-line JNI layer on a `JSThread` (plain `Thread` with an 8 MB stack + `Looper`; `HandlerThread` cannot set the stack size) | QuickJS-ng on a `std::thread` | |
| 17 | | `packages/core/src/sandbox/*` bundle (shim + linkedom + parse5), evaluated as source | same bundle, **precompiled to QuickJS bytecode** (`JS_WriteObject`), loaded with `JS_ReadObject` + `JS_EvalFunction` | same (source eval for now, like iOS) | same | |
| 18 | | `__host(kind, arg)` C→JS function | `JS_NewCFunction` with the same string API | same | same | |
| 19 | | `Validator` (TypeScript, no DOM dependency) | port to Swift (or compile the TS to JS and run it in a second, trusted QuickJS context) | trusted QuickJS context (`TrustedValidator.kt`, same `validator-bundle.js`) | C++ / trusted QuickJS | |
| 20 | | `<iframe sandbox srcdoc>` + nonce CSP | `WKWebView` loading the renderer document from a custom `WKURLSchemeHandler`; CSP as an HTTP header; `WKContentRuleList` blocking `http(s)`/`ws(s)`; non-persistent `WKWebsiteDataStore`; `decidePolicyFor` cancels every navigation; macOS additionally empties the context menu and refuses `runOpenPanelWith` | `WebView`; `shouldInterceptRequest` serves the document on `https://w-<uuid>.tgwidget.invalid/` and answers everything else with an empty 403; CSP as header and `<meta>`; `setBlockNetworkLoads(true)`; `shouldOverrideUrlLoading` cancels; document-start hardening script; windows/dialogs/permissions/storage off | WebView2 in its own environment with `--host-resolver-rules="MAP * ~NOTFOUND"`, `--proxy-server=…dead…`, `--webrtc-ip-handling-policy=disable_non_proxied_udp`; `NavigationStarting` cancels | |
| 21 | | `MessageChannel` port host ⇄ renderer | `WKScriptMessageHandler` (renderer → host, `window.webkit.messageHandlers.tg.postMessage`) and `evaluateJavaScript` / `callAsyncJavaScript` (host → renderer); or `WKWebView` `MessagePort` through `postMessage` | `@JavascriptInterface` object `tw` (renderer → host) + `evaluateJavascript("__twReceive(…)")` (host → renderer); binary results as base64 | `PostWebMessageAsJson` / `WebMessageReceived` | |
| 22 | | `SharedArrayBuffer` + `Atomics.wait/notify` sync query bridge | `DispatchSemaphore` (QuickJS thread waits; main thread evaluates the query in the WebView — `evaluateJavaScript` completion handler signals) | `Semaphore` (engine thread waits ≤ 3 s; main thread validates and calls `evaluateJavascript`; the bridge callback releases) | `std::binary_semaphore` + `ExecuteScript` callback | |
| 23 | | Dev server COOP/COEP | not needed | not needed | not needed | |
| 24 | | `setInterruptHandler` deadline | `JS_SetInterruptHandler` with `mach_absolute_time` | same with `CLOCK_BOOTTIME` (= `SystemClock.elapsedRealtimeNanos`) | same | |
| 25 | | `setMemoryLimit` + a `WebAssembly.Memory` with `maximum = 16 MB + limit` (the emscripten build cannot count its heap, `decisions.md`) | `JS_SetMemoryLimit` counts via `malloc_size`, nothing else needed | same via bionic `malloc_usable_size` | same (`_msize` / glibc) | |
| 26 | | `performance.now()` via host | monotonic clock | same | same | |
| 27 | | `Intl` delegated to host | `NumberFormatter`, `DateFormatter`, `String.localizedCompare` | `android.icu.text.*` (NumberFormat, DateFormat skeletons, PluralRules, RelativeDateTimeFormatter, ListFormatter, Collator) | ICU | |
| 28 |
| 29 | ## Things that change |
| 30 |
| 31 | ### Sync queries on native |
| 32 |
| 33 | The sandbox thread must block while the UI thread asks the WebView. On the web |
| 34 | the worker blocks in `Atomics.wait`; natively the QuickJS thread waits on a |
| 35 | semaphore. Two consequences, same as on the web: |
| 36 |
| 37 | 1. **Never run QuickJS on the UI thread** — a blocked UI thread would deadlock |
| 38 | on its own WebView. |
| 39 | 2. The WebView must answer **inside one run-loop turn**. `evaluateJavaScript` |
| 40 | returns asynchronously but reasonably fast (~0.1–0.5 ms on iOS for a |
| 41 | `getBoundingClientRect`). The prototype's query cache (valid until the next |
| 42 | flush) is what keeps D3-style layout loops bearable; keep it. |
| 43 |
| 44 | The timeout (3 s on the web) becomes the safety net for a frozen WebView. |
| 45 |
| 46 | ### Swift renderer task boundaries |
| 47 |
| 48 | `TaskRenderer` is an optional Swift renderer interface. The host delivers |
| 49 | `beginTask()` and `endTask()` around a sandbox task through the same ordered |
| 50 | validation/executor pipeline as its operations and queries. A native renderer |
| 51 | can lay out intermediate changes to answer a synchronous query while delaying |
| 52 | presentation and height notifications until the task ends. Query answers must |
| 53 | not wait for `endTask()`: the script is blocked on that answer. |
| 54 |
| 55 | This is a renderer presentation optimization, not a widget profile feature or |
| 56 | a new SDK capability. A renderer without this interface still receives the same |
| 57 | validated operations and query requests. The interface does not change script |
| 58 | execution, validation, query answers, CPU accounting, event policy or the shared |
| 59 | wire protocol, so Kotlin, C++ and the web do not need a matching presentation |
| 60 | callback. A change to any of those shared behaviors would require the parity |
| 61 | work in `CONTRIBUTING.md`; a platform-only callback is not permission to change |
| 62 | the contract. |
| 63 |
| 64 | The engine closes a started task after a script exception or CPU-limit stop. |
| 65 | When the renderer is not ready, the host buffers task boundaries along with the |
| 66 | operations and replays them in order. Destroying the host discards later |
| 67 | renderer delivery and releases a blocked query; renderer destruction must |
| 68 | release any held presentation state without waiting for another callback. |
| 69 |
| 70 | `TaskRendererHostTests` exercises the real Swift host, QuickJS engine and |
| 71 | validator with synchronous/asynchronous validation, JSON/typed binary output, |
| 72 | buffered startup, exceptions, CPU stops and destruction during a query. It also |
| 73 | compares a plain renderer with a task-aware renderer for identical validated |
| 74 | operations, query requests and script-observed answers. Native pixel and |
| 75 | presentation tests remain in the renderer repository; these host tests alone |
| 76 | do not establish visual parity across clients. |
| 77 |
| 78 | ### Renderer is the same JavaScript |
| 79 |
| 80 | `packages/core/src/renderer/renderer.ts` is a plain script with no bundler-specific code. It |
| 81 | only needs `postMessage`/`onmessage` replaced by the platform bridge; the |
| 82 | `RenderOp` applier, event serializer and query answerer are unchanged. The |
| 83 | renderer document is tiny (`srcdoc.ts`), so serving it from a custom scheme is |
| 84 | trivial, and the nonce CSP can be sent as a response header instead of a |
| 85 | `<meta>`. |
| 86 |
| 87 | ### Validator placement |
| 88 |
| 89 | The validator must run in trusted code **outside** the widget's QuickJS context |
| 90 | and **before** the WebView. Two viable placements: |
| 91 |
| 92 | - a native port (Swift/Kotlin/C++) — most auditable, ~900 lines + css-tree |
| 93 | replacement (a real CSS parser is needed; `swift-css-parser`, `ph-css`, or |
| 94 | running css-tree in a *trusted* QuickJS context); |
| 95 | - the same TypeScript compiled to JS and run in a second, trusted QuickJS |
| 96 | context (one per app, not per widget). This reuses `css-tree` unchanged and |
| 97 | keeps a single implementation across platforms; the cost is one extra |
| 98 | JSON round trip per batch. |
| 99 |
| 100 | ### Bytecode (done, Oct 2026) |
| 101 |
| 102 | `packages/core/scripts/build-native-bundles.ts` compiles the sandbox bundle, the validator |
| 103 | bundle and the bundled libraries to quickjs-ng bytecode next to each `.js` |
| 104 | (`sandbox-bundle.qbc`, `validator-bundle.qbc`, `libs/*.qbc`) with |
| 105 | `packages/tools/qjsc/qjsc.c`, a 60-line tool built on the fly from the vendored |
| 106 | `packages/ios/Sources/CQuickJS` — the same sources every port links, so the bytecode |
| 107 | format (quickjs-ng `BC_VERSION`) always matches the engine. The blob is a |
| 108 | `TWQB` container (format version, source length, FNV-1a 64 of the source) in |
| 109 | front of `JS_WriteObject(JS_WRITE_OBJ_BYTECODE | JS_WRITE_OBJ_STRIP_SOURCE)` |
| 110 | output; `qjs_eval_bytecode` in `qjs_shim.c` checks the header against the |
| 111 | source the host would otherwise evaluate and quickjs-ng checks its own version |
| 112 | byte, so a stale `.qbc` next to a newer `.js` is refused with an exception and |
| 113 | the glue falls back to evaluating the source (diag `bytecode`). Every port |
| 114 | (`SandboxEngine.swift` / `.kt` / `.cpp`, the three `TrustedValidator`s) tries |
| 115 | the blob first and reports `(bytecode)` or `(source)` in the `boot` and |
| 116 | `library` diags; the renderer bundle runs in a web view and has no bytecode. |
| 117 | Only the host's own bundles ever go through `JS_ReadObject` (it has no |
| 118 | verifier); widget code is always parsed from source. Debug info is kept (shim |
| 119 | stack traces keep line numbers), source text is not, so the blobs are 1.2–1.5× |
| 120 | the minified source. Measured on the desktop core (release quickjs-ng, macOS |
| 121 | arm64): sandbox bundle boot 38–74 ms → 20–22 ms, Chart.js 18 ms → 4 ms; the |
| 122 | remainder is the bundle's own top-level execution, which bytecode cannot remove |
| 123 | (QuickJS has no heap snapshots). |
| 124 |
| 125 | ### Version stamp (v0.6.0) |
| 126 |
| 127 | `build-native-bundles.ts` writes `VERSION.json` on the first line of each of |
| 128 | the three bundles (`/* widget-sandbox version=0.6.0 protocol=1 profile=1 sdk=1 */`) |
| 129 | and into the glue as constants (`WidgetSandboxVersion.swift` / `.kt`, |
| 130 | `twidget/version.h`). Before it evaluates a bundle (the `.qbc` or the source) |
| 131 | the engine checks the stamps of the whole set (`BundleStamp.swift` / `.kt`, |
| 132 | `bundle_stamp.cpp`, one parser in three copies with the format's tests in |
| 133 | `version.test.ts`): no stamp, or another protocol, profile or sdk, and it dies |
| 134 | at boot with `bundle-mismatch`; the validator loads nothing. A port reads the |
| 135 | stamp from the source it already has for the `.qbc` check, so the check costs |
| 136 | one line's parse. |
| 137 |
| 138 | ### Lifecycle |
| 139 |
| 140 | One QuickJS runtime per visible widget; when a message scrolls out of view, |
| 141 | stop timers, drop the runtime and keep the WebView (or a bitmap snapshot) as a |
| 142 | static view; recreate on return. Memory: a QuickJS runtime with linkedom and a |
| 143 | chart library costs ~5–15 MB; the WebView dominates. |
| 144 |
| 145 | ## Purely web-specific parts (can be dropped) |
| 146 |
| 147 | - `COOP/COEP` headers and `crossOriginIsolated` (only needed for SAB). |
| 148 | - `Worker` + `postMessage` glue in `packages/core/src/host/worker.ts` (becomes the thread + |
| 149 | C bindings). |
| 150 | - `<iframe sandbox>` / `srcdoc` / `MessageChannel` / `window.parent` handshake. |
| 151 | - Synchronous `XMLHttpRequest` to fetch bundled libraries (becomes a file read). |
| 152 | - Vite dev server, `/reference/` mode, Playwright harness. |
| 153 |
| 154 | ## Open questions for native |
| 155 |
| 156 | - **App Store review**: executing downloaded JavaScript in a bundled |
| 157 | interpreter (not JavaScriptCore) — Figma plugins do it; check guideline 2.5.2 |
| 158 | wording for the chosen framing ("the code cannot change app features"). |
| 159 | - **`WKContentRuleList` and WebSocket**: rule lists cover `ws(s)` schemes in |
| 160 | recent iOS versions; keep `connect-src 'none'` as the second barrier. |
| 161 | - **Android WebView versions** vary in CSP support; the renderer should also |
| 162 | install a document-start script that deletes `fetch`, `XMLHttpRequest`, |
| 163 | `WebSocket`, `RTCPeerConnection` from the renderer window (defense in depth; |
| 164 | only our code runs there anyway). |
| 165 | - **IME and caret**: native WebViews behave like Chrome for the "assign |
| 166 | `value` only if different" rule used by the renderer; verify on Android |
| 167 | Gboard composition. |
| 168 |
| 169 | ## Android port: start here (lessons from the iOS port, Oct 2026) |
| 170 |
| 171 | Everything below was learned while shipping `ios/` and was the plan for |
| 172 | `android/`. The port followed it; what actually differed is in the "Android |
| 173 | implementation" section of `docs/decisions.md` and in `packages/android/README.md`. |
| 174 |
| 175 | ### Reuse, do not re-implement |
| 176 |
| 177 | - **Three JS bundles are the product**: `sandbox-bundle.js` (shim + linkedom, |
| 178 | untrusted once loaded), `validator-bundle.js` (trusted, runs in its *own* |
| 179 | QuickJS runtime, one per app or per widget), `renderer-bundle.js` (trusted, |
| 180 | runs in the WebView). `packages/core/scripts/build-native-bundles.ts` emits them |
| 181 | with their bytecode (no libraries are bundled since profile 1). Add an output |
| 182 | directory parameter or an `android/` target to that script instead of a new |
| 183 | one; keep `pnpm build:ios` working. |
| 184 | - **Renderer transport** is a build-time define `__TW_TRANSPORT__` in |
| 185 | `packages/core/scripts/sandbox-build.ts` (`'port'` for the web, `'webkit'` for iOS). The |
| 186 | `webkit` branch at the end of `packages/core/src/renderer/renderer.ts` is ~20 lines: |
| 187 | host → renderer by `window.__twReceive(json)` (`evaluateJavaScript`), renderer |
| 188 | → host by `webkit.messageHandlers.tw.postMessage(json)`, binary query results |
| 189 | as `binaryBase64`. Android needs a third value (`'android'`): renderer → host via |
| 190 | an `@JavascriptInterface` object (`window.tw.postMessage(json)`), host → |
| 191 | renderer via `WebView.evaluateJavascript("__twReceive(...)")`. The rest of the |
| 192 | renderer is unchanged. |
| 193 | - **Protocol** (`docs/protocol.md`, `packages/core/src/shared/protocol.ts`) and the `__host` |
| 194 | string API are identical on every platform. Host kinds the engine must answer: |
| 195 | `ops`, `query` (sync), `now`, `timer`, `clearTimer`, `raf`, `log`, `diag`, |
| 196 | `listen`, `pd`, `bridge`, `intl`, `random`, `stat`. Inputs to the sandbox: |
| 197 | `event`, `frame`, `viewport`, `resize`, `theme`, `bridge`. Copy the Swift |
| 198 | `SandboxEngine.swift` structure 1:1; it is the shortest correct reference. |
| 199 | - **Intl** lives in the host: kinds `number`, `numberParts`, `numberOptions`, |
| 200 | `date`, `dateMethod`, `dateParts`, `dateOptions`, `plural`, `relative`, `list`, |
| 201 | `compare`, `upper`, `lower`. iOS maps them to Foundation and returns `[]` for |
| 202 | the `*Parts` kinds; `java.text` / `android.icu.text` can do better. |
| 203 | - **Tests to port** (`packages/ios/Tests/WidgetSandboxTests/`): engine boot, network |
| 204 | stubs throw `NetworkDisabledError`, CPU limit kills, memory limit kills, |
| 205 | layout query round trip, pre-boot buffering, bridge + timers, validator |
| 206 | diagnostics reach the host, CSSOM attacks (`api-css-adopted`, |
| 207 | `api-css-insertrule`) reported as `url-blocked`/`css-dropped`, create/teardown |
| 208 | churn (25 runtimes). Demo app features worth copying: corpus browser |
| 209 | (compat/attacks/generated), attack runner against `pnpm canary` (0 hits is the |
| 210 | bar), generated runner writing a JSON report to app storage. |
| 211 |
| 212 | ### QuickJS on a JVM process |
| 213 |
| 214 | - quickjs-ng v0.17.0 is vendored under `packages/ios/Sources/CQuickJS/` with a 40-line |
| 215 | `qjs_shim.c` that hides `JSValue` macros; reuse both via the NDK (CMake) and |
| 216 | write the JNI layer against the shim, not against `quickjs.h` directly. |
| 217 | - **One dedicated thread per runtime with a big stack.** On iOS a GCD queue |
| 218 | produced bogus `RangeError: Maximum call stack size exceeded` because QuickJS |
| 219 | records the stack top at `JS_NewRuntime` and pool threads hop. On Android use |
| 220 | `Thread(null, runnable, "widget.sandbox", 8L shl 20)` + `Looper.prepare()` / |
| 221 | `Handler` (a `HandlerThread` has no stack-size constructor), never a shared |
| 222 | executor. Set `JS_SetMaxStackSize` to ~6 MB and call `JS_UpdateStackTop` |
| 223 | on every entry (eval, call, pending jobs). Debug builds of quickjs-ng use |
| 224 | ~10 KB of C stack per JS call; css-tree inside the validator needs > 40 |
| 225 | levels. |
| 226 | - CPU limit: `JS_SetInterruptHandler` with a deadline from |
| 227 | `SystemClock.elapsedRealtime()`; 500 ms per continuous run, 5 s for boot. |
| 228 | Memory: `JS_SetMemoryLimit`, 8 MB (64 MB until the strict limits). Both are `SandboxConfig` fields, keep them |
| 229 | configurable from the public host API (the iOS `WidgetHost.init` does not yet |
| 230 | expose them, only `SandboxEngine` does). |
| 231 | - Buffer inputs that arrive before the runtime has booted (the renderer sends |
| 232 | `size` before `ready`). |
| 233 |
| 234 | ### WebView renderer on Android |
| 235 |
| 236 | - Serve the renderer document from a custom path with `shouldInterceptRequest` |
| 237 | (per-widget origin, e.g. `https://w-<uuid>.tgwidget.invalid/`); refuse every |
| 238 | other request there with an empty response, so no subresource ever leaves. |
| 239 | `WebViewAssetLoader` is a convenience, not a security boundary. |
| 240 | - Belt and braces, like iOS: CSP as both response header and `<meta>` with |
| 241 | `connect-src 'none'`, nonce `script-src`; `WebSettings.setBlockNetworkLoads(true)` |
| 242 | (requires the `INTERNET` permission to be *present* when toggled); |
| 243 | `shouldOverrideUrlLoading` returns `true` for every navigation; |
| 244 | `setJavaScriptCanOpenWindowsAutomatically(false)`, `setSupportMultipleWindows(false)`; |
| 245 | a document-start script (`WebViewCompat.addDocumentStartJavaScript`) deleting |
| 246 | `fetch`/`XMLHttpRequest`/`WebSocket`/`RTCPeerConnection`/`EventSource`/ |
| 247 | `navigator.sendBeacon`; disable geolocation, file access, content access, |
| 248 | DOM storage; `CookieManager.setAcceptThirdPartyCookies(false)`. |
| 249 | - Register the `@JavascriptInterface` object and the client callbacks *before* |
| 250 | `loadUrl` (iOS lesson: handlers added after view creation were ignored). |
| 251 | - Sync layout queries: the engine thread blocks on a `Semaphore` (3 s timeout) |
| 252 | while the main thread runs `evaluateJavascript` and the callback signals. |
| 253 | Never run QuickJS on the main thread. |
| 254 | - Attack suite on a device needs the canary at the Mac's LAN address (the iOS |
| 255 | demo hardcodes `127.0.0.1`, which only works on the simulator). |
| 256 |