Skip to content
Myr

Merge pull request #3394 from honojs/next

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Next

authored by Yusuke Wada · committed by GitHub · parents f9a23a9, 743f66c · Browse files · 28 files+1290 added−246 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

28 files+1290 added−246 removed

  • tests:+886 added−152 removed
  • other:+404 added−94 removed

28 files+1290 added−246 removed

modified:runtime_tests/node/index.test.ts+46 added-3 removed
1import type { Server } from 'node:http'1import { createAdaptorServer } from '@hono/node-server'2import { createAdaptorServer, serve } from '@hono/node-server'3import request from 'supertest'4import { Hono } from '../../src'5import { Context } from '../../src/context'6import { env, getRuntimeKey } from '../../src/helper/adapter'7import { basicAuth } from '../../src/middleware/basic-auth'8import { jwt } from '../../src/middleware/jwt'8import { HonoRequest } from '../../src/request'9import { compress } from '../../src/middleware/compress'10import { stream, streamSSE } from '../../src/helper/streaming'11import type { AddressInfo } from 'node:net'1213// Test only minimal patterns.14// See <https://github.com/honojs/node-server> for more tests and information.15
23 unmodified lines
39})4041describe('Environment Variables', () => {42 it('Should return the environment variable', async () => {41 const c = new Context(new HonoRequest(new Request('http://localhost/')))43 const c = new Context(new Request('http://localhost/'))44 const { NAME } = env<{ NAME: string }>(c)45 expect(NAME).toBe('Node')46 })47})
156 unmodified lines
204 expect(res.text).toBe('Hello')205 expect(aborted).toBe(false)206 })207})208209describe('compress', async () => {210 const cssContent = Array.from({ length: 60 }, () => 'body { color: red; }').join('\n')211 const [externalServer, serverInfo] = await new Promise<[Server, AddressInfo]>((resolve) => {212 const externalApp = new Hono()213 externalApp.get('/style.css', (c) =>214 c.text(cssContent, {215 headers: {216 'Content-Type': 'text/css',217 },218 })219 )220 const server = serve(221 {222 fetch: externalApp.fetch,223 port: 0,224 },225 (serverInfo) => {226 resolve([server as Server, serverInfo])227 }228 )229 })230231 const app = new Hono()232 app.use(compress())233 app.get('/fetch/:file', (c) => {234 return fetch(`http://${serverInfo.address}:${serverInfo.port}/${c.req.param('file')}`)235 })236 const server = createAdaptorServer(app)237238 afterAll(() => {239 externalServer.close()240 })241242 it('Should be compressed a fetch response', async () => {243 const res = await request(server).get('/fetch/style.css')244 expect(res.status).toBe(200)245 expect(res.headers['content-encoding']).toBe('gzip')246 expect(res.text).toBe(cssContent)247 })248})
modified:src/adapter/bun/websocket.ts+6 added-7 removed
modified:src/adapter/cloudflare-pages/handler.test.ts+12 added
228 unmodified lines
229 const eventContext = createEventContext({ request, next })230 await expect(handler(eventContext)).rejects.toThrowError('Something went wrong')231 expect(next).not.toHaveBeenCalled()232 })233234 it('Should set the data in eventContext.data', async () => {235 const next = vi.fn()236 const eventContext = createEventContext({ next })237 const handler = handleMiddleware(async (c, next) => {238 c.env.eventContext.data.user = 'Joe'239 await next()240 })241 expect(eventContext.data.user).toBeUndefined()242 await handler(eventContext)243 expect(eventContext.data.user).toBe('Joe')244 })245})246247describe('serveStatic()', () => {248 it('Should pass the raw request to ASSETS.fetch', async () => {
36 unmodified lines
modified:src/adapter/cloudflare-pages/handler.ts+12 added-4 removed
7 unmodified lines
8// eslint-disable-next-line @typescript-eslint/no-explicit-any9type Params<P extends string = any> = Record<P, string | string[]>1011// eslint-disable-next-line @typescript-eslint/no-explicit-any12export type EventContext<Env = {}, P extends string = any, Data = {}> = {12export type EventContext<Env = {}, P extends string = any, Data = Record<string, unknown>> = {13 request: Request14 functionPath: string15 waitUntil: (promise: Promise<unknown>) => void16 passThroughOnException: () => void
25 unmodified lines
42 )43 }4445// eslint-disable-next-line @typescript-eslint/no-explicit-any46export function handleMiddleware<E extends Env = any, P extends string = any, I extends Input = {}>(47 middleware: MiddlewareHandler<E, P, I>46export function handleMiddleware<E extends Env = {}, P extends string = any, I extends Input = {}>(47 middleware: MiddlewareHandler<48 E & {49 Bindings: {50 eventContext: EventContext51 }52 },53 P,54 I55 >56): PagesFunction<E['Bindings']> {57 return async (executionCtx) => {58 const context = new Context(executionCtx.request, {51 env: executionCtx.env,59 env: { ...executionCtx.env, eventContext: executionCtx },60 executionCtx,61 })6263 let response: Response | void = undefined
57 unmodified lines
modified:src/adapter/cloudflare-workers/websocket.ts+2 added-2 removed
modified:src/adapter/deno/websocket.ts+2 added-2 removed
18 unmodified lines
19 */20 idleTimeout?: number21}2223export const upgradeWebSocket: UpgradeWebSocket<UpgradeWebSocketOptions> =23export const upgradeWebSocket: UpgradeWebSocket<WebSocket, UpgradeWebSocketOptions> =24 (createEvents, options) => async (c, next) => {25 if (c.req.header('upgrade') !== 'websocket') {26 return await next()27 }2829 const events = await createEvents(c)30 const { response, socket } = Deno.upgradeWebSocket(c.req.raw, options || {})3132 const wsContext: WSContext = {32 const wsContext: WSContext<WebSocket> = {33 binaryType: 'arraybuffer',34 close: (code, reason) => socket.close(code, reason),35 get protocol() {36 return socket.protocol
15 unmodified lines
deleted:src/helper/streaming/sse.test.ts-148 removed
1import { Context } from '../../context'2import { streamSSE } from '.'34describe('SSE Streaming helper', () => {5 const req = new Request('http://localhost/')6 let c: Context7 beforeEach(() => {8 c = new Context(req)9 })1011 it('Check streamSSE Response', async () => {12 let spy13 const res = streamSSE(c, async (stream) => {14 spy = vi.spyOn(stream, 'close').mockImplementation(async () => {})1516 let id = 017 const maxIterations = 51819 while (id < maxIterations) {20 const message = `Message\nIt is ${id}`21 await stream.writeSSE({ data: message, event: 'time-update', id: String(id++) })22 await stream.sleep(10)23 }24 })2526 expect(res).not.toBeNull()27 expect(res.status).toBe(200)28 expect(res.headers.get('Transfer-Encoding')).toEqual('chunked')29 expect(res.headers.get('Content-Type')).toEqual('text/event-stream')30 expect(res.headers.get('Cache-Control')).toEqual('no-cache')31 expect(res.headers.get('Connection')).toEqual('keep-alive')3233 if (!res.body) {34 throw new Error('Body is null')35 }36 const reader = res.body.getReader()37 const decoder = new TextDecoder()38 for (let i = 0; i < 5; i++) {39 const { value } = await reader.read()40 const decodedValue = decoder.decode(value)4142 // Check the structure and content of the SSE message43 let expectedValue = 'event: time-update\n'44 expectedValue += 'data: Message\n'45 expectedValue += `data: It is ${i}\n`46 expectedValue += `id: ${i}\n\n`47 expect(decodedValue).toBe(expectedValue)48 }49 await new Promise((resolve) => setTimeout(resolve, 100))50 expect(spy).toHaveBeenCalled()51 })5253 it('Check streamSSE Response if aborted by client', async () => {54 let aborted = false55 const res = streamSSE(c, async (stream) => {56 stream.onAbort(() => {57 aborted = true58 })59 for (let i = 0; i < 3; i++) {60 await stream.writeSSE({61 data: `Message ${i}`,62 })63 await stream.sleep(1)64 }65 })66 if (!res.body) {67 throw new Error('Body is null')68 }69 const reader = res.body.getReader()70 const { value } = await reader.read()71 expect(value).toEqual(new TextEncoder().encode('data: Message 0\n\n'))72 reader.cancel()73 expect(aborted).toBeTruthy()74 })7576 it('Check streamSSE Response if aborted by abort signal', async () => {77 const ac = new AbortController()78 const req = new Request('http://localhost/', { signal: ac.signal })79 const c = new Context(req)8081 let aborted = false82 const res = streamSSE(c, async (stream) => {83 stream.onAbort(() => {84 aborted = true85 })86 for (let i = 0; i < 3; i++) {87 await stream.writeSSE({88 data: `Message ${i}`,89 })90 await stream.sleep(1)91 }92 })93 if (!res.body) {94 throw new Error('Body is null')95 }96 const reader = res.body.getReader()97 const { value } = await reader.read()98 expect(value).toEqual(new TextEncoder().encode('data: Message 0\n\n'))99 ac.abort()100 expect(aborted).toBeTruthy()101 })102103 it('Should include retry in the SSE message', async () => {104 const retryTime = 3000 // 3 seconds105 const res = streamSSE(c, async (stream) => {106 await stream.writeSSE({107 data: 'This is a test message',108 retry: retryTime,109 })110 })111112 expect(res).not.toBeNull()113 expect(res.status).toBe(200)114115 if (!res.body) {116 throw new Error('Body is null')117 }118 const reader = res.body.getReader()119 const decoder = new TextDecoder()120 const { value } = await reader.read()121 const decodedValue = decoder.decode(value)122123 // Check if the retry parameter is included in the SSE message124 const expectedRetryValue = `retry: ${retryTime}\n\n`125 expect(decodedValue).toContain(expectedRetryValue)126 })127128 it('Check stream Response if error occurred', async () => {129 const onError = vi.fn()130 const res = streamSSE(131 c,132 async () => {133 throw new Error('Test error')134 },135 onError136 )137 if (!res.body) {138 throw new Error('Body is null')139 }140 const reader = res.body.getReader()141 const decoder = new TextDecoder()142 const { value } = await reader.read()143 const decodedValue = decoder.decode(value)144 expect(decodedValue).toBe('event: error\ndata: Test error\n\n')145 expect(onError).toBeCalledTimes(1)146 expect(onError).toBeCalledWith(new Error('Test error'), expect.anything()) // 2nd argument is StreamingApi instance147 })148})
added:src/helper/streaming/sse.test.tsx+236 added
1/** @jsxImportSource ../../jsx */2import { ErrorBoundary } from '../../jsx'3import { Context } from '../../context'4import { streamSSE } from '.'56describe('SSE Streaming helper', () => {7 const req = new Request('http://localhost/')8 let c: Context9 beforeEach(() => {10 c = new Context(req)11 })1213 it('Check streamSSE Response', async () => {14 let spy15 const res = streamSSE(c, async (stream) => {16 spy = vi.spyOn(stream, 'close').mockImplementation(async () => {})1718 let id = 019 const maxIterations = 52021 while (id < maxIterations) {22 const message = `Message\nIt is ${id}`23 await stream.writeSSE({ data: message, event: 'time-update', id: String(id++) })24 await stream.sleep(10)25 }26 })2728 expect(res).not.toBeNull()29 expect(res.status).toBe(200)30 expect(res.headers.get('Transfer-Encoding')).toEqual('chunked')31 expect(res.headers.get('Content-Type')).toEqual('text/event-stream')32 expect(res.headers.get('Cache-Control')).toEqual('no-cache')33 expect(res.headers.get('Connection')).toEqual('keep-alive')3435 if (!res.body) {36 throw new Error('Body is null')37 }38 const reader = res.body.getReader()39 const decoder = new TextDecoder()40 for (let i = 0; i < 5; i++) {41 const { value } = await reader.read()42 const decodedValue = decoder.decode(value)4344 // Check the structure and content of the SSE message45 let expectedValue = 'event: time-update\n'46 expectedValue += 'data: Message\n'47 expectedValue += `data: It is ${i}\n`48 expectedValue += `id: ${i}\n\n`49 expect(decodedValue).toBe(expectedValue)50 }51 await new Promise((resolve) => setTimeout(resolve, 100))52 expect(spy).toHaveBeenCalled()53 })5455 it('Check streamSSE Response if aborted by client', async () => {56 let aborted = false57 const res = streamSSE(c, async (stream) => {58 stream.onAbort(() => {59 aborted = true60 })61 for (let i = 0; i < 3; i++) {62 await stream.writeSSE({63 data: `Message ${i}`,64 })65 await stream.sleep(1)66 }67 })68 if (!res.body) {69 throw new Error('Body is null')70 }71 const reader = res.body.getReader()72 const { value } = await reader.read()73 expect(value).toEqual(new TextEncoder().encode('data: Message 0\n\n'))74 reader.cancel()75 expect(aborted).toBeTruthy()76 })7778 it('Check streamSSE Response if aborted by abort signal', async () => {79 const ac = new AbortController()80 const req = new Request('http://localhost/', { signal: ac.signal })81 const c = new Context(req)8283 let aborted = false84 const res = streamSSE(c, async (stream) => {85 stream.onAbort(() => {86 aborted = true87 })88 for (let i = 0; i < 3; i++) {89 await stream.writeSSE({90 data: `Message ${i}`,91 })92 await stream.sleep(1)93 }94 })95 if (!res.body) {96 throw new Error('Body is null')97 }98 const reader = res.body.getReader()99 const { value } = await reader.read()100 expect(value).toEqual(new TextEncoder().encode('data: Message 0\n\n'))101 ac.abort()102 expect(aborted).toBeTruthy()103 })104105 it('Should include retry in the SSE message', async () => {106 const retryTime = 3000 // 3 seconds107 const res = streamSSE(c, async (stream) => {108 await stream.writeSSE({109 data: 'This is a test message',110 retry: retryTime,111 })112 })113114 expect(res).not.toBeNull()115 expect(res.status).toBe(200)116117 if (!res.body) {118 throw new Error('Body is null')119 }120 const reader = res.body.getReader()121 const decoder = new TextDecoder()122 const { value } = await reader.read()123 const decodedValue = decoder.decode(value)124125 // Check if the retry parameter is included in the SSE message126 const expectedRetryValue = `retry: ${retryTime}\n\n`127 expect(decodedValue).toContain(expectedRetryValue)128 })129130 it('Check stream Response if error occurred', async () => {131 const onError = vi.fn()132 const res = streamSSE(133 c,134 async () => {135 throw new Error('Test error')136 },137 onError138 )139 if (!res.body) {140 throw new Error('Body is null')141 }142 const reader = res.body.getReader()143 const decoder = new TextDecoder()144 const { value } = await reader.read()145 const decodedValue = decoder.decode(value)146 expect(decodedValue).toBe('event: error\ndata: Test error\n\n')147 expect(onError).toBeCalledTimes(1)148 expect(onError).toBeCalledWith(new Error('Test error'), expect.anything()) // 2nd argument is StreamingApi instance149 })150151 it('Check streamSSE Response via Promise<string>', async () => {152 const res = streamSSE(c, async (stream) => {153 await stream.writeSSE({ data: Promise.resolve('Async Message') })154 })155156 expect(res).not.toBeNull()157 expect(res.status).toBe(200)158159 if (!res.body) {160 throw new Error('Body is null')161 }162 const reader = res.body.getReader()163 const decoder = new TextDecoder()164 const { value } = await reader.read()165 const decodedValue = decoder.decode(value)166 expect(decodedValue).toBe('data: Async Message\n\n')167 })168169 it('Check streamSSE Response via JSX.Element', async () => {170 const res = streamSSE(c, async (stream) => {171 await stream.writeSSE({ data: <div>Hello</div> })172 })173174 expect(res).not.toBeNull()175 expect(res.status).toBe(200)176177 if (!res.body) {178 throw new Error('Body is null')179 }180 const reader = res.body.getReader()181 const decoder = new TextDecoder()182 const { value } = await reader.read()183 const decodedValue = decoder.decode(value)184 expect(decodedValue).toBe('data: <div>Hello</div>\n\n')185 })186187 it('Check streamSSE Response via ErrorBoundary in success case', async () => {188 const AsyncComponent = async () => Promise.resolve(<div>Async Hello</div>)189 const res = streamSSE(c, async (stream) => {190 await stream.writeSSE({191 data: (192 <ErrorBoundary fallback={<div>Error</div>}>193 <AsyncComponent />194 </ErrorBoundary>195 ),196 })197 })198199 expect(res).not.toBeNull()200 expect(res.status).toBe(200)201202 if (!res.body) {203 throw new Error('Body is null')204 }205 const reader = res.body.getReader()206 const decoder = new TextDecoder()207 const { value } = await reader.read()208 const decodedValue = decoder.decode(value)209 expect(decodedValue).toBe('data: <div>Async Hello</div>\n\n')210 })211212 it('Check streamSSE Response via ErrorBoundary in error case', async () => {213 const AsyncComponent = async () => Promise.reject()214 const res = streamSSE(c, async (stream) => {215 await stream.writeSSE({216 data: (217 <ErrorBoundary fallback={<div>Error</div>}>218 <AsyncComponent />219 </ErrorBoundary>220 ),221 })222 })223224 expect(res).not.toBeNull()225 expect(res.status).toBe(200)226227 if (!res.body) {228 throw new Error('Body is null')229 }230 const reader = res.body.getReader()231 const decoder = new TextDecoder()232 const { value } = await reader.read()233 const decodedValue = decoder.decode(value)234 expect(decodedValue).toBe('data: <div>Error</div>\n\n')235 })236})
modified:src/helper/streaming/sse.ts+5 added-3 removed
1import type { Context } from '../../context'2import { StreamingApi } from '../../utils/stream'3import { HtmlEscapedCallbackPhase, resolveCallback } from '../../utils/html'45export interface SSEMessage {5 data: string6 data: string | Promise<string>7 event?: string8 id?: string9 retry?: number10}
3 unmodified lines
14 super(writable, readable)15 }1617 async writeSSE(message: SSEMessage) {17 const data = message.data18 const data = await resolveCallback(message.data, HtmlEscapedCallbackPhase.Stringify, false, {})19 const dataLines = (data as string)20 .split('\n')21 .map((line) => {22 return `data: ${line}`23 })
1 unmodified line
2526 const sseData =27 [28 message.event && `event: ${message.event}`,27 data,29 dataLines,30 message.id && `id: ${message.id}`,31 message.retry && `retry: ${message.retry}`,32 ]33 .filter(Boolean)
56 unmodified lines
modified:src/helper/websocket/index.ts+10 added-10 removed
8 unmodified lines
910/**11 * WebSocket Event Listeners type12 */13export interface WSEvents {14 onOpen?: (evt: Event, ws: WSContext) => void15 onMessage?: (evt: MessageEvent<WSMessageReceive>, ws: WSContext) => void16 onClose?: (evt: CloseEvent, ws: WSContext) => void17 onError?: (evt: Event, ws: WSContext) => void13export interface WSEvents<T = unknown> {14 onOpen?: (evt: Event, ws: WSContext<T>) => void15 onMessage?: (evt: MessageEvent<WSMessageReceive>, ws: WSContext<T>) => void16 onClose?: (evt: CloseEvent, ws: WSContext<T>) => void17 onError?: (evt: Event, ws: WSContext<T>) => void18}1920/**21 * Upgrade WebSocket Type22 */23export type UpgradeWebSocket<T = any> = (24 createEvents: (c: Context) => WSEvents | Promise<WSEvents>,25 options?: T23export type UpgradeWebSocket<T = unknown, U = any> = (24 createEvents: (c: Context) => WSEvents<T> | Promise<WSEvents<T>>,25 options?: U26) => MiddlewareHandler<27 any,28 string,29 {
2 unmodified lines
32>3334export type WSReadyState = 0 | 1 | 2 | 33536export type WSContext = {36export type WSContext<T = unknown> = {37 send(38 source: string | ArrayBuffer | Uint8Array,39 options?: {40 compress: boolean41 }42 ): void43 raw?: unknown43 raw?: T44 binaryType: BinaryType45 readyState: WSReadyState46 url: URL | null47 protocol: string | null
10 unmodified lines
modified:src/middleware/basic-auth/index.test.ts+92 added
81 unmodified lines
82 })83 return auth(c, next)84 })8586 app.use(87 '/auth-custom-invalid-user-message-string/*',88 basicAuth({89 username,90 password,91 invalidUserMessage: 'Custom unauthorized message as string',92 })93 )9495 app.use(96 '/auth-custom-invalid-user-message-object/*',97 basicAuth({98 username,99 password,100 invalidUserMessage: { message: 'Custom unauthorized message as object' },101 })102 )103104 app.use(105 '/auth-custom-invalid-user-message-function-string/*',106 basicAuth({107 username,108 password,109 invalidUserMessage: () => 'Custom unauthorized message as function string',110 })111 )112113 app.use(114 '/auth-custom-invalid-user-message-function-object/*',115 basicAuth({116 username,117 password,118 invalidUserMessage: () => ({ message: 'Custom unauthorized message as function object' }),119 })120 )121122 app.get('/auth/*', (c) => {123 handlerExecuted = true124 return c.text('auth')125 })
19 unmodified lines
145 handlerExecuted = true146 return c.text('verify-user')147 })148149 app.get('/auth-custom-invalid-user-message-string/*', (c) => {150 handlerExecuted = true151 return c.text('auth')152 })153 app.get('/auth-custom-invalid-user-message-object/*', (c) => {154 handlerExecuted = true155 return c.text('auth')156 })157 app.get('/auth-custom-invalid-user-message-function-string/*', (c) => {158 handlerExecuted = true159 return c.text('auth')160 })161162 app.get('/auth-custom-invalid-user-message-function-object/*', (c) => {163 handlerExecuted = true164 return c.text('auth')165 })166167 it('Should not authorize', async () => {168 const req = new Request('http://localhost/auth/a')169 const res = await app.request(req)170 expect(res).not.toBeNull()
108 unmodified lines
279 expect(res).not.toBeNull()280 expect(res.status).toBe(401)281 expect(await res.text()).toBe('Unauthorized')282 })283284 it('Should not authorize - custom invalid user message as string', async () => {285 const req = new Request('http://localhost/auth-custom-invalid-user-message-string')286 const res = await app.request(req)287 expect(res).not.toBeNull()288 expect(res.status).toBe(401)289 expect(handlerExecuted).toBeFalsy()290 expect(await res.text()).toBe('Custom unauthorized message as string')291 })292293 it('Should not authorize - custom invalid user message as object', async () => {294 const req = new Request('http://localhost/auth-custom-invalid-user-message-object')295 const res = await app.request(req)296 expect(res).not.toBeNull()297 expect(res.status).toBe(401)298 expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')299 expect(handlerExecuted).toBeFalsy()300 expect(await res.text()).toBe('{"message":"Custom unauthorized message as object"}')301 })302303 it('Should not authorize - custom invalid user message as function string', async () => {304 const req = new Request('http://localhost/auth-custom-invalid-user-message-function-string')305 const res = await app.request(req)306 expect(res).not.toBeNull()307 expect(res.status).toBe(401)308 expect(handlerExecuted).toBeFalsy()309 expect(await res.text()).toBe('Custom unauthorized message as function string')310 })311312 it('Should not authorize - custom invalid user message as function object', async () => {313 const req = new Request('http://localhost/auth-custom-invalid-user-message-function-object')314 const res = await app.request(req)315 expect(res).not.toBeNull()316 expect(res.status).toBe(401)317 expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')318 expect(handlerExecuted).toBeFalsy()319 expect(await res.text()).toBe('{"message":"Custom unauthorized message as function object"}')320 })321})
modified:src/middleware/basic-auth/index.ts+29 added-7 removed
7 unmodified lines
8import type { MiddlewareHandler } from '../../types'9import { auth } from '../../utils/basic-auth'10import { timingSafeEqual } from '../../utils/buffer'1112type MessageFunction = (c: Context) => string | object | Promise<string | object>1314type BasicAuthOptions =15 | {16 username: string17 password: string18 realm?: string19 hashFunction?: Function20 invalidUserMessage?: string | object | MessageFunction21 }22 | {23 verifyUser: (username: string, password: string, c: Context) => boolean | Promise<boolean>24 realm?: string25 hashFunction?: Function26 invalidUserMessage?: string | object | MessageFunction27 }2829/**30 * Basic Auth Middleware for Hono.
5 unmodified lines
36 * @param {string} options.password - The password for authentication.37 * @param {string} [options.realm="Secure Area"] - The realm attribute for the WWW-Authenticate header.38 * @param {Function} [options.hashFunction] - The hash function used for secure comparison.39 * @param {Function} [options.verifyUser] - The function to verify user credentials.40 * @param {string | object | MessageFunction} [options.invalidUserMessage="Unauthorized"] - The invalid user message.41 * @returns {MiddlewareHandler} The middleware handler function.42 * @throws {HTTPException} If neither "username and password" nor "verifyUser" options are provided.43 *44 * @example
29 unmodified lines
74 if (!options.realm) {75 options.realm = 'Secure Area'76 }7778 if (!options.invalidUserMessage) {79 options.invalidUserMessage = 'Unauthorized'80 }8182 if (usernamePasswordInOptions) {83 users.unshift({ username: options.username, password: options.password })84 }85
17 unmodified lines
103 }104 }105 }106 }98 const res = new Response('Unauthorized', {99 status: 401,100 headers: {101 'WWW-Authenticate': 'Basic realm="' + options.realm?.replace(/"/g, '\\"') + '"',102 },103 })104 throw new HTTPException(401, { res })107 // Invalid user.108 const status = 401109 const headers = {110 'WWW-Authenticate': 'Basic realm="' + options.realm?.replace(/"/g, '\\"') + '"',111 }112 const responseMessage =113 typeof options.invalidUserMessage === 'function'114 ? await options.invalidUserMessage(ctx)115 : options.invalidUserMessage116 const res =117 typeof responseMessage === 'string'118 ? new Response(responseMessage, { status, headers })119 : new Response(JSON.stringify(responseMessage), {120 status,121 headers: {122 ...headers,123 'content-type': 'application/json; charset=UTF-8',124 },125 })126 throw new HTTPException(status, { res })127 }128}
modified:src/middleware/bearer-auth/index.test.ts+297 added
66 unmodified lines
67 app.get('/auth-custom-header/*', (c) => {68 handlerExecuted = true69 return c.text('auth-custom-header')70 })7172 app.use(73 '/auth-custom-no-authentication-header-message-string/*',74 bearerAuth({75 token,76 noAuthenticationHeaderMessage: 'Custom no authentication header message as string',77 })78 )79 app.get('/auth-custom-no-authentication-header-message-string/*', (c) => {80 handlerExecuted = true81 return c.text('auth')82 })8384 app.use(85 '/auth-custom-no-authentication-header-message-object/*',86 bearerAuth({87 token,88 noAuthenticationHeaderMessage: {89 message: 'Custom no authentication header message as object',90 },91 })92 )93 app.get('/auth-custom-no-authentication-header-message-object/*', (c) => {94 handlerExecuted = true95 return c.text('auth')96 })9798 app.use(99 '/auth-custom-no-authentication-header-message-function-string/*',100 bearerAuth({101 token,102 noAuthenticationHeaderMessage: () =>103 'Custom no authentication header message as function string',104 })105 )106 app.get('/auth-custom-no-authentication-header-message-function-string/*', (c) => {107 handlerExecuted = true108 return c.text('auth')109 })110111 app.use(112 '/auth-custom-no-authentication-header-message-function-object/*',113 bearerAuth({114 token,115 noAuthenticationHeaderMessage: () => ({116 message: 'Custom no authentication header message as function object',117 }),118 })119 )120 app.get('/auth-custom-no-authentication-header-message-function-object/*', (c) => {121 handlerExecuted = true122 return c.text('auth')123 })124125 app.use(126 '/auth-custom-invalid-authentication-header-message-string/*',127 bearerAuth({128 token,129 invalidAuthenticationHeaderMessage:130 'Custom invalid authentication header message as string',131 })132 )133 app.get('/auth-custom-invalid-authentication-header-message-string/*', (c) => {134 handlerExecuted = true135 return c.text('auth')136 })137138 app.use(139 '/auth-custom-invalid-authentication-header-message-object/*',140 bearerAuth({141 token,142 invalidAuthenticationHeaderMessage: {143 message: 'Custom invalid authentication header message as object',144 },145 })146 )147 app.get('/auth-custom-invalid-authentication-header-message-object/*', (c) => {148 handlerExecuted = true149 return c.text('auth')150 })151152 app.use(153 '/auth-custom-invalid-authentication-header-message-function-string/*',154 bearerAuth({155 token,156 invalidAuthenticationHeaderMessage: () =>157 'Custom invalid authentication header message as function string',158 })159 )160 app.get('/auth-custom-invalid-authentication-header-message-function-string/*', (c) => {161 handlerExecuted = true162 return c.text('auth')163 })164165 app.use(166 '/auth-custom-invalid-authentication-header-message-function-object/*',167 bearerAuth({168 token,169 invalidAuthenticationHeaderMessage: () => ({170 message: 'Custom invalid authentication header message as function object',171 }),172 })173 )174 app.get('/auth-custom-invalid-authentication-header-message-function-object/*', (c) => {175 handlerExecuted = true176 return c.text('auth')177 })178179 app.use(180 '/auth-custom-invalid-token-message-string/*',181 bearerAuth({182 token,183 invalidTokenMessage: 'Custom invalid token message as string',184 })185 )186 app.get('/auth-custom-invalid-token-message-string/*', (c) => {187 handlerExecuted = true188 return c.text('auth')189 })190191 app.use(192 '/auth-custom-invalid-token-message-object/*',193 bearerAuth({194 token,195 invalidTokenMessage: { message: 'Custom invalid token message as object' },196 })197 )198 app.get('/auth-custom-invalid-token-message-object/*', (c) => {199 handlerExecuted = true200 return c.text('auth')201 })202203 app.use(204 '/auth-custom-invalid-token-message-function-string/*',205 bearerAuth({206 token,207 invalidTokenMessage: () => 'Custom invalid token message as function string',208 })209 )210 app.get('/auth-custom-invalid-token-message-function-string/*', (c) => {211 handlerExecuted = true212 return c.text('auth')213 })214215 app.use(216 '/auth-custom-invalid-token-message-function-object/*',217 bearerAuth({218 token,219 invalidTokenMessage: () => ({220 message: 'Custom invalid token message as function object',221 }),222 })223 )224 app.get('/auth-custom-invalid-token-message-function-object/*', (c) => {225 handlerExecuted = true226 return c.text('auth')227 })228 })229230 it('Should authorize', async () => {231 const req = new Request('http://localhost/auth/a')
152 unmodified lines
384 expect(handlerExecuted).toBeFalsy()385 expect(res.status).toBe(401)386 expect(await res.text()).toBe('Unauthorized')387 })388389 it('Should not authorize - custom no authorization header message as string', async () => {390 const req = new Request('http://localhost/auth-custom-no-authentication-header-message-string')391 const res = await app.request(req)392 expect(res).not.toBeNull()393 expect(res.status).toBe(401)394 expect(handlerExecuted).toBeFalsy()395 expect(await res.text()).toBe('Custom no authentication header message as string')396 })397398 it('Should not authorize - custom no authorization header message as object', async () => {399 const req = new Request('http://localhost/auth-custom-no-authentication-header-message-object')400 const res = await app.request(req)401 expect(res).not.toBeNull()402 expect(res.status).toBe(401)403 expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')404 expect(handlerExecuted).toBeFalsy()405 expect(await res.text()).toBe('{"message":"Custom no authentication header message as object"}')406 })407408 it('Should not authorize - custom no authorization header message as function string', async () => {409 const req = new Request(410 'http://localhost/auth-custom-no-authentication-header-message-function-string'411 )412 const res = await app.request(req)413 expect(res).not.toBeNull()414 expect(res.status).toBe(401)415 expect(handlerExecuted).toBeFalsy()416 expect(await res.text()).toBe('Custom no authentication header message as function string')417 })418419 it('Should not authorize - custom no authorization header message as function object', async () => {420 const req = new Request(421 'http://localhost/auth-custom-no-authentication-header-message-function-object'422 )423 const res = await app.request(req)424 expect(res).not.toBeNull()425 expect(res.status).toBe(401)426 expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')427 expect(handlerExecuted).toBeFalsy()428 expect(await res.text()).toBe(429 '{"message":"Custom no authentication header message as function object"}'430 )431 })432433 it('Should not authorize - custom invalid authentication header message as string', async () => {434 const req = new Request(435 'http://localhost/auth-custom-invalid-authentication-header-message-string'436 )437 req.headers.set('Authorization', 'Beare abcdefg12345-._~+/=')438 const res = await app.request(req)439 expect(res).not.toBeNull()440 expect(res.status).toBe(400)441 expect(handlerExecuted).toBeFalsy()442 expect(await res.text()).toBe('Custom invalid authentication header message as string')443 })444445 it('Should not authorize - custom invalid authentication header message as object', async () => {446 const req = new Request(447 'http://localhost/auth-custom-invalid-authentication-header-message-object'448 )449 req.headers.set('Authorization', 'Beare abcdefg12345-._~+/=')450 const res = await app.request(req)451 expect(res).not.toBeNull()452 expect(res.status).toBe(400)453 expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')454 expect(handlerExecuted).toBeFalsy()455 expect(await res.text()).toBe(456 '{"message":"Custom invalid authentication header message as object"}'457 )458 })459460 it('Should not authorize - custom invalid authentication header message as function string', async () => {461 const req = new Request(462 'http://localhost/auth-custom-invalid-authentication-header-message-function-string'463 )464 req.headers.set('Authorization', 'Beare abcdefg12345-._~+/=')465 const res = await app.request(req)466 expect(res).not.toBeNull()467 expect(res.status).toBe(400)468 expect(handlerExecuted).toBeFalsy()469 expect(await res.text()).toBe('Custom invalid authentication header message as function string')470 })471472 it('Should not authorize - custom invalid authentication header message as function object', async () => {473 const req = new Request(474 'http://localhost/auth-custom-invalid-authentication-header-message-function-object'475 )476 req.headers.set('Authorization', 'Beare abcdefg12345-._~+/=')477 const res = await app.request(req)478 expect(res).not.toBeNull()479 expect(res.status).toBe(400)480 expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')481 expect(handlerExecuted).toBeFalsy()482 expect(await res.text()).toBe(483 '{"message":"Custom invalid authentication header message as function object"}'484 )485 })486487 it('Should not authorize - custom invalid token message as string', async () => {488 const req = new Request('http://localhost/auth-custom-invalid-token-message-string')489 req.headers.set('Authorization', 'Bearer invalid-token')490 const res = await app.request(req)491 expect(res).not.toBeNull()492 expect(res.status).toBe(401)493 expect(handlerExecuted).toBeFalsy()494 expect(await res.text()).toBe('Custom invalid token message as string')495 })496497 it('Should not authorize - custom invalid token message as object', async () => {498 const req = new Request('http://localhost/auth-custom-invalid-token-message-object')499 req.headers.set('Authorization', 'Bearer invalid-token')500 const res = await app.request(req)501 expect(res).not.toBeNull()502 expect(res.status).toBe(401)503 expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')504 expect(handlerExecuted).toBeFalsy()505 expect(await res.text()).toBe('{"message":"Custom invalid token message as object"}')506 })507508 it('Should not authorize - custom invalid token message as function string', async () => {509 const req = new Request('http://localhost/auth-custom-invalid-token-message-function-string')510 req.headers.set('Authorization', 'Bearer invalid-token')511 const res = await app.request(req)512 expect(res).not.toBeNull()513 expect(res.status).toBe(401)514 expect(handlerExecuted).toBeFalsy()515 expect(await res.text()).toBe('Custom invalid token message as function string')516 })517518 it('Should not authorize - custom invalid token message as function object', async () => {519 const req = new Request('http://localhost/auth-custom-invalid-token-message-function-object')520 req.headers.set('Authorization', 'Bearer invalid-token')521 const res = await app.request(req)522 expect(res).not.toBeNull()523 expect(res.status).toBe(401)524 expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')525 expect(handlerExecuted).toBeFalsy()526 expect(await res.text()).toBe('{"message":"Custom invalid token message as function object"}')527 })528})
modified:src/middleware/bearer-auth/index.ts+54 added-21 removed
5 unmodified lines
6import type { Context } from '../../context'7import { HTTPException } from '../../http-exception'8import type { MiddlewareHandler } from '../../types'9import { timingSafeEqual } from '../../utils/buffer'10import type { StatusCode } from '../../utils/http-status'1112const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'13const PREFIX = 'Bearer'14const HEADER = 'Authorization'1516type MessageFunction = (c: Context) => string | object | Promise<string | object>1718type BearerAuthOptions =19 | {20 token: string | string[]21 realm?: string22 prefix?: string23 headerName?: string24 hashFunction?: Function25 noAuthenticationHeaderMessage?: string | object | MessageFunction26 invalidAuthenticationHeaderMessage?: string | object | MessageFunction27 invalidTokenMessage?: string | object | MessageFunction28 }29 | {30 realm?: string31 prefix?: string32 headerName?: string33 verifyToken: (token: string, c: Context) => boolean | Promise<boolean>34 hashFunction?: Function35 noAuthenticationHeaderMessage?: string | object | MessageFunction36 invalidAuthenticationHeaderMessage?: string | object | MessageFunction37 invalidTokenMessage?: string | object | MessageFunction38 }3940/**41 * Bearer Auth Middleware for Hono.
6 unmodified lines
48 * @param {string} [options.realm=""] - The domain name of the realm, as part of the returned WWW-Authenticate challenge header.49 * @param {string} [options.prefix="Bearer"] - The prefix (or known as `schema`) for the Authorization header value. If set to the empty string, no prefix is expected.50 * @param {string} [options.headerName=Authorization] - The header name.51 * @param {Function} [options.hashFunction] - A function to handle hashing for safe comparison of authentication tokens.52 * @param {string | object | MessageFunction} [options.noAuthenticationHeaderMessage="Unauthorized"] - The no authentication header message.53 * @param {string | object | MessageFunction} [options.invalidAuthenticationHeaderMeasage="Bad Request"] - The invalid authentication header message.54 * @param {string | object | MessageFunction} [options.invalidTokenMessage="Unauthorized"] - The invalid token message.55 * @returns {MiddlewareHandler} The middleware handler function.56 * @throws {Error} If neither "token" nor "verifyToken" options are provided.57 * @throws {HTTPException} If authentication fails, with 401 status code for missing or invalid token, or 400 status code for invalid request.58 *
25 unmodified lines
84 const prefixRegexStr = options.prefix === '' ? '' : `${options.prefix} +`85 const regexp = new RegExp(`^${prefixRegexStr}(${TOKEN_STRINGS}) *$`)86 const wwwAuthenticatePrefix = options.prefix === '' ? '' : `${options.prefix} `8788 const throwHTTPException = async (89 c: Context,90 status: StatusCode,91 wwwAuthenticateHeader: string,92 messageOption: string | object | MessageFunction93 ): Promise<Response> => {94 const headers = {95 'WWW-Authenticate': wwwAuthenticateHeader,96 }97 const responseMessage =98 typeof messageOption === 'function' ? await messageOption(c) : messageOption99 const res =100 typeof responseMessage === 'string'101 ? new Response(responseMessage, { status, headers })102 : new Response(JSON.stringify(responseMessage), {103 status,104 headers: {105 ...headers,106 'content-type': 'application/json; charset=UTF-8',107 },108 })109 throw new HTTPException(status, { res })110 }111112 return async function bearerAuth(c, next) {113 const headerToken = c.req.header(options.headerName || HEADER)114 if (!headerToken) {115 // No Authorization header80 const res = new Response('Unauthorized', {81 status: 401,82 headers: {83 'WWW-Authenticate': `${wwwAuthenticatePrefix}realm="` + realm + '"',84 },85 })86 throw new HTTPException(401, { res })116 await throwHTTPException(117 c,118 401,119 `${wwwAuthenticatePrefix}realm="${realm}"`,120 options.noAuthenticationHeaderMessage || 'Unauthorized'121 )122 } else {123 const match = regexp.exec(headerToken)124 if (!match) {125 // Invalid Request91 const res = new Response('Bad Request', {92 status: 400,93 headers: {94 'WWW-Authenticate': `${wwwAuthenticatePrefix}error="invalid_request"`,95 },96 })97 throw new HTTPException(400, { res })126 await throwHTTPException(127 c,128 400,129 `${wwwAuthenticatePrefix}error="invalid_request"`,130 options.invalidAuthenticationHeaderMessage || 'Bad Request'131 )132 } else {133 let equal = false134 if ('verifyToken' in options) {135 equal = await options.verifyToken(match[1], c)
8 unmodified lines
144 }145 }146 if (!equal) {147 // Invalid Token114 const res = new Response('Unauthorized', {115 status: 401,116 headers: {117 'WWW-Authenticate': `${wwwAuthenticatePrefix}error="invalid_token"`,118 },119 })120 throw new HTTPException(401, { res })148 await throwHTTPException(149 c,150 401,151 `${wwwAuthenticatePrefix}error="invalid_token"`,152 options.invalidTokenMessage || 'Unauthorized'153 )154 }155 }156 }157 await next()
2 unmodified lines
added:src/middleware/context-storage/index.test.ts+30 added
1import { Hono } from '../../hono'2import { contextStorage, getContext } from '.'34describe('Context Storage Middleware', () => {5 type Env = {6 Variables: {7 message: string8 }9 }1011 const app = new Hono<Env>()1213 app.use(contextStorage())14 app.use(async (c, next) => {15 c.set('message', 'Hono is cool!!')16 await next()17 })18 app.get('/', (c) => {19 return c.text(getMessage())20 })2122 const getMessage = () => {23 return getContext<Env>().var.message24 }2526 it('Should get context', async () => {27 const res = await app.request('/')28 expect(await res.text()).toBe('Hono is cool!!')29 })30})
added:src/middleware/context-storage/index.ts+55 added
1/**2 * @module3 * Context Storage Middleware for Hono.4 */56import type { Context } from '../../context'7import type { Env, MiddlewareHandler } from '../../types'8import { AsyncLocalStorage } from 'node:async_hooks'910const asyncLocalStorage = new AsyncLocalStorage<Context>()1112/**13 * Context Storage Middleware for Hono.14 *15 * @see {@link https://hono.dev/docs/middleware/builtin/context-storage}16 *17 * @returns {MiddlewareHandler} The middleware handler function.18 *19 * @example20 * ```ts21 * type Env = {22 * Variables: {23 * message: string24 * }25 * }26 *27 * const app = new Hono<Env>()28 *29 * app.use(contextStorage())30 *31 * app.use(async (c, next) => {32 * c.set('message', 'Hono is cool!!)33 * await next()34 * })35 *36 * app.get('/', async (c) => { c.text(getMessage()) })37 *38 * const getMessage = () => {39 * return getContext<Env>().var.message40 * }41 * ```42 */43export const contextStorage = (): MiddlewareHandler => {44 return async function contextStorage(c, next) {45 await asyncLocalStorage.run(c, next)46 }47}4849export const getContext = <E extends Env = Env>(): Context<E> => {50 const context = asyncLocalStorage.getStore()51 if (!context) {52 throw new Error('Context is not available')53 }54 return context55}
modified:src/middleware/jsx-renderer/index.test.tsx+1 added
236 unmodified lines
237 expect(res).not.toBeNull()238 expect(res.status).toBe(200)239 expect(res.headers.get('Transfer-Encoding')).toEqual('chunked')240 expect(res.headers.get('Content-Type')).toEqual('text/html; charset=UTF-8')241 expect(res.headers.get('Content-Encoding')).toEqual('Identity')242243 if (!res.body) {244 throw new Error('Body is null')245 }
213 unmodified lines
modified:src/middleware/jsx-renderer/index.ts+1 added
58 unmodified lines
59 if (options?.stream) {60 if (options.stream === true) {61 c.header('Transfer-Encoding', 'chunked')62 c.header('Content-Type', 'text/html; charset=UTF-8')63 c.header('Content-Encoding', 'Identity')64 } else {65 for (const [key, value] of Object.entries(options.stream)) {66 c.header(key, value)67 }
91 unmodified lines
modified:src/middleware/secure-headers/index.test.ts+35 added
34 unmodified lines
35 expect(res.headers.get('X-Permitted-Cross-Domain-Policies')).toEqual('none')36 expect(res.headers.get('Cross-Origin-Resource-Policy')).toEqual('same-origin')37 expect(res.headers.get('Cross-Origin-Opener-Policy')).toEqual('same-origin')38 expect(res.headers.get('Origin-Agent-Cluster')).toEqual('?1')39 expect(res.headers.get('Permissions-Policy')).toBeNull()40 expect(res.headers.get('Content-Security-Policy')).toBeFalsy()41 })4243 it('all headers enabled', async () => {
4 unmodified lines
48 contentSecurityPolicy: {49 defaultSrc: ["'self'"],50 },51 crossOriginEmbedderPolicy: true,52 permissionsPolicy: {53 camera: [],54 },55 })56 )57 app.get('/test', async (ctx) => {58 return ctx.text('test')
16 unmodified lines
75 expect(res.headers.get('Cross-Origin-Resource-Policy')).toEqual('same-origin')76 expect(res.headers.get('Cross-Origin-Opener-Policy')).toEqual('same-origin')77 expect(res.headers.get('Origin-Agent-Cluster')).toEqual('?1')78 expect(res.headers.get('Cross-Origin-Embedder-Policy')).toEqual('require-corp')79 expect(res.headers.get('Permissions-Policy')).toEqual('camera=()')80 expect(res.headers.get('Content-Security-Policy')).toEqual("default-src 'self'")81 })8283 it('specific headers disabled', async () => {
18 unmodified lines
102 expect(res.headers.get('Referrer-Policy')).toEqual('no-referrer')103 expect(res.headers.get('X-Permitted-Cross-Domain-Policies')).toEqual('none')104 expect(res.headers.get('Cross-Origin-Resource-Policy')).toEqual('same-origin')105 expect(res.headers.get('Cross-Origin-Opener-Policy')).toEqual('same-origin')106 expect(res.headers.get('Permissions-Policy')).toBeNull()107 expect(res.headers.get('Origin-Agent-Cluster')).toEqual('?1')108 })109110 it('should remove x-powered-by header', async () => {
48 unmodified lines
159 expect(res.headers.get('X-FRAME-OPTIONS')).toEqual('DENY')160 expect(res.headers.get('X-XSS-Protection')).toEqual('1')161 })162163 it('should set Permission-Policy header correctly', async () => {164 const app = new Hono()165 app.use(166 '/test',167 secureHeaders({168 permissionsPolicy: {169 fullscreen: ['self'],170 bluetooth: ['none'],171 payment: ['self', 'example.com'],172 syncXhr: [],173 camera: false,174 microphone: true,175 geolocation: ['*'],176 usb: ['self', 'https://a.example.com', 'https://b.example.com'],177 accelerometer: ['https://*.example.com'],178 gyroscope: ['src'],179 magnetometer: ['https://a.example.com', 'https://b.example.com'],180 },181 })182 )183184 const res = await app.request('/test')185 expect(res.headers.get('Permissions-Policy')).toEqual(186 'fullscreen=(self), bluetooth=none, payment=(self "example.com"), sync-xhr=(), camera=none, microphone=*, ' +187 'geolocation=*, usb=(self "https://a.example.com" "https://b.example.com"), ' +188 'accelerometer=("https://*.example.com"), gyroscope=(src), ' +189 'magnetometer=("https://a.example.com" "https://b.example.com")'190 )191 })192 it('CSP Setting', async () => {193 const app = new Hono()194 app.use(195 '/test',
277 unmodified lines
added:src/middleware/secure-headers/permissions-policy.ts+86 added
1// https://github.com/w3c/webappsec-permissions-policy/blob/main/features.md23export type PermissionsPolicyDirective =4 | StandardizedFeatures5 | ProposedFeatures6 | ExperimentalFeatures78/**9 * These features have been declared in a published version of the respective specification.10 */11type StandardizedFeatures =12 | 'accelerometer'13 | 'ambientLightSensor'14 | 'attributionReporting'15 | 'autoplay'16 | 'battery'17 | 'bluetooth'18 | 'camera'19 | 'chUa'20 | 'chUaArch'21 | 'chUaBitness'22 | 'chUaFullVersion'23 | 'chUaFullVersionList'24 | 'chUaMobile'25 | 'chUaModel'26 | 'chUaPlatform'27 | 'chUaPlatformVersion'28 | 'chUaWow64'29 | 'computePressure'30 | 'crossOriginIsolated'31 | 'directSockets'32 | 'displayCapture'33 | 'encryptedMedia'34 | 'executionWhileNotRendered'35 | 'executionWhileOutOfViewport'36 | 'fullscreen'37 | 'geolocation'38 | 'gyroscope'39 | 'hid'40 | 'identityCredentialsGet'41 | 'idleDetection'42 | 'keyboardMap'43 | 'magnetometer'44 | 'microphone'45 | 'midi'46 | 'navigationOverride'47 | 'payment'48 | 'pictureInPicture'49 | 'publickeyCredentialsGet'50 | 'screenWakeLock'51 | 'serial'52 | 'storageAccess'53 | 'syncXhr'54 | 'usb'55 | 'webShare'56 | 'windowManagement'57 | 'xrSpatialTracking'5859/**60 * These features have been proposed, but the definitions have not yet been integrated into their respective specs.61 */62type ProposedFeatures =63 | 'clipboardRead'64 | 'clipboardWrite'65 | 'gemepad'66 | 'sharedAutofill'67 | 'speakerSelection'6869/**70 * These features generally have an explainer only, but may be available for experimentation by web developers.71 */72type ExperimentalFeatures =73 | 'allScreensCapture'74 | 'browsingTopics'75 | 'capturedSurfaceControl'76 | 'conversionMeasurement'77 | 'digitalCredentialsGet'78 | 'focusWithoutUserActivation'79 | 'joinAdInterestGroup'80 | 'localFonts'81 | 'runAdAuction'82 | 'smartCard'83 | 'syncScript'84 | 'trustTokenRedemption'85 | 'unload'86 | 'verticalScroll'
modified:src/middleware/secure-headers/secure-headers.ts+47 added
4 unmodified lines
56import type { Context } from '../../context'7import type { MiddlewareHandler } from '../../types'8import { encodeBase64 } from '../../utils/encode'9import type { PermissionsPolicyDirective } from './permissions-policy'1011export type SecureHeadersVariables = {12 secureHeadersNonce?: string13}
40 unmodified lines
54 name: string55 url: string56}5758type PermissionsPolicyValue = '*' | 'self' | 'src' | 'none' | string5960type PermissionsPolicyOptions = Partial<61 Record<PermissionsPolicyDirective, PermissionsPolicyValue[] | boolean>62>6364type overridableHeader = boolean | string6566interface SecureHeadersOptions {67 contentSecurityPolicy?: ContentSecurityPolicyOptions
11 unmodified lines
79 xFrameOptions?: overridableHeader80 xPermittedCrossDomainPolicies?: overridableHeader81 xXssProtection?: overridableHeader82 removePoweredBy?: boolean83 permissionsPolicy?: PermissionsPolicyOptions84}8586type HeadersMap = {87 [key in keyof SecureHeadersOptions]: [string, string]
27 unmodified lines
115 xFrameOptions: true,116 xPermittedCrossDomainPolicies: true,117 xXssProtection: true,118 removePoweredBy: true,119 permissionsPolicy: {},120}121122type SecureHeadersCallback = (123 ctx: Context,
38 unmodified lines
162 * @param {overridableHeader} [customOptions.xFrameOptions=true] - Settings for the X-Frame-Options header.163 * @param {overridableHeader} [customOptions.xPermittedCrossDomainPolicies=true] - Settings for the X-Permitted-Cross-Domain-Policies header.164 * @param {overridableHeader} [customOptions.xXssProtection=true] - Settings for the X-XSS-Protection header.165 * @param {boolean} [customOptions.removePoweredBy=true] - Settings for remove X-Powered-By header.166 * @param {PermissionsPolicyOptions} [customOptions.permissionsPolicy] - Settings for the Permissions-Policy header.167 * @returns {MiddlewareHandler} The middleware handler function.168 *169 * @example170 * ```ts
13 unmodified lines
184 }185 headersToSet.push(['Content-Security-Policy', value as string])186 }187188 if (options.permissionsPolicy && Object.keys(options.permissionsPolicy).length > 0) {189 headersToSet.push([190 'Permissions-Policy',191 getPermissionsPolicyDirectives(options.permissionsPolicy),192 ])193 }194195 if (options.reportingEndpoints) {196 headersToSet.push(['Reporting-Endpoints', getReportingEndpoints(options.reportingEndpoints)])197 }198
72 unmodified lines
271 resultValues,272 ]273}274275function getPermissionsPolicyDirectives(policy: PermissionsPolicyOptions): string {276 return Object.entries(policy)277 .map(([directive, value]) => {278 const kebabDirective = camelToKebab(directive)279280 if (typeof value === 'boolean') {281 return `${kebabDirective}=${value ? '*' : 'none'}`282 }283284 if (Array.isArray(value)) {285 if (value.length === 0) {286 return `${kebabDirective}=()`287 }288 if (value.length === 1 && (value[0] === '*' || value[0] === 'none')) {289 return `${kebabDirective}=${value[0]}`290 }291 const allowlist = value.map((item) => (['self', 'src'].includes(item) ? item : `"${item}"`))292 return `${kebabDirective}=(${allowlist.join(' ')})`293 }294295 return ''296 })297 .filter(Boolean)298 .join(', ')299}300301function camelToKebab(str: string): string {302 return str.replace(/([a-z\d])([A-Z])/g, '$1-$2').toLowerCase()303}304305function getReportingEndpoints(306 reportingEndpoints: SecureHeadersOptions['reportingEndpoints'] = []307): string {308 return reportingEndpoints.map((endpoint) => `${endpoint.name}="${endpoint.url}"`).join(', ')
11 unmodified lines
modified:src/middleware/serve-static/index.test.ts+92 added-1 removed
16 unmodified lines
17 },18 isDir: (path) => {19 return path === 'static/hello.world'20 },21 onFound: (path, c) => {22 if (path.endsWith('hello.html')) {23 c.header('X-Custom', `Found the file at ${path}`)24 }25 },26 })2728 app.get('/static/*', serveStatic)29
3 unmodified lines
3334 it('Should return 200 response - /static/hello.html', async () => {35 const res = await app.request('/static/hello.html')36 expect(res.status).toBe(200)37 expect(res.headers.get('Content-Encoding')).toBeNull()38 expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)39 expect(await res.text()).toBe('Hello in ./static/hello.html')40 expect(res.headers.get('X-Custom')).toBe('Found the file at ./static/hello.html')41 })4243 it('Should return 200 response - /static/sub', async () => {44 const res = await app.request('/static/sub')
18 unmodified lines
6364 it('Should decode URI strings - /static/%E7%82%8E.txt', async () => {65 const res = await app.request('/static/%E7%82%8E.txt')66 expect(res.status).toBe(200)67 expect(res.headers.get('Content-Type')).toMatch(/^text\/plain/)68 expect(await res.text()).toBe('Hello in ./static/炎.txt')69 })7063 it('Should return 404 response - /static/not-found', async () => {71 it('Should return 404 response - /static/not-found.txt', async () => {72 const res = await app.request('/static/not-found.txt')73 expect(res.status).toBe(404)74 expect(res.headers.get('Content-Encoding')).toBeNull()75 expect(res.headers.get('Content-Type')).toMatch(/^text\/plain/)76 expect(await res.text()).toBe('404 Not Found')77 expect(getContent).toBeCalledTimes(1)78 })79
2 unmodified lines
82 method: 'GET',83 url: 'http://localhost/static/%2e%2e/static/hello.html',84 } as Request)85 expect(res.status).toBe(404)86 expect(res.headers.get('Content-Type')).toMatch(/^text\/plain/)87 expect(await res.text()).toBe('404 Not Found')88 })8990 it('Should return a pre-compressed zstd response - /static/hello.html', async () => {91 const app = new Hono().use(92 '*',93 baseServeStatic({94 getContent,95 precompressed: true,96 })97 )9899 const res = await app.request('/static/hello.html', {100 headers: { 'Accept-Encoding': 'zstd' },101 })102103 expect(res.status).toBe(200)104 expect(res.headers.get('Content-Encoding')).toBe('zstd')105 expect(res.headers.get('Vary')).toBe('Accept-Encoding')106 expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)107 expect(await res.text()).toBe('Hello in static/hello.html.zst')108 })109110 it('Should return a pre-compressed brotli response - /static/hello.html', async () => {111 const app = new Hono().use(112 '*',113 baseServeStatic({114 getContent,115 precompressed: true,116 })117 )118119 const res = await app.request('/static/hello.html', {120 headers: { 'Accept-Encoding': 'wompwomp, gzip, br, deflate, zstd' },121 })122123 expect(res.status).toBe(200)124 expect(res.headers.get('Content-Encoding')).toBe('br')125 expect(res.headers.get('Vary')).toBe('Accept-Encoding')126 expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)127 expect(await res.text()).toBe('Hello in static/hello.html.br')128 })129130 it('Should not return a pre-compressed response - /static/not-found.txt', async () => {131 const app = new Hono().use(132 '*',133 baseServeStatic({134 getContent,135 precompressed: true,136 })137 )138139 const res = await app.request('/static/not-found.txt', {140 headers: { 'Accept-Encoding': 'gzip, zstd, br' },141 })142143 expect(res.status).toBe(404)144 expect(res.headers.get('Content-Encoding')).toBeNull()145 expect(res.headers.get('Vary')).toBeNull()146 expect(res.headers.get('Content-Type')).toMatch(/^text\/plain/)147 expect(await res.text()).toBe('404 Not Found')148 })149150 it('Should not return a pre-compressed response - /static/hello.html', async () => {151 const app = new Hono().use(152 '*',153 baseServeStatic({154 getContent,155 precompressed: true,156 })157 )158159 const res = await app.request('/static/hello.html', {160 headers: { 'Accept-Encoding': 'wompwomp, unknown' },161 })162163 expect(res.status).toBe(200)164 expect(res.headers.get('Content-Encoding')).toBeNull()165 expect(res.headers.get('Vary')).toBeNull()166 expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)167 expect(await res.text()).toBe('Hello in static/hello.html')168 })169170 it('Should return response object content as-is', async () => {171 const body = new ReadableStream()172 const response = new Response(body)173 const app = new Hono().use(
16 unmodified lines
modified:src/middleware/serve-static/index.ts+47 added-16 removed
9 unmodified lines
1011export type ServeStaticOptions<E extends Env = Env> = {12 root?: string13 path?: string14 precompressed?: boolean15 mimes?: Record<string, string>16 rewriteRequestPath?: (path: string) => string17 onFound?: (path: string, c: Context<E>) => void | Promise<void>18 onNotFound?: (path: string, c: Context<E>) => void | Promise<void>19}2021const ENCODINGS = {22 br: '.br',23 zstd: '.zst',24 gzip: '.gz',25} as const2627const DEFAULT_DOCUMENT = 'index.html'28const defaultPathResolve = (path: string) => path2930/**
23 unmodified lines
54 filename,55 root,56 })57 if (path && (await options.isDir(path))) {50 filename = filename + '/'58 filename += '/'59 }60 }6162 let path = getFilePath({
7 unmodified lines
70 }7172 const getContent = options.getContent73 const pathResolve = options.pathResolve ?? defaultPathResolve6674 path = pathResolve(path)75 let content = await getContent(path, c)7677 if (!content) {71 let pathWithOutDefaultDocument = getFilePathWithoutDefaultDocument({78 let pathWithoutDefaultDocument = getFilePathWithoutDefaultDocument({79 filename,80 root,81 })75 if (!pathWithOutDefaultDocument) {82 if (!pathWithoutDefaultDocument) {83 return await next()84 }78 pathWithOutDefaultDocument = pathResolve(pathWithOutDefaultDocument)85 pathWithoutDefaultDocument = pathResolve(pathWithoutDefaultDocument)8680 if (pathWithOutDefaultDocument !== path) {81 content = await getContent(pathWithOutDefaultDocument, c)87 if (pathWithoutDefaultDocument !== path) {88 content = await getContent(pathWithoutDefaultDocument, c)89 if (content) {83 path = pathWithOutDefaultDocument90 path = pathWithoutDefaultDocument91 }92 }93 }9495 if (content instanceof Response) {96 return c.newResponse(content.body, content)97 }9899 const mimeType = options.mimes100 ? getMimeType(path, options.mimes) ?? getMimeType(path)101 : getMimeType(path)102103 if (mimeType) {104 c.header('Content-Type', mimeType)105 }106107 if (content) {93 let mimeType: string | undefined94 if (options.mimes) {95 mimeType = getMimeType(path, options.mimes) ?? getMimeType(path)96 } else {97 mimeType = getMimeType(path)108 if (options.precompressed) {109 const acceptEncodings =110 c.req111 .header('Accept-Encoding')112 ?.split(',')113 .map((encoding) => encoding.trim())114 .filter((encoding): encoding is keyof typeof ENCODINGS =>115 Object.hasOwn(ENCODINGS, encoding)116 )117 .sort(118 (a, b) => Object.keys(ENCODINGS).indexOf(a) - Object.keys(ENCODINGS).indexOf(b)119 ) ?? []120121 for (const encoding of acceptEncodings) {122 const compressedContent = (await getContent(path + ENCODINGS[encoding], c)) as Data | null123124 if (compressedContent) {125 content = compressedContent126 c.header('Content-Encoding', encoding)127 c.header('Vary', 'Accept-Encoding', { append: true })128 break129 }130 }131 }99 if (mimeType) {100 c.header('Content-Type', mimeType)101 }132 await options.onFound?.(path, c)133 return c.body(content)134 }135136 await options.onNotFound?.(path, c)
4 unmodified lines
modified:src/utils/html.ts+11 added-2 removed
138 unmodified lines
139 return buffer[0]140}141142export const resolveCallback = async (143 str: string | HtmlEscapedString,143 str: string | HtmlEscapedString | Promise<string>,144 phase: (typeof HtmlEscapedCallbackPhase)[keyof typeof HtmlEscapedCallbackPhase],145 preserveCallbacks: boolean,146 context: object,147 buffer?: [string]148): Promise<string> => {149 if (typeof str === 'object' && !(str instanceof String)) {150 if (!((str as unknown) instanceof Promise)) {151 str = (str as unknown as string).toString() // HtmlEscapedString object to string152 }153 if ((str as string | Promise<string>) instanceof Promise) {154 str = await (str as unknown as Promise<string>)155 }156 }157158 const callbacks = (str as HtmlEscapedString).callbacks as HtmlEscapedCallback[]159 if (!callbacks?.length) {160 return Promise.resolve(str)161 }162 if (buffer) {163 buffer[0] += str164 } else {156 buffer = [str]165 buffer = [str as string]166 }167168 const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) =>169 Promise.all(
13 unmodified lines
modified:src/context.test.ts+45 added
1import { Context } from './context'2import { setCookie } from './helper/cookie'34const makeResponseHeaderImmutable = (res: Response) => {5 Object.defineProperty(res, 'headers', {6 value: new Proxy(res.headers, {7 set(target, prop, value) {8 if (prop === 'set') {9 throw new TypeError('Cannot modify headers: Headers are immutable')10 }11 return Reflect.set(target, prop, value)12 },13 get(target, prop) {14 if (prop === 'set') {15 return function () {16 throw new TypeError('Cannot modify headers: Headers are immutable')17 }18 }19 return Reflect.get(target, prop)20 },21 }),22 writable: false,23 })24 return res25}2627describe('Context', () => {28 const req = new Request('http://localhost/')2930 let c: Context
351 unmodified lines
382 })383 const res = c.text('Hi')384 expect(res.headers.get('set-cookie')).toBe('a, b, c')385 })386387 it('Should be able to overwrite a fetch response with a new response.', async () => {388 c.res = makeResponseHeaderImmutable(new Response('bar'))389 c.res = new Response('foo', {390 headers: {391 'X-Custom': 'Message',392 },393 })394 expect(c.res.text()).resolves.toBe('foo')395 expect(c.res.headers.get('X-Custom')).toBe('Message')396 })397398 it('Should be able to overwrite a response with a fetch response.', async () => {399 c.res = new Response('foo', {400 headers: {401 'X-Custom': 'Message',402 },403 })404 c.res = makeResponseHeaderImmutable(new Response('bar'))405 expect(c.res.text()).resolves.toBe('bar')406 expect(c.res.headers.get('X-Custom')).toBe('Message')407 })408})409410describe('Pass a ResponseInit to respond methods', () => {411 const req = new Request('http://localhost/')
99 unmodified lines
modified:src/context.ts+28 added-20 removed
463 unmodified lines
464 */465 set res(_res: Response | undefined) {466 this.#isFresh = false467 if (this.#res && _res) {468 this.#res.headers.delete('content-type')469 for (const [k, v] of this.#res.headers.entries()) {470 if (k === 'set-cookie') {471 const cookies = this.#res.headers.getSetCookie()472 _res.headers.delete('set-cookie')473 for (const cookie of cookies) {474 _res.headers.append('set-cookie', cookie)468 try {469 for (const [k, v] of this.#res.headers.entries()) {470 if (k === 'content-type') {471 continue472 }473 if (k === 'set-cookie') {474 const cookies = this.#res.headers.getSetCookie()475 _res.headers.delete('set-cookie')476 for (const cookie of cookies) {477 _res.headers.append('set-cookie', cookie)478 }479 } else {480 _res.headers.set(k, v)481 }482 }483 } catch (e) {484 if (e instanceof TypeError && e.message.includes('immutable')) {485 // `_res` is immutable (probably a response from a fetch API), so retry with a new response.486 this.res = new Response(_res.body, {487 headers: _res.headers,488 status: _res.status,489 })490 return491 } else {477 _res.headers.set(k, v)492 throw e493 }494 }495 }496 this.#res = _res
361 unmodified lines
858 this.#preparedHeaders ??= {}859 this.#preparedHeaders['content-type'] = 'text/html; charset=UTF-8'860861 if (typeof html === 'object') {847 if (!(html instanceof Promise)) {848 html = (html as string).toString() // HtmlEscapedString object to string849 }850 if ((html as string | Promise<string>) instanceof Promise) {851 return (html as unknown as Promise<string>)852 .then((html) => resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}))853 .then((html) => {854 return typeof arg === 'number'855 ? this.newResponse(html, arg, headers)856 : this.newResponse(html, arg)857 })862 return resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then((html) => {863 return typeof arg === 'number'864 ? this.newResponse(html, arg, headers)865 : this.newResponse(html, arg)866 })858 }867 }868869 return typeof arg === 'number'870 ? this.newResponse(html as string, arg, headers)
44 unmodified lines
modified:jsr.json+1 added
24 unmodified lines
25 "./cache": "./src/middleware/cache/index.ts",26 "./cookie": "./src/helper/cookie/index.ts",27 "./accepts": "./src/helper/accepts/index.ts",28 "./compress": "./src/middleware/compress/index.ts",29 "./context-storage": "./src/middleware/context-storage/index.ts",30 "./cors": "./src/middleware/cors/index.ts",31 "./csrf": "./src/middleware/csrf/index.ts",32 "./etag": "./src/middleware/etag/index.ts",33 "./trailing-slash": "./src/middleware/trailing-slash/index.ts",
86 unmodified lines
modified:package.json+8 added
102 unmodified lines
103 "types": "./dist/types/middleware/compress/index.d.ts",104 "import": "./dist/middleware/compress/index.js",105 "require": "./dist/cjs/middleware/compress/index.js"106 },107 "./context-storage": {108 "types": "./dist/types/middleware/context-storage/index.d.ts",109 "import": "./dist/middleware/context-storage/index.js",110 "require": "./dist/cjs/middleware/context-storage/index.js"111 },112 "./cors": {113 "types": "./dist/types/middleware/cors/index.d.ts",114 "import": "./dist/middleware/cors/index.js",115 "require": "./dist/cjs/middleware/cors/index.js"
309 unmodified lines
425 ],426 "compress": [427 "./dist/types/middleware/compress"428 ],429 "context-storage": [430 "./dist/types/middleware/context-storage"431 ],432 "cors": [433 "./dist/types/middleware/cors"434 ],435 "csrf": [
215 unmodified lines