fetch-metadata
Advanced tools
Comparing version 0.2.1 to 0.3.0
@@ -5,2 +5,18 @@ 'use strict'; | ||
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } | ||
var UrlPattern = _interopDefault(require('url-pattern')); | ||
var CONFIG_DEFAULTS = { | ||
allowedFetchSites: ['same-origin', 'same-site', 'none'], | ||
disallowedNavigationRequests: ['object', 'embed'], | ||
allowedPaths: [], | ||
errorStatusCode: 403, | ||
// @ts-expect-error | ||
onError: function onError(req, res, next, options) { | ||
res.statusCode = options.errorStatusCode; | ||
res.end(); | ||
} | ||
}; | ||
var extractHeader = function extractHeader(req, header) { | ||
@@ -19,14 +35,30 @@ var reqHeader = req.headers[header]; | ||
var CONFIG_DEFAULTS = { | ||
allowedFetchSites: ['same-origin', 'same-site', 'none'], | ||
disallowedNavigationRequests: ['object', 'embed'], | ||
allowedPaths: [], | ||
errorStatusCode: 403, | ||
// @ts-expect-error | ||
onError: function onError(req, res, next, options) { | ||
res.statusCode = options.errorStatusCode; | ||
res.end(); | ||
} | ||
var isString = function isString(str) { | ||
return typeof str === 'string'; | ||
}; | ||
var matchAllowedURL = function matchAllowedURL(list, req) { | ||
if (!Array.isArray(list)) return false; | ||
var _req$url = req.url, | ||
url = _req$url === void 0 ? '' : _req$url, | ||
_req$method = req.method, | ||
method = _req$method === void 0 ? '' : _req$method; | ||
method = method.toUpperCase(); | ||
var match = list.find(function (item) { | ||
var allowedPath = isString(item) ? { | ||
path: item | ||
} : item; | ||
if (isString(allowedPath.method)) { | ||
if (allowedPath.method.toUpperCase() !== method) { | ||
return false; | ||
} | ||
} | ||
var pattern = new UrlPattern(allowedPath.path); | ||
return !!pattern.match(url); | ||
}); | ||
return !!match; | ||
}; | ||
function middlewareWrapper(config) { | ||
@@ -39,3 +71,3 @@ if (config === void 0) { | ||
return function middleware(req, res, next) { | ||
var _req$method; | ||
var _req$method2; | ||
@@ -58,9 +90,8 @@ var _getSecFetchHeaders = getSecFetchHeaders(req), | ||
if (secFetchMode === 'navigate' && ((_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase()) === 'GET' && Array.isArray(options.disallowedNavigationRequests) && !options.disallowedNavigationRequests.includes(secFetchDest)) { | ||
if (secFetchMode === 'navigate' && ((_req$method2 = req.method) === null || _req$method2 === void 0 ? void 0 : _req$method2.toUpperCase()) === 'GET' && Array.isArray(options.disallowedNavigationRequests) && !options.disallowedNavigationRequests.includes(secFetchDest)) { | ||
return next(); | ||
} // Explicitly allowed paths | ||
// TODO: Improve this to match dynamic paths with optional patterns | ||
if (Array.isArray(options.allowedPaths) && options.allowedPaths.includes(req.url || '')) { | ||
if (matchAllowedURL(options.allowedPaths, req)) { | ||
return next(); | ||
@@ -67,0 +98,0 @@ } |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=function(e,t){var s=e.headers[t];return Array.isArray(s)?s.join(","):s||""},t={allowedFetchSites:["same-origin","same-site","none"],disallowedNavigationRequests:["object","embed"],allowedPaths:[],errorStatusCode:403,onError:function(e,t,s,r){t.statusCode=r.errorStatusCode,t.end()}};function s(s){void 0===s&&(s={});var r=Object.assign(t,s);return function(t,s,o){var a,i=function(t){return{secFetchSite:e(t,"sec-fetch-site"),secFetchMode:e(t,"sec-fetch-mode"),secFetchDest:e(t,"sec-fetch-dest")}}(t),d=i.secFetchSite,c=i.secFetchMode,n=i.secFetchDest;return d?Array.isArray(r.allowedFetchSites)&&r.allowedFetchSites.includes(d)||"navigate"===c&&"GET"===(null===(a=t.method)||void 0===a?void 0:a.toUpperCase())&&Array.isArray(r.disallowedNavigationRequests)&&!r.disallowedNavigationRequests.includes(n)||Array.isArray(r.allowedPaths)&&r.allowedPaths.includes(t.url||"")?o():void r.onError(t,s,o,r):o()}}module.exports=s,exports.default=s; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=(e=require("url-pattern"))&&"object"==typeof e&&"default"in e?e.default:e,r={allowedFetchSites:["same-origin","same-site","none"],disallowedNavigationRequests:["object","embed"],allowedPaths:[],errorStatusCode:403,onError:function(e,t,r,o){t.statusCode=o.errorStatusCode,t.end()}},o=function(e,t){var r=e.headers[t];return Array.isArray(r)?r.join(","):r||""},s=function(e){return"string"==typeof e};function a(e){void 0===e&&(e={});var a=Object.assign(r,e);return function(e,r,i){var n,d=function(e){return{secFetchSite:o(e,"sec-fetch-site"),secFetchMode:o(e,"sec-fetch-mode"),secFetchDest:o(e,"sec-fetch-dest")}}(e),c=d.secFetchSite,u=d.secFetchMode,l=d.secFetchDest;return c?Array.isArray(a.allowedFetchSites)&&a.allowedFetchSites.includes(c)||"navigate"===u&&"GET"===(null===(n=e.method)||void 0===n?void 0:n.toUpperCase())&&Array.isArray(a.disallowedNavigationRequests)&&!a.disallowedNavigationRequests.includes(l)||function(e,r){if(!Array.isArray(e))return!1;var o=r.url,a=void 0===o?"":o,i=r.method,n=void 0===i?"":i;return n=n.toUpperCase(),!!e.find((function(e){var r=s(e)?{path:e}:e;return!(s(r.method)&&r.method.toUpperCase()!==n||!new t(r.path).match(a))}))}(a.allowedPaths,e)?i():void a.onError(e,r,i,a):i()}}module.exports=a,exports.default=a; | ||
//# sourceMappingURL=fetch-metadata.cjs.production.min.js.map |
@@ -0,1 +1,15 @@ | ||
import UrlPattern from 'url-pattern'; | ||
var CONFIG_DEFAULTS = { | ||
allowedFetchSites: ['same-origin', 'same-site', 'none'], | ||
disallowedNavigationRequests: ['object', 'embed'], | ||
allowedPaths: [], | ||
errorStatusCode: 403, | ||
// @ts-expect-error | ||
onError: function onError(req, res, next, options) { | ||
res.statusCode = options.errorStatusCode; | ||
res.end(); | ||
} | ||
}; | ||
var extractHeader = function extractHeader(req, header) { | ||
@@ -14,14 +28,30 @@ var reqHeader = req.headers[header]; | ||
var CONFIG_DEFAULTS = { | ||
allowedFetchSites: ['same-origin', 'same-site', 'none'], | ||
disallowedNavigationRequests: ['object', 'embed'], | ||
allowedPaths: [], | ||
errorStatusCode: 403, | ||
// @ts-expect-error | ||
onError: function onError(req, res, next, options) { | ||
res.statusCode = options.errorStatusCode; | ||
res.end(); | ||
} | ||
var isString = function isString(str) { | ||
return typeof str === 'string'; | ||
}; | ||
var matchAllowedURL = function matchAllowedURL(list, req) { | ||
if (!Array.isArray(list)) return false; | ||
var _req$url = req.url, | ||
url = _req$url === void 0 ? '' : _req$url, | ||
_req$method = req.method, | ||
method = _req$method === void 0 ? '' : _req$method; | ||
method = method.toUpperCase(); | ||
var match = list.find(function (item) { | ||
var allowedPath = isString(item) ? { | ||
path: item | ||
} : item; | ||
if (isString(allowedPath.method)) { | ||
if (allowedPath.method.toUpperCase() !== method) { | ||
return false; | ||
} | ||
} | ||
var pattern = new UrlPattern(allowedPath.path); | ||
return !!pattern.match(url); | ||
}); | ||
return !!match; | ||
}; | ||
function middlewareWrapper(config) { | ||
@@ -34,3 +64,3 @@ if (config === void 0) { | ||
return function middleware(req, res, next) { | ||
var _req$method; | ||
var _req$method2; | ||
@@ -53,9 +83,8 @@ var _getSecFetchHeaders = getSecFetchHeaders(req), | ||
if (secFetchMode === 'navigate' && ((_req$method = req.method) === null || _req$method === void 0 ? void 0 : _req$method.toUpperCase()) === 'GET' && Array.isArray(options.disallowedNavigationRequests) && !options.disallowedNavigationRequests.includes(secFetchDest)) { | ||
if (secFetchMode === 'navigate' && ((_req$method2 = req.method) === null || _req$method2 === void 0 ? void 0 : _req$method2.toUpperCase()) === 'GET' && Array.isArray(options.disallowedNavigationRequests) && !options.disallowedNavigationRequests.includes(secFetchDest)) { | ||
return next(); | ||
} // Explicitly allowed paths | ||
// TODO: Improve this to match dynamic paths with optional patterns | ||
if (Array.isArray(options.allowedPaths) && options.allowedPaths.includes(req.url || '')) { | ||
if (matchAllowedURL(options.allowedPaths, req)) { | ||
return next(); | ||
@@ -62,0 +91,0 @@ } |
/// <reference types="node" /> | ||
import { IncomingMessage, ServerResponse } from 'http'; | ||
declare type Next = (error?: Error) => void; | ||
declare type AllowedPath = { | ||
path: string; | ||
method?: string; | ||
}; | ||
declare type NextFn = (error?: Error) => void; | ||
declare type Config = { | ||
allowedFetchSites: string[]; | ||
disallowedNavigationRequests: string[]; | ||
allowedPaths: string[]; | ||
allowedPaths: (string | AllowedPath)[]; | ||
errorStatusCode: number; | ||
onError: (request: IncomingMessage, response: ServerResponse, next: Next, options: Config) => void; | ||
onError: (request: IncomingMessage, response: ServerResponse, next: NextFn, options: Config) => void; | ||
}; | ||
declare function middlewareWrapper(config?: Partial<Config>): (req: IncomingMessage, res: ServerResponse, next: Next) => void; | ||
declare function middlewareWrapper(config?: Partial<Config>): (req: IncomingMessage, res: ServerResponse, next: NextFn) => void; | ||
export default middlewareWrapper; |
{ | ||
"version": "0.2.1", | ||
"version": "0.3.0", | ||
"license": "MIT", | ||
@@ -52,3 +52,6 @@ "main": "dist/index.js", | ||
"typescript": "3.9.7" | ||
}, | ||
"dependencies": { | ||
"url-pattern": "^1.0.3" | ||
} | ||
} |
# Fetch Metadata Request Headers Middleware | ||
This project is Node.js middleware for enforcing browser [Fetch metadata request headers](https://web.dev/fetch-metadata/). This helps in preventing CSRF, XSSI and information leaking attacks. | ||
This project is Node.js middleware for enforcing browser [Fetch metadata request headers](https://web.dev/fetch-metadata/). This helps in preventing CSRF, XSSI and information leaking attacks. Use it to add to your [defense in depth](https://en.wikipedia.org/wiki/Defense_in_depth_%28computing%29) security strategy. | ||
@@ -15,3 +15,3 @@ ## Installation | ||
Once installed, import and use the middleware like you would for any other Express.js/Connect middleware: | ||
Once installed, import and use the middleware as you would for any other Express.js/Connect middleware: | ||
@@ -24,3 +24,3 @@ ```typescript | ||
The middleware takes an optional config object with defaults shown below: | ||
The middleware takes an **optional** config object with defaults shown below: | ||
@@ -32,4 +32,4 @@ ```typescript | ||
disallowedNavigationRequests: ['object', 'embed'], | ||
errorStatusCode: 403, | ||
allowedPaths: [], | ||
errorStatusCode: 403, | ||
onError: (request, response, next, options) => { | ||
@@ -44,4 +44,58 @@ // Responds with `errorStatusCode` by default | ||
### Config Options | ||
#### allowedFetchSites | ||
Array of all the `Sec-Fetch-Site` request header values to allow. | ||
The current possible values are: | ||
- `same-origin`: request came from your own application | ||
- `same-site`: request came from a subdomain of your own application | ||
- `none`: request came from user's interaction with the user agent (e.g. clicking on a bookmark) | ||
- `cross-site`: request came from a completely different site | ||
#### disallowedNavigationRequests | ||
Array of all the `Sec-Fetch-Dest` request header values to block for navigation requests. With the defaults set to block `object` and `embed` top-level GET requests, your site can still be linked to from other sites and embedded in an iframe (if you don't block that with something else). | ||
If you want to disable this setting, set an empty array. | ||
#### errorStatusCode | ||
The HTTP status code to return when a request is blocked. | ||
#### allowedPaths | ||
Optionally, specify an array of route paths that you want to allow regardless of any of the other checks. You can also specify this for a specific HTTP method to allow a `POST` to `/api/public/route` for instance. | ||
##### Examples | ||
```typescript | ||
const allowedPaths = [ | ||
'/api/public/route', // plain string | ||
'/products(/:productId)', // string with dynamic parts | ||
{ | ||
path: '/api/public/route', | ||
method: 'GET', | ||
}, // object with plain string path and method | ||
{ | ||
path: '/products(/:productId)', | ||
method: 'POST', | ||
}, // object with string with dynamic parts and method | ||
] | ||
``` | ||
As you can see, you can mix and match strings with objects and the paths can have dynamic parts, similar to how Express.js routes work. | ||
> Allowed paths can have any pattern that [url-pattern](https://www.npmjs.com/package/url-pattern) can match. | ||
#### onError | ||
A callback function that will be called with a request was blocked. The function is called with the `request`, `response`, `next` and `options` objects, where the first three objects are the standard middleware arguments and the `options` object is a copy of the current configuration of this middleware. | ||
By default, this callback will simply respond with the `errorStatusCode` that you've set (or 403). This callback is a great place is you want to log any blocked requests or even by-pass the block completely by calling `next()` here while you're testing this middleware. | ||
## License | ||
MIT License |
import { IncomingMessage, ServerResponse } from 'http' | ||
import UrlPattern from 'url-pattern' | ||
const extractHeader = (req: IncomingMessage, header: string): string => { | ||
const reqHeader = req.headers[header] | ||
return Array.isArray(reqHeader) ? reqHeader.join(',') : reqHeader || '' | ||
type AllowedPath = { | ||
path: string | ||
method?: string | ||
} | ||
const getSecFetchHeaders = (req: IncomingMessage) => { | ||
return { | ||
secFetchSite: extractHeader(req, 'sec-fetch-site'), | ||
secFetchMode: extractHeader(req, 'sec-fetch-mode'), | ||
secFetchDest: extractHeader(req, 'sec-fetch-dest'), | ||
} | ||
} | ||
type NextFn = (error?: Error) => void | ||
type Next = (error?: Error) => void | ||
type Config = { | ||
allowedFetchSites: string[] | ||
disallowedNavigationRequests: string[] | ||
allowedPaths: string[] | ||
allowedPaths: (string | AllowedPath)[] | ||
errorStatusCode: number | ||
@@ -26,3 +19,3 @@ onError: ( | ||
response: ServerResponse, | ||
next: Next, | ||
next: NextFn, | ||
options: Config | ||
@@ -44,2 +37,45 @@ ) => void | ||
const extractHeader = (req: IncomingMessage, header: string): string => { | ||
const reqHeader = req.headers[header] | ||
return Array.isArray(reqHeader) ? reqHeader.join(',') : reqHeader || '' | ||
} | ||
const getSecFetchHeaders = (req: IncomingMessage) => { | ||
return { | ||
secFetchSite: extractHeader(req, 'sec-fetch-site'), | ||
secFetchMode: extractHeader(req, 'sec-fetch-mode'), | ||
secFetchDest: extractHeader(req, 'sec-fetch-dest'), | ||
} | ||
} | ||
const isString = (str: any): str is string => { | ||
return typeof str === 'string' | ||
} | ||
const matchAllowedURL = ( | ||
list: (string | AllowedPath)[], | ||
req: IncomingMessage | ||
): boolean => { | ||
if (!Array.isArray(list)) return false | ||
let { url = '', method = '' } = req | ||
method = method.toUpperCase() | ||
const match = list.find(item => { | ||
const allowedPath: AllowedPath = isString(item) ? { path: item } : item | ||
if (isString(allowedPath.method)) { | ||
if (allowedPath.method.toUpperCase() !== method) { | ||
return false | ||
} | ||
} | ||
const pattern = new UrlPattern(allowedPath.path) | ||
return !!pattern.match(url) | ||
}) | ||
return !!match | ||
} | ||
function middlewareWrapper(config: Partial<Config> = {}) { | ||
@@ -51,3 +87,3 @@ const options = Object.assign(CONFIG_DEFAULTS, config) | ||
res: ServerResponse, | ||
next: Next | ||
next: NextFn | ||
) { | ||
@@ -80,7 +116,3 @@ const { secFetchSite, secFetchMode, secFetchDest } = getSecFetchHeaders(req) | ||
// Explicitly allowed paths | ||
// TODO: Improve this to match dynamic paths with optional patterns | ||
if ( | ||
Array.isArray(options.allowedPaths) && | ||
options.allowedPaths.includes(req.url || '') | ||
) { | ||
if (matchAllowedURL(options.allowedPaths, req)) { | ||
return next() | ||
@@ -87,0 +119,0 @@ } |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
35212
284
98
1
3
+ Addedurl-pattern@^1.0.3
+ Addedurl-pattern@1.0.3(transitive)