-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
213 lines (184 loc) · 4.85 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import fs from 'fs'
import path from 'path'
import { readPackageUpSync } from 'read-package-up'
import hyperid from 'hyperid'
import fp from 'fastify-plugin'
import helmet from '@fastify/helmet'
import sensible from '@fastify/sensible'
import swagger from '@fastify/swagger'
import swaggerUi from '@fastify/swagger-ui'
import autoload from '@fastify/autoload'
import underPressure from '@fastify/under-pressure'
import assign from 'assign-deep'
import configure from './config.js'
const instance = hyperid({ urlSafe: true })
/**
* read package information
*/
const pack = readPackageUpSync()
/**
* factory to provide id generator and
* logger defaults by environment
*/
export const options = (config = {}) => {
const { ajv, logLevel = 'debug', trustProxy = false } = config
const { name, version } = pack.packageJson
const { NODE_ENV } = process.env
const envToLogger = {
development: {
level: logLevel,
name: `${name}@v${version}`,
transport: {
target: 'pino-pretty',
options: {
sync: true,
translateTime: true,
ignore: 'pid,hostname'
}
}
},
production: {
level: logLevel,
name: `${name}@v${version}`
},
test: false
}
const opts = {
forceCloseConnections: true,
trustProxy,
genReqId: instance,
logger: envToLogger[NODE_ENV || 'development'] ?? true // defaults to true if no entry matches in the map
}
return ajv ? { ...opts, ajv } : opts
}
export default fp((fastify, opts, next) => {
/**
* verify config options
*/
const config = configure(opts)
/**
* read package information
*/
const pack = readPackageUpSync()
const pkg = {
name: pack.packageJson.name,
version: pack.packageJson.version,
description: pack.packageJson.description,
root: path.dirname(pack.path)
}
/**
* add package information
*/
for (const [k, v] of Object.entries(pkg)) {
/**
* fastify ^3.6.0 uses fastify.version internaly,
* so avoid redeclaring
*/
if (!fastify.hasDecorator(k)) {
fastify.decorate(k, v)
}
}
/**
* add package information, namespaced
*/
fastify.decorate('app', pkg)
/**
* add config
*/
fastify.decorate('config', assign(config, opts))
/**
* add OpenAPI docs (v3.0 aka swagger)
*/
const swaggerConfig = config.swagger
/**
* prefer .openapi but use .swagger per default
*/
const customSwaggerConfig = {
...swaggerConfig.swagger,
...swaggerConfig.openapi
}
fastify.register(swagger, {
...swaggerConfig,
openapi: {
// customizable
...customSwaggerConfig,
// default infos from package.json
info: {
title: pkg.name,
description: pkg.description,
version: pkg.version,
// but customizable
...customSwaggerConfig.info
}
}
})
if (swaggerConfig.exposeRoute) {
fastify.register(swaggerUi, swaggerConfig)
}
/**
* add helmet (http security headers)
*/
fastify.register(helmet, {
contentSecurityPolicy: config.contentSecurityPolicy
})
/**
* @see https://github.com/fastify/fastify-swagger#integration
*/
// fastify.register(helmet, (instance) => {
// console.log(helmet.contentSecurityPolicy.getDefaultDirectives())
// console.log(instance.swaggerCSP)
// return {
// contentSecurityPolicy: {
// directives: {
// ...helmet.contentSecurityPolicy.getDefaultDirectives(),
// 'form-action': ["'self'"],
// 'img-src': ["'self'", 'data:', 'validator.swagger.io'],
// 'script-src': ["'self'"].concat(instance.swaggerCSP.script),
// 'style-src': ["'self'", 'https:'].concat(instance.swaggerCSP.style)
// }
// }
// }
// })
/**
* add sensible defaults
*/
fastify.register(sensible)
/**
* autoload plugins, services, etc
* @see https://github.com/fastify/fastify/blob/master/docs/Getting-Started.md#loading-order-of-your-plugins
*/
for (const dir of config.autoloads) {
if (fs.existsSync(dir))
fastify.register(autoload, {
dir,
options: config
})
}
/**
* add application health check
*/
fastify.register(underPressure, config.health)
/**
* post-treatment
*/
fastify.ready((err) => {
/* c8 ignore next */
if (err) throw err
fastify.log.debug(
`${fastify.name} (${fastify.app.version}) ready. pwd: ${fastify.root}`
)
// re-read routes for OpenAPI docs
fastify.swagger()
})
/**
* add some custom headers
*/
fastify.addHook('onSend', async (request, reply, payload) => {
reply.header('X-Request-ID', request.id)
reply.header('x-Powered-By', `${fastify.name} ${fastify.version}`)
// helmet changed defaults, @see https://github.com/helmetjs/helmet/issues/230
reply.header('X-XSS-Protection', '1; mode=block')
return payload
})
next()
})