Skip to content

Commit 48a7ccb

Browse files
authored
feat(bearer-auth): make bearerAuth generic for typed context in verifyToken (#4913)
* feat(bearer-auth): make bearerAuth generic for typed context in verify token * test(bearer-auth): add type tests * docs(bearer-auth): add tsdocs
1 parent ff7522f commit 48a7ccb

2 files changed

Lines changed: 33 additions & 5 deletions

File tree

‎src/middleware/bearer-auth/index.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
import { expectTypeOf } from 'vitest'
12
import { Hono } from '../../hono'
3+
import type { Context, MiddlewareHandler } from '../../index'
24
import { bearerAuth } from '.'
35

46
describe('Bearer Auth by Middleware', () => {
@@ -982,3 +984,26 @@ describe('Bearer Auth with prefix containing regex metacharacters', () => {
982984
expect(handlerExecuted).toBeFalsy()
983985
})
984986
})
987+
988+
describe('Bearer Auth types', () => {
989+
interface TestEnv {
990+
Bindings: { API_KEY: string }
991+
}
992+
993+
it('returns MiddlewareHandler<E> with explicit generic', () => {
994+
const middleware = bearerAuth<TestEnv>({
995+
verifyToken: (token, ctx) => {
996+
expectTypeOf(ctx.env.API_KEY).toEqualTypeOf<string>()
997+
return token === ctx.env.API_KEY
998+
},
999+
})
1000+
expectTypeOf(middleware).toEqualTypeOf<MiddlewareHandler<TestEnv>>()
1001+
})
1002+
1003+
it('infers E from ctx annotation', () => {
1004+
const middleware = bearerAuth({
1005+
verifyToken: (token, ctx: Context<TestEnv>) => token === ctx.env.API_KEY,
1006+
})
1007+
expectTypeOf(middleware).toEqualTypeOf<MiddlewareHandler<TestEnv>>()
1008+
})
1009+
})

‎src/middleware/bearer-auth/index.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
import type { Context } from '../../context'
77
import { HTTPException } from '../../http-exception'
8-
import type { MiddlewareHandler } from '../../types'
8+
import type { Env, MiddlewareHandler } from '../../types'
99
import { timingSafeEqual } from '../../utils/buffer'
1010
import type { ContentfulStatusCode } from '../../utils/http-status'
1111

@@ -19,7 +19,7 @@ type CustomizedErrorResponseOptions = {
1919
message?: string | object | MessageFunction
2020
}
2121

22-
type BearerAuthOptions =
22+
type BearerAuthOptions<E extends Env = Env> =
2323
| {
2424
token: string | string[]
2525
realm?: string
@@ -46,7 +46,7 @@ type BearerAuthOptions =
4646
realm?: string
4747
prefix?: string
4848
headerName?: string
49-
verifyToken: (token: string, c: Context) => boolean | Promise<boolean>
49+
verifyToken: (token: string, c: Context<E>) => boolean | Promise<boolean>
5050
hashFunction?: Function
5151
/**
5252
* @deprecated Use noAuthenticationHeader.message instead
@@ -70,6 +70,7 @@ type BearerAuthOptions =
7070
*
7171
* @see {@link https://hono.dev/docs/middleware/builtin/bearer-auth}
7272
*
73+
* @template E - The environment type.
7374
* @param {BearerAuthOptions} options - The options for the bearer authentication middleware.
7475
* @param {string | string[]} [options.token] - The string or array of strings to validate the incoming bearer token against.
7576
* @param {Function} [options.verifyToken] - The function to verify the token.
@@ -83,7 +84,7 @@ type BearerAuthOptions =
8384
* @param {string | object | MessageFunction} [options.invalidAuthenticationHeader.wwwAuthenticateHeader="Bearer error=\"invalid_request\""] - The response header value for the WWW-Authenticate header when authentication header is invalid.
8485
* @param {string | object | MessageFunction} [options.invalidToken.message="Unauthorized"] - The invalid token message.
8586
* @param {string | object | MessageFunction} [options.invalidToken.wwwAuthenticateHeader="Bearer error=\"invalid_token\""] - The response header value for the WWW-Authenticate header when token is invalid.
86-
* @returns {MiddlewareHandler} The middleware handler function.
87+
* @returns {MiddlewareHandler<E>} The middleware handler function.
8788
* @throws {Error} If neither "token" nor "verifyToken" options are provided.
8889
* @throws {HTTPException} If authentication fails, with 401 status code for missing or invalid token, or 400 status code for invalid request.
8990
*
@@ -100,7 +101,9 @@ type BearerAuthOptions =
100101
* })
101102
* ```
102103
*/
103-
export const bearerAuth = (options: BearerAuthOptions): MiddlewareHandler => {
104+
export const bearerAuth = <E extends Env = Env>(
105+
options: BearerAuthOptions<E>
106+
): MiddlewareHandler<E> => {
104107
if (!('token' in options || 'verifyToken' in options)) {
105108
throw new Error('bearer auth middleware requires options for "token"')
106109
}

0 commit comments

Comments
 (0)