fix(auth-js): fix cloned request causing request body to be unavailable in middleware (#806)

pull/809/head
Jee 2024-11-06 13:37:59 +08:00 committed by GitHub
parent b5fab5f6ff
commit 9a2cf452c7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 34 additions and 4 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/auth-js': major
---
fix cloned request causing request body to be unavailable in middleware

View File

@ -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}:`
@ -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)
}

View File

@ -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: {},
@ -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
@ -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')