Skip to content

Commit

Permalink
fix(fetch): fix baseUrl
Browse files Browse the repository at this point in the history
  • Loading branch information
gutenye committed Jan 6, 2025
1 parent e487445 commit 98b9594
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 5 deletions.
8 changes: 4 additions & 4 deletions src/fetch/__tests__/fetchUtils.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { describe, expect, it, spyOn } from 'bun:test'
import { createRequest, request } from '../fetch'

const BASE_URL = 'https://example.com'
const BASE_URL = 'https://example.com/v1'

spyOn(globalThis, 'fetch').mockImplementation(async (input, options) => {
const result = [input, options]
const result = [input.toString(), options]
return {
ok: true,
json: async () => result,
Expand Down Expand Up @@ -38,7 +38,7 @@ describe('createRequest', () => {
it('works', async () => {
const api = createRequest(BASE_URL)
expect(await api('/a')).toEqual([
new URL(`${BASE_URL}/a`),
`${BASE_URL}/a`,
{
headers: {
'Content-Type': 'application/json',
Expand All @@ -49,6 +49,6 @@ describe('createRequest', () => {

it('path traversal attack', async () => {
const api = createRequest(BASE_URL)
expect((await api('/../a'))[0]).toEqual(new URL(`${BASE_URL}/a`))
expect((await api('/../../a'))[0]).toEqual(`${new URL(BASE_URL).origin}/a`)
})
})
3 changes: 2 additions & 1 deletion src/fetch/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,10 @@ export function createRequest(baseUrl: string) {
input: FetchArgs[0],
options?: FetchArgs[1],
) {
const newBaseUrl = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`
const newInput =
typeof input === 'string' && input.startsWith('/')
? new URL(input, baseUrl)
? new URL(input.slice(1), newBaseUrl)
: input
return request(newInput, options)
}
Expand Down

0 comments on commit 98b9594

Please sign in to comment.