Merge pull request #4340 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 23c6d5a, 87858fb · Browse files · 29 files·+916 added−221 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
29 files+916 added−221 removed
- tests:+501 added−65 removed
- other:+415 added−156 removed
Provenance
- Commit
3a5248f- Tree
de2c986- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent 1
23c6d5a- Parent 2
87858fb
29 files changed+916 added−221 removed
modified:runtime-tests/bun/index.test.tsx+3 added-1 removed
122 unmodified lines123 const res = await app.request(new Request('http://localhost/favicon-notfound.ico'))124 expect(res.status).toBe(404)125 expect(res.headers.get('X-Custom')).toBe('Bun')126 expect(onNotFound).toHaveBeenCalledWith(127+ process.platform === 'win32'128+ ? 'runtime-tests\\bun\\favicon-notfound.ico'127- './runtime-tests/bun/favicon-notfound.ico',129+ : 'runtime-tests/bun/favicon-notfound.ico',130 expect.anything()131 )132 })133 321 unmodified linesmodified:src/adapter/aws-lambda/handler.test.ts+116 added-12 removed
1 import type { LambdaEvent } from './handler'2-import { getProcessor, isContentEncodingBinary, isContentTypeBinary } from './handler'2+import { getProcessor, isContentEncodingBinary, defaultIsContentTypeBinary } from './handler'3 4 describe('isContentTypeBinary', () => {5 it('Should determine whether it is binary', () => {6- expect(isContentTypeBinary('image/png')).toBe(true)7- expect(isContentTypeBinary('font/woff2')).toBe(true)8- expect(isContentTypeBinary('image/svg+xml')).toBe(false)9- expect(isContentTypeBinary('image/svg+xml; charset=UTF-8')).toBe(false)10- expect(isContentTypeBinary('text/plain')).toBe(false)11- expect(isContentTypeBinary('text/plain; charset=UTF-8')).toBe(false)12- expect(isContentTypeBinary('text/css')).toBe(false)13- expect(isContentTypeBinary('text/javascript')).toBe(false)14- expect(isContentTypeBinary('application/json')).toBe(false)15- expect(isContentTypeBinary('application/ld+json')).toBe(false)16- expect(isContentTypeBinary('application/json')).toBe(false)6+ expect(defaultIsContentTypeBinary('image/png')).toBe(true)7+ expect(defaultIsContentTypeBinary('font/woff2')).toBe(true)8+ expect(defaultIsContentTypeBinary('image/svg+xml')).toBe(false)9+ expect(defaultIsContentTypeBinary('image/svg+xml; charset=UTF-8')).toBe(false)10+ expect(defaultIsContentTypeBinary('text/plain')).toBe(false)11+ expect(defaultIsContentTypeBinary('text/plain; charset=UTF-8')).toBe(false)12+ expect(defaultIsContentTypeBinary('text/css')).toBe(false)13+ expect(defaultIsContentTypeBinary('text/javascript')).toBe(false)14+ expect(defaultIsContentTypeBinary('application/json')).toBe(false)15+ expect(defaultIsContentTypeBinary('application/ld+json')).toBe(false)16+ expect(defaultIsContentTypeBinary('application/json')).toBe(false)17 })18 })19 20 describe('isContentEncodingBinary', () => {7 unmodified lines28 expect(isContentEncodingBinary('unknown')).toBe(false)29 })30 })31 32+describe('EventProcessor.createResult with contentTypsAsBinary', () => {33+ const event: LambdaEvent = {34+ version: '1.0',35+ resource: '/my/path',36+ path: '/my/path',37+ httpMethod: 'GET',38+ headers: {},39+ multiValueHeaders: {},40+ queryStringParameters: {},41+ requestContext: {42+ accountId: '123456789012',43+ apiId: 'id',44+ authorizer: { claims: null, scopes: null },45+ domainName: 'id.execute-api.us-east-1.amazonaws.com',46+ domainPrefix: 'id',47+ extendedRequestId: 'request-id',48+ httpMethod: 'GET',49+ identity: {50+ sourceIp: '192.0.2.1',51+ userAgent: 'user-agent',52+ clientCert: {53+ clientCertPem: 'CERT_CONTENT',54+ subjectDN: 'www.example.com',55+ issuerDN: 'Example issuer',56+ serialNumber: 'a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1:a1',57+ validity: {58+ notBefore: 'May 28 12:30:02 2019 GMT',59+ notAfter: 'Aug 5 09:36:04 2021 GMT',60+ },61+ },62+ },63+ path: '/my/path',64+ protocol: 'HTTP/1.1',65+ requestId: 'id=',66+ requestTime: '04/Mar/2020:19:15:17 +0000',67+ requestTimeEpoch: 1583349317135,68+ resourcePath: '/my/path',69+ stage: '$default',70+ },71+ pathParameters: {},72+ stageVariables: {},73+ body: null,74+ isBase64Encoded: false,75+ }76+77+ it('Should encode as base64 when content-type is in contentTypesAsBinary array', async () => {78+ const processor = getProcessor(event)79+ const response = new Response('test content', {80+ headers: { 'content-type': 'application/custom' },81+ })82+83+ const result = await processor.createResult(event, response, {84+ isContentTypeBinary: (contentType: string) => contentType === 'application/custom',85+ })86+87+ expect(result.isBase64Encoded).toBe(true)88+ expect(result.body).toBe('dGVzdCBjb250ZW50')89+ })90+91+ it('Should not encode as base64 when content-type is not in isContentTypeBinary array', async () => {92+ const processor = getProcessor(event)93+ const response = new Response('test content', {94+ headers: { 'content-type': 'application/json' },95+ })96+97+ const result = await processor.createResult(event, response, {98+ isContentTypeBinary: (contentType: string) => contentType === 'application/custom',99+ })100+101+ expect(result.isBase64Encoded).toBe(false)102+ expect(result.body).toBe('test content')103+ })104+105+ it('Should use defaultIsContentTypeBinary when isContentTypeBinary is undefined with binary content', async () => {106+ const processor = getProcessor(event)107+ const response = new Response('test image content', {108+ headers: { 'content-type': 'image/png' },109+ })110+111+ // Pass undefined for isContentTypeBinary to test default behavior112+ const result = await processor.createResult(event, response, {113+ isContentTypeBinary: undefined,114+ })115+116+ expect(result.isBase64Encoded).toBe(true)117+ expect(result.body).toBe('dGVzdCBpbWFnZSBjb250ZW50')118+ })119+120+ it('Should use defaultIsContentTypeBinary when isContentTypeBinary is undefined with non-binary content', async () => {121+ const processor = getProcessor(event)122+ const response = new Response('test text content', {123+ headers: { 'content-type': 'text/plain' },124+ })125+126+ // Pass undefined for isContentTypeBinary to test default behavior127+ const result = await processor.createResult(event, response, {128+ isContentTypeBinary: undefined,129+ })130+131+ expect(result.isBase64Encoded).toBe(false)132+ expect(result.body).toBe('test text content')133+ })134+})135+136 describe('EventProcessor.createRequest', () => {137 it('Should return valid Request object from version 1.0 API Gateway event', () => {138 const event: LambdaEvent = {139 version: '1.0',136 unmodified linesmodified:src/adapter/aws-lambda/handler.ts+59 added-5 removed
160 unmodified lines161 }162 )163 }164 165+type HandleOptions = {166+ isContentTypeBinary: ((contentType: string) => boolean) | undefined167+}168+169 /**166- * Accepts events from API Gateway/ELB(`APIGatewayProxyEvent`) and directly through Function Url(`APIGatewayProxyEventV2`)170+ * Converts a Hono application to an AWS Lambda handler.171+ *172+ * Accepts events from API Gateway (v1 and v2), Application Load Balancer (ALB),173+ * and Lambda Function URLs.174+ *175+ * @param app - The Hono application instance176+ * @param options - Optional configuration177+ * @param options.isContentTypeBinary - A function to determine if the content type is binary.178+ * If not provided, the default function will be used.179+ * @returns Lambda handler function180+ *181+ * @example182+ * ```js183+ * import { Hono } from 'hono'184+ * import { handle } from 'hono/aws-lambda'185+ *186+ * const app = new Hono()187+ *188+ * app.get('/', (c) => c.text('Hello from Lambda'))189+ * app.get('/json', (c) => c.json({ message: 'Hello JSON' }))190+ *191+ * export const handler = handle(app)192+ * ```193+ *194+ * @example195+ * ```js196+ * // With custom binary content type detection197+ * import { handle, defaultIsContentTypeBinary } from 'hono/aws-lambda'198+ * export const handler = handle(app, {199+ * isContentTypeBinary: (contentType) => {200+ * if (defaultIsContentTypeBinary(contentType)) {201+ * // default logic same as prior to v4.8.4202+ * return true203+ * }204+ * return contentType.startsWith('image/') || contentType === 'application/pdf'205+ * }206+ * })207+ * ```208 */209 export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(169- app: Hono<E, S, BasePath>210+ app: Hono<E, S, BasePath>,211+ { isContentTypeBinary }: HandleOptions = { isContentTypeBinary: undefined }212 ): (<L extends LambdaEvent>(213 event: L,214 lambdaContext?: LambdaContext215 ) => Promise<14 unmodified lines230 requestContext,231 lambdaContext,232 })233 192- return processor.createResult(event, res)234+ return processor.createResult(event, res, { isContentTypeBinary })235 }236 }237 238 export abstract class EventProcessor<E extends LambdaEvent> {33 unmodified lines272 273 return new Request(url, requestInit)274 }275 234- async createResult(event: E, res: Response): Promise<APIGatewayProxyResult> {276+ async createResult(277+ event: E,278+ res: Response,279+ options: Pick<HandleOptions, 'isContentTypeBinary'>280+ ): Promise<APIGatewayProxyResult> {281+ // determine whether the response body should be base64 encoded282 const contentType = res.headers.get('content-type')283+ const isContentTypeBinary = options.isContentTypeBinary ?? defaultIsContentTypeBinary // overwrite default function if provided284 let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false285 286 if (!isBase64Encoded) {287 const contentEncoding = res.headers.get('content-encoding')249 unmodified lines537 const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {538 return Object.hasOwn(event, 'rawPath')539 }540 493-export const isContentTypeBinary = (contentType: string) => {541+/**542+ * Check if the given content type is binary.543+ * This is a default function and may be overwritten by the user via `isContentTypeBinary` option in handler().544+ * @param contentType The content type to check.545+ * @returns True if the content type is binary, false otherwise.546+ */547+export const defaultIsContentTypeBinary = (contentType: string): boolean => {548 return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(549 contentType550 )551 }7 unmodified linesmodified:src/adapter/aws-lambda/index.ts+1 added-1 removed
1234566789103 unmodified lines/** * @module * AWS Lambda Adapter for Hono. */
export { handle, streamHandle } from './handler'export { handle, streamHandle, defaultIsContentTypeBinary } from './handler'export type { APIGatewayProxyResult, LambdaEvent } from './handler'export type { ApiGatewayRequestContext, ApiGatewayRequestContextV2,3 unmodified linesmodified:src/adapter/bun/index.ts+1 added-1 removed
3 unmodified lines4567889103 unmodified lines */
export { serveStatic } from './serve-static'export { bunFileSystemModule, toSSG } from './ssg'export { createBunWebSocket } from './websocket'export { createBunWebSocket, upgradeWebSocket, websocket } from './websocket'export type { BunWebSocketData, BunWebSocketHandler } from './websocket'export { getConnInfo } from './conninfo'modified:src/adapter/bun/serve-static.ts+2 added-5 removed
1234567891011121213141516171819171819203 unmodified lines24252627312829303132/* eslint-disable @typescript-eslint/ban-ts-comment */import { stat } from 'node:fs/promises'import { join } from 'node:path'import { serveStatic as baseServeStatic } from '../../middleware/serve-static'import type { ServeStaticOptions } from '../../middleware/serve-static'import type { Env, MiddlewareHandler } from '../../types'
export const serveStatic = <E extends Env = Env>( options: ServeStaticOptions<E>): MiddlewareHandler => { return async function serveStatic(c, next) { const getContent = async (path: string) => { path = path.startsWith('/') ? path : `./${path}` // @ts-ignore const file = Bun.file(path) return (await file.exists()) ? file : null } const pathResolve = (path: string) => { return path.startsWith('/') ? path : `./${path}` } const isDir = async (path: string) => { let isDir try { const stats = await stat(path)3 unmodified lines } return baseServeStatic({ ...options, getContent, pathResolve, join, isDir, })(c, next) }}modified:src/adapter/bun/websocket.test.ts+17 added-17 removed
1233456713 unmodified lines2122232425262728293031323326343536375 unmodified lines4344454640474849503 unmodified lines5455565752585960612 unmodified lines64656667636465666768697071726874756970717239 unmodified lines112113114115123116117118119120121122123124125126127import { Context } from '../../context'import type { BunWebSocketData, BunServerWebSocket } from './websocket'import { createWSContext, createBunWebSocket } from './websocket'import { createWSContext, websocket, upgradeWebSocket, createBunWebSocket } from './websocket'
describe('createWSContext()', () => { it('Should send() and close() works', () => { const send = vi.fn()13 unmodified lines expect(close).toBeCalled() })})describe('upgradeWebSocket()', () => { beforeAll(() => { // @ts-expect-error patch global globalThis.CloseEvent = Event }) afterAll(() => { // @ts-expect-error patch global delete globalThis.CloseEvent }) it('Should throw error when server is null', async () => { const { upgradeWebSocket } = createBunWebSocket() const run = async () => await upgradeWebSocket(() => ({}))( new Context(new Request('http://localhost'), { env: {5 unmodified lines
await expect(run).rejects.toThrowError(/env has/) }) it('Should response null when upgraded', async () => { const { upgradeWebSocket } = createBunWebSocket() const upgraded = await upgradeWebSocket(() => ({}))( new Context(new Request('http://localhost'), { env: { upgrade: () => true,3 unmodified lines ) expect(upgraded).toBeTruthy() }) it('Should response undefined when upgrade failed', async () => { const { upgradeWebSocket } = createBunWebSocket() const upgraded = await upgradeWebSocket(() => ({}))( new Context(new Request('http://localhost'), { env: { upgrade: () => undefined,2 unmodified lines () => Promise.resolve() ) expect(upgraded).toBeFalsy() })})describe('createBunWebSocket()', () => { beforeAll(() => { // @ts-expect-error patch global globalThis.CloseEvent = Event }) afterAll(() => { // @ts-expect-error patch global delete globalThis.CloseEvent }) it('Should events are called', async () => { const { websocket, upgradeWebSocket } = createBunWebSocket()
const open = vi.fn() const message = vi.fn() const close = vi.fn()
39 unmodified lines
websocket.message(ws, new Uint8Array(16)) expect(receivedArrayBuffer).toBeInstanceOf(ArrayBuffer) expect(receivedArrayBuffer!.byteLength).toBe(16)
websocket.close(ws) expect(close).toBeCalled() })})
describe('createBunWebSocket()', () => { it('Should create a BunWebSocket', () => { const { upgradeWebSocket, websocket } = createBunWebSocket() expect(upgradeWebSocket).toBe(upgradeWebSocket) expect(websocket).toBe(websocket) })})modified:src/adapter/bun/websocket.ts+52 added-52 removed
43 unmodified lines44 },45 })46 }47 48-export const createBunWebSocket = <T>(): CreateWebSocket<T> => {49- // eslint-disable-next-line @typescript-eslint/no-explicit-any50- const upgradeWebSocket: UpgradeWebSocket<any> = defineWebSocketHelper((c, events) => {51- const server = getBunServer(c)52- if (!server) {53- throw new TypeError('env has to include the 2nd argument of fetch.')48+export const upgradeWebSocket: UpgradeWebSocket<any> = defineWebSocketHelper((c, events) => {49+ const server = getBunServer(c)50+ if (!server) {51+ throw new TypeError('env has to include the 2nd argument of fetch.')52+ }53+ const upgradeResult = server.upgrade<BunWebSocketData>(c.req.raw, {54+ data: {55+ events,56+ url: new URL(c.req.url),57+ protocol: c.req.url,58+ },59+ })60+ if (upgradeResult) {61+ return new Response(null)62+ }63+ return // failed64+})65+66+export const websocket: BunWebSocketHandler<BunWebSocketData> = {67+ open(ws) {68+ const websocketListeners = ws.data.events69+ if (websocketListeners.onOpen) {70+ websocketListeners.onOpen(new Event('open'), createWSContext(ws))71 }55- const upgradeResult = server.upgrade<BunWebSocketData>(c.req.raw, {56- data: {57- events,58- url: new URL(c.req.url),59- protocol: c.req.url,60- },61- })62- if (upgradeResult) {63- return new Response(null)72+ },73+ close(ws, code, reason) {74+ const websocketListeners = ws.data.events75+ if (websocketListeners.onClose) {76+ websocketListeners.onClose(77+ new CloseEvent('close', {78+ code,79+ reason,80+ }),81+ createWSContext(ws)82+ )83 }65- return // failed66- })67- const websocket: BunWebSocketHandler<BunWebSocketData> = {68- open(ws) {69- const websocketListeners = ws.data.events70- if (websocketListeners.onOpen) {71- websocketListeners.onOpen(new Event('open'), createWSContext(ws))72- }73- },74- close(ws, code, reason) {75- const websocketListeners = ws.data.events76- if (websocketListeners.onClose) {77- websocketListeners.onClose(78- new CloseEvent('close', {79- code,80- reason,81- }),82- createWSContext(ws)83- )84- }85- },86- message(ws, message) {87- const websocketListeners = ws.data.events88- if (websocketListeners.onMessage) {89- const normalizedReceiveData =90- typeof message === 'string' ? message : (message.buffer satisfies WSMessageReceive)84+ },85+ message(ws, message) {86+ const websocketListeners = ws.data.events87+ if (websocketListeners.onMessage) {88+ const normalizedReceiveData =89+ typeof message === 'string' ? message : (message.buffer satisfies WSMessageReceive)90 92- websocketListeners.onMessage(93- createWSMessageEvent(normalizedReceiveData),94- createWSContext(ws)95- )96- }97- },91+ websocketListeners.onMessage(createWSMessageEvent(normalizedReceiveData), createWSContext(ws))92+ }93+ },98- }99- return {100- upgradeWebSocket,101- websocket,102- }94 }95+96+/**97+ * @deprecated Import `createWebSocket` and `websocket` directly from `hono/bun` instead.98+ * @returns A function to create a Bun WebSocket handler.99+ */100+export const createBunWebSocket = <T>(): CreateWebSocket<T> => ({101+ upgradeWebSocket,102+ websocket,103+})modified:src/adapter/cloudflare-workers/serve-static.test.ts+2 added-1 removed
77 unmodified lines78 expect(await res.text()).toBe('That is plain.txt')79 expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')80 })81 82+ // Serve static on Cloudflare Workers cannot determine whether the target path is a directory or not82- it('Should return index.html', async () => {83+ it.skip('Should return index.html', async () => {84 const res = await app.request('http://localhost/static/top')85 expect(res.status).toBe(200)86 expect(await res.text()).toBe('<h1>Top</h1>')87 expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')134 unmodified linesmodified:src/adapter/deno/serve-static.ts+2 added-5 removed
1+import { join } from 'node:path'2 import type { ServeStaticOptions } from '../../middleware/serve-static'3 import { serveStatic as baseServeStatic } from '../../middleware/serve-static'4 import type { Env, MiddlewareHandler } from '../../types'5 17 unmodified lines23 }24 return null25 }26 }26- const pathResolve = (path: string) => {27- return path.startsWith('/') ? path : `./${path}`28- }27 const isDir = (path: string) => {28 let isDir29 try {30 const stat = lstatSync(path)31 isDir = stat.isDirectory32 } catch {}33 return isDir34 }37-35 return baseServeStatic({36 ...options,37 getContent,41- pathResolve,38+ join,39 isDir,40 })(c, next)41 }42 }added:src/client/fetch-result-please.ts+85 added
1+/**2+ * @description This file is a modified version of `fetch-result-please` (`ofetch`), minimalized and adapted to Hono's custom needs.3+ *4+ * @link https://www.npmjs.com/package/fetch-result-please5+ */6+7+const nullBodyResponses = new Set([101, 204, 205, 304])8+9+/**10+ * Smartly parses and return the consumable result from a fetch `Response`.11+ *12+ * Throwing a structured error if the response is not `ok`. ({@link DetailedError})13+ */14+export async function fetchRP(fetchRes: Response | Promise<Response>): Promise<any> {15+ const _fetchRes = (await fetchRes) as unknown as Response & { _data: any }16+17+ const hasBody = _fetchRes.body && !nullBodyResponses.has(_fetchRes.status)18+19+ if (hasBody) {20+ const responseType = detectResponseType(_fetchRes)21+ _fetchRes._data = await _fetchRes[responseType]()22+ }23+24+ if (!_fetchRes.ok) {25+ throw new DetailedError(`${_fetchRes.status} ${_fetchRes.statusText}`, {26+ statusCode: _fetchRes?.status,27+ detail: {28+ data: _fetchRes?._data,29+ statusText: _fetchRes?.statusText,30+ },31+ })32+ }33+34+ return _fetchRes._data35+}36+37+export class DetailedError extends Error {38+ /**39+ * Additional `message` that will be logged AND returned to client40+ */41+ public detail?: any42+ /**43+ * Additional `code` that will be logged AND returned to client44+ */45+ public code?: any46+ /**47+ * Additional value that will be logged AND NOT returned to client48+ */49+ public log?: any50+ /**51+ * Optionally set the status code to return, in a web server context52+ */53+ public statusCode?: any54+55+ constructor(56+ message: string,57+ options: { detail?: any; code?: any; statusCode?: number; log?: any } = {}58+ ) {59+ super(message)60+ this.log = options.log61+ this.detail = options.detail62+ this.code = options.code63+ this.statusCode = options.statusCode64+ }65+}66+67+// This is used to match the content-type header for 'json'68+const jsonRegex = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(?:;.+)?$/i69+70+function detectResponseType(response: Response): 'json' | 'text' {71+ const _contentType = response.headers.get('content-type')72+73+ if (!_contentType) {74+ return 'text'75+ }76+77+ // `_contentType` might look like: `application/json; charset=utf-8`, `text/plain`, so we get the first part before `;`78+ const contentType = _contentType.split(';').shift()!79+80+ if (jsonRegex.test(contentType)) {81+ return 'json'82+ }83+84+ return 'text'85+}modified:src/client/index.ts+1 added
2 unmodified lines3 * The HTTP Client for Hono.4 */5 6 export { hc } from './client'7+export { parseResponse, DetailedError } from './utils'8 export type {9 InferResponseType,10 InferRequestType,11 Fetch,4 unmodified linesmodified:src/client/utils.test.ts+100 added
1+import { HttpResponse, http } from 'msw'2+import { setupServer } from 'msw/node'3+import { Hono } from '../hono'4+import type { Expect, Equal } from '../utils/types'5+import { hc } from './client'6 import {7 buildSearchParams,8 deepMerge,9+ parseResponse,10 mergePath,11 removeIndexString,12 replaceUrlParam,13 replaceUrlProtocol,130 unmodified lines144 timeout: 2,145 })146 })147 })148+149+describe('parseResponse', async () => {150+ const app = new Hono()151+ .get('/text', (c) => c.text('hi'))152+ .get('/json', (c) => c.json({ message: 'hi' }))153+ .get('/404', (c) => c.notFound())154+ .get('/raw', (c) => {155+ c.header('content-type', '')156+ return c.body('hello')157+ })158+ .get('/rawUnknown', (c) => {159+ c.header('content-type', 'x/custom-type')160+ return c.body('hello')161+ })162+ .get('/rawBuffer', (c) => {163+ c.header('content-type', 'x/custom-type')164+ return c.body(new TextEncoder().encode('hono'))165+ })166+167+ const client = hc<typeof app>('http://localhost')168+169+ const server = setupServer(170+ http.get('http://localhost/text', () => {171+ return HttpResponse.text('hi')172+ }),173+ http.get('http://localhost/json', () => {174+ return HttpResponse.json({ message: 'hi' })175+ }),176+ http.get('http://localhost/404', () => {177+ return HttpResponse.text('404 Not Found', { status: 404 })178+ }),179+ http.get('http://localhost/raw', () => {180+ return HttpResponse.text('hello', {181+ headers: {182+ 'content-type': '',183+ },184+ })185+ }),186+ http.get('http://localhost/rawUnknown', () => {187+ return HttpResponse.text('hello', {188+ headers: {189+ 'content-type': 'x/custom-type',190+ },191+ })192+ }),193+ http.get('http://localhost/rawBuffer', () => {194+ return HttpResponse.arrayBuffer(new TextEncoder().encode('hono'), {195+ headers: {196+ 'content-type': 'x/custom-type',197+ },198+ })199+ })200+ )201+202+ beforeAll(() => server.listen())203+ afterEach(() => server.resetHandlers())204+ afterAll(() => server.close())205+206+ await Promise.all([207+ it('should auto parse the text response - async fetch', async () => {208+ const result = await parseResponse(client.text.$get())209+ expect(result).toBe('hi')210+ type _verify = Expect<Equal<typeof result, 'hi'>>211+ }),212+ it('should auto parse the text response - sync fetch', async () => {213+ const result = await parseResponse(await client.text.$get())214+ expect(result).toBe('hi')215+ type _verify = Expect<Equal<typeof result, 'hi'>>216+ }),217+ it('should auto parse the json response - async fetch', async () => {218+ const result = await parseResponse(client.json.$get())219+ expect(result).toEqual({ message: 'hi' })220+ type _verify = Expect<Equal<typeof result, { message: string }>>221+ }),222+ it('should auto parse the json response - sync fetch', async () => {223+ const result = await parseResponse(await client.json.$get())224+ expect(result).toEqual({ message: 'hi' })225+ type _verify = Expect<Equal<typeof result, { message: string }>>226+ }),227+ it('should throw error when the response is not ok', async () => {228+ await expect(parseResponse(client['404'].$get())).rejects.toThrowError('404 Not Found')229+ }),230+ it('should parse as text for raw responses without content-type header', async () => {231+ const result = await parseResponse(client.raw.$get())232+ expect(result).toBe('hello')233+ type _verify = Expect<Equal<typeof result, 'hello'>>234+ }),235+ it('should parse as unknown string for raw buffer responses with unknown content-type header', async () => {236+ const result = await parseResponse(client.rawBuffer.$get())237+ expect(result).toMatchInlineSnapshot('"hono"')238+ type _verify = Expect<Equal<typeof result, string>>239+ }),240+ ])241+})modified:src/client/utils.ts+26 added-1 removed
1+import { fetchRP, DetailedError } from './fetch-result-please'1-import type { ObjectType } from './types'2+import type { ClientResponse, ObjectType } from './types'3 4+export { DetailedError }5+6 export const mergePath = (base: string, path: string) => {7 base = base.replace(/\/+$/, '')8 base = base + '/'9 path = path.replace(/^\/+/, '')64 unmodified lines74 }75 76 return merged as T77 }78+79+/**80+ * Shortcut to get a consumable response from `hc`'s fetch calls (Response), with types inference.81+ *82+ * Smartly parse the response data, throwing a structured error if the response is not `ok`. ({@link DetailedError})83+ *84+ * @example const result = await parseResponse(client.posts.$get())85+ */86+// eslint-disable-next-line @typescript-eslint/no-explicit-any87+export async function parseResponse<T extends ClientResponse<any>>(88+ fetchRes: T | Promise<T>89+): Promise<90+ T extends ClientResponse<infer RT, infer _, infer RF>91+ ? RF extends 'json'92+ ? RT93+ : RT extends string94+ ? RT95+ : string96+ : never97+> {98+ return fetchRP(fetchRes)99+}modified:src/helper/cookie/index.test.ts+54 added-1 removed
1 import { Hono } from '../../hono'2-import { deleteCookie, getCookie, getSignedCookie, setCookie, setSignedCookie } from '.'2+import {3+ deleteCookie,4+ getCookie,5+ getSignedCookie,6+ setCookie,7+ setSignedCookie,8+ generateCookie,9+ generateSignedCookie,10+} from '.'11 12 describe('Cookie Middleware', () => {13 describe('Parse cookie', () => {14 const apps: Record<string, Hono> = {}437 unmodified lines452 expect(res.status).toBe(200)453 expect(await res.text()).toBe('choco')454 })455 })456+457+ describe('Generate cookie', () => {458+ it('should generate a cookie', () => {459+ const cookie = generateCookie('delicious_cookie', 'macha')460+ expect(cookie).toBe('delicious_cookie=macha; Path=/')461+ })462+463+ it('should generate a cookie with options', () => {464+ const cookie = generateCookie('delicious_cookie', 'macha', {465+ path: '/',466+ secure: true,467+ httpOnly: true,468+ domain: 'example.com',469+ })470+ expect(cookie).toBe('delicious_cookie=macha; Domain=example.com; Path=/; HttpOnly; Secure')471+ })472+473+ it('should generate a signed cookie', async () => {474+ const cookie = await generateSignedCookie(475+ 'delicious_cookie',476+ 'macha',477+ 'secret chocolate chips'478+ )479+ expect(cookie).toBe(480+ 'delicious_cookie=macha.diubJPY8O7hI1pLa42QSfkPiyDWQ0I4DnlACH%2FN2HaA%3D; Path=/'481+ )482+ })483+484+ it('should generate a signed cookie with options', async () => {485+ const cookie = await generateSignedCookie(486+ 'delicious_cookie',487+ 'macha',488+ 'secret chocolate chips',489+ {490+ path: '/',491+ secure: true,492+ httpOnly: true,493+ domain: 'example.com',494+ }495+ )496+ expect(cookie).toBe(497+ 'delicious_cookie=macha.diubJPY8O7hI1pLa42QSfkPiyDWQ0I4DnlACH%2FN2HaA%3D; Domain=example.com; Path=/; HttpOnly; Secure'498+ )499+ })500+ })501 })modified:src/helper/cookie/index.ts+19 added-4 removed
73 unmodified lines74 // eslint-disable-next-line @typescript-eslint/no-explicit-any75 return obj as any76 }77 78-export const setCookie = (c: Context, name: string, value: string, opt?: CookieOptions): void => {78+export const generateCookie = (name: string, value: string, opt?: CookieOptions): string => {79 // Cookie names prefixed with __Secure- can be used only if they are set with the secure attribute.80 // Cookie names prefixed with __Host- can be used only if they are set with the secure attribute, must have a path of / (meaning any path at the host)81 // and must not have a Domain attribute.82 // Read more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#cookie_prefixes'9 unmodified lines92 })93 } else {94 cookie = serialize(name, value, { path: '/', ...opt })95 }96+ return cookie97+}98+99+export const setCookie = (c: Context, name: string, value: string, opt?: CookieOptions): void => {100+ const cookie = generateCookie(name, value, opt)101 c.header('Set-Cookie', cookie, { append: true })102 }103 99-export const setSignedCookie = async (100- c: Context,104+export const generateSignedCookie = async (105 name: string,106 value: string,107 secret: string | BufferSource,108 opt?: CookieOptions105-): Promise<void> => {109+): Promise<string> => {110 let cookie111 if (opt?.prefix === 'secure') {112 cookie = await serializeSigned('__Secure-' + name, value, secret, {113 path: '/',9 unmodified lines123 })124 } else {125 cookie = await serializeSigned(name, value, secret, { path: '/', ...opt })126 }127+ return cookie128+}129+130+export const setSignedCookie = async (131+ c: Context,132+ name: string,133+ value: string,134+ secret: string | BufferSource,135+ opt?: CookieOptions136+): Promise<void> => {137+ const cookie = await generateSignedCookie(name, value, secret, opt)138 c.header('set-cookie', cookie, { append: true })139 }140 141 export const deleteCookie = (c: Context, name: string, opt?: CookieOptions): string | undefined => {4 unmodified linesmodified:src/helper/ssg/ssg.ts+9 added
166 unmodified lines167 }168 169 export interface ToSSGOptions {170 dir?: string171+ /**172+ * @deprecated Use plugins[].beforeRequestHook instead.173+ */174 beforeRequestHook?: BeforeRequestHook | BeforeRequestHook[]175+ /**176+ * @deprecated Use plugins[].afterResponseHook instead.177+ */178 afterResponseHook?: AfterResponseHook | AfterResponseHook[]179+ /**180+ * @deprecated Use plugins[].afterGenerateHook instead.181+ */182 afterGenerateHook?: AfterGenerateHook | AfterGenerateHook[]183 concurrency?: number184 extensionMap?: Record<string, string>185 plugins?: SSGPlugin[]273 unmodified linesmodified:src/middleware/jwk/index.test.ts+55 added-4 removed
5 unmodified lines6 import { encodeBase64Url } from '../../utils/encode'7 import { Jwt } from '../../utils/jwt'8 import type { HonoJsonWebKey } from '../../utils/jwt/jws'9 import { signing } from '../../utils/jwt/jws'10-import { verifyFromJwks } from '../../utils/jwt/jwt'10+import { verifyWithJwks } from '../../utils/jwt/jwt'11 import type { JWTPayload } from '../../utils/jwt/types'12 import { utf8Encoder } from '../../utils/jwt/utf8'13 import * as test_keys from './keys.test.json'14 import { jwk } from '.'18 unmodified lines33 beforeAll(() => server.listen())34 afterEach(() => server.resetHandlers())35 afterAll(() => server.close())36 37- describe('verifyFromJwks', () => {37+ describe('verifyWithJwks', () => {38 it('Should throw error on missing options', async () => {39 const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])40- await expect(verifyFromJwks(credential, {})).rejects.toThrow(41- 'verifyFromJwks requires options for either "keys" or "jwks_uri" or both'40+ await expect(verifyWithJwks(credential, {})).rejects.toThrow(41+ 'verifyWithJwks requires options for either "keys" or "jwks_uri" or both'42 )43 })44 })45 387 unmodified lines433 expect(handlerExecuted).toBeTruthy()434 })435 })436 437+ describe('Credentials in custom header', () => {438+ let handlerExecuted: boolean439+440+ beforeEach(() => {441+ handlerExecuted = false442+ })443+444+ const app = new Hono()445+446+ app.use('/auth-with-keys/*', jwk({ keys: verify_keys, headerName: 'x-custom-auth-header' }))447+448+ app.get('/auth-with-keys/*', (c) => {449+ handlerExecuted = true450+ const payload = c.get('jwtPayload')451+ return c.json(payload)452+ })453+454+ it('Should not authorize', async () => {455+ const req = new Request('http://localhost/auth-with-keys/a')456+ const res = await app.request(req)457+ expect(res).not.toBeNull()458+ expect(res.status).toBe(401)459+ expect(await res.text()).toBe('Unauthorized')460+ expect(handlerExecuted).toBeFalsy()461+ })462+463+ it('Should not authorize even if default authorization header present', async () => {464+ const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[0])465+466+ const req = new Request('http://localhost/auth-with-keys/a')467+ req.headers.set('Authorization', `Bearer ${credential}`)468+ const res = await app.request(req)469+ expect(res).not.toBeNull()470+ expect(res.status).toBe(401)471+ expect(await res.text()).toBe('Unauthorized')472+ expect(handlerExecuted).toBeFalsy()473+ })474+475+ it('Should authorize', async () => {476+ const credential = await Jwt.sign({ message: 'hello world' }, test_keys.private_keys[1])477+478+ const req = new Request('http://localhost/auth-with-keys/a')479+ req.headers.set('x-custom-auth-header', `Bearer ${credential}`)480+ const res = await app.request(req)481+ expect(res).not.toBeNull()482+ expect(res.status).toBe(200)483+ expect(await res.json()).toEqual({ message: 'hello world' })484+ expect(handlerExecuted).toBeTruthy()485+ })486+ })487+488 describe('Credentials in cookie', () => {489 let handlerExecuted: boolean490 491 beforeEach(() => {255 unmodified linesmodified:src/middleware/jwk/jwk.ts+17 added-3 removed
9 unmodified lines10 import type { CookiePrefixOptions } from '../../utils/cookie'11 import { Jwt } from '../../utils/jwt'12 import '../../context'13 import type { HonoJsonWebKey } from '../../utils/jwt/jws'14+import type { VerifyOptions } from '../../utils/jwt/jwt'15 16 /**17 * JWK Auth Middleware for Hono.18 *3 unmodified lines22 * @param {HonoJsonWebKey[] | ((ctx: Context) => Promise<HonoJsonWebKey[]> | HonoJsonWebKey[])} [options.keys] - The public keys used for JWK verification, or a function that returns them.23 * @param {string | ((ctx: Context) => Promise<string> | string)} [options.jwks_uri] - If set to a URI string or a function that returns a URI string, attempt to fetch JWKs from it. The response must be a JSON object containing a `keys` array, which will be merged with the `keys` option.24 * @param {boolean} [options.allow_anon] - If set to `true`, the middleware allows requests without a token to proceed without authentication.25 * @param {string} [options.cookie] - If set, the middleware attempts to retrieve the token from a cookie with these options (optionally signed) only if no token is found in the header.26+ * @param {string} [options.headerName='Authorization'] - The name of the header to look for the JWT token. Default is 'Authorization'.27 * @param {RequestInit} [init] - Optional init options for the `fetch` request when retrieving JWKS from a URI.28+ * @param {VerifyOptions} [options.verification] - Additional options for JWK payload verification.29 * @returns {MiddlewareHandler} The middleware handler function.30 *31 * @example32 * ```ts33 * const app = new Hono()34 *32- * app.use("/auth/*", jwk({ jwks_uri: (c) => `https://${c.env.authServer}/.well-known/jwks.json` }))35+ * app.use("/auth/*", jwk({36+ * jwks_uri: (c) => `https://${c.env.authServer}/.well-known/jwks.json`,37+ * headerName: 'x-custom-auth-header', // Optional, default is 'Authorization'38+ * }))39 *40 * app.get('/auth/page', (c) => {41 * return c.text('You are authorized')42 * })7 unmodified lines50 allow_anon?: boolean51 cookie?:52 | string53 | { key: string; secret?: string | BufferSource; prefixOptions?: CookiePrefixOptions }54+55+ headerName?: string56+57+ verification?: VerifyOptions58 },59 init?: RequestInit60 ): MiddlewareHandler => {61+ const verifyOpts = options.verification || {}62+63 if (!options || !(options.keys || options.jwks_uri)) {64 throw new Error('JWK auth middleware requires options for either "keys" or "jwks_uri" or both')65 }66 1 unmodified line68 throw new Error('`crypto.subtle.importKey` is undefined. JWK auth middleware requires it.')69 }70 71 return async function jwk(ctx, next) {72+ const headerName = options.headerName || 'Authorization'73+60- const credentials = ctx.req.raw.headers.get('Authorization')74+ const credentials = ctx.req.raw.headers.get(headerName)75 let token76 if (credentials) {77 const parts = credentials.split(/\s+/)78 if (parts.length !== 2) {52 unmodified lines131 try {132 const keys = typeof options.keys === 'function' ? await options.keys(ctx) : options.keys133 const jwks_uri =134 typeof options.jwks_uri === 'function' ? await options.jwks_uri(ctx) : options.jwks_uri121- payload = await Jwt.verifyFromJwks(token, { keys, jwks_uri }, init)135+ payload = await Jwt.verifyWithJwks(token, { keys, jwks_uri, verification: verifyOpts }, init)136 } catch (e) {137 cause = e138 }139 36 unmodified linesmodified:src/middleware/jwt/index.ts+1 added-1 removed
1 import type { JwtVariables } from './jwt'2 export type { JwtVariables }3-export { jwt, verify, decode, sign } from './jwt'3+export { jwt, verifyWithJwks, verify, decode, sign } from './jwt'4 import type {} from '../..'5 6 declare module '../..' {7 interface ContextVariableMap extends JwtVariables {}1 unmodified linemodified:src/middleware/jwt/jwt.ts+10 added-1 removed
10 unmodified lines11 import { Jwt } from '../../utils/jwt'12 import '../../context'13 import type { SignatureAlgorithm } from '../../utils/jwt/jwa'14 import type { SignatureKey } from '../../utils/jwt/jws'15+import type { VerifyOptions } from '../../utils/jwt/jwt'16 17 // eslint-disable-next-line @typescript-eslint/no-explicit-any18 export type JwtVariables<T = any> = {19 jwtPayload: T8 unmodified lines28 * @param {SignatureKey} [options.secret] - A value of your secret key.29 * @param {string} [options.cookie] - If this value is set, then the value is retrieved from the cookie header using that value as a key, which is then validated as a token.30 * @param {SignatureAlgorithm} [options.alg=HS256] - An algorithm type that is used for verifying. Available types are `HS256` | `HS384` | `HS512` | `RS256` | `RS384` | `RS512` | `PS256` | `PS384` | `PS512` | `ES256` | `ES384` | `ES512` | `EdDSA`.31 * @param {string} [options.headerName='Authorization'] - The name of the header to look for the JWT token. Default is 'Authorization'.32+ * @param {VerifyOptions} [options.verification] - Additional options for JWT payload verification.33 * @returns {MiddlewareHandler} The middleware handler function.34 *35 * @example36 * ```ts18 unmodified lines55 | string56 | { key: string; secret?: string | BufferSource; prefixOptions?: CookiePrefixOptions }57 alg?: SignatureAlgorithm58 headerName?: string59+ verification?: VerifyOptions60 }): MiddlewareHandler => {61+ const verifyOpts = options.verification || {}62+63 if (!options || !options.secret) {64 throw new Error('JWT auth middleware requires options for "secret"')65 }66 58 unmodified lines125 126 let payload127 let cause128 try {124- payload = await Jwt.verify(token, options.secret, options.alg)129+ payload = await Jwt.verify(token, options.secret, {130+ alg: options.alg,131+ ...verifyOpts,132+ })133 } catch (e) {134 cause = e135 }136 if (!payload) {29 unmodified lines166 },167 })168 }169 170+export const verifyWithJwks = Jwt.verifyWithJwks171 export const verify = Jwt.verify172 export const decode = Jwt.decode173 export const sign = Jwt.signmodified:src/middleware/serve-static/index.test.ts+10 added-26 removed
10 unmodified lines11 })12 13 const serveStatic = baseServeStatic({14 getContent,15- pathResolve: (path) => {16- return `./${path}`17- },15 isDir: (path) => {19- return path === 'static/hello.world'16+ if (path === 'static/sub' || path === 'static/hello.world') {17+ return true18+ }19 },20 onFound: (path, c) => {21 if (path.endsWith('hello.html')) {22 c.header('X-Custom', `Found the file at ${path}`)11 unmodified lines34 const res = await app.request('/static/hello.html')35 expect(res.status).toBe(200)36 expect(res.headers.get('Content-Encoding')).toBeNull()37 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')38+ expect(await res.text()).toBe('Hello in static/hello.html')39+ expect(res.headers.get('X-Custom')).toBe('Found the file at static/hello.html')40 })41 42 it('Should return 200 response - /static/sub', async () => {43 const res = await app.request('/static/sub')44 expect(res.status).toBe(200)45 expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)47- expect(await res.text()).toBe('Hello in ./static/sub/index.html')46+ expect(await res.text()).toBe('Hello in static/sub/index.html')47 })48 50- it('Should return 200 response - /static/helloworld', async () => {51- const res = await app.request('/static/helloworld')52- expect(res.status).toBe(200)53- expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)54- expect(await res.text()).toBe('Hello in ./static/helloworld/index.html')55- })56-49 it('Should return 200 response - /static/hello.world', async () => {50 const res = await app.request('/static/hello.world')51 expect(res.status).toBe(200)52 expect(res.headers.get('Content-Type')).toMatch(/^text\/html/)61- expect(await res.text()).toBe('Hello in ./static/hello.world/index.html')53+ expect(await res.text()).toBe('Hello in static/hello.world/index.html')54 })55 56 it('Should decode URI strings - /static/%E7%82%8E.txt', async () => {57 const res = await app.request('/static/%E7%82%8E.txt')58 expect(res.status).toBe(200)59 expect(res.headers.get('Content-Type')).toMatch(/^text\/plain/)68- expect(await res.text()).toBe('Hello in ./static/炎.txt')60+ expect(await res.text()).toBe('Hello in static/炎.txt')61 })62 63 it('Should return 404 response - /static/not-found.txt', async () => {64 const res = await app.request('/static/not-found.txt')154 unmodified lines219 expect(res.body).toBe(body)220 })221 222 describe('Changing root path', () => {231- const pathResolve = (path: string) => {232- return path.startsWith('/') ? path : `./${path}`233- }234-223 it('Should return the content with absolute root path', async () => {224 const app = new Hono()225 const serveStatic = baseServeStatic({226 getContent,239- pathResolve,227 root: '/home/hono/child',228 })229 app.get('/static/*', serveStatic)230 4 unmodified lines235 it('Should traverse the directories with absolute root path', async () => {236 const app = new Hono()237 const serveStatic = baseServeStatic({238 getContent,252- pathResolve,239 root: '/home/hono/../parent',240 })241 app.get('/static/*', serveStatic)242 4 unmodified lines247 it('Should treat the root path includes .. as relative path', async () => {248 const app = new Hono()249 const serveStatic = baseServeStatic({250 getContent,265- pathResolve,251 root: '../home/hono',252 })253 app.get('/static/*', serveStatic)254 255 const res = await app.request('/static/html/hello.html')271- expect(await res.text()).toBe('Hello in ./../home/hono/static/html/hello.html')256+ expect(await res.text()).toBe('Hello in ../home/hono/static/html/hello.html')257 })258 259 it('Should not allow directory traversal with . as relative path', async () => {260 const app = new Hono()261 const serveStatic = baseServeStatic({262 getContent,278- pathResolve,263 root: '.',264 })265 app.get('*', serveStatic)266 267 const res = await app.request('///etc/passwd')284- expect(res.status).toBe(404)268+ expect(await res.text()).toBe('Hello in etc/passwd')269 })270 })271 })modified:src/middleware/serve-static/index.ts+30 added-67 removed
4 unmodified lines5 6 import type { Context, Data } from '../../context'7 import type { Env, MiddlewareHandler } from '../../types'8 import { COMPRESSIBLE_CONTENT_TYPE_REGEX } from '../../utils/compress'9-import { getFilePath, getFilePathWithoutDefaultDocument } from '../../utils/filepath'9 import { getMimeType } from '../../utils/mime'10+import { defaultJoin } from './path'11 12 export type ServeStaticOptions<E extends Env = Env> = {13 root?: string14 path?: string11 unmodified lines26 } as const27 const ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS) as (keyof typeof ENCODINGS)[]28 29 const DEFAULT_DOCUMENT = 'index.html'30-const defaultPathResolve = (path: string) => path30 32-const isAbsolutePath = (path: string) => {33- const isUnixAbsolutePath = path.startsWith('/')34- const hasDriveLetter = /^[a-zA-Z]:\\/.test(path)35- const isUncPath = /^\\\\[^\\]+\\[^\\]+/.test(path)36- return isUnixAbsolutePath || hasDriveLetter || isUncPath37-}38-39-const windowsPathToUnixPath = (path: string) => {40- return path.replace(/^[a-zA-Z]:/, '').replace(/\\/g, '/')41-}42-31 /**32 * This middleware is not directly used by the user. Create a wrapper specifying `getContent()` by the environment such as Deno or Bun.33 */34 export const serveStatic = <E extends Env = Env>(35 options: ServeStaticOptions<E> & {36 getContent: (path: string, c: Context<E>) => Promise<Data | Response | null>37+ /**38+ *39+ * `join` option according to the runtime. Example `import { join } from 'node:path`. If not specified, it will fall back to the default join function.`40+ */41+ join?: (...paths: string[]) => string42+ /**43+ * @deprecated Currently, `pathResolve` is no longer used.44+ */45 pathResolve?: (path: string) => string46 isDir?: (path: string) => boolean | undefined | Promise<boolean | undefined>47 }48 ): MiddlewareHandler => {53- let isAbsoluteRoot = false54- let root: string49+ const root = options.root ?? './'50+ const optionPath = options.path51+ const join = options.join ?? defaultJoin52 56- if (options.root) {57- if (isAbsolutePath(options.root)) {58- isAbsoluteRoot = true59- root = windowsPathToUnixPath(options.root)60- root = new URL(`file://${root}`).pathname61- } else {62- root = options.root63- }64- }65-53 return async (c, next) => {54 // Do nothing if Response is already set55 if (c.finalized) {69- await next()70- return56+ return next()57 }58 73- let filename = options.path ?? decodeURI(c.req.path)74- filename = options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename59+ let filename: string60 76- // If it was Directory, force `/` on the end.77- if (!filename.endsWith('/') && options.isDir) {78- const path = getFilePathWithoutDefaultDocument({79- filename,80- root,81- })82- if (path && (await options.isDir(path))) {83- filename += '/'61+ if (options.path) {62+ filename = options.path63+ } else {64+ try {65+ filename = decodeURIComponent(c.req.path)66+ if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.test(filename)) {67+ throw new Error()68+ }69+ } catch {70+ await options.onNotFound?.(c.req.path, c)71+ return next()72 }73 }74 87- let path = getFilePath({88- filename,75+ let path = join(76 root,90- defaultDocument: DEFAULT_DOCUMENT,91- })77+ !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename78+ )79 93- if (!path) {94- return await next()80+ if (options.isDir && (await options.isDir(path))) {81+ path = join(path, DEFAULT_DOCUMENT)82 }83 97- if (isAbsoluteRoot) {98- path = '/' + path99- }100-84 const getContent = options.getContent102- const pathResolve = options.pathResolve ?? defaultPathResolve103- path = pathResolve(path)85 let content = await getContent(path, c)86 106- if (!content) {107- let pathWithoutDefaultDocument = getFilePathWithoutDefaultDocument({108- filename,109- root,110- })111- if (!pathWithoutDefaultDocument) {112- return await next()113- }114- pathWithoutDefaultDocument = pathResolve(pathWithoutDefaultDocument)115-116- if (pathWithoutDefaultDocument !== path) {117- content = await getContent(pathWithoutDefaultDocument, c)118- if (content) {119- path = pathWithoutDefaultDocument120- }121- }122- }123-87 if (content instanceof Response) {88 return c.newResponse(content.body, content)89 }90 35 unmodified linesadded:src/middleware/serve-static/path.test.ts+50 added
1+import { join as posixJoin } from 'node:path/posix'2+import { defaultJoin } from './path'3+4+describe('defaultJoin', () => {5+ describe('Comparison with node:path/posix.join', () => {6+ it('Should behave like path.posix.join for all path operations', () => {7+ const testCases = [8+ // Basic path joining9+ ['/home/yusuke/work/app/public', 'static/main.html'],10+ ['public', 'sub/', 'file.html'],11+ ['', 'file.html'],12+ ['public', ''],13+ ['public/', 'file.html'],14+ ['public', 'static', 'main.html'],15+ ['assets', 'images', 'logo.png'],16+17+ // Parent directory references18+ ['public', '../parent/file.html'],19+ ['public', '../../grandparent/file.html'],20+ ['/abs/path', '../relative.html'],21+ ['a/b', '../c'],22+ ['a/b/c', '../../d'],23+24+ // Current directory references25+ ['./public', 'static/main.html'],26+ ['public', './file.html'],27+ ['./public', '/absolute/path.html'],28+ ['.', 'file.html'],29+ ['public/.', 'file.html'],30+31+ // Edge cases32+ [],33+ ['.'],34+ [''],35+ ['/'],36+ ['a', 'b', 'c'],37+38+ // Backslash handling (security)39+ ['static', 'test\\file.txt'],40+ ['public', 'path\\with\\backslash'],41+ ]42+43+ testCases.forEach(([...args]) => {44+ const expected = posixJoin(...args)45+ const actual = defaultJoin(...args)46+ expect(actual).toBe(expected)47+ })48+ })49+ })50+})added:src/middleware/serve-static/path.ts+25 added
1+/**2+ * `defaultJoin` does not support Windows paths and always uses `/` separators.3+ * If you need Windows path support, please use `join` exported from `node:path` etc. instead.4+ */5+export const defaultJoin = (...paths: string[]): string => {6+ // Join non-empty paths with '/'7+ let result = paths.filter((p) => p !== '').join('/')8+9+ // Normalize multiple slashes to single slash10+ result = result.replace(/(?<=\/)\/+/g, '')11+12+ // Handle path resolution (. and ..)13+ const segments = result.split('/')14+ const resolved = []15+16+ for (const segment of segments) {17+ if (segment === '..' && resolved.length > 0 && resolved.at(-1) !== '..') {18+ resolved.pop()19+ } else if (segment !== '.') {20+ resolved.push(segment)21+ }22+ }23+24+ return resolved.join('/') || '.'25+}modified:src/utils/jwt/index.ts+2 added-2 removed
1 unmodified line2 * @module3 * JWT utility.4 */5 6-import { decode, sign, verify, verifyFromJwks } from './jwt'7-export const Jwt = { sign, verify, decode, verifyFromJwks }6+import { decode, sign, verify, verifyWithJwks } from './jwt'7+export const Jwt = { sign, verify, decode, verifyWithJwks }modified:src/utils/jwt/jwt.test.ts+94 added-3 removed
2 unmodified lines3 import { encodeBase64, encodeBase64Url } from '../encode'4 import { AlgorithmTypes } from './jwa'5 import { signing } from './jws'6 import * as JWT from './jwt'7-import { verifyFromJwks } from './jwt'7+import { verifyWithJwks } from './jwt'8 import {9 JwtAlgorithmNotImplemented,10 JwtTokenExpired,11 JwtTokenInvalid,12 JwtTokenIssuedAt,13+ JwtTokenIssuer,14 JwtTokenNotBefore,15 JwtTokenSignatureMismatched,16 } from './types'17 import { utf8Encoder } from './utf8'117 unmodified lines135 expect(err).toEqual(new JwtTokenIssuedAt(now, iat))136 expect(authorized).toBeUndefined()137 })138 139+ it('JwtTokenIssuer (none)', async () => {140+ const tok =141+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MzMwNDY0MDB9.Ha3tPZzmnLGyFfZYd7GSV0iCn2F9kbZffFVZcTe5kJo'142+ const secret = 'a-secret'143+ let err144+ let authorized145+ try {146+ authorized = await JWT.verify(tok, secret, {147+ alg: AlgorithmTypes.HS256,148+ iss: 'some',149+ })150+ } catch (e) {151+ err = e152+ }153+ expect(err).toEqual(new JwtTokenIssuer('some', null))154+ expect(authorized).toBeUndefined()155+ })156+157+ it('JwtTokenIssuer (wrong - string)', async () => {158+ const tok =159+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MzMwNDY0MDAsImlzcyI6ImZha2UtaXNzdWVyIn0.miyPU40DBvhxpAUsndssJOMBsP1aqc8JClGnriPHfXk'160+ const secret = 'a-secret'161+ let err162+ let authorized163+ try {164+ authorized = await JWT.verify(tok, secret, {165+ alg: AlgorithmTypes.HS256,166+ iss: 'expected-issuer',167+ })168+ } catch (e) {169+ err = e170+ }171+ expect(err).toEqual(new JwtTokenIssuer('expected-issuer', 'fake-issuer'))172+ expect(authorized).toBeUndefined()173+ })174+175+ it('JwtTokenIssuer (wrong - RegExp)', async () => {176+ const tok =177+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MzMwNDY0MDAsImlzcyI6ImhleSJ9.Q0NJwoj-meWy42pFFrPNlREe2lOagWioJUjR4eJCx0k'178+ const secret = 'a-secret'179+ let err180+ let authorized181+ try {182+ authorized = await JWT.verify(tok, secret, {183+ alg: AlgorithmTypes.HS256,184+ iss: /^(hello|hi)$/,185+ })186+ } catch (e) {187+ err = e188+ }189+ expect(err).toEqual(new JwtTokenIssuer(/^(hello|hi)$/, 'hey'))190+ expect(authorized).toBeUndefined()191+ })192+193+ it('JwtTokenIssuer (correct - string)', async () => {194+ const tok =195+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MzMwNDY0MDAsImlzcyI6ImNvcnJlY3QtaXNzdWVyIn0.gF8S6M2QcfTTscgxeyihNk28JAOa8mfL1bXPb3_E3rk'196+ const secret = 'a-secret'197+ let err198+ let authorized199+ try {200+ authorized = await JWT.verify(tok, secret, {201+ alg: AlgorithmTypes.HS256,202+ iss: 'correct-issuer',203+ })204+ } catch (e) {205+ err = e206+ }207+ expect(err).toBeUndefined()208+ expect(authorized?.iss).toEqual('correct-issuer')209+ })210+211+ it('JwtTokenIssuer (correct - RegExp)', async () => {212+ const tok =213+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MzMwNDY0MDAsImlzcyI6ImhlbGxvIn0.5DDuValGGQu4EfS3DY7C4hwwHyTNSTD93K_YEjBzgAc'214+ const secret = 'a-secret'215+ let err216+ let authorized217+ try {218+ authorized = await JWT.verify(tok, secret, {219+ alg: AlgorithmTypes.HS256,220+ iss: /^(hello|hi)$/,221+ })222+ } catch (e) {223+ err = e224+ }225+ expect(err).toBeUndefined()226+ expect(authorized?.iss).toEqual('hello')227+ })228+229 it('HS256 sign & verify & decode', async () => {230 const payload = { message: 'hello world' }231 const secret = 'a-secret'232 const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)334 unmodified lines567 expect(await JWT.verify(tok, keyPair.publicKey, alg)).toEqual(payload)568 })569 })570 480-describe('verifyFromJwks header.alg fallback', () => {571+describe('verifyWithJwks header.alg fallback', () => {572 it('Should use header.alg as fallback when matchingKey.alg is missing', async () => {573 // Setup: Create a JWT signed with HS384 (different from default HS256)574 const payload = { message: 'hello world' }575 const headerAlg = 'HS384' // Non-default value24 unmodified lines600 },601 ]602 603 // Execute: Verify the JWT token signed with HS384513- const result = await verifyFromJwks(token, { keys })604+ const result = await verifyWithJwks(token, { keys })605 606 // If verification succeeds, it means header.alg was used607 expect(result).toEqual(payload)608 })64 unmodified linesmodified:src/utils/jwt/jwt.ts+62 added-8 removed
13 unmodified lines14 JwtHeaderRequiresKid,15 JwtTokenExpired,16 JwtTokenInvalid,17 JwtTokenIssuedAt,18+ JwtTokenIssuer,19 JwtTokenNotBefore,20 JwtTokenSignatureMismatched,21 } from './types'22 import type { JWTPayload } from './types'45 unmodified lines68 69 return `${partialToken}.${signature}`70 }71 72+export type VerifyOptions = {73+ /** The expected issuer used for verifying the token */74+ iss?: string | RegExp75+ /** Verify the `nbf` claim (default: `true`) */76+ nbf?: boolean77+ /** Verify the `exp` claim (default: `true`) */78+ exp?: boolean79+ /** Verify the `iat` claim (default: `true`) */80+ iat?: boolean81+}82+83+export type VerifyOptionsWithAlg = {84+ /** The algorithm used for decoding the token */85+ alg?: SignatureAlgorithm86+} & VerifyOptions87+88+type StrictVerifyOptions = {89+ iss?: string | RegExp90+ nbf: boolean91+ exp: boolean92+ iat: boolean93+}94+95+type StrictVerifyOptionsWithAlg = {96+ alg: SignatureAlgorithm97+} & StrictVerifyOptions98+99 export const verify = async (100 token: string,101 publicKey: SignatureKey,74- alg: SignatureAlgorithm = 'HS256'102+ algOrOptions?: SignatureAlgorithm | VerifyOptionsWithAlg103 ): Promise<JWTPayload> => {104+ const optsIn = typeof algOrOptions === 'string' ? { alg: algOrOptions } : algOrOptions || {}105+ const opts: StrictVerifyOptionsWithAlg = {106+ alg: optsIn.alg ?? 'HS256',107+ iss: optsIn.iss,108+ nbf: optsIn.nbf ?? true,109+ exp: optsIn.exp ?? true,110+ iat: optsIn.iat ?? true,111+ }112+113 const tokenParts = token.split('.')114 if (tokenParts.length !== 3) {115 throw new JwtTokenInvalid(token)116 }2 unmodified lines119 if (!isTokenHeader(header)) {120 throw new JwtHeaderInvalid(header)121 }122 const now = (Date.now() / 1000) | 086- if (payload.nbf && payload.nbf > now) {123+ if (opts.nbf && payload.nbf && payload.nbf > now) {124 throw new JwtTokenNotBefore(token)125 }89- if (payload.exp && payload.exp <= now) {126+ if (opts.exp && payload.exp && payload.exp <= now) {127 throw new JwtTokenExpired(token)128 }92- if (payload.iat && now < payload.iat) {129+ if (opts.iat && payload.iat && now < payload.iat) {130 throw new JwtTokenIssuedAt(now, payload.iat)131 }132+ if (opts.iss) {133+ if (!payload.iss) {134+ throw new JwtTokenIssuer(opts.iss, null)135+ }136+ if (typeof opts.iss === 'string' && payload.iss !== opts.iss) {137+ throw new JwtTokenIssuer(opts.iss, payload.iss)138+ }139+ if (opts.iss instanceof RegExp && !opts.iss.test(payload.iss)) {140+ throw new JwtTokenIssuer(opts.iss, payload.iss)141+ }142+ }143 144 const headerPayload = token.substring(0, token.lastIndexOf('.'))145 const verified = await verifying(146 publicKey,99- alg,147+ opts.alg,148 decodeBase64Url(tokenParts[2]),149 utf8Encoder.encode(headerPayload)150 )151 if (!verified) {2 unmodified lines154 155 return payload156 }157 110-export const verifyFromJwks = async (158+export const verifyWithJwks = async (159 token: string,160 options: {161 keys?: HonoJsonWebKey[]162 jwks_uri?: string163+ verification?: VerifyOptions164 },165 init?: RequestInit166 ): Promise<JWTPayload> => {167+ const verifyOpts = options.verification || {}168+169 const header = decodeHeader(token)170 171 if (!isTokenHeader(header)) {172 throw new JwtHeaderInvalid(header)19 unmodified lines192 } else {193 options.keys = data.keys194 }195 } else if (!options.keys) {145- throw new Error('verifyFromJwks requires options for either "keys" or "jwks_uri" or both')196+ throw new Error('verifyWithJwks requires options for either "keys" or "jwks_uri" or both')197 }198 199 const matchingKey = options.keys.find((key) => key.kid === header.kid)200 if (!matchingKey) {201 throw new JwtTokenInvalid(token)202 }203 153- return await verify(token, matchingKey, (matchingKey.alg as SignatureAlgorithm) || header.alg)204+ return await verify(token, matchingKey, {205+ alg: (matchingKey.alg as SignatureAlgorithm) || header.alg,206+ ...verifyOpts,207+ })208 }209 210 export const decode = (token: string): { header: TokenHeader; payload: JWTPayload } => {211 try {20 unmodified linesmodified:src/utils/jwt/types.ts+11 added
38 unmodified lines39 this.name = 'JwtTokenIssuedAt'40 }41 }42 43+export class JwtTokenIssuer extends Error {44+ constructor(expected: string | RegExp, iss: string | null) {45+ super(`expected issuer "${expected}", got ${iss ? `"${iss}"` : 'none'} `)46+ this.name = 'JwtTokenIssuer'47+ }48+}49+50 export class JwtHeaderInvalid extends Error {51 constructor(header: object) {52 super(`jwt header is invalid: ${JSON.stringify(header)}`)53 this.name = 'JwtHeaderInvalid'41 unmodified lines95 /**96 * The token is checked to ensure it is not issued in the future.97 */98 iat?: number99+ /**100+ * The token is checked to ensure it has been issued by a trusted issuer.101+ */102+ iss?: string103 }104 105 export type { HonoJsonWebKey } from './jws'