Skip to content

Commit 26706fb

Browse files
committed
fix(worker): bypass same-origin script requests
1 parent 0f87d46 commit 26706fb

3 files changed

Lines changed: 125 additions & 0 deletions

File tree

‎src/mockServiceWorker.js‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,18 @@ addEventListener('fetch', function (event) {
163163
return
164164
}
165165

166+
// Bypass same-origin module script requests (i.e. the modules of the page).
167+
// Performing them from the worker resets their destination, making
168+
// the browser send "Sec-Fetch-Dest: empty" instead of "script",
169+
// which breaks the servers that rely on it (e.g. for module caching).
170+
if (
171+
event.request.destination === 'script' &&
172+
event.request.mode === 'cors' &&
173+
event.request.url.startsWith(self.location.origin + '/')
174+
) {
175+
return
176+
}
177+
166178
// This request may be the one waking the worker up after the browser
167179
// has terminated it. Wait for the active clients to be restored
168180
// before deciding whether to handle the request.
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/**
2+
* @see https://github.com/mswjs/msw/issues/2831
3+
*/
4+
// @vitest-environment node
5+
import axios from 'axios'
6+
import { createTestHttpServer } from '@epic-web/test-server/http'
7+
import { setupServer } from 'msw/node'
8+
9+
const server = setupServer()
10+
11+
beforeAll(() => {
12+
server.listen({ onUnhandledFrame: 'bypass' })
13+
})
14+
15+
afterAll(() => {
16+
server.close()
17+
})
18+
19+
test('performs consecutive multipart uploads as-is on a reused connection', async () => {
20+
await using httpServer = await createTestHttpServer({
21+
defineRoutes(router) {
22+
router.post('/upload', async ({ req }) => {
23+
const data = await req.formData()
24+
const file = data.get('file')
25+
26+
if (!(file instanceof File)) {
27+
return new Response('Missing file', { status: 422 })
28+
}
29+
30+
return Response.json({ name: file.name, size: file.size })
31+
})
32+
},
33+
})
34+
35+
const client = axios.create({
36+
baseURL: httpServer.http.url('/').href,
37+
validateStatus: () => {
38+
return true
39+
},
40+
})
41+
42+
const createUpload = () => {
43+
const formData = new FormData()
44+
formData.append(
45+
'file',
46+
new Blob([new Uint8Array(4096)], { type: 'image/png' }),
47+
'picture.png',
48+
)
49+
50+
return formData
51+
}
52+
53+
const firstResponse = await client.post('/upload', createUpload())
54+
expect.soft(firstResponse.status).toBe(200)
55+
expect.soft(firstResponse.data).toEqual({ name: 'picture.png', size: 4096 })
56+
57+
const secondResponse = await client.post('/upload', createUpload())
58+
expect.soft(secondResponse.status).toBe(200)
59+
expect.soft(secondResponse.data).toEqual({ name: 'picture.png', size: 4096 })
60+
61+
const thirdResponse = await client.post('/upload', createUpload())
62+
expect.soft(thirdResponse.status).toBe(200)
63+
expect.soft(thirdResponse.data).toEqual({ name: 'picture.png', size: 4096 })
64+
65+
const fourthResponse = await client.post('/upload', createUpload())
66+
expect.soft(fourthResponse.status).toBe(200)
67+
expect(fourthResponse.data).toEqual({ name: 'picture.png', size: 4096 })
68+
})
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @see https://github.com/mswjs/msw/issues/2843
3+
*/
4+
import { vi, onTestFinished } from 'vitest'
5+
import { test, expect } from '../setup/vitest-helpers'
6+
7+
test('does not intercept same-origin module script requests', async ({
8+
network,
9+
}) => {
10+
const requestListener = vi.fn<(url: string) => void>()
11+
const handleRequest = ({ request }: { request: Request }) => {
12+
requestListener(request.url)
13+
}
14+
15+
network.events.on('request:start', handleRequest)
16+
onTestFinished(() => {
17+
network.events.removeListener('request:start', handleRequest)
18+
})
19+
20+
const scriptUrl = new URL(
21+
`/script.js?id=${crypto.randomUUID()}`,
22+
location.href,
23+
).href
24+
const scriptRequestFinished = Promise.withResolvers<void>()
25+
26+
const link = document.createElement('link')
27+
link.rel = 'modulepreload'
28+
link.href = scriptUrl
29+
link.addEventListener('load', () => scriptRequestFinished.resolve())
30+
link.addEventListener('error', () => scriptRequestFinished.resolve())
31+
document.head.append(link)
32+
onTestFinished(() => {
33+
link.remove()
34+
})
35+
36+
await scriptRequestFinished.promise
37+
// Requests are intercepted in the same order they are performed.
38+
// Once this one is, the script request would have been as well.
39+
await fetch(new URL('/resource', location.href))
40+
41+
expect(requestListener).toHaveBeenCalledWith(
42+
new URL('/resource', location.href).href,
43+
)
44+
expect(requestListener).not.toHaveBeenCalledWith(scriptUrl)
45+
})

0 commit comments

Comments
 (0)