Skip to content
Myr

handler.ts

This file

Path

src/adapter/lambda-edge/handler.ts

240 lines · 6.5 KiB · TypeScript

Last changed by

fix(lambda-edge): fail with a descriptive error on a malformed event (#5358)Md. Kawsar Ahmedbefore adoption6cadf75

History of this file

Take it

The walk stopped after 200 commits: lines older than f774f8d point at it.

4.12.15Yusuke Wadabefore adoptionf774f8d

lines 1–122why, one step back
1import crypto from 'node:crypto'
2import type { Hono } from '../../hono'34import { decodeBase64, encodeBase64 } from '../../utils/encode'56// eslint-disable-next-line @typescript-eslint/ban-ts-comment7// @ts-ignore8globalThis.crypto ??= crypto910interface CloudFrontHeader {11 key: string12 value: string13}1415interface CloudFrontHeaders {16 [name: string]: CloudFrontHeader[]17}1819interface CloudFrontCustomOrigin {20 customHeaders: CloudFrontHeaders21 domainName: string22 keepaliveTimeout: number23 path: string24 port: number25 protocol: string26 readTimeout: number27 sslProtocols: string[]28}29// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html30interface CloudFrontS3Origin {31 authMethod: 'origin-access-identity' | 'none'32 customHeaders: CloudFrontHeaders33 domainName: string34 path: string35 region: string36}37type CloudFrontOrigin =38 | { s3: CloudFrontS3Origin; custom?: never }39 | { custom: CloudFrontCustomOrigin; s3?: never }4041export interface CloudFrontRequest {42 clientIp: string43 headers: CloudFrontHeaders44 method: string45 querystring: string46 uri: string47 body?: {48 inputTruncated: boolean49 action: string50 encoding: string51 data: string52 }53 origin?: CloudFrontOrigin54}5556export interface CloudFrontResponse {57 headers: CloudFrontHeaders58 status: string59 statusDescription?: string60}6162export interface CloudFrontConfig {63 distributionDomainName: string64 distributionId: string65 eventType: string66 requestId: string67}6869interface CloudFrontEvent {70 cf: {71 config: CloudFrontConfig72 request: CloudFrontRequest73 response?: CloudFrontResponse74 }75}7677export interface CloudFrontEdgeEvent {78 Records: CloudFrontEvent[]79}8081type CloudFrontContext = {}8283export interface Callback {84 (err: Error | null, result?: CloudFrontRequest | CloudFrontResult): void85}8687// https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-generating-http-responses-in-requests.html#lambda-generating-http-responses-programming-model88interface CloudFrontResult {89 status: string90 statusDescription?: string91 headers?: {92 [header: string]: {93 key: string94 value: string95 }[]96 }97 body?: string98 bodyEncoding?: 'text' | 'base64'99}100101/**102 * Accepts events from 'Lambda@Edge' event103 * https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html104 */105const convertHeaders = (headers: Headers): CloudFrontHeaders => {106 const cfHeaders: CloudFrontHeaders = {}107 headers.forEach((value, key) => {108 cfHeaders[key.toLowerCase()] = [109 ...(cfHeaders[key.toLowerCase()] || []),110 { key: key.toLowerCase(), value },111 ]112 })113 return cfHeaders114}115116export const handle = (117 // eslint-disable-next-line @typescript-eslint/no-explicit-any118 app: Hono<any>119): ((120 event: CloudFrontEdgeEvent,121 context?: CloudFrontContext,122 callback?: Callback

fix(lambda-edge): resolve the handler with the value passed to the callback (#5094)Yusuke Wadabefore adoption24547a6

line 123why, one step back
123) => Promise<CloudFrontResult | CloudFrontRequest>) => {

4.12.15Yusuke Wadabefore adoptionf774f8d

lines 124–125why, one step back
124 return async (event, ...args: [context?: CloudFrontContext, callback?: Callback]) => {
125 const [context, callback] = args

fix(lambda-edge): resolve the handler with the value passed to the callback (#5094)Yusuke Wadabefore adoption24547a6

lines 126–127why, one step back
126 let callbackError: Error | null = null
127 let callbackResult: CloudFrontResult | CloudFrontRequest | undefined

fix(lambda-edge): fail with a descriptive error on a malformed event (#5358)Md. Kawsar Ahmedbefore adoption6cadf75

lines 128–129why, one step back
128 const cf = getCloudFrontRecord(event)
129 const res = await app.fetch(createRequest(cf), {

4.12.15Yusuke Wadabefore adoptionf774f8d

lines 130–132why, one step back
130 event,
131 context,132 callback: (err: Error | null, result?: CloudFrontResult | CloudFrontRequest) => {

fix(lambda-edge): resolve the handler with the value passed to the callback (#5094)Yusuke Wadabefore adoption24547a6

lines 133–136why, one step back
133 if (!callbackError && !callbackResult) {
134 callbackError = err135 callbackResult = result136 }

4.12.15Yusuke Wadabefore adoptionf774f8d

lines 137–138why, one step back
137 callback?.(err, result)
138 },

fix(lambda-edge): fail with a descriptive error on a malformed event (#5358)Md. Kawsar Ahmedbefore adoption6cadf75

lines 139–141why, one step back
139 config: cf.config,
140 request: cf.request,141 response: cf.response,

4.12.15Yusuke Wadabefore adoptionf774f8d

line 142why, one step back
142 })

fix(lambda-edge): resolve the handler with the value passed to the callback (#5094)Yusuke Wadabefore adoption24547a6

lines 143–146why, one step back
143 if (callbackError) {
144 throw callbackError145 }146 return callbackResult ?? createResult(res)

4.12.15Yusuke Wadabefore adoptionf774f8d

lines 147–150why, one step back
147 }
148}149150const createResult = async (res: Response): Promise<CloudFrontResult> => {

fix(lambda-edge): base64 encode content-encoded response bodies (#5099)Yusuke Wadabefore adoption6217f4b

lines 151–154why, one step back
151 const contentEncoding = res.headers.get('content-encoding')
152 const isBase64Encoded =153 isContentTypeBinary(res.headers.get('content-type') || '') ||154 (!!contentEncoding && !/^identity$/i.test(contentEncoding))

4.12.15Yusuke Wadabefore adoptionf774f8d

lines 155–164why, one step back
155 const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()
156157 return {158 status: res.status.toString(),159 headers: convertHeaders(res.headers),160 body,161 ...(isBase64Encoded && { bodyEncoding: 'base64' }),162 }163}164

fix(lambda-edge): fail with a descriptive error on a malformed event (#5358)Md. Kawsar Ahmedbefore adoption6cadf75

lines 165–187why, one step back
165/**
166 * Reads the CloudFront record out of a Lambda@Edge event.167 *168 * The event is supplied by the runtime, so a malformed one means the function169 * was invoked with something other than a Lambda@Edge event. Fail with a170 * message naming the adapter and the missing field, rather than letting an171 * unattributable property access error escape.172 */173const getCloudFrontRecord = (event: CloudFrontEdgeEvent): CloudFrontEvent['cf'] => {174 const cf = event?.Records?.[0]?.cf175 if (!cf?.request) {176 throw new TypeError(177 'Unable to map the CloudFront event to a Request: expected `Records[0].cf.request` in the Lambda@Edge event.'178 )179 }180 return cf181}182183const createRequest = (cf: CloudFrontEvent['cf']): Request => {184 const request = cf.request185 const queryString = request.querystring186 const host = request.headers?.host?.[0]?.value || cf.config?.distributionDomainName187 const urlPath = `https://${host}${request.uri}`

4.12.15Yusuke Wadabefore adoptionf774f8d

lines 188–190why, one step back
188 const url = queryString ? `${urlPath}?${queryString}` : urlPath
189190 const headers = new Headers()

fix(lambda-edge): fail with a descriptive error on a malformed event (#5358)Md. Kawsar Ahmedbefore adoption6cadf75

line 191why, one step back
191 Object.entries(request.headers ?? {}).forEach(([k, v]) => {

Merge commit from forkYusuke Wadabefore adoption3892a6c

line 192why, one step back
192 v.forEach((header) => headers.append(k, header.value))

4.12.15Yusuke Wadabefore adoptionf774f8d

lines 193–194why, one step back
193 })
194

fix(lambda-edge): fail with a descriptive error on a malformed event (#5358)Md. Kawsar Ahmedbefore adoption6cadf75

lines 195–196why, one step back
195 const requestBody = request.body
196 const method = request.method

Merge commit from forkYusuke Wadabefore adoptionfa5f9bf

lines 197–200why, one step back
197 const rawBody = createBody(method, requestBody)
198199 let body: string | Uint8Array<ArrayBuffer> | undefined = rawBody200 if (rawBody !== undefined) {

fix(lambda-edge): satisfy Deno lib types for Content-Length body encoding (#5013)Yusuke Wadabefore adoptione50df01

lines 201–204why, one step back
201 const bytes =
202 typeof rawBody === 'string'203 ? (new TextEncoder().encode(rawBody) as Uint8Array<ArrayBuffer>)204 : rawBody

Merge commit from forkYusuke Wadabefore adoptionfa5f9bf

lines 205–207why, one step back
205 body = bytes
206 headers.set('content-length', bytes.length.toString())207 }

4.12.15Yusuke Wadabefore adoptionf774f8d

lines 208–232why, one step back
208
209 return new Request(url, {210 headers,211 method,212 body,213 })214}215216export const createBody = (217 method: string,218 requestBody: CloudFrontRequest['body']219): string | Uint8Array<ArrayBuffer> | undefined => {220 if (!requestBody || !requestBody.data) {221 return undefined222 }223 if (method === 'GET' || method === 'HEAD') {224 return undefined225 }226 if (requestBody.encoding === 'base64') {227 return decodeBase64(requestBody.data)228 }229 return requestBody.data230}231232export const isContentTypeBinary = (contentType: string): boolean => {

fix(lambda-edge): sync content type detection with aws-lambda (#5426)sarybefore adoptionde310ac

lines 233–237why, one step back
233 if (/^application\/vnd\.(?:apple\.installer|mozilla\.xul)\+xml\s*(?:;|$)/i.test(contentType)) {
234 return true235 }236237 return !/^text\/(?:plain|html|css|javascript|csv)|(?:\/|\+)(?:json|xml)\s*(?:;|$)/i.test(

4.12.15Yusuke Wadabefore adoptionf774f8d

lines 238–240why, one step back
238 contentType
239 )240}