Files
orca/mobile/modules/orca-mobile-web-shell/tests/MobileWebShellChecks.swift
Jinwoo Hong 381a3da46f feat(build): Route A, the phone's host routes bundled for the web, dark (OTA phase C, C0.7) (#21449)
* refactor(mobile-web): share the bundle manifest assembly with a second builder

Manifest assembly and the on-disk write move to writeMobileWebBundleTree, and
the helpers the Phase C app builder needs become exports. No behaviour change
to the shipped bootstrap bundle.

The CRLF guard grows two exemptions it needs once it is pointed at mobile/src:
the image and font extensions .gitattributes already pins -text, and the
gitignored webview engine modules the postinstall writes.

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

* feat(mobile): web entry for the host route tree, and its two transport siblings

The entry mounts app/h on react-native-web through expo-router's own ExpoRoot.
It lives inside mobile/ so one React resolves, and supplies RpcClientProvider
itself: the route tree starts below the native root layout that owns it.

route-manifest.ts is a real typed module whose body the builder replaces --
esbuild has no require.context. A virtual specifier would need an ambient
declaration and would leave the entry unchecked.

Two .web.* siblings, both listed with a reason in web-overrides.json: the
transport substitution point (a placeholder client until C0.4 lands
BridgeRpcClient) and the device token store, whose native path imports
expo-secure-store, which is {} on web.

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

* feat(build): build:mobile-web:app, the phone's host routes bundled for the web

Same builder shape as the Phase A bootstrap into a separate out/mobile-web-app,
with the same manifest and the same two-scratch-build determinism check. Dark:
build:mobile-web, packaging and the A2 census are untouched, and C1 is what
flips build:release.

Six shims, each a named Metro or RN Web gap. Images are emitted as same-origin
hashed assets rather than data: URLs, because the shell's CSP sets img-src
'self'; the render check under that exact header is what found it. The script is
referenced root-absolute for the same reason a <base> tag cannot be used: the
document is served at every route depth and base-uri is 'none'.

The budget sits below the contract's per-asset ceiling so growth trips a build
rather than a refused asset on a phone. esbuild splitting does not lower it:
one entry with only static imports emits one chunk (measured).

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

* fix(mobile): let React Native Web paint under the shell CSP

RN Web 0.21.2 injects its stylesheet at runtime with no nonce support, so
style-src 'self' blocks every rule and the page renders unstyled. Measured, not
predicted: the render check serves the document under this exact header and
reported the violation.

'unsafe-inline' is granted to style-src and nothing else. script-src 'self'
holds, which is the directive that decides whether page code can arrive any way
other than as a fetched same-origin script. The test now pins that scoping
rather than rejecting the token everywhere.

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

* ci: prove the Route A app bundle on every PR

A dedicated job, for the same reason the browser provider has one: it needs
mobile/node_modules and a real browser, and the sharded test matrix would pay
for both on every shard. It builds the bundle, verifies it, and runs the
builder, override-census and render suites. It ships nothing.

The mobile_web_app signal is lifted out of should_run the way static_analysis
is. A mobile-only diff is desktop-irrelevant and skips every gated job, and
that is exactly the diff that changes the page this job builds.

Also the C0.6 review follow-up: mobile/package.json and mobile/pnpm-lock.yaml
join the installer cache keys in the two workflows that build an installer off
a hashFiles key, since beforePack requires out/mobile-web and a mobile-only
change must miss those caches rather than reuse a stale build.

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

* test(build): pin the shipped builder against the app builder's own module name

The assertion named a specifier that no longer exists, so it held vacuously.

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

* test(mobile): assert the RN Web style-src grant in the Swift checks

The Swift twin of the Kotlin CSP test still required style-src 'self' and
no unsafe-inline anywhere, so it trapped on the approved grant.

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

* test(build): make the Route A render check name what each route paints

The check asserted only "some html, no errors", which expo-router's Unmatched
screen satisfies: pointing HOST_ROUTE at /zzz/not-a-real-prefix stayed green.
Each route now asserts content only its own component produces, and the
unmatched case asserts the screen positively so the negatives discriminate.

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

* test(build): read the shell CSP past the comments that quote directives

Both constants document themselves with // comments containing quoted
directive text, which the quoted-string scan picked up as directives. One
parser now drops comment lines, and iOS and Android go through it.

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

* feat(build): honour a .web.* route sibling in the app bundle

Routes were imported by absolute path with the extension, so esbuild's
resolveExtensions never applied and a .web.tsx under app/ was dead code the
census still accepted. The manifest now carries a key and a module: the key
stays the native filename so the URL does not move, and the module is the web
sibling when one exists.

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

* test(build): tie each named shim to the esbuild option that implements it

The shim list was asserted against a literal copy of itself, which passes
however the build is configured. Each entry now carries an appliesTo that
reads its own option, checked against the real options object.

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

* chore(build): line up the CRLF exemptions, the budget comment, and the job scope

The builder loads .gif as a file but neither .gitattributes nor the CRLF scan
exempted it, so the blanket eol=lf pin would have rewritten one. A test now
keeps the two lists in step. The Phase C byte budget's comment sat on the
asset count, and a root package.json edit could change build:mobile-web:app
without running the job that proves it.

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

* style(build): satisfy the index-check lint rule in the CSP parser

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

* ci: key the installer caches on the mobile page trees too

beforePack builds the mobile web bundle into the installer. Today those bytes
are Phase A's, which src/** already covers, but once C1 flips the entry to
mobile/app a page-only change would hit a cache holding a stale installer.

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

* test(build): skip the bundling tests where mobile dependencies are absent

The sharded `test` job collects config/scripts/**/*.test.mjs and installs no
mobile dependencies, so the two new suites failed there on "Could not resolve
react-native-web". They now skip themselves with a message naming the job that
runs them, and that job sets ORCA_MOBILE_WEB_APP_DEPS_REQUIRED so a missing
install fails it instead of skipping everything it exists to prove.

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

* fix(build): scan mobile/packages in the .web.* census

The census claimed the app entry never resolves into packages/, but the
dictation hook imports @orca/expo-two-way-audio and the built script carries
ExpoTwoWayAudioModule.web.ts. That file is now listed with its reason, and
planting a .web.* in each scanned tree proves the scan is not passing because
a tree happens to be empty.

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

* test(build): assert the route exclusions against a tree that has them

mobile/app holds no test, spec or +api file, so the exclusion rule was
asserted against a tree it could not fire on. A scratch tree plants one of
each; dropping the rule now fails this test.

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

* test(build): 404 unknown file paths in the render check's page server

The server answered every path with the document, so pointing publicPath at
/wrong-prefix still rendered three green routes: the script is fetched from
the one prefix that is served. A path naming a file now has to come out of the
bundle, which is what the shell's manifest map does.

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

* test(build): cover the app bundle verifier's own checks

The verifier had no test. One doctors the buildId, which the packaged assert
catches; the other rewrites the tree so every digest still agrees and only the
two fresh builds can tell, which is what a stale out/ looks like. Deleting
either check now fails a test.

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

* chore(build): tidy the app bundle comments and the job's path prefixes

Drops an export nothing read, merges two comments that had drifted apart from
the constant they describe, and corrects the claim that the job runs on every
PR when it is path-gated. package.json leaves the prefix list because
GLOBAL_FORCE_FILES already forces every job on it; mobile/packages/ joins it,
since the page resolves a .web.ts out of there.

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

* style(build): merge the duplicate node:fs/promises import in the census

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

* fix(mobile): redirect the hybrid shell route on the web page

app/h/[hostId]/web.tsx reaches OrcaMobileWebShellView, whose module calls
requireNativeViewManager at import. In a browser that throws before React
mounts, and the route manifest imports every route statically, so one native
route left the whole page blank at every URL.

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

* test(build): fail the render check with the error that stopped the mount

The check waited on "#root has children" with Playwright's animation-frame
polling, so a route module that threw at import read as a bare 30s timeout
naming nothing. It now waits on a mount attribute the entry sets after the
router commits, polls on a timer, and races the wait against the first
uncaught error so the failure carries it.

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

* test(build): answer the favicon the render browser asks for

CI resolves the runner's Google Chrome, which requests /favicon.ico; the
bundled headless shell does not. The bundle carries no icon, so the server
answers 204 rather than turning a browser habit into a console error the
render assertions read as a page fault.

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

* test(build): settle the render check's uncaught-error race without rejecting

The entry throws during goto, before anything awaits the race, so a rejected
promise surfaced as an unhandled rejection beside the real failure. The same
signal now resolves with the error.

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

* chore(mobile): list the page transport in the raw request port inventory

The placeholder client implements the port, so the boundary test counts it as
an unlisted file. It belongs under OWNERS until C0.4's BridgeRpcClient
replaces it.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
2026-09-18 09:50:37 -04:00

507 lines
24 KiB
Swift

import Foundation
// Everything the shell decides before WebKit is involved: the session id it will accept, the
// requests it will answer, the map it builds from a manifest, and the policy header. Compiled and
// run without a device:
//
// swiftc -O -o /tmp/mobile-web-shell-checks \
// ios/MobileWebShellOrigin.swift ios/MobileWebShellGeneration.swift ios/MobileWebShellCsp.swift \
// ios/MobileWebShellLoadState.swift ios/MobileWebShellResponseHeaders.swift \
// ios/MobileWebShellBridge.swift ios/MobileWebShellAppliedProps.swift \
// tests/MobileWebShellChecks.swift && /tmp/mobile-web-shell-checks
@main struct MobileWebShellChecks {
static let session = "sess-01JN_aZ9"
static func parts(
path: String,
method: String = "GET",
hasRangeHeader: Bool = false,
scheme: String? = MobileWebShellOrigin.scheme,
host: String? = session,
port: Int? = nil,
user: String? = nil,
query: String? = nil,
fragment: String? = nil,
urlByteCount: Int = 64
) -> MobileWebShellRequestParts {
MobileWebShellRequestParts(
method: method,
hasRangeHeader: hasRangeHeader,
scheme: scheme,
host: host,
port: port,
user: user,
query: query,
fragment: fragment,
percentEncodedPath: path,
urlByteCount: urlByteCount
)
}
static func resolve(_ request: MobileWebShellRequestParts) -> String? {
MobileWebShellOrigin.resolveRequestPath(request, sessionId: session)
}
static func manifest(
schemaVersion: Int = 1,
entrypoint: String = "index.html",
assets: [[String: Any]] = [
["path": "index.html", "contentType": "text/html; charset=utf-8"],
["path": "assets/aa.js", "contentType": "text/javascript; charset=utf-8"],
["path": "assets/bb.png", "contentType": "image/png"]
]
) -> Data {
let root: [String: Any] = [
"schemaVersion": schemaVersion,
"entrypoint": entrypoint,
"assets": assets
]
return try! JSONSerialization.data(withJSONObject: root)
}
static func generation(_ data: Data) -> MobileWebShellGeneration? {
try? MobileWebShellGeneration.make(
manifestData: data,
directory: URL(fileURLWithPath: "/tmp/generation", isDirectory: true)
)
}
static func checkSessionIds() {
precondition(MobileWebShellOrigin.isValidSessionId("aZ0-_"))
precondition(MobileWebShellOrigin.isValidSessionId(String(repeating: "a", count: 128)))
precondition(!MobileWebShellOrigin.isValidSessionId(String(repeating: "a", count: 129)))
precondition(!MobileWebShellOrigin.isValidSessionId(""))
precondition(!MobileWebShellOrigin.isValidSessionId("has space"))
precondition(!MobileWebShellOrigin.isValidSessionId("dots.are.hosts.too"))
precondition(!MobileWebShellOrigin.isValidSessionId("sl/ash"))
// Non-ASCII letters and digits satisfy Character.isLetter/isNumber, so the ASCII gate is load
// bearing: an IDNA-mapped host would not be the origin we minted.
precondition(!MobileWebShellOrigin.isValidSessionId("sessioñ"))
precondition(!MobileWebShellOrigin.isValidSessionId("session٣"))
precondition(MobileWebShellOrigin.documentUrl(sessionId: session)?.absoluteString ==
"orca-mobile-web://\(session)/")
precondition(MobileWebShellOrigin.documentUrl(sessionId: "bad host") == nil)
}
static func checkRequestResolution() {
precondition(resolve(parts(path: "/")) == "/")
precondition(resolve(parts(path: "")) == "/")
precondition(resolve(parts(path: "/assets/aa.js")) == "/assets/aa.js")
// A host a parser canonicalised must still bind to this session.
precondition(resolve(parts(path: "/", host: session.uppercased())) == "/")
precondition(resolve(parts(path: "/", method: "POST")) == nil)
precondition(resolve(parts(path: "/", method: "HEAD")) == nil)
precondition(resolve(parts(path: "/", hasRangeHeader: true)) == nil)
precondition(resolve(parts(path: "/", scheme: "https")) == nil)
precondition(resolve(parts(path: "/", scheme: nil)) == nil)
// The same ASCII-only fold as the bridge: a Kelvin-sign host is a host nobody minted, and a
// caseInsensitiveCompare here would serve it every asset.
precondition(MobileWebShellOrigin.resolveRequestPath(
parts(path: "/", host: "\u{212A}ey"),
sessionId: "key"
) == nil)
precondition(MobileWebShellOrigin.resolveRequestPath(
parts(path: "/", host: "KEY"),
sessionId: "key"
) == "/")
precondition(resolve(parts(path: "/", host: "other-session")) == nil)
precondition(resolve(parts(path: "/", host: nil)) == nil)
precondition(resolve(parts(path: "/", port: 443)) == nil)
precondition(resolve(parts(path: "/", user: "someone")) == nil)
precondition(resolve(parts(path: "/", query: "v=1")) == nil)
precondition(resolve(parts(path: "/", fragment: "frag")) == nil)
precondition(resolve(parts(path: "/assets/%2e%2e/etc")) == nil)
precondition(resolve(parts(path: "assets/aa.js")) == nil)
precondition(resolve(parts(path: "/", urlByteCount: 8 * 1024)) == "/")
precondition(resolve(parts(path: "/", urlByteCount: 8 * 1024 + 1)) == nil)
precondition(MobileWebShellOrigin.resolveRequestPath(parts(path: "/"), sessionId: "") == nil)
}
static func checkAssetPaths() {
precondition(MobileWebShellGeneration.isServableAssetPath("index.html"))
precondition(MobileWebShellGeneration.isServableAssetPath("assets/a-b_c.2.js"))
precondition(!MobileWebShellGeneration.isServableAssetPath(""))
precondition(!MobileWebShellGeneration.isServableAssetPath("/leading"))
precondition(!MobileWebShellGeneration.isServableAssetPath("trailing/"))
precondition(!MobileWebShellGeneration.isServableAssetPath("a//b"))
precondition(!MobileWebShellGeneration.isServableAssetPath("../secret"))
precondition(!MobileWebShellGeneration.isServableAssetPath("assets/../../secret"))
precondition(!MobileWebShellGeneration.isServableAssetPath("assets/./a.js"))
precondition(!MobileWebShellGeneration.isServableAssetPath("back\\slash"))
precondition(!MobileWebShellGeneration.isServableAssetPath("has space.js"))
precondition(MobileWebShellGeneration.isServableAssetPath(String(repeating: "a", count: 255)))
precondition(!MobileWebShellGeneration.isServableAssetPath(String(repeating: "a", count: 256)))
}
static func checkContentTypes() {
precondition(MobileWebShellGeneration.isServableContentType("image/png"))
precondition(MobileWebShellGeneration.isServableContentType("text/html; charset=utf-8"))
precondition(MobileWebShellGeneration.isServableContentType("application/manifest+json"))
precondition(!MobileWebShellGeneration.isServableContentType(""))
precondition(!MobileWebShellGeneration.isServableContentType("text/html"
+ "\r\nX-Injected: 1"))
precondition(!MobileWebShellGeneration.isServableContentType("text/html; charset=utf-8; x=1"))
precondition(!MobileWebShellGeneration.isServableContentType("TEXT/HTML"))
// A header value we did not mint character for character is a value we did not check.
precondition(!MobileWebShellGeneration.isServableContentType("text/html; charset=UTF-8"))
precondition(!MobileWebShellGeneration.isServableContentType("text"))
precondition(!MobileWebShellGeneration.isServableContentType("text/html/extra"))
precondition(!MobileWebShellGeneration.isServableContentType("/html"))
precondition(!MobileWebShellGeneration.isServableContentType("-text/html"))
precondition(!MobileWebShellGeneration.isServableContentType("text/html; charset="))
precondition(!MobileWebShellGeneration.isServableContentType(
String(repeating: "a", count: 130) + "/b"))
}
static func checkGenerationMap() {
guard let built = generation(manifest()) else { preconditionFailure("manifest rejected") }
precondition(built.entries.count == 4)
precondition(built.entries["/"]?.file.path == "/tmp/generation/index.html")
precondition(built.entries["/"]?.contentType == "text/html; charset=utf-8")
// Only "/" reaches the document: a second URL for the same bytes would answer without the CSP
// header, which rides the document response alone.
precondition(built.entries["/index.html"] == nil)
precondition(built.entries["/assets/aa.js"]?.contentType == "text/javascript; charset=utf-8")
precondition(built.entries["/assets/bb.png"]?.file.path == "/tmp/generation/assets/bb.png")
precondition(built.entries["/manifest.json"]?.contentType == "application/json")
precondition(built.entries["/assets/cc.js"] == nil)
precondition(built.entries["/../secret"] == nil)
precondition(generation(manifest(schemaVersion: 2)) == nil)
precondition(generation(manifest(entrypoint: "start.html")) == nil)
precondition(generation(manifest(assets: [])) == nil)
// The entrypoint must be one of the assets, or "/" would map to a file nobody declared.
precondition(generation(manifest(assets: [
["path": "assets/aa.js", "contentType": "text/javascript; charset=utf-8"]
])) == nil)
precondition(generation(manifest(assets: [
["path": "index.html", "contentType": "text/html; charset=utf-8"],
["path": "../escape.js", "contentType": "text/javascript; charset=utf-8"]
])) == nil)
precondition(generation(manifest(assets: [
["path": "index.html", "contentType": "text/html; charset=utf-8"],
["path": "assets/aa.js", "contentType": "text/javascript\r\nX-Injected: 1"]
])) == nil)
precondition(generation(manifest(assets: [
["path": "index.html", "contentType": "text/html; charset=utf-8"],
["path": 7, "contentType": "text/javascript; charset=utf-8"]
])) == nil)
let tooMany = (0..<257).map { index in
["path": "assets/a\(index).js", "contentType": "text/javascript; charset=utf-8"]
}
precondition(generation(manifest(assets: tooMany)) == nil)
// A JSON string is not a JSON number, and true and 1.0 are not the integer 1, though NSNumber
// bridges all three to something `as? Int` accepts.
precondition(generation(Data(#"{"schemaVersion":true,"entrypoint":"index.html","assets":[{"path":"index.html","contentType":"text/html"}]}"#.utf8)) == nil)
precondition(generation(Data(#"{"schemaVersion":1.0,"entrypoint":"index.html","assets":[{"path":"index.html","contentType":"text/html"}]}"#.utf8)) == nil)
precondition(generation(Data(#"{"schemaVersion":1,"entrypoint":"index.html","assets":[{"path":"index.html","contentType":"text/html"}]}"#.utf8)) != nil)
precondition(generation(Data(#"{"schemaVersion":"1","entrypoint":"index.html","assets":[{"path":"index.html","contentType":"text/html"}]}"#.utf8)) == nil)
precondition(generation(Data("not json".utf8)) == nil)
precondition(generation(Data("[]".utf8)) == nil)
}
static func checkCsp() {
let header = MobileWebShellCsp.header
let directives = header.components(separatedBy: "; ")
precondition(directives.contains("default-src 'none'"))
precondition(directives.contains("script-src 'self'"))
// React Native Web injects runtime styles with no nonce; see MobileWebShellCsp.
precondition(directives.contains("style-src 'self' 'unsafe-inline'"))
precondition(directives.contains("connect-src 'self'"))
precondition(directives.contains("worker-src 'none'"))
precondition(directives.contains("frame-src 'none'"))
precondition(directives.contains("base-uri 'none'"))
precondition(directives.contains("form-action 'none'"))
precondition(directives.contains("frame-ancestors 'none'"))
// 'unsafe-inline' is granted to style-src and to nothing else: the page's code still has to
// arrive as a fetched same-origin script, which is the directive that matters.
precondition(directives.filter { $0.contains("unsafe-inline") } == ["style-src 'self' 'unsafe-inline'"])
precondition(!header.contains("unsafe-eval"))
precondition(!header.contains("data:"))
precondition(!header.contains("blob:"))
precondition(!header.contains("\r") && !header.contains("\n"))
}
static func checkLoadStateMachine() {
precondition(MobileWebShellFailureReason.generationUnreadable.rawValue == "generation-unreadable")
precondition(MobileWebShellFailureReason.isolationUnavailable.rawValue == "isolation-unavailable")
precondition(MobileWebShellFailureReason.documentLoadFailed.rawValue == "document-load-failed")
precondition(MobileWebShellFailureReason.renderProcessGone.rawValue == "render-process-gone")
let progress = MobileWebShellLoadStateMachine()
precondition(progress.started()?.state == "loading")
precondition(progress.started() == nil)
precondition(progress.finished()?.state == "ready")
precondition(progress.finished() == nil)
// A rule list compiles asynchronously, so it can fail after the generation was already refused.
let refused = MobileWebShellLoadStateMachine()
precondition(refused.failed(.generationUnreadable)?.reason == "generation-unreadable")
precondition(refused.failed(.isolationUnavailable) == nil)
precondition(refused.failed(.renderProcessGone) == nil)
precondition(refused.finished() == nil)
precondition(refused.started() == nil)
refused.reset()
precondition(refused.failed(.generationUnreadable)?.reason == "generation-unreadable")
// A document is heard only between its own commit and the end of that load.
let arming = MobileWebShellLoadStateMachine()
precondition(!arming.hasCommittedDocument)
_ = arming.started()
// The previous document is alive and same-origin until the next one commits.
precondition(!arming.hasCommittedDocument)
arming.committed()
precondition(arming.hasCommittedDocument)
// A new prop triple: the committed document is the one being replaced.
arming.reset()
precondition(!arming.hasCommittedDocument)
arming.committed()
arming.documentEnded()
precondition(!arming.hasCommittedDocument)
// A failure ends the document, and nothing after it re-arms: a retry is a remount.
arming.committed()
_ = arming.failed(.renderProcessGone)
precondition(!arming.hasCommittedDocument)
arming.committed()
precondition(!arming.hasCommittedDocument)
}
static func checkResponseHeaders() {
let document = MobileWebShellResponseHeaders.forPath(
"/",
contentType: "text/html; charset=utf-8",
byteCount: 12
)
precondition(document["Content-Security-Policy"] == MobileWebShellCsp.header)
precondition(document["Content-Type"] == "text/html; charset=utf-8")
precondition(document["Content-Length"] == "12")
precondition(document["Cache-Control"] == "no-store")
precondition(document["X-Content-Type-Options"] == "nosniff")
// The policy rides the document alone; on a subresource response it is inert.
for path in ["/index.html", "/assets/aa.js", "/manifest.json", "/assets/bb.png"] {
let headers = MobileWebShellResponseHeaders.forPath(
path,
contentType: "text/javascript; charset=utf-8",
byteCount: 0
)
precondition(headers["Content-Security-Policy"] == nil)
precondition(headers["Cache-Control"] == "no-store")
precondition(headers["X-Content-Type-Options"] == "nosniff")
}
}
static func checkNavigationErrors() {
let ignorable = MobileWebShellNavigationError.isIgnorable
// Our own stopLoading on a prop update, and every navigation the policy delegate refuses.
precondition(ignorable(NSURLErrorDomain, NSURLErrorCancelled))
precondition(ignorable("WebKitErrorDomain", 102))
// Anything else is the document failing to load, which is the caller's cue to redownload.
precondition(!ignorable(NSURLErrorDomain, NSURLErrorNetworkConnectionLost))
precondition(!ignorable(NSURLErrorDomain, NSURLErrorResourceUnavailable))
precondition(!ignorable("WebKitErrorDomain", 101))
precondition(!ignorable("WebKitErrorDomain", NSURLErrorCancelled))
// WKErrorDomain has no frame-load codes at all, so 102 there is some other error.
precondition(!ignorable("WKErrorDomain", 102))
precondition(!ignorable("SomeOtherDomain", 102))
}
static func bridgeSource(
isOurWebView: Bool = true,
isMainFrame: Bool = true,
hasCommittedDocument: Bool = true,
originProtocol: String = MobileWebShellOrigin.scheme,
originHost: String = session
) -> MobileWebShellBridgeSource {
MobileWebShellBridgeSource(
isOurWebView: isOurWebView,
isMainFrame: isMainFrame,
hasCommittedDocument: hasCommittedDocument,
originProtocol: originProtocol,
originHost: originHost
)
}
static func acceptsBridge(_ source: MobileWebShellBridgeSource) -> Bool {
MobileWebShellBridge.accepts(source, sessionId: session)
}
static func checkAppliedProps() {
func props(
directory: String = "/gen/aa",
session: String = session,
bridge: Bool = true
) -> MobileWebShellAppliedProps {
MobileWebShellAppliedProps(
generationDirectory: directory,
sessionId: session,
bridgeEnabled: bridge
)
}
precondition(props().matches(props()))
precondition(!props().matches(props(directory: "/gen/ab")))
precondition(!props().matches(props(session: "sess-01JN_aZ8")))
precondition(!props().matches(props(bridge: false)))
// A triple that could not be honoured is still applied: re-entry reads the props, never whether
// the install succeeded, so a corrupt generation reports its failure once rather than on every
// commit for the life of the mount.
precondition(props(directory: "/gen/corrupt").matches(props(directory: "/gen/corrupt")))
// A fourth prop that nobody compared is a prop that silently never reloads, so the record's
// shape is pinned here rather than left to whoever adds the field.
let fields = Mirror(reflecting: props()).children.compactMap(\.label).sorted()
precondition(fields == ["bridgeEnabled", "generationDirectory", "sessionId"])
}
static func checkBridgeAcceptance() {
precondition(acceptsBridge(bridgeSource()))
// Simulator-measured: WebKit reports the custom scheme's host ASCII-lowercased, so the session
// we minted never equals the host verbatim. Exact equality here refuses every message.
precondition(acceptsBridge(bridgeSource(originHost: "sess-01jn_az9")))
precondition(acceptsBridge(bridgeSource(originHost: "SESS-01JN_AZ9")))
// A frame we did not serve.
precondition(!acceptsBridge(bridgeSource(originHost: "sess-01JN_aZ8")))
precondition(!acceptsBridge(bridgeSource(originHost: "")))
precondition(!acceptsBridge(bridgeSource(originHost: "sess-01JN_aZ9.evil")))
// ASCII folding only: U+212A KELVIN SIGN lowercases to "k" under Unicode case folding, so a
// caseInsensitiveCompare would accept a host nobody minted.
precondition(!MobileWebShellBridge.accepts(
bridgeSource(originHost: "\u{212A}ey"),
sessionId: "key"
))
precondition(MobileWebShellOrigin.asciiLowercased("\u{212A}EY") == "\u{212A}ey")
// Another scheme reaching the same handler.
precondition(!acceptsBridge(bridgeSource(originProtocol: "https")))
precondition(!acceptsBridge(bridgeSource(originProtocol: "")))
precondition(!acceptsBridge(bridgeSource(originProtocol: "orca-mobile-web ")))
// A subframe, and a message routed to a WebView that is not ours.
precondition(!acceptsBridge(bridgeSource(isMainFrame: false)))
precondition(!acceptsBridge(bridgeSource(isOurWebView: false)))
// The document the current props replaced: same session, same origin, still alive between
// `stopLoading` and the next commit, speaking for a load already reported as `loading`.
precondition(!acceptsBridge(bridgeSource(hasCommittedDocument: false)))
// No applied session is not an empty one: nothing may be accepted before a load.
precondition(!MobileWebShellBridge.accepts(bridgeSource(originHost: ""), sessionId: ""))
precondition(!MobileWebShellBridge.accepts(bridgeSource(originHost: "a b"), sessionId: "a b"))
}
static func checkBridgePostTarget() {
func canPost(
_ host: String?,
_ sessionId: String = session,
committed: Bool = true
) -> Bool {
MobileWebShellBridge.canPost(
toFrameOriginHost: host,
sessionId: sessionId,
hasCommittedDocument: committed
)
}
precondition(canPost(session))
// The same ASCII fold as acceptance: WebKit reports the host lowercased.
precondition(canPost("sess-01jn_az9"))
// Nowhere to post, all four for the same reason: no frame has been accepted. A page that has
// never spoken, a document whose load failed, a renderer that died, a bridge not installed.
precondition(!canPost(nil))
// A frame from another document, and a frame under no session at all.
precondition(!canPost("sess-01JN_aZ8"))
precondition(!canPost("\u{212A}ey", "key"))
precondition(!canPost(session, ""))
precondition(!canPost("", ""))
// In flight: a navigation has started and not committed, so there is no document to post into
// even while a frame from the one being replaced is still held.
precondition(!canPost(session, committed: false))
}
/// The target across one document replacing another, in the order the navigation delegate runs:
/// a frame armed by document A is never what a post to document B goes to.
static func checkBridgeTargetLifecycle() {
func canPost(_ target: MobileWebShellBridgeTarget<String>, committed: Bool) -> Bool {
MobileWebShellBridge.canPost(
toFrameOriginHost: target.originHost,
sessionId: session,
hasCommittedDocument: committed
)
}
var target = MobileWebShellBridgeTarget<String>()
precondition(target.frame == nil && target.originHost == nil)
precondition(!canPost(target, committed: true))
// didCommit for document A, then A's first accepted message.
target.clear()
target.arm(frame: "frame-a", originHost: session)
precondition(target.frame == "frame-a")
precondition(canPost(target, committed: true))
// didStartProvisionalNavigation for document B. Refused twice over: nothing armed, and nothing
// committed to post into.
target.clear()
precondition(target.frame == nil)
precondition(!canPost(target, committed: false))
// didCommit for document B. Arming re-opens, so the clear has to happen here as well or A's
// frame becomes postable again as B's.
target.clear()
precondition(!canPost(target, committed: true))
// B speaks for itself, and that is the only way a post reaches it.
target.arm(frame: "frame-b", originHost: session)
precondition(target.frame == "frame-b")
precondition(canPost(target, committed: true))
}
static func checkBridgeByteCap() {
let cap = MobileWebShellBridge.maxMessageByteCount
precondition(cap == 640 * 1024)
precondition(MobileWebShellBridge.acceptsByteCount(0))
precondition(MobileWebShellBridge.acceptsByteCount(cap - 1))
precondition(MobileWebShellBridge.acceptsByteCount(cap))
precondition(!MobileWebShellBridge.acceptsByteCount(cap + 1))
// The cap is on UTF-8 bytes, not characters: a multi-byte payload must not buy extra room.
let wide = String(repeating: "\u{1F600}", count: 4)
precondition(wide.count == 4 && wide.utf8.count == 16)
let gate = MobileWebShellBridgeGate()
precondition(gate.refusedCount == 0)
precondition(gate.accepts(byteCount: cap))
precondition(gate.refusedCount == 0)
precondition(!gate.accepts(byteCount: cap + 1))
precondition(!gate.accepts(byteCount: cap * 2))
precondition(gate.refusedCount == 2)
}
static func main() {
checkSessionIds()
checkRequestResolution()
checkAssetPaths()
checkContentTypes()
checkGenerationMap()
checkCsp()
checkLoadStateMachine()
checkResponseHeaders()
checkNavigationErrors()
checkAppliedProps()
checkBridgeAcceptance()
checkBridgePostTarget()
checkBridgeTargetLifecycle()
checkBridgeByteCap()
print("mobile web shell checks OK")
}
}