| 1 | // Console harness for the desktop core (the C++ twin of scripts/sandbox-node.ts). |
| 2 | // |
| 3 | // twidget-run <widget.html> [--verbose] [--ops] [--events '<json>']... [--wait-ms N] [--probe EXPR]... [--theme dark] |
| 4 | // [--theme-params '{"bg_color":"#212121",…}'] [--locale ru] [--storage '{"local":{…},"session":{…}}'] |
| 5 | // SDK v1 (docs/sdk-v1.md §3.1): the client's palette, UI language and Web Storage |
| 6 | // preload; the run prints the actions (`onAction`), the storage commits and the |
| 7 | // resize anchor when the widget called `setResizeAnchor` |
| 8 | // [--message private|group|via-bot|no-queries|live-copy|copy|preview] [--copy] [--can-query] [--background-query] |
| 9 | // [--chat-type T] [--viewer ID[,FIRST,LAST,USERNAME,PREMIUM]] [--chat-data S] [--public-data S] |
| 10 | // [--answer JSON | --answer-error TIMEOUT|RATE_LIMITED|FAILED] [--set-data JSON] |
| 11 | // the bot (docs/sdk-v1.md §2.13–§2.16), as scripts/sandbox-node.ts: --message sets the |
| 12 | // server's flags for a kind of message (WIDGET_MESSAGE_KINDS in sdk-policy.ts: private |
| 13 | // taps and background requests; group, via-bot taps only; no-queries, an original sent |
| 14 | // without allow_queries, no requests; live-copy, a forward of a widget sent with |
| 15 | // fwd_allow_queries, taps only; copy no requests; preview an inline result not |
| 16 | // sent yet: no input, no requests, only ready and setResizeAnchor, no storage); --copy, --can-query, |
| 17 | // --background-query, --chat-type set them one by one on top (none given: no |
| 18 | // requests); every request that passes the glue gets --answer (the server's answer, |
| 19 | // {"result":"…"}, default {"result":null}) or fails with --answer-error; --set-data is |
| 20 | // the bot's data (the full state) after the events and their answers (--wait-ms); the |
| 21 | // run prints `request …` and `copyText …` |
| 22 | // twidget-run --attacks [DIR] every attack file: nothing but data:/#fragment URLs may reach the validated ops |
| 23 | // twidget-run --corpus DIR smoke run of a corpus directory: loaded, alive, no uncaught errors |
| 24 | // … --blitz [--png out.png | --png-dir DIR] [--click X,Y]... [--dpr N] |
| 25 | // the same through WidgetHost + the Blitz renderer (-DTW_BLITZ=ON): real layout |
| 26 | // answers, pointer events hit-tested by the document, a raster of the result |
| 27 | // |
| 28 | // Without --blitz, layout queries get canned answers (no renderer), so chart |
| 29 | // libraries lay out against a 100×20 box; what is checked is the sandbox, the |
| 30 | // validator and the limits — not pixels. With --blitz the validated ops go to |
| 31 | // the Rust document and a fetch attempt from it is counted as a leak too. |
| 32 | |
| 33 | #include "png.h" |
| 34 | #include "recording_host.h" |
| 35 | #ifdef TW_HAVE_BLITZ |
| 36 | #include "twidget/blitz_renderer.h" |
| 37 | #endif |
| 38 | #ifdef TW_HAVE_LITEHTML |
| 39 | #include "twidget/litehtml_renderer.h" |
| 40 | #endif |
| 41 | #if defined(TW_HAVE_BLITZ) || defined(TW_HAVE_LITEHTML) |
| 42 | #include "twidget/widget_host.h" |
| 43 | #endif |
| 44 | |
| 45 | #include <algorithm> |
| 46 | #include <cctype> |
| 47 | #include <chrono> |
| 48 | #include <cstdio> |
| 49 | #include <cstdlib> |
| 50 | #include <cstring> |
| 51 | #include <filesystem> |
| 52 | #include <fstream> |
| 53 | #include <map> |
| 54 | #include <sstream> |
| 55 | #include <string> |
| 56 | #include <thread> |
| 57 | #include <vector> |
| 58 | |
| 59 | using namespace twidget; |
| 60 | namespace fs = std::filesystem; |
| 61 | |
| 62 | static std::string readFile(const fs::path& p) { |
| 63 | std::ifstream in(p, std::ios::binary); |
| 64 | std::ostringstream ss; |
| 65 | ss << in.rdbuf(); |
| 66 | return ss.str(); |
| 67 | } |
| 68 | |
| 69 | struct Options { |
| 70 | std::string jsDir = TW_WIDGET_JS; |
| 71 | std::string theme = "light"; |
| 72 | std::map<std::string, std::string> themeParams; |
| 73 | std::string locale = std::string(sdk::DEFAULT_LOCALE); |
| 74 | WidgetStorage storage; |
| 75 | // The client's side of the bot (the harness handles every request, as the Node harness's CLI does). |
| 76 | WidgetData data; |
| 77 | WidgetContext context; |
| 78 | WidgetRequestOutcome answer; |
| 79 | std::optional<WidgetData> setData; |
| 80 | double width = 400; |
| 81 | int waitMs = 1500; |
| 82 | bool verbose = false; |
| 83 | bool printOps = false; |
| 84 | std::vector<std::string> events; |
| 85 | std::vector<std::string> probes; |
| 86 | // --blitz / --litehtml |
| 87 | bool blitz = false; |
| 88 | bool litehtml = false; |
| 89 | double dpr = 1; |
| 90 | std::string png, pngDir; |
| 91 | std::vector<std::pair<double, double>> clicks; |
| 92 | }; |
| 93 | |
| 94 | struct RunOutcome { |
| 95 | bool loaded = false; |
| 96 | std::optional<std::string> died; |
| 97 | int batches = 0, renderOps = 0, elements = 0, queries = 0, errors = 0; |
| 98 | std::map<std::string, int> diagCounts; |
| 99 | std::vector<std::string> leaks; |
| 100 | std::vector<std::string> notes; |
| 101 | std::vector<std::pair<std::string, std::string>> logs; |
| 102 | std::vector<WidgetAction> actions; |
| 103 | std::vector<std::pair<std::string, StorageArea>> storageCommits; |
| 104 | /// The widget's latest `setResizeAnchor` ("top" until then) and, without a native renderer, each change in order. |
| 105 | std::string resizeAnchor = std::string(sdk::DEFAULT_RESIZE_ANCHOR); |
| 106 | std::vector<std::string> resizeAnchors; |
| 107 | /// Whether the widget watches its shared public_data at the end (round 7) and each change in order. |
| 108 | bool watchesPublicData = false; |
| 109 | std::vector<bool> publicDataWatches; |
| 110 | /// The requests that passed the glue (the gate's refusals are `request-blocked` diagnostics) and the texts copied. |
| 111 | std::vector<WidgetRequest> requests; |
| 112 | std::vector<std::string> copiedTexts; |
| 113 | std::vector<std::string> probeResults; |
| 114 | std::string renderOpsJson; |
| 115 | SandboxStats stats; |
| 116 | // --blitz |
| 117 | double height = 0, paintMs = -1, initMs = 0, loadedMs = 0, renderedMs = 0; |
| 118 | uint32_t frameW = 0, frameH = 0; |
| 119 | std::vector<uint8_t> frame; |
| 120 | }; |
| 121 | |
| 122 | /// Anything in the validated ops that could make a renderer touch the network. |
| 123 | /// |
| 124 | /// `data:` payloads are opaque to the renderer's network stack: an SVG loaded as |
| 125 | /// an image may not fetch external resources (SVG-as-image rules in every |
| 126 | /// engine), so a URL *inside* a data: URL is reported as a note, not a leak — |
| 127 | /// the browser attack suite confirms zero canary hits for exactly these files. |
| 128 | /// In CSS only `url()`-family functions and `@import` can trigger a fetch; a |
| 129 | /// string token holding "http://…" (e.g. in a custom property) is inert. |
| 130 | static bool mentionsNetwork(std::string l) { |
| 131 | std::transform(l.begin(), l.end(), l.begin(), [](unsigned char c) { return char(std::tolower(c)); }); |
| 132 | return l.find("127.0.0.1") != std::string::npos || l.find("http://") != std::string::npos || l.find("https://") |
| 133 | l.find("ws://") != std::string::npos || l.find("wss://") != std::string::npos || l.rfind("//", 0) |
| 134 | } |
| 135 | |
| 136 | static void scanCssForLeaks(const std::string& where, const std::string& css, std::vector<std::string |
| 137 | std::string l = css; |
| 138 | std::transform(l.begin(), l.end(), l.begin(), [](unsigned char c) { return char(std::tolower(c)); }); |
| 139 | if (l.find("@import") != std::string::npos) leaks.push_back(where + ": @import survived: " + css.substr(0, 160)); |
| 140 | static const char* const fns[] = {"url(", "image-set(", "image(", "src(", "cross-fade("}; |
| 141 | for (const char* fn : fns) { |
| 142 | size_t len = std::strlen(fn); |
| 143 | for (size_t pos = l.find(fn); pos != std::string::npos; pos = l.find(fn, pos + len)) { |
| 144 | if (pos > 0 && (std::isalnum((unsigned char)l[pos - 1]) || l[pos - 1] == '-')) |
| 145 | size_t a = pos + len; |
| 146 | while (a < l.size() && (l[a] == ' ' || l[a] == '\t' || l[a] == '\n' || l[a] |
| 147 | std::string arg = l.substr(a, 12); |
| 148 | if (arg.rfind("data:", 0) == 0 || arg.rfind("#", 0) == 0) continue; |
| 149 | if (std::strcmp(fn, "image-set(") == 0 && (arg.rfind("url(", 0) == 0 || arg.rfind("image(", |
| 150 | leaks.push_back(where + ": " + css.substr(pos, 160)); |
| 151 | } |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | static void scanForLeaks(const Json& op, std::vector<std::string>& leaks, std::vector<std:: |
| 156 | const std::string& kind = op["op"].asString(); |
| 157 | auto flagAttr = [&](const std::string& where, const std::string& value) { |
| 158 | if (value.rfind("data:", 0) == 0) { if (mentionsNetwork(value)) notes.push_back(where + " (inert URL inside a data: payload): " + value.substr(0, 120 |
| 159 | if (mentionsNetwork(value)) leaks.push_back(where + ": " + value.substr(0, 160)); |
| 160 | }; |
| 161 | if (kind == "el") { |
| 162 | for (const auto& pair : op["attrs"].arr()) { |
| 163 | const std::string& name = pair[0].asString(); |
| 164 | if (name == "style") scanCssForLeaks("el.style", pair[1].asString(), leaks); |
| 165 | else flagAttr("el." + name, pair[1].asString()); |
| 166 | } |
| 167 | } else if (kind == "attr") { |
| 168 | if (op["name"].asString() == "style") scanCssForLeaks("attr style", op["value"].asString(), leaks); |
| 169 | else flagAttr("attr " + op["name"].asString(), op["value"].asString()); |
| 170 | } else if (kind == "style") { |
| 171 | scanCssForLeaks("style " + op["name"].asString(), op["value"].asString(), leaks); |
| 172 | } else if (kind == "css") { |
| 173 | scanCssForLeaks("css", op["text"].asString(), leaks); |
| 174 | } else if (kind == "canvas") { |
| 175 | for (const auto& cmd : op["cmds"].arr()) |
| 176 | for (const auto& a : cmd.arr()) if (a.isString()) { scanCssForLeaks("canvas", a.asString(), leaks); flagAttr("canvas", a.asString()); } |
| 177 | } |
| 178 | } |
| 179 | |
| 180 | #if defined(TW_HAVE_BLITZ) || defined(TW_HAVE_LITEHTML) |
| 181 | /// WidgetHost + a native renderer (BlitzRenderer or LitehtmlRenderer, the same owner contract): the pipeline |
| 182 | /// the demos run, with the native document answering layout queries. |
| 183 | template <typename NativeRenderer> |
| 184 | static RunOutcome runWidgetNative(const std::string& html, const Options& opts, std::shared_ptr<SandboxResources> res) { |
| 185 | RunOutcome out; |
| 186 | std::vector<std::string> renderOps; |
| 187 | WidgetHostOptions ho; |
| 188 | ho.devicePixelRatio = opts.dpr; |
| 189 | ho.locale = opts.locale; |
| 190 | ho.storage = opts.storage; |
| 191 | ho.data = opts.data; |
| 192 | ho.context = opts.context; |
| 193 | NativeRenderer* blitz = nullptr; |
| 194 | WidgetTheme theme{opts.theme, opts.themeParams, {}}; |
| 195 | WidgetHost host(html, theme, opts.width, ho, res, [&](std::shared_ptr<SandboxResources>, const std::string& scheme, double width) -> std::unique_ptr<Renderer> { |
| 196 | auto r = std::make_unique<NativeRenderer>(scheme, width, opts.dpr); |
| 197 | blitz = r.get(); |
| 198 | return r; |
| 199 | }); |
| 200 | host.onRenderOps = [&](const std::string& clean) { |
| 201 | renderOps.push_back(clean); |
| 202 | if (opts.verbose) fprintf(stderr, "ops → %s\n", clean.size() > 2000 ? (clean.substr(0, 2000) + "…").c_str() : clean. |
| 203 | }; |
| 204 | // On the host thread; read after destroy(), when the host thread has drained. |
| 205 | host.onStorageCommit = [&](const std::string& area, const StorageArea& values) { out.storageCommits.emplace_back(area, values); }; |
| 206 | host.onRequest = [&](const WidgetRequest& request, std::function<void(const WidgetRequestOutcome&)> respond) { |
| 207 | out.requests.push_back(request); |
| 208 | respond(opts.answer); |
| 209 | }; |
| 210 | host.onCopyText = [&](const std::string& text) { out.copiedTexts.push_back(text); }; |
| 211 | host.onWatchPublicData = [&](bool on) { out.publicDataWatches.push_back(on); }; |
| 212 | host.start(); |
| 213 | host.waitLoaded(30); |
| 214 | host.waitRendered(5); |
| 215 | for (const auto& ev : opts.events) host.event(ev); |
| 216 | for (const auto& [x, y] : opts.clicks) blitz->click(x, y); |
| 217 | std::this_thread::sleep_for(std::chrono::milliseconds(opts.waitMs)); |
| 218 | if (opts.setData) host.setData(*opts.setData); // after the presses' answers; before the probes, which wait for it |
| 219 | for (const auto& p : opts.probes) out.probeResults.push_back(host.probe(p)); |
| 220 | typename NativeRenderer::Frame frame = blitz->paint(); |
| 221 | out.initMs = blitz->initMs(); |
| 222 | WidgetDiagnostics d = host.diagnostics(); |
| 223 | host.destroy(); |
| 224 | |
| 225 | out.loaded = d.loaded; |
| 226 | out.died = d.dead; |
| 227 | if (out.died && *out.died == "terminated") out.died.reset(); |
| 228 | out.batches = int(renderOps.size()); |
| 229 | for (const auto& b : renderOps) { |
| 230 | if (auto arr = Json::parse(b)) { |
| 231 | for (const auto& op : arr->arr()) { |
| 232 | out.renderOps++; |
| 233 | if (op["op"].asString() == "el") out.elements++; |
| 234 | scanForLeaks(op, out.leaks, out.notes); |
| 235 | } |
| 236 | } |
| 237 | out.renderOpsJson += b; |
| 238 | } |
| 239 | out.queries = d.stats.queries; |
| 240 | for (const auto& [kind, entry] : d.diags) { |
| 241 | out.diagCounts[kind] = entry.first; |
| 242 | // The Rust side refuses every non-data: URL; with the validator in front it must never see one. |
| 243 | if (kind == "renderer-violation") |
| 244 | for (const auto& detail : entry.second) if (detail.rfind("fetch refused", 0) == 0) out.leaks.push_back("renderer " + detail); |
| 245 | } |
| 246 | for (const auto& lg : d.logs) if (lg.first == "error") out.errors++; |
| 247 | out.logs = d.logs; |
| 248 | out.actions = d.actions; |
| 249 | out.resizeAnchor = d.resizeAnchor; |
| 250 | out.watchesPublicData = d.watchesPublicData; |
| 251 | out.stats = d.stats; |
| 252 | out.height = d.height; |
| 253 | out.loadedMs = d.loadedMs.value_or(0); |
| 254 | out.renderedMs = d.renderedMs.value_or(0); |
| 255 | out.paintMs = frame.paintMs; |
| 256 | out.frameW = frame.width; |
| 257 | out.frameH = frame.height; |
| 258 | out.frame = std::move(frame.rgba); |
| 259 | return out; |
| 260 | } |
| 261 | #endif |
| 262 | |
| 263 | static RunOutcome runWidget(const std::string& html, const Options& opts, std::shared_ptr<SandboxResources> res, SandboxConfig |
| 264 | #ifdef TW_HAVE_BLITZ |
| 265 | if (opts.blitz) return runWidgetNative<BlitzRenderer>(html, opts, res); |
| 266 | #endif |
| 267 | #ifdef TW_HAVE_LITEHTML |
| 268 | if (opts.litehtml) return runWidgetNative<LitehtmlRenderer>(html, opts, res); |
| 269 | #endif |
| 270 | RunOutcome out; |
| 271 | RecordingHost host(opts.theme, res, opts.verbose, config.policy); |
| 272 | host.onRequest = [&](const WidgetRequest&, std::function<void(const WidgetRequestOutcome&)> respond) { respond(opts.answer); }; |
| 273 | { |
| 274 | SandboxEngine engine(html, config, res); |
| 275 | engine.setDelegate(&host); |
| 276 | // As WidgetHost: the validator's time on the widget's messages counts against its JS quota. |
| 277 | host.validator().setCpuSink([&engine](double ms) { engine.chargeValidator(ms); }); |
| 278 | engine.start(); |
| 279 | host.waitLoaded(30); |
| 280 | // An event with a numeric `gesture` is a trusted press (as the Node harness's `gesture: n`); the rest are untrusted. |
| 281 | for (const auto& ev : opts.events) { |
| 282 | auto parsed = Json::parse(ev); |
| 283 | if (parsed && (*parsed)["gesture"].isNumber() && (*parsed)["gesture"].asInt() > 0) { |
| 284 | // Without a renderer, a trusted event also stands for the renderer's press (pointerdown, mousedown) or its |
| 285 | // release (anything else): the haptic gate's touch, as in scripts/sandbox-node.ts. |
| 286 | const std::string& type = (*parsed)["type"].asString(); |
| 287 | if (type == "pointerdown" || type == "mousedown") engine.pressBegan(); |
| 288 | else engine.pressEnded(); |
| 289 | engine.activationEvent(ev, (*parsed)["gesture"].asInt()); |
| 290 | } else { |
| 291 | engine.event(ev); |
| 292 | } |
| 293 | } |
| 294 | std::this_thread::sleep_for(std::chrono::milliseconds(opts.waitMs)); |
| 295 | if (opts.setData) engine.setData(*opts.setData); // after the presses' answers; before the probes, which wait for it |
| 296 | for (const auto& p : opts.probes) out.probeResults.push_back(engine.probe(p)); |
| 297 | engine.terminate(); |
| 298 | engine.thread().join(); |
| 299 | host.validator().setCpuSink(nullptr); |
| 300 | } |
| 301 | auto l = host.lock(); |
| 302 | out.loaded = host.loaded; |
| 303 | out.died = host.died; |
| 304 | if (out.died && *out.died == "terminated") out.died.reset(); |
| 305 | out.batches = int(host.ops.size()); |
| 306 | for (const auto& b : host.renderOps) { |
| 307 | if (auto arr = Json::parse(b)) { |
| 308 | for (const auto& op : arr->arr()) { |
| 309 | out.renderOps++; |
| 310 | if (op["op"].asString() == "el") out.elements++; |
| 311 | scanForLeaks(op, out.leaks, out.notes); |
| 312 | } |
| 313 | } |
| 314 | out.renderOpsJson += b; |
| 315 | } |
| 316 | out.queries = int(host.queries.size()); |
| 317 | for (const auto& d : host.diags) out.diagCounts[d.first]++; |
| 318 | for (const auto& lg : host.logs) if (lg.first == "error") out.errors++; |
| 319 | out.logs = host.logs; |
| 320 | out.actions = host.actions; |
| 321 | out.storageCommits = host.storageCommits; |
| 322 | out.resizeAnchors = host.resizeAnchors; |
| 323 | if (!host.resizeAnchors.empty()) out.resizeAnchor = host.resizeAnchors.back(); |
| 324 | out.requests = host.requests; |
| 325 | out.copiedTexts = host.copiedTexts; |
| 326 | out.publicDataWatches = host.publicDataWatches; |
| 327 | if (!host.publicDataWatches.empty()) out.watchesPublicData = host.publicDataWatches.back(); |
| 328 | out.stats = host.stats; |
| 329 | return out; |
| 330 | } |
| 331 | |
| 332 | /// `--set-data`, the full state: {"chatData": "…" | null, "publicData": "…" | null}; a missing field is none. |
| 333 | static bool widgetData(const Json& v, WidgetData& out) { |
| 334 | if (!v.isObject()) return false; |
| 335 | for (const char* field : {"chatData", "publicData"}) { |
| 336 | const Json& x = v[field]; |
| 337 | if (!x.isString() && !x.isNull()) return false; |
| 338 | (std::string(field) == "chatData" ? out.chatData : out.publicData) = x.isString() ? std::optional<std::string>(x.asString()) : |
| 339 | } |
| 340 | return true; |
| 341 | } |
| 342 | |
| 343 | /// The answer as the client hands it over; what breaks the limits is the glue's to refuse (`answer-rejected`). |
| 344 | static std::string outcomeText(const WidgetRequestOutcome& o) { |
| 345 | if (o.failure != WidgetRequestFailure::None) return std::string(sdk::requestFailureCode(o.failure)); |
| 346 | Json a = Json::object(); |
| 347 | a.set("result", o.answer.result ? Json(*o.answer.result) : Json()); |
| 348 | return a.dump(); |
| 349 | } |
| 350 | |
| 351 | /// `--viewer id,first,last,username,premium` (the TS `viewerFromList`): parts trimmed, empty parts absent, premium any of |
| 352 | /// `1`, `true`, `premium`; no positive id → no viewer. Unchecked: the engine checks it (`data-rejected` per field). |
| 353 | static std::optional<WidgetViewer> viewerFromList(const std::string& list) { |
| 354 | std::vector<std::string> parts; |
| 355 | for (size_t start = 0;;) { |
| 356 | size_t comma = list.find(',', start); |
| 357 | std::string part = list.substr(start, comma == std::string::npos ? std::string::npos : comma - start); |
| 358 | size_t a = part.find_first_not_of(" \t"), b = part.find_last_not_of(" \t"); |
| 359 | parts.push_back(a == std::string::npos ? std::string() : part.substr(a, b - a + 1)); |
| 360 | if (comma == std::string::npos) break; |
| 361 | start = comma + 1; |
| 362 | } |
| 363 | parts.resize(std::max<size_t>(parts.size(), 5)); |
| 364 | char* end = nullptr; |
| 365 | double id = std::strtod(parts[0].c_str(), &end); |
| 366 | if (parts[0].empty() || !end || *end != '\0' || !(id > 0)) return |
| 367 | WidgetViewer v; |
| 368 | v.id = int64_t(id); |
| 369 | if (!parts[1].empty()) v.firstName = parts[1]; |
| 370 | if (!parts[2].empty()) v.lastName = parts[2]; |
| 371 | if (!parts[3].empty()) v.username = parts[3]; |
| 372 | v.isPremium = parts[4] == "1" || parts[4] == "true" || parts[4] == "premium"; |
| 373 | return v; |
| 374 | } |
| 375 | |
| 376 | /// `--message`: the server's flags for a kind of message and the chat type it comes with (WIDGET_MESSAGE_KINDS in |
| 377 | /// sdk-policy.ts); false for an unknown kind. |
| 378 | static bool messageKind(const std::string& kind, WidgetContext& out) { |
| 379 | struct Kind { const char* name; bool isCopy, canQuery, backgroundQuery; const char* chatType; bool preview; }; |
| 380 | static const Kind kinds[] = { |
| 381 | {"private", false, true, true, "private", false}, // the original in the private chat with the bot that sent it |
| 382 | {"group", false, true, false, "group", false}, // an original the bot sent to a group it is a member of |
| 383 | {"via-bot", false, true, false, "private", false}, // an original sent via the bot (inline mode), in a private chat between two users |
| 384 | {"no-queries", false, false, false, "private", false}, // an original the bot sent without allow_queries |
| 385 | {"live-copy", true, true, false, "private", false}, // a forwarded copy of a widget the bot sent with fwd_allow_queries |
| 386 | {"copy", true, false, false, "private", false}, // a forwarded copy of a widget sent without fwd_allow_queries |
| 387 | {"preview", false, false, false, "private", true}, // an inline result not sent yet (docs/sdk-v1.md §2.16) |
| 388 | }; |
| 389 | for (const Kind& k : kinds) { |
| 390 | if (kind != k.name) continue; |
| 391 | out.isCopy = k.isCopy; |
| 392 | out.canQuery = k.canQuery; |
| 393 | out.backgroundQuery = k.backgroundQuery; |
| 394 | out.chatType = k.chatType; |
| 395 | out.preview = k.preview; |
| 396 | return true; |
| 397 | } |
| 398 | return false; |
| 399 | } |
| 400 | |
| 401 | /// `--theme-params` / `--storage`: a JSON object of strings (the engine checks keys, colours and the quota). |
| 402 | static bool stringMap(const Json& v, std::map<std::string, std::string>& out) { |
| 403 | if (!v.isObject()) return false; |
| 404 | for (const auto& [k, x] : v.obj()) { |
| 405 | if (!x.isString()) return false; |
| 406 | out[k] = x.asString(); |
| 407 | } |
| 408 | return true; |
| 409 | } |
| 410 | |
| 411 | static std::string diagSummary(const std::map<std::string, int>& counts) { |
| 412 | std::string s; |
| 413 | for (const auto& [k, n] : counts) { |
| 414 | if (k == "boot" || k == "library") continue; |
| 415 | if (!s.empty()) s += ", "; |
| 416 | s += k + (n > 1 ? "×" + std::to_string(n) : ""); |
| 417 | } |
| 418 | return s; |
| 419 | } |
| 420 | |
| 421 | /// `--png` / `--png-dir`: the Blitz raster of a run, if any; returns what was written for the report. |
| 422 | static std::string writePng(const RunOutcome& r, const std::string& path) { |
| 423 | if (path.empty() || r.frame.empty()) return ""; |
| 424 | fs::create_directories(fs::path(path).parent_path().empty() ? fs::path(".") : fs::path(path).parent_path()); |
| 425 | return png::write(path, r.frameW, r.frameH, r.frame) ? path : "(png write failed: " + path + ")"; |
| 426 | } |
| 427 | |
| 428 | static std::vector<fs::path> htmlFiles(const fs::path& dir) { |
| 429 | std::vector<fs::path> files; |
| 430 | for (const auto& e : fs::directory_iterator(dir)) if (e.path().extension() == ".html") files.push_back(e.path()); |
| 431 | std::sort(files.begin(), files.end()); |
| 432 | return files; |
| 433 | } |
| 434 | |
| 435 | int main(int argc, char** argv) { |
| 436 | Options opts; |
| 437 | std::string file, attacksDir, corpusDir; |
| 438 | bool attacks = false; |
| 439 | // The message's flags: --message's kind first, then --copy / --can-query / --background-query / --chat-type on top, in any order. |
| 440 | std::optional<std::string> message, chatType; |
| 441 | bool copy = false, canQuery = false, backgroundQuery = false; |
| 442 | for (int i = 1; i < argc; i++) { |
| 443 | std::string a = argv[i]; |
| 444 | auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; }; |
| 445 | if (a == "--verbose") opts.verbose = true; |
| 446 | else if (a == "--ops") opts.printOps = true; |
| 447 | else if (a == "--events") opts.events.push_back(next()); |
| 448 | else if (a == "--probe" || a == "--eval") opts.probes.push_back(next()); |
| 449 | else if (a == "--wait-ms") opts.waitMs = std::atoi(next().c_str()); |
| 450 | else if (a == "--theme") opts.theme = next(); |
| 451 | else if (a == "--theme-params") { |
| 452 | auto v = Json::parse(next()); |
| 453 | if (!v || !stringMap(*v, opts.themeParams)) { fprintf(stderr, "--theme-params wants a JSON object of strings\n"); return 2; } |
| 454 | } |
| 455 | else if (a == "--locale") opts.locale = next(); |
| 456 | else if (a == "--storage") { |
| 457 | auto v = Json::parse(next()); |
| 458 | bool ok = v && v->isObject(); |
| 459 | for (const auto& [area, values] : ok ? v->obj() : Json::Object{}) |
| 460 | ok = ok && (area == "local" || area == "session") && stringMap(values, area == "local" ? opts.storage.local : opts.storage.session); |
| 461 | if (!ok) { fprintf(stderr, "--storage wants {\"local\": {…}, \"session\": {…}} with string values\n"); return 2; } |
| 462 | } |
| 463 | else if (a == "--chat-data") opts.data.chatData = next(); |
| 464 | else if (a == "--public-data") opts.data.publicData = next(); |
| 465 | else if (a == "--message") message = next(); |
| 466 | else if (a == "--copy") copy = true; |
| 467 | else if (a == "--can-query") canQuery = true; |
| 468 | else if (a == "--background-query") backgroundQuery = true; |
| 469 | else if (a == "--chat-type") chatType = next(); |
| 470 | else if (a == "--viewer") opts.context.viewer = viewerFromList(next()); |
| 471 | else if (a == "--answer") { |
| 472 | // The server's answer is only the result (the bot changes its data with edits: --set-data). |
| 473 | auto v = Json::parse(next()); |
| 474 | bool ok = v && v->isObject() && ((*v)["result"].isString() || (*v)["result"].isNull()); |
| 475 | for (const auto& [key, _] : ok ? v->obj() : Json::Object{}) ok = ok && key == "result"; |
| 476 | if (ok && (*v)["result"].isString()) opts.answer.answer.result = (*v)["result"].asString(); |
| 477 | if (!ok) { fprintf(stderr, "--answer wants {\"result\": \"…\" | null}\n"); return 2; } |
| 478 | } |
| 479 | else if (a == "--answer-error") { |
| 480 | std::string code = next(); |
| 481 | opts.answer.failure = code == "TIMEOUT" ? WidgetRequestFailure::Timeout : code == "RATE_LIMITED" ? WidgetRequestFailure::RateLimited : WidgetRequestFailure::Failed; |
| 482 | if (code != "TIMEOUT" && code != "RATE_LIMITED" && code != "FAILED") { fprintf(stderr, "--answer-error wants TIMEOUT, RATE_LIMITED or FAILED\n"); return 2; } |
| 483 | } |
| 484 | else if (a == "--set-data") { |
| 485 | auto v = Json::parse(next()); |
| 486 | if (!v || !widgetData(*v, opts.setData.emplace())) { fprintf(stderr, "--set-data wants {\"chatData\": \"…\" | null, \"publicData\": \" |
| 487 | } |
| 488 | else if (a == "--width") opts.width = std::atof(next().c_str()); |
| 489 | else if (a == "--js-dir") opts.jsDir = next(); |
| 490 | else if (a == "--blitz") opts.blitz = true; |
| 491 | else if (a == "--litehtml") opts.litehtml = true; |
| 492 | else if (a == "--dpr") opts.dpr = std::atof(next().c_str()); |
| 493 | else if (a == "--png") opts.png = next(); |
| 494 | else if (a == "--png-dir") opts.pngDir = next(); |
| 495 | else if (a == "--click") { std::string v = next(); size_t c = v.find(','); if (c == std::string::npos) { |
| 496 | else if (a == "--attacks") { attacks = true; if (i + 1 < argc && argv[i + 1][0] != |
| 497 | else if (a == "--corpus") corpusDir = next(); |
| 498 | else if (!a.empty() && a[0] == '-') { fprintf(stderr, "unknown option %s\n", a.c_str()); return 2; } |
| 499 | else file = a; |
| 500 | } |
| 501 | if (message && !messageKind(*message, opts.context)) { fprintf(stderr, "--message takes private, group, via-bot, no-queries, live-copy, copy or preview\n"); return 2; } |
| 502 | if (copy) opts.context.isCopy = true; |
| 503 | if (canQuery) opts.context.canQuery = true; |
| 504 | if (backgroundQuery) opts.context.backgroundQuery = true; |
| 505 | if (chatType) opts.context.chatType = *chatType; |
| 506 | if (file.empty() && !attacks && corpusDir.empty()) { |
| 507 | fprintf(stderr, "usage: twidget-run <widget.html> [--verbose] [--ops] [--events JSON] [--wait-ms N] [--probe EXPR]\n" |
| 508 | " [--theme dark] [--theme-params JSON] [--locale TAG] [--storage JSON] (an event with \"gesture\": n is a trusted press)\n" |
| 509 | " [--message private|group|via-bot|no-queries|live-copy|copy|preview] [--copy] [--can-query] [--background-query]\n" |
| 510 | " [--chat-type T] [--viewer ID[,FIRST,LAST,USERNAME,PREMIUM]] [--chat-data S] [--public-data S]\n" |
| 511 | " [--answer '{\"result\":…}' | --answer-error TIMEOUT|RATE_LIMITED|FAILED] [--set-data JSON] (the bot)\n" |
| 512 | " twidget-run --attacks [DIR] | --corpus DIR\n" |
| 513 | " … --blitz | --litehtml [--png FILE | --png-dir DIR] [--click X,Y] [--dpr N] (built with -DTW_BLITZ=ON / -DTW_LITEHTML=ON)\n"); |
| 514 | return 2; |
| 515 | } |
| 516 | #ifndef TW_HAVE_BLITZ |
| 517 | if (opts.blitz) { fprintf(stderr, "--blitz needs a build with -DTW_BLITZ=ON (rustup's cargo; see packages/desktop/README.md)\n"); return 2; } |
| 518 | #endif |
| 519 | #ifndef TW_HAVE_LITEHTML |
| 520 | if (opts.litehtml) { fprintf(stderr, "--litehtml needs a build with -DTW_LITEHTML=ON (macOS; see packages/desktop/README.md)\n"); return 2; } |
| 521 | #endif |
| 522 | if (opts.blitz && opts.litehtml) { fprintf(stderr, "--blitz and --litehtml are exclusive\n"); return 2; } |
| 523 | std::shared_ptr<SandboxResources> res; |
| 524 | try { res = SandboxResources::fromDirectory(opts.jsDir); } catch (const std::exception& e) { fprintf(stderr, "%s\n", e.what()); return 2; } |
| 525 | SandboxConfig config; |
| 526 | config.innerWidth = opts.width; |
| 527 | config.theme = opts.theme; |
| 528 | config.themeParams = opts.themeParams; |
| 529 | config.locale = opts.locale; |
| 530 | config.storage = opts.storage; |
| 531 | config.data = opts.data; |
| 532 | config.context = opts.context; |
| 533 | |
| 534 | if (attacks) { |
| 535 | fs::path dir = attacksDir.empty() ? fs::path(TW_CORPUS) / "attacks" : fs::path(attacksDir); |
| 536 | auto files = htmlFiles(dir); |
| 537 | int leaks = 0, dead = 0; |
| 538 | printf("%-40s %-8s %s\n", "attack", "status", "diagnostics"); |
| 539 | for (const auto& f : files) { |
| 540 | // One click so click-triggered vectors fire too (targetId 2 = <html>; events bubble from the document). |
| 541 | Options o = opts; |
| 542 | o.events.push_back("{\"type\":\"click\",\"targetId\":2,\"clientX\":5,\"clientY\":5}"); |
| 543 | RunOutcome r = runWidget(readFile(f), o, res, config); |
| 544 | std::string status = !r.leaks.empty() ? "LEAK" : r.died ? "dead" : "ok"; |
| 545 | if (!r.leaks.empty()) leaks++; |
| 546 | if (r.died) dead++; |
| 547 | std::string extra = r.died ? " — " + r.died->substr(0, 90) : ""; |
| 548 | printf("%-40s %-8s %s%s\n", f.filename().string().c_str(), status.c_str(), diagSummary(r.diagCounts).c_str(), extra.c_str()); |
| 549 | for (const auto& leak : r.leaks) printf(" LEAK %s\n", leak.c_str()); |
| 550 | for (const auto& note : r.notes) printf(" note %s\n", note.c_str()); |
| 551 | if (!opts.pngDir.empty()) writePng(r, (fs::path(opts.pngDir) / (f.stem().string() + ".png")).string()); |
| 552 | fflush(stdout); |
| 553 | } |
| 554 | printf("\n%zu attacks, %d with URLs leaking into validated ops%s, %d runtimes killed by limits\n", files.size(), leaks, |
| 555 | (opts.blitz || opts.litehtml) ? " or fetched by the renderer" : "", dead); |
| 556 | return leaks ? 1 : 0; |
| 557 | } |
| 558 | |
| 559 | if (!corpusDir.empty()) { |
| 560 | auto files = htmlFiles(corpusDir); |
| 561 | int pass = 0; |
| 562 | const bool native = opts.blitz || opts.litehtml; |
| 563 | if (native) printf("%-32s %-6s %6s %6s %5s %4s %6s %6s %7s %s\n", "widget", "status", |
| 564 | else printf("%-32s %-6s %6s %6s %5s %4s %s\n", "widget", "status", "ops", "els", "qry", |
| 565 | for (const auto& f : files) { |
| 566 | RunOutcome r = runWidget(readFile(f), opts, res, config); |
| 567 | bool ok = r.loaded && !r.died && r.errors == 0 && r.leaks.empty(); |
| 568 | if (ok) pass++; |
| 569 | std::string status = !r.leaks.empty() ? "LEAK" : r.died ? "dead" : r.errors ? "errors" : "ok"; |
| 570 | if (native) |
| 571 | printf("%-32s %-6s %6d %6d %5d %4d %6.0f %5.1fms %5.0fms %s%s\n", f.filename().string().c_str(), status. |
| 572 | r.height, r.paintMs, r.loadedMs, diagSummary(r.diagCounts).c_str(), r.died ? (" — " + r.died->substr(0, 80)).c_str() : ""); |
| 573 | else |
| 574 | printf("%-32s %-6s %6d %6d %5d %4d %s%s\n", f.filename().string().c_str(), status.c_str(), r.renderOps, r.elements, r.queries, r.errors, |
| 575 | diagSummary(r.diagCounts).c_str(), r.died ? (" — " + r.died->substr(0, 80)).c_str() : ""); |
| 576 | if (!opts.pngDir.empty()) writePng(r, (fs::path(opts.pngDir) / (f.stem().string() + ".png")).string()); |
| 577 | if (opts.verbose) for (const auto& lg : r.logs) if (lg.first == "error") printf(" %s\n", lg.second.substr(0, 300).c_str()); |
| 578 | fflush(stdout); |
| 579 | } |
| 580 | printf("\n%d / %zu loaded without errors\n", pass, files.size()); |
| 581 | return pass == int(files.size()) ? 0 : 1; |
| 582 | } |
| 583 | |
| 584 | RunOutcome r = runWidget(readFile(file), opts, res, config); |
| 585 | for (size_t i = 0; i < r.probeResults.size(); i++) printf("probe[%zu] %s → %s\n", i, opts.probes[i].c_str(), r.probeResults[i].c_str()); |
| 586 | if (opts.printOps) printf("%s\n", r.renderOpsJson.c_str()); |
| 587 | printf("\nbatches %d, render ops %d (%d elements), queries %d, tasks %d, js %.0f ms, validator %.0f ms, memory %zu KB%s\n", r.batches, r.renderOps, r.elements, r.queries, |
| 588 | r.stats.tasks, r.stats.jsMs, r.stats.validatorMs, r.stats.memoryBytes / 1024, r.died ? (" — DEAD: " + *r.died).c_str() : ""); |
| 589 | if (opts.blitz || opts.litehtml) { |
| 590 | printf("%-6s height %.0f px, frame %u×%u px, paint %.1f ms, init %.1f ms, loaded %.0f ms, rendered %.0f ms\n", opts.blitz ? "blitz" : "lite" |
| 591 | std::string written = writePng(r, opts.png); |
| 592 | if (!written.empty()) printf("png %s\n", written.c_str()); |
| 593 | } |
| 594 | for (const auto& [k, n] : r.diagCounts) printf("diag %s ×%d\n", k.c_str(), n); |
| 595 | for (const auto& lg : r.logs) printf("[%s] %s\n", lg.first.c_str(), lg.second.c_str()); |
| 596 | for (const auto& a : r.actions) printf("action %s\n", a.toJson().dump().c_str()); |
| 597 | if (!r.resizeAnchors.empty() || r.resizeAnchor != sdk::DEFAULT_RESIZE_ANCHOR) { |
| 598 | std::string calls; |
| 599 | for (const auto& e : r.resizeAnchors) calls += (calls.empty() ? "" : " → ") + e; |
| 600 | printf("resize anchor: %s%s: the %s edge of the bubble stays put when the height changes\n", r.resizeAnchor.c_str(), |
| 601 | calls.empty() ? "" : (" (setResizeAnchor: " + calls + ")").c_str(), r.resizeAnchor.c_str()); |
| 602 | } |
| 603 | if (!r.publicDataWatches.empty()) { |
| 604 | std::string calls; |
| 605 | for (bool on : r.publicDataWatches) calls += std::string(calls.empty() ? "" : " → ") + (on ? "true" : "false"); |
| 606 | printf("public data: %s (watchPublicData: %s): a client polls a shared widget's public_data only while it watches\n", |
| 607 | r.watchesPublicData ? "watched" : "not watched", calls.c_str()); |
| 608 | } |
| 609 | for (const auto& q : r.requests) |
| 610 | printf("request %s → %s\n", Json::quote(q.data).c_str(), outcomeText(opts.answer).c_str()); |
| 611 | for (const auto& t : r.copiedTexts) printf("copyText %s\n", Json::quote(t).c_str()); |
| 612 | for (const auto& [area, values] : r.storageCommits) { |
| 613 | Json v = Json::object(); |
| 614 | for (const auto& [k, x] : values) v.set(k, x); |
| 615 | std::string text = v.dump(); |
| 616 | printf("storage %s %s\n", area.c_str(), text.size() > 500 ? (text.substr(0, 500) + "…").c_str() |
| 617 | } |
| 618 | for (const auto& leak : r.leaks) printf("LEAK %s\n", leak.c_str()); |
| 619 | return r.leaks.empty() ? 0 : 1; |
| 620 | } |
| 621 | |