Files
orca/config/scripts/mobile-web-app-preview-frame-readings.mjs
T
Jinwoo Hong e47ef8cc28 feat(mobile): the shell tells a page which optional capabilities it has (OTA phase D, C8.1) (#22141)
* fix(mobile): publish page-route pairs the strict host schema accepts (OTA phase D, C8.1)

`routeViewOf` handed the manifest's own route entries to the host as
`pageRouteGrants`. The phone reads a manifest route loosely, so an entry
arrives carrying whatever field the desktop that wrote it knew about, and
`BridgePageRouteGrantsSchema` is `.strict()`: one unread key refuses the
pairs, `createBridgeHost` refuses the route with them, and the page gets no
`init` at all rather than losing one field.

Fixed before any route carries an optional grant (ruling 37.4), so the
manifest field the next commits add costs an installed shell nothing.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* chore: drop the closure and bundle probe scripts from the tree

Scratch measurements for C8.1 (which route closures reach the HTML preview,
and what the preview render rig costs to bundle with a client provider). They
belong outside the repository and were swept in by the previous commit's
`git add -A`.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* feat(mobile): a manifest route may declare optional grants (OTA phase D, C8.1)

Design B of design-ota-c8-1.md, ruling 37. `MobileWebBundleRouteSchema` grows
`optionalGrants` under the required lane's own grammar, with the 16-name
ceiling applied over the union of the two lists rather than to each. Serving a
route still reads `grants` alone, so a capability a screen cannot work without
stays required and takes the route native; a session's granted list is
`[...grants, ...optionalGrants]` narrowed to what this shell implements, from
one helper that both `grantsForRoute` and the `pageRouteGrants` publish read.

The ruling's compatibility rationale is corrected in place. `z.looseObject`
passes unknown members through rather than dropping them (measured, zod
4.4.3), so a shell older than the field still receives the key; what it lacks
is a policy that reads one. What makes the lane safe against such a shell is
therefore the previous commit's publish fix, not the reader.

BRIDGE_PROTOCOL_VERSION stays 1. No new notify, verb or frame field.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* feat(mobile): name the shell's cancelled-navigation behaviour as a grant (OTA phase D, C8.1)

`externalNavigation` joins `MOBILE_WEB_SHELL_GRANTS` beside `screencastBinary`
and `haptics`, declared in `cancelled-navigation-target.ts` because that is
the module holding the rule which acts on it. A third token that is neither a
verb nor a notify: the page posts nothing to make a cancelled top-frame
navigation happen, so this list is the only thing that can tell a page whether
a tap inside the sealed HTML-preview frame escapes at all.

A constant and not a platform read (ruling 37.1): both engines dispatch the
event, `ios/MobileWebShellView.swift:481` and Android's
`MobileWebShellView.kt:382`, so an app build carries the behaviour on both or
on neither.

The policy census grows the half that was only pinned by the verb table: the
implemented set is that table plus exactly three non-verb tokens, each read
off the module that declares it.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* feat(mobile): the bundle builder carries a route's optional grants (OTA phase D, C8.1)

`resolveMobileWebPageRoutes` maps each declaration member by member, so a
field the declaration grows reaches a phone only once the map names it: until
now `optionalGrants` would have been dropped in silence and every route would
have declared nothing optional. Omitted when the route declares none, because
absent and empty are the same answer to a shell.

The declaration suite grows the rule rather than a row: the map carries the
lane through and writes no key without one, and the lane is held to the
manifest's own grammar and to the ceiling over the union of the two lists.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* feat(mobile): the HTML preview hides its links on a shell that cannot open one (OTA phase D, C8.1)

The session route declares `externalNavigation` on the optional lane, and the
preview asks for it before it renders an artifact's links as links. Ruling
37.2's three readings are what "hide" means here, and removing `href` is what
delivers all three at once: `a:any-link` stops matching, so the UA stylesheet
stops underlining, the element leaves the tab order, and there is no dead
anchor a tap does nothing on. The text the author wrote stays where it was,
the artifact paints, and the Preview/Source toggle is untouched.

Done with the browser's own parser rather than over the source text: an `href`
inside a comment or a `<template>` is text to a browser, and a pass that
rewrote either would be editing the artifact instead of its links. The frame
also loses `allow-top-navigation-by-user-activation` on that path, so a link
the pass somehow missed is refused by the browsing context as well.

One route, measured rather than assumed: the design said two, and the file
preview route's closure does not reach the HTML preview at all - it renders
`MobileFilePreviewScreen`. The new closure census derives that list from the
hook's callers.

The render rig grows the case on both engines and the readings it needs, and
`mobile-web-app-preview-frame-readings.mjs` is split out of it at the
readings/arms boundary, because the two were over the 600-line cap together.
Two engine findings are recorded in the rig: an `<a>` with no `href` still
answers `tabIndex` 0 on both, so focusability is asked by focusing; and WebKit
computes `cursor: auto` for a real link, so that reading is pinned where it
discriminates and its blindness pinned where it does not.

The hop-coverage census now reads the effective set, because that is what the
running rule compares. Inert today: the session route is the only declarer and
an opener into every other route.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): pin the preview's hidden link path where the unit suite can reach it (OTA phase D, C8.1)

The mobile suite runs in a `node` environment whose resolver has no `.web`
precedence, so `MobileHtmlPreview.web.tsx`'s import of the grant hook lands on
the native sibling, which answers yes unconditionally. That is why the
existing component suite still measured the granted frame without knowing a
grant exists, and it means the hidden path had no coverage in the sharded
`test` job, where the render rig is skipped for want of the bundler's
dependencies.

So the wiring gets its own file with the module replaced: that the component
asks, and that both the frame's sandbox and the document it is handed follow
the one answer. happy-dom rather than the suite default, because the inerting
pass parses with the browser's own `DOMParser`.

`String(node.type)` rather than a literal comparison: `node.type` is
`ElementType`, which overlaps a real intrinsic tag and not the host strings
these mocks render, so `=== 'Pressable'` is a no-overlap error under
`tsconfig.test.json` and the tests-typecheck ratchet reds on it.

Also replaces a `Reflect.get` the anti-slop gate refuses with an `in` check.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): repin the session page closure at 4,362 for C8.1's three modules

Measured on both sides with `mobileWebAppRouteClosure(SESSION_ROUTE)` at base
`841d06a969` with all five postinstall generators run first, and the two
`local` lists diffed rather than the total inferred: 4,359 -> 4,362 modules,
1,017 -> 1,020 local.

All three are local source modules and none is vendored: the page's read of
`init.grants.native`, the pass that turns an artifact's links back into text
without the grant, and the module declaring the token beside the rule that
acts on it - reached both by that hook and by `page-route-policy.ts`. The
`bridge-caps.ts` it imports was already in this closure, and the hook's native
sibling is replaced rather than joined.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): allowlist the preview's grant sibling among the .web.* overrides

`mobile-web-app-web-overrides.test.mjs` pins the allowlist against the `.web.*`
files on disk, so a new web sibling reds it until the file says why the page
needs one. Red before: `expected [ …(36) ] to deeply equal [ …(37) ]`, naming
`src/components/use-html-preview-link-grant.web.ts`.

The preview's own entry is corrected with it: its reason said
`allow-top-navigation-by-user-activation` is granted, and that token is now
conditional on the shell answering that it can open such a navigation.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* test(mobile): the hidden-link render case waits on the frame's own reading (round 1)

CI's chromium arm timed out at the full 240 s on this case alone while the
WebKit sibling passed in 1.5 s and it passed 26/26 locally. The cause is the
third arm: it tapped the granted link and waited through
`expectNavigation: 'main-frame'`, and `waitForRecordedNavigation` has no bound
but the case's own timeout. Under CI load the click missed its 2 s
actionability window, no navigation was ever recorded, and the arm sat in that
wait until vitest gave up - `recorded []`, with the frame attached only at
38.9 s. Three arms sharing one budget is what made this the case to find it.

The arm is dropped rather than its wait lengthened or retried. Every verdict
left is a reading the frame itself publishes: the anchors its document holds,
the style the engine computed for one, whether focus lands on it, and now
whether the tap this arm made landed at all - `actError` is asserted null, so
a click that never reached its target is no longer the same three zeros as a
tap that did nothing.

Nothing is lost. The tap's outcome on a granted shell is the next case, on
these same counters from this same rig and with a budget of its own, which is
the presence precondition this file already uses elsewhere for the same
reason. The WebKit sibling's discriminating reads are untouched.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* fix(mobile): the inert-link pass changes nothing an engine renders but the links (round 2)

Round 2's ruling: the hidden-link path may change nothing about the artifact's
rendering except that links are not links. A parse and a reserialise is not
free of that by default, and all four findings reproduced on Chromium 147 and
WebKit 26.4.

A same-document fragment link is kept. It starts no navigation at all, so it
goes on working inside the sealed frame whatever the shell can do, and taking
it away would be degradation over a capability it never needed - an artifact's
own table of contents is the case. Its `target` still goes, because a fragment
aimed at another frame is a navigation rather than a scroll, and `href=""` is
not a fragment: it resolves to the frame's own URL.

Links inside `template.content` are reached, recursively. `<template
shadowrootmode>` is a declarative shadow root the frame's parser attaches and
renders, and `querySelectorAll` does not walk into template content, so those
links arrived live inside a sandbox that refuses their navigation - the dead
anchor ruling 37.2 forbids. Measured: `parseFromString` attaches no such root
on either engine or in happy-dom, so the pass can reach them.

The leading newline of a `pre`, `listing` or `textarea` is written back. A
parser drops one after the start tag and the serialiser is specified to put it
back; measured, neither engine's does, so a round trip lost a blank line from
every such block.

The doctype is carried whole, and the reason is corrected from the one the
finding gave. It cannot move this frame between layout modes: a `srcdoc`
document takes its mode from its embedder, and measured, a quirks doctype, the
bare name and no doctype at all all read `CSS1Compat` inside the frame. What
rewriting it does is change the document the author wrote for no reason, with
`document.doctype` observable beside a Source tab showing the original. The
render case pins `compatMode` as the blind reading it is and reads the frame's
own doctype identifiers as the one that discriminates.

Option B was not available: the frame has no `allow-scripts` and inherits
`script-src 'self'`, so nothing runs inside it and there is no injection to
carry the work.

Also drops a vacuous half of the affordance test. `renderSource()` is called
with no argument, so the markup a Source view shows is the caller's own
closure and asserting it equals the fixture passed whatever the component did.
What the component decides is whether the rewritten frame stays mounted
underneath, and that is what is read now.

`mobile-web-app-preview-arm-driver.mjs` is split out of the render rig at the
boundary the readings module already names - the rig holds what each case
claims, the driver how an arm is driven, the readings what it reports - since
the three were over the 600-line cap together. No max-lines disable or bump.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb

* fix(mobile): a fragment link is a frame navigation in this preview, so it is inerted too (round 3)

pullfrog is right, reproduced on both engines before believing it. Round 2
kept `#`-prefixed hrefs on the theory that they are same-document scrolls. In
this frame they are not: the document's URL is `about:srcdoc` while its base
URL is inherited from the embedder, so `#section` resolves against the shell's
own URL and the destination differs from the document's by more than a
fragment - which makes activating it a frame navigation, and the shipped
`frame-src 'none'` refuses it.

Measured under the shipped policy, one tap, with something to scroll:

  Chromium 147   scrollY 0, frame becomes chrome-error://chromewebdata/,
                 artifact gone, embedder reports frame-src <origin>/preview
  WebKit 26.4    scrollY 0, frame stays about:srcdoc and intact, same report

So the destruction is Chromium-only but the absence of a scroll is not: there
was no working affordance to carve out for, and the carve-out left a live link
that destroys the preview - worse than the inert text it was meant to avoid.
Both sandbox values behave the same, so this is the base URL and the policy
rather than the sandbox.

The same tap does the same thing on the granted path, where this pass does not
run, so an artifact's internal links have never worked in the preview. That is
not this change's to fix; it is recorded in
`followup-html-preview-fragment-links.md`, and the render case reads the
granted arm's violation as its presence precondition so the behaviour is
pinned rather than merely known.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
2026-09-22 02:11:40 -04:00

211 lines
10 KiB
JavaScript

/**
* Everything one arm of the HTML-preview render rig can be asserted on, read off a settled page.
*
* Split from the rig for the reason `mobile-web-app-preview-frame-readiness.mjs` and
* `mobile-web-app-preview-csp-reports.mjs` were: the rig file holds how an arm is driven and what
* each case claims, and this holds what a driven arm reports. They grow for different reasons -- a
* case is added when a fence is added, a reading when a fence becomes measurable in a new way -- and
* together they were over the 600-line cap the moment C8.1's link readings landed.
*
* Every reading is taken after the arm has settled, and every one that reaches inside the frame
* falls back to null: the frame is an opaque origin, so an engine that refuses to evaluate in one
* reports absence rather than failing the arm. A case that depends on such a reading therefore pins
* a presence precondition beside it.
*/
import { PNG } from 'pngjs'
import { reportedDirectives } from './mobile-web-app-preview-csp-reports.mjs'
import { previewFrame } from './mobile-web-app-preview-frame-readiness.mjs'
/**
* One RGB triple from the page, clipped to where the frame sits.
*
* A pixel rather than a read inside the frame, because the frame is an opaque origin and the paint
* is the one claim that must hold on every engine.
*/
export async function probePreviewPixel(page, clip) {
const png = PNG.sync.read(await page.screenshot({ clip }))
return `${png.data[0]},${png.data[1]},${png.data[2]}`
}
/** What the toolbar emits into the DOM, not what the component was handed: react-native-web
* forwards `aria-*` and drops `accessibilityState` on the floor, so a selected state that reads
* fine in the test renderer can reach a screen reader as nothing at all. */
export async function readPreviewToggles(page) {
return await page
.evaluate(() =>
[...document.querySelectorAll('[role="tab"]')].map((one) => ({
label: one.getAttribute('aria-label'),
selected: one.getAttribute('aria-selected')
}))
)
.catch(() => null)
}
/** The element's own attributes and geometry, which is where "the artifact is parsed inside the
* frame rather than fetched into it" actually lives. Read from the element the component rendered
* and not from the constant it exports: a literal in the JSX would leave the constant correct and
* the frame unsealed, which is what the control run for this rig did before this reading existed. */
async function readFrameElement(page) {
return await page
.evaluate(() => {
const frame = document.querySelector('iframe')
if (!frame) {
return { sandbox: null, srcDoc: null, src: null, box: null }
}
const box = frame.getBoundingClientRect()
return {
sandbox: frame.getAttribute('sandbox'),
srcDoc: frame.getAttribute('srcdoc'),
src: frame.getAttribute('src'),
// Reported so a pixel that read the page instead of the frame names the layout rather than
// looking like a frame that refused to load.
box: { x: box.x, y: box.y, width: box.width, height: box.height }
}
})
.catch(() => ({ sandbox: null, srcDoc: null, src: null, box: null }))
}
/** The frame's own document: what the artifact rendered, whether its script ran, and the refusals
* the frame itself was told about. `securitypolicyviolation` does not cross frames, so the page's
* init script installs the same collector in every one. */
async function readInsideFrame(page) {
return await (previewFrame(page)
?.evaluate(() => ({
marker: document.getElementById('marker')?.textContent ?? null,
title: document.title,
// The two the hidden-link path could change without touching a link (C8.1 round 2). The
// rendering mode the engine resolved from the doctype it was handed, and the text a
// preformatted block holds -- both read off the frame's own document, because the claim is
// about what the engine parsed rather than about the string the page built.
compatMode: document.compatMode,
// The doctype the frame's own document reports, which is the reading that discriminates:
// `compatMode` cannot, because a `srcdoc` document takes its mode from its embedder.
doctypePublicId: document.doctype?.publicId ?? null,
doctypeSystemId: document.doctype?.systemId ?? null,
preText: document.getElementById('pre')?.textContent ?? null,
fragmentHref: document.getElementById('fraglink')?.getAttribute('href') ?? null,
// Where the frame is aimed and where it has scrolled to, which is how a tap on a fragment is
// told apart from a same-document scroll: inside this frame the base URL is the embedder's,
// so a fragment resolves off-document and activating it navigates rather than scrolls.
baseUri: document.baseURI,
scrollY: Math.round(window.scrollY),
ran: document.documentElement.dataset.ran === '1' ? 1 : 0,
threw: document.documentElement.dataset.threw ?? null,
// The two moments the late-listener question turns on: when the page's init script ran in
// this frame, and when the artifact's own script did.
initAt: window.__initAt ?? null,
artifactAt: document.documentElement.dataset.artifactAt ?? null,
violations: window.__violations ?? null
}))
.catch(() => null) ?? Promise.resolve(null))
}
/**
* Whether the artifact's links are links, as a browser resolves them (C8.1, ruling 37.2).
*
* Three readings rather than one, because the ruling names three: no underline, no pointer cursor,
* no anchor a tap does nothing on. The first two are the UA stylesheet's `a:any-link` rules
* resolving, which is a computed style and cannot be read off the markup; the third is the markup.
* `#toplink` is the fixture's own link and the one every tapping arm taps.
*
* `focusable` is asked by focusing, not by reading `tabIndex`: measured on Chromium 152 and WebKit,
* an `<a>` with no `href` still answers `tabIndex` 0, so that property says nothing about the tab
* order. It is the last reading taken, because it is the one that changes the document.
*/
async function readFrameLinks(page) {
return await (previewFrame(page)
?.evaluate(() => {
const first = document.getElementById('toplink')
const style = first === null ? null : getComputedStyle(first)
const reading = {
linked: document.querySelectorAll('a[href], area[href]').length,
// Every anchor the fixture wrote, link or not: the text has to still be there, because
// hiding an affordance is not deleting what the author wrote.
anchors: document.querySelectorAll('a').length,
text: first?.textContent ?? null,
decoration: style?.textDecorationLine ?? null,
cursor: style?.cursor ?? null,
focusable: null
}
if (first !== null) {
first.focus()
reading.focusable = document.activeElement === first
}
return reading
})
.catch(() => null) ?? Promise.resolve(null))
}
/**
* The whole reading for one arm.
*
* `arm` carries what the rig already knows and cannot read back off the page: the counters it
* subscribed for, the policy the response actually carried, and the error an action reported.
*/
export async function readPreviewArm({
page,
clip,
pixelBefore,
togglesBefore,
servedCsp,
actError,
navigations,
popups,
foreignHits,
readImageHits,
assetServer,
cspReports,
nonce
}) {
const element = await readFrameElement(page)
return {
page,
pixelBefore,
pixel: await probePreviewPixel(page, clip),
declaredSandbox: await page.evaluate(() => window.__sandbox),
togglesBefore,
toggles: await readPreviewToggles(page),
mountedSandbox: element.sandbox,
mountedSrcDoc: element.srcDoc,
mountedSrc: element.src,
frameBox: element.box,
frameCount: page.frames().length - 1,
// Reported, never asserted on: a `srcdoc` frame's URL reads `about:srcdoc` on one engine and
// empty on CI's browser, so nothing may be decided by it.
frameUrl: previewFrame(page)?.url() ?? null,
// What the shell told the page, read back off the document so an arm cannot assert against a
// grant list it only believes it passed.
grants: await page.evaluate(() => window.__grants ?? null),
links: await readFrameLinks(page),
inside: await readInsideFrame(page),
// What this document was actually served, so "the shipped policy, plus a report endpoint and
// nothing else" is asserted rather than intended.
servedCsp,
// Every refusal the browser reported for this arm, which is the evidence an in-frame listener
// cannot be relied on to have collected.
reported: reportedDirectives(cspReports, nonce),
// Null on every arm that acted successfully, and on every arm that did not act at all.
actError,
topNavigations: navigations.filter((one) => one.main && one.foreign).length,
ownOriginTopNavigations: navigations.filter((one) => one.main && !one.foreign).length,
// What the frame asked for itself at the embedder's origin, which is a different escape from a
// top-frame request and is refused by a different line of the policy.
ownOriginFrameNavigations: navigations.filter((one) => !one.main && !one.foreign).length,
popups: popups.length,
// This arm's fetches only, by nonce: the paths, with the nonce stripped, so a case reads the
// subresource rather than the bookkeeping.
foreignHits: foreignHits
.filter((one) => one.includes(`n=${nonce}`))
.map((one) => one.split('?')[0]),
// Same shape as `foreignHits` and read the same way: this arm's requests only, by nonce, as
// paths. Absolute URLs go in, so the origin is stripped along with the query.
secureHits: readImageHits(),
// What each admitted request carried, this arm's only, so an absence is this artifact's. Read
// off the header the listener received rather than off a request object handed to a route: the
// header on the wire is what the shell's `Referrer-Policy` is about.
secureReferers: assetServer.referersFor(nonce),
violations: await page.evaluate(() => window.__violations),
body: await page.evaluate(() => document.body.innerText)
}
}