forked from effect-app/boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddlewares.ts
More file actions
286 lines (237 loc) · 7.55 KB
/
middlewares.ts
File metadata and controls
286 lines (237 loc) · 7.55 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/**
* Mechanism for extendning behaviour of all handlers on the server.
*
* @since 1.0.0
*/
import * as crypto from "crypto"
import { dropUndefined } from "@effect-app/core/utils"
import { NotLoggedInError } from "@effect-app/infra/errors"
import * as Middleware from "@effect/platform/Http/Middleware"
import * as ServerRequest from "@effect/platform/Http/ServerRequest"
import * as ServerResponse from "@effect/platform/Http/ServerResponse"
import { HttpBody, HttpHeaders, HttpServerResponse } from "api/lib/http"
import { Effect } from "effect-app"
import * as Either from "effect/Either"
import * as FiberRef from "effect/FiberRef"
import { pipe } from "effect/Function"
import * as HashMap from "effect/HashMap"
import * as Metric from "effect/Metric"
import type * as Middlewares from "../Middlewares"
export const accessLog = (level: "Info" | "Warning" | "Debug" = "Info") =>
Middleware.make((app) =>
pipe(
ServerRequest.ServerRequest,
Effect.flatMap((request) => Effect[`log${level}`](`${request.method} ${request.url}`)),
Effect.flatMap(() => app)
)
)
export const uuidLogAnnotation = (logAnnotationKey = "requestId") =>
Middleware.make((app) =>
pipe(
Effect.sync(() => crypto.randomUUID()),
Effect.flatMap((uuid) =>
FiberRef.update(
FiberRef.currentLogAnnotations,
HashMap.set<string, unknown>(logAnnotationKey, uuid)
)
),
Effect.flatMap(() => app)
)
)
export const endpointCallsMetric = () => {
const endpointCalledCounter = Metric.counter("server.endpoint_calls")
return Middleware.make((app) =>
Effect.gen(function*(_) {
const request = yield* _(ServerRequest.ServerRequest)
yield* _(
Metric.increment(endpointCalledCounter),
Effect.tagMetrics("path", request.url)
)
return yield* _(app)
})
)
}
export const errorLog = Middleware.make((app) =>
Effect.gen(function*(_) {
const request = yield* _(ServerRequest.ServerRequest)
const response = yield* _(app)
if (response.status >= 400 && response.status < 500) {
yield* _(
Effect.logWarning(
`${request.method.toUpperCase()} ${request.url} client error ${response.status}`
)
)
} else if (response.status >= 500) {
yield* _(
Effect.logError(
`${request.method.toUpperCase()} ${request.url} server error ${response.status}`
)
)
}
return response
})
)
export const toServerResponse = (err: NotLoggedInError) =>
HttpServerResponse.empty().pipe(
HttpServerResponse.setStatus(401),
HttpServerResponse.setBody(HttpBody.unsafeJson({ message: err.message }))
)
export const basicAuth = <R, _>(
checkCredentials: (
credentials: Middlewares.BasicAuthCredentials
) => Effect<_, NotLoggedInError, R>,
options?: Partial<{
headerName: string
skipPaths: readonly string[]
}>
) =>
Middleware.make((app) =>
Effect.gen(function*(_) {
const headerName = options?.headerName ?? "Authorization"
const skippedPaths = options?.skipPaths ?? []
const request = yield* _(ServerRequest.ServerRequest)
if (skippedPaths.includes(request.url)) {
return yield* _(app)
}
const authHeader = request.headers[headerName.toLowerCase()]
if (authHeader === undefined) {
return toServerResponse(
new NotLoggedInError(
`Expected header ${headerName}`
)
)
}
const authorizationParts = authHeader.split(" ")
if (authorizationParts.length !== 2) {
return toServerResponse(
new NotLoggedInError(
"Incorrect auhorization scheme. Expected \"Basic <credentials>\""
)
)
}
if (authorizationParts[0] !== "Basic") {
return toServerResponse(
new NotLoggedInError(
`Incorrect auhorization type. Expected "Basic", got "${authorizationParts[0]}"`
)
)
}
const credentialsBuffer = Buffer.from(authorizationParts[1]!, "base64")
const credentialsText = credentialsBuffer.toString("utf-8")
const credentialsParts = credentialsText.split(":")
if (credentialsParts.length !== 2) {
return toServerResponse(
new NotLoggedInError(
"Incorrect basic auth credentials format. Expected base64 encoded \"<user>:<pass>\"."
)
)
}
const check = yield* _(
checkCredentials({
user: credentialsParts[0],
password: credentialsParts[1]!
}),
Effect.either
)
if (Either.isLeft(check)) {
return toServerResponse(check.left)
}
return yield* _(app)
})
)
export const cors = (_options?: Partial<Middlewares.CorsOptions>) => {
const DEFAULTS = {
allowedOrigins: ["*"],
allowedMethods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
allowedHeaders: [],
exposedHeaders: [],
credentials: false
} as const
const options = { ...DEFAULTS, ..._options }
const isAllowedOrigin = (origin: string) => {
return options.allowedOrigins.includes(origin)
}
const allowOrigin = (originHeader: string) => {
if (options.allowedOrigins.length === 0) {
return { "Access-Control-Allow-Origin": "*" }
}
if (options.allowedOrigins.length === 1) {
return {
"Access-Control-Allow-Origin": options.allowedOrigins[0],
Vary: "Origin"
}
}
if (isAllowedOrigin(originHeader)) {
return {
"Access-Control-Allow-Origin": originHeader,
Vary: "Origin"
}
}
return undefined
}
const allowMethods = (() => {
if (options.allowedMethods.length > 0) {
return {
"Access-Control-Allow-Methods": options.allowedMethods.join(", ")
}
}
return undefined
})()
const allowCredentials = (() => {
if (options.credentials) {
return { "Access-Control-Allow-Credentials": "true" }
}
return undefined
})()
const allowHeaders = (accessControlRequestHeaders: string | undefined) => {
if (options.allowedHeaders.length === 0 && accessControlRequestHeaders) {
return {
Vary: "Access-Control-Request-Headers",
"Access-Control-Allow-Headers": accessControlRequestHeaders
}
}
if (options.allowedHeaders) {
return {
"Access-Control-Allow-Headers": options.allowedHeaders.join(",")
}
}
return undefined
}
const exposeHeaders = (() => {
if (options.exposedHeaders.length > 0) {
return {
"Access-Control-Expose-Headers": options.exposedHeaders.join(",")
}
}
return undefined
})()
const maxAge = (() => {
if (options.maxAge) {
return { "Access-Control-Max-Age": options.maxAge.toString() }
}
return undefined
})()
return Middleware.make((app) =>
Effect.gen(function*(_) {
const request = yield* _(ServerRequest.ServerRequest)
const origin = request.headers["origin"]
const accessControlRequestHeaders = request.headers["access-control-request-headers"]
let corsHeaders = {
...allowOrigin(origin ?? ""),
...allowCredentials,
...exposeHeaders
}
if (request.method === "OPTIONS") {
corsHeaders = {
...corsHeaders,
...allowMethods,
...allowHeaders(accessControlRequestHeaders),
...maxAge
}
return ServerResponse.empty({ status: 204, headers: HttpHeaders.fromInput(dropUndefined(corsHeaders)) })
}
const response = yield* _(app)
return response.pipe(ServerResponse.setHeaders(dropUndefined(corsHeaders)))
})
)
}