|
| 1 | +import { getLogger } from '../../logging/LoggerUtils'; |
| 2 | +import { HttpHandler } from '../models/HttpHandler'; |
| 3 | +import { HttpHandlerContext } from '../models/HttpHandlerContext'; |
| 4 | +import { HttpHandlerResponse } from '../models/HttpHandlerResponse'; |
| 5 | + |
| 6 | +export const cleanHeaders = (headers: Record<string, string>): Record<string, string> => Object.entries(headers).reduce( |
| 7 | + (acc: Record<string, string>, [ key, value ]) => { |
| 8 | + |
| 9 | + const lKey = key.toLowerCase(); |
| 10 | + |
| 11 | + return { ... acc, [lKey]: acc[lKey] ? `${acc[lKey]},${value}` : value }; |
| 12 | + |
| 13 | + }, {}, |
| 14 | +); |
| 15 | + |
| 16 | +export interface HttpCorsOptions { |
| 17 | + origins?: string[]; |
| 18 | + allowMethods?: string[]; |
| 19 | + allowHeaders?: string[]; |
| 20 | + exposeHeaders?: string[]; |
| 21 | + credentials?: boolean; |
| 22 | + maxAge?: number; |
| 23 | +} |
| 24 | +export class CorsRequestHandler implements HttpHandler { |
| 25 | + |
| 26 | + public logger = getLogger(); |
| 27 | + |
| 28 | + constructor( |
| 29 | + private handler: HttpHandler, |
| 30 | + private options?: HttpCorsOptions, |
| 31 | + private passThroughOptions: boolean = false, |
| 32 | + ) { } |
| 33 | + |
| 34 | + async handle(context: HttpHandlerContext): Promise<HttpHandlerResponse> { |
| 35 | + |
| 36 | + const { origins, allowMethods, allowHeaders, exposeHeaders, credentials, maxAge } = this.options || ({}); |
| 37 | + |
| 38 | + const requestHeaders = context.request.headers; |
| 39 | + |
| 40 | + const cleanRequestHeaders = cleanHeaders(requestHeaders); |
| 41 | + |
| 42 | + const { |
| 43 | + /* eslint-disable-next-line @typescript-eslint/no-unused-vars -- destructuring for removal */ |
| 44 | + ['access-control-request-method']: requestedMethod, |
| 45 | + ['access-control-request-headers']: requestedHeaders, |
| 46 | + ... noCorsHeaders |
| 47 | + } = cleanRequestHeaders; |
| 48 | + |
| 49 | + const noCorsRequestContext = { |
| 50 | + ... context, |
| 51 | + request: { |
| 52 | + ... context.request, |
| 53 | + headers: { |
| 54 | + ... noCorsHeaders, |
| 55 | + }, |
| 56 | + }, |
| 57 | + }; |
| 58 | + |
| 59 | + const requestedOrigin = cleanRequestHeaders.origin ?? ''; |
| 60 | + |
| 61 | + const allowOrigin = origins |
| 62 | + ? origins.includes(requestedOrigin) |
| 63 | + ? requestedOrigin |
| 64 | + : undefined |
| 65 | + : credentials |
| 66 | + ? requestedOrigin |
| 67 | + : '*'; |
| 68 | + |
| 69 | + const allowHeadersOrRequested = allowHeaders?.join(',') ?? requestedHeaders; |
| 70 | + |
| 71 | + if (context.request.method === 'OPTIONS') { |
| 72 | + |
| 73 | + /* Preflight Request */ |
| 74 | + |
| 75 | + this.logger.debug('Processing preflight request'); |
| 76 | + |
| 77 | + const routeMethods = context.route?.operations.map((op) => op.method); |
| 78 | + const allMethods = [ 'GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH' ]; |
| 79 | + |
| 80 | + const initialOptions = this.passThroughOptions |
| 81 | + ? this.handler.handle(noCorsRequestContext) |
| 82 | + : Promise.resolve({ status: 204, headers: {} }); |
| 83 | + |
| 84 | + return initialOptions |
| 85 | + .then((response) => ({ |
| 86 | + ... response, |
| 87 | + headers: response.headers ? cleanHeaders(response.headers) : {}, |
| 88 | + })) |
| 89 | + .then((response) => ({ |
| 90 | + ... response, |
| 91 | + headers: { |
| 92 | + |
| 93 | + ... response.headers, |
| 94 | + ... allowOrigin && ({ |
| 95 | + ... (allowOrigin !== '*') && { |
| 96 | + 'vary': [ ... new Set([ |
| 97 | + ... response.headers.vary?.split(',').map((v) => v.trim().toLowerCase()) ?? [], `origin` |
| 98 | + ]) ].join(', ') |
| 99 | + }, |
| 100 | + 'access-control-allow-origin': allowOrigin, |
| 101 | + 'access-control-allow-methods': (allowMethods ?? routeMethods ?? allMethods).join(', '), |
| 102 | + ... (allowHeadersOrRequested) && { 'access-control-allow-headers': allowHeadersOrRequested }, |
| 103 | + ... (credentials) && { 'access-control-allow-credentials': 'true' }, |
| 104 | + 'access-control-max-age': (maxAge ?? -1).toString(), |
| 105 | + }), |
| 106 | + }, |
| 107 | + })); |
| 108 | + |
| 109 | + } else { |
| 110 | + |
| 111 | + /* CORS Request */ |
| 112 | + |
| 113 | + this.logger.debug('Processing CORS request'); |
| 114 | + |
| 115 | + return this.handler.handle(noCorsRequestContext) |
| 116 | + .then((response) => ({ |
| 117 | + ... response, |
| 118 | + headers: { |
| 119 | + ... response.headers, |
| 120 | + ... allowOrigin && ({ |
| 121 | + 'access-control-allow-origin': allowOrigin, |
| 122 | + ... (allowOrigin !== '*') && { |
| 123 | + 'vary': [ ... new Set([ |
| 124 | + ... response.headers?.vary?.split(',').map((v) => v.trim().toLowerCase()) ?? [], `origin` |
| 125 | + ]) ].join(', ') |
| 126 | + }, |
| 127 | + ... (credentials) && { 'access-control-allow-credentials': 'true' }, |
| 128 | + ... (exposeHeaders) && { 'access-control-expose-headers': exposeHeaders.join(',') }, |
| 129 | + }), |
| 130 | + }, |
| 131 | + })); |
| 132 | + |
| 133 | + } |
| 134 | + |
| 135 | + } |
| 136 | + |
| 137 | +} |
0 commit comments