Skip to content
Myr

handler.ts

This file

Path

src/adapter/aws-lambda/handler.ts

492 lines 路 14.4 KiB 路 TypeScript

Last changed by

fix(aws-lambda): set cookies with comma is bugged (#3084)Trung Dangbefore adoption1e3e58b

History of this file

Take it

1import crypto from 'node:crypto'2import type { Hono } from '../../hono'3import type { Env, Schema } from '../../types'4import { decodeBase64, encodeBase64 } from '../../utils/encode'5import type {6  ALBRequestContext,7  ApiGatewayRequestContext,8  ApiGatewayRequestContextV2,9  Handler,10  LambdaContext,11} from './types'1213// eslint-disable-next-line @typescript-eslint/ban-ts-comment14// @ts-ignore15globalThis.crypto ??= crypto1617export type LambdaEvent = APIGatewayProxyEvent | APIGatewayProxyEventV2 | ALBProxyEvent1819// When calling HTTP API or Lambda directly through function urls20export interface APIGatewayProxyEventV2 {21  version: string22  routeKey: string23  headers: Record<string, string | undefined>24  multiValueHeaders?: undefined25  cookies?: string[]26  rawPath: string27  rawQueryString: string28  body: string | null29  isBase64Encoded: boolean30  requestContext: ApiGatewayRequestContextV231  queryStringParameters?: {32    [name: string]: string | undefined33  }34  pathParameters?: {35    [name: string]: string | undefined36  }37  stageVariables?: {38    [name: string]: string | undefined39  }40}4142// When calling Lambda through an API Gateway43export interface APIGatewayProxyEvent {44  version: string45  httpMethod: string46  headers: Record<string, string | undefined>47  multiValueHeaders?: {48    [headerKey: string]: string[]49  }50  path: string51  body: string | null52  isBase64Encoded: boolean53  queryStringParameters?: Record<string, string | undefined>54  requestContext: ApiGatewayRequestContext55  resource: string56  multiValueQueryStringParameters?: {57    [parameterKey: string]: string[]58  }59  pathParameters?: Record<string, string>60  stageVariables?: Record<string, string>61}6263// When calling Lambda through an Application Load Balancer64export interface ALBProxyEvent {65  httpMethod: string66  headers?: Record<string, string | undefined>67  multiValueHeaders?: Record<string, string[] | undefined>68  path: string69  body: string | null70  isBase64Encoded: boolean71  queryStringParameters?: Record<string, string | undefined>72  multiValueQueryStringParameters?: {73    [parameterKey: string]: string[]74  }75  requestContext: ALBRequestContext76}7778export interface APIGatewayProxyResult {79  statusCode: number80  statusDescription?: string81  body: string82  headers: Record<string, string>83  cookies?: string[]84  multiValueHeaders?: {85    [headerKey: string]: string[]86  }87  isBase64Encoded: boolean88}8990const getRequestContext = (91  event: LambdaEvent92): ApiGatewayRequestContext | ApiGatewayRequestContextV2 | ALBRequestContext => {93  return event.requestContext94}9596const streamToNodeStream = async (97  reader: ReadableStreamDefaultReader<Uint8Array>,98  writer: NodeJS.WritableStream99): Promise<void> => {100  let readResult = await reader.read()101  while (!readResult.done) {102    writer.write(readResult.value)103    readResult = await reader.read()104  }105  writer.end()106}107108export const streamHandle = <109  E extends Env = Env,110  S extends Schema = {},111  BasePath extends string = '/'112>(113  app: Hono<E, S, BasePath>114): Handler => {115  // @ts-expect-error awslambda is not a standard API116  return awslambda.streamifyResponse(117    async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {118      const processor = getProcessor(event)119      try {120        const req = processor.createRequest(event)121        const requestContext = getRequestContext(event)122123        const res = await app.fetch(req, {124          event,125          requestContext,126          context,127        })128129        const headers: Record<string, string> = {}130        const cookies: string[] = []131        res.headers.forEach((value, name) => {132          if (name === 'set-cookie') {133            cookies.push(value)134          } else {135            headers[name] = value136          }137        })138139        // Check content type140        const httpResponseMetadata = {141          statusCode: res.status,142          headers,143          cookies,144        }145146        // Update response stream147        // @ts-expect-error awslambda is not a standard API148        responseStream = awslambda.HttpResponseStream.from(responseStream, httpResponseMetadata)149150        if (res.body) {151          await streamToNodeStream(res.body.getReader(), responseStream)152        } else {153          responseStream.write('')154        }155      } catch (error) {156        console.error('Error processing request:', error)157        responseStream.write('Internal Server Error')158      } finally {159        responseStream.end()160      }161    }162  )163}164165/**166 * Accepts events from API Gateway/ELB(`APIGatewayProxyEvent`) and directly through Function Url(`APIGatewayProxyEventV2`)167 */168export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(169  app: Hono<E, S, BasePath>170): ((event: LambdaEvent, lambdaContext?: LambdaContext) => Promise<APIGatewayProxyResult>) => {171  return async (event, lambdaContext?) => {172    const processor = getProcessor(event)173174    const req = processor.createRequest(event)175    const requestContext = getRequestContext(event)176177    const res = await app.fetch(req, {178      event,179      requestContext,180      lambdaContext,181    })182183    return processor.createResult(event, res)184  }185}186187abstract class EventProcessor<E extends LambdaEvent> {188  protected abstract getPath(event: E): string189190  protected abstract getMethod(event: E): string191192  protected abstract getQueryString(event: E): string193194  protected abstract getHeaders(event: E): Headers195196  protected abstract getCookies(event: E, headers: Headers): void197198  protected abstract setCookiesToResult(199    event: E,200    result: APIGatewayProxyResult,201    cookies: string[]202  ): void203204  createRequest(event: E): Request {205    const queryString = this.getQueryString(event)206    const domainName =207      event.requestContext && 'domainName' in event.requestContext208        ? event.requestContext.domainName209        : event.headers?.['host'] ?? event.multiValueHeaders?.['host']?.[0]210    const path = this.getPath(event)211    const urlPath = `https://${domainName}${path}`212    const url = queryString ? `${urlPath}?${queryString}` : urlPath213214    const headers = this.getHeaders(event)215216    const method = this.getMethod(event)217    const requestInit: RequestInit = {218      headers,219      method,220    }221222    if (event.body) {223      requestInit.body = event.isBase64Encoded ? decodeBase64(event.body) : event.body224    }225226    return new Request(url, requestInit)227  }228229  async createResult(event: E, res: Response): Promise<APIGatewayProxyResult> {230    const contentType = res.headers.get('content-type')231    let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false232233    if (!isBase64Encoded) {234      const contentEncoding = res.headers.get('content-encoding')235      isBase64Encoded = isContentEncodingBinary(contentEncoding)236    }237238    const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()239240    const result: APIGatewayProxyResult = {241      body: body,242      headers: {},243      multiValueHeaders: event.multiValueHeaders ? {} : undefined,244      statusCode: res.status,245      isBase64Encoded,246    }247248    this.setCookies(event, res, result)249    res.headers.forEach((value, key) => {250      result.headers[key] = value251      if (event.multiValueHeaders && result.multiValueHeaders) {252        result.multiValueHeaders[key] = [value]253      }254    })255256    return result257  }258259  setCookies(event: E, res: Response, result: APIGatewayProxyResult) {260    if (res.headers.has('set-cookie')) {261      const cookies = res.headers.getSetCookie262        ? res.headers.getSetCookie()263        : Array.from(res.headers.entries())264            .filter(([k]) => k === 'set-cookie')265            .map(([, v]) => v)266267      if (Array.isArray(cookies)) {268        this.setCookiesToResult(event, result, cookies)269        res.headers.delete('set-cookie')270      }271    }272  }273}274275class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {276  protected getPath(event: APIGatewayProxyEventV2): string {277    return event.rawPath278  }279280  protected getMethod(event: APIGatewayProxyEventV2): string {281    return event.requestContext.http.method282  }283284  protected getQueryString(event: APIGatewayProxyEventV2): string {285    return event.rawQueryString286  }287288  protected getCookies(event: APIGatewayProxyEventV2, headers: Headers): void {289    if (Array.isArray(event.cookies)) {290      headers.set('Cookie', event.cookies.join('; '))291    }292  }293294  protected setCookiesToResult(295    _: APIGatewayProxyEventV2,296    result: APIGatewayProxyResult,297    cookies: string[]298  ): void {299    result.cookies = cookies300  }301302  protected getHeaders(event: APIGatewayProxyEventV2): Headers {303    const headers = new Headers()304    this.getCookies(event, headers)305    if (event.headers) {306      for (const [k, v] of Object.entries(event.headers)) {307        if (v) {308          headers.set(k, v)309        }310      }311    }312    return headers313  }314}315316const v2Processor: EventV2Processor = new EventV2Processor()317318class EventV1Processor extends EventProcessor<Exclude<LambdaEvent, APIGatewayProxyEventV2>> {319  protected getPath(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {320    return event.path321  }322323  protected getMethod(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {324    return event.httpMethod325  }326327  protected getQueryString(event: Exclude<LambdaEvent, APIGatewayProxyEventV2>): string {328    return Object.entries(event.queryStringParameters || {})329      .filter(([, value]) => value)330      .map(([key, value]) => `${key}=${value}`)331      .join('&')332  }333334  protected getCookies(335    // eslint-disable-next-line @typescript-eslint/no-unused-vars336    event: Exclude<LambdaEvent, APIGatewayProxyEventV2>,337    // eslint-disable-next-line @typescript-eslint/no-unused-vars338    headers: Headers339  ): void {340    // nop341  }342343  protected getHeaders(event: APIGatewayProxyEvent): Headers {344    const headers = new Headers()345    this.getCookies(event, headers)346    if (event.headers) {347      for (const [k, v] of Object.entries(event.headers)) {348        if (v) {349          headers.set(k, v)350        }351      }352    }353    if (event.multiValueHeaders) {354      for (const [k, values] of Object.entries(event.multiValueHeaders)) {355        if (values) {356          // avoid duplicating already set headers357          const foundK = headers.get(k)358          values.forEach((v) => (!foundK || !foundK.includes(v)) && headers.append(k, v))359        }360      }361    }362    return headers363  }364365  protected setCookiesToResult(366    _: APIGatewayProxyEvent,367    result: APIGatewayProxyResult,368    cookies: string[]369  ): void {370    result.multiValueHeaders = {371      'set-cookie': cookies,372    }373  }374}375376const v1Processor: EventV1Processor = new EventV1Processor()377378class ALBProcessor extends EventProcessor<ALBProxyEvent> {379  protected getHeaders(event: ALBProxyEvent): Headers {380    const headers = new Headers()381    // if multiValueHeaders is present the ALB will use it instead of the headers field382    // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#multi-value-headers383    if (event.multiValueHeaders) {384      for (const [key, values] of Object.entries(event.multiValueHeaders)) {385        if (values && Array.isArray(values)) {386          // https://www.rfc-editor.org/rfc/rfc9110.html#name-common-rules-for-defining-f387          headers.set(key, values.join('; '))388        }389      }390    } else {391      for (const [key, value] of Object.entries(event.headers ?? {})) {392        if (value) {393          headers.set(key, value)394        }395      }396    }397    return headers398  }399400  protected getPath(event: ALBProxyEvent): string {401    return event.path402  }403404  protected getMethod(event: ALBProxyEvent): string {405    return event.httpMethod406  }407408  protected getQueryString(event: ALBProxyEvent): string {409    // In the case of ALB Integration either queryStringParameters or multiValueQueryStringParameters can be present not both410    /* 411      In other cases like when using the serverless framework, the event object does contain both queryStringParameters and multiValueQueryStringParameters:412      Below is an example event object for this URL: /payment/b8c55e69?select=amount&select=currency413      {414        ...415        queryStringParameters: { select: 'currency' },416        multiValueQueryStringParameters: { select: [ 'amount', 'currency' ] },417      }418      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.419      A simple fix would be to invert the if statement and check the multiValueQueryStringParameters first.420    */421    if (event.multiValueQueryStringParameters) {422      return Object.entries(event.multiValueQueryStringParameters || {})423        .filter(([, value]) => value)424        .map(([key, value]) => `${key}=${value.join(`&${key}=`)}`)425        .join('&')426    } else {427      return Object.entries(event.queryStringParameters || {})428        .filter(([, value]) => value)429        .map(([key, value]) => `${key}=${value}`)430        .join('&')431    }432  }433434  protected getCookies(event: ALBProxyEvent, headers: Headers): void {435    let cookie436    if (event.multiValueHeaders) {437      cookie = event.multiValueHeaders['cookie']?.join('; ')438    } else {439      cookie = event.headers ? event.headers['cookie'] : undefined440    }441    if (cookie) {442      headers.append('Cookie', cookie)443    }444  }445446  protected setCookiesToResult(447    event: ALBProxyEvent,448    result: APIGatewayProxyResult,449    cookies: string[]450  ): void {451    // when multi value headers is enabled452    if (event.multiValueHeaders && result.multiValueHeaders) {453      result.multiValueHeaders['set-cookie'] = cookies454    } else {455      // otherwise serialize the set-cookie456      result.headers['set-cookie'] = cookies.join(', ')457    }458  }459}460461const albProcessor: ALBProcessor = new ALBProcessor()462463export const getProcessor = (event: LambdaEvent): EventProcessor<LambdaEvent> => {464  if (isProxyEventALB(event)) {465    return albProcessor466  }467  if (isProxyEventV2(event)) {468    return v2Processor469  }470  return v1Processor471}472473const isProxyEventALB = (event: LambdaEvent): event is ALBProxyEvent => {474  return Object.hasOwn(event.requestContext, 'elb')475}476477const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {478  return Object.hasOwn(event, 'rawPath')479}480481export const isContentTypeBinary = (contentType: string) => {482  return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(483    contentType484  )485}486487export const isContentEncodingBinary = (contentEncoding: string | null) => {488  if (contentEncoding === null) {489    return false490  }491  return /^(gzip|deflate|compress|br)/.test(contentEncoding)492}