-
Notifications
You must be signed in to change notification settings - Fork 579
Expand file tree
/
Copy pathdit-header-normalization.js
More file actions
190 lines (155 loc) · 6.78 KB
/
Copy pathdit-header-normalization.js
File metadata and controls
190 lines (155 loc) · 6.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//const FORMAT_PRIORITY = ['webp', 'avif', 'jpeg', 'png', 'heif', 'tiff', 'raw', 'gif'];
// Priority: WebP first to avoid Chromium AVIF top-level-navigation download bug
// (Chrome/Edge fail to render AVIF on direct URL nav even with Content-Disposition: inline).
// Reverts the Issue #5 reorder. AVIF is still served when client explicitly accepts only AVIF.
const FORMAT_PRIORITY = ['webp', 'avif', 'jpeg', 'png', 'heif', 'tiff', 'raw', 'gif'];
const FORMAT_MAPPING = {
'image/webp': 'webp',
'image/avif': 'avif',
'image/jpeg': 'jpeg',
'image/jpg': 'jpeg',
'image/png': 'png',
'image/heif': 'heif',
'image/heic': 'heif',
'image/tiff': 'tiff',
'image/raw': 'raw',
'image/gif': 'gif'
};
const NON_ALPHA_FORMATS = ['jpeg'];
// Accept-header wildcard tokens that mean "any image type"
const WILDCARD_TOKENS = ['*/*', 'image/*'];
// User-Agent substrings that confirm WebP support.
// Verified support matrices:
// - Chrome 32+ (Jan 2014), Edge 18+, Firefox 65+, Opera 19+: WebP full support
// - Safari 14+ (macOS 11/iOS 14, Sep 2020): WebP full support
// - Mobile WebViews (Android Chrome, iOS WKWebView 14+): WebP full support
// References: https://caniuse.com/webp
const WEBP_CAPABLE_UA_PATTERNS = [
/Chrome\/\d+/i, // Chrome, Edge (Chromium), Opera, modern Android browsers
/Firefox\/(6[5-9]|[7-9]\d|\d{3,})/i, // Firefox 65+
/Version\/(1[4-9]|[2-9]\d|\d{3,})[\d.]*\s.*Safari\//i, // Safari 14+ desktop and iOS (Mobile token may appear between Version and Safari)
// Safari 14+ desktop and iOS (Mobile token may appear between Version and Safari)
// Safari 14+ (Version token, Safari trailing)
/CriOS\/\d+/i, // Chrome on iOS
/FxiOS\/\d+/i, // Firefox on iOS (uses iOS WebView, WebP support tied to OS)
/EdgiOS\/\d+/i // Edge on iOS
];
function isWebpCapableUserAgent(ua) {
if (!ua) return false;
for (var i = 0; i < WEBP_CAPABLE_UA_PATTERNS.length; i++) {
if (WEBP_CAPABLE_UA_PATTERNS[i].test(ua)) {
return true;
}
}
return false;
}
function normalizeAcceptHeader(acceptHeader, userAgent, excludeFormats) {
if (!acceptHeader) return null;
const mimeTypes = acceptHeader
.split(',')
.map(part => part.split(';')[0].trim().toLowerCase());
var supportedFormats = [];
var hasWildcard = false;
for (var i = 0; i < mimeTypes.length; i++) {
if (WILDCARD_TOKENS.indexOf(mimeTypes[i]) !== -1) {
hasWildcard = true;
continue;
}
if (FORMAT_MAPPING[mimeTypes[i]]) {
supportedFormats.push(FORMAT_MAPPING[mimeTypes[i]]);
}
}
// Issue #2: drop alpha-incompatible formats (e.g. JPEG) when source has alpha
if (excludeFormats && excludeFormats.length > 0) {
supportedFormats = supportedFormats.filter(function (fmt) {
return excludeFormats.indexOf(fmt) === -1;
});
}
// Specific MIME types win over wildcard
for (var j = 0; j < FORMAT_PRIORITY.length; j++) {
if (supportedFormats.indexOf(FORMAT_PRIORITY[j]) !== -1) {
return 'image/' + FORMAT_PRIORITY[j];
}
}
// Wildcard fallback: only set dit-accept if UA confirms WebP support.
// Unknown UAs fall through to null -> no dit-accept -> source format served (status quo).
if (hasWildcard && isWebpCapableUserAgent(userAgent)) {
return 'image/webp';
}
return null;
}
async function handler(event) {
var request = event.request;
var headers = request.headers;
console.log("DIT Function - Processing request:", JSON.stringify(event, null, 2));
try {
// Get header mapping configuration from KVS
const ditHostHeader = "dit-host";
const ditAcceptHeader = "dit-accept";
const ditDprHeader = "dit-dpr";
const ditViewportWidthHeader = "dit-viewport-width";
const ditOriginHeader = ""; // eg. dit-origin
const viewportBreakpoints = "320,480,768,1024,1200,1440,1920";
// Parse viewport breakpoints
const breakpoints = viewportBreakpoints
? viewportBreakpoints
.split(",")
.map(Number)
.sort((a, b) => a - b)
: [320, 480, 768, 1024, 1200, 1440, 1920];
// Normalize viewport width to nearest breakpoint and map to DIT header
if (headers["sec-ch-viewport-width"] && ditViewportWidthHeader) {
const viewportWidth = parseInt(headers["sec-ch-viewport-width"]["value"]);
let normalizedWidth = breakpoints[0]; // Default to smallest
for (let i = 0; i < breakpoints.length; i++) {
if (viewportWidth <= breakpoints[i]) {
normalizedWidth = breakpoints[i];
break;
}
if (i === breakpoints.length - 1) {
normalizedWidth = breakpoints[i]; // Use the largest if exceeds all
}
}
// Set normalized viewport width header
request.headers[ditViewportWidthHeader] = { value: normalizedWidth.toString() };
}
// Issue #2: detect alpha-capable source via URL extension to prevent
// transparent PNG/GIF/WebP being converted to JPEG (which loses alpha).
var excludeFormats = [];
var uri = request.uri ? request.uri.toLowerCase() : '';
if (uri.endsWith('.png') || uri.endsWith('.gif') || uri.endsWith('.webp')) {
excludeFormats = NON_ALPHA_FORMATS;
}
// Map standard headers to DIT headers for cache key optimization
if (headers["host"] && ditHostHeader) {
request.headers[ditHostHeader] = { value: headers["host"]["value"] };
}
// Only set dit-accept if format parameter is not present in query string
if (headers["accept"] && ditAcceptHeader && !(request.querystring && request.querystring.format)) {
const userAgent = headers["user-agent"] && headers["user-agent"]["value"];
const normalizedFormat = normalizeAcceptHeader(headers["accept"]["value"], userAgent, excludeFormats);
if (normalizedFormat) {
request.headers[ditAcceptHeader] = { value: normalizedFormat };
}
}
// Normalize DPR values to nearest tenth and cap at 5.0
if (headers["sec-ch-dpr"] && ditDprHeader) {
const dprValue = parseFloat(headers["sec-ch-dpr"]["value"]);
const normalizedDpr = Math.min(Math.round(dprValue * 10) / 10, 5.0);
request.headers[ditDprHeader] = { value: normalizedDpr.toString() };
}
// Customer-specific origin header mapping (placeholder for extension)
// Customers can extend this logic to set dit-origin based on their routing needs
if (ditOriginHeader) {
// Example: Set based on host or custom logic
// request.headers[ditOriginHeader] = { "value": "custom-origin-value" };
}
console.log("DIT Function - Processed headers:", JSON.stringify(request.headers, null, 2));
} catch (error) {
console.error("DIT Function - Error processing request:", error);
// Continue with original request on error
}
return request;
}