Skip to content
Myr

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

2 files+33 added−5 removed

modified:src/middleware/bearer-auth/index.test.ts+25 added
1import { expectTypeOf } from 'vitest'2import { Hono } from '../../hono'3import type { Context, MiddlewareHandler } from '../../index'4import { bearerAuth } from '.'56describe('Bearer Auth by Middleware', () => {7 let app: Hono
975 unmodified lines
983 expect(res.status).toBe(400)984 expect(handlerExecuted).toBeFalsy()985 })986})987988describe('Bearer Auth types', () => {989 interface TestEnv {990 Bindings: { API_KEY: string }991 }992993 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 })10021003 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 lines
4 */56import type { Context } from '../../context'7import { HTTPException } from '../../http-exception'8import type { MiddlewareHandler } from '../../types'8import type { Env, MiddlewareHandler } from '../../types'9import { timingSafeEqual } from '../../utils/buffer'10import type { ContentfulStatusCode } from '../../utils/http-status'1112const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'
5 unmodified lines
18 wwwAuthenticateHeader?: string | object | MessageFunction19 message?: string | object | MessageFunction20}2122type BearerAuthOptions =22type BearerAuthOptions<E extends Env = Env> =23 | {24 token: string | string[]25 realm?: string26 prefix?: string
18 unmodified lines
45 | {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 lines
69 * 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 lines
83 * @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 * @example
8 unmodified lines
100 * return c.json({ message: 'You are authorized' })101 * })102 * ```103 */103export const bearerAuth = (options: BearerAuthOptions): MiddlewareHandler => {104export 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