Skip to content
Myr

feat(serve-static): support absolute root (#3420)

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

* feat(serve-static): support absolute root * add bun runtime test * don't use `Request` * add code for deno * remove unnecessay `console.log` * use `normalizeFilePath` instead of `URL` * use `URL` for `options.root` * don't allow directory traversal and fix the behavior when root including `../`

authored by Yusuke Wada · committed by GitHub · parent 7779fca · Browse files · 12 files+137 added−12 removed
This commit

State

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

Diff stats

12 files+137 added−12 removed

  • tests:+85 added−4 removed
  • other:+52 added−8 removed

12 files+137 added−12 removed

added:runtime-tests/bun/static-absolute-root/plain.txt+1 added
1Bun!
modified:runtime-tests/bun/index.test.tsx+12 added-4 removed
1import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'2import fs from 'fs/promises'3import path from 'path'4import { stream, streamSSE } from '../..//src/helper/streaming'5import { serveStatic, toSSG } from '../../src/adapter/bun'6import { createBunWebSocket } from '../../src/adapter/bun/websocket'7import type { BunWebSocketData } from '../../src/adapter/bun/websocket'
4 unmodified lines
12// eslint-disable-next-line @typescript-eslint/no-unused-vars13import { jsx } from '../../src/jsx'14import { basicAuth } from '../../src/middleware/basic-auth'15import { jwt } from '../../src/middleware/jwt'14import { HonoRequest } from '../../src/request'1617// Test just only minimal patterns.18// Because others are tested well in Cloudflare Workers environment already.19
22 unmodified lines
42})4344describe('Environment Variables', () => {45 it('Should return the environment variable', async () => {45 const c = new Context(new HonoRequest(new Request('http://localhost/')))46 const c = new Context(new Request('http://localhost/'))47 const { NAME } = env<{ NAME: string }>(c)48 expect(NAME).toBe('Bun')49 })50})
56 unmodified lines
107 rewriteRequestPath: (path) => path.replace(/^\/dot-static/, './.static'),108 })109 )110111 app.all('/static-absolute-root/*', serveStatic({ root: path.dirname(__filename) }))112113 beforeEach(() => onNotFound.mockClear())114115 it('Should return static file correctly', async () => {116 const res = await app.request(new Request('http://localhost/favicon.ico'))
42 unmodified lines
159 const res = await app.request('http://localhost/static/hello.world')160 expect(res.status).toBe(200)161 expect(await res.text()).toBe('Hi\n')162 })163164 it('Should return 200 response - /static-absolute-root/plain.txt', async () => {165 const res = await app.request('http://localhost/static-absolute-root/plain.txt')166 expect(res.status).toBe(200)167 expect(await res.text()).toBe('Bun!')168 expect(onNotFound).not.toHaveBeenCalled()169 })170})171172// Bun support WebCrypto since v0.2.2173// So, JWT middleware works well.
145 unmodified lines
319 const receivedMessage = await receivedMessagePromise320 expect(receivedMessage).toBe(message)321 })322})313const fs = require('fs').promises314const path = require('path')323324async function deleteDirectory(dirPath) {325 if (326 await fs
114 unmodified lines
modified:runtime-tests/deno/.vscode/settings.json+1 added-1 removed
added:runtime-tests/deno/static-absolute-root/plain.txt+1 added
1Deno!
modified:runtime-tests/deno/deno.json+2 added-1 removed
modified:runtime-tests/deno/deno.lock+24 added-2 removed
1{2 "version": "3",3 "packages": {4 "specifiers": {5 "jsr:@std/assert@^1.0.3": "jsr:@std/assert@1.0.3",5 "jsr:@std/assert@^1.0.3": "jsr:@std/assert@1.0.5",6 "jsr:@std/assert@^1.0.4": "jsr:@std/assert@1.0.5",7 "jsr:@std/internal@^1.0.2": "jsr:@std/internal@1.0.2",8 "jsr:@std/internal@^1.0.3": "jsr:@std/internal@1.0.3",9 "jsr:@std/path@^1.0.3": "jsr:@std/path@1.0.6",7 "jsr:@std/testing@^1.0.1": "jsr:@std/testing@1.0.1"10 "jsr:@std/testing@^1.0.1": "jsr:@std/testing@1.0.2"11 },12 "jsr": {13 "@std/assert@1.0.3": {14 "integrity": "b0d03ce1ced880df67132eea140623010d415848df66f6aa5df76507ca7c26d8",15 "dependencies": [16 "jsr:@std/internal@^1.0.2"17 ]18 },19 "@std/assert@1.0.5": {20 "integrity": "e37da8e4033490ce613eec4ac1d78dba1faf5b02a3f6c573a28f15365b9b440f",21 "dependencies": [22 "jsr:@std/internal@^1.0.3"23 ]24 },25 "@std/internal@1.0.2": {26 "integrity": "f4cabe2021352e8bfc24e6569700df87bf070914fc38d4b23eddd20108ac4495"27 },28 "@std/internal@1.0.3": {29 "integrity": "208e9b94a3d5649bd880e9ca38b885ab7651ab5b5303a56ed25de4755fb7b11e"30 },31 "@std/path@1.0.6": {32 "integrity": "ab2c55f902b380cf28e0eec501b4906e4c1960d13f00e11cfbcd21de15f18fed"33 },34 "@std/testing@1.0.1": {35 "integrity": "9c25841137ee818933e1722091bb9ed5fdc251c35e84c97979a52196bdb6c5c3",36 "dependencies": [37 "jsr:@std/assert@^1.0.3"38 ]39 },40 "@std/testing@1.0.2": {41 "integrity": "9e8a7f4e26c219addabe7942d09c3450fa0a74e9662341961bc0ef502274dec3",42 "dependencies": [43 "jsr:@std/assert@^1.0.4"44 ]45 }46 }47 },48 "remote": {},49 "workspace": {50 "dependencies": [51 "jsr:@std/assert@^1.0.3",52 "jsr:@std/path@^1.0.3",53 "jsr:@std/testing@^1.0.1"54 ]55 }56}
modified:runtime-tests/deno/middleware.test.tsx+15 added
modified:src/adapter/bun/serve-static.ts+2 added-2 removed
7 unmodified lines
8 options: ServeStaticOptions<E>9): MiddlewareHandler => {10 return async function serveStatic(c, next) {11 const getContent = async (path: string) => {12 path = `./${path}`12 path = path.startsWith('/') ? path : `./${path}`13 // @ts-ignore14 const file = Bun.file(path)15 return (await file.exists()) ? file : null16 }17 const pathResolve = (path: string) => {18 return `./${path}`18 return path.startsWith('/') ? path : `./${path}`19 }20 const isDir = async (path: string) => {21 let isDir22 try {
13 unmodified lines
modified:src/adapter/deno/serve-static.ts+1 added-1 removed
18 unmodified lines
19 console.warn(`${e}`)20 }21 }22 const pathResolve = (path: string) => {23 return `./${path}`23 return path.startsWith('/') ? path : `./${path}`24 }25 const isDir = (path: string) => {26 let isDir27 try {
13 unmodified lines
modified:src/middleware/serve-static/index.test.ts+58 added
224 unmodified lines
225 } as Request)226 expect(res.status).toBe(200)227 expect(res.body).toBe(body)228 })229230 describe('Changing root path', () => {231 const pathResolve = (path: string) => {232 return path.startsWith('/') ? path : `./${path}`233 }234235 it('Should return the content with absolute root path', async () => {236 const app = new Hono()237 const serveStatic = baseServeStatic({238 getContent,239 pathResolve,240 root: '/home/hono/child',241 })242 app.get('/static/*', serveStatic)243244 const res = await app.request('/static/html/hello.html')245 expect(await res.text()).toBe('Hello in /home/hono/child/static/html/hello.html')246 })247248 it('Should traverse the directories with absolute root path', async () => {249 const app = new Hono()250 const serveStatic = baseServeStatic({251 getContent,252 pathResolve,253 root: '/home/hono/../parent',254 })255 app.get('/static/*', serveStatic)256257 const res = await app.request('/static/html/hello.html')258 expect(await res.text()).toBe('Hello in /home/parent/static/html/hello.html')259 })260261 it('Should treat the root path includes .. as relative path', async () => {262 const app = new Hono()263 const serveStatic = baseServeStatic({264 getContent,265 pathResolve,266 root: '../home/hono',267 })268 app.get('/static/*', serveStatic)269270 const res = await app.request('/static/html/hello.html')271 expect(await res.text()).toBe('Hello in ./../home/hono/static/html/hello.html')272 })273274 it('Should not allow directory traversal with . as relative path', async () => {275 const app = new Hono()276 const serveStatic = baseServeStatic({277 getContent,278 pathResolve,279 root: '.',280 })281 app.get('*', serveStatic)282283 const res = await app.request('///etc/passwd')284 expect(res.status).toBe(404)285 })286 })287})
modified:src/middleware/serve-static/index.ts+16 added-1 removed
37 unmodified lines
38 pathResolve?: (path: string) => string39 isDir?: (path: string) => boolean | undefined | Promise<boolean | undefined>40 }41): MiddlewareHandler => {42 let isAbsoluteRoot = false43 let root: string4445 if (options.root) {46 if (options.root.startsWith('/')) {47 isAbsoluteRoot = true48 root = new URL(`file://${options.root}`).pathname49 } else {50 root = options.root51 }52 }5354 return async (c, next) => {55 // Do nothing if Response is already set56 if (c.finalized) {57 await next()
1 unmodified line
59 }6061 let filename = options.path ?? decodeURI(c.req.path)62 filename = options.rewriteRequestPath ? options.rewriteRequestPath(filename) : filename51 const root = options.root6364 // If it was Directory, force `/` on the end.65 if (!filename.endsWith('/') && options.isDir) {66 const path = getFilePathWithoutDefaultDocument({
14 unmodified lines
81 if (!path) {82 return await next()83 }8485 if (isAbsoluteRoot) {86 path = '/' + path87 }8889 const getContent = options.getContent90 const pathResolve = options.pathResolve ?? defaultPathResolve91 path = pathResolve(path)92 let content = await getContent(path, c)
58 unmodified lines
modified:src/utils/filepath.ts+4 added
50 unmodified lines
51 // ./assets/foo.html => assets/foo.html52 let path = root ? root + '/' + filename : filename53 path = path.replace(/^\.?\//, '')5455 if (root[0] !== '/' && path[0] === '/') {56 return57 }5859 return path60}