handler.ts
This file
Path
src/adapter/lambda-edge/handler.ts
195 lines · 5.0 KiB · TypeScript
Last changed by
fix(lambda-edge-adapter): Support Alternate Domain Names and Multiple Cookies in Lambda@Edge (#3858)Kent Kweebefore adoptiona1ae224
History of this fileTake it
The walk stopped after 200 commits: lines older than e43f203 point at it.
perf(helper/cookie): fast-path for name specified (#3608)TATSUNO “Taz” Yasuhirobefore adoptione43f203
lines 1–107why, one step back1import 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) => {fix(lambda-edge-adapter): Support Alternate Domain Names and Multiple Cookies in Lambda@Edge (#3858)Kent Kweebefore adoptiona1ae224
lines 108–111why, one step back108 cfHeaders[key.toLowerCase()] = [109 ...(cfHeaders[key.toLowerCase()] || []),110 { key: key.toLowerCase(), value },111 ]perf(helper/cookie): fast-path for name specified (#3608)TATSUNO “Taz” Yasuhirobefore adoptione43f203
lines 112–152why, one step back112 })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?: Callback123) => Promise<CloudFrontResult>) => {124 return async (event, context?, callback?) => {125 const res = await app.fetch(createRequest(event), {126 event,127 context,128 callback: (err: Error | null, result?: CloudFrontResult | CloudFrontRequest) => {129 callback?.(err, result)130 },131 config: event.Records[0].cf.config,132 request: event.Records[0].cf.request,133 response: event.Records[0].cf.response,134 })135 return createResult(res)136 }137}138139const createResult = async (res: Response): Promise<CloudFrontResult> => {140 const isBase64Encoded = isContentTypeBinary(res.headers.get('content-type') || '')141 const body = isBase64Encoded ? encodeBase64(await res.arrayBuffer()) : await res.text()142143 return {144 status: res.status.toString(),145 headers: convertHeaders(res.headers),146 body,147 ...(isBase64Encoded && { bodyEncoding: 'base64' }),148 }149}150151const createRequest = (event: CloudFrontEdgeEvent): Request => {152 const queryString = event.Records[0].cf.request.querystringfix(lambda-edge-adapter): Support Alternate Domain Names and Multiple Cookies in Lambda@Edge (#3858)Kent Kweebefore adoptiona1ae224
lines 153–156why, one step back153 const host =154 event.Records[0].cf.request.headers?.host?.[0]?.value ||155 event.Records[0].cf.config.distributionDomainName156 const urlPath = `https://${host}${event.Records[0].cf.request.uri}`perf(helper/cookie): fast-path for name specified (#3608)TATSUNO “Taz” Yasuhirobefore adoptione43f203
lines 157–195why, one step back157 const url = queryString ? `${urlPath}?${queryString}` : urlPath158159 const headers = new Headers()160 Object.entries(event.Records[0].cf.request.headers).forEach(([k, v]) => {161 v.forEach((header) => headers.set(k, header.value))162 })163164 const requestBody = event.Records[0].cf.request.body165 const method = event.Records[0].cf.request.method166 const body = createBody(method, requestBody)167168 return new Request(url, {169 headers,170 method,171 body,172 })173}174175export const createBody = (176 method: string,177 requestBody: CloudFrontRequest['body']178): string | Uint8Array | undefined => {179 if (!requestBody || !requestBody.data) {180 return undefined181 }182 if (method === 'GET' || method === 'HEAD') {183 return undefined184 }185 if (requestBody.encoding === 'base64') {186 return decodeBase64(requestBody.data)187 }188 return requestBody.data189}190191export const isContentTypeBinary = (contentType: string): boolean => {192 return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test(193 contentType194 )195}