Aktueller Stand

This commit is contained in:
2026-01-22 19:05:45 +01:00
parent 85dee61a4d
commit e280e4eadb
1967 changed files with 397327 additions and 74093 deletions

View File

@@ -1,903 +0,0 @@
/*!
* send
* Copyright(c) 2012 TJ Holowaychuk
* Copyright(c) 2014-2022 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
const fs = require('node:fs')
const path = require('node:path')
const Stream = require('node:stream')
const util = require('node:util')
const debug = require('node:util').debuglog('send')
const decode = require('fast-decode-uri-component')
const escapeHtml = require('escape-html')
const mime = require('mime')
const ms = require('@lukeed/ms')
const { clearHeaders } = require('./clearHeaders')
const { collapseLeadingSlashes } = require('./collapseLeadingSlashes')
const { containsDotFile } = require('./containsDotFile')
const { contentRange } = require('./contentRange')
const { createHtmlDocument } = require('./createHtmlDocument')
const { createHttpError } = require('./createHttpError')
const { isUtf8MimeType } = require('./isUtf8MimeType')
const { normalizeList } = require('./normalizeList')
const { parseBytesRange } = require('./parseBytesRange')
const { parseTokenList } = require('./parseTokenList')
const { setHeaders } = require('./setHeaders')
/**
* Path function references.
* @private
*/
const extname = path.extname
const join = path.join
const normalize = path.normalize
const resolve = path.resolve
const sep = path.sep
/**
* Regular expression for identifying a bytes Range header.
* @private
*/
const BYTES_RANGE_REGEXP = /^ *bytes=/
/**
* Maximum value allowed for the max age.
* @private
*/
const MAX_MAXAGE = 60 * 60 * 24 * 365 * 1000 // 1 year
/**
* Regular expression to match a path with a directory up component.
* @private
*/
const UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/
const ERROR_RESPONSES = {
400: createHtmlDocument('Error', 'Bad Request'),
403: createHtmlDocument('Error', 'Forbidden'),
404: createHtmlDocument('Error', 'Not Found'),
412: createHtmlDocument('Error', 'Precondition Failed'),
416: createHtmlDocument('Error', 'Range Not Satisfiable'),
500: createHtmlDocument('Error', 'Internal Server Error')
}
const validDotFilesOptions = [
'allow',
'ignore',
'deny'
]
/**
* Initialize a `SendStream` with the given `path`.
*
* @param {Request} req
* @param {String} path
* @param {object} [options]
* @private
*/
function SendStream (req, path, options) {
if (!new.target) {
return new SendStream(req, path, options)
}
Stream.call(this)
const opts = options || {}
this.options = opts
this.path = path
this.req = req
this._acceptRanges = opts.acceptRanges !== undefined
? Boolean(opts.acceptRanges)
: true
this._cacheControl = opts.cacheControl !== undefined
? Boolean(opts.cacheControl)
: true
this._etag = opts.etag !== undefined
? Boolean(opts.etag)
: true
this._dotfiles = opts.dotfiles !== undefined
? validDotFilesOptions.indexOf(opts.dotfiles)
: 1 // 'ignore'
if (this._dotfiles === -1) {
throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"')
}
this._extensions = opts.extensions !== undefined
? normalizeList(opts.extensions, 'extensions option')
: []
this._immutable = opts.immutable !== undefined
? Boolean(opts.immutable)
: false
this._index = opts.index !== undefined
? normalizeList(opts.index, 'index option')
: ['index.html']
this._lastModified = opts.lastModified !== undefined
? Boolean(opts.lastModified)
: true
this._maxage = opts.maxAge || opts.maxage
this._maxage = typeof this._maxage === 'string'
? ms.parse(this._maxage)
: Number(this._maxage)
// eslint-disable-next-line no-self-compare
this._maxage = this._maxage === this._maxage // fast path of isNaN(number)
? Math.min(Math.max(0, this._maxage), MAX_MAXAGE)
: 0
this._root = opts.root
? resolve(opts.root)
: null
}
/**
* Inherits from `Stream`.
*/
util.inherits(SendStream, Stream)
/**
* Set root `path`.
*
* @param {String} path
* @return {SendStream}
* @api private
*/
SendStream.prototype.root = function root (path) {
this._root = resolve(String(path))
debug('root %s', this._root)
return this
}
/**
* Emit error with `status`.
*
* @memberof SendStream
* @param {number} status
* @param {Error} [err]
* @this {Stream}
* @private
*/
SendStream.prototype.error = function error (status, err) {
// emit if listeners instead of responding
if (this.listenerCount('error') > 0) {
return this.emit('error', createHttpError(status, err))
}
const res = this.res
// clear existing headers
clearHeaders(res)
// add error headers
if (err && err.headers) {
setHeaders(res, err.headers)
}
const doc = ERROR_RESPONSES[status]
// send basic response
res.statusCode = status
res.setHeader('Content-Type', 'text/html; charset=UTF-8')
res.setHeader('Content-Length', doc[1])
res.setHeader('Content-Security-Policy', "default-src 'none'")
res.setHeader('X-Content-Type-Options', 'nosniff')
res.end(doc[0])
}
/**
* Check if the pathname ends with "/".
*
* @return {boolean}
* @private
*/
SendStream.prototype.hasTrailingSlash = function hasTrailingSlash () {
return this.path[this.path.length - 1] === '/'
}
/**
* Check if this is a conditional GET request.
*
* @return {Boolean}
* @api private
*/
SendStream.prototype.isConditionalGET = function isConditionalGET () {
return this.req.headers['if-match'] ||
this.req.headers['if-unmodified-since'] ||
this.req.headers['if-none-match'] ||
this.req.headers['if-modified-since']
}
SendStream.prototype.isNotModifiedFailure = function isNotModifiedFailure () {
const req = this.req
const res = this.res
// Always return stale when Cache-Control: no-cache
// to support end-to-end reload requests
// https://tools.ietf.org/html/rfc2616#section-14.9.4
if (
'cache-control' in req.headers &&
req.headers['cache-control'].indexOf('no-cache') !== -1
) {
return false
}
// if-none-match
if ('if-none-match' in req.headers) {
const ifNoneMatch = req.headers['if-none-match']
if (ifNoneMatch === '*') {
return true
}
const etag = res.getHeader('etag')
if (typeof etag !== 'string') {
return false
}
const etagL = etag.length
const isMatching = parseTokenList(ifNoneMatch, function (match) {
const mL = match.length
if (
(etagL === mL && match === etag) ||
(etagL > mL && 'W/' + match === etag)
) {
return true
}
})
if (isMatching) {
return true
}
/**
* A recipient MUST ignore If-Modified-Since if the request contains an
* If-None-Match header field; the condition in If-None-Match is considered
* to be a more accurate replacement for the condition in If-Modified-Since,
* and the two are only combined for the sake of interoperating with older
* intermediaries that might not implement If-None-Match.
*
* @see RFC 9110 section 13.1.3
*/
return false
}
// if-modified-since
if ('if-modified-since' in req.headers) {
const ifModifiedSince = req.headers['if-modified-since']
const lastModified = res.getHeader('last-modified')
if (!lastModified || (Date.parse(lastModified) <= Date.parse(ifModifiedSince))) {
return true
}
}
return false
}
/**
* Check if the request preconditions failed.
*
* @return {boolean}
* @private
*/
SendStream.prototype.isPreconditionFailure = function isPreconditionFailure () {
const req = this.req
const res = this.res
// if-match
const ifMatch = req.headers['if-match']
if (ifMatch) {
const etag = res.getHeader('ETag')
if (ifMatch !== '*') {
const isMatching = parseTokenList(ifMatch, function (match) {
if (
match === etag ||
'W/' + match === etag
) {
return true
}
}) || false
if (isMatching !== true) {
return true
}
}
}
// if-unmodified-since
if ('if-unmodified-since' in req.headers) {
const ifUnmodifiedSince = req.headers['if-unmodified-since']
const unmodifiedSince = Date.parse(ifUnmodifiedSince)
// eslint-disable-next-line no-self-compare
if (unmodifiedSince === unmodifiedSince) { // fast path of isNaN(number)
const lastModified = Date.parse(res.getHeader('Last-Modified'))
if (
// eslint-disable-next-line no-self-compare
lastModified !== lastModified ||// fast path of isNaN(number)
lastModified > unmodifiedSince
) {
return true
}
}
}
return false
}
/**
* Strip various content header fields for a change in entity.
*
* @private
*/
SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields () {
const res = this.res
res.removeHeader('Content-Encoding')
res.removeHeader('Content-Language')
res.removeHeader('Content-Length')
res.removeHeader('Content-Range')
res.removeHeader('Content-Type')
}
/**
* Respond with 304 not modified.
*
* @api private
*/
SendStream.prototype.notModified = function notModified () {
const res = this.res
debug('not modified')
this.removeContentHeaderFields()
res.statusCode = 304
res.end()
}
/**
* Raise error that headers already sent.
*
* @api private
*/
SendStream.prototype.headersAlreadySent = function headersAlreadySent () {
const err = new Error('Can\'t set headers after they are sent.')
debug('headers already sent')
this.error(500, err)
}
/**
* Check if the request is cacheable, aka
* responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}).
*
* @return {Boolean}
* @api private
*/
SendStream.prototype.isCachable = function isCachable () {
const statusCode = this.res.statusCode
return (statusCode >= 200 && statusCode < 300) ||
statusCode === 304
}
/**
* Handle stat() error.
*
* @param {Error} error
* @private
*/
SendStream.prototype.onStatError = function onStatError (error) {
// POSIX throws ENAMETOOLONG and ENOTDIR, Windows only ENOENT
/* istanbul ignore next */
switch (error.code) {
case 'ENAMETOOLONG':
case 'ENOTDIR':
case 'ENOENT':
this.error(404, error)
break
default:
this.error(500, error)
break
}
}
/**
* Check if the range is fresh.
*
* @return {Boolean}
* @api private
*/
SendStream.prototype.isRangeFresh = function isRangeFresh () {
if (!('if-range' in this.req.headers)) {
return true
}
const ifRange = this.req.headers['if-range']
// if-range as etag
if (ifRange.indexOf('"') !== -1) {
const etag = this.res.getHeader('ETag')
return (etag && ifRange.indexOf(etag) !== -1) || false
}
const ifRangeTimestamp = Date.parse(ifRange)
// eslint-disable-next-line no-self-compare
if (ifRangeTimestamp !== ifRangeTimestamp) { // fast path of isNaN(number)
return false
}
// if-range as modified date
const lastModified = Date.parse(this.res.getHeader('Last-Modified'))
return (
// eslint-disable-next-line no-self-compare
lastModified !== lastModified || // fast path of isNaN(number)
lastModified <= ifRangeTimestamp
)
}
/**
* Redirect to path.
*
* @param {string} path
* @private
*/
SendStream.prototype.redirect = function redirect (path) {
const res = this.res
if (this.listenerCount('directory') > 0) {
this.emit('directory', res, path)
return
}
if (this.hasTrailingSlash()) {
this.error(403)
return
}
const loc = encodeURI(collapseLeadingSlashes(this.path + '/'))
const doc = createHtmlDocument('Redirecting', 'Redirecting to <a href="' + escapeHtml(loc) + '">' +
escapeHtml(loc) + '</a>')
// redirect
res.statusCode = 301
res.setHeader('Content-Type', 'text/html; charset=UTF-8')
res.setHeader('Content-Length', doc[1])
res.setHeader('Content-Security-Policy', "default-src 'none'")
res.setHeader('X-Content-Type-Options', 'nosniff')
res.setHeader('Location', loc)
res.end(doc[0])
}
/**
* Pipe to `res.
*
* @param {Stream} res
* @return {Stream} res
* @api public
*/
SendStream.prototype.pipe = function pipe (res) {
// root path
const root = this._root
// references
this.res = res
// decode the path
let path = decode(this.path)
if (path === null) {
this.error(400)
return res
}
// null byte(s)
if (~path.indexOf('\0')) {
this.error(400)
return res
}
let parts
if (root !== null) {
// normalize
if (path) {
path = normalize('.' + sep + path)
}
// malicious path
if (UP_PATH_REGEXP.test(path)) {
debug('malicious path "%s"', path)
this.error(403)
return res
}
// explode path parts
parts = path.split(sep)
// join / normalize from optional root dir
path = normalize(join(root, path))
} else {
// ".." is malicious without "root"
if (UP_PATH_REGEXP.test(path)) {
debug('malicious path "%s"', path)
this.error(403)
return res
}
// explode path parts
parts = normalize(path).split(sep)
// resolve the path
path = resolve(path)
}
// dotfile handling
if (
(
debug.enabled || // if debugging is enabled, then check for all cases to log allow case
this._dotfiles !== 0 // if debugging is not enabled, then only check if 'deny' or 'ignore' is set
) &&
containsDotFile(parts)
) {
switch (this._dotfiles) {
/* istanbul ignore next: unreachable, because NODE_DEBUG can not be set after process is running */
case 0: // 'allow'
debug('allow dotfile "%s"', path)
break
case 2: // 'deny'
debug('deny dotfile "%s"', path)
this.error(403)
return res
case 1: // 'ignore'
default:
debug('ignore dotfile "%s"', path)
this.error(404)
return res
}
}
// index file support
if (this._index.length && this.hasTrailingSlash()) {
this.sendIndex(path)
return res
}
this.sendFile(path)
return res
}
/**
* Transfer `path`.
*
* @param {String} path
* @api public
*/
SendStream.prototype.send = function send (path, stat) {
let len = stat.size
const options = this.options
const opts = {}
const res = this.res
const req = this.req
let offset = options.start || 0
if (res.headersSent) {
// impossible to send now
this.headersAlreadySent()
return
}
debug('pipe "%s"', path)
// set header fields
this.setHeader(path, stat)
// set content-type
this.type(path)
// conditional GET support
if (this.isConditionalGET()) {
if (this.isPreconditionFailure()) {
this.error(412)
return
}
if (this.isCachable() && this.isNotModifiedFailure()) {
this.notModified()
return
}
}
// adjust len to start/end options
len = Math.max(0, len - offset)
if (options.end !== undefined) {
const bytes = options.end - offset + 1
if (len > bytes) len = bytes
}
// Range support
if (this._acceptRanges) {
const rangeHeader = req.headers.range
if (
rangeHeader !== undefined &&
BYTES_RANGE_REGEXP.test(rangeHeader)
) {
// If-Range support
if (this.isRangeFresh()) {
// parse
const ranges = parseBytesRange(len, rangeHeader)
// unsatisfiable
if (ranges.length === 0) {
debug('range unsatisfiable')
// Content-Range
res.setHeader('Content-Range', contentRange('bytes', len))
// 416 Requested Range Not Satisfiable
return this.error(416, {
headers: { 'Content-Range': res.getHeader('Content-Range') }
})
// valid (syntactically invalid/multiple ranges are treated as a regular response)
} else if (ranges.length === 1) {
debug('range %j', ranges)
// Content-Range
res.statusCode = 206
res.setHeader('Content-Range', contentRange('bytes', len, ranges[0]))
// adjust for requested range
offset += ranges[0].start
len = ranges[0].end - ranges[0].start + 1
}
} else {
debug('range stale')
}
}
}
// clone options
for (const prop in options) {
opts[prop] = options[prop]
}
// set read options
opts.start = offset
opts.end = Math.max(offset, offset + len - 1)
// content-length
res.setHeader('Content-Length', len)
// HEAD support
if (req.method === 'HEAD') {
res.end()
return
}
this.stream(path, opts)
}
/**
* Transfer file for `path`.
*
* @param {String} path
* @api private
*/
SendStream.prototype.sendFile = function sendFile (path) {
let i = 0
const self = this
debug('stat "%s"', path)
fs.stat(path, function onstat (err, stat) {
if (err && err.code === 'ENOENT' && !extname(path) && path[path.length - 1] !== sep) {
// not found, check extensions
return next(err)
}
if (err) return self.onStatError(err)
if (stat.isDirectory()) return self.redirect(path)
self.emit('file', path, stat)
self.send(path, stat)
})
function next (err) {
if (self._extensions.length <= i) {
return err
? self.onStatError(err)
: self.error(404)
}
const p = path + '.' + self._extensions[i++]
debug('stat "%s"', p)
fs.stat(p, function (err, stat) {
if (err) return next(err)
if (stat.isDirectory()) return next()
self.emit('file', p, stat)
self.send(p, stat)
})
}
}
/**
* Transfer index for `path`.
*
* @param {String} path
* @api private
*/
SendStream.prototype.sendIndex = function sendIndex (path) {
let i = -1
const self = this
function next (err) {
if (++i >= self._index.length) {
if (err) return self.onStatError(err)
return self.error(404)
}
const p = join(path, self._index[i])
debug('stat "%s"', p)
fs.stat(p, function (err, stat) {
if (err) return next(err)
if (stat.isDirectory()) return next()
self.emit('file', p, stat)
self.send(p, stat)
})
}
next()
}
/**
* Stream `path` to the response.
*
* @param {String} path
* @param {Object} options
* @api private
*/
SendStream.prototype.stream = function stream (path, options) {
const self = this
const res = this.res
// pipe
const stream = fs.createReadStream(path, options)
this.emit('stream', stream)
stream.pipe(res)
let destroyed = false
// destroy piped stream
function destroy () {
if (destroyed) {
return
}
destroyed = true
stream.destroy()
}
res.once('finish', destroy)
// error handling
stream.on('error', function onerror (err) {
// clean up stream early
destroy()
// error
self.onStatError(err)
})
// end
stream.on('end', function onend () {
self.emit('end')
})
}
/**
* Set content-type based on `path`
* if it hasn't been explicitly set.
*
* @param {String} path
* @api private
*/
SendStream.prototype.type = function type (path) {
const res = this.res
if (res.getHeader('Content-Type')) return
const type = mime.getType(path) || mime.default_type
if (!type) {
debug('no content-type')
return
}
debug('content-type %s', type)
if (isUtf8MimeType(type)) {
res.setHeader('Content-Type', type + '; charset=UTF-8')
} else {
res.setHeader('Content-Type', type)
}
}
/**
* Set response header fields, most
* fields may be pre-defined.
*
* @param {String} path
* @param {Object} stat
* @api private
*/
SendStream.prototype.setHeader = function setHeader (path, stat) {
const res = this.res
this.emit('headers', res, path, stat)
if (this._acceptRanges && !res.getHeader('Accept-Ranges')) {
debug('accept ranges')
res.setHeader('Accept-Ranges', 'bytes')
}
if (this._cacheControl && !res.getHeader('Cache-Control')) {
let cacheControl = 'public, max-age=' + Math.floor(this._maxage / 1000)
if (this._immutable) {
cacheControl += ', immutable'
}
debug('cache-control %s', cacheControl)
res.setHeader('Cache-Control', cacheControl)
}
if (this._lastModified && !res.getHeader('Last-Modified')) {
const modified = stat.mtime.toUTCString()
debug('modified %s', modified)
res.setHeader('Last-Modified', modified)
}
if (this._etag && !res.getHeader('ETag')) {
const etag = 'W/"' + stat.size.toString(16) + '-' + stat.mtime.getTime().toString(16) + '"'
debug('etag %s', etag)
res.setHeader('ETag', etag)
}
}
/**
* Module exports.
* @public
*/
module.exports = SendStream

View File

@@ -1,21 +0,0 @@
/*!
* send
* Copyright(c) 2012 TJ Holowaychuk
* Copyright(c) 2014-2022 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Clear all headers from a response.
*
* @param {object} res
* @private
*/
function clearHeaders (res) {
const headers = res.getHeaderNames()
for (let i = 0; i < headers.length; i++) {
res.removeHeader(headers[i])
}
}
exports.clearHeaders = clearHeaders

View File

@@ -19,6 +19,7 @@ function collapseLeadingSlashes (str) {
return str.slice(i - 1)
}
}
/* c8 ignore next */
}
module.exports.collapseLeadingSlashes = collapseLeadingSlashes

729
backend/node_modules/@fastify/send/lib/send.js generated vendored Normal file
View File

@@ -0,0 +1,729 @@
'use strict'
const fs = require('node:fs')
const path = require('node:path')
const stream = require('node:stream')
const debug = require('node:util').debuglog('send')
const decode = require('fast-decode-uri-component')
const escapeHtml = require('escape-html')
const mime = require('mime')
const ms = require('@lukeed/ms')
const { collapseLeadingSlashes } = require('./collapseLeadingSlashes')
const { containsDotFile } = require('../lib/containsDotFile')
const { contentRange } = require('../lib/contentRange')
const { createHtmlDocument } = require('../lib/createHtmlDocument')
const { isUtf8MimeType } = require('../lib/isUtf8MimeType')
const { normalizeList } = require('../lib/normalizeList')
const { parseBytesRange } = require('../lib/parseBytesRange')
const { parseTokenList } = require('./parseTokenList')
const { createHttpError } = require('./createHttpError')
/**
* Path function references.
* @private
*/
const extname = path.extname
const join = path.join
const normalize = path.normalize
const resolve = path.resolve
const sep = path.sep
/**
* Stream function references.
* @private
*/
const Readable = stream.Readable
/**
* Regular expression for identifying a bytes Range header.
* @private
*/
const BYTES_RANGE_REGEXP = /^ *bytes=/
/**
* Maximum value allowed for the max age.
* @private
*/
const MAX_MAXAGE = 60 * 60 * 24 * 365 * 1000 // 1 year
/**
* Regular expression to match a path with a directory up component.
* @private
*/
const UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/
const ERROR_RESPONSES = {
400: createHtmlDocument('Error', 'Bad Request'),
403: createHtmlDocument('Error', 'Forbidden'),
404: createHtmlDocument('Error', 'Not Found'),
412: createHtmlDocument('Error', 'Precondition Failed'),
416: createHtmlDocument('Error', 'Range Not Satisfiable'),
500: createHtmlDocument('Error', 'Internal Server Error')
}
const validDotFilesOptions = [
'allow',
'ignore',
'deny'
]
function normalizeMaxAge (_maxage) {
let maxage
if (typeof _maxage === 'string') {
maxage = ms.parse(_maxage)
} else {
maxage = Number(_maxage)
}
// eslint-disable-next-line no-self-compare
if (maxage !== maxage) {
// fast path of isNaN(number)
return 0
}
return Math.min(Math.max(0, maxage), MAX_MAXAGE)
}
function normalizeOptions (options) {
options = options ?? {}
const acceptRanges = options.acceptRanges !== undefined
? Boolean(options.acceptRanges)
: true
const cacheControl = options.cacheControl !== undefined
? Boolean(options.cacheControl)
: true
const contentType = options.contentType !== undefined
? Boolean(options.contentType)
: true
const etag = options.etag !== undefined
? Boolean(options.etag)
: true
const dotfiles = options.dotfiles !== undefined
? validDotFilesOptions.indexOf(options.dotfiles)
: 1 // 'ignore'
if (dotfiles === -1) {
throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"')
}
const extensions = options.extensions !== undefined
? normalizeList(options.extensions, 'extensions option')
: []
const immutable = options.immutable !== undefined
? Boolean(options.immutable)
: false
const index = options.index !== undefined
? normalizeList(options.index, 'index option')
: ['index.html']
const lastModified = options.lastModified !== undefined
? Boolean(options.lastModified)
: true
const maxage = normalizeMaxAge(options.maxAge ?? options.maxage)
const maxContentRangeChunkSize = options.maxContentRangeChunkSize !== undefined
? Number(options.maxContentRangeChunkSize)
: null
const root = options.root
? resolve(options.root)
: null
const highWaterMark = Number.isSafeInteger(options.highWaterMark) && options.highWaterMark > 0
? options.highWaterMark
: null
return {
acceptRanges,
cacheControl,
contentType,
etag,
dotfiles,
extensions,
immutable,
index,
lastModified,
maxage,
maxContentRangeChunkSize,
root,
highWaterMark,
start: options.start,
end: options.end
}
}
function normalizePath (_path, root) {
// decode the path
let path = decode(_path)
if (path == null) {
return { statusCode: 400 }
}
// null byte(s)
if (~path.indexOf('\0')) {
return { statusCode: 400 }
}
let parts
if (root !== null) {
// normalize
if (path) {
path = normalize('.' + sep + path)
}
// malicious path
if (UP_PATH_REGEXP.test(path)) {
debug('malicious path "%s"', path)
return { statusCode: 403 }
}
// explode path parts
parts = path.split(sep)
// join / normalize from optional root dir
path = normalize(join(root, path))
} else {
// ".." is malicious without "root"
if (UP_PATH_REGEXP.test(path)) {
debug('malicious path "%s"', path)
return { statusCode: 403 }
}
// explode path parts
parts = normalize(path).split(sep)
// resolve the path
path = resolve(path)
}
return { path, parts }
}
/**
* Check if the pathname ends with "/".
*
* @return {boolean}
* @private
*/
function hasTrailingSlash (path) {
return path[path.length - 1] === '/'
}
/**
* Check if this is a conditional GET request.
*
* @return {Boolean}
* @api private
*/
function isConditionalGET (request) {
return request.headers['if-match'] ||
request.headers['if-unmodified-since'] ||
request.headers['if-none-match'] ||
request.headers['if-modified-since']
}
function isNotModifiedFailure (request, headers) {
// Always return stale when Cache-Control: no-cache
// to support end-to-end reload requests
// https://tools.ietf.org/html/rfc2616#section-14.9.4
if (
'cache-control' in request.headers &&
request.headers['cache-control'].indexOf('no-cache') !== -1
) {
return false
}
// if-none-match
if ('if-none-match' in request.headers) {
const ifNoneMatch = request.headers['if-none-match']
if (ifNoneMatch === '*') {
return true
}
const etag = headers.ETag
if (typeof etag !== 'string') {
return false
}
const etagL = etag.length
const isMatching = parseTokenList(ifNoneMatch, function (match) {
const mL = match.length
if (
(etagL === mL && match === etag) ||
(etagL > mL && 'W/' + match === etag)
) {
return true
}
})
if (isMatching) {
return true
}
/**
* A recipient MUST ignore If-Modified-Since if the request contains an
* If-None-Match header field; the condition in If-None-Match is considered
* to be a more accurate replacement for the condition in If-Modified-Since,
* and the two are only combined for the sake of interoperating with older
* intermediaries that might not implement If-None-Match.
*
* @see RFC 9110 section 13.1.3
*/
return false
}
// if-modified-since
if ('if-modified-since' in request.headers) {
const ifModifiedSince = request.headers['if-modified-since']
const lastModified = headers['Last-Modified']
if (!lastModified || (Date.parse(lastModified) <= Date.parse(ifModifiedSince))) {
return true
}
}
return false
}
/**
* Check if the request preconditions failed.
*
* @return {boolean}
* @private
*/
function isPreconditionFailure (request, headers) {
// if-match
const ifMatch = request.headers['if-match']
if (ifMatch) {
const etag = headers.ETag
if (ifMatch !== '*') {
const isMatching = parseTokenList(ifMatch, function (match) {
if (
match === etag ||
'W/' + match === etag
) {
return true
}
}) || false
if (isMatching !== true) {
return true
}
}
}
// if-unmodified-since
if ('if-unmodified-since' in request.headers) {
const ifUnmodifiedSince = request.headers['if-unmodified-since']
const unmodifiedSince = Date.parse(ifUnmodifiedSince)
// eslint-disable-next-line no-self-compare
if (unmodifiedSince === unmodifiedSince) { // fast path of isNaN(number)
const lastModified = Date.parse(headers['Last-Modified'])
if (
// eslint-disable-next-line no-self-compare
lastModified !== lastModified ||// fast path of isNaN(number)
lastModified > unmodifiedSince
) {
return true
}
}
}
return false
}
/**
* Check if the range is fresh.
*
* @return {Boolean}
* @api private
*/
function isRangeFresh (request, headers) {
if (!('if-range' in request.headers)) {
return true
}
const ifRange = request.headers['if-range']
// if-range as etag
if (ifRange.indexOf('"') !== -1) {
const etag = headers.ETag
return (etag && ifRange.indexOf(etag) !== -1) || false
}
const ifRangeTimestamp = Date.parse(ifRange)
// eslint-disable-next-line no-self-compare
if (ifRangeTimestamp !== ifRangeTimestamp) { // fast path of isNaN(number)
return false
}
// if-range as modified date
const lastModified = Date.parse(headers['Last-Modified'])
return (
// eslint-disable-next-line no-self-compare
lastModified !== lastModified || // fast path of isNaN(number)
lastModified <= ifRangeTimestamp
)
}
// we provide stat function that will always resolve
// without throwing
function tryStat (path) {
return new Promise((resolve) => {
fs.stat(path, function onstat (error, stat) {
resolve({ error, stat })
})
})
}
function sendError (statusCode, err) {
const headers = {}
// add error headers
if (err && err.headers) {
for (const headerName in err.headers) {
headers[headerName] = err.headers[headerName]
}
}
const doc = ERROR_RESPONSES[statusCode]
// basic response
headers['Content-Type'] = 'text/html; charset=utf-8'
headers['Content-Length'] = doc[1]
headers['Content-Security-Policy'] = "default-src 'none'"
headers['X-Content-Type-Options'] = 'nosniff'
return {
statusCode,
headers,
stream: Readable.from(doc[0]),
// metadata
type: 'error',
metadata: { error: createHttpError(statusCode, err) }
}
}
function sendStatError (err) {
// POSIX throws ENAMETOOLONG and ENOTDIR, Windows only ENOENT
/* c8 ignore start */
switch (err.code) {
case 'ENAMETOOLONG':
case 'ENOTDIR':
case 'ENOENT':
return sendError(404, err)
default:
return sendError(500, err)
}
/* c8 ignore stop */
}
/**
* Respond with 304 not modified.
*
* @api private
*/
function sendNotModified (headers, path, stat) {
debug('not modified')
delete headers['Content-Encoding']
delete headers['Content-Language']
delete headers['Content-Length']
delete headers['Content-Range']
delete headers['Content-Type']
return {
statusCode: 304,
headers,
stream: Readable.from(''),
// metadata
type: 'file',
metadata: { path, stat }
}
}
function sendFileDirectly (request, path, stat, options) {
let len = stat.size
let offset = options.start ?? 0
let statusCode = 200
const headers = {}
debug('send "%s"', path)
// set header fields
if (options.acceptRanges) {
debug('accept ranges')
headers['Accept-Ranges'] = 'bytes'
}
if (options.cacheControl) {
let cacheControl = 'public, max-age=' + Math.floor(options.maxage / 1000)
if (options.immutable) {
cacheControl += ', immutable'
}
debug('cache-control %s', cacheControl)
headers['Cache-Control'] = cacheControl
}
if (options.lastModified) {
const modified = stat.mtime.toUTCString()
debug('modified %s', modified)
headers['Last-Modified'] = modified
}
if (options.etag) {
const etag = 'W/"' + stat.size.toString(16) + '-' + stat.mtime.getTime().toString(16) + '"'
debug('etag %s', etag)
headers.ETag = etag
}
// set content-type
if (options.contentType) {
let type = mime.getType(path) || mime.default_type
debug('content-type %s', type)
if (type && isUtf8MimeType(type)) {
type += '; charset=utf-8'
}
if (type) {
headers['Content-Type'] = type
}
}
// conditional GET support
if (isConditionalGET(request)) {
if (isPreconditionFailure(request, headers)) {
return sendError(412)
}
if (isNotModifiedFailure(request, headers)) {
return sendNotModified(headers, path, stat)
}
}
// adjust len to start/end options
len = Math.max(0, len - offset)
if (options.end !== undefined) {
const bytes = options.end - offset + 1
if (len > bytes) len = bytes
}
// Range support
if (options.acceptRanges) {
const rangeHeader = request.headers.range
if (
rangeHeader !== undefined &&
BYTES_RANGE_REGEXP.test(rangeHeader)
) {
// If-Range support
if (isRangeFresh(request, headers)) {
// parse
const ranges = parseBytesRange(len, rangeHeader)
// unsatisfiable
if (ranges.length === 0) {
debug('range unsatisfiable')
// Content-Range
headers['Content-Range'] = contentRange('bytes', len)
// 416 Requested Range Not Satisfiable
return sendError(416, {
headers: { 'Content-Range': headers['Content-Range'] }
})
// valid (syntactically invalid/multiple ranges are treated as a regular response)
} else if (ranges.length === 1) {
debug('range %j', ranges)
// Content-Range
statusCode = 206
if (options.maxContentRangeChunkSize) {
ranges[0].end = Math.min(ranges[0].end, ranges[0].start + options.maxContentRangeChunkSize - 1)
}
headers['Content-Range'] = contentRange('bytes', len, ranges[0])
// adjust for requested range
offset += ranges[0].start
len = ranges[0].end - ranges[0].start + 1
}
} else {
debug('range stale')
}
}
}
// content-length
headers['Content-Length'] = len
// HEAD support
if (request.method === 'HEAD') {
return {
statusCode,
headers,
stream: Readable.from(''),
// metadata
type: 'file',
metadata: { path, stat }
}
}
const stream = fs.createReadStream(path, {
highWaterMark: options.highWaterMark,
start: offset,
end: Math.max(offset, offset + len - 1)
})
return {
statusCode,
headers,
stream,
// metadata
type: 'file',
metadata: { path, stat }
}
}
function sendRedirect (path, options) {
if (hasTrailingSlash(options.path)) {
return sendError(403)
}
const loc = encodeURI(collapseLeadingSlashes(options.path + '/'))
const doc = createHtmlDocument('Redirecting', 'Redirecting to ' + escapeHtml(loc))
const headers = {}
headers['Content-Type'] = 'text/html; charset=utf-8'
headers['Content-Length'] = doc[1]
headers['Content-Security-Policy'] = "default-src 'none'"
headers['X-Content-Type-Options'] = 'nosniff'
headers.Location = loc
return {
statusCode: 301,
headers,
stream: Readable.from(doc[0]),
// metadata
type: 'directory',
metadata: { requestPath: options.path, path }
}
}
async function sendIndex (request, path, options) {
let err
for (let i = 0; i < options.index.length; i++) {
const index = options.index[i]
const p = join(path, index)
const { error, stat } = await tryStat(p)
if (error) {
err = error
continue
}
if (stat.isDirectory()) continue
return sendFileDirectly(request, p, stat, options)
}
if (err) {
return sendStatError(err)
}
return sendError(404)
}
async function sendFile (request, path, options) {
const { error, stat } = await tryStat(path)
if (error && error.code === 'ENOENT' && !extname(path) && path[path.length - 1] !== sep) {
let err = error
// not found, check extensions
for (let i = 0; i < options.extensions.length; i++) {
const extension = options.extensions[i]
const p = path + '.' + extension
const { error, stat } = await tryStat(p)
if (error) {
err = error
continue
}
if (stat.isDirectory()) {
err = null
continue
}
return sendFileDirectly(request, p, stat, options)
}
if (err) {
return sendStatError(err)
}
return sendError(404)
}
if (error) return sendStatError(error)
if (stat.isDirectory()) return sendRedirect(path, options)
return sendFileDirectly(request, path, stat, options)
}
async function send (request, _path, options) {
const opts = normalizeOptions(options)
opts.path = _path
const parsed = normalizePath(_path, opts.root)
const { path, parts } = parsed
if (parsed.statusCode !== undefined) {
return sendError(parsed.statusCode)
}
// dotfile handling
if (
(
debug.enabled || // if debugging is enabled, then check for all cases to log allow case
opts.dotfiles !== 0 // if debugging is not enabled, then only check if 'deny' or 'ignore' is set
) &&
containsDotFile(parts)
) {
switch (opts.dotfiles) {
/* c8 ignore start */ /* unreachable, because NODE_DEBUG can not be set after process is running */
case 0: // 'allow'
debug('allow dotfile "%s"', path)
break
/* c8 ignore stop */
case 2: // 'deny'
debug('deny dotfile "%s"', path)
return sendError(403)
case 1: // 'ignore'
default:
debug('ignore dotfile "%s"', path)
return sendError(404)
}
}
// index file support
if (opts.index.length && hasTrailingSlash(_path)) {
return sendIndex(request, path, opts)
}
return sendFile(request, path, opts)
}
module.exports.send = send

View File

@@ -1,20 +0,0 @@
'use strict'
/**
* Set an object of headers on a response.
*
* @param {object} res
* @param {object} headers
* @private
*/
function setHeaders (res, headers) {
const keys = Object.keys(headers)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
res.setHeader(key, headers[key])
}
}
module.exports.setHeaders = setHeaders