From 081c2ef7929ff82e804b14b4267fee2bb3165872 Mon Sep 17 00:00:00 2001 From: Dylan-GJ <178807215+Dylan-GJ@users.noreply.github.com> Date: Tue, 6 Oct 2026 11:35:21 -0400 Subject: [PATCH] Forward CORS preflight requests from the app dev proxy to the app The proxy answered every OPTIONS request itself without Access-Control-Allow-Credentials, which broke credentialed cross-origin requests. Preflights now reach the target app, which decides CORS. The target's answer is only relayed when it is a 2xx that allows the request's origin. Otherwise (error or redirect status, no CORS headers as with Vite's default server.cors, or an unreachable target) the proxy responds itself, without credentials, as before. --- .changeset/app-dev-proxy-forward-preflight.md | 5 + .../utilities/app/http-reverse-proxy.test.ts | 122 +++++++++++++++++- .../cli/utilities/app/http-reverse-proxy.ts | 81 +++++++++--- 3 files changed, 190 insertions(+), 18 deletions(-) create mode 100644 .changeset/app-dev-proxy-forward-preflight.md diff --git a/.changeset/app-dev-proxy-forward-preflight.md b/.changeset/app-dev-proxy-forward-preflight.md new file mode 100644 index 00000000000..7e7b9e907f8 --- /dev/null +++ b/.changeset/app-dev-proxy-forward-preflight.md @@ -0,0 +1,5 @@ +--- +'@shopify/app': patch +--- + +Forward CORS preflight requests from the app dev proxy to your app, so credentialed requests work again diff --git a/packages/app/src/cli/utilities/app/http-reverse-proxy.test.ts b/packages/app/src/cli/utilities/app/http-reverse-proxy.test.ts index 7d26a2bf0c8..98029a1432e 100644 --- a/packages/app/src/cli/utilities/app/http-reverse-proxy.test.ts +++ b/packages/app/src/cli/utilities/app/http-reverse-proxy.test.ts @@ -8,6 +8,7 @@ import https from 'https' import net from 'net' const each = ['http', 'https'] as const +const authorizedOrigin = 'https://app.example' describe.sequential.each(each)('http-reverse-proxy for %s', (protocol) => { const test = getTestReverseProxy(protocol) @@ -55,8 +56,25 @@ describe.sequential.each(each)('http-reverse-proxy for %s', (protocol) => { }) }) - test('responds to CORS preflight OPTIONS with default headers', {retry: 2}, async ({setup}) => { + test('forwards the CORS preflight to the target and keeps its credentials decision', {retry: 2}, async ({setup}) => { const response = await fetch(`${protocol}://localhost:${setup.proxyPort}/path1/test`, { + method: 'OPTIONS', + headers: { + Origin: authorizedOrigin, + 'Access-Control-Request-Method': 'POST', + 'Access-Control-Request-Headers': 'Content-Type', + }, + agent, + }) + expect(response.status).toBe(204) + expect(response.headers.get('access-control-allow-origin')).toBe(authorizedOrigin) + expect(response.headers.get('access-control-allow-credentials')).toBe('true') + expect(response.headers.get('access-control-allow-methods')).toBe('POST') + expect(response.headers.get('access-control-allow-headers')).toBe('Content-Type') + }) + + test('responds to the preflight when the target has no OPTIONS handler', {retry: 2}, async ({setup}) => { + const response = await fetch(`${protocol}://localhost:${setup.proxyPort}/path2/test`, { method: 'OPTIONS', headers: { Origin: 'https://extensions.shopifycdn.com', @@ -70,10 +88,71 @@ describe.sequential.each(each)('http-reverse-proxy for %s', (protocol) => { expect(response.headers.get('access-control-allow-methods')).toBe('GET') expect(response.headers.get('access-control-allow-headers')).toBe('Authorization') expect(response.headers.get('access-control-max-age')).toBe('86400') + expect(response.headers.get('access-control-allow-credentials')).toBeNull() }) - test('responds to CORS preflight OPTIONS with defaults when no request headers', {retry: 2}, async ({setup}) => { - const response = await fetch(`${protocol}://localhost:${setup.proxyPort}/path1/test`, { + test( + 'responds to the preflight when the target answers 2xx without allowing the origin', + {retry: 2}, + async ({setup}) => { + const response = await fetch(`${protocol}://localhost:${setup.proxyPort}/path1/test`, { + method: 'OPTIONS', + headers: {Origin: 'https://evil.example', 'Access-Control-Request-Method': 'POST'}, + agent, + }) + expect(response.status).toBe(204) + expect(response.headers.get('access-control-allow-origin')).toBe('https://evil.example') + expect(response.headers.get('access-control-allow-credentials')).toBeNull() + }, + ) + + test('relays the target response body when the target allows the origin', {retry: 2}, async ({setup}) => { + const response = await fetch(`${protocol}://localhost:${setup.proxyPort}/path1/with-body`, { + method: 'OPTIONS', + headers: {Origin: authorizedOrigin, 'Access-Control-Request-Method': 'POST'}, + agent, + }) + expect(response.status).toBe(200) + expect(response.headers.get('access-control-allow-origin')).toBe(authorizedOrigin) + await expect(response.text()).resolves.toBe('ok') + }) + + test('relays the target response to an OPTIONS request without Origin', {retry: 2}, async ({setup}) => { + const response = await fetch(`${protocol}://localhost:${setup.proxyPort}/path1/with-body`, { + method: 'OPTIONS', + agent, + }) + expect(response.status).toBe(200) + expect(response.headers.get('access-control-allow-origin')).toBeNull() + await expect(response.text()).resolves.toBe('ok') + }) + + for (const status of [200, 302, 403, 404]) { + test(`responds to the preflight when the target answers ${status}`, {retry: 2}, async ({setup}) => { + const response = await fetch(`${protocol}://localhost:${setup.proxyPort}/path2/status-${status}`, { + method: 'OPTIONS', + headers: {Origin: 'https://evil.example', 'Access-Control-Request-Method': 'POST'}, + agent, + }) + expect(response.status).toBe(204) + expect(response.headers.get('access-control-allow-origin')).toBe('https://evil.example') + expect(response.headers.get('access-control-allow-credentials')).toBeNull() + }) + } + + test('responds to the preflight when the target is unreachable', {retry: 2}, async ({setup}) => { + const response = await fetch(`${protocol}://localhost:${setup.proxyPort}/unreachable/test`, { + method: 'OPTIONS', + headers: {Origin: 'https://extensions.shopifycdn.com', 'Access-Control-Request-Method': 'GET'}, + agent, + }) + expect(response.status).toBe(204) + expect(response.headers.get('access-control-allow-origin')).toBe('https://extensions.shopifycdn.com') + expect(response.headers.get('access-control-allow-credentials')).toBeNull() + }) + + test('responds to the preflight with defaults when no request headers', {retry: 2}, async ({setup}) => { + const response = await fetch(`${protocol}://localhost:${setup.proxyPort}/path2/test`, { method: 'OPTIONS', agent, }) @@ -81,6 +160,7 @@ describe.sequential.each(each)('http-reverse-proxy for %s', (protocol) => { expect(response.headers.get('access-control-allow-origin')).toBe('*') expect(response.headers.get('access-control-allow-methods')).toBe('GET, POST, PUT, DELETE, PATCH, OPTIONS') expect(response.headers.get('access-control-allow-headers')).toBe('Content-Type, Authorization') + expect(response.headers.get('access-control-allow-credentials')).toBeNull() }) test('closes the server when aborted', async ({setup}) => { @@ -113,11 +193,40 @@ function getTestReverseProxy(protocol: 'http' | 'https') { // eslint-disable-next-line no-empty-pattern setup: async ({}, use) => { const targetServer1 = http.createServer((req, res) => { + if (req.method === 'OPTIONS' && req.url?.endsWith('/with-body')) { + // Writes the body in several chunks, as a real app would after sending headers. + res.writeHead( + 200, + req.headers.origin === authorizedOrigin ? {'Access-Control-Allow-Origin': authorizedOrigin} : {}, + ) + res.write('o') + return res.end('k') + } + if (req.method === 'OPTIONS') { + const origin = req.headers.origin + // Like a backend with an origin allowlist: only trusted origins get CORS headers. + res.writeHead( + 204, + origin === authorizedOrigin + ? { + 'Access-Control-Allow-Origin': origin, + 'Access-Control-Allow-Credentials': 'true', + 'Access-Control-Allow-Methods': req.headers['access-control-request-method'] ?? '', + 'Access-Control-Allow-Headers': req.headers['access-control-request-headers'] ?? '', + } + : {}, + ) + return res.end() + } res.writeHead(200, {'Content-Type': 'text/plain'}) res.end('Response from target server 1') }) const targetServer2 = http.createServer((req, res) => { + if (req.method === 'OPTIONS') { + res.writeHead(Number(/status-(\d+)/.exec(req.url ?? '')?.[1] ?? 405)) + return res.end() + } res.writeHead(200, {'Content-Type': 'text/plain'}) res.end('Response from target server 2') }) @@ -131,11 +240,18 @@ function getTestReverseProxy(protocol: 'http' | 'https') { const targetPort1 = (targetServer1.address() as net.AddressInfo).port const targetPort2 = (targetServer2.address() as net.AddressInfo).port + // A port that was free a moment ago and has nothing listening on it. + const closedServer = http.createServer() + await new Promise((resolve) => closedServer.listen(0, 'localhost', resolve)) + const closedPort = (closedServer.address() as net.AddressInfo).port + await new Promise((resolve) => closedServer.close(() => resolve())) + const abortController = new AbortController() const {server: proxyServer} = await getProxyingWebServer( { '/path1': `http://localhost:${targetPort1}`, '/path2': `http://localhost:${targetPort2}`, + '/unreachable': `http://localhost:${closedPort}`, default: `http://localhost:${targetPort1}`, }, abortController.signal, diff --git a/packages/app/src/cli/utilities/app/http-reverse-proxy.ts b/packages/app/src/cli/utilities/app/http-reverse-proxy.ts index a0380b05995..84050887ac5 100644 --- a/packages/app/src/cli/utilities/app/http-reverse-proxy.ts +++ b/packages/app/src/cli/utilities/app/http-reverse-proxy.ts @@ -26,6 +26,7 @@ export async function getProxyingWebServer( // to block the loading of the ESM module graph. const httpProxy = await import('http-proxy-node16') const proxy = httpProxy.default.createProxyServer() + proxy.on('proxyRes', handlePreflightResponse) const requestListener = getProxyServerRequestListener(rules, proxy, stdout) @@ -70,27 +71,14 @@ function getProxyServerRequestListener( return function (req, res) { const target = match(rules, req) if (target) { - // Handle CORS preflight requests directly - // The proxy does not forward OPTIONS reliably, so we respond here - // using the headers requested by the client. - if (req.method === 'OPTIONS') { - res.writeHead(204, { - 'Access-Control-Allow-Origin': req.headers.origin ?? '*', - 'Access-Control-Allow-Methods': - req.headers['access-control-request-method'] ?? 'GET, POST, PUT, DELETE, PATCH, OPTIONS', - 'Access-Control-Allow-Headers': - req.headers['access-control-request-headers'] ?? 'Content-Type, Authorization', - 'Access-Control-Max-Age': '86400', - }) - return res.end() - } - return proxy.web(req, res, {target}, (err) => { + return proxy.web(req, res, {target, selfHandleResponse: isPreflight(req)}, (err) => { useConcurrentOutputContext({outputPrefix: 'proxy', stripAnsi: false}, () => { const lastError = isAggregateError(err) ? err.errors[err.errors.length - 1] : undefined const error = lastError ?? err outputWarn(`Error forwarding web request: ${error.message}`, stdout) outputWarn(`└ Unreachable target "${target}" for path: "${req.url}"`, stdout) }) + if (isPreflight(req) && !res.headersSent) respondToPreflight(req, res) }) } @@ -105,6 +93,69 @@ ${outputToken.json(JSON.stringify(rules))} } } +// Headers that only apply to a single connection and must not be relayed when we write the response ourselves. +const HOP_BY_HOP_HEADERS = new Set([ + 'connection', + 'keep-alive', + 'proxy-authenticate', + 'proxy-authorization', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', +]) + +function isPreflight(req: http.IncomingMessage) { + return req.method === 'OPTIONS' +} + +/** + * CORS preflights are answered by the target app, which is the only one that knows which origins to trust + * (including whether to allow credentials). + * + * A browser only accepts a preflight that is a 2xx allowing the request's origin. Anything else (dev servers that + * don't implement OPTIONS or answer it without CORS headers, redirects, errors, unreachable targets) would fail in the + * browser, so the proxy responds instead by reflecting the request. This also replaces a deliberate rejection from the + * target, which is acceptable for local development. Credentials are never granted here, as that would authorize any + * origin. + */ +function handlePreflightResponse( + targetResponse: http.IncomingMessage, + req: http.IncomingMessage, + res: http.ServerResponse, +) { + if (!isPreflight(req)) return + + const statusCode = targetResponse.statusCode ?? 500 + const {origin} = req.headers + const allowOrigin = targetResponse.headers['access-control-allow-origin'] + // An OPTIONS request without Origin is not a browser preflight, so there is no CORS decision to enforce. + const targetAllowsOrigin = origin === undefined || allowOrigin === '*' || allowOrigin === origin + if (statusCode < 200 || statusCode >= 300 || !targetAllowsOrigin) { + targetResponse.resume() + respondToPreflight(req, res) + return + } + + const headers = Object.fromEntries( + Object.entries(targetResponse.headers).filter(([name]) => !HOP_BY_HOP_HEADERS.has(name)), + ) + res.writeHead(statusCode, headers) + targetResponse.on('error', () => res.destroy()) + targetResponse.pipe(res) +} + +function respondToPreflight(req: http.IncomingMessage, res: http.ServerResponse) { + res.writeHead(204, { + 'Access-Control-Allow-Origin': req.headers.origin ?? '*', + 'Access-Control-Allow-Methods': + req.headers['access-control-request-method'] ?? 'GET, POST, PUT, DELETE, PATCH, OPTIONS', + 'Access-Control-Allow-Headers': req.headers['access-control-request-headers'] ?? 'Content-Type, Authorization', + 'Access-Control-Max-Age': '86400', + }) + res.end() +} + function match(rules: {[key: string]: string}, req: http.IncomingMessage, websocket = false) { const path: string = req.url ?? '/'