| 6 |
| differences are described in [`apps/macos/README.md`](../../apps/macos/README.md). |
| 7 |
| 8 | ``` |
| 9 | ios/ |
| 10 | Package.swift Swift package `WidgetSandbox` |
| 11 | Sources/CQuickJS/ quickjs-ng v0.17.0 (vendored, MIT) + qjs_shim.c for Swift |
| 12 | Sources/WidgetSandbox/ |
| 13 | QuickJS.swift runtime/context wrapper, string host functions, interrupt deadline |
| 14 | JSThread.swift the thread a runtime is pinned to (8 MB stack, run loop, timers) |
| 15 | SandboxEngine.swift = packages/core/src/host/worker.ts: one runtime per widget on its own JSThread, |
| 16 | `__host`/`__hostBinary`, timers, scripts, CPU/memory limits, Intl bridge |
| 17 | TrustedValidator.swift = packages/core/src/host/validator.ts, run in a separate TRUSTED QuickJS context |
| 18 | Renderer.swift the renderer as WidgetHost sees it (view + JSON contract); RendererFactory |
| 19 | RendererWebView.swift = srcdoc iframe: WKWebView + custom scheme + nonce CSP + rule list |
| 20 | WidgetHost.swift = packages/core/src/host/widget-host.ts: engine ↔ validator ↔ renderer, sync queries |
| 21 | WidgetView.swift SwiftUI wrapper + observable model |
| 22 | Platform.swift PlatformView = UIView | NSView; the UIKit / AppKit seam |
| 23 | RendererEnvironment.swift one WebKit environment for many renderers (process pool, data store, content |
| 24 | controller, rule list, scheme handler) + RendererPool (documents loaded ahead) |
| 25 | Pools.swift EnginePool (runtime + sandbox bundle evaluated ahead), ValidatorPool (contexts on the |
| 26 | shared validator thread, recycled), WidgetWarmup — see docs/chat-feed-ios.md |
| 27 | WidgetJS/ built by `pnpm build:ios` (bundles, libs, libraries.json, and |
| 28 | .qbc bytecode next to each file QuickJS evaluates — see |
| 29 | docs/native-port-notes.md "Bytecode") |
| 30 | Tests/WidgetSandboxTests/ XCTest: engine boot, network stubs, CPU limit, layout query, bridge, validator |
| 31 | DemoApp/ SwiftUI demo (xcodegen project, sources shared with apps/macos/DemoApp): corpus |
| 32 | browser (compat, attacks, generated), dark toggle, diagnostics, Reference |
| 33 | toggle (native WebKit twin, dev tooling), Renderer picker WebView | Blitz | litehtml (see below), runners for attacks / generated / |
| 34 | compat / Telegram demos (htmlbubbles-ported) / sandbox-vs-reference timing (JSON reports, `--autorun` launch argument) |
| 35 | Sources/NativeRenderer.swift the Renderer contract on a native engine's C ABI: raster view, touches, frames, diagnostics (dev tooling) |
| 36 | Sources/BlitzRenderer.swift the Blitz engine's function table (apps/renderer-blitz/, Rust) |
| 37 | Sources/LitehtmlRenderer.swift the litehtml engine's function table (apps/renderer-litehtml/, C++; docs/litehtml-renderer.md) |
| 38 | Sources/ChatFeed/ the chat feed (iOS only): UICollectionView of bubbles with a widget in each, every |
| 39 | optimisation behind a FeedConfig switch, autorun with hitch / timing report |
| 40 | (`--autorun feed`, docs/chat-feed-ios.md) |
| 41 | BridgingHeader.h their C headers (apps/renderer-blitz/include/twidget_blitz.h, apps/renderer-litehtml/include/twidget_litehtml.h) |
| 42 | ``` |
| 43 |
| 44 | ## Build |
| 45 |
| 46 | ```bash |
| 47 | pnpm build:ios # bundles → packages/ios/Sources/WidgetSandbox/WidgetJS, corpus → apps/ios/DemoApp/Corpus |
| 48 | cd apps/ios/DemoApp && xcodegen generate # regenerates TwidgetDemo.xcodeproj (brew install xcodegen) |
| 49 | open apps/ios/DemoApp/TwidgetDemo.xcodeproj |
| 50 | ``` |
| 51 |
| 52 | Package only (no simulator runtime needed; the WKWebView tests run natively on macOS too): |
| 53 |
| 54 | ```bash |
| 55 | xcodebuild test -scheme WidgetSandbox -destination 'platform=macOS' |
| 56 | ``` |
| 57 |
| 58 | The Blitz and litehtml renderer prototypes (next section) are frozen since 2026-10-30 (`docs/decisions.md`, "The renderer prototypes are frozen"): |
| 59 | the demo builds and links them only with `TW_NATIVE_RENDERERS=YES` on the `xcodebuild` command line. Such a build |
| 60 | compiles the Rust crate, which needs rustup's `cargo` (`brew install rustup`, then `rustup default stable`; the iOS |
| 61 | targets are added on first use), and the C++ core, which needs `cmake` and `ninja` from Homebrew. |
| 62 |
| 63 | Cross-compile check for the simulator: |
| 64 |
| 65 | ```bash |
| 66 | cd packages/ios && swift build --build-tests --triple arm64-apple-ios16.0-simulator --sdk "$(xcrun --sdk iphonesimulator --show-sdk-path)" |
| 67 | ``` |
| 68 |
| 69 | On a real iPhone (free Apple ID is enough; the app is only installed, not |
| 70 | distributed): |
| 71 |
| 72 | 1. On the phone: Settings → Privacy & Security → Developer Mode → on (reboots). |
| 73 | Connect it by cable and tap "Trust this computer". |
| 74 | 2. `open apps/ios/DemoApp/TwidgetDemo.xcodeproj`, select the TwidgetDemo target → |
| 75 | Signing & Capabilities → tick "Automatically manage signing" and pick your |
| 76 | Team (add your Apple ID under Xcode → Settings → Accounts if the list is |
| 77 | empty). If the bundle id is taken, change its last part. |
| 78 | 3. Choose your iPhone as the run destination and press Run. The first launch |
| 79 | asks you to trust the developer on the phone: Settings → General → VPN & |
| 80 | Device Management → your Apple ID → Trust. |
| 81 | 4. The attack runner expects the canary on the Mac; on a phone replace |
| 82 | `127.0.0.1` in `AttackRunnerView.swift` with the Mac's LAN address and run |
| 83 | `pnpm canary` there. Free-account builds expire after 7 days. |
| 84 |
| 85 | Verified on an iPhone 17 Pro Max (iOS 27.0.1) with Xcode 26.6: the first |
| 86 | connection extracts ~13 GB of device support files from the phone's dyld |
| 87 | shared cache into `~/Library/Developer/Xcode/iOS DeviceSupport/`; with a full |
| 88 | disk Xcode shows `dyld_shared_cache_extract_dylibs failed` next to the device |
| 89 | and cannot build for it. Free the space and reconnect. CLI install without |
| 90 | Xcode's Run button: |
| 91 |
| 92 | ```bash |
| 93 | cd apps/ios/DemoApp && xcodebuild build -project TwidgetDemo.xcodeproj -scheme TwidgetDemo -destination 'id=<device udid>' -allowProvisioningUpdates -derivedDataPath /tmp/twidget-device |
| 94 | xcrun devicectl list devices # udid column |
| 95 | xcrun devicectl device install app --device <udid> /tmp/twidget-device/Build/Products/Debug-iphoneos/TwidgetDemo.app |
| 96 | xcrun devicectl device process launch --device <udid> org.telegram.widgetsandbox.TwidgetDemo |
| 97 | ``` |
| 98 |
| 99 | Or without opening Xcode, once the team is known: |
| 100 |
| 101 | ```bash |
| 102 | cd apps/ios/DemoApp && TWIDGET_TEAM=ABCDE12345 xcodegen generate |
| 103 | xcodebuild -project TwidgetDemo.xcodeproj -scheme TwidgetDemo -destination 'generic/platform=iOS' -allowProvisioningUpdates build |
| 104 | ``` |
| 105 |
| 106 | Tests and the demo need a simulator runtime matching Xcode (`xcodebuild -downloadPlatform iOS`), then: |
| 107 |
| 108 | ```bash |
| 109 | xcodebuild test -scheme WidgetSandbox -destination 'platform=iOS Simulator,name=iPhone 17,OS=26.5' |
| 110 | ``` |
| 111 |
| 112 | Note for the host-side code: register the `tgwidget://` scheme handler and the |
| 113 | `tw` script message handler on the `WKWebViewConfiguration` *before* creating |
| 114 | the `WKWebView` (it copies the configuration); and expect renderer messages |
| 115 | (`size`) before `ready` — `SandboxEngine` buffers anything that arrives before |
| 116 | its runtime has booted. Both QuickJS runtimes are pinned to a `JSThread` |
| 117 | (8 MB stack, run loop) — never run a context on a GCD queue: pool threads have |
| 118 | 512 KB stacks and a debug build of quickjs-ng needs ~10 KB per JS call. |
| 119 |
| 120 | ## Verified on the iPhone 17 simulator (iOS 26.5) and on a real iPhone |
| 121 |
| 122 | - Device: the demo installs, launches and renders the compat and generated |
| 123 | corpora on an iPhone 17 Pro Max running iOS 27.0.1 (attack runner not run |
| 124 | there yet: it needs the canary's LAN address). |
| 125 |
| 126 | - XCTest: engine (boot, network stubs, CPU limit, layout query, pre-boot |
| 127 | buffering, bridge/timers), QuickJS thread-hopping stack check, trusted |
| 128 | validator (incl. create/teardown churn), renderer in a real WKWebView, and |
| 129 | WidgetHost end-to-end (validator diagnostics reach the host; CSSOM attacks |
| 130 | reported as blocked) — all green. |
| 131 | - Demo: chartjs-line, d3-bar (click → highlight), drag, forms, Dark toggle. |
| 132 | - Attack runner: all 82 `corpus/attacks` files, canary hits **0**. |
| 133 | - Generated corpus runner: 40/40 (`corpus/generated/{with,without}-profile`) |
| 134 | load without errors; median JS time 171 ms per widget in a debug build. |
| 135 |
| 136 | ## Chat feed (iOS): a widget in every bubble |
| 137 |
| 138 | `Chat feed` in the corpus list opens a UIKit list of bubbles (text + widget, |
| 139 | cycling through compat, generated and the Telegram demos) with every |
| 140 | optimisation of `docs/chat-feed-ios.md` behind a switch: shared WebKit |
| 141 | environment, renderer/engine/validator pools, parallel boot, validation off |
| 142 | the main thread, `callAsyncJavaScript` transport, remembered heights, |
| 143 | prefetch, parked prefetched views, snapshot-and-drop of far-away runtimes, |
| 144 | prewarm at launch. `baseline` is the host as the single-widget screens use |
| 145 | it; `max` is everything on. The autorun scrolls like a reader (`step`) or a |
| 146 | flick, then writes `feed-report.json` (per-widget clocks, hitch rate per |
| 147 | phase, memory, pool hits, main-thread work) to the app's Documents: |
| 148 |
| 149 | ```bash |
| 150 | xcrun simctl launch booted org.telegram.widgetsandbox.TwidgetDemo --autorun feed --feed max --feed-count 40 --feed-scroll step |
| 151 | xcrun simctl launch booted org.telegram.widgetsandbox.TwidgetDemo --autorun feed --feed baseline --feed-count 40 --feed-set heightCache=true |
| 152 | ``` |
| 153 |
| 154 | Build with `-configuration Release` for numbers. The package side of this |
| 155 | (`RendererEnvironment`, `Pools.swift`, the new `WidgetHost.Options` flags, |
| 156 | `WidgetHost.snapshot`, `WidgetDiagnostics.rendered`) is covered by |
| 157 | `PoolsTests`; the flags default to the previous behaviour. |
| 158 |
| 159 | ## Security mapping (invariants → iOS) |
| 160 |
| 161 | | Invariant | Mechanism | |
| 162 | |---|---| |
| 163 | | 1 Widget JS only in QuickJS | `SandboxEngine`: one `JSRuntime` per widget on its own queue; no module loader; only `__host`/`__hostBinary` exist | |
| 164 | | 2 Everything from the context is hostile | engine output goes through `TrustedValidator` (same TS validator, separate runtime) before the renderer | |
| 165 | | 3 Renderer runs only trusted code | `RendererWebView`: document served by our `WKURLSchemeHandler` with `script-src 'nonce-…'`; `__twReceive` is the only entry point | |
| 166 | | 4 No external URLs in renderer DOM/CSS | validator URL policy (`data:` / `#fragment` only); scheme handler refuses every subresource | |
| 167 | | 5 QuickJS has no network | nothing but `__host` is bound; `fetch`/`XMLHttpRequest`/… are the shim's `NetworkDisabledError` stubs | |
| 168 | | 6 Defense in depth | `WKContentRuleList` blocking `http(s)://`/`ws(s)://`, `connect-src 'none'`, non-persistent data store, every navigation cancelled in `decidePolicyFor`, `window.open` → nil, document-start script deleting network APIs, `allowsInlineMediaPlayback`, no `allow-same-origin` equivalent (opaque custom-scheme origin per widget) | |
| 169 |
| 170 | Sync layout queries: the engine queue blocks on a `DispatchSemaphore` (3 s |
| 171 | timeout) while the main thread validates the query and asks the WKWebView |
| 172 | through `evaluateJavaScript`; the renderer answers via the `tw` script message |
| 173 | handler. The main thread never waits for the engine. |
| 174 |
| 175 | ## Not done / next |
| 176 |
| 177 | - `Intl` bridge covers number/date/plural/relative/list/compare; `formatToParts` |
| 178 | returns empty arrays. |
| 179 | - Snapshot-and-drop of a runtime hidden for minutes (`WidgetHost.setVisible` |
| 180 | already pauses frames and slows timers to 1 Hz; see `docs/decisions.md`, |
| 181 | "Runtime limits"). |
| 182 | - Pentest of `WKContentRuleList` + WebSocket and of the scheme handler on real devices. |
| 183 |
| 184 | ## Native renderer prototypes (dev tooling, never a product path; frozen) |
| 185 |
| 186 | Frozen since 2026-10-30: no client draws with them, so the demo has them only in a `TW_NATIVE_RENDERERS=YES` build |
| 187 | (the Swift condition of the same name; without it the picker is hidden). The **Renderer** picker on a widget screen (WebView | Blitz | litehtml) swaps |
| 188 | the renderer; the sandbox and the validator stay the same. Both native engines |
| 189 | sit behind one Swift glue, `NativeRenderer.swift` (raster view, touches, |
| 190 | coalesced paints, diagnostics), parameterised by a table of C functions: the |
| 191 | two ABIs are the same shape (`twb_*` / `twl_*`). litehtml is described in |
| 192 | `docs/litehtml-renderer.md` (C++ core in `apps/renderer-litehtml/`, built by |
| 193 | `apps/renderer-litehtml/build-apple.sh` from the pre-build phase like the Rust |
| 194 | crate; `litehtml-init` / `litehtml-build` / `litehtml-paint` / `litehtml-touch` |
| 195 | panel lines). With Blitz, instead of the |
| 196 | WKWebView running the renderer bundle, the validated DOM goes to |
| 197 | [`apps/renderer-blitz/`](../../apps/renderer-blitz) (Rust: blitz-dom + blitz-paint + |
| 198 | vello_cpu, the engine measured in `docs/blitz-experiment.md`), which lays it |
| 199 | out and paints it on the CPU into a CGImage shown by a plain view. The sandbox |
| 200 | and the validator are untouched — the Rust side only ever sees validated |
| 201 | `RenderOp`s and `data:` images, has no script and no network — so this is a |
| 202 | renderer comparison, not a second trust model. The same crate is the Android |
| 203 | demo's `renderer-blitz` module; `Renderer.swift` (= `Renderer.kt`) is the seam |
| 204 | `WidgetHost` plugs it into (`WidgetModel(…, rendererFactory: BlitzRenderer.factory)`). |
| 205 |
| 206 | - `apps/ios/DemoApp/project.yml` (and the macOS twin) run `apps/renderer-blitz/build-apple.sh` |
| 207 | as a pre-build script phase: `cargo build --release` for the platform and |
| 208 | architectures of the current build (`PLATFORM_NAME`, `ARCHS`), lipo into |
| 209 | `apps/renderer-blitz/target/apple/<platform>/libtwidget_blitz.a`, linked with |
| 210 | `-ltwidget_blitz -framework CoreText -liconv`. First build ≈ 1–2 min per |
| 211 | platform; after that cargo is incremental. The crate's `target/` is gitignored. |
| 212 | - `--renderer webview|blitz|litehtml` (shorthands `--blitz`, `--litehtml`, |
| 213 | `--webview` = `--no-blitz`) picks the renderer before anything loads (it is |
| 214 | persisted as `demo.renderer`), so the runners can be driven on any of them: |
| 215 | `--autorun generated --blitz`. |
| 216 | - What the prototype shows today (iPhone 17 Pro Max and the simulator, 3×): |
| 217 | paint 2–3 ms for a 360 × 360 pt card, touches reach the widget's handlers |
| 218 | (events go back through the same JSON contract), `size` reports drive the |
| 219 | bubble height, the Dark toggle flips `prefers-color-scheme`. Wall time to |
| 220 | `loaded` on the phone is ~20 ms better than the WebView renderer (median |
| 221 | 107 vs 128 ms over compat + generated), because `loaded` is mostly QuickJS |
| 222 | boot; the renderer only decides when `ready` arrives. |
| 223 | - Real fingers jitter: Blitz turns any move beyond 2 px into a document pan |
| 224 | and drops the click, so the Rust core keeps an 8 px tap slop before it |
| 225 | forwards moves (`TAP_SLOP` in `renderer.rs`; the Android glue gets it too). |
| 226 | - Diagnostics panel lines: `blitz-init` (creating the document; the first in |
| 227 | the process scans the system fonts, ≈ 0.4–0.5 s on a phone, once), |
| 228 | `blitz-paint` (ms and px of the last raster, reported at most once a |
| 229 | second), `blitz-touch` (per finger lift: moves, distance, and what the |
| 230 | document answered, e.g. `event:click`). The status line's `renderer ready |
| 231 | at` is the renderer's share of `loaded in`. Known gaps are Blitz's own |
| 232 | (`docs/blitz-experiment.md`): no canvas (the element stays empty), no 3D |
| 233 | transforms, CSS does not style inline SVG, form controls are partial. |
| 234 | - Emoji are blank on iOS (fine on macOS): the iOS `Apple Color Emoji` font |
| 235 | stores its `sbix` bitmaps in Apple's proprietary `emjc` format, which |
| 236 | skrifa/glifo cannot decode (macOS ships PNG). The `blitz-fonts` panel line |
| 237 | confirms the family is found; `renderer-blitz`'s ignored `font_probe` / |
| 238 | `sbix_probe` tests show the graphic type per strike. The way out is a |
| 239 | bundled open colour-emoji font (COLR, e.g. Twemoji) registered as the |
| 240 | generic `emoji` family on iOS, or an `emjc` decoder. |
| 241 |