@dr.pogodin/react-utils 1.43.11 → 1.43.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/development/server/server.js +1 -1
- package/build/development/server/server.js.map +1 -1
- package/build/development/web.bundle.js +1 -1
- package/build/production/server/server.js +1 -1
- package/build/production/server/server.js.map +1 -1
- package/build/types-code/server/server.d.ts +1 -0
- package/package.json +12 -12
- package/src/server/server.ts +2 -1
|
@@ -131,7 +131,7 @@ async function factory(webpackConfig, options) {
|
|
|
131
131
|
server.use(_express.default.urlencoded({
|
|
132
132
|
extended: false
|
|
133
133
|
}));
|
|
134
|
-
server.use((0, _cookieParser.default)());
|
|
134
|
+
server.use((0, _cookieParser.default)(options.cookieSignatureSecret));
|
|
135
135
|
server.use(_requestIp.default.mw());
|
|
136
136
|
server.use((0, _csurf.default)({
|
|
137
137
|
cookie: true
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","names":["_path","require","_url","_lodash","_compression","_interopRequireDefault","_cookieParser","_csurf","_express","_serveFavicon","_helmet","_morgan","_requestIp","_uuid","_renderer","_errors","defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","requestIp","mw","csrf","cookie","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","getErrorForCode","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\n\nimport express, {\n type Express,\n type NextFunction,\n type RequestHandler,\n type Request,\n type Response,\n} from 'express';\n\nimport favicon from 'serve-favicon';\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport type { Compiler, Configuration } from 'webpack';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT =\nExclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => boolean | Promise<boolean>;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser());\n server.use(requestIp.mw());\n\n server.use(csrf({ cookie: true }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n /* eslint-disable @typescript-eslint/no-require-imports */\n const webpack = require('webpack') as (ops: Configuration) => Compiler;\n\n // TODO: Figure out the exact type for options, don't wanna waste time on it\n // right now.\n const webpackDevMiddleware = require('webpack-dev-middleware') as\n (c: Compiler, ops: unknown) => RequestHandler;\n\n const webpackHotMiddleware = require('webpack-hot-middleware') as\n (c: Compiler) => RequestHandler;\n\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":";;;;;;;;AAIA,IAAAA,KAAA,GAAAC,OAAA;AACA,IAAAC,IAAA,GAAAD,OAAA;AAEA,IAAAE,OAAA,GAAAF,OAAA;AAMA,IAAAG,YAAA,GAAAC,sBAAA,CAAAJ,OAAA;AACA,IAAAK,aAAA,GAAAD,sBAAA,CAAAJ,OAAA;AACA,IAAAM,MAAA,GAAAF,sBAAA,CAAAJ,OAAA;AAEA,IAAAO,QAAA,GAAAH,sBAAA,CAAAJ,OAAA;AAQA,IAAAQ,aAAA,GAAAJ,sBAAA,CAAAJ,OAAA;AACA,IAAAS,OAAA,GAAAL,sBAAA,CAAAJ,OAAA;AACA,IAAAU,OAAA,GAAAN,sBAAA,CAAAJ,OAAA;AACA,IAAAW,UAAA,GAAAP,sBAAA,CAAAJ,OAAA;AACA,IAAAY,KAAA,GAAAZ,OAAA;AAIA,IAAAa,SAAA,GAAAT,sBAAA,CAAAJ,OAAA;AAKA,IAAAc,OAAA,GAAAd,OAAA;AAtCA;AACA;AACA;;AA8CA;;AAMA;AACA;AACA;AACA;AACA,MAAMe,kBAAkB,GAAG;EACzBC,UAAU,EAAE,IAAAC,iBAAS,EACnBC,eAAM,CAACC,qBAAqB,CAACC,oBAAoB,CAAC,CAAC;EAEnD;EACA;EACA;EACA;EACCC,KAAK,IAAMA,KAAK,CAAcC,MAAM,CAAEC,IAAY,IAAKA,IAAI,KAAK,QAAQ,CAC3E;AACF,CAAC;AACDR,kB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AAI,KAAK;IAC7BA,IAAI,CAAC,IAAAwD,gBAAQ,EAACC,cAAM,CAACC,SAAS,EAAEC,aAAK,CAACD,SAAS,CAAC,CAAC;EACnD,CAAC,CAAC;EAEF,IAAIE,6BAA6B;EACjC,IAAI3E,OAAO,CAAC4E,oBAAoB,EAAE;IAChCD,6BAA6B,GAAG,MAAM3E,OAAO,CAAC4E,oBAAoB,CAACrE,MAAM,CAAC;EAC5E;;EAEA;EACA,IAAI,CAACoE,6BAA6B,EAAE;IAClC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACApE,MAAM,CAACK,GAAG,CAAC,CACTiE,KAEC,EACDhE,GAAY,EACZC,GAAa,EACbC,IAAkB,KACf;MACH;MACA;MACA,IAAID,GAAG,CAACgE,WAAW,EAAE;QACnB/D,IAAI,CAAC8D,KAAK,CAAC;QACX;MACF;MAEA,MAAME,MAAM,GAAGF,KAAK,CAACE,MAAM,IAAIL,aAAK,CAACM,qBAAqB;MAC1D,MAAMC,UAAU,GAAGF,MAAM,IAAKL,aAAK,CAACM,qBAAgC;;MAEpE;MACAhF,OAAO,CAACU,MAAM,CAAEwE,GAAG,CAACD,UAAU,GAAG,OAAO,GAAG,OAAO,EAAEJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC;MAErE,IAAIC,OAAO,GAAGP,KAAK,CAACO,OAAO,IAAI,IAAAC,uBAAe,EAACN,MAAM,CAAC;MACtD,IAAIE,UAAU,IAAInB,OAAO,CAACwB,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;QACvDH,OAAO,GAAGZ,cAAM,CAACQ,qBAAqB;MACxC;MAEAlE,GAAG,CAACiE,MAAM,CAACA,MAAM,CAAC,CAAC7C,IAAI,CAACkD,OAAO,CAAC;IAClC,CAAC,CAAC;EACJ;EAEA,OAAO7E,MAAM;AACf","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"server.js","names":["_path","require","_url","_lodash","_compression","_interopRequireDefault","_cookieParser","_csurf","_express","_serveFavicon","_helmet","_morgan","_requestIp","_uuid","_renderer","_errors","defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","cookieSignatureSecret","requestIp","mw","csrf","cookie","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","getErrorForCode","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\n\nimport express, {\n type Express,\n type NextFunction,\n type RequestHandler,\n type Request,\n type Response,\n} from 'express';\n\nimport favicon from 'serve-favicon';\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport type { Compiler, Configuration } from 'webpack';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT =\nExclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => boolean | Promise<boolean>;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cookieSignatureSecret?: string;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser(options.cookieSignatureSecret));\n server.use(requestIp.mw());\n\n server.use(csrf({ cookie: true }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n /* eslint-disable @typescript-eslint/no-require-imports */\n const webpack = require('webpack') as (ops: Configuration) => Compiler;\n\n // TODO: Figure out the exact type for options, don't wanna waste time on it\n // right now.\n const webpackDevMiddleware = require('webpack-dev-middleware') as\n (c: Compiler, ops: unknown) => RequestHandler;\n\n const webpackHotMiddleware = require('webpack-hot-middleware') as\n (c: Compiler) => RequestHandler;\n\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":";;;;;;;;AAIA,IAAAA,KAAA,GAAAC,OAAA;AACA,IAAAC,IAAA,GAAAD,OAAA;AAEA,IAAAE,OAAA,GAAAF,OAAA;AAMA,IAAAG,YAAA,GAAAC,sBAAA,CAAAJ,OAAA;AACA,IAAAK,aAAA,GAAAD,sBAAA,CAAAJ,OAAA;AACA,IAAAM,MAAA,GAAAF,sBAAA,CAAAJ,OAAA;AAEA,IAAAO,QAAA,GAAAH,sBAAA,CAA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MC,UAAU,GAAGF,MAAM,IAAKL,aAAK,CAACM,qBAAgC;;MAEpE;MACAjF,OAAO,CAACU,MAAM,CAAEyE,GAAG,CAACD,UAAU,GAAG,OAAO,GAAG,OAAO,EAAEJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC;MAErE,IAAIC,OAAO,GAAGP,KAAK,CAACO,OAAO,IAAI,IAAAC,uBAAe,EAACN,MAAM,CAAC;MACtD,IAAIE,UAAU,IAAInB,OAAO,CAACwB,GAAG,CAACC,QAAQ,KAAK,YAAY,EAAE;QACvDH,OAAO,GAAGZ,cAAM,CAACQ,qBAAqB;MACxC;MAEAnE,GAAG,CAACkE,MAAM,CAACA,MAAM,CAAC,CAAC9C,IAAI,CAACmD,OAAO,CAAC;IAClC,CAAC,CAAC;EACJ;EAEA,OAAO9E,MAAM;AACf","ignoreList":[]}
|
|
@@ -36,7 +36,7 @@ eval("/**\n * @license React\n * react-jsx-runtime.development.js\n *\n * Copyri
|
|
|
36
36
|
\*******************************************/
|
|
37
37
|
/***/ (function(module, __unused_webpack_exports, __webpack_require__) {
|
|
38
38
|
|
|
39
|
-
eval("\n\nif (false) {} else {\n module.exports = __webpack_require__(/*! ./cjs/react-jsx-runtime.development.js */ \"./node_modules/react/cjs/react-jsx-runtime.development.js\");\n}\n\n\n//# sourceURL=webpack://@dr.pogodin/react-utils/./node_modules/react/jsx-runtime.js?");
|
|
39
|
+
eval("\n\nif (false) // removed by dead control flow\n{} else {\n module.exports = __webpack_require__(/*! ./cjs/react-jsx-runtime.development.js */ \"./node_modules/react/cjs/react-jsx-runtime.development.js\");\n}\n\n\n//# sourceURL=webpack://@dr.pogodin/react-utils/./node_modules/react/jsx-runtime.js?");
|
|
40
40
|
|
|
41
41
|
/***/ }),
|
|
42
42
|
|
|
@@ -31,7 +31,7 @@ delete defaultCspSettings.directives["upgrade-insecure-requests"];/**
|
|
|
31
31
|
// compatibility. Should be removed sometime later.
|
|
32
32
|
req2.cspNonce=req2.nonce;// The deep clone is necessary here to ensure that default value can't be
|
|
33
33
|
// mutated during request processing.
|
|
34
|
-
let cspSettings=(0,_lodash.cloneDeep)(defaultCspSettings);(cspSettings.directives?.["script-src"]).push(`'nonce-${req2.nonce}'`);if(options.cspSettingsHook){cspSettings=options.cspSettingsHook(cspSettings,req)}_helmet.default.contentSecurityPolicy(cspSettings)(req,res,next)})}if(options.favicon){server.use((0,_serveFavicon.default)(options.favicon))}server.use("/robots.txt",(req,res)=>{res.send("User-agent: *\nDisallow:")});server.use(_express.default.json({limit:"300kb"}));server.use(_express.default.urlencoded({extended:false}));server.use((0,_cookieParser.default)());server.use(_requestIp.default.mw());server.use((0,_csurf.default)({cookie:true}));_morgan.default.token("ip",req=>req.clientIp);const FORMAT=":ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent";server.use((0,_morgan.default)(FORMAT,{stream:{// TODO: This implies the logger is always set. Is it on a higher level?
|
|
34
|
+
let cspSettings=(0,_lodash.cloneDeep)(defaultCspSettings);(cspSettings.directives?.["script-src"]).push(`'nonce-${req2.nonce}'`);if(options.cspSettingsHook){cspSettings=options.cspSettingsHook(cspSettings,req)}_helmet.default.contentSecurityPolicy(cspSettings)(req,res,next)})}if(options.favicon){server.use((0,_serveFavicon.default)(options.favicon))}server.use("/robots.txt",(req,res)=>{res.send("User-agent: *\nDisallow:")});server.use(_express.default.json({limit:"300kb"}));server.use(_express.default.urlencoded({extended:false}));server.use((0,_cookieParser.default)(options.cookieSignatureSecret));server.use(_requestIp.default.mw());server.use((0,_csurf.default)({cookie:true}));_morgan.default.token("ip",req=>req.clientIp);const FORMAT=":ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent";server.use((0,_morgan.default)(FORMAT,{stream:{// TODO: This implies the logger is always set. Is it on a higher level?
|
|
35
35
|
// then mark it as always present.
|
|
36
36
|
write:options.logger.info.bind(options.logger)}}));// Note: no matter the "public path", we want the service worker, if any,
|
|
37
37
|
// to be served from the root, to have all web app pages in its scope.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","names":["_path","require","_url","_lodash","_compression","_interopRequireDefault","_cookieParser","_csurf","_express","_serveFavicon","_helmet","_morgan","_requestIp","_uuid","_renderer","_errors","defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","requestIp","mw","csrf","cookie","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","getErrorForCode","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\n\nimport express, {\n type Express,\n type NextFunction,\n type RequestHandler,\n type Request,\n type Response,\n} from 'express';\n\nimport favicon from 'serve-favicon';\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport type { Compiler, Configuration } from 'webpack';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT =\nExclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => boolean | Promise<boolean>;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser());\n server.use(requestIp.mw());\n\n server.use(csrf({ cookie: true }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n /* eslint-disable @typescript-eslint/no-require-imports */\n const webpack = require('webpack') as (ops: Configuration) => Compiler;\n\n // TODO: Figure out the exact type for options, don't wanna waste time on it\n // right now.\n const webpackDevMiddleware = require('webpack-dev-middleware') as\n (c: Compiler, ops: unknown) => RequestHandler;\n\n const webpackHotMiddleware = require('webpack-hot-middleware') as\n (c: Compiler) => RequestHandler;\n\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":"qOAIA,IAAAA,KAAA,CAAAC,OAAA,SACA,IAAAC,IAAA,CAAAD,OAAA,QAEA,IAAAE,OAAA,CAAAF,OAAA,WAMA,IAAAG,YAAA,CAAAC,sBAAA,CAAAJ,OAAA,iBACA,IAAAK,aAAA,CAAAD,sBAAA,CAAAJ,OAAA,mBACA,IAAAM,MAAA,CAAAF,sBAAA,CAAAJ,OAA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AM,CAAGF,KAAK,CAACE,MAAM,EAAIL,aAAK,CAACM,qBAAqB,CAC1D,KAAM,CAAAC,UAAU,CAAGF,MAAM,EAAKL,aAAK,CAACM,qBAAgC,CAEpE;AACAhF,OAAO,CAACU,MAAM,CAAEwE,GAAG,CAACD,UAAU,CAAG,OAAO,CAAG,OAAO,CAAEJ,KAAK,CAACM,QAAQ,CAAC,CAAC,CAAC,CAErE,GAAI,CAAAC,OAAO,CAAGP,KAAK,CAACO,OAAO,EAAI,GAAAC,uBAAe,EAACN,MAAM,CAAC,CACtD,GAAIE,UAAU,EAAInB,OAAO,CAACwB,GAAG,CAACC,QAAQ,GAAK,YAAY,CAAE,CACvDH,OAAO,CAAGZ,cAAM,CAACQ,qBACnB,CAEAlE,GAAG,CAACiE,MAAM,CAACA,MAAM,CAAC,CAAC7C,IAAI,CAACkD,OAAO,CACjC,CAAC,CACH,CAEA,MAAO,CAAA7E,MACT","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"server.js","names":["_path","require","_url","_lodash","_compression","_interopRequireDefault","_cookieParser","_csurf","_express","_serveFavicon","_helmet","_morgan","_requestIp","_uuid","_renderer","_errors","defaultCspSettings","directives","mapValues","helmet","contentSecurityPolicy","getDefaultDirectives","array","filter","item","push","getDefaultCspSettings","cloneDeep","factory","webpackConfig","options","rendererOps","pick","renderer","rendererFactory","publicPath","output","server","express","beforeExpressJsSetup","logger","httpsRedirect","use","req","res","next","schema","headers","url","host","originalUrl","redirect","compression","crossOriginEmbedderPolicy","crossOriginOpenerPolicy","crossOriginResourcePolicy","noCsp","req2","nonce","uuid","cspNonce","cspSettings","cspSettingsHook","favicon","send","json","limit","urlencoded","extended","cookieParser","cookieSignatureSecret","requestIp","mw","csrf","cookie","loggerMiddleware","token","clientIp","FORMAT","stream","write","info","bind","get","static","path","setHeaders","set","devMode","global","location","href","pathToFileURL","process","cwd","sep","webpack","webpackDevMiddleware","webpackHotMiddleware","compiler","serverSideRender","onExpressJsSetup","newError","ERRORS","NOT_FOUND","CODES","dontAttachDefaultErrorHandler","beforeExpressJsError","error","headersSent","status","INTERNAL_SERVER_ERROR","serverSide","log","toString","message","getErrorForCode","env","NODE_ENV"],"sources":["../../../src/server/server.ts"],"sourcesContent":["/**\n * Creation of standard ExpressJS server for ReactJS apps.\n */\n\nimport { sep } from 'path';\nimport { pathToFileURL } from 'url';\n\nimport {\n cloneDeep,\n mapValues,\n pick,\n} from 'lodash';\n\nimport compression from 'compression';\nimport cookieParser from 'cookie-parser';\nimport csrf from '@dr.pogodin/csurf';\n\nimport express, {\n type Express,\n type NextFunction,\n type RequestHandler,\n type Request,\n type Response,\n} from 'express';\n\nimport favicon from 'serve-favicon';\nimport helmet, { type HelmetOptions } from 'helmet';\nimport loggerMiddleware from 'morgan';\nimport requestIp from 'request-ip';\nimport { v4 as uuid } from 'uuid';\n\nimport type { Compiler, Configuration } from 'webpack';\n\nimport rendererFactory, {\n type LoggerI,\n type OptionsT as RendererOptionsT,\n} from './renderer';\n\nimport {\n CODES,\n ERRORS,\n getErrorForCode,\n newError,\n} from './utils/errors';\n\nexport type CspOptionsT =\nExclude<HelmetOptions['contentSecurityPolicy'], boolean | undefined>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface RequestT extends Request {\n cspNonce: string;\n nonce: string;\n}\n\n/**\n * Default Content Security Policy settings.\n * @ignore\n */\nconst defaultCspSettings = {\n directives: mapValues(\n helmet.contentSecurityPolicy.getDefaultDirectives(),\n\n // 'https:' options (automatic re-write of insecure URLs to secure ones)\n // is removed to facilitate local development with HTTP server. In cloud\n // deployments we assume Apache or Nginx server in front of out app takes\n // care about such re-writes.\n (array) => (array as string[]).filter((item: string) => item !== 'https:'),\n ),\n};\ndefaultCspSettings.directives['frame-src'] = [\n \"'self'\",\n\n // YouTube domain is whitelisted to allow <YouTubeVideo> component to work\n // out of box.\n 'https://*.youtube.com',\n];\n\n{\n const directives = defaultCspSettings.directives['script-src'];\n if (directives) directives.push(\"'unsafe-eval'\");\n else defaultCspSettings.directives['script-src'] = [\"'unsafe-eval'\"];\n}\n\n// No need for automatic re-writes via Content Security Policy settings:\n// the forefront Apache or Nginx server is supposed to take care of this\n// in production cloud deployments.\ndelete defaultCspSettings.directives['upgrade-insecure-requests'];\n\n/**\n * @category Utilities\n * @func server/getDefaultCspSettings\n * @global\n * @desc\n * ```js\n * import { server } from '@dr.pogodin/react-utils';\n * const { getDefaultCspSettings } from '@dr.pogodin/react-utils';\n * ```\n * @return {{\n * directives: object\n * }} A deep copy of default CSP settings object used by `react-utils`,\n * with the exception of `nonce-xxx` clause in `script-src` directive,\n * which is added dynamically for each request.\n */\nexport function getDefaultCspSettings(): {\n directives: Record<string, string[]>;\n} {\n return cloneDeep(defaultCspSettings);\n}\n\nexport type ServerT = Express & {\n logger: LoggerI;\n};\n\nexport type OptionsT = RendererOptionsT & {\n beforeExpressJsError?:\n (server: ServerT) => boolean | Promise<boolean>;\n\n beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n cookieSignatureSecret?: string;\n cspSettingsHook?: (\n defaultOptions: CspOptionsT,\n req: Request,\n ) => CspOptionsT;\n devMode?: boolean;\n httpsRedirect?: boolean;\n onExpressJsSetup?: (server: ServerT) => Promise<void> | void;\n};\n\nexport default async function factory(\n webpackConfig: Configuration,\n options: OptionsT,\n): Promise<ServerT> {\n const rendererOps: RendererOptionsT = pick(options, [\n 'Application',\n 'beforeRender',\n 'favicon',\n 'logger',\n 'maxSsrRounds',\n 'noCsp',\n 'ssrTimeout',\n 'staticCacheController',\n 'staticCacheSize',\n ]);\n const renderer = rendererFactory(webpackConfig, rendererOps);\n const { publicPath } = webpackConfig.output!;\n\n const server = express() as ServerT;\n\n if (options.beforeExpressJsSetup) {\n await options.beforeExpressJsSetup(server);\n }\n\n if (options.logger) server.logger = options.logger;\n\n if (options.httpsRedirect) {\n server.use((req, res, next) => {\n const schema = req.headers['x-forwarded-proto'];\n if (schema === 'http') {\n let url = `https://${req.headers.host}`;\n if (req.originalUrl !== '/') url += req.originalUrl;\n res.redirect(url);\n return;\n }\n next();\n });\n }\n\n server.use(compression());\n server.use(\n helmet({\n contentSecurityPolicy: false,\n crossOriginEmbedderPolicy: false,\n crossOriginOpenerPolicy: false,\n crossOriginResourcePolicy: false,\n }),\n );\n\n if (!options.noCsp) {\n server.use(\n (req: Request, res: Response, next: NextFunction) => {\n const req2 = req as RequestT;\n\n req2.nonce = uuid();\n\n // TODO: This is deprecated, but it is kept for now for backward\n // compatibility. Should be removed sometime later.\n req2.cspNonce = req2.nonce;\n\n // The deep clone is necessary here to ensure that default value can't be\n // mutated during request processing.\n let cspSettings: CspOptionsT = cloneDeep(defaultCspSettings);\n (cspSettings.directives?.['script-src'] as string[]).push(`'nonce-${req2.nonce}'`);\n if (options.cspSettingsHook) {\n cspSettings = options.cspSettingsHook(cspSettings, req);\n }\n helmet.contentSecurityPolicy(cspSettings)(req, res, next);\n },\n );\n }\n\n if (options.favicon) {\n server.use(favicon(options.favicon));\n }\n\n server.use('/robots.txt', (req, res) => {\n res.send('User-agent: *\\nDisallow:');\n });\n\n server.use(express.json({ limit: '300kb' }));\n server.use(express.urlencoded({ extended: false }));\n server.use(cookieParser(options.cookieSignatureSecret));\n server.use(requestIp.mw());\n\n server.use(csrf({ cookie: true }));\n\n loggerMiddleware.token(\n 'ip',\n (req: Request & { clientIp: string }) => req.clientIp,\n );\n const FORMAT = ':ip > :status :method :url :response-time ms :res[content-length] :referrer :user-agent';\n server.use(loggerMiddleware(FORMAT, {\n stream: {\n // TODO: This implies the logger is always set. Is it on a higher level?\n // then mark it as always present.\n write: options.logger!.info.bind(options.logger),\n },\n }));\n\n // Note: no matter the \"public path\", we want the service worker, if any,\n // to be served from the root, to have all web app pages in its scope.\n // Thus, this setup to serve it. Probably, need some more configuration\n // for special cases, but this will do for now.\n server.get('/__service-worker.js', express.static(\n webpackConfig.output?.path ?? '',\n {\n setHeaders: (res) => res.set('Cache-Control', 'no-cache'),\n },\n ));\n\n /* Setup of Hot Module Reloading for development environment.\n * These dependencies are not used, nor installed for production use,\n * hence we should violate some import-related lint rules. */\n /* eslint-disable import/no-extraneous-dependencies */\n if (options.devMode) {\n // This is a workaround for SASS bug:\n // https://github.com/dart-lang/sdk/issues/27979\n // which manifests itself sometimes when webpack dev middleware is used\n // (in dev mode), and app modules are imported in some unfortunate ways.\n // TODO: Double-check, what is going on here.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!global.location) {\n global.location = {\n href: `${pathToFileURL(process.cwd()).href}${sep}`,\n } as Location;\n }\n\n /* eslint-disable @typescript-eslint/no-require-imports */\n const webpack = require('webpack') as (ops: Configuration) => Compiler;\n\n // TODO: Figure out the exact type for options, don't wanna waste time on it\n // right now.\n const webpackDevMiddleware = require('webpack-dev-middleware') as\n (c: Compiler, ops: unknown) => RequestHandler;\n\n const webpackHotMiddleware = require('webpack-hot-middleware') as\n (c: Compiler) => RequestHandler;\n\n const compiler = webpack(webpackConfig);\n server.use(webpackDevMiddleware(compiler, {\n publicPath,\n serverSideRender: true,\n }));\n server.use(webpackHotMiddleware(compiler));\n }\n /* eslint-enable import/no-extraneous-dependencies */\n\n server.use(publicPath as string, express.static(webpackConfig.output!.path!));\n\n if (options.onExpressJsSetup) {\n await options.onExpressJsSetup(server);\n }\n server.use(renderer);\n\n /* Detects 404 errors, and forwards them to the error handler. */\n server.use((req, res, next) => {\n next(newError(ERRORS.NOT_FOUND, CODES.NOT_FOUND));\n });\n\n let dontAttachDefaultErrorHandler;\n if (options.beforeExpressJsError) {\n dontAttachDefaultErrorHandler = await options.beforeExpressJsError(server);\n }\n\n /* Error handler. */\n if (!dontAttachDefaultErrorHandler) {\n // TODO: Do we need this error handler at all? It actually seems to do\n // what the default ExpressJS error handler does anyway, see:\n // https://expressjs.com/en/guide/error-handling.html\n //\n // TODO: It is better to move the default error handler definition\n // to a stand-alone function at top-level, but the use of options.logger\n // prevents to do it without some extra refactoring. Should be done sometime\n // though.\n server.use((\n error: Error & {\n status?: number;\n },\n req: Request,\n res: Response,\n next: NextFunction,\n ) => {\n // TODO: This is needed to correctly handled any errors thrown after\n // sending initial response to the client.\n if (res.headersSent) {\n next(error);\n return;\n }\n\n const status = error.status ?? CODES.INTERNAL_SERVER_ERROR;\n const serverSide = status >= (CODES.INTERNAL_SERVER_ERROR as number);\n\n // Log server-side errors always, client-side at debug level only.\n options.logger!.log(serverSide ? 'error' : 'debug', error.toString());\n\n let message = error.message || getErrorForCode(status);\n if (serverSide && process.env.NODE_ENV === 'production') {\n message = ERRORS.INTERNAL_SERVER_ERROR;\n }\n\n res.status(status).send(message);\n });\n }\n\n return server;\n}\n"],"mappings":"qOAIA,IAAAA,KAAA,CAAAC,OAAA,SACA,IAAAC,IAAA,CAAAD,OAAA,QAEA,IAAAE,OAAA,CAAAF,OAAA,WAMA,IAAAG,YAAA,CAAAC,sBAAA,CAAAJ,OAAA,iBACA,IAAAK,aAAA,CAAAD,sBAAA,CAAAJ,OAAA,mBACA,IAAAM,MAAA,CAAAF,sBAAA,CAAAJ,OAAA,uBAEA,IAAAO,QAAA,CAAAH,sBAAA,CAAAJ,OAAA,aAQA,IAAAQ,aAAA,CAAAJ,sBAAA,CAAAJ,OAAA,mBACA,IAAAS,OAAA,CAAAL,sBAAA,CAAAJ,OAAA,YACA,IAAAU,OAAA,CAAAN,sBAAA,CAAAJ,OAAA,YACA,IAAAW,UAAA,CAAAP,sBAAA,CAAAJ,OAAA,gBACA,IAAAY,KAAA,CAAAZ,OAAA,SAIA,IAAAa,SAAA,CAAAT,sBAAA,CAAAJ,OAAA,gBAKA,IAAAc,OAAA,CAAAd,OAAA,mBAtCA;AACA;AACA,GA8CA;AAMA;AACA;AACA;AACA,GACA,KAAM,CAAAe,kBAAkB,CAAG,CACzBC,UAAU,CAAE,GAAAC,iBAAS,EACnBC,eAAM,CAACC,qBAAqB,CAACC,oBAAoB,CAAC,CAAC,CAEnD;AACA;AACA;AACA;AACCC,KAAK,EAAMA,KAAK,CAAcC,MAAM,CAAEC,IAA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ignoreList":[]}
|
|
@@ -30,6 +30,7 @@ export type ServerT = Express & {
|
|
|
30
30
|
export type OptionsT = RendererOptionsT & {
|
|
31
31
|
beforeExpressJsError?: (server: ServerT) => boolean | Promise<boolean>;
|
|
32
32
|
beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;
|
|
33
|
+
cookieSignatureSecret?: string;
|
|
33
34
|
cspSettingsHook?: (defaultOptions: CspOptionsT, req: Request) => CspOptionsT;
|
|
34
35
|
devMode?: boolean;
|
|
35
36
|
httpsRedirect?: boolean;
|
package/package.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "1.43.
|
|
2
|
+
"version": "1.43.13",
|
|
3
3
|
"bin": {
|
|
4
4
|
"react-utils-build": "bin/build.js",
|
|
5
5
|
"react-utils-setup": "bin/setup.js"
|
|
@@ -10,16 +10,16 @@
|
|
|
10
10
|
"dependencies": {
|
|
11
11
|
"@babel/runtime": "^7.27.1",
|
|
12
12
|
"@dr.pogodin/babel-plugin-react-css-modules": "^6.13.5",
|
|
13
|
-
"@dr.pogodin/csurf": "^1.16.
|
|
13
|
+
"@dr.pogodin/csurf": "^1.16.2",
|
|
14
14
|
"@dr.pogodin/js-utils": "^0.0.18",
|
|
15
15
|
"@dr.pogodin/react-global-state": "^0.19.2",
|
|
16
16
|
"@dr.pogodin/react-helmet": "^3.0.2",
|
|
17
17
|
"@dr.pogodin/react-themes": "^1.9.0",
|
|
18
18
|
"@jest/environment": "^29.7.0",
|
|
19
19
|
"axios": "^1.9.0",
|
|
20
|
-
"commander": "^
|
|
20
|
+
"commander": "^14.0.0",
|
|
21
21
|
"compression": "^1.8.0",
|
|
22
|
-
"config": "^
|
|
22
|
+
"config": "^4.0.0",
|
|
23
23
|
"cookie": "^1.0.2",
|
|
24
24
|
"cookie-parser": "^1.4.7",
|
|
25
25
|
"cross-env": "^7.0.3",
|
|
@@ -66,14 +66,14 @@
|
|
|
66
66
|
"@types/config": "^3.3.5",
|
|
67
67
|
"@types/cookie": "^0.6.0",
|
|
68
68
|
"@types/cookie-parser": "^1.4.8",
|
|
69
|
-
"@types/express": "^5.0.
|
|
69
|
+
"@types/express": "^5.0.2",
|
|
70
70
|
"@types/jest": "^29.5.14",
|
|
71
71
|
"@types/lodash": "^4.17.16",
|
|
72
72
|
"@types/morgan": "^1.9.9",
|
|
73
73
|
"@types/node-forge": "^1.3.11",
|
|
74
74
|
"@types/pretty": "^2.0.3",
|
|
75
|
-
"@types/react": "^19.1.
|
|
76
|
-
"@types/react-dom": "^19.1.
|
|
75
|
+
"@types/react": "^19.1.4",
|
|
76
|
+
"@types/react-dom": "^19.1.5",
|
|
77
77
|
"@types/request-ip": "^0.0.41",
|
|
78
78
|
"@types/serialize-javascript": "^5.0.4",
|
|
79
79
|
"@types/serve-favicon": "^2.5.7",
|
|
@@ -90,7 +90,7 @@
|
|
|
90
90
|
"identity-obj-proxy": "^3.0.0",
|
|
91
91
|
"jest": "^29.7.0",
|
|
92
92
|
"jest-environment-jsdom": "^29.7.0",
|
|
93
|
-
"memfs": "^4.17.
|
|
93
|
+
"memfs": "^4.17.2",
|
|
94
94
|
"mini-css-extract-plugin": "^2.9.2",
|
|
95
95
|
"mockdate": "^3.0.5",
|
|
96
96
|
"nodelist-foreach-polyfill": "^1.2.0",
|
|
@@ -101,18 +101,18 @@
|
|
|
101
101
|
"react-refresh": "^0.17.0",
|
|
102
102
|
"regenerator-runtime": "^0.14.1",
|
|
103
103
|
"resolve-url-loader": "^5.0.0",
|
|
104
|
-
"sass": "^1.
|
|
104
|
+
"sass": "^1.89.0",
|
|
105
105
|
"sass-loader": "^16.0.5",
|
|
106
106
|
"sitemap": "^8.0.0",
|
|
107
107
|
"source-map-loader": "^5.0.0",
|
|
108
108
|
"stylelint": "^16.19.1",
|
|
109
|
-
"stylelint-config-standard-scss": "^15.0.
|
|
110
|
-
"supertest": "^7.1.
|
|
109
|
+
"stylelint-config-standard-scss": "^15.0.1",
|
|
110
|
+
"supertest": "^7.1.1",
|
|
111
111
|
"tsc-alias": "1.8.16",
|
|
112
112
|
"tstyche": "^3.5.0",
|
|
113
113
|
"typed-scss-modules": "^8.1.1",
|
|
114
114
|
"typescript": "^5.8.3",
|
|
115
|
-
"webpack": "^5.99.
|
|
115
|
+
"webpack": "^5.99.9",
|
|
116
116
|
"webpack-dev-middleware": "^7.4.2",
|
|
117
117
|
"webpack-hot-middleware": "^2.26.1",
|
|
118
118
|
"webpack-merge": "^6.0.1",
|
package/src/server/server.ts
CHANGED
|
@@ -116,6 +116,7 @@ export type OptionsT = RendererOptionsT & {
|
|
|
116
116
|
(server: ServerT) => boolean | Promise<boolean>;
|
|
117
117
|
|
|
118
118
|
beforeExpressJsSetup?: (server: ServerT) => Promise<void> | void;
|
|
119
|
+
cookieSignatureSecret?: string;
|
|
119
120
|
cspSettingsHook?: (
|
|
120
121
|
defaultOptions: CspOptionsT,
|
|
121
122
|
req: Request,
|
|
@@ -207,7 +208,7 @@ export default async function factory(
|
|
|
207
208
|
|
|
208
209
|
server.use(express.json({ limit: '300kb' }));
|
|
209
210
|
server.use(express.urlencoded({ extended: false }));
|
|
210
|
-
server.use(cookieParser());
|
|
211
|
+
server.use(cookieParser(options.cookieSignatureSecret));
|
|
211
212
|
server.use(requestIp.mw());
|
|
212
213
|
|
|
213
214
|
server.use(csrf({ cookie: true }));
|