Skip to content
Myr

handler.ts

This file

Path

src/adapter/aws-lambda/handler.ts

577 lines 路 17.5 KiB 路 TypeScript

Last changed by

fix(aws-lambda): serve microsoft office files as binary in lambda handler (#4469)Matthias Feistbefore adoption253ec28

History of this file

Take it

1import type { Hono } from '../../hono'2import type { Env, Schema } from '../../types'3import { decodeBase64, encodeBase64 } from '../../utils/encode'4import type {5  ALBRequestContext,6  ApiGatewayRequestContext,7  ApiGatewayRequestContextV2,8  Handler,9  LambdaContext,10} from './types'1112function sanitizeHeaderValue(value: string): string {13  // Check if the value contains non-ASCII characters (char codes > 127)14  // eslint-disable-next-line no-control-regex15  const hasNonAscii = /[^\x00-\x7F]/.test(value)16  if (!hasNonAscii) {17    return value18  }19  return encodeURIComponent(value)20}2122export type LambdaEvent = APIGatewayProxyEvent | APIGatewayProxyEventV2 | ALBProxyEvent2324// When calling HTTP API or Lambda directly through function urls25export interface APIGatewayProxyEventV2 {26  version: string27  routeKey: string28  headers: Record<string, string | undefined>29  multiValueHeaders?: undefined30  cookies?: string[]31  rawPath: string32  rawQueryString: string33  body: string | null34  isBase64Encoded: boolean35  requestContext: ApiGatewayRequestContextV236  queryStringParameters?: {37    [name: string]: string | undefined38  }39  pathParameters?: {40    [name: string]: string | undefined41  }42  stageVariables?: {43    [name: string]: string | undefined44  }45}4647// When calling Lambda through an API Gateway48export interface APIGatewayProxyEvent {49  version: string50  httpMethod: string51  headers: Record<string, string | undefined>52  multiValueHeaders?: {53    [headerKey: string]: string[]54  }55  path: string56  body: string | null57  isBase64Encoded: boolean58  queryStringParameters?: Record<string, string | undefined>59  requestContext: ApiGatewayRequestContext60  resource: string61  multiValueQueryStringParameters?: {62    [parameterKey: string]: string[]63  }64  pathParameters?: Record<string, string>65  stageVariables?: Record<string, string>66}6768// When calling Lambda through an Application Load Balancer69export interface ALBProxyEvent {70  httpMethod: string71  headers?: Record<string, string | undefined>72  multiValueHeaders?: Record<string, string[] | undefined>73  path: string74  body: string | null75  isBase64Encoded: boolean76  queryStringParameters?: Record<string, string | undefined>77  multiValueQueryStringParameters?: {78    [parameterKey: string]: string[]79  }80  requestContext: ALBRequestContext81}8283type WithHeaders = {84  headers: Record<string, string>85  multiValueHeaders?: undefined86}87type WithMultiValueHeaders = {88  headers?: undefined89  multiValueHeaders: Record<string, string[]>90}9192export type APIGatewayProxyResult = {93  statusCode: number94  statusDescription?: string95  body: string96  cookies?: string[]97  isBase64Encoded: boolean98} & (WithHeaders | WithMultiValueHeaders)99100const getRequestContext = (101  event: LambdaEvent102): ApiGatewayRequestContext | ApiGatewayRequestContextV2 | ALBRequestContext => {103  return event.requestContext104}105106const streamToNodeStream = async (107  reader: ReadableStreamDefaultReader<Uint8Array>,108  writer: NodeJS.WritableStream109): Promise<void> => {110  let readResult = await reader.read()111  while (!readResult.done) {112    writer.write(readResult.value)113    readResult = await reader.read()114  }115  writer.end()116}117118export const streamHandle = <119  E extends Env = Env,120  S extends Schema = {},121  BasePath extends string = '/'122>(123  app: Hono<E, S, BasePath>124): Handler => {125  // @ts-expect-error awslambda is not a standard API126  return awslambda.streamifyResponse(127    async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {128      const processor = getProcessor(event)129      try {130        const req = processor.createRequest(event)131        const requestContext = getRequestContext(event)132133        const res = await app.fetch(req, {134          event,135          requestContext,136          context,137        })138139        const headers: Record<string, string> = {}140        const cookies: string[] = []141        res.headers.forEach((value, name) => {142          if (name === 'set-cookie') {143            cookies.push(value)144          } else {145            headers[name] = value146          }147        })148149        // Check content type150        const httpResponseMetadata = {151          statusCode: res.status,152          headers,153          cookies,154        }155156        // Update response stream157        // @ts-expect-error awslambda is not a standard API158        responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata)159160        if (res.body) {161          await streamToNodeStream(res.body.getReader(), responseStream)162        } else {163          responseStream.write('')164        }165      } catch (error) {166        console.error('Error processing request:', error)167        responseStream.write('Internal Server Error')168      } finally {169        responseStream.end()170      }171    }172  )173}174175type HandleOptions = {176  isContentTypeBinary: ((contentType: string) => boolean) | undefined177}178179/**180 * Converts a Hono application to an AWS Lambda handler.181 *182 * Accepts events from API Gateway (v1 and v2), Application Load Balancer (ALB),183 * and Lambda Function URLs.184 *185 * @param app - The Hono application instance186 * @param options - Optional configuration187 * @param options.isContentTypeBinary - A function to determine if the content type is binary.188 *                                      If not provided, the default function will be used.189 * @returns Lambda handler function190 *191 * @example192 * ```js193 * import { Hono } from 'hono'194 * import { handle } from 'hono/aws-lambda'195 *196 * const app = new Hono()197 *198 * app.get('/', (c) => c.text('Hello from Lambda'))199 * app.get('/json', (c) => c.json({ message: 'Hello JSON' }))200 *201 * export const handler = handle(app)202 * ```203 *204 * @example205 * ```js206 * // With custom binary content type detection207 * import { handle, defaultIsContentTypeBinary } from 'hono/aws-lambda'208 * export const handler = handle(app, {209 *   isContentTypeBinary: (contentType) => {210 *     if (defaultIsContentTypeBinary(contentType)) {211 *       // default logic same as prior to v4.8.4212 *       return true213 *     }214 *     return contentType.startsWith('image/') || contentType === 'application/pdf'215 *   }216 * })217 * ```218 */219export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(220  app: Hono<E, S, BasePath>,221  { isContentTypeBinary }: HandleOptions = { isContentTypeBinary: undefined }222): (<L extends LambdaEvent>(223  event: L,224  lambdaContext?: LambdaContext225) => Promise<226  APIGatewayProxyResult &227    (L extends { multiValueHeaders: Record<string, string[]> }228      ? WithMultiValueHeaders229      : WithHeaders)230>) => {231  // @ts-expect-error FIXME: Fix return typing232  return async (event, lambdaContext?) => {233    const processor = getProcessor(event)234235    const req = processor.createRequest(event)236    const requestContext = getRequestContext(event)237238    const res = await app.fetch(req, {239      event,240      requestContext,241      lambdaContext,242    })243244    return processor.createResult(event, res, { isContentTypeBinary })245  }246}247248export abstract class EventProcessor<E extends LambdaEvent> {249  protected abstract getPath(event: E): string250251  protected abstract getMethod(event: E): string252253  protected abstract getQueryString(event: E): string254255  protected abstract getHeaders(event: E): Headers256257  protected abstract getCookies(event: E, headers: Headers): void258259  protected abstract setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void260261  createRequest(event: E): Request {262    const queryString = this.getQueryString(event)263    const domainName =264      event.requestContext && 'domainName' in event.requestContext265        ? event.requestContext.domainName266        : event.headers?.['host'] ?? event.multiValueHeaders?.['host']?.[0]267    const path = this.getPath(event)268    const urlPath = `https://${domainName}${path}`269    const url = queryString ? `${urlPath}?${queryString}` : urlPath270271    const headers = this.getHeaders(event)272273    const method = this.getMethod(event)274    const requestInit: RequestInit = {275      headers,276      method,277    }278279    if (event.body) {280      requestInit.body = event.isBase64Encoded ? decodeBase64(event.body) : event.body281    }282283    return new Request(url, requestInit)284  }285286  async createResult(287    event: E,288    res: Response,289    options: Pick<HandleOptions, 'isContentTypeBinary'>290  ): Promise<APIGatewayProxyResult> {291    // determine whether the response body should be base64 encoded292    const contentType = res.headers.get('content-type')293    const isContentTypeBinary = options.isContentTypeBinary ?? defaultIsContentTypeBinary // overwrite default function if provided294    let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false295296    if (!isBase64Encoded) {297      const contentEncoding = res.headers.get('content-encoding')298      isBase64Encoded = isContentEncodingBinary(contentEncoding)299    }300301    const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()302303    const result: APIGatewayProxyResult = {304      body: body,305      statusCode: res.status,306      isBase64Encoded,307      ...(event.multiValueHeaders308        ? {309            multiValueHeaders: {},310          }311        : {312            headers: {},313          }),314    }315316    this.setCookies(event, res, result)317    if (result.multiValueHeaders) {318      res.headers.forEach((value, key) => {319        result.multiValueHeaders[key] = [value]320      })321    } else {322      res.headers.forEach((value, key) => {323        result.headers[key] = value324      })325    }326327    return result328  }329330  setCookies(event: E, res: Response, result: APIGatewayProxyResult) {331    if (res.headers.has('set-cookie')) {332      const cookies = res.headers.getSetCookie333        ? res.headers.getSetCookie()334        : Array.from(res.headers.entries())335            .filter(([k]) => k === 'set-cookie')336            .map(([, v]) => v)337338      if (Array.isArray(cookies)) {339        this.setCookiesToResult(result, cookies)340        res.headers.delete('set-cookie')341      }342    }343  }344}345346export class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {347  protected getPath(event: APIGatewayProxyEventV2): string {348    return event.rawPath349  }350351  protected getMethod(event: APIGatewayProxyEventV2): string {352    return event.requestContext.http.method353  }354355  protected getQueryString(event: APIGatewayProxyEventV2): string {356    return event.rawQueryString357  }358359  protected getCookies(event: APIGatewayProxyEventV2, headers: Headers): void {360    if (Array.isArray(event.cookies)) {361      headers.set('Cookie', event.cookies.join('; '))362    }363  }364365  protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {366    result.cookies = cookies367  }368369  protected getHeaders(event: APIGatewayProxyEventV2): Headers {370    const headers = new Headers()371    this.getCookies(event, headers)372    if (event.headers) {373      for (const [k, v] of Object.entries(event.headers)) {374        if (v) {375          headers.set(k, v)376        }377      }378    }379    return headers380  }381}382383const v2Processor: EventV2Processor = new EventV2Processor()384385export class EventV1Processor extends EventProcessor<Exclude<LambdaEvent, APIGatewayProxyEventV2>> {386  protected getPath(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {387    return event.path388  }389390  protected getMethod(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {391    return event.httpMethod392  }393394  protected getQueryString(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {395    // In the case of gateway Integration either queryStringParameters or multiValueQueryStringParameters can be present not both396    // API Gateway passes decoded values, so we need to re-encode them to preserve the original URL397    if (event.multiValueQueryStringParameters) {398      return Object.entries(event.multiValueQueryStringParameters || {})399        .filter(([, value]) => value)400        .map(([key, values]) =>401          values.map((value) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('&')402        )403        .join('&')404    } else {405      return Object.entries(event.queryStringParameters || {})406        .filter(([, value]) => value)407        .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value || '')}`)408        .join('&')409    }410  }411412  protected getCookies(413    // eslint-disable-next-line @typescript-eslint/no-unused-vars414    event: Exclude<LambdaEvent, APIGatewayProxyEventV2>,415    // eslint-disable-next-line @typescript-eslint/no-unused-vars416    headers: Headers417  ): void {418    // nop419  }420421  protected getHeaders(event: APIGatewayProxyEvent): Headers {422    const headers = new Headers()423    this.getCookies(event, headers)424    if (event.headers) {425      for (const [k, v] of Object.entries(event.headers)) {426        if (v) {427          headers.set(k, sanitizeHeaderValue(v))428        }429      }430    }431    if (event.multiValueHeaders) {432      for (const [k, values] of Object.entries(event.multiValueHeaders)) {433        if (values) {434          // avoid duplicating already set headers435          const foundK = headers.get(k)436          values.forEach((v) => {437            const sanitizedValue = sanitizeHeaderValue(v)438            return (439              (!foundK || !foundK.includes(sanitizedValue)) && headers.append(k, sanitizedValue)440            )441          })442        }443      }444    }445    return headers446  }447448  protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {449    result.multiValueHeaders = {450      'set-cookie': cookies,451    }452  }453}454455const v1Processor: EventV1Processor = new EventV1Processor()456457export class ALBProcessor extends EventProcessor<ALBProxyEvent> {458  protected getHeaders(event: ALBProxyEvent): Headers {459    const headers = new Headers()460    // if multiValueHeaders is present the ALB will use it instead of the headers field461    // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers462    if (event.multiValueHeaders) {463      for (const [key, values] of Object.entries(event.multiValueHeaders)) {464        if (values && Array.isArray(values)) {465          // https://www.rfc-editor.org/rfc/rfc9110.html#name-common-rules-for-defining-f466          const sanitizedValue = sanitizeHeaderValue(values.join('; '))467          headers.set(key, sanitizedValue)468        }469      }470    } else {471      for (const [key, value] of Object.entries(event.headers ?? {})) {472        if (value) {473          headers.set(key, sanitizeHeaderValue(value))474        }475      }476    }477    return headers478  }479480  protected getPath(event: ALBProxyEvent): string {481    return event.path482  }483484  protected getMethod(event: ALBProxyEvent): string {485    return event.httpMethod486  }487488  protected getQueryString(event: ALBProxyEvent): string {489    // In the case of ALB Integration either queryStringParameters or multiValueQueryStringParameters can be present not both490    /*491      In other cases like when using the serverless framework, the event object does contain both queryStringParameters and multiValueQueryStringParameters:492      Below is an example event object for this URL: /payment/b8c55e69?select=amount&select=currency493      {494        ...495        queryStringParameters: { select: 'currency' },496        multiValueQueryStringParameters: { select: [ 'amount', 'currency' ] },497      }498      The expected results is for select to be an array with two items. However the pre-fix code is only returning one item ('currency') in the array.499      A simple fix would be to invert the if statement and check the multiValueQueryStringParameters first.500    */501    if (event.multiValueQueryStringParameters) {502      return Object.entries(event.multiValueQueryStringParameters || {})503        .filter(([, value]) => value)504        .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)505        .join('&')506    } else {507      return Object.entries(event.queryStringParameters || {})508        .filter(([, value]) => value)509        .map(([key, value]) => `${key}=${value}`)510        .join('&')511    }512  }513514  protected getCookies(event: ALBProxyEvent, headers: Headers): void {515    let cookie516    if (event.multiValueHeaders) {517      cookie = event.multiValueHeaders['cookie']?.join('; ')518    } else {519      cookie = event.headers ? event.headers['cookie'] : undefined520    }521    if (cookie) {522      headers.append('Cookie', cookie)523    }524  }525526  protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void {527    // when multi value headers is enabled528    if (result.multiValueHeaders) {529      result.multiValueHeaders['set-cookie'] = cookies530    } else {531      // otherwise serialize the set-cookie532      result.headers['set-cookie'] = cookies.join(', ')533    }534  }535}536537const albProcessor: ALBProcessor = new ALBProcessor()538539export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {540  if (isProxyEventALB(event)) {541    return albProcessor542  }543  if (isProxyEventV2(event)) {544    return v2Processor545  }546  return v1Processor547}548549const isProxyEventALB = (event: LambdaEvent): event is ALBProxyEvent => {550  if (event.requestContext) {551    return Object.hasOwn(event.requestContext, 'elb')552  }553  return false554}555556const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {557  return Object.hasOwn(event, 'rawPath')558}559560/**561 * Check if the given content type is binary.562 * This is a default function and may be overwritten by the user via `isContentTypeBinary` option in handler().563 * @param contentType The content type to check.564 * @returns True if the content type is binary, false otherwise.565 */566export const defaultIsContentTypeBinary = (contentType: string): boolean => {567  return !/^text\/(?:plain|html|css|javascript|csv)|(?:\/|\+)(?:json|xml)\s*(?:;|$)/.test(568    contentType569  )570}571572export const isContentEncodingBinary = (contentEncoding: string | null) => {573  if (contentEncoding === null) {574    return false575  }576  return /^(gzip|deflate|compress|br)/.test(contentEncoding)577}