-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathexpress.ts
More file actions
820 lines (720 loc) · 26.1 KB
/
Copy pathexpress.ts
File metadata and controls
820 lines (720 loc) · 26.1 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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
import path from 'path';
import fs from 'fs';
import { Express } from 'express';
import type { AnySchemaObject } from 'ajv';
import { apiReference } from '@scalar/express-api-reference';
import fetch from 'node-fetch';
import {
AdminUserAuthorizeFunction,
IAdminForth,
IAdminForthAuthenticatedEndpointOptions,
IAdminForthEndpointOptions,
IAdminForthExpressRouteSchema,
IAdminForthNoAuthEndpointOptions,
IExpressHttpServer,
HttpExtra,
} from '../types/Back.js';
import { WebSocketServer } from 'ws';
import { WebSocketClient } from './common.js';
import { AdminUser } from '../types/Common.js';
import http from 'http';
import type { AddressInfo } from 'net';
import { randomUUID } from 'crypto';
import { listify } from '../modules/utils.js';
import { afLogger } from '../modules/logger.js';
import { ADMINFORTH_CLIENT_ID_HEADER, runWithRequestContext } from '../modules/requestContext.js';
import * as z from 'zod';
import multer from 'multer';
import { createRequire } from 'module';
// express is a peer dependency, so resolve it from the host project at runtime
// instead of a static JSON import (which would hard-link a peer dep at parse time).
const require = createRequire(import.meta.url);
const expressVersion: string = require('express/package.json').version;
const expressMajor = Number(expressVersion.split('.')[0]);
function replaceAtStart(string, substring) {
if (string.startsWith(substring)) {
return string.slice(substring.length);
}
return string;
}
async function proxyTo(url, res) {
const actual = await fetch(url);
actual.headers.forEach((v, n) => res.setHeader(n, v));
actual.body.pipe(res);
}
function parseCookiesString(cookiesString: string): Array<{
key: string,
value: string
}> {
const parts = cookiesString.split('; ');
const result = [];
parts.forEach(part => {
const [key, value] = part.split('=');
result.push({key, value});
});
return result;
}
function getHeaderString(headers: Record<string, any>, name: string): string | undefined {
const value = headers[name];
return typeof value === 'string' ? value : undefined;
}
async function parseExpressCookie(req): Promise<
Array<{
key: string,
value: string
}>
> {
const cookies = req.headers.cookie;
if (!cookies) {
return [];
}
return parseCookiesString(cookies);
}
const EXPRESS_ROUTE_SCHEMA = Symbol('adminforth.express.withSchema');
const EXPRESS_REGEXP_LEADING_SLASH_RE = /^\\\//;
const EXPRESS_REGEXP_OPTIONAL_TRAILING_SLASH_RE = /\\\/\?\(\?=\\\/\|\$\)\$$/;
const EXPRESS_REGEXP_PARAM_CAPTURE_RE = /\(\?:\(\[\^\\\/]\+\?\)\)/g;
const EXPRESS_REGEXP_ESCAPED_SLASH_RE = /\\\//g;
const EXPRESS_REGEXP_TRAILING_DOLLAR_RE = /\$$/;
const EXPRESS_REGEXP_LEADING_CARET_RE = /^\^/;
type MulterParser = (req: any, res: any, callback: (error?: unknown) => void) => void;
type RegisteredExpressRouteSchema = IAdminForthExpressRouteSchema & {
request?: AnySchemaObject;
response?: AnySchemaObject;
};
type SchemaAnnotatedHandler = ((...args: any[]) => any) & {
[EXPRESS_ROUTE_SCHEMA]?: RegisteredExpressRouteSchema;
};
type ZodSchemaLike = {
_zod?: unknown;
_def?: unknown;
safeParse?: (...args: any[]) => any;
};
function isZodSchemaLike(schema: unknown): schema is ZodSchemaLike {
return !!schema
&& typeof schema === 'object'
&& 'safeParse' in schema
&& typeof (schema as ZodSchemaLike).safeParse === 'function'
&& ('_zod' in schema || '_def' in schema);
}
function normalizeExpressRuntimeSchema(schema: unknown): AnySchemaObject | undefined {
if (!schema) {
return undefined;
}
if (isZodSchemaLike(schema)) {
return z.toJSONSchema(schema as any, { target: 'draft-07' }) as AnySchemaObject;
}
return schema as AnySchemaObject;
}
function normalizeExpressLayerRegexpSource(regexpSource: string): string {
return regexpSource
.replace(EXPRESS_REGEXP_LEADING_SLASH_RE, '/')
.replace(EXPRESS_REGEXP_OPTIONAL_TRAILING_SLASH_RE, '')
.replace(EXPRESS_REGEXP_PARAM_CAPTURE_RE, ':param')
.replace(EXPRESS_REGEXP_ESCAPED_SLASH_RE, '/')
.replace(EXPRESS_REGEXP_TRAILING_DOLLAR_RE, '')
.replace(EXPRESS_REGEXP_LEADING_CARET_RE, '');
}
const respondNoServer = (title, explanation) => {
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AdminForth</title>
</head>
<body>
<div class="center">
<h1>Oops!</h1>
<h2>${title}</h2>
<p>${explanation}</p>
</div>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 0;
}
.center {
display: flex;
justify-content: center;
align-items: center;
height: 100dvh;
flex-direction: column;
}
</style>
<script>
setTimeout(() => {
location.reload();
}, 1500);
</script>
</body>
`;
}
class ExpressServer implements IExpressHttpServer {
expressApp: Express;
adminforth: IAdminForth;
server: http.Server;
schemaAwareRouteRegistrationPatched = false;
uploadParser: MulterParser;
pendingEndpointRegistrations: Array<() => void> = [];
constructor(adminforth: IAdminForth) {
this.adminforth = adminforth;
this.uploadParser = multer({
storage: multer.memoryStorage(),
}).any();
}
setupSpaServer() {
const prefix = this.adminforth.config.baseUrl
const slashedPrefix = prefix.endsWith('/') ? prefix : `${prefix}/`;
// Express 5 (path-to-regexp v8) requires named wildcards instead of a bare `*`.
// `{*splat}` is an optional catch-all so the SPA route also matches the base path itself
// (e.g. `/admin` as well as `/admin/...`; `/` as well as `/foo` when baseUrl is empty).
let assetsRoute = `${slashedPrefix}assets/*splat`;
let spaCatchAll = prefix ? `${prefix}{*splat}` : '/{*splat}';
if (expressMajor === 4) {
assetsRoute = `${slashedPrefix}assets/*`;
spaCatchAll = `${prefix}*`;
}
if (this.adminforth.runningHotReload) {
const handler = async (req, res) => {
// proxy using fetch to webpack dev server
try {
if (this.adminforth.codeInjector.devServerPort === null) {
throw new Error('Dev server port is not set');
}
await proxyTo(`http://localhost:${this.adminforth.codeInjector.devServerPort}${req.url}`, res);
} catch (e) {
res.status(500).send(respondNoServer('AdminForth SPA is not ready yet', 'Vite is still starting up. Please wait a moment...'));
return;
}
}
this.expressApp.get(assetsRoute, handler);
afLogger.trace(`®️ Registering SPA serve handler', ${assetsRoute}`);
this.expressApp.get(spaCatchAll, handler);
} else {
const codeInjector = this.adminforth.codeInjector;
this.expressApp.get(assetsRoute, (req, res) => {
if (req.url?.includes('..')) {
res.status(400).send('Invalid path');
return;
}
const fullPath = path.join(codeInjector.getServeDir(), replaceAtStart(req.url, prefix));
res.sendFile(
fullPath,
{
cacheControl: false,
dotfiles: 'allow',
// store for a year
headers: {
'Cache-Control': 'public, max-age=31536000',
'Pragma': 'public',
}
}
, (err) => {
if (err && err.message.includes('ENOENT')) {
res.status(404).send('Not found');
}
});
})
this.expressApp.get(spaCatchAll, async (req, res) => {
const fullPath = path.join(codeInjector.getServeDir(), 'index.html');
let fileExists = true;
try {
await fs.promises.access(fullPath, fs.constants.F_OK);
} catch (e) {
fileExists = false;
}
if (!fileExists) {
res.status(500).send(respondNoServer(`${this.adminforth.config.customization.brandName} is still warming up`, 'Please wait a moment...'));
return;
}
res.sendFile(fullPath, {
dotfiles: 'allow',
cacheControl: false,
headers: {
'Content-Type': 'text/html',
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
} });
});
}
}
setupWsServer() {
let base = this.adminforth.config.baseUrl || '';
if (base.endsWith('/')) {
base = base.slice(0, -1);
}
this.server = http.createServer(this.expressApp);
const wss = new WebSocketServer({ server: this.server, path: `${base}/afws` });
afLogger.info(`${this.adminforth.formatAdminForth()} 🚂 Using express v${expressVersion}`);
afLogger.info(`${this.adminforth.formatAdminForth()} 🌐 WebSocket server started`);
// Handle WebSocket connections
wss.on('connection', async (ws, req) => {
try {
// get cookies and parse
let adminUser: AdminUser | null = null;
const cookies = req.headers.cookie;
if (cookies) {
const parsedCookies = parseCookiesString(cookies);
// find adminforth_jwt
const brandSlug = this.adminforth.config.customization.brandNameSlug;
const jwt = parsedCookies.find(({key}) => key === `adminforth_${brandSlug}_jwt`);
if (jwt) {
adminUser = await this.adminforth.auth.verify(jwt.value, 'auth');
}
}
this.adminforth.websocket.registerWsClient(
new WebSocketClient({
id: randomUUID(),
clientId: typeof req.url === 'string' ? new URL(req.url, 'http://localhost').searchParams.get('clientId') || undefined : undefined,
adminUser,
send: (data) => ws.send(data),
close: () => ws.close(),
onMessage: (handler) => ws.on('message', handler),
onClose: (handler) => ws.on('close', handler),
})
);
} catch (e) {
afLogger.error(`Failed to handle WS connection ${e}`);
}
});
}
serve(app) {
this.expressApp = app;
this.expressApp.use((req, res, next) => {
runWithRequestContext({
websocketClientId: getHeaderString(req.headers, ADMINFORTH_CLIENT_ID_HEADER),
}, next);
});
this.patchSchemaAwareRouteRegistration();
this.flushPendingEndpointRegistrations();
// Express 5 exposes the router as `app.router`; Express 4 used the internal `app._router`.
const stack = ((this.expressApp as any)?._router ?? (this.expressApp as any)?.router)?.stack;
if (Array.isArray(stack)) {
this.registerSchemaAwareStack(stack, '');
}
this.setupWsServer();
this.adminforth.setupEndpoints(this);
this.setupOpenApiRoutes();
this.setupSpaServer();
}
flushPendingEndpointRegistrations() {
this.pendingEndpointRegistrations.splice(0).forEach((registerEndpoint) => {
registerEndpoint();
});
}
listen(...args) {
this.server.listen(...args);
}
getInternalApiOrigin(): string | undefined {
const address = this.server?.address();
if (!address || typeof address === 'string') {
return undefined;
}
return `http://127.0.0.1:${(address as AddressInfo).port}`;
}
async processAuthorizeCallbacks(adminUser: AdminUser, toReturn: { error?: string, allowed: boolean }, response: Response, extra: HttpExtra) {
const adminUserAuthorize = this.adminforth.config.auth.adminUserAuthorize as (AdminUserAuthorizeFunction[] | undefined);
for (const hook of listify(adminUserAuthorize)) {
const resp = await hook({
adminUser,
response,
adminforth: this.adminforth,
extra,
});
if (resp?.allowed === false || resp?.error) {
// delete all items from toReturn and add these:
toReturn.allowed = resp?.allowed;
toReturn.error = resp?.error;
break;
}
}
}
runInRequestContext(req, callback) {
return runWithRequestContext({
websocketClientId: getHeaderString(req.headers, ADMINFORTH_CLIENT_ID_HEADER),
}, callback);
}
authorize(handler) {
return async (req, res, next) => {
return this.runInRequestContext(req, async () => {
const cookies = await parseExpressCookie(req);
const brandSlug = this.adminforth.config.customization.brandNameSlug;
// check if multiple adminforth_jwt providerd and show warning
const jwts = cookies.filter(({key}) => key === `adminforth_${brandSlug}_jwt`);
if (jwts.length > 1) {
afLogger.error('Multiple adminforth_jwt cookies provided');
}
const jwt = jwts[0]?.value;
if (!jwt) {
res.status(401).send('Unauthorized by AdminForth');
return
}
let adminforthUser;
try {
adminforthUser = await this.adminforth.auth.verify(jwt, 'auth');
} catch (e) {
// this might happen if e.g. database intialization in progress.
// so we can't answer with 401 (would logout user)
// reproduced during usage of listRowsAutoRefreshSeconds
afLogger.error(e.stack);
res.status(500).send('Failed to verify JWT token - something went wrong');
return;
}
if (!adminforthUser) {
res.status(401).send('Unauthorized by AdminForth');
} else {
req.adminUser = adminforthUser;
const toReturn: { error?: string, allowed: boolean } = { allowed: true };
await this.processAuthorizeCallbacks(adminforthUser, toReturn, res, {
body: req.body,
query: req.query,
headers: req.headers,
cookies: cookies as any,
requestUrl: req.url,
meta: {},
response: res
});
if (!toReturn.allowed) {
res.status(401).send('Unauthorized by AdminForth');
} else {
return handler(req, res, next);
}
}
});
};
}
withSchema(schema, handler) {
const wrapped = ((...args: any[]) => handler(...args)) as SchemaAnnotatedHandler;
wrapped[EXPRESS_ROUTE_SCHEMA] = {
...schema,
request: normalizeExpressRuntimeSchema(schema.request),
response: normalizeExpressRuntimeSchema(schema.response),
};
return wrapped;
}
translatable(handler) {
// same as authorize, but injects tr function into request
return async (req, res, next) => {
const tr = (msg: string, category: string, params: any, pluralizationNumber?: number): Promise<string> => this.adminforth.tr(msg, category, req.headers['accept-language'], params, pluralizationNumber);
req.tr = tr;
return handler(req, res, next);
}
}
patchSchemaAwareRouteRegistration() {
if (this.schemaAwareRouteRegistrationPatched) {
return;
}
const methods = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options'];
methods.forEach((method) => {
const original = this.expressApp[method]?.bind(this.expressApp);
if (!original) {
return;
}
this.expressApp[method] = ((path, ...handlers) => {
this.registerSchemaAwareRoute([method], path, handlers);
return original(path, ...handlers);
}) as any;
});
const originalUse = this.expressApp.use?.bind(this.expressApp);
if (originalUse) {
this.expressApp.use = ((...args) => {
const [firstArg, ...restArgs] = args;
const path = typeof firstArg === 'string' || Array.isArray(firstArg)
? firstArg
: '';
const handlers = path ? restArgs : args;
this.flattenHandlers(handlers).forEach((handler) => {
if (Array.isArray((handler as any)?.stack)) {
this.registerSchemaAwareStack((handler as any).stack, path);
}
});
return originalUse(...args);
}) as any;
}
this.schemaAwareRouteRegistrationPatched = true;
}
registerSchemaAwareRoute(methods, path, handlers) {
const flatHandlers = this.flattenHandlers(handlers);
const schema = flatHandlers.find((handler) => (handler as SchemaAnnotatedHandler)?.[EXPRESS_ROUTE_SCHEMA])?.[EXPRESS_ROUTE_SCHEMA];
if (!schema || (!schema.request && !schema.response)) {
return;
}
const normalizedMethods = methods.filter((method, index, allMethods) => {
if (!method || method === '_all') {
return false;
}
if (method === 'head' && allMethods.includes('get')) {
return false;
}
return allMethods.indexOf(method) === index;
});
const routePaths = Array.isArray(path) ? path : [path];
routePaths.forEach((routePath) => {
if (typeof routePath !== 'string') {
return;
}
normalizedMethods.forEach((method) => {
this.adminforth.openApi.registerApiSchema({
method: method.toUpperCase(),
path: routePath,
description: schema.description,
agent: schema.agent,
request_schema: schema.request,
response_schema: schema.response,
meta: schema.meta,
handler: undefined as never,
});
});
});
}
registerSchemaAwareStack(stack, prefix) {
const prefixes = this.flattenPaths(prefix);
stack.forEach((layer) => {
if (layer.route) {
const methods = Object.keys(layer.route.methods || {}).filter((method) => layer.route.methods[method]);
const handlers = (layer.route.stack || []).map((routeLayer) => routeLayer.handle);
this.registerSchemaAwareRoute(methods, this.combineRoutePaths(prefixes, layer.route.path), handlers);
return;
}
const nestedStack = layer.handle?.stack;
if (!Array.isArray(nestedStack)) {
return;
}
const layerPath = this.extractLayerPath(layer);
const nestedPrefix = this.combineRoutePaths(prefixes, layerPath);
this.registerSchemaAwareStack(nestedStack, nestedPrefix);
});
}
combineRoutePaths(prefixes, paths) {
return prefixes.flatMap((prefix) => this.flattenPaths(paths).map((path) => {
if (!prefix) return path || '/';
if (!path || path === '/') return prefix;
return `${prefix.endsWith('/') ? prefix.slice(0, -1) : prefix}${path.startsWith('/') ? path : `/${path}`}`;
}));
}
extractLayerPath(layer) {
if (typeof layer.path === 'string') {
return layer.path;
}
const regexpSource = layer.regexp?.source;
if (typeof regexpSource !== 'string') {
return '';
}
if (layer.regexp?.fast_slash) {
return '';
}
return normalizeExpressLayerRegexpSource(regexpSource);
}
flattenHandlers(handlers) {
return handlers.flat(Infinity);
}
flattenPaths(paths) {
const flattened = (Array.isArray(paths) ? paths : [paths]).flat(Infinity);
const stringPaths = flattened.filter((path): path is string => typeof path === 'string');
return stringPaths.length ? stringPaths : [''];
}
setupOpenApiRoutes() {
let base = this.adminforth.config.baseUrl || '';
if (base.endsWith('/')) {
base = base.slice(0, -1);
}
const openApiJsonPath = `${base}/api/v1/openapi.json`;
this.expressApp.get(openApiJsonPath, (req, res) => {
res.json(this.adminforth.openApi.renderOpenApiDocument());
});
this.expressApp.use(`${base}/api-docs`, apiReference({
url: openApiJsonPath,
theme: 'saturn',
}));
}
endpoint(options: IAdminForthAuthenticatedEndpointOptions): void;
endpoint(options: IAdminForthNoAuthEndpointOptions): void;
endpoint(options: IAdminForthEndpointOptions) {
const {
method='GET',
path,
handler,
noAuth=false,
description,
request_schema,
response_schema,
agent,
target='json'
} = options;
if (!path.startsWith('/')) {
throw new Error(`Path must start with /, got: ${path}`);
}
const fullPath = `${this.adminforth.config.baseUrl}/adminapi/v1${path}`;
const normalizedRequestSchema = normalizeExpressRuntimeSchema(request_schema);
const normalizedResponseSchema = normalizeExpressRuntimeSchema(response_schema);
const registeredApiSchema = (normalizedRequestSchema || normalizedResponseSchema)
? this.adminforth.openApi.registerApiSchema({
method,
noAuth,
path: fullPath,
description,
request_schema: normalizedRequestSchema,
response_schema: normalizedResponseSchema,
agent,
handler,
})
: null;
const expressHandler = async (req, res) => this.runInRequestContext(req, async () => {
const abortController = new AbortController();
res.on('close', () => {
if(req.destroyed) {
abortController.abort();
}
});
// Enforce JSON-only for mutation HTTP methods
// AdminForth API endpoints accept only application/json for POST, PUT, PATCH, DELETE
// If you need other content types, use a custom server endpoint.
const method = (req.method || '').toUpperCase();
const contentTypeHeader = (req.headers?.['content-type'] || '').toString();
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
const expectedContentType = target === 'upload' ? 'multipart/form-data' : 'application/json';
const hasExpectedContentType = contentTypeHeader.toLowerCase().startsWith(expectedContentType);
if (!hasExpectedContentType) {
const passed = contentTypeHeader || 'undefined';
res.status(415).send(`AdminForth API endpoint supports only requests with Content-Type: ${expectedContentType}, when you passed: ${passed}. Please use custom server endpoint if you really need this content type`);
return;
}
}
if (target === 'upload') {
try {
await new Promise<void>((resolve, reject) => {
this.uploadParser(req, res, (error?: unknown) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
if (!(req as any).file && Array.isArray((req as any).files) && (req as any).files.length) {
(req as any).file = (req as any).files[0];
}
} catch (error) {
afLogger.error(`Failed to parse multipart form-data body, ${error}`);
res.status(400).send('Invalid multipart/form-data body');
return;
}
}
let body = req.body || {};
if (typeof body === 'string' && target === 'json') {
try {
body = JSON.parse(body);
} catch (e) {
afLogger.error(`Failed to parse body, ${e}`);
res.status(400).send('Invalid JSON body');
return;
}
}
const requestValidation = this.adminforth.openApi.validateRequestSchema(registeredApiSchema, body);
if (!requestValidation.valid) {
res.status(400).json({
error: 'Request body validation failed',
details: requestValidation.errors,
});
return;
}
const query = req.query;
const adminUser = req.adminUser;
// lower request headers
const headers = req.headers;
const cookies = await parseExpressCookie(req);
const response = {
headers: [],
status: 200,
message: undefined,
setHeader(name, value) {
afLogger.trace(`🪲Setting header, ${name}, ${value}`);
this.headers.push([name, value]);
},
setStatus(code, message) {
this.status = code;
this.message = message;
},
blobStream() {
return res;
}
};
const requestUrl = req.url;
const acceptLang = headers['accept-language'];
const tr = (msg: string, category: string, params: any, pluralizationNumber?: number): Promise<string> => this.adminforth.tr(msg, category, acceptLang, params, pluralizationNumber);
const input = { body, query, headers, cookies, adminUser, response, requestUrl, _raw_express_req: req, _raw_express_res: res, tr, abortSignal: abortController.signal};
let output;
if (expressMajor === 5) {
output = await handler(input);
} else if (expressMajor === 4) {
// Express 4 does not support async handlers, so we need to wrap it in a try/catch
try {
output = await handler(input);
} catch (e) {
afLogger.error(`Error in handler ${e}`);
afLogger.error(e.stack);
const expressErrorCallback = this.adminforth.config.expressErrorCallback;
if (expressErrorCallback) {
try {
await expressErrorCallback({
error: e,
adminforth: this.adminforth,
extra: {
body,
query,
headers,
cookies: cookies as any,
requestUrl,
meta: {},
response,
},
});
} catch (callbackError) {
afLogger.error(`Error in expressErrorCallback ${callbackError}`);
afLogger.error(callbackError?.stack);
}
}
res.status(500).send('Internal server error');
return;
}
}
response.headers.forEach(([name, value]) => {
res.setHeader(name, value);
});
res.status(response.status);
if (response.message) {
res.send(response.message);
return;
}
if (output === null) {
// nothing should be returned anymore
return;
}
const responseValidation = this.adminforth.openApi.validateResponseSchema(registeredApiSchema, output);
if (!responseValidation.valid) {
res.status(500).json({
error: 'Response validation failed',
details: responseValidation.errors,
});
return;
}
res.json(output);
});
const registerEndpoint = () => {
afLogger.trace(`👂 Adding endpoint ${method} ${fullPath}`);
this.expressApp[method.toLowerCase()](fullPath, noAuth ? expressHandler : this.authorize(expressHandler));
};
if (this.expressApp) {
registerEndpoint();
return;
}
this.pendingEndpointRegistrations.push(registerEndpoint);
}
}
export default ExpressServer;