-
Notifications
You must be signed in to change notification settings - Fork 19
/
server.ts
254 lines (225 loc) · 7.17 KB
/
server.ts
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
import { CaptureConsole } from "@sentry/integrations";
import {
ApolloServer,
makeExecutableSchema,
ApolloError,
UserInputError
} from "apollo-server-express";
import express from "express";
import passport from "passport";
import session from "express-session";
import rateLimit from "express-rate-limit";
import RateLimitRedisStore from "rate-limit-redis";
import redisStore from "connect-redis";
import depthLimit from "graphql-depth-limit";
import bodyParser from "body-parser";
import cors from "cors";
import graphqlBodyParser from "./common/middlewares/graphqlBodyParser";
import { applyMiddleware } from "graphql-middleware";
import { sentry } from "graphql-middleware-sentry";
import { authRouter } from "./routers/auth-router";
import { downloadFileHandler } from "./common/file-download";
import { oauth2Router } from "./routers/oauth2-router";
import { prisma } from "./generated/prisma-client";
import { healthRouter } from "./health";
import { userActivationHandler } from "./users/activation";
import { typeDefs, resolvers } from "./schema";
import { getUIBaseURL } from "./utils";
import { passportBearerMiddleware, passportJwtMiddleware } from "./auth";
import { GraphQLContext } from "./types";
import { ErrorCode } from "./common/errors";
import { redisClient } from "./common/redis";
import loggingMiddleware from "./common/middlewares/loggingMiddleware";
import errorHandler from "./common/middlewares/errorHandler";
const {
SENTRY_DSN,
SESSION_SECRET,
SESSION_COOKIE_HOST,
SESSION_COOKIE_SECURE,
SESSION_NAME,
UI_HOST,
NODE_ENV
} = process.env;
const UI_BASE_URL = getUIBaseURL();
/**
* Custom report error for sentry middleware
* It decides whether or not the error should be captured
*/
export function reportError(res: Error | any) {
const whiteList = [
ErrorCode.GRAPHQL_PARSE_FAILED,
ErrorCode.GRAPHQL_VALIDATION_FAILED,
ErrorCode.BAD_USER_INPUT,
ErrorCode.UNAUTHENTICATED,
ErrorCode.FORBIDDEN
];
if (res.extensions && whiteList.includes(res.extensions.code)) {
return false;
}
return true;
}
/**
* Sentry configuration
* Capture console.error statements
*/
const sentryMiddleware = () =>
sentry<GraphQLContext>({
config: {
dsn: SENTRY_DSN,
environment: NODE_ENV,
integrations: [new CaptureConsole({ levels: ["error"] })]
},
forwardErrors: true,
withScope: (scope, error, context) => {
const reqUser = !!context.user ? context.user.email : "anonymous";
scope.setUser({
email: reqUser
});
scope.setExtra("body", context.req.body);
scope.setExtra("origin", context.req.headers.origin);
scope.setExtra("user-agent", context.req.headers["user-agent"]);
scope.setExtra("ip", context.req.headers["x-real-ip"]);
scope.setTag("service", "api");
},
reportError
});
const schema = makeExecutableSchema({
typeDefs,
resolvers
});
export const schemaWithMiddleware = applyMiddleware(
schema,
...[...(SENTRY_DSN ? [sentryMiddleware()] : [])]
);
// GraphQL endpoint
const graphQLPath = "/";
export const server = new ApolloServer({
schema: schemaWithMiddleware,
introspection: true, // used to enable the playground in production
playground: true, // used to enable the playground in production
validationRules: [depthLimit(10)],
context: async ctx => {
return {
...ctx,
// req.user is made available by passport
user: ctx.req?.user ?? null,
prisma
};
},
formatError: err => {
// Catch Yup `ValidationError` and throw a `UserInputError` instead of an `InternalServerError`
if (err.extensions.exception?.name === "ValidationError") {
return new UserInputError(err.extensions.exception.errors.join("\n"));
}
if (
err.extensions.code === ErrorCode.INTERNAL_SERVER_ERROR &&
NODE_ENV === "production"
) {
// Workaround for graphQL validation error displayed as internal server error
// when graphQL variables are of of invalid type
// See: https://github.com/apollographql/apollo-server/issues/3498
if (err.message && err.message.startsWith(`Variable "`)) {
err.extensions.code = "GRAPHQL_VALIDATION_FAILED";
return err;
}
// Do not leak error for internal server error in production
return new ApolloError("Erreur serveur", ErrorCode.INTERNAL_SERVER_ERROR);
}
return err;
}
});
export const app = express();
const RATE_LIMIT_WINDOW_SECONDS = 60;
const MAX_REQUESTS_PER_WINDOW = 1000;
app.use(
rateLimit({
message: `Quota de ${MAX_REQUESTS_PER_WINDOW} requêtes par minute excédée pour cette adresse IP, merci de réessayer plus tard.`,
windowMs: RATE_LIMIT_WINDOW_SECONDS * 1000,
max: MAX_REQUESTS_PER_WINDOW,
store: new RateLimitRedisStore({
client: redisClient,
expiry: RATE_LIMIT_WINDOW_SECONDS
})
})
);
/**
* parse application/x-www-form-urlencoded
* used when submitting login form
*/
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// allow application/graphql header
app.use(graphqlBodyParser);
// logging middleware
app.use(loggingMiddleware(graphQLPath));
/**
* Set the following headers for cross-domain cookie
* Access-Control-Allow-Credentials: true
* Access-Control-Allow-Origin: $UI_DOMAIN
*/
app.use(
cors({
origin: UI_BASE_URL,
credentials: true
})
);
// configure session for passport local strategy
const RedisStore = redisStore(session);
export const sess = {
store: new RedisStore({ client: redisClient }),
name: SESSION_NAME || "trackdechets.connect.sid",
secret: SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
domain: SESSION_COOKIE_HOST || UI_HOST,
maxAge: 24 * 3600 * 1000
}
};
if (SESSION_COOKIE_SECURE === "true") {
app.set("trust proxy", 1); // trust first proxy
sess.cookie.secure = true; // serve secure cookies
}
app.use(session(sess));
app.use(passport.initialize());
app.use(passport.session());
// Load passport configuration
import("./auth");
// authentification routes used by td-ui (/login /logout, /isAuthenticated)
app.use(authRouter);
app.use(oauth2Router);
app.get("/ping", (_, res) => res.send("Pong!"));
app.get("/userActivation", userActivationHandler);
app.get("/download", downloadFileHandler);
app.use("/health", healthRouter);
// TODO Remove
app.get("/pdf", (_, res) =>
res.status(410).send("Route dépréciée, utilisez la query GraphQL `formPdf`")
);
app.get("/exports", (_, res) =>
res
.status(410)
.send("Route dépréciée, utilisez la query GraphQL `formsRegister`")
);
// Apply passport auth middlewares to the graphQL endpoint
app.use(graphQLPath, passportBearerMiddleware, passportJwtMiddleware);
/**
* Wire up ApolloServer to /
* UI_BASE_URL is explicitly set in the origin list
* to avoid "Credentials is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’"
* See https://developer.mozilla.org/fr/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials
*/
server.applyMiddleware({
app,
cors: {
origin: [UI_BASE_URL, "*"],
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: true
},
path: graphQLPath
});
// error handler
app.use(errorHandler);