Files
orca/config/scripts/verify-packaged-mobile-web-bundle.cjs
Jinwoo Hong da1c322b00 feat(mobile): one build-time switch picks native or OTA, default native (OTA phase E1) (#22193)
* feat(mobile): one build-time constant decides native or OTA, default native

EXPO_PUBLIC_MOBILE_SHELL is read in exactly one place, mobileShellBuildKind in
preferences.ts. Expo's babel preset inlines a literal process.env member
expression at build time, so a release bundle carries the answer as a constant
and anything but the exact string 'ota' — unset, empty, a typo — is native.
Every default build is therefore the native app, unchanged.

mobileWebShellFlagCanBeOn now answers __DEV__ or an OTA build, so the ability to
mount the page comes from the build and never from storage: a native binary
installed over an OTA one, same bundle id and same data container, still refuses
a stored 'true' without reading the key. An unset key reads on only in an OTA
build; a development build keeps its opt-in, and a stored 'false' wins
everywhere so the Troubleshoot toggle can switch an OTA build back to native.

That toggle now mounts wherever the flag can be on, which is the only way back
to the native screens in an OTA build, and its label names the build kind rather
than saying "(dev)". The bundle probe row beside it stays development-only: it
fetches.

The flag census gains two rules — one module reads the switch, in the member
form Expo inlines and not the bracket form, and one named function answers the
build kind — and the build-kind fence now lists the Troubleshoot route that asks
it. Docblocks that said a store build can never mount the shell now say it
mounts only when built for OTA.

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

* ci(mobile): one workflow input picks the shell, and no input means native

Both release workflows gain a `shell` workflow_dispatch choice, options native
and ota, default native, and hand it to the step that bundles the JavaScript as
EXPO_PUBLIC_MOBILE_SHELL. That is the Gradle assembleRelease step on Android and
the fastlane build_and_upload step on iOS; nothing else in either file sets it.

A tag push and a schedule carry no inputs at all, so `inputs.shell || 'native'`
yields native for them — the first OTA release is a dispatch with one field
changed, and every other run is the app we ship today.

Each build step prints the value it is about to build with, read back from the
same variable rather than from a second copy of the expression, so a run's log
cannot claim a shell the build did not use.

The new contract test evaluates that expression rather than matching its text:
absent, empty and 'native' all resolve to native, 'ota' to ota, and any
expression shape it cannot evaluate is a failure rather than a pass.

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

* build: the desktop packages the real page, and the placeholder is retired

build:mobile-web now runs the app builder and app verifier, and both take their
output root from MOBILE_WEB_BUNDLE_DIR in the packaging guard rather than each
carrying a constant of their own — one definition of where the bundle lives, so
a drift cannot leave electron-builder's beforePack looking at an empty directory
while the builder reports a tree it wrote elsewhere. build:mobile-web:app is
gone; it was the same two commands.

src/mobile-web/ and its two scripts go with it. What the app builder shared with
them is split into three modules named for what they hold rather than for the
bundle that used to own them: mobile-web-bundle-manifest.mjs (content types, the
canonical asset serialization, buildId, hashed assets, the protocol window and
the manifest write), script-entry-detection.mjs (isDirectInvocation, whose two
failure modes are Windows paths and symlinked entries), and
mobile-web-source-line-endings.mjs (the CRLF guard, now with a required
directory rather than a default pointing at the deleted tree).

The two suites that only needed *a* valid tree on disk — the beforePack guard
and the packaged-bundle guard — build one from mobile-web-bundle-fixture-tree
instead of bundling the whole mobile graph. It goes through the same manifest
writer the page does, so a manifest shape change still reaches them.

Also retired: the placeholder's tsconfig project and its typecheck lane, its
knip entry, its electron-builder exclusion and .gitattributes pins, and the
app-bundle test that asserted the shims stayed out of a builder that no longer
exists. pr.yml's page job builds the same bundle the package job ships.

Inert for native phones: they never fetch it.

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

* style(config): one import of node:fs/promises in the entry-detection suite

The changed-code quality gate's focused plugins read the two as a duplicate
import; the readFile line was left over from the split.

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

* docs: the comments that still describe the retired placeholder bundle

The web entry said it was built by `build:mobile-web:app` into out/mobile-web-app
and shipped by nothing. That script, that directory and that fact are all gone:
it is built by `build:mobile-web` into the packaged bundle dir, and a phone
mounts it only when the binary was built with EXPO_PUBLIC_MOBILE_SHELL=ota.

Two Windows cache keys explained themselves by naming src/mobile-web and "the
two bundle builders"; config/** now covers the builder, the verifier and the
manifest writer, and the spike's key no longer waits on a Phase C flip that has
happened. The keys themselves are unchanged.

Three scratch directories in the app-bundle suites and one in the verifier still
spelled the retired output root. Renamed to mobile-web, which is what the build
writes; they are temp subdirectory names and nothing reads them.

Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
2026-09-22 06:18:33 -04:00

194 lines
7.4 KiB
JavaScript

const { createHash } = require('node:crypto')
const { readFileSync, readdirSync, statSync } = require('node:fs')
const { join, resolve } = require('node:path')
const projectDir = resolve(__dirname, '..', '..')
const MOBILE_WEB_BUNDLE_DIR = join(projectDir, 'out', 'mobile-web')
const REMEDY = 'Run pnpm build:mobile-web (build:desktop and build:release already do).'
const ENTRYPOINT = 'index.html'
const SHA256_PATTERN = /^[0-9a-f]{64}$/
function failure(message) {
return new Error(`[verify-packaged-mobile-web-bundle] ${message}`)
}
function assertSafeRelativePath(path) {
if (typeof path !== 'string' || path.length === 0) {
throw failure('manifest asset has a missing or empty path')
}
const segments = path.split('/')
if (
path.includes('\\') ||
path.startsWith('/') ||
/^[a-zA-Z]:/.test(path) ||
segments.some((segment) => segment === '' || segment === '.' || segment === '..')
) {
throw failure(`manifest asset path is not a safe relative path: ${path}`)
}
}
function assertInteger(value, field) {
if (!Number.isSafeInteger(value) || value < 0) {
throw failure(`manifest field ${field} is not a non-negative integer: ${String(value)}`)
}
}
/**
* Canonical serialization of the asset list. Must stay byte-identical to
* serializeMobileWebBundleAssets in config/scripts/mobile-web-bundle-manifest.mjs; a divergence here
* would reject every honest bundle, so the two move together.
*/
function serializeAssets(assets) {
return JSON.stringify(
[...assets]
.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0))
.map(({ path, sha256, byteLength, contentType }) => ({
path,
sha256,
byteLength,
contentType
}))
)
}
function parseManifest(bundleDir) {
const manifestPath = join(bundleDir, 'manifest.json')
let raw
try {
raw = readFileSync(manifestPath, 'utf8')
} catch (error) {
throw failure(
`no bundle manifest at ${manifestPath} (${error.code ?? error.message}). ${REMEDY}`
)
}
let manifest
try {
manifest = JSON.parse(raw)
} catch (error) {
throw failure(`${manifestPath} is not valid JSON: ${error.message}. ${REMEDY}`)
}
if (typeof manifest !== 'object' || manifest === null || Array.isArray(manifest)) {
throw failure(`${manifestPath} is not a JSON object. ${REMEDY}`)
}
if (manifest.schemaVersion !== 1) {
throw failure(`unsupported manifest schemaVersion: ${String(manifest.schemaVersion)}`)
}
if (typeof manifest.buildId !== 'string' || !SHA256_PATTERN.test(manifest.buildId)) {
throw failure(`manifest buildId is not a sha256 digest: ${String(manifest.buildId)}`)
}
if (typeof manifest.desktopVersion !== 'string' || manifest.desktopVersion.length === 0) {
throw failure('manifest desktopVersion is missing')
}
assertInteger(manifest.minCompatibleRuntimeProtocolVersion, 'minCompatibleRuntimeProtocolVersion')
assertInteger(manifest.runtimeProtocolVersion, 'runtimeProtocolVersion')
assertInteger(manifest.totalBytes, 'totalBytes')
if (manifest.entrypoint !== ENTRYPOINT) {
throw failure(`manifest entrypoint must be ${ENTRYPOINT}, got ${String(manifest.entrypoint)}`)
}
if (!Array.isArray(manifest.assets) || manifest.assets.length === 0) {
throw failure('manifest lists no assets')
}
for (const asset of manifest.assets) {
if (typeof asset !== 'object' || asset === null) {
throw failure('manifest asset entry is not an object')
}
assertSafeRelativePath(asset.path)
if (typeof asset.sha256 !== 'string' || !SHA256_PATTERN.test(asset.sha256)) {
throw failure(`manifest asset ${asset.path} has no sha256 digest`)
}
assertInteger(asset.byteLength, `assets[${asset.path}].byteLength`)
if (typeof asset.contentType !== 'string' || asset.contentType.length === 0) {
throw failure(`manifest asset ${asset.path} has no contentType`)
}
}
if (!manifest.assets.some((asset) => asset.path === manifest.entrypoint)) {
throw failure(`manifest entrypoint ${manifest.entrypoint} is not one of its assets`)
}
const declaredTotal = manifest.assets.reduce((total, asset) => total + asset.byteLength, 0)
if (declaredTotal !== manifest.totalBytes) {
throw failure(
`manifest totalBytes is ${String(manifest.totalBytes)}, its assets sum to ${String(declaredTotal)}`
)
}
const recomputed = createHash('sha256')
.update(serializeAssets(manifest.assets), 'utf8')
.digest('hex')
if (recomputed !== manifest.buildId) {
throw failure(
`manifest buildId ${manifest.buildId} does not match its asset list (expected ${recomputed}). ${REMEDY}`
)
}
return manifest
}
/** Every file under the bundle directory, as a manifest-shaped relative path. */
function listBundleFiles(directory, prefix = '') {
const found = []
for (const entry of readdirSync(directory, { withFileTypes: true })) {
const relativePath = prefix === '' ? entry.name : `${prefix}/${entry.name}`
if (entry.isDirectory()) {
found.push(...listBundleFiles(join(directory, entry.name), relativePath))
} else {
found.push(relativePath)
}
}
return found
}
/**
* Nothing in the bundle directory may be unaccounted for. An asset dropped from the manifest but
* left on disk by an interrupted build ships inside asar, unreachable and unverified, and grows
* the installer; content-addressed names mean stale copies never get overwritten.
*/
function assertNoUnlistedFiles(bundleDir, manifest) {
const listed = new Set(['manifest.json', ...manifest.assets.map((asset) => asset.path)])
const strays = listBundleFiles(bundleDir).filter((path) => !listed.has(path))
if (strays.length > 0) {
throw failure(
`${bundleDir} holds ${String(strays.length)} file(s) the manifest does not list: ` +
`${strays.sort().join(', ')}. ${REMEDY}`
)
}
}
/**
* Packaging guard: electron-builder only warns about a missing input, so without this a release
* would ship an app that advertises the bundle capability and then errors on every request. The
* hash check, not the existence check, is what catches a half-written or stale out/.
*/
function assertMobileWebBundleBuilt(bundleDir = MOBILE_WEB_BUNDLE_DIR) {
const manifest = parseManifest(bundleDir)
assertNoUnlistedFiles(bundleDir, manifest)
for (const asset of manifest.assets) {
const assetPath = join(bundleDir, asset.path)
let size
try {
size = statSync(assetPath).size
} catch (error) {
throw failure(
`manifest lists ${asset.path}, which is missing from ${bundleDir} (${error.code ?? error.message}). ${REMEDY}`
)
}
if (size !== asset.byteLength) {
throw failure(
`${asset.path} is ${String(size)} bytes on disk, manifest says ${String(asset.byteLength)}. ${REMEDY}`
)
}
const sha256 = createHash('sha256').update(readFileSync(assetPath)).digest('hex')
if (sha256 !== asset.sha256) {
throw failure(
`${asset.path} hashes to ${sha256} on disk, manifest says ${asset.sha256}. ${REMEDY}`
)
}
}
console.log(
`[verify-packaged-mobile-web-bundle] OK — buildId ${manifest.buildId}, ` +
`${String(manifest.assets.length)} asset(s), ${String(manifest.totalBytes)} bytes`
)
return manifest
}
// serializeAssets is exported for the parity test that pins it against the builder's and the
// contract's serializers; nothing in packaging calls it from outside this module.
module.exports = { MOBILE_WEB_BUNDLE_DIR, assertMobileWebBundleBuilt, serializeAssets }