-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
207 lines (180 loc) · 4.69 KB
/
Copy pathindex.js
File metadata and controls
207 lines (180 loc) · 4.69 KB
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
import fs from 'node:fs'
import path from 'node:path'
import autoload from '@fastify/autoload'
import helmet from '@fastify/helmet'
import sensible from '@fastify/sensible'
import swagger from '@fastify/swagger'
import underPressure from '@fastify/under-pressure'
import ScalarApiReference from '@scalar/fastify-api-reference'
import assign from 'assign-deep'
import fp from 'fastify-plugin'
import hyperid from 'hyperid'
import { readPackageUpSync } from 'read-package-up'
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
/**
* set logger name by config or package information
*/
const loggerName = config.logger?.name || `${name}@v${version}`
const opts = {
forceCloseConnections: true,
trustProxy,
genReqId: instance,
logger: {
level: logLevel,
name: loggerName,
transport: {
target: '@fastify/one-line-logger',
options: { colorize: true }
}
}
}
return ajv ? { ...opts, ajv } : opts
}
export default fp(async (fastify, opts) => {
/**
* 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 {
scalar: scalarConfig,
openapi: openapiConfig,
...swaggerConfig
} = config.swagger
fastify.register(swagger, {
...swaggerConfig,
openapi: {
// customizable
...openapiConfig,
// default infos from package.json
info: {
title: pkg.name,
description: pkg.description,
version: pkg.version,
// but customizable
...openapiConfig.info
}
}
})
/**
* add Scalar Client (if enabled)
*/
if (swaggerConfig.exposeRoute) {
await fastify.register(ScalarApiReference, {
...swaggerConfig,
configuration: scalarConfig
})
}
/**
* 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.app.version}`)
// helmet changed defaults, @see https://github.com/helmetjs/helmet/issues/230
reply.header('X-XSS-Protection', '1; mode=block')
return payload
})
})