use got instead of axios, some cleanup, problem with async context being lost for...
[websub-hub] / src / service.js
1 'use strict';
2
3 /**
4 * Here we extend the base API server to define our routes and any route-specific
5 * behavior (middlewares) before handing off to the manager.
6 */
7
8 const { Dingus } = require('@squeep/api-dingus');
9 const common = require('./common');
10 const Enum = require('./enum');
11 const Manager = require('./manager');
12 const { Authenticator, SessionManager } = require('@squeep/authentication-module');
13 const path = require('path');
14
15 const _fileScope = common.fileScope(__filename);
16
17 class Service extends Dingus {
18 constructor(logger, db, options, asyncLocalStorage) {
19 super(logger, {
20 ...options.dingus,
21 ignoreTrailingSlash: false,
22 });
23 this.asyncLocalStorage = asyncLocalStorage;
24 this.manager = new Manager(logger, db, options);
25 this.authenticator = new Authenticator(logger, db, options);
26 this.sessionManager = new SessionManager(logger, this.authenticator, options);
27 this.staticPath = path.join(__dirname, '..', 'static');
28 this.loginPath = `${options.dingus.proxyPrefix}/admin/login`;
29
30 // Primary API endpoint
31 this.on('POST', '/', this.handlerPostRoot.bind(this));
32
33 // Information page about service
34 this.on(['GET', 'HEAD'], '/', this.handlerGetRoot.bind(this));
35
36 // Give load-balancers something to check
37 this.on(['GET', 'HEAD'], '/healthcheck', this.handlerGetHealthcheck.bind(this));
38
39 // Public information about topics
40 this.on('GET', '/info', this.handlerGetInfo.bind(this));
41 this.on('GET', '/info/', this.handlerGetInfo.bind(this));
42
43 // These routes are intended for accessing static content during development.
44 // In production, a proxy server would likely handle these first.
45 this.on(['GET', 'HEAD'], '/static', this.handlerRedirect.bind(this), `${options.dingus.proxyPrefix}/static/`);
46 this.on(['GET', 'HEAD'], '/static/', this.handlerGetStaticFile.bind(this), 'index.html');
47 this.on(['GET', 'HEAD'], '/static/:file', this.handlerGetStaticFile.bind(this));
48 this.on(['GET', 'HEAD'], '/favicon.ico', this.handlerGetStaticFile.bind(this), 'favicon.ico');
49 this.on(['GET', 'HEAD'], '/robots.txt', this.handlerGetStaticFile.bind(this), 'robots.txt');
50
51 // Private informational endpoints
52 this.on(['GET', 'HEAD'], '/admin', this.handlerRedirect.bind(this), `${options.dingus.proxyPrefix}/admin/`);
53 this.on(['GET', 'HEAD'], '/admin/', this.handlerGetAdminOverview.bind(this));
54 this.on(['GET', 'HEAD'], '/admin/topic/:topicId', this.handlerGetAdminTopicDetails.bind(this));
55 this.on(['GET', 'HEAD'], '/admin/topic/:topicId/history.svg', this.handlerGetHistorySVG.bind(this));
56
57 // Private data-editing endpoints
58 this.on(['PATCH', 'DELETE'], '/admin/topic/:topicId', this.handlerUpdateTopic.bind(this));
59 this.on(['PATCH', 'DELETE'], '/admin/subscription/:subscriptionId', this.handlerUpdateSubscription.bind(this));
60
61 // Private server-action endpoints
62 this.on('POST', '/admin/process', this.handlerPostAdminProcess.bind(this));
63
64 // Admin login
65 this.on(['GET', 'HEAD'], '/admin/login', this.handlerGetAdminLogin.bind(this));
66 this.on(['POST'], '/admin/login', this.handlerPostAdminLogin.bind(this));
67 this.on(['GET'], '/admin/logout', this.handlerGetAdminLogout.bind(this));
68 this.on(['GET'], '/admin/_ia', this.handlerGetAdminIA.bind(this));
69
70 }
71
72
73 /**
74 * Rearrange logging data.
75 * @param {http.ClientRequest} req
76 * @param {http.ServerResponse} res
77 * @param {Object} ctx
78 */
79 async preHandler(req, res, ctx) {
80 await super.preHandler(req, res, ctx);
81 const logObject = this.asyncLocalStorage.getStore();
82 // FIXME: for some reason, returning from the super.preHandler loses async context?
83 // Workaround until cause and solution are found.
84 if (logObject) {
85 logObject.requestId = ctx.requestId;
86 delete ctx.requestId;
87 }
88 }
89
90
91 /**
92 * @param {http.ClientRequest} req
93 * @param {http.ServerResponse} res
94 * @param {Object} ctx
95 */
96 async handlerPostRoot(req, res, ctx) {
97 const _scope = _fileScope('handlerPostRoot');
98 this.logger.debug(_scope, 'called', { req, ctx });
99
100 this.setResponseType(this.responseTypes, req, res, ctx);
101 await this.ingestBody(req, res, ctx);
102
103 await this.manager.postRoot(req, res, ctx);
104 }
105
106
107 /**
108 * @param {http.ClientRequest} req
109 * @param {http.ServerResponse} res
110 * @param {Object} ctx
111 */
112 async handlerGetRoot(req, res, ctx) {
113 const _scope = _fileScope('handlerGetRoot');
114 const responseTypes = [
115 Enum.ContentType.TextHTML,
116 ];
117 this.logger.debug(_scope, 'called', { req, ctx });
118
119 Dingus.setHeadHandler(req, res, ctx);
120
121 this.setResponseType(responseTypes, req, res, ctx);
122
123 await this.authenticator.sessionOptional(req, res, ctx, this.loginPath);
124
125 await this.manager.getRoot(req, res, ctx);
126 }
127
128
129 /**
130 * @param {http.ClientRequest} req
131 * @param {http.ServerResponse} res
132 * @param {Object} ctx
133 */
134 async handlerGetHealthcheck(req, res, ctx) {
135 const _scope = _fileScope('handlerGetHealthcheck');
136 this.logger.debug(_scope, 'called', { req, ctx });
137
138 Dingus.setHeadHandler(req, res, ctx);
139
140 this.setResponseType(this.responseTypes, req, res, ctx);
141
142 await this.manager.getHealthcheck(res, ctx);
143 }
144
145
146 /**
147 * @param {http.ClientRequest} req
148 * @param {http.ServerResponse} res
149 * @param {Object} ctx
150 */
151 async handlerGetInfo(req, res, ctx) {
152 const _scope = _fileScope('handlerGetInfo');
153 this.logger.debug(_scope, 'called', { req, ctx });
154
155 const responseTypes = [...this.responseTypes, Enum.ContentType.ImageSVG];
156
157 Dingus.setHeadHandler(req, res, ctx);
158
159 this.setResponseType(responseTypes, req, res, ctx);
160
161 await this.manager.getInfo(res, ctx);
162 }
163
164
165 async handlerGetHistorySVG(req, res, ctx) {
166 const _scope = _fileScope('handlerGetHist');
167 this.logger.debug(_scope, 'called', { req, ctx });
168
169 const responseTypes = [Enum.ContentType.ImageSVG];
170
171 Dingus.setHeadHandler(req, res, ctx);
172
173 this.setResponseType(responseTypes, req, res, ctx);
174
175 await this.manager.getHistorySVG(res, ctx);
176 }
177
178
179 /**
180 * @param {http.ClientRequest} req
181 * @param {http.ServerResponse} res
182 * @param {Object} ctx
183 */
184 async handlerGetAdminOverview(req, res, ctx) {
185 const _scope = _fileScope('handlerGetAdminOverview');
186 this.logger.debug(_scope, 'called', { req, ctx });
187
188 Dingus.setHeadHandler(req, res, ctx);
189
190 this.setResponseType(this.responseTypes, req, res, ctx);
191
192 if (await this.authenticator.sessionRequired(req, res, ctx, this.loginPath)) {
193 await this.manager.getAdminOverview(res, ctx);
194 }
195 }
196
197
198 /**
199 * @param {http.ClientRequest} req
200 * @param {http.ServerResponse} res
201 * @param {Object} ctx
202 */
203 async handlerGetAdminTopicDetails(req, res, ctx) {
204 const _scope = _fileScope('handlerGetAdminTopicDetails');
205 this.logger.debug(_scope, 'called', { req, ctx });
206
207 Dingus.setHeadHandler(req, res, ctx);
208
209 this.setResponseType(this.responseTypes, req, res, ctx);
210
211 if (await this.authenticator.sessionRequired(req, res, ctx, this.loginPath)) {
212 await this.manager.getTopicDetails(res, ctx);
213 }
214 }
215
216
217 /**
218 * If no body was sent, do not parse (and thus avoid possible unsupported media type error).
219 * @param {http.ClientRequest} req
220 * @param {http.ServerResponse} res
221 * @param {Object} ctx
222 */
223 async maybeIngestBody(req, res, ctx) {
224 return super.ingestBody(req, res, ctx, {
225 parseEmptyBody: false,
226 });
227 }
228
229
230 /**
231 * @param {http.ClientRequest} req
232 * @param {http.ServerResponse} res
233 * @param {Object} ctx
234 */
235 async handlerUpdateTopic(req, res, ctx) {
236 const _scope = _fileScope('handlerUpdateTopic');
237 this.logger.debug(_scope, 'called', { req, ctx });
238
239 this.setResponseType(this.responseTypes, req, res, ctx);
240
241 await this.authenticator.apiRequiredLocal(req, res, ctx);
242
243 await this.maybeIngestBody(req, res, ctx);
244 ctx.method = req.method;
245 await this.manager.updateTopic(res, ctx);
246 }
247
248
249 /**
250 * @param {http.ClientRequest} req
251 * @param {http.ServerResponse} res
252 * @param {Object} ctx
253 */
254 async handlerUpdateSubscription(req, res, ctx) {
255 const _scope = _fileScope('handlerUpdateSubscription');
256 this.logger.debug(_scope, 'called', { req, ctx });
257
258 this.setResponseType(this.responseTypes, req, res, ctx);
259
260 await this.authenticator.apiRequiredLocal(req, res, ctx);
261
262 await this.maybeIngestBody(req, res, ctx);
263 ctx.method = req.method;
264 await this.manager.updateSubscription(res, ctx);
265 }
266
267
268 /**
269 * @param {http.ClientRequest} req
270 * @param {http.ServerResponse} res
271 * @param {Object} ctx
272 */
273 async handlerPostAdminProcess(req, res, ctx) {
274 const _scope = _fileScope('handlerPostAdminProcess');
275 this.logger.debug(_scope, 'called', { req, ctx });
276
277 this.setResponseType(this.responseTypes, req, res, ctx);
278
279 await this.authenticator.apiRequiredLocal(req, res, ctx);
280
281 await this.manager.processTasks(res, ctx);
282 }
283
284
285 /**
286 * Delegate login to authentication module.
287 * @param {http.ClientRequest} req
288 * @param {http.ServerResponse} res
289 * @param {Object} ctx
290 */
291 async handlerGetAdminLogin(req, res, ctx) {
292 const _scope = _fileScope('handlerGetAdminLogin');
293 this.logger.debug(_scope, 'called', { req, ctx });
294
295 Dingus.setHeadHandler(req, res, ctx);
296
297 this.setResponseType(this.responseTypes, req, res, ctx);
298
299 await this.sessionManager.getAdminLogin(res, ctx);
300 }
301
302
303 /**
304 * Delegate login to authentication module.
305 * @param {http.ClientRequest} req
306 * @param {http.ServerResponse} res
307 * @param {Object} ctx
308 */
309 async handlerPostAdminLogin(req, res, ctx) {
310 const _scope = _fileScope('handlerPostAdminLogin');
311 this.logger.debug(_scope, 'called', { req, ctx });
312
313 this.setResponseType(this.responseTypes, req, res, ctx);
314
315 await this.authenticator.sessionOptionalLocal(req, res, ctx);
316
317 await this.maybeIngestBody(req, res, ctx);
318
319 await this.sessionManager.postAdminLogin(res, ctx);
320 }
321
322
323 /**
324 * Delegate login to authentication module.
325 * @param {http.ClientRequest} req
326 * @param {http.ServerResponse} res
327 * @param {Object} ctx
328 */
329 async handlerGetAdminLogout(req, res, ctx) {
330 const _scope = _fileScope('handlerGetAdminLogout');
331 this.logger.debug(_scope, 'called', { req, ctx });
332
333 this.setResponseType(this.responseTypes, req, res, ctx);
334
335 await this.authenticator.sessionOptionalLocal(req, res, ctx);
336
337 await this.sessionManager.getAdminLogout(res, ctx);
338 }
339
340
341 /**
342 * Delegate login to authentication module.
343 * @param {http.ClientRequest} req
344 * @param {http.ServerResponse} res
345 * @param {Object} ctx
346 */
347 async handlerGetAdminIA(req, res, ctx) {
348 const _scope = _fileScope('handlerGetAdminIA');
349 this.logger.debug(_scope, 'called', { req, ctx });
350
351 this.setResponseType(this.responseTypes, req, res, ctx);
352
353 // Special case here, to see cookie before session established
354 ctx.cookie = req.getHeader(Enum.Header.Cookie);
355
356 await this.sessionManager.getAdminIA(res, ctx);
357 }
358
359 }
360
361 module.exports = Service;