| 6 | for glue; the JS bundles are byte-for-byte what `packages/core/scripts/build-native-bundles.ts` |
| 7 | emits for iOS except for the renderer transport define. |
| 8 |
| 9 | ``` |
| 10 | android/ |
| 11 | settings.gradle.kts, build.gradle.kts, gradle/libs.versions.toml Gradle 8.14 · AGP 8.13 · Kotlin 2.2 · compileSdk 35 · minSdk 26 |
| 12 | widget-sandbox/ library module (Kotlin + NDK) |
| 13 | src/main/cpp/CMakeLists.txt builds packages/ios/Sources/CQuickJS (quickjs-ng v0.17.0 + qjs_shim.c) unmodified, -O2, no STL |
| 14 | src/main/cpp/quickjs_jni.c JNI layer written against qjs_shim.h: strings cross as UTF-8 byte[] |
| 15 | src/main/java/…/sandbox/ |
| 16 | QuickJSContext.kt runtime/context wrapper, string host functions, interrupt deadline (CLOCK_BOOTTIME) |
| 17 | JSThread.kt the thread a runtime is pinned to (8 MB stack, Looper/Handler, timers) |
| 18 | SandboxEngine.kt = SandboxEngine.swift: one runtime per widget on its own JSThread, |
| 19 | `__host`/`__hostBinary`, timers, scripts, CPU/memory limits, Intl bridge |
| 20 | TrustedValidator.kt = validator.ts run in a separate TRUSTED QuickJS context |
| 21 | RendererWebView.kt = srcdoc iframe: WebView + shouldInterceptRequest origin + nonce CSP + hardening |
| 22 | WidgetHost.kt = widget-host.ts: engine ↔ validator ↔ renderer, sync queries, public limits |
| 23 | IntlBridge.kt, SandboxResources.kt |
| 24 | src/main/assets/WidgetJS/ built by `pnpm build:android` (the three bundles and their bytecode) |
| 25 | src/androidTest/ instrumented tests (JUnit4 on the emulator) |
| 26 | demo/ Compose demo: corpus browser (compat, attacks, generated), Dark toggle, |
| 27 | diagnostics panel, attack runner against the canary (address editable), |
| 28 | generated / compat runners writing JSON reports into app storage, |
| 29 | Ref toggle (ReferenceWebView.kt: the same file in a plain WebView without |
| 30 | the sandbox — dev tooling, like `?reference=1` on the web; hidden for attacks/) |
| 31 | src/main/assets/Corpus/ copied by `pnpm build:android` (gitignored) |
| 32 | apps/renderer-blitz/ Blitz renderer prototype (dev tooling, frozen since 2026-10-30: in the demo only with |
| 33 | -Ptw.nativeRenderers=true; the same for renderer-litehtml): JNI glue + Kotlin Renderer for the |
| 34 | Rust crate in ../renderer-blitz (repo root, shared with the iOS/macOS demo), |
| 35 | built by cargo-ndk from build.gradle.kts |
| 36 | apps/renderer-litehtml/ litehtml renderer prototype (dev tooling): the C++ core in ../renderer-litehtml built by |
| 37 | the NDK's CMake (externalNativeBuild), LitehtmlBackend.kt (fonts, text widths, images, |
| 38 | display-list painter on Canvas) + LitehtmlRenderer.kt; docs/litehtml-renderer.md |
| 39 | The demo's Renderer picker (WebView | Blitz | litehtml) / `--es renderer litehtml` |
| 40 | (`--ez blitz true` still means `--es renderer blitz`) |
| 41 | ``` |
| 42 |
| 43 | ## Build |
| 44 |
| 45 | Toolchain (no Android Studio needed): JDK 17+, Android SDK with |
| 46 | `platforms;android-35`, `build-tools;35.0.0`, `ndk;28.2.13676358`, |
| 47 | `cmake;3.31.6`, and for the runs an arm64 API 35 emulator image. Put |
| 48 | `sdk.dir=…` into `android/local.properties` (gitignored) and export |
| 49 | `JAVA_HOME`; with Homebrew on a Mac: |
| 50 |
| 51 | ```bash |
| 52 | export JAVA_HOME=/opt/homebrew/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home |
| 53 | export ANDROID_HOME=$HOME/Library/Android/sdk |
| 54 | corepack pnpm build:android # bundles → widget-sandbox/src/main/assets/WidgetJS, corpus → demo/src/main/assets/Corpus |
| 55 | cd packages/android && ./gradlew :widget-sandbox:assembleDebug :demo:assembleDebug |
| 56 | ``` |
| 57 |
| 58 | Tests need a booted emulator (or a device over USB): |
| 59 |
| 60 | ```bash |
| 61 | $ANDROID_HOME/emulator/emulator -avd twidget-35 -no-window -no-audio -no-boot-anim -gpu swiftshader_indirect & |
| 62 | cd packages/android && ./gradlew :widget-sandbox:connectedDebugAndroidTest # results: widget-sandbox/build/reports/androidTests/connected/ |
| 63 | ``` |
| 64 |
| 65 | To look at the demo by eye start the emulator with a window and the host |
| 66 | GPU: `emulator -avd twidget-35 -gpu host`. With `-gpu auto` an API 35 image |
| 67 | falls back to software rendering (swangle + lavapipe) where a frame takes |
| 68 | seconds, so taps land late and Back looks broken; switching the renderer cold |
| 69 | boots the AVD (reinstall the APK). |
| 70 |
| 71 | Demo on the emulator, driven from the command line: |
| 72 |
| 73 | ```bash |
| 74 | adb install -r -t apps/android/demo/build/outputs/apk/debug/demo-debug.apk |
| 75 | corepack pnpm canary # on the Mac; 10.0.2.2 is the Mac from the emulator |
| 76 | adb shell am start -n org.telegram.widgetsandbox.demo/.MainActivity --es autorun attacks --es canary 10.0.2.2:9999 |
| 77 | adb shell am start -n org.telegram.widgetsandbox.demo/.MainActivity --es autorun generated |
| 78 | adb shell am start -n org.telegram.widgetsandbox.demo/.MainActivity --es autorun compat |
| 79 | adb shell am start -n org.telegram.widgetsandbox.demo/.MainActivity --es autorun htmlbubbles # Telegram's demos as classic widgets (corpus/htmlbubbles-ported) |
| 80 | adb shell run-as org.telegram.widgetsandbox.demo cat files/attack-report.json # also generated-report.json, compat-report.json, htmlbubbles-report.json |
| 81 | ``` |
| 82 |
| 83 | On a real phone replace `10.0.2.2:9999` with the Mac's LAN address (the field |
| 84 | on the attack screen is editable and remembered) and start the canary bound |
| 85 | to all interfaces: `CANARY_HOST=0.0.0.0 corepack pnpm canary`. |
| 86 |
| 87 | ## Verified on the Android 15 emulator (Pixel 7 AVD, arm64) |
| 88 |
| 89 | - Instrumented tests, 27 green: QuickJS/JNI (UTF-8 round trips, host |
| 90 | functions, exceptions, interrupt deadline, memory limit, promise jobs, stack |
| 91 | check follows the calling thread, pinned thread recursion depth), engine |
| 92 | (boot, network stubs throw `NetworkDisabledError`, CPU limit kills, memory |
| 93 | limit kills, layout query round trip, pre-boot buffering, bridge + timers, |
| 94 | Intl), trusted validator (diag bridge, URL/handler stripping, stylesheet |
| 95 | text only shipped sanitized, 25× create/teardown), renderer in a real |
| 96 | WebView (ready, query answered, network APIs removed, external image refused |
| 97 | and reported, navigation blocked), WidgetHost end-to-end (validator |
| 98 | diagnostics reach the host, CSSOM attacks reported as blocked, limits from |
| 99 | the public API, theme toggle reaches computed styles and form controls, |
| 100 | 25 full widgets created and torn down). |
| 101 | - Attack runner: all 82 `corpus/attacks` files, canary hits **0**, no widget terminated (`attack-report.json`). |
| 102 | - Generated corpus runner: 40/40 (`corpus/generated/{with,without}-profile`) |
| 103 | load without JS errors or termination; median JS time 64 ms per widget |
| 104 | including the sandbox-bundle boot (debug build, no bytecode cache); the |
| 105 | "without" widgets show the same `tag-dropped` / `url-blocked` / |
| 106 | `network-blocked` diagnostics as on the web and iOS. |
| 107 | - Compat corpus runner: 21/21 load without JS errors or termination, median |
| 108 | JS time 67 ms (chartjs-line 198 ms, d3-bar 112 ms); no pixel comparison on |
| 109 | Android (the Ref toggle shows the native render under the sandbox one for a |
| 110 | comparison by eye, it is not scripted). Checked by eye on the emulator: |
| 111 | chartjs-line, d3-bar, dark-mode, dark toggle, sandbox vs reference. |
| 112 | - On a real phone (Nothing A142, Android 16, WebView 154, same debug APK over |
| 113 | USB): the demo renders the compat corpus (chartjs-line 203 ms JS, d3-bar |
| 114 | 137 ms) and the attack runner against the canary on the Mac's LAN address |
| 115 | (`CANARY_HOST=0.0.0.0 pnpm canary`) reports **0** hits over all |
| 116 | `corpus/attacks` files; the canary's own log, which also records bare TCP |
| 117 | connections and UDP datagrams, stayed empty. |
| 118 | Both corpus runners (`--es autorun generated|compat`) pass on the phone |
| 119 | as well: generated 40/40 (median JS time 14 ms, max 331 ms), compat 21/21 |
| 120 | (median 9 ms, max 195 ms), no JS errors, no widget terminated, the same |
| 121 | diagnostics as on the emulator. |
| 122 | - Widget boot (sandbox bundle eval + initial tree) is ~60–90 ms in a debug |
| 123 | build: quickjs-ng is compiled with `-O2` even in debug, see below. |
| 124 |
| 125 | ## Security mapping (invariants → Android) |
| 126 |
| 127 | | Invariant | Mechanism | |
| 128 | |---|---| |
| 129 | | 1 Widget JS only in QuickJS | `SandboxEngine`: one `JSRuntime` per widget on its own `JSThread`; no module loader; only `__host`/`__hostBinary` exist | |
| 130 | | 2 Everything from the context is hostile | engine output goes through `TrustedValidator` (same TS validator, separate runtime) before the renderer | |
| 131 | | 3 Renderer runs only trusted code | `RendererWebView`: document served by our `shouldInterceptRequest` with `script-src 'nonce-…'` (header and `<meta>`); `__twReceive` is the only entry point | |
| 132 | | 4 No external URLs in renderer DOM/CSS | validator URL policy (`data:` / `#fragment` only); every non-document request is answered with an empty 403 and reported as `url-blocked` | |
| 133 | | 5 QuickJS has no network | nothing but `__host` is bound; `fetch`/`XMLHttpRequest`/… are the shim's `NetworkDisabledError` stubs | |
| 134 | | 6 Defense in depth | `setBlockNetworkLoads(true)`, `connect-src 'none'`, every navigation cancelled in `shouldOverrideUrlLoading`, `onCreateWindow` → false, dialogs cancelled, geolocation / permissions / file chooser denied, file/content/DOM-storage/database access off, cookies off, Safe Browsing off, mixed content never, document-start script deleting `fetch`/XHR/WebSocket/EventSource/RTCPeerConnection/WebTransport/workers/`sendBeacon`/`window.open`, opaque per-widget origin `https://w-<uuid>.tgwidget.invalid/` | |
| 135 |
| 136 | Sync layout queries: the engine thread blocks on a `Semaphore` (3 s timeout) |
| 137 | while the main thread validates the query and asks the WebView through |
| 138 | `evaluateJavascript`; the renderer answers through the `tw` |
| 139 | `@JavascriptInterface` object (JavaBridge thread → main). The main thread |
| 140 | never waits for the engine. QuickJS never runs on the main thread. |
| 141 |
| 142 | Memory and CPU limits are part of the public API: `WidgetHost.Options(memoryLimitBytes, cpuLimitMs)`. |
| 143 |
| 144 | SDK v1 (`docs/sdk-v1.md` §4.2): `WidgetHost(context, html, WidgetTheme(colorScheme, params, |
| 145 | button), widthDp, Options(locale, storage = WidgetStorage(local, session), …))`, `setTheme(WidgetTheme)`, |
| 146 | `onAction` (`WidgetAction.Ready` / `OpenLink` / `OpenTelegramLink` / `Haptic`), `onStorageCommit(area, |
| 147 | values)`, `onGesture(WidgetGestureClaim)`; all callbacks on the main thread. `SandboxEngine` checks every bridge |
| 148 | call with `SdkPolicy.kt` (the twin of `sdk-policy.ts`, `SdkPolicyTest` against the shared fixture): |
| 149 | the call itself (`bridge-rejected`), one link per tap under `strict` (`activation-blocked`), the haptic |
| 150 | limit (`haptic-limit`); storage commits and the preload against the 16 KB quota (`storage-rejected`). |
| 151 | `TelegramWidget.setResizeAnchor('top' | 'bottom')` (v0.1.3) is no action: `SdkPolicy.checkBridgeCall` |
| 152 | returns a `BridgeCall` (a `WidgetAction`, or `BridgeCall.SetResizeAnchor(edge)`), the engine hands the |
| 153 | anchor to `SandboxEngine.Delegate.onResizeAnchor`, and `WidgetHost` keeps the latest one in |
| 154 | `WidgetDiagnostics.resizeAnchor` ("top" until the widget calls it) next to `height`, set before the size |
| 155 | report of the content its task changed; the client keeps that edge of the bubble in place when the height |
| 156 | changes (the demo's lists: `WidgetView(scroll = …)`). |
| 157 | The client's time over a widget with no caption below it (`docs/sdk-v1.md` §2.17, §5.12): `Options(contentSafeArea = |
| 158 | WidgetContentSafeArea(bottom, cornerRight, cornerLeft))` at creation and `setContentSafeArea` with the bubble's layout |
| 159 | (dp = CSS px, 0 by default); the renderer core sets the `--tg-content-safe-area-*` variables, the engine passes |
| 160 | `contentSafeArea` at boot and the `safeArea` dispatch (`SandboxEngine.contentSafeArea`). |
| 161 | The widget's state and requests (`docs/sdk-v1.md` §2.13–§2.15, §4.2): `Options(data = WidgetData(chatData, publicData), |
| 162 | context = WidgetContext(isCopy, canQuery, backgroundQuery, chatType, viewer))` (the chat state and the shared state, |
| 163 | which only the bot writes; the server's flags), `setData(WidgetData)` (the full state on every change), |
| 164 | `onRequest(WidgetRequest(data), complete)` (complete once, from any thread, with `Result.success(WidgetRequestAnswer(result))`, |
| 165 | the server's answer, or `Result.failure(WidgetRequestException(WidgetRequestFailure.…))`), |
| 166 | `onCopyText(text)`. `SandboxEngine` runs |
| 167 | the request gate of `SdkPolicy.kt` (`RequestGate`: from the server's flags, one press per request, background only with `backgroundQuery`, |
| 168 | one when the widget appears on screen, then one per 5 s; one in flight; `request-blocked`) and checks the answers |
| 169 | (`answer-rejected`, `data-rejected`). |
| 170 | The string-theme constructor, `setTheme(String)`, `onBridge` and `onGestureClaim(x, y)` remain as deprecated conveniences; |
| 171 | `bridgeEvent` is gone. |
| 172 |
| 173 | Touch gestures: a `WebView` inside a scrolling container loses the touch to |
| 174 | the container as soon as the finger moves past the slop — Android cannot see |
| 175 | `touch-action` inside the page. Since v0.1.3 a vertical drag is always the |
| 176 | chat's: the list scrolls over every widget, `touch-action: none` included, and |
| 177 | the widget gets `pointercancel`. `RendererWebView` denies the parent's |
| 178 | interception from `ACTION_DOWN` until the renderer's `gesture` message (sent |
| 179 | on every primary `pointerdown`, see `docs/protocol.md`) arrives, or for 150 ms; |
| 180 | then only a `hold` claim (`touch-action: none`) keeps the parent out, and only |
| 181 | until the press first leaves the slop: vertically (a tie is vertical) the list |
| 182 | may intercept, horizontally the press stays the widget's to its end. Without a |
| 183 | hold claim, or in the leading 20 px edge strip, the list may intercept at once |
| 184 | (`GestureTest`). The same message carries the whole claim |
| 185 | (`WidgetHost.onGesture`): horizontal drags (`pan-y`, `none`) and holds |
| 186 | (`none`); `y` is always false; taps and double taps over the widget are always |
| 187 | the widget's. The bubble's own recognizers (the message menu on a hold, swipe-to-reply) are the |
| 188 | client's: `GesturePolicy.kt` (the twin of `gesture-policy.ts`, |
| 189 | `GesturePolicyTest` against the shared fixture) gives them a `GestureArbiter` |
| 190 | to feed the press and the claim, and a verdict with `cancel` is the moment to |
| 191 | take the touch from the renderer's view (`ACTION_CANCEL`: the widget gets |
| 192 | `pointercancel`); the demo's `BubbleGestureLayout` does exactly that. |
| 193 |
| 194 | Native pickers: Chromium's colour / date dialogs and `<select>` popups need |
| 195 | an Activity reachable behind the WebView's context — pass an Activity (or a |
| 196 | wrapper over one) to `WidgetHost`, not an application context, or they |
| 197 | silently do nothing. |
| 198 |
| 199 | Theme: the WebView's own `prefers-color-scheme` is whatever the configuration |
| 200 | context said at creation and cannot be flipped later (`WKWebView` has |
| 201 | `overrideUserInterfaceStyle`, `WebView` has nothing). It does not matter: the |
| 202 | validator resolves `prefers-color-scheme` media queries, `color-scheme: light |
| 203 | dark` and `light-dark()` against the host theme and re-emits the stylesheets |
| 204 | on `setTheme`, and `matchMedia` is answered by the host. Verified by |
| 205 | `themeToggleReachesComputedStylesAndFormControls`: after a toggle the root |
| 206 | `color-scheme`, `light-dark()` colours and the UA's own form-control colours |
| 207 | all switch. |
| 208 |
| 209 | ## Not done / next |
| 210 |
| 211 | - `Intl` bridge covers number/date/plural/relative/list/compare through |
| 212 | `android.icu`; `formatToParts` returns empty arrays. |
| 213 | - Snapshot-and-drop of a runtime hidden for minutes (`WidgetHost.setVisible` |
| 214 | already pauses frames and slows timers to 1 Hz; see `docs/decisions.md`, |
| 215 | "Runtime limits"). |
| 216 | - Device pentest of the WebView blockers beyond the attack corpus (the corpus |
| 217 | itself and both widget corpora have run on one real phone, see above). |
| 218 |