diff --git a/README.md b/README.md index 5aab07f..6ca47f0 100644 --- a/README.md +++ b/README.md @@ -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` diff --git a/index.js b/index.js index 45a91ac..07a986f 100644 --- a/index.js +++ b/index.js @@ -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') { @@ -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 }) @@ -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 @@ -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] @@ -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) } diff --git a/test/static.test.js b/test/static.test.js index 3fd700a..994dcac 100644 --- a/test/static.test.js +++ b/test/static.test.js @@ -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' + }) +}) diff --git a/types/index.d.ts b/types/index.d.ts index f64a6db..857a38e 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -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?: (