(ctx: CordisContext, public config: ReturnType<typeof WebService.Config>)
| 386 | ConnectionHandler = ConnectionHandler; |
| 387 | |
| 388 | constructor(ctx: CordisContext, public config: ReturnType<typeof WebService.Config>) { |
| 389 | super(ctx, 'server'); |
| 390 | ctx.mixin('server', ['Route', 'Connection', 'withHandlerClass']); |
| 391 | this.server.keys = this.config.keys; |
| 392 | this.server.proxy = this.config.proxy; |
| 393 | const corsAllowHeaders = 'x-requested-with, accept, origin, content-type, upgrade-insecure-requests'; |
| 394 | this.server.use(Compress()); |
| 395 | this.server.use(async (c, next) => { |
| 396 | if ((c.request.headers.origin || c.request.headers.referer) && this.config.cors) { |
| 397 | try { |
| 398 | const host = new URL(c.request.headers.origin || c.request.headers.referer).host; |
| 399 | if (host !== c.request.headers.host && `,${this.config.cors},`.includes(`,${host},`)) { |
| 400 | c.set('Access-Control-Allow-Credentials', 'true'); |
| 401 | c.set('Access-Control-Allow-Headers', corsAllowHeaders); |
| 402 | if (c.request.headers.origin) { |
| 403 | c.set('Access-Control-Allow-Origin', c.request.headers.origin); |
| 404 | c.set('Vary', 'Origin'); |
| 405 | } else { |
| 406 | c.set('Vary', 'Referer'); |
| 407 | } |
| 408 | c.cors = true; |
| 409 | } |
| 410 | } catch (e) { |
| 411 | // invalid origin header, ignore |
| 412 | } |
| 413 | } |
| 414 | if (c.request.method.toLowerCase() === 'options') { |
| 415 | c.body = 'ok'; |
| 416 | return null; |
| 417 | } |
| 418 | for (const key in this.captureAllRoutes) { |
| 419 | if (c.path.startsWith(key)) return this.captureAllRoutes[key](c, next); |
| 420 | } |
| 421 | return await next(); |
| 422 | }); |
| 423 | if (process.env.DEV) { |
| 424 | this.server.use(async (c: Koa.Context, next: Function) => { |
| 425 | const startTime = Date.now(); |
| 426 | try { |
| 427 | await next(); |
| 428 | } finally { |
| 429 | const endTime = Date.now(); |
| 430 | if (!c.nolog && !c.response.headers.nolog) { |
| 431 | logger.debug(`${c.request.method} /${c.domainId || 'system'}${c.request.path} \ |
| 432 | ${c.response.status} ${endTime - startTime}ms ${c.response.length}`); |
| 433 | } |
| 434 | } |
| 435 | }); |
| 436 | } |
| 437 | if (this.config.upload) { |
| 438 | const uploadDir = join(tmpdir(), 'hydro', 'upload', process.env.NODE_APP_INSTANCE || '0'); |
| 439 | fs.ensureDirSync(uploadDir); |
| 440 | logger.debug('Using upload dir: %s', uploadDir); |
| 441 | this.server.use(Body({ |
| 442 | multipart: true, |
| 443 | jsonLimit: '8mb', |
| 444 | formLimit: '8mb', |
| 445 | formidable: { |
nothing calls this directly
no test coverage detected