Skip to content

Commit

Permalink
fix(auth-js): fix cloned request causing request body to be unavailab…
Browse files Browse the repository at this point in the history
…le in middleware (#806)
  • Loading branch information
985563349 authored Nov 6, 2024
1 parent b5fab5f commit 9a2cf45
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/rare-toys-decide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hono/auth-js': major
---

fix cloned request causing request body to be unavailable in middleware
6 changes: 3 additions & 3 deletions packages/auth-js/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ export function reqWithEnvUrl(req: Request, authUrl?: string) {
}
return new Request(reqUrlObj.href, req)
}
const newReq = new Request(req)
const url = new URL(newReq.url)
const url = new URL(req.url)
const newReq = new Request(url.href, req)
const proto = newReq.headers.get('x-forwarded-proto')
const host = newReq.headers.get('x-forwarded-host') ?? newReq.headers.get('host')
if (proto != null) url.protocol = proto.endsWith(':') ? proto : `${proto}:`
Expand Down Expand Up @@ -128,7 +128,7 @@ export function authHandler(): MiddlewareHandler {
if (!config.secret || config.secret.length === 0) {
throw new HTTPException(500, { message: 'Missing AUTH_SECRET' })
}

const res = await Auth(reqWithEnvUrl(c.req.raw, ctxEnv.AUTH_URL), config)
return new Response(res.body, res)
}
Expand Down
27 changes: 26 additions & 1 deletion packages/auth-js/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,11 @@ describe('Credentials Provider', () => {
return c.json(auth)
})

app.post('/api/create', async (c) => {
const data = await c.req.json()
return c.json({ data })
})

const credentials = Credentials({
credentials: {
password: {},
Expand Down Expand Up @@ -186,7 +191,7 @@ describe('Credentials Provider', () => {
headers,
})
expect(res.status).toBe(200)
const obj = await res.json() as {
const obj = (await res.json()) as {
token: {
name: string
email: string
Expand All @@ -196,6 +201,26 @@ describe('Credentials Provider', () => {
expect(obj.token.email).toBe(user.email)
})

it('Should authorize and return 200 - /api/create', async () => {
const data = { name: 'Hono' }

const headers = new Headers()
headers.append('cookie', cookie[1])
headers.append('Content-Type', 'application/json')
const res = await app.request('http://localhost/api/create', {
method: 'POST',
headers,
body: JSON.stringify(data),
})
expect(res.status).toBe(200)
const obj = (await res.json()) as {
data: {
name: string
}
}
expect(obj.data.name).toBe(data.name)
})

it('Should respect x-forwarded-proto and x-forwarded-host', async () => {
const headers = new Headers()
headers.append('x-forwarded-proto', 'https')
Expand Down

0 comments on commit 9a2cf45

Please sign in to comment.