fix(auth-js): env AUTH_URL not working (#478)

* fix(auth-js): env AUTH_URL not working

* test(auth-js): add reqWithEnvUrl test case

* chore: add changeset
pull/479/head
DIYgod 2024-04-26 02:57:56 +01:00 committed by GitHub
parent 9533c582ae
commit 5004ca9c5b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 24 additions and 3 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/auth-js': patch
---
fix env AUTH_URL not working

View File

@ -29,8 +29,16 @@ export interface AuthConfig extends Omit<AuthConfigCore, 'raw'> {}
export type ConfigHandler = (c: Context) => AuthConfig
function reqWithEnvUrl(req: Request, authUrl?: string): Request {
return authUrl ? new Request(new URL(req.url, authUrl).href, req) : req
export function reqWithEnvUrl(req: Request, authUrl?: string): Request {
if (authUrl) {
const reqUrlObj = new URL(req.url)
const authUrlObj = new URL(authUrl)
const props = ['hostname', 'protocol', 'port', 'password', 'username'] as const
props.forEach(prop => reqUrlObj[prop] = authUrlObj[prop])
return new Request(reqUrlObj.href, req);
} else {
return req;
}
}
function setEnvDefaults(env: AuthEnv, config: AuthConfig) {

View File

@ -1,7 +1,7 @@
import { webcrypto } from 'node:crypto'
import { Hono } from 'hono'
import { describe, expect, it } from 'vitest'
import { authHandler, verifyAuth, initAuthConfig } from '../src'
import { authHandler, verifyAuth, initAuthConfig, reqWithEnvUrl } from '../src'
// @ts-expect-error - global crypto
//needed for node 18 and below but should work in node 20 and above
@ -82,3 +82,11 @@ describe('Auth.js Adapter Middleware', () => {
expect(res.status).toBe(401)
})
})
describe('reqWithEnvUrl()', () => {
const req = new Request('http://request-base/request-path')
const newReq = reqWithEnvUrl(req, 'https://auth-url-base/auth-url-path')
it('Should rewrite the base path', () => {
expect(newReq.url.toString()).toBe('https://auth-url-base/request-path')
})
})