From bf23facf878547aede8418ec6ad7d302337182d6 Mon Sep 17 00:00:00 2001 From: Edgar Durand Date: Mon, 23 Nov 2026 21:00:22 -0300 Subject: [PATCH] fix(cli): Point mode on an Expo preview highlights the element under the cursor The Expo bring-up never put the inspector proxy in front of Metro ("a DOM inspector means nothing against a native app"), but since v2.76.42 the frame shows Expo's WEB build: react-native-web DOM. With no injected picker the dashboard fell back to drawing boxes, so Point showed only "Tap or drag to mark" and no hover highlight. When the web build is served, the inspector (the same Remix picker every Vite preview gets) now sits first: tunnel -> inspector -> [app-server proxy] -> Metro. Expo Go only requests manifests and bundles, never an HTML navigation, so it never sees the script. The proxy takes its upstream headers from `devRequestHeaders` here, because Metro 500s a same-origin Origin that is not its own host; that rule now also accepts the loopback Origin a proxy in front already rewrote for this hop. Co-Authored-By: Claude Opus 5.5 --- .../preview/inspector-proxy.expo.int.test.ts | 103 ++++++++++++++++++ .../preview/remix-app-server.test.ts | 7 ++ .../src/services/preview/app-server-proxy.ts | 8 +- .../src/services/preview/inspector-bringup.ts | 5 +- .../src/services/preview/inspector-proxy.ts | 14 ++- .../services/preview/start-orchestrator.ts | 31 ++++-- 6 files changed, 156 insertions(+), 12 deletions(-) create mode 100644 apps/cli/__tests__/preview/inspector-proxy.expo.int.test.ts diff --git a/apps/cli/__tests__/preview/inspector-proxy.expo.int.test.ts b/apps/cli/__tests__/preview/inspector-proxy.expo.int.test.ts new file mode 100644 index 00000000..a4418d55 --- /dev/null +++ b/apps/cli/__tests__/preview/inspector-proxy.expo.int.test.ts @@ -0,0 +1,103 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import * as http from 'http'; +import type { AddressInfo } from 'net'; +import { startInspectorProxy, type InspectorProxy } from '../../src/services/preview/inspector-proxy'; +import { + devRequestHeaders, + startAppServerProxy, + type AppServerProxy, +} from '../../src/services/preview/app-server-proxy'; + +/** + * Point mode had no hover highlight on an Expo preview (owner 2026-11-23): the Expo bring-up never + * put the inspector in front of Metro, so the dashboard fell back to drawing boxes. Now the WEB + * build gets it like any Vite app. These run the real chain against a Metro stand-in that refuses, + * like Expo's dev middleware, any Origin that isn't its own host (the 2026-11-23 icon-font 500). + */ + +const SCRIPT = ''; +const PUBLIC_HOST = 'preview-x.codeagent-mobile.com'; + +let closers: Array<() => Promise> = []; +afterEach(async () => { + for (const c of closers.reverse()) await c(); + closers = []; +}); + +async function fakeMetro(): Promise { + const server = http.createServer((req, res) => { + const port = (server.address() as AddressInfo).port; + const origin = req.headers.origin; + if (origin && origin !== `http://localhost:${port}`) { + res.writeHead(500, { 'content-type': 'text/plain' }); + res.end('origin refused'); + return; + } + if (req.url === '/') { + res.writeHead(200, { 'content-type': 'text/html' }); + res.end('app
'); + return; + } + res.writeHead(200, { 'content-type': 'font/ttf' }); + res.end('font'); + }); + await new Promise((r) => server.listen(0, '127.0.0.1', () => r())); + closers.push(() => new Promise((r) => server.close(() => r()))); + return (server.address() as AddressInfo).port; +} + +function get( + port: number, + path: string, + headers: http.OutgoingHttpHeaders, +): Promise<{ status: number; body: string }> { + return new Promise((resolve, reject) => { + const req = http.request({ host: '127.0.0.1', port, path, headers: { host: PUBLIC_HOST, ...headers } }, (res) => { + let body = ''; + res.setEncoding('utf8'); + res.on('data', (c: string) => (body += c)); + res.on('end', () => resolve({ status: res.statusCode ?? 0, body })); + }); + req.on('error', reject); + req.end(); + }); +} + +const page = { accept: 'text/html', 'sec-fetch-dest': 'iframe' }; +const font = { origin: `https://${PUBLIC_HOST}`, 'sec-fetch-dest': 'font' }; + +async function inspector(targetPort: number): Promise { + const p = await startInspectorProxy({ targetPort, script: SCRIPT, upstreamHeaders: devRequestHeaders }); + closers.push(() => p.close()); + return p; +} + +describe('the Expo web preview behind the inspector', () => { + it('tunnel → inspector → Metro: the page gets the picker, same-origin assets still load', async () => { + const metro = await fakeMetro(); + const insp = await inspector(metro); + expect((await get(insp.port, '/', page)).body).toContain(SCRIPT); + expect(await get(insp.port, '/assets/?unstable_path=Feather.ttf', font)).toEqual({ status: 200, body: 'font' }); + }); + + it('tunnel → inspector → app-server proxy → Metro (a Remix MOBILE app with a server)', async () => { + const metro = await fakeMetro(); + const app: AppServerProxy = await startAppServerProxy({ + devPort: metro, + serverPort: 1, // never reached: no server path below + injectBase: true, + routeRoot: false, + }); + closers.push(() => app.close()); + const insp = await inspector(app.port); + expect((await get(insp.port, '/', page)).body).toContain(SCRIPT); + expect(await get(insp.port, '/assets/?unstable_path=Feather.ttf', font)).toEqual({ status: 200, body: 'font' }); + }); + + it('without the Origin rewrite Metro refuses the fonts — why Expo passes devRequestHeaders', async () => { + const metro = await fakeMetro(); + const plain = await startInspectorProxy({ targetPort: metro, script: SCRIPT }); + closers.push(() => plain.close()); + expect((await get(plain.port, '/assets/?unstable_path=Feather.ttf', font)).status).toBe(500); + }); +}); diff --git a/apps/cli/__tests__/preview/remix-app-server.test.ts b/apps/cli/__tests__/preview/remix-app-server.test.ts index 6e093655..069d8c90 100644 --- a/apps/cli/__tests__/preview/remix-app-server.test.ts +++ b/apps/cli/__tests__/preview/remix-app-server.test.ts @@ -184,6 +184,13 @@ describe('app-server proxy — the dev server sees a same-origin request as its ); expect(devRequestHeaders({ host: 'p.example.com' }, 8081).origin).toBeUndefined(); }); + it('rewrites the loopback Origin a proxy in front already set for this hop (Expo inspector)', () => { + const h = devRequestHeaders( + { host: 'localhost:5001', origin: 'http://localhost:5001', 'x-forwarded-host': 'p.example.com' }, + 8081, + ); + expect(h).toMatchObject({ host: 'localhost:8081', origin: 'http://localhost:8081' }); + }); }); describe('app-server proxy — live', () => { diff --git a/apps/cli/src/services/preview/app-server-proxy.ts b/apps/cli/src/services/preview/app-server-proxy.ts index 6e9ac62d..03577afe 100644 --- a/apps/cli/src/services/preview/app-server-proxy.ts +++ b/apps/cli/src/services/preview/app-server-proxy.ts @@ -109,7 +109,13 @@ export function devRequestHeaders( ): http.OutgoingHttpHeaders { const out = upstreamRequestHeaders(headers, devPort); const origin = one(headers.origin); - if (origin && origin === publicOriginOf(headers)) out.origin = `http://localhost:${devPort}`; + // Same-origin = the public origin, OR this hop's own loopback host: the inspector proxy in front + // already rewrote it to `http://localhost:` (Expo web preview: tunnel → inspector → + // this proxy → Metro). + const host = one(headers.host); + if (origin && (origin === publicOriginOf(headers) || (host && origin === `http://${host}`))) { + out.origin = `http://localhost:${devPort}`; + } return out; } diff --git a/apps/cli/src/services/preview/inspector-bringup.ts b/apps/cli/src/services/preview/inspector-bringup.ts index af6e8b59..1a7aa49e 100644 --- a/apps/cli/src/services/preview/inspector-bringup.ts +++ b/apps/cli/src/services/preview/inspector-bringup.ts @@ -1,4 +1,4 @@ -import { startInspectorProxy, type InspectorProxy } from './inspector-proxy'; +import { startInspectorProxy, type InspectorProxy, type InspectorProxyOptions } from './inspector-proxy'; import { inspectorClientSource } from './inspector-client'; /** @@ -52,6 +52,8 @@ export interface BringUpInspectorDeps { start?: typeof startInspectorProxy; /** The loopback the dev server bound (`::1` for an IPv6-only Vite). */ targetHost?: string; + /** See `InspectorProxyOptions.upstreamHeaders` (Expo's Origin rewrite). */ + upstreamHeaders?: InspectorProxyOptions['upstreamHeaders']; log?: (message: string) => void; env?: NodeJS.ProcessEnv; } @@ -84,6 +86,7 @@ export async function bringUpInspector( const proxy = await start({ targetPort, ...(deps.targetHost ? { targetHost: deps.targetHost } : {}), + ...(deps.upstreamHeaders ? { upstreamHeaders: deps.upstreamHeaders } : {}), script: inspectorClientSource({ allowedOrigins: resolveInspectorOrigins(env) }), }); log(`preview inspector proxy on :${proxy.port} → ${deps.targetHost ?? '127.0.0.1'}:${targetPort}`); diff --git a/apps/cli/src/services/preview/inspector-proxy.ts b/apps/cli/src/services/preview/inspector-proxy.ts index 28c3f2fc..87f02315 100644 --- a/apps/cli/src/services/preview/inspector-proxy.ts +++ b/apps/cli/src/services/preview/inspector-proxy.ts @@ -57,6 +57,15 @@ export interface InspectorProxyOptions { script: string; /** Host del dev server. Solo para tests; en producción es localhost. */ targetHost?: string; + /** + * The headers the dev server sees (HTTP and websocket upgrades). Default + * {@link upstreamRequestHeaders}. Expo passes `devRequestHeaders`: Metro's + * middleware 500s a same-origin `Origin` that is not its own host. + */ + upstreamHeaders?: ( + headers: http.IncomingHttpHeaders, + targetPort: number, + ) => http.OutgoingHttpHeaders; } export interface InspectorProxy { @@ -166,6 +175,7 @@ export async function startInspectorProxy( opts: InspectorProxyOptions, ): Promise { const targetHost = opts.targetHost ?? '127.0.0.1'; + const headersFor = opts.upstreamHeaders ?? upstreamRequestHeaders; /** * Los sockets ASCENDIDOS (websockets de recarga en caliente). @@ -186,7 +196,7 @@ export async function startInspectorProxy( secFetchDest: one(req.headers['sec-fetch-dest']), secFetchMode: one(req.headers['sec-fetch-mode']), }); - const headers = upstreamRequestHeaders(req.headers, opts.targetPort); + const headers = headersFor(req.headers, opts.targetPort); // ⚠️ No se puede inyectar dentro de bytes comprimidos. Se renuncia a la // compresión SOLO en las navegaciones; los assets —que son la mayor parte @@ -267,7 +277,7 @@ export async function startInspectorProxy( const upstream = net.connect(opts.targetPort, targetHost, () => { const lines = [`${req.method} ${req.url} HTTP/1.1`]; - for (const [k, v] of Object.entries(upstreamRequestHeaders(req.headers, opts.targetPort))) { + for (const [k, v] of Object.entries(headersFor(req.headers, opts.targetPort))) { for (const one of Array.isArray(v) ? v : [v]) { if (one !== undefined) lines.push(`${k}: ${one}`); } diff --git a/apps/cli/src/services/preview/start-orchestrator.ts b/apps/cli/src/services/preview/start-orchestrator.ts index f3a17890..375e5400 100644 --- a/apps/cli/src/services/preview/start-orchestrator.ts +++ b/apps/cli/src/services/preview/start-orchestrator.ts @@ -38,7 +38,7 @@ import { type ServedAddress, } from './served-address'; import type { InspectorProxy } from './inspector-proxy'; -import { startAppServerProxy, type AppServerProxy } from './app-server-proxy'; +import { devRequestHeaders, startAppServerProxy, type AppServerProxy } from './app-server-proxy'; import * as remixServer from './remix-app-server'; import { fetchNamedPreviewTunnel } from '../pairing.service'; import { stopExportTunnel } from '../../scratch/export-tunnel'; @@ -626,9 +626,23 @@ async function runExpoBringUp(ctx: StageCtx): Promise { return; } } + // The WEB build is react-native-web DOM, so the element inspector (Point mode's hover highlight + + // element picks, the same picker as Remix) works on it exactly as on a Vite app. It sits first, + // in front of the app-server proxy / Metro; Expo Go asks for manifests and bundles, never an + // HTML navigation, so it never sees the script. Metro 500s a same-origin `Origin` that isn't its + // own host, hence `devRequestHeaders`. No web build → no DOM → no inspector (QR only). + const inspection = web + ? await bringUpInspector(tunnelPort, { + upstreamHeaders: devRequestHeaders, + log: (m) => log.info('preview', m), + }) + : { port: tunnelPort, proxy: null }; + const closeInspector = (): void => void inspection.proxy?.close().catch(() => undefined); + emitProgress('TUNNEL_STARTING', `cloudflared quick tunnel → Expo :${detection.port}`); - const pub = await bringUpPublicUrl(ctx, tunnelPort); + const pub = await bringUpPublicUrl(ctx, inspection.port); if (!pub.ok) { + closeInspector(); emit(USER_EVENTS.PREVIEW_ERROR, { stage: 'tunnel', message: pub.message }); return; } @@ -645,12 +659,14 @@ async function runExpoBringUp(ctx: StageCtx): Promise { // Terminal event already emitted (error, or a `preview_ready` reuse that // has its own tunnel) — don't leak the connector we brought up first. killQuiet(pub.tunnel); + closeInspector(); return; } if (web && !(await appBuilds(ctx, detection.port))) { if (dev.devServer) previewSvc.killProcessTree(dev.devServer, 'SIGTERM'); killQuiet(pub.tunnel); + closeInspector(); return; } @@ -660,8 +676,7 @@ async function runExpoBringUp(ctx: StageCtx): Promise { url: web ? pub.url : expoGoUrl, expoGoUrl: web ? expoGoUrl : undefined, tunnel: pub.tunnel, - // No inspector: a DOM inspector means nothing against a native app. - inspector: null, + inspector: inspection.proxy, }); } @@ -1188,9 +1203,9 @@ interface TunnelUp { /** * El proxy del inspector, cuando se pudo levantar. * - * `null` significa camino directo — o porque es Expo (un inspector de DOM no - * significa nada contra una app nativa), o porque el proxy no arrancó y se - * cayó al camino de siempre. Hay que cerrarlo al parar el preview. + * `null` significa camino directo — o porque es Expo sin build web (solo el + * QR de Expo Go: no hay DOM), o porque el proxy no arrancó y se cayó al + * camino de siempre. Hay que cerrarlo al parar el preview. */ inspector: InspectorProxy | null; } @@ -1221,7 +1236,7 @@ async function establishTunnel(ctx: StageCtx, dev: DevServerUp): Promise