Skip to content
Myr

handler.ts

This file

Path

src/adapter/lambda-edge/handler.ts

218 lines · 5.9 KiB · TypeScript

Last changed by

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

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

4.12.15Yusuke Wadabefore adoptionf774f8d

lines 128–131why, one step back
128 const res = await app.fetch(createRequest(event), {
129 event,130 context,131 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 132–135why, one step back
132 if (!callbackError && !callbackResult) {
133 callbackError = err134 callbackResult = result135 }

4.12.15Yusuke Wadabefore adoptionf774f8d

lines 136–141why, one step back
136 callback?.(err, result)
137 },138 config: event.Records[0].cf.config,139 request: event.Records[0].cf.request,140 response: event.Records[0].cf.response,141 })

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

lines 142–145why, one step back
142 if (callbackError) {
143 throw callbackError144 }145 return callbackResult ?? createResult(res)

4.12.15Yusuke Wadabefore adoptionf774f8d

lines 146–149why, one step back
146 }
147}148149const createResult = async (res: Response): Promise<CloudFrontResult> => {

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

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

4.12.15Yusuke Wadabefore adoptionf774f8d

lines 154–173why, one step back
154 const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()
155156 return {157 status: res.status.toString(),158 headers: convertHeaders(res.headers),159 body,160 ...(isBase64Encoded && { bodyEncoding: 'base64' }),161 }162}163164const createRequest = (event: CloudFrontEdgeEvent): Request => {165 const queryString = event.Records[0].cf.request.querystring166 const host =167 event.Records[0].cf.request.headers?.host?.[0]?.value ||168 event.Records[0].cf.config.distributionDomainName169 const urlPath = `https://${host}${event.Records[0].cf.request.uri}`170 const url = queryString ? `${urlPath}?${queryString}` : urlPath171172 const headers = new Headers()173 Object.entries(event.Records[0].cf.request.headers).forEach(([k, v]) => {

Merge commit from forkYusuke Wadabefore adoption3892a6c

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

4.12.15Yusuke Wadabefore adoptionf774f8d

lines 175–178why, one step back
175 })
176177 const requestBody = event.Records[0].cf.request.body178 const method = event.Records[0].cf.request.method

Merge commit from forkYusuke Wadabefore adoptionfa5f9bf

lines 179–182why, one step back
179 const rawBody = createBody(method, requestBody)
180181 let body: string | Uint8Array<ArrayBuffer> | undefined = rawBody182 if (rawBody !== undefined) {

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

lines 183–186why, one step back
183 const bytes =
184 typeof rawBody === 'string'185 ? (new TextEncoder().encode(rawBody) as Uint8Array<ArrayBuffer>)186 : rawBody

Merge commit from forkYusuke Wadabefore adoptionfa5f9bf

lines 187–189why, one step back
187 body = bytes
188 headers.set('content-length', bytes.length.toString())189 }

4.12.15Yusuke Wadabefore adoptionf774f8d

lines 190–218why, one step back
190
191 return new Request(url, {192 headers,193 method,194 body,195 })196}197198export const createBody = (199 method: string,200 requestBody: CloudFrontRequest['body']201): string | Uint8Array<ArrayBuffer> | undefined => {202 if (!requestBody || !requestBody.data) {203 return undefined204 }205 if (method === 'GET' || method === 'HEAD') {206 return undefined207 }208 if (requestBody.encoding === 'base64') {209 return decodeBase64(requestBody.data)210 }211 return requestBody.data212}213214export const isContentTypeBinary = (contentType: string): boolean => {215 return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(216 contentType217 )218}