| 1 | // Attack suite: every file in corpus/attacks/ is loaded in SANDBOX mode (never |
| 2 | // reference mode) and must cause (a) zero hits on the canary server and (b) no |
| 3 | // browser request from any frame to anything but the app's own origin. |
| 4 | // TW_RENDERER=shadow runs the same suite on the Shadow DOM renderer (no iframe, |
| 5 |
| 6 | // so (a) and (b) measure exactly what the frame boundary used to add. |
| 7 |
| 8 | import { expect, test, type Page } from '@playwright/test'; |
| 9 | import fs from 'node:fs'; |
| 10 | import path from 'node:path'; |
| 11 | import { fileURLToPath } from 'node:url'; |
| 12 | import { APP_ORIGIN, CANARY } from '../playwright.config'; |
| 13 |
| 14 | const attacksDir = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'corpus', 'attacks'); |
| 15 | const files = fs.readdirSync(attacksDir).filter((f) => f.endsWith('.html')).sort(); |
| 16 |
| 17 | const ALLOWED = [APP_ORIGIN + '/', APP_ORIGIN.replace(/^http/, 'ws') + '/', 'data:', 'blob:', 'about:']; |
| 18 | const SHADOW = process.env.TW_RENDERER === 'shadow'; |
| 19 | const RENDERER_PARAM = SHADOW ? '&shadow=1' : ''; |
| 20 | /** The renderer's element in the bubble. */ |
| 21 | const RENDERER_SEL = SHADOW ? '#sandbox-wrap .widget-shadow' : '#sandbox-wrap iframe'; |
| 22 | /** Locator for the widget's DOM: the frame, or the shadow host (Playwright pierces open shadow roots). */ |
| 23 | const widgetDom = (page: Page) => (SHADOW ? page.locator(RENDERER_SEL) : page.frameLocator(RENDERER_SEL)); |
| 24 | const isAllowed = (url: string) => ALLOWED.some((p) => url.startsWith(p)); |
| 25 |
| 26 | async function canaryHits(): Promise<unknown[]> { |
| 27 | return (await (await fetch(CANARY + '/__hits')).json()) as unknown[]; |
| 28 | } |
| 29 | async function resetCanary(): Promise<void> { |
| 30 | await fetch(CANARY + '/__reset'); |
| 31 | } |
| 32 |
| 33 | /** Record every request / websocket the page (any frame) attempts. */ |
| 34 | function watchRequests(page: Page): string[] { |
| 35 | const seen: string[] = []; |
| 36 | page.on('request', (r) => { if (!isAllowed(r.url())) seen.push(`${r.method()} ${r.url()} [${r.resourceType()}]`); }); |
| 37 | page.on('websocket', (ws) => { if (!isAllowed(ws.url())) seen.push(`WS ${ws.url()}`); }); |
| 38 | page.on('requestfailed', (r) => { if (!isAllowed(r.url())) seen.push(`FAILED ${r.url()}`); }); |
| 39 | return seen; |
| 40 | } |
| 41 |
| 42 | test('control: the canary records hits from the app page', async ({ page }) => { |
| 43 | await resetCanary(); |
| 44 | // Not reference mode and not a widget: trusted page code on the app origin |
| 45 | // (loopback → loopback, like a leaking widget would be) proving the harness |
| 46 | // can see leaks. An about:blank page would be in Chrome's "public" address |
| 47 | // space and get Private Network Access treatment instead. |
| 48 | await page.goto('/'); |
| 49 | await page.evaluate((canary) => { |
| 50 | const img = document.createElement('img'); |
| 51 | img.src = `${canary}/hit/control-img`; |
| 52 | document.body.appendChild(img); |
| 53 | fetch(`${canary}/hit/control-fetch`, { mode: 'no-cors' }).catch(() => {}); |
| 54 | }, CANARY); |
| 55 | await expect.poll(async () => (await canaryHits()).filter((h: any) => h.kind === 'http' && /control-(img|fetch)/.test(h.url)), { timeout: 5000 }).not.toHaveLength(0); |
| 56 | await resetCanary(); |
| 57 | }); |
| 58 |
| 59 | // ───────────── runtime limits (docs/decisions.md) ───────────── |
| 60 |
| 61 | const twState = (page: Page) => page.evaluate(() => { |
| 62 | const s = (window as any).__tw.state; |
| 63 | return { dead: s.dead as string | null, loaded: s.loaded as boolean, diags: s.diags as Record<string, { count: number; details: string[] }>, stats: s.stats, logs: s.logs as { level: string; text: string }[], actions: s.actions as { kind: string }[] }; |
| 64 | }); |
| 65 | async function openAttack(page: Page, file: string, params = '') { |
| 66 | await page.goto(`/?file=attacks/${file}${params}${RENDERER_PARAM}`); |
| 67 | await page.waitForFunction(() => (window as any).__tw?.state && ((window as any).__tw.state.loaded || (window as any).__tw.state.dead), null, { timeout: 60_000 }); |
| 68 | return widgetDom(page); |
| 69 | } |
| 70 | const waitDead = (page: Page) => page.waitForFunction(() => (window as any).__tw.state.dead, null, { timeout: 15_000 }); |
| 71 |
| 72 | test.describe('last render as fallback', () => { |
| 73 | test('a widget killed after a click stays on screen, frozen, and ignores further events', async ({ page }) => { |
| 74 | const pageErrors: string[] = []; |
| 75 | page.on('pageerror', (e) => pageErrors.push(String(e))); |
| 76 | const f = await openAttack(page, 'fallback-after-kill.html'); |
| 77 | await f.locator('#go').click(); |
| 78 | await waitDead(page); |
| 79 | expect((await twState(page)).dead).toMatch(/CPU limit/); |
| 80 | // The last consistent render is still there; the click handler's own mutation never flushed. |
| 81 | await expect(f.locator('#text')).toHaveText('Delivered to the front desk at 14:32.'); |
| 82 | await expect(f.locator('#clicks')).toHaveText('0'); |
| 83 | await expect(f.locator('html')).toHaveAttribute('data-tw-frozen', 'fatal'); |
| 84 | await expect(f.locator('[data-tw-badge]')).toHaveText('Widget stopped'); |
| 85 | await expect(page.locator('#widget-error')).toContainText('Widget stopped'); |
| 86 | await expect(page.locator(RENDERER_SEL)).toHaveCount(1); |
| 87 | // Events are no longer forwarded (pointer-events: none on <html>; forwarding gated in the renderer too). |
| 88 | await f.locator('#go').click({ force: true }); |
| 89 | await page.waitForTimeout(300); |
| 90 | await expect(f.locator('#clicks')).toHaveText('0'); |
| 91 | expect(pageErrors).toEqual([]); |
| 92 | }); |
| 93 |
| 94 | test('a task killed in the middle of a batch leaves none of its mutations in the renderer', async ({ page }) => { |
| 95 | const f = await openAttack(page, 'fallback-mid-batch.html'); |
| 96 | await f.locator('#go').click(); |
| 97 | await waitDead(page); |
| 98 | await expect(f.locator('#status')).toHaveText('ready'); |
| 99 | await expect(f.locator('#list li')).toHaveCount(0); |
| 100 | await expect(f.locator('html')).toHaveAttribute('data-tw-frozen', 'fatal'); |
| 101 | }); |
| 102 |
| 103 | test('a script that hangs at boot leaves the static markup visible', async ({ page }) => { |
| 104 | const f = await openAttack(page, 'fallback-at-boot.html'); |
| 105 | await waitDead(page); |
| 106 | await expect(f.locator('#static')).toHaveText('Weather in Lisbon'); |
| 107 | await expect(f.locator('#temp')).toBeVisible(); |
| 108 | // Unlike a browser, the whole document is parsed before the first script runs, so later markup is there too. |
| 109 | await expect(f.locator('#after')).toBeVisible(); |
| 110 | await expect(f.locator('[data-tw-badge]')).toBeVisible(); |
| 111 | }); |
| 112 | }); |
| 113 |
| 114 | test.describe('timer limit', () => { |
| 115 | test('a 100 000-timer flood is refused past maxTimers with a RangeError; the widget stays alive and bounded', async ({ page }) => { |
| 116 | const f = await openAttack(page, 'timer-flood.html'); |
| 117 | await expect(f.locator('#status')).toHaveText('done: RangeError: too many timers (max 64)'); |
| 118 | await expect(f.locator('#count')).toHaveText('64 accepted, 99936 refused'); |
| 119 | await page.waitForTimeout(1500); |
| 120 | const s = await twState(page); |
| 121 | expect(s.dead).toBeNull(); |
| 122 | expect(s.diags['timer-limit']?.count).toBe(1); |
| 123 | expect(s.diags['timer-limit-enforced']).toBeUndefined(); |
| 124 | expect(s.stats.memoryBytes).toBeLessThan(32 * 1024 * 1024); |
| 125 | await f.locator('#btn').click(); |
| 126 | await expect(f.locator('#clicks')).toHaveText('1'); |
| 127 | }); |
| 128 |
| 129 | test('a timer id the shim asks for again replaces its timer: 1000 forged calls on one id fire its callback once', async ({ page }) => { |
| 130 | const f = await openAttack(page, 'timer-id-reuse.html'); |
| 131 | await expect(f.locator('#p')).toHaveText('fired 1', { timeout: 10_000 }); |
| 132 | const s = await twState(page); |
| 133 | expect(s.dead).toBeNull(); |
| 134 | expect(s.diags['timer-limit-enforced']).toBeUndefined(); |
| 135 | }); |
| 136 | }); |
| 137 |
| 138 | // The paint limit (docs/decisions.md, "Heavy boxes"): the renderer counts the widget's heavy boxes before each frame and |
| 139 | // stops it past 16 (2 with backdrop-filter). Each corpus/attacks/paint-* is stopped with its count, its last frame drawn |
| 140 | // without the effects (no blurred shadow, filter, backdrop-filter or transparency on any of its elements) under the |
| 141 | // badge, and the page keeps its frame rate. |
| 142 | test.describe('paint limit', () => { |
| 143 | const PAINT = (n: number) => new RegExp(`^Paint limit exceeded: ${n} boxes with shadows, filters or transparency \\(max 16\\)$`); |
| 144 | const cases: [string, RegExp, string][] = [ |
| 145 | ['paint-shadow-layers.html', PAINT(120), 'paint-limit'], |
| 146 | ['paint-nested-filters.html', PAINT(60), 'paint-limit'], |
| 147 | ['paint-heavy-17.html', PAINT(17), 'paint-limit'], |
| 148 | ['paint-animation-17.html', PAINT(17), 'paint-limit'], |
| 149 | ['paint-ars.html', PAINT(250), 'paint-limit'], |
| 150 | ['paint-backdrop-3.html', /^Paint limit exceeded: 3 boxes with backdrop-filter \(max 2\)$/, 'backdrop-limit'], |
| 151 | ]; |
| 152 | /** The widget's elements that still draw an effect: a blurred shadow layer, a filter, a backdrop-filter, opacity below 1. */ |
| 153 | const effectsLeft = (page: Page) => widgetDom(page).locator('[data-tw-frozen]').evaluate((root) => [root, ...Array.from(root.querySelectorAll('*'))] |
| 154 | .filter((el) => !el.hasAttribute('data-tw-badge')) |
| 155 | .filter((el) => { |
| 156 | const cs = getComputedStyle(el); |
| 157 | const blurred = cs.boxShadow !== 'none' && cs.boxShadow.replace(/\([^)]*\)/g, '').split(',').some((l) => { |
| 158 | const n = l.trim().split(/\s+/).filter((t) => /^-?[\d.]+px$/.test(t)); |
| 159 | return n.length >= 3 && parseFloat(n[2]) > 0; |
| 160 | }); |
| 161 | return blurred || cs.filter !== 'none' || (cs.backdropFilter || 'none') !== 'none' || parseFloat(cs.opacity) < 1; |
| 162 | }).length); |
| 163 | const pageFps = (page: Page) => page.evaluate(async () => { |
| 164 | let n = 0; |
| 165 | const t0 = performance.now(); |
| 166 | while (performance.now() - t0 < 1000) { await new Promise((r) => requestAnimationFrame(r)); n++; } |
| 167 | return n; |
| 168 | }); |
| 169 |
| 170 | for (const [file, reason, code] of cases) { |
| 171 | test(`${file}: stopped by the paint limit, its last frame without the effects, the page at full rate`, async ({ page }) => { |
| 172 | const f = await openAttack(page, file); |
| 173 | await waitDead(page); |
| 174 | const s = await twState(page); |
| 175 | expect(s.dead).toMatch(reason); |
| 176 | expect(s.diags[code]?.details).toEqual([s.dead]); |
| 177 | await expect(f.locator('[data-tw-badge]')).toHaveText('Widget stopped'); |
| 178 | expect(await effectsLeft(page)).toBe(0); |
| 179 | expect(await pageFps(page)).toBeGreaterThan(40); |
| 180 | }); |
| 181 | } |
| 182 |
| 183 | test('compat counts nothing: 17 heavy boxes draw with their effects', async ({ page }) => { |
| 184 | const f = await openAttack(page, 'paint-heavy-17.html', '&policy=compat'); |
| 185 | await expect(f.locator('#p')).toHaveText('drawn'); |
| 186 | await page.waitForTimeout(500); |
| 187 | const s = await twState(page); |
| 188 | expect(s.dead).toBeNull(); |
| 189 | expect(s.diags['paint-limit']).toBeUndefined(); |
| 190 | const shadows = await f.locator('.b').evaluateAll((els) => els.filter((el) => getComputedStyle(el).boxShadow !== 'none').length); |
| 191 | expect(shadows).toBe(17); |
| 192 | }); |
| 193 | }); |
| 194 |
| 195 | test.describe('bitmaps', () => { |
| 196 | const claimed = fs.readFileSync(path.join(attacksDir, 'mem-huge-bitmaps.html'), 'utf8').match(/id="claims" alt="" src="data:image\/png;base64,([^"]+)"/)![1]; |
| 197 | test('strict: canvases past 2048² pixels together stop the widget before they reach the page', async ({ page }) => { |
| 198 | await openAttack(page, 'mem-huge-bitmaps.html'); |
| 199 | await waitDead(page); |
| 200 | expect((await twState(page)).dead).toMatch(/^Canvas limit exceeded: canvases of \d+ pixels together \(max 4194304\)$/); |
| 201 | const sizes = await widgetDom(page).locator('canvas').evaluateAll((cs) => cs.map((c) => (c as HTMLCanvasElement).width * (c as HTMLCanvasElement).height)); |
| 202 | expect(sizes.reduce((a, b) => a + b, 0)).toBeLessThanOrEqual(2048 * 2048); |
| 203 | }); |
| 204 |
| 205 | test('compat: the renderer itself never applies a canvas size past 4096 × 4096, and images past 1024² are the placeholder', async ({ page }) => { |
| 206 | const f = await openAttack(page, 'mem-huge-bitmaps.html', '&policy=compat'); |
| 207 | await expect(f.locator('#log')).toHaveText('drawn'); |
| 208 | const image = (id: string) => f.locator(id).evaluate(async (el: HTMLImageElement) => { |
| 209 | await el.decode().catch(() => {}); |
| 210 | return [el.naturalWidth, el.naturalHeight]; |
| 211 | }); |
| 212 | const canvas = (id: string) => f.locator(id).evaluate((el: HTMLCanvasElement) => [el.width, el.height]); |
| 213 | const pixels = ([w, h]: number[]) => w * h; |
| 214 | await expect.poll(() => image('#small')).toEqual([40, 20]); |
| 215 | for (const id of ['#claims', '#past']) expect(pixels(await image(id)), id).toBeLessThanOrEqual(1024 * 1024); |
| 216 | for (const id of ['#attr', '#scripted']) expect(pixels(await canvas(id)), id).toBeLessThanOrEqual(4096 * 4096); |
| 217 | expect(await canvas('#plain')).toEqual([300, 150]); |
| 218 | expect(await f.locator('#css').evaluate((el) => getComputedStyle(el).backgroundImage)).not.toContain(claimed.slice(0, 40)); |
| 219 | const s = await twState(page); |
| 220 | expect(s.dead).toBeNull(); |
| 221 | expect(s.diags['renderer-violation']?.count).toBeGreaterThanOrEqual(1); |
| 222 | }); |
| 223 | }); |
| 224 |
| 225 | test.describe('pointers', () => { |
| 226 | test('a widget that asks for the mouse every frame never takes a press on the page; its own press is its own', async ({ page }) => { |
| 227 | const f = await openAttack(page, 'activation-pointer-capture.html'); |
| 228 | await page.evaluate(() => { |
| 229 | const b = document.createElement('button'); |
| 230 | b.textContent = 'app'; |
| 231 | b.style.cssText = 'position:fixed;left:0;top:0;width:120px;height:40px;z-index:99999'; |
| 232 | (window as any).__appClicks = 0; |
| 233 | b.addEventListener('click', () => (window as any).__appClicks++); |
| 234 | document.body.appendChild(b); |
| 235 | }); |
| 236 | await page.waitForTimeout(300); |
| 237 | await page.mouse.move(60, 20); |
| 238 | await page.mouse.down(); |
| 239 | await page.waitForTimeout(200); |
| 240 | await page.mouse.up(); |
| 241 | await page.waitForTimeout(500); |
| 242 | expect(await page.evaluate(() => (window as any).__appClicks)).toBe(1); |
| 243 | expect(await page.evaluate(() => (window as any).__tw.state.copiedTexts)).toEqual([]); |
| 244 | await f.locator('#t').click(); |
| 245 | // the dev app's phone mode plays a finger with the mouse: the widget sees pointerType touch |
| 246 | await expect.poll(() => page.evaluate(() => (window as any).__tw.state.copiedTexts)).toEqual([expect.stringMatching(/^captured-(mouse|touch)$/)]); |
| 247 | }); |
| 248 | }); |
| 249 |
| 250 | test.describe("a finger's press", () => { |
| 251 | // Real touch input (CDP touch events): the dev app's phone mode and Playwright's clicks play a finger with the mouse, |
| 252 | // whose pointerdown is a gesture. |
| 253 | test.use({ hasTouch: true }); |
| 254 | const touches = async (page: Page) => { |
| 255 | const cdp = await page.context().newCDPSession(page); |
| 256 | const box = (await page.locator(RENDERER_SEL).boundingBox())!; |
| 257 | const x = box.x + box.width / 2, y = box.y + 60; |
| 258 | const touch = (type: 'touchStart' | 'touchMove' | 'touchEnd', points: { x: number; y: number }[]) => cdp.send('Input.dispatchTouchEvent', { type, touchPoints: points.map((p) => ({ ...p, id: 1 })) }); |
| 259 | return { |
| 260 | async swipe(dy: number) { |
| 261 | await touch('touchStart', [{ x, y }]); |
| 262 | for (let i = 1; i <= 10; i++) { await touch('touchMove', [{ x, y: y + (dy * i) / 10 }]); await page.waitForTimeout(16); } |
| 263 | await touch('touchEnd', []); |
| 264 | }, |
| 265 | async tap() { |
| 266 | await touch('touchStart', [{ x, y }]); |
| 267 | await page.waitForTimeout(60); |
| 268 | await touch('touchEnd', []); |
| 269 | }, |
| 270 | }; |
| 271 | }; |
| 272 | const seen = (page: Page) => page.evaluate(() => ({ requests: (window as any).__tw.bot.requests.map((r: any) => r.data as string), copied: (window as any).__tw.state.copiedTexts as string[] })); |
| 273 |
| 274 | test('a swipe that starts on the widget is the chat\'s scroll: no request and no copyText from its pointerdown; a tap still gets its click', async ({ page }) => { |
| 275 | await resetCanary(); |
| 276 | await openAttack(page, 'activation-touch-swipe.html', '&message=group'); |
| 277 | await page.waitForTimeout(300); |
| 278 | const t = await touches(page); |
| 279 | await t.swipe(160); |
| 280 | await page.waitForTimeout(800); |
| 281 | expect(await seen(page)).toEqual({ requests: [], copied: [] }); |
| 282 | await t.tap(); |
| 283 | await expect.poll(async () => (await seen(page)).copied).toEqual(['click']); |
| 284 | await page.waitForTimeout(300); |
| 285 | expect((await seen(page)).requests).toEqual([]); |
| 286 | expect(await canaryHits()).toHaveLength(0); |
| 287 | }); |
| 288 | }); |
| 289 |
| 290 | test.describe('light-dark()', () => { |
| 291 | test('no branch of light-dark() fetches anything in the dark theme either', async ({ page }) => { |
| 292 | await resetCanary(); |
| 293 | const outside = watchRequests(page); |
| 294 | await page.goto(`/?file=attacks/css-light-dark-url.html&theme=dark${RENDERER_PARAM}`); |
| 295 | await page.waitForFunction(() => (window as any).__tw?.state?.loaded, null, { timeout: 60_000 }); |
| 296 | await page.waitForTimeout(1500); |
| 297 | expect(await canaryHits()).toHaveLength(0); |
| 298 | expect(outside).toHaveLength(0); |
| 299 | expect((await twState(page)).diags['url-blocked']?.count).toBeGreaterThan(0); |
| 300 | }); |
| 301 | }); |
| 302 |
| 303 | test.describe('memory limit', () => { |
| 304 | // The wasm build cannot count its heap (quickjs-ng has no malloc_usable_size under emscripten), so the |
| 305 | // worker caps the wasm Memory at INITIAL + memoryLimitBytes; the engine then throws the same catchable |
| 306 | // `InternalError: out of memory` as the native builds do at JS_SetMemoryLimit. tests/unit/memory-limit.test.ts |
| 307 | // covers the harness; this is the real worker, with the kill, the frozen fallback and the stats. |
| 308 | const FOOTPRINT_MB = 16 + 8; |
| 309 |
| 310 | test('steady growth without a try/catch is killed with "Memory limit exceeded" and the last render stays frozen', async ({ page }) => { |
| 311 | const f = await openAttack(page, 'mem-uncaught-growth.html'); |
| 312 | await waitDead(page); |
| 313 | const s = await twState(page); |
| 314 | expect(s.dead).toMatch(/^Memory limit exceeded \(8 MB\)/); |
| 315 | // The render before the fatal tick is still there: a count in MB, below the cap. |
| 316 | const reached = parseInt(await f.locator('#mb').textContent() ?? '', 10); |
| 317 | expect(reached).toBeGreaterThanOrEqual(4); |
| 318 | expect(reached).toBeLessThanOrEqual(FOOTPRINT_MB); |
| 319 | await expect(f.locator('html')).toHaveAttribute('data-tw-frozen', 'fatal'); |
| 320 | await expect(f.locator('[data-tw-badge]')).toHaveText('Widget stopped'); |
| 321 | }); |
| 322 |
| 323 | // QuickJS from the TelegramMessenger/quickjs fork (quickjs-ng 0.17, as on native): out-of-memory is |
| 324 | // uncatchable, so a widget that tries to catch it is stopped like one that does not; the last render stays. |
| 325 | test('steady growth that tries to catch the error is still stopped at the cap, with its last render kept', async ({ page }) => { |
| 326 | const f = await openAttack(page, 'mem-steady-growth.html'); |
| 327 | await page.waitForFunction(() => (window as any).__tw.state.dead, null, { timeout: 15_000 }); |
| 328 | const s = await twState(page); |
| 329 | expect(s.dead).toMatch(/^Memory limit exceeded/); |
| 330 | const reached = parseInt(await f.locator('#mb').textContent() ?? '', 10); |
| 331 | expect(reached).toBeGreaterThanOrEqual(4); |
| 332 | expect(reached).toBeLessThanOrEqual(FOOTPRINT_MB); |
| 333 | await expect(f.locator('#mb')).not.toHaveText(/alloc refused/); |
| 334 | await expect(f.locator('html')).toHaveAttribute('data-tw-frozen', 'fatal'); |
| 335 | }); |
| 336 |
| 337 | test('one 256 MB allocation is refused outright and stops the widget without growing it', async ({ page }) => { |
| 338 | const f = await openAttack(page, 'mem-burst-alloc.html'); |
| 339 | await f.locator('#go').click(); |
| 340 | await page.waitForFunction(() => (window as any).__tw.state.dead, null, { timeout: 15_000 }); |
| 341 | const s = await twState(page); |
| 342 | expect(s.dead).toMatch(/^Memory limit exceeded/); |
| 343 | await expect(f.locator('#status')).not.toHaveText(/allocated/); |
| 344 | expect(s.stats.memoryBytes).toBeLessThan(32 * 1024 * 1024); |
| 345 | }); |
| 346 |
| 347 | test('the engine-agnostic probe is stopped at the cap during boot', async ({ page }) => { |
| 348 | // mem-cap-probe.html allocates synchronously at boot: the runtime dies there, never past the cap. |
| 349 | await openAttack(page, 'mem-cap-probe.html'); |
| 350 | const s = await twState(page); |
| 351 | expect(s.dead).toMatch(/^Memory limit exceeded/); |
| 352 | }); |
| 353 | }); |
| 354 |
| 355 | // ───────────── requests to the bot (docs/sdk-v1.md §2.14) ───────────── |
| 356 |
| 357 | test.describe('requests to the bot', () => { |
| 358 | const bot = (page: Page) => page.evaluate(() => { |
| 359 | const tw = (window as any).__tw; |
| 360 | return { requests: tw.bot.requests.map((r: any) => r.data as string), pending: tw.bot.pendingRequests.length, copied: tw.state.copiedTexts as string[], actions: tw.state.actions as unknown[] }; |
| 361 | }); |
| 362 | const diagCount = async (page: Page, kind: string) => (await twState(page)).diags[kind]?.count ?? 0; |
| 363 |
| 364 | test('no request and no copyText without a real tap; the tap sends exactly one', async ({ page }) => { |
| 365 | await resetCanary(); |
| 366 | const f = await openAttack(page, 'request-no-activation.html', '&message=group'); |
| 367 | await page.waitForTimeout(800); |
| 368 | expect((await bot(page)).requests).toEqual([]); |
| 369 | expect((await bot(page)).copied).toEqual([]); |
| 370 | expect(await diagCount(page, 'request-blocked')).toBeGreaterThanOrEqual(4); |
| 371 | await f.locator('#go').click(); |
| 372 | await expect.poll(async () => (await bot(page)).requests).toEqual(['http://127.0.0.1:9999/hit/request-tap']); |
| 373 | await page.waitForTimeout(500); |
| 374 | const b = await bot(page); |
| 375 | expect(b.requests).toHaveLength(1); |
| 376 | expect(b.copied).toEqual([]); // the request took the tap |
| 377 | await expect(f.locator('#log')).toContainText('tap:sent'); |
| 378 | expect(await canaryHits()).toHaveLength(0); |
| 379 | }); |
| 380 |
| 381 | test('a widget that rewrites the wire gets nothing over the limits through: the glue re-checks every call', async ({ page }) => { |
| 382 | const f = await openAttack(page, 'request-forged-wire.html', '&message=group'); |
| 383 | await f.locator('#go').click(); |
| 384 | // The oversized request, the one with a forged id (the shim forwards it: only the glue's gate says BUSY) and the copyText. |
| 385 | await expect.poll(() => diagCount(page, 'bridge-rejected')).toBe(3); |
| 386 | await page.waitForTimeout(300); |
| 387 | const b = await bot(page); |
| 388 | expect(b.requests).toEqual([]); |
| 389 | expect(b.copied).toEqual([]); |
| 390 | expect(b.actions).toEqual([]); |
| 391 | expect(await canaryHits()).toHaveLength(0); |
| 392 | }); |
| 393 |
| 394 | test('background requests: none where they are not allowed; where they are, one at a time and one per 5 s', async ({ page }) => { |
| 395 | await openAttack(page, 'request-background-flood.html', '&message=group'); |
| 396 | await page.waitForTimeout(1500); |
| 397 | expect((await bot(page)).requests).toEqual([]); |
| 398 | await openAttack(page, 'request-background-flood.html'); |
| 399 | await page.waitForTimeout(6500); |
| 400 | const b = await bot(page); |
| 401 | expect(b.requests.length).toBeGreaterThanOrEqual(1); |
| 402 | expect(b.requests.length).toBeLessThanOrEqual(2); |
| 403 | expect((await twState(page)).dead).toBeNull(); |
| 404 | expect(await canaryHits()).toHaveLength(0); |
| 405 | }); |
| 406 |
| 407 | test('background requests off screen: none go out while hidden; one per appearance, then one per 5 s', async ({ page }) => { |
| 408 | await openAttack(page, 'request-background-flood.html', '&offscreen=1'); |
| 409 | await page.waitForTimeout(1500); |
| 410 | expect((await bot(page)).requests).toEqual([]); |
| 411 | const show = async (n: number) => { |
| 412 | await page.evaluate(() => (window as any).__tw.setVisible(true)); |
| 413 | await expect.poll(async () => (await bot(page)).requests.length).toBe(n); |
| 414 | await page.waitForTimeout(2500); |
| 415 | expect((await bot(page)).requests).toHaveLength(n); |
| 416 | }; |
| 417 | await show(1); // the request held since boot, at once |
| 418 | for (const n of [2, 3]) { |
| 419 | await page.evaluate(() => (window as any).__tw.setVisible(false)); |
| 420 | await page.waitForTimeout(1200); // the hidden flood's timers run at 1 Hz: one request is held, the rest BUSY |
| 421 | expect((await bot(page)).requests).toHaveLength(n - 1); |
| 422 | await show(n); |
| 423 | } |
| 424 | expect((await twState(page)).dead).toBeNull(); |
| 425 | expect(await canaryHits()).toHaveLength(0); |
| 426 | }); |
| 427 |
| 428 | test('one request in flight: a second one in the same tap, from a timer or forged on the wire never reaches the client', async ({ page }) => { |
| 429 | const f = await openAttack(page, 'request-in-flight.html', '&message=group&botmode=manual'); |
| 430 | await f.locator('#go').click(); |
| 431 | await expect.poll(async () => (await bot(page)).pending).toBe(1); |
| 432 | await page.waitForTimeout(500); |
| 433 | const b = await bot(page); |
| 434 | expect(b.requests).toEqual(['first']); |
| 435 | await expect(f.locator('#log')).toContainText('second:BUSY'); |
| 436 | await expect(f.locator('#log')).toContainText('timer:BUSY'); |
| 437 | expect(await diagCount(page, 'request-blocked')).toBeGreaterThanOrEqual(1); // the forged one: busy in the glue |
| 438 | }); |
| 439 |
| 440 | test('an answer over the limits never reaches the widget: INVALID_ANSWER', async ({ page }) => { |
| 441 | const f = await openAttack(page, 'request-in-flight.html', '&message=group'); |
| 442 | await page.evaluate(() => { (window as any).__tw.bot.request = () => Promise.resolve({ result: 'x'.repeat(1025) }); }); |
| 443 | await f.locator('#go').click(); |
| 444 | await expect(f.locator('#log')).toContainText('first:INVALID_ANSWER'); |
| 445 | expect(await diagCount(page, 'answer-rejected')).toBe(1); |
| 446 | }); |
| 447 |
| 448 | test('a forwarded copy without fwd_allow_queries reads no chatData, chat or viewer and sends nothing, tap or not', async ({ page }) => { |
| 449 | const f = await openAttack(page, 'request-copy.html', '&message=copy'); |
| 450 | await expect(f.locator('#seen')).toHaveText('true||||'); |
| 451 | await f.locator('#go').click(); |
| 452 | await page.waitForTimeout(800); |
| 453 | expect((await bot(page)).requests).toEqual([]); |
| 454 | await expect(f.locator('#log')).toContainText('tap:NOT_ALLOWED'); |
| 455 | }); |
| 456 |
| 457 | test('a live copy (fwd_allow_queries) reads no chatData or chat and asks only on a tap, never in the background', async ({ page }) => { |
| 458 | const f = await openAttack(page, 'request-copy.html', '&message=live-copy'); |
| 459 | await expect(f.locator('#seen')).toHaveText(/^true\|\|\|\[object Object\]\|/); |
| 460 | await page.waitForTimeout(800); |
| 461 | expect((await bot(page)).requests).toEqual([]); |
| 462 | await f.locator('#go').click(); |
| 463 | await expect.poll(async () => (await bot(page)).requests).toEqual(['copy-tap']); |
| 464 | await page.waitForTimeout(800); |
| 465 | expect((await bot(page)).requests).toEqual(['copy-tap']); |
| 466 | }); |
| 467 | }); |
| 468 |
| 469 | // ───────────── the wallet (docs/sdk-v1.md §2.18) ───────────── |
| 470 |
| 471 | test.describe('the wallet', () => { |
| 472 | const calls = (page: Page) => page.evaluate(() => (window as any).__tw.bot.requests.map((r: any) => (r.kind ? r.kind + ':' : '') + r.data) as string[]); |
| 473 | const diagCount = async (page: Page, kind: string) => (await twState(page)).diags[kind]?.count ?? 0; |
| 474 |
| 475 | test('no wallet window without a real tap, not even on a background request\'s answer; the tap opens one', async ({ page }) => { |
| 476 | await resetCanary(); |
| 477 | const f = await openAttack(page, 'wallet-no-activation.html'); |
| 478 | await page.waitForTimeout(1000); |
| 479 | expect(await calls(page)).toEqual(['bg']); // the background request itself, which grants nothing |
| 480 | await expect(page.locator('.wallet-sheet')).toHaveCount(0); |
| 481 | await expect(f.locator('#log')).toContainText('canary:TypeError'); |
| 482 | await expect(f.locator('#log')).toContainText('background-answer:NOT_ALLOWED'); |
| 483 | expect(await diagCount(page, 'request-blocked')).toBeGreaterThanOrEqual(5); |
| 484 | await f.locator('#go').click(); |
| 485 | await expect(page.locator('.wallet-sheet')).toHaveCount(1); |
| 486 | await page.locator('#wallet-decline').click(); |
| 487 | await expect(f.locator('#log')).toContainText('tap:REJECTED'); |
| 488 | expect(await calls(page)).toEqual(['bg', 'sendTransaction:tap']); |
| 489 | expect(await canaryHits()).toHaveLength(0); |
| 490 | }); |
| 491 |
| 492 | test('a widget that rewrites the wire gets no wallet call through: the glue re-checks every one', async ({ page }) => { |
| 493 | await resetCanary(); |
| 494 | const f = await openAttack(page, 'wallet-forged-wire.html'); |
| 495 | await f.locator('#go').click(); |
| 496 | await expect.poll(() => diagCount(page, 'bridge-rejected')).toBe(5); |
| 497 | await page.waitForTimeout(500); |
| 498 | expect(await calls(page)).toEqual([]); |
| 499 | await expect(page.locator('.wallet-sheet')).toHaveCount(0); |
| 500 | expect(await canaryHits()).toHaveLength(0); |
| 501 | }); |
| 502 |
| 503 | test('one grant, one window: a second call is BUSY, a refusal brings no grant, a later timer gets none', async ({ page }) => { |
| 504 | const f = await openAttack(page, 'wallet-grant-reuse.html', '&message=group'); |
| 505 | await f.locator('#go').click(); |
| 506 | await expect(page.locator('.wallet-sheet')).toHaveCount(1); |
| 507 | await expect(f.locator('#log')).toContainText('second:BUSY'); |
| 508 | await page.locator('#wallet-decline').click(); |
| 509 | await expect(f.locator('#log')).toContainText('after-refusal:NOT_ALLOWED'); |
| 510 | await expect(f.locator('#log')).toContainText('timer:NOT_ALLOWED', { timeout: 5000 }); |
| 511 | await expect(page.locator('.wallet-sheet')).toHaveCount(0); |
| 512 | expect(await calls(page)).toEqual(['order', 'sendTransaction:first']); |
| 513 | }); |
| 514 | }); |
| 515 |
| 516 | test.describe('cpu quota', () => { |
| 517 | test('a forced-layout loop is killed by the layout-query budget, the host stays responsive', async ({ page }) => { |
| 518 | await resetCanary(); |
| 519 | const t0 = Date.now(); |
| 520 | await openAttack(page, 'layout-query-loop.html'); |
| 521 | await waitDead(page); |
| 522 | const s = await twState(page); |
| 523 | // Which limit fires first depends on the renderer's answer time: the iframe's round trip makes the query budget the binding one |
| 524 | // ("Layout query limit exceeded"), the Shadow DOM renderer answers fast enough for the loop's own CPU to reach the slice first. |
| 525 | expect(s.dead).toMatch(/^(Layout query limit exceeded: (more than 128 layout queries|host queries blocked the renderer for more than \d+ ms) in one boot task|CPU limit exceeded: more than \d+ ms of continuous execution)/); |
| 526 | // The main thread answered the queries all along and is free now: a round trip through the page is instant. |
| 527 | expect(Date.now() - t0).toBeLessThan(15_000); |
| 528 | expect(await page.evaluate(() => 1 + 1)).toBe(2); |
| 529 | expect(await canaryHits()).toHaveLength(0); |
| 530 | }); |
| 531 |
| 532 | test('a greedy interval is throttled, not killed, and clicks still get through', async ({ page }) => { |
| 533 | const f = await openAttack(page, 'cpu-greedy-timer.html'); |
| 534 | const js0 = (await twState(page)).stats.jsMs as number; |
| 535 | await page.waitForTimeout(3000); |
| 536 | const s = await twState(page); |
| 537 | expect(s.dead).toBeNull(); |
| 538 | expect(s.diags['cpu-throttled']?.count).toBeGreaterThan(0); |
| 539 | expect(s.stats.throttledTasks).toBeGreaterThan(0); |
| 540 | // 40 ms per tick at 10 Hz would be 1200 ms of JS in 3 s; the 300 ms/s quota caps it (plus one slice of slack). |
| 541 | expect((s.stats.jsMs as number) - js0).toBeLessThan(3 * 300 * 1.2 + 50); |
| 542 | expect(Number(await f.locator('#ticks').textContent())).toBeGreaterThan(3); |
| 543 | await f.locator('#btn').click(); |
| 544 | await expect(f.locator('#clicks')).toHaveText('1'); |
| 545 | await expect(page.locator('#status')).toHaveText('● loaded'); |
| 546 | }); |
| 547 |
| 548 | test('haptics from a timer with no touch: one second of them, then nothing (the widget cannot buzz the phone)', async ({ page }) => { |
| 549 | const f = await openAttack(page, 'haptic-timer-buzz.html'); |
| 550 | await page.waitForTimeout(3000); |
| 551 | const s = await twState(page); |
| 552 | const played = s.actions.filter((a) => a.kind === 'haptic').length; |
| 553 | // One series: the first second, under the rate limit (a burst of 5, then 10 per second); the widget asked far more. |
| 554 | expect(played).toBeGreaterThan(0); |
| 555 | expect(played).toBeLessThanOrEqual(5 + 10 + 1); |
| 556 | expect(Number(await f.locator('#n').textContent())).toBeGreaterThan(played * 3); |
| 557 | expect(s.diags['haptic-limit']?.count).toBeGreaterThan(0); |
| 558 | }); |
| 559 |
| 560 | test('a rAF loop burning 30 ms per frame is throttled and frames collapse', async ({ page }) => { |
| 561 | const f = await openAttack(page, 'cpu-raf-burn.html'); |
| 562 | await page.waitForTimeout(3000); |
| 563 | const s = await twState(page); |
| 564 | expect(s.dead).toBeNull(); |
| 565 | expect(s.diags['cpu-throttled']?.count).toBeGreaterThan(0); |
| 566 | const frames = Number(await f.locator('#frames').textContent()); |
| 567 | // 60 Hz would give ~180 frames in 3 s; at 300 ms/s and 30 ms a frame at most ~10 per second. |
| 568 | expect(frames).toBeGreaterThan(3); |
| 569 | expect(frames).toBeLessThan(45); |
| 570 | expect(s.diags['cpu-throttled'].details[0]).toMatch(/deferred \d+ frames?/); |
| 571 | }); |
| 572 |
| 573 | test('cpuKillAfterMs terminates a sustained hog and keeps its last render', async ({ page }) => { |
| 574 | const f = await openAttack(page, 'cpu-kill-after.html', '&cpuKillAfterMs=2000'); |
| 575 | await page.waitForFunction(() => (window as any).__tw.state.dead, null, { timeout: 15_000 }); |
| 576 | const s = await twState(page); |
| 577 | expect(s.dead).toMatch(/^CPU quota: throttled for \d+\.\d s/); |
| 578 | expect(s.diags['cpu-throttled']?.count).toBeGreaterThan(0); |
| 579 | await expect(f.locator('#keep')).toHaveText('Price alert: BTC 61 240 USD'); |
| 580 | await expect(f.locator('html')).toHaveAttribute('data-tw-frozen', 'fatal'); |
| 581 | expect(Number(await f.locator('#ticks').textContent())).toBeGreaterThan(0); |
| 582 | }); |
| 583 | }); |
| 584 |
| 585 | for (const file of files) { |
| 586 | test(`attack ${file} leaks nothing`, async ({ page }) => { |
| 587 | await resetCanary(); |
| 588 | const outside = watchRequests(page); |
| 589 | const consoleErrors: string[] = []; |
| 590 | page.on('pageerror', (e) => consoleErrors.push(String(e))); |
| 591 |
| 592 | await page.goto(`/?file=attacks/${file}${RENDERER_PARAM}`); |
| 593 | await page.waitForFunction(() => (window as any).__tw?.state && ((window as any).__tw.state.loaded || (window as any).__tw.state.dead), null, { timeout: 60_000 }); |
| 594 | // Give timers, rAF callbacks and deferred mutations time to fire. |
| 595 | await page.waitForTimeout(1500); |
| 596 | // Poke the widget: click into it and press a key, in case a vector needs user activation. |
| 597 | const frame = page.locator(RENDERER_SEL); |
| 598 | await frame.click({ position: { x: 20, y: 10 }, force: true }).catch(() => {}); |
| 599 | await page.keyboard.press('Enter').catch(() => {}); |
| 600 | await page.waitForTimeout(700); |
| 601 |
| 602 | const state = await page.evaluate(() => { |
| 603 | const s = (window as any).__tw.state; |
| 604 | return { dead: s.dead, diags: Object.keys(s.diags), logs: s.logs.slice(0, 5) }; |
| 605 | }); |
| 606 | const hits = await canaryHits(); |
| 607 | expect(hits, `canary hits for ${file}: ${JSON.stringify(hits)}`).toHaveLength(0); |
| 608 | expect(outside, `requests outside app origin for ${file} (state ${JSON.stringify(state)})`).toHaveLength(0); |
| 609 | expect(consoleErrors.filter((e) => /SecurityError|not allowed/.test(e) ? false : true)).toHaveLength(0); |
| 610 | }); |
| 611 | } |
| 612 |