feat(bearer-auth): make bearerAuth generic for typed context in verifyToken (#4913)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(bearer-auth): make bearerAuth generic for typed context in verify token * test(bearer-auth): add type tests * docs(bearer-auth): add tsdocs
authored by Justin Naismith · committed by GitHub · parent ff7522f · Browse files · 2 files·+33 added−5 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+33 added−5 removed
- tests:+25 added−0 removed
- other:+8 added−5 removed
Provenance
- Commit
48a7ccb- Tree
ab6a7f9- Author
Justin Naismith <justin@nais.dev>- Committer
GitHub <noreply@github.com>- Parent
ff7522f
2 files changed+33 added−5 removed
modified:src/middleware/bearer-auth/index.test.ts+25 added
1+import { expectTypeOf } from 'vitest'2 import { Hono } from '../../hono'3+import type { Context, MiddlewareHandler } from '../../index'4 import { bearerAuth } from '.'5 6 describe('Bearer Auth by Middleware', () => {7 let app: Hono975 unmodified lines983 expect(res.status).toBe(400)984 expect(handlerExecuted).toBeFalsy()985 })986 })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_KEY998+ },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+})modified:src/middleware/bearer-auth/index.ts+8 added-5 removed
3 unmodified lines4 */5 6 import type { Context } from '../../context'7 import { HTTPException } from '../../http-exception'8-import type { MiddlewareHandler } from '../../types'8+import type { Env, MiddlewareHandler } from '../../types'9 import { timingSafeEqual } from '../../utils/buffer'10 import type { ContentfulStatusCode } from '../../utils/http-status'11 12 const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'5 unmodified lines18 wwwAuthenticateHeader?: string | object | MessageFunction19 message?: string | object | MessageFunction20 }21 22-type BearerAuthOptions =22+type BearerAuthOptions<E extends Env = Env> =23 | {24 token: string | string[]25 realm?: string26 prefix?: string18 unmodified lines45 | {46 realm?: string47 prefix?: string48 headerName?: string49- verifyToken: (token: string, c: Context) => boolean | Promise<boolean>49+ verifyToken: (token: string, c: Context<E>) => boolean | Promise<boolean>50 hashFunction?: Function51 /**52 * @deprecated Use noAuthenticationHeader.message instead53 */15 unmodified lines69 * Bearer Auth Middleware for Hono.70 *71 * @see {@link https://hono.dev/docs/middleware/builtin/bearer-auth}72 *73+ * @template E - The environment type.74 * @param {BearerAuthOptions} options - The options for the bearer authentication middleware.75 * @param {string | string[]} [options.token] - The string or array of strings to validate the incoming bearer token against.76 * @param {Function} [options.verifyToken] - The function to verify the token.77 * @param {string} [options.realm=""] - The domain name of the realm, as part of the returned WWW-Authenticate challenge header.5 unmodified lines83 * @param {string | object | MessageFunction} [options.invalidAuthenticationHeader.message="Bad Request"] - The invalid authentication header message.84 * @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.85 * @param {string | object | MessageFunction} [options.invalidToken.message="Unauthorized"] - The invalid token message.86 * @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.88 * @throws {Error} If neither "token" nor "verifyToken" options are provided.89 * @throws {HTTPException} If authentication fails, with 401 status code for missing or invalid token, or 400 status code for invalid request.90 *91 * @example8 unmodified lines100 * return c.json({ message: 'You are authorized' })101 * })102 * ```103 */103-export const bearerAuth = (options: BearerAuthOptions): MiddlewareHandler => {104+export const bearerAuth = <E extends Env = Env>(105+ options: BearerAuthOptions<E>106+): MiddlewareHandler<E> => {107 if (!('token' in options || 'verifyToken' in options)) {108 throw new Error('bearer auth middleware requires options for "token"')109 }110 if (!options.realm) {111 unmodified lines