config.default.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. 'use strict';
  2. const fs = require('fs');
  3. const path = require('path');
  4. /**
  5. * The configuration of egg application, can be access by `app.config`
  6. * @class Config
  7. * @since 1.0.0
  8. */
  9. module.exports = appInfo => {
  10. const config = {
  11. /**
  12. * The environment of egg
  13. * @member {String} Config#env
  14. * @see {appInfo#env}
  15. * @since 1.0.0
  16. */
  17. env: appInfo.env,
  18. /**
  19. * The name of the application
  20. * @member {String} Config#name
  21. * @see {appInfo#name}
  22. * @since 1.0.0
  23. */
  24. name: appInfo.name,
  25. /**
  26. * The key that signing cookies. It can contain multiple keys seperated by `,`.
  27. * @member {String} Config#keys
  28. * @see http://eggjs.org/en/core/cookie-and-session.html#cookie-secret-key
  29. * @default
  30. * @since 1.0.0
  31. */
  32. keys: '',
  33. /**
  34. * default cookie options
  35. *
  36. * @member Config#cookies
  37. * @property {String} sameSite - SameSite property, defaults is ''
  38. * @property {Boolean} httpOnly - httpOnly property, defaults is true
  39. */
  40. cookies: {
  41. // httpOnly: true | false,
  42. // sameSite: 'none|lax|strict',
  43. },
  44. /**
  45. * Whether application deployed after a reverse proxy,
  46. * when true proxy header fields will be trusted
  47. * @member {Boolean} Config#proxy
  48. * @default
  49. * @since 1.0.0
  50. */
  51. proxy: false,
  52. /**
  53. *
  54. * max ips read from proxy ip header, default to 0 (means infinity)
  55. * to prevent users from forging client ip addresses via x-forwarded-for
  56. * @see https://github.com/koajs/koa/blob/master/docs/api/request.md#requestips
  57. * @member {Integer} Config#maxIpsCount
  58. * @default
  59. * @since 2.25.0
  60. */
  61. maxIpsCount: 0,
  62. /**
  63. * please use maxIpsCount instead
  64. * @member {Integer} Config#maxProxyCount
  65. * @default
  66. * @since 2.21.0
  67. * @deprecated
  68. */
  69. maxProxyCount: 0,
  70. /**
  71. * Detect request's protocol from specified headers, not case-sensitive.
  72. * Only worked when config.proxy set to true.
  73. * @member {String} Config#protocolHeaders
  74. * @default
  75. * @since 1.0.0
  76. */
  77. protocolHeaders: 'x-forwarded-proto',
  78. /**
  79. * Detect request' ip from specified headers, not case-sensitive.
  80. * Only worked when config.proxy set to true.
  81. * @member {String} Config#ipHeaders
  82. * @default
  83. * @since 1.0.0
  84. */
  85. ipHeaders: 'x-forwarded-for',
  86. /**
  87. * Detect request' host from specified headers, not case-sensitive.
  88. * Only worked when config.proxy set to true.
  89. * @member {String} Config#hostHeaders
  90. * @default
  91. * @since 1.0.0
  92. */
  93. hostHeaders: '',
  94. /**
  95. * package.json
  96. * @member {Object} Config#pkg
  97. * @see {appInfo#pkg}
  98. * @since 1.0.0
  99. */
  100. pkg: appInfo.pkg,
  101. /**
  102. * The current directory of the application
  103. * @member {String} Config#baseDir
  104. * @see {appInfo#baseDir}
  105. * @since 1.0.0
  106. */
  107. baseDir: appInfo.baseDir,
  108. /**
  109. * The current HOME directory
  110. * @member {String} Config#HOME
  111. * @see {appInfo#HOME}
  112. * @since 1.0.0
  113. */
  114. HOME: appInfo.HOME,
  115. /**
  116. * The directory of server running. You can find `application_config.json` under it that is dumpped from `app.config`.
  117. * @member {String} Config#rundir
  118. * @default
  119. * @since 1.0.0
  120. */
  121. rundir: path.join(appInfo.baseDir, 'run'),
  122. /**
  123. * dump config
  124. *
  125. * It will ignore special keys when dumpConfig
  126. *
  127. * @member Config#dump
  128. * @property {Set} ignore - keys to ignore
  129. */
  130. dump: {
  131. ignore: new Set([
  132. 'pass', 'pwd', 'passd', 'passwd', 'password', 'keys', 'masterKey', 'accessKey',
  133. // ignore any key contains "secret" keyword
  134. /secret/i,
  135. ]),
  136. },
  137. /**
  138. * configurations are confused to users
  139. * {
  140. * [unexpectedKey]: [expectedKey],
  141. * }
  142. * @member Config#confusedConfigurations
  143. * @type {Object}
  144. */
  145. confusedConfigurations: {
  146. bodyparser: 'bodyParser',
  147. notFound: 'notfound',
  148. sitefile: 'siteFile',
  149. middlewares: 'middleware',
  150. httpClient: 'httpclient',
  151. },
  152. };
  153. /**
  154. * The option of `notfound` middleware
  155. *
  156. * It will return page or json depend on negotiation when 404,
  157. * If pageUrl is set, it will redirect to the page.
  158. *
  159. * @member Config#notfound
  160. * @property {String} pageUrl - the 404 page url
  161. */
  162. config.notfound = {
  163. pageUrl: '',
  164. };
  165. /**
  166. * The option of `siteFile` middleware
  167. *
  168. * You can map some files using this options, it will response immdiately when matching.
  169. *
  170. * @member {Object} Config#siteFile - key is path, and value is url or buffer.
  171. * @property {String} cacheControl - files cache , default is public, max-age=2592000
  172. * @example
  173. * // specific app's favicon, => '/favicon.ico': 'https://eggjs.org/favicon.ico',
  174. * config.siteFile = {
  175. * '/favicon.ico': 'https://eggjs.org/favicon.ico',
  176. * };
  177. */
  178. config.siteFile = {
  179. '/favicon.ico': fs.readFileSync(path.join(__dirname, 'favicon.png')),
  180. // default cache in 30 days
  181. cacheControl: 'public, max-age=2592000',
  182. };
  183. /**
  184. * The option of `bodyParser` middleware
  185. *
  186. * @member Config#bodyParser
  187. * @property {Boolean} enable - enable bodyParser or not, default is true
  188. * @property {String | RegExp | Function | Array} ignore - won't parse request body when url path hit ignore pattern, can not set `ignore` when `match` presented
  189. * @property {String | RegExp | Function | Array} match - will parse request body only when url path hit match pattern
  190. * @property {String} encoding - body's encoding type,default is utf8
  191. * @property {String} formLimit - limit of the urlencoded body. If the body ends up being larger than this limit, a 413 error code is returned. Default is 1mb
  192. * @property {String} jsonLimit - limit of the json body, default is 1mb
  193. * @property {String} textLimit - limit of the text body, default is 1mb
  194. * @property {Boolean} strict - when set to true, JSON parser will only accept arrays and objects. Default is true
  195. * @property {Number} queryString.arrayLimit - urlencoded body array's max length, default is 100
  196. * @property {Number} queryString.depth - urlencoded body object's max depth, default is 5
  197. * @property {Number} queryString.parameterLimit - urlencoded body maximum parameters, default is 1000
  198. */
  199. config.bodyParser = {
  200. enable: true,
  201. encoding: 'utf8',
  202. formLimit: '1mb',
  203. jsonLimit: '1mb',
  204. textLimit: '1mb',
  205. strict: true,
  206. // @see https://github.com/hapijs/qs/blob/master/lib/parse.js#L8 for more options
  207. queryString: {
  208. arrayLimit: 100,
  209. depth: 5,
  210. parameterLimit: 1000,
  211. },
  212. onerror(err) {
  213. err.message += ', check bodyParser config';
  214. throw err;
  215. },
  216. };
  217. /**
  218. * logger options
  219. * @member Config#logger
  220. * @property {String} dir - directory of log files
  221. * @property {String} encoding - log file encoding, defaults to utf8
  222. * @property {String} level - default log level, could be: DEBUG, INFO, WARN, ERROR or NONE, defaults to INFO in production
  223. * @property {String} consoleLevel - log level of stdout, defaults to INFO in local serverEnv, defaults to WARN in unittest, defaults to NONE elsewise
  224. * @property {Boolean} disableConsoleAfterReady - disable logger console after app ready. defaults to `false` on local and unittest env, others is `true`.
  225. * @property {Boolean} outputJSON - log as JSON or not, defaults to false
  226. * @property {Boolean} buffer - if enabled, flush logs to disk at a certain frequency to improve performance, defaults to true
  227. * @property {String} errorLogName - file name of errorLogger
  228. * @property {String} coreLogName - file name of coreLogger
  229. * @property {String} agentLogName - file name of agent worker log
  230. * @property {Object} coreLogger - custom config of coreLogger
  231. * @property {Boolean} allowDebugAtProd - allow debug log at prod, defaults to false
  232. * @property {Boolean} enablePerformanceTimer - using performance.now() timer instead of Date.now() for more more precise milliseconds, defaults to false. e.g.: logger will set 1.456ms instead of 1ms.
  233. */
  234. config.logger = {
  235. dir: path.join(appInfo.root, 'logs', appInfo.name),
  236. encoding: 'utf8',
  237. env: appInfo.env,
  238. level: 'INFO',
  239. consoleLevel: 'INFO',
  240. disableConsoleAfterReady: appInfo.env !== 'local' && appInfo.env !== 'unittest',
  241. outputJSON: false,
  242. buffer: true,
  243. appLogName: `${appInfo.name}-web.log`,
  244. coreLogName: 'egg-web.log',
  245. agentLogName: 'egg-agent.log',
  246. errorLogName: 'common-error.log',
  247. coreLogger: {},
  248. allowDebugAtProd: false,
  249. enablePerformanceTimer: false,
  250. };
  251. /**
  252. * The option for httpclient
  253. * @member Config#httpclient
  254. * @property {Boolean} enableDNSCache - Enable DNS lookup from local cache or not, default is false.
  255. * @property {Boolean} dnsCacheLookupInterval - minimum interval of DNS query on the same hostname (default 10s).
  256. *
  257. * @property {Number} request.timeout - httpclient request default timeout, default is 5000 ms.
  258. *
  259. * @property {Boolean} httpAgent.keepAlive - Enable http agent keepalive or not, default is true
  260. * @property {Number} httpAgent.freeSocketTimeout - http agent socket keepalive max free time, default is 4000 ms.
  261. * @property {Number} httpAgent.maxSockets - http agent max socket number of one host, default is `Number.MAX_SAFE_INTEGER` @ses https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
  262. * @property {Number} httpAgent.maxFreeSockets - http agent max free socket number of one host, default is 256.
  263. *
  264. * @property {Boolean} httpsAgent.keepAlive - Enable https agent keepalive or not, default is true
  265. * @property {Number} httpsAgent.freeSocketTimeout - httpss agent socket keepalive max free time, default is 4000 ms.
  266. * @property {Number} httpsAgent.maxSockets - https agent max socket number of one host, default is `Number.MAX_SAFE_INTEGER` @ses https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
  267. * @property {Number} httpsAgent.maxFreeSockets - https agent max free socket number of one host, default is 256.
  268. */
  269. config.httpclient = {
  270. enableDNSCache: false,
  271. dnsCacheLookupInterval: 10000,
  272. dnsCacheMaxLength: 1000,
  273. request: {
  274. timeout: 5000,
  275. },
  276. httpAgent: {
  277. keepAlive: true,
  278. freeSocketTimeout: 4000,
  279. maxSockets: Number.MAX_SAFE_INTEGER,
  280. maxFreeSockets: 256,
  281. },
  282. httpsAgent: {
  283. keepAlive: true,
  284. freeSocketTimeout: 4000,
  285. maxSockets: Number.MAX_SAFE_INTEGER,
  286. maxFreeSockets: 256,
  287. },
  288. };
  289. /**
  290. * The option of `meta` middleware
  291. *
  292. * @member Config#meta
  293. * @property {Boolean} enable - enable meta or not, default is true
  294. * @property {Boolean} logging - enable logging start request, default is false
  295. */
  296. config.meta = {
  297. enable: true,
  298. logging: false,
  299. };
  300. /**
  301. * core enable middlewares
  302. * @member {Array} Config#middleware
  303. */
  304. config.coreMiddleware = [
  305. 'meta',
  306. 'siteFile',
  307. 'notfound',
  308. 'bodyParser',
  309. 'overrideMethod',
  310. ];
  311. /**
  312. * emit `startTimeout` if worker don't ready after `workerStartTimeout` ms
  313. * @member {Number} Config.workerStartTimeout
  314. */
  315. config.workerStartTimeout = 10 * 60 * 1000;
  316. /**
  317. * server timeout in milliseconds, default to 2 minutes.
  318. *
  319. * for special request, just use `ctx.req.setTimeout(ms)`
  320. *
  321. * @member {Number} Config#serverTimeout
  322. * @see https://nodejs.org/api/http.html#http_server_timeout
  323. */
  324. config.serverTimeout = null;
  325. /**
  326. *
  327. * @member {Object} Config#cluster
  328. * @property {Object} listen - listen options, see {@link https://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback}
  329. * @property {String} listen.path - set a unix sock path when server listen
  330. * @property {Number} listen.port - set a port when server listen
  331. * @property {String} listen.hostname - set a hostname binding server when server listen
  332. */
  333. config.cluster = {
  334. listen: {
  335. path: '',
  336. port: 7001,
  337. hostname: '',
  338. },
  339. };
  340. /**
  341. * @property {Number} responseTimeout - response timeout, default is 60000
  342. */
  343. config.clusterClient = {
  344. maxWaitTime: 60000,
  345. responseTimeout: 60000,
  346. };
  347. /**
  348. * This function / async function will be called when a client error occurred and return the response.
  349. *
  350. * The arguments are `err`, `socket` and `application` which indicate current client error object, current socket
  351. * object and the application object.
  352. *
  353. * The response to be returned should include properties below:
  354. *
  355. * @member {Function} Config#onClientError
  356. * @property [body] {String|Buffer} - the response body
  357. * @property [status] {Number} - the response status code
  358. * @property [headers] {Object} - the response header key-value pairs
  359. *
  360. * @example
  361. * exports.onClientError = async (err, socket, app) => {
  362. * return {
  363. * body: 'error',
  364. * status: 400,
  365. * headers: {
  366. * 'powered-by': 'Egg.js',
  367. * }
  368. * };
  369. * }
  370. */
  371. config.onClientError = null;
  372. return config;
  373. };