Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,31 @@ are applied for getting the file list.

This option cannot be `false` if `redirect` is `true` and `ignoreTrailingSlash` is `true`.


#### `globPattern`

Default: `undefined`

An optional glob pattern used to select static files relative
to the configured root directory.

This option supports both `wildcard: true` and `wildcard: false`.

For example, to serve only JavaScript and CSS files:

```js
fastify.register(require('@fastify/static'), {
root: path.join(__dirname, 'public'),
globPattern: '**/*.{js,css}'
})
```

When using `wildcard: true`, newly created files matching the
pattern can be served without restarting the server.

When this option is omitted, the default file-serving
behaviour is preserved.

#### `globIgnore`

Default: `undefined`
Expand Down
27 changes: 24 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,12 @@ async function fastifyStatic (fastify, opts) {
opts.root = normalizeRoot(opts.root)
checkRootPathForErrors(fastify, opts.root, suppressWarning)
}
if (opts.globPattern !== undefined &&
typeof opts.globPattern !== 'string') {
throw new FST_STATIC_INVALID_OPTION_VALUE(
'globPattern', 'must be a string'
)
}

const setHeaders = opts.setHeaders
if (setHeaders !== undefined && typeof setHeaders !== 'function') {
Expand Down Expand Up @@ -191,7 +197,7 @@ async function fastifyStatic (fastify, opts) {
for (let rootPath of roots) {
rootPath = rootPath.split(path.win32.sep).join(path.posix.sep)
!rootPath.endsWith('/') && (rootPath += '/')
const files = await glob('**/**', {
const files = await glob(opts.globPattern ?? '**/**', {
cwd: rootPath, absolute: false, follow: true, nodir: true, dot: opts.serveDotFiles, ignore: opts.globIgnore
})

Expand Down Expand Up @@ -229,6 +235,8 @@ async function fastifyStatic (fastify, opts) {

const allowedPath = opts.allowedPath

const globPattern = opts.globPattern

/**
* @param {import("fastify").FastifyReply} reply
* @param {string} pathname
Expand Down Expand Up @@ -372,7 +380,8 @@ async function fastifyStatic (fastify, opts) {
return reply.callNotFound()
}

if (allowedPath && (callerOnFile === undefined || typeof callerOnFile === 'function')) {
if ((allowedPath || globPattern !== undefined) &&
(callerOnFile === undefined || typeof callerOnFile === 'function')) {
options.onFile = async function authorizeFinalPath (selectedPath, selectedStat) {
let logicalPath = selectedPath
const encodingExtension = encodingExtensionMap[encoding]
Expand All @@ -387,11 +396,23 @@ async function fastifyStatic (fastify, opts) {
)
if (
finalPathname === undefined ||
(finalPathname !== normalizedPathname && !allowedPath(finalPathname, options.root, request))
(allowedPath && finalPathname !== normalizedPathname &&
!allowedPath(finalPathname, options.root, request))
) {
throw finalPathDenied
}

if (globPattern !== undefined) {
const relativePath = getFinalPathname(logicalPath, options.root, false)

if (
relativePath === undefined ||
!path.posix.matchesGlob(relativePath, globPattern)
) {
throw finalPathDenied
}
}

if (callerOnFile) {
await callerOnFile(selectedPath, selectedStat)
}
Expand Down
107 changes: 107 additions & 0 deletions test/static.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6054,3 +6054,110 @@ test('serves files with # or ? in their names', async (t) => {
t.assert.deepStrictEqual(literal.statusCode, 200)
t.assert.deepStrictEqual(literal.body, 'literal')
})

for (const wildcard of [false, true]) {
test(`register with wildcard ${wildcard} and globPattern`, async t => {
t.plan(5)

const fastify = Fastify()

fastify.register(fastifyStatic, {
root: path.join(__dirname, '/static-filtered'),
wildcard,
globPattern: '**/*.html'
})

t.after(() => fastify.close())

const indexResponse = await fastify.inject({
method: 'GET',
url: '/index.html'
})

t.assert.strictEqual(indexResponse.statusCode, 200)

const privateResponse = await fastify.inject({
method: 'GET',
url: '/bar.private'
})

t.assert.strictEqual(privateResponse.statusCode, 404)

const deepResponse = await fastify.inject({
method: 'GET',
url: '/deep/path/to/baz.html'
})

t.assert.strictEqual(deepResponse.statusCode, 200)

const rootResponse = await fastify.inject({
method: 'GET',
url: '/'
})

t.assert.strictEqual(rootResponse.statusCode, 200)

const headResponse = await fastify.inject({
method: 'HEAD',
url: '/bar.private'
})

t.assert.strictEqual(headResponse.statusCode, 404)
})
}

test('globPattern supports newly added files', async t => {
t.plan(2)

const root = fs.mkdtempSync(
path.join(require('node:os').tmpdir(), 'fastify-static-')
)

const fastify = Fastify()

t.after(async () => {
await fastify.close()
fs.rmSync(root, { recursive: true, force: true })
})

fastify.register(fastifyStatic, {
root,
wildcard: true,
globPattern: '**/*.html'
})

await fastify.ready()

fs.writeFileSync(path.join(root, 'new.html'), 'Hello')
fs.writeFileSync(path.join(root, 'new.txt'), 'Hello')

const allowed = await fastify.inject({
method: 'GET',
url: '/new.html'
})

const denied = await fastify.inject({
method: 'GET',
url: '/new.txt'
})

t.assert.strictEqual(allowed.statusCode, 200)
t.assert.strictEqual(denied.statusCode, 404)
})

test('globPattern must be a string', async t => {
t.plan(1)

const fastify = Fastify()

t.after(() => fastify.close())

fastify.register(fastifyStatic, {
root: path.join(__dirname, '/static-filtered'),
globPattern: 123
})

await t.assert.rejects(fastify.ready(), {
code: 'FST_STATIC_INVALID_OPTION_VALUE'
})
})
1 change: 1 addition & 0 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ declare namespace fastifyStatic {
setHeaders?: (reply: FastifyReply, path: string, stat: Stats) => void;
redirect?: boolean;
wildcard?: boolean;
globPattern?: string;
globIgnore?: string[];
list?: boolean | ListOptionsJsonFormat | ListOptionsHtmlFormat;
allowedPath?: (
Expand Down