-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathworker.js
More file actions
291 lines (256 loc) · 9.7 KB
/
Copy pathworker.js
File metadata and controls
291 lines (256 loc) · 9.7 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/**
* Cloudflare Worker - CORS Proxy for Cambridge Beer Festival Data API
*
* This worker proxies requests to data.cambridgebeerfestival.com and adds
* the necessary CORS headers to allow the web app to access the data.
*
* It also serves the festivals.json file which contains festival metadata
* and enables dynamic loading of festival drinks.
*
* Cache Strategy:
* - Uses Vary: Origin header to ensure CORS responses are cached per origin
* - CORS preflight cache (Access-Control-Max-Age) is reduced to 10 seconds for
* staging/preview environments for quick recovery from deployment issues
*/
// Import festivals data directly - copied from data/festivals.json during build
import festivalsData from './festivals.json';
const UPSTREAM_URL = 'https://data.cambridgebeerfestival.com';
// Cache control for festivals.json
// Use no-cache to ensure browsers revalidate on each request while still caching
// This ensures updates are visible immediately while allowing conditional requests
const FESTIVALS_CACHE_CONTROL = 'no-cache, must-revalidate';
// Allowed origins for CORS
const ALLOWED_ORIGINS = [
'https://richardthe3rd.github.io',
'https://cambeerfestival.app',
'https://staging.cambeerfestival.app',
'https://tunnel.cambeerfestival.app',
'http://localhost:8080',
'http://localhost:3000',
'http://127.0.0.1:8080',
];
export default {
async fetch(request, env, ctx) {
// Handle CORS preflight requests
if (request.method === 'OPTIONS') {
return handleCorsPreflight(request);
}
const url = new URL(request.url);
// Health check endpoint
if (url.pathname === '/health') {
return new Response(JSON.stringify({ status: 'ok' }), {
headers: {
'Content-Type': 'application/json; charset=utf-8',
...getCorsHeaders(request),
},
});
}
// Serve festivals.json directly from embedded data
if (url.pathname === '/festivals.json' || url.pathname === '/festivals') {
return new Response(JSON.stringify(festivalsData), {
status: 200,
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': FESTIVALS_CACHE_CONTROL,
...getCorsHeaders(request),
},
});
}
// Handle dynamic available_beverage_types.json endpoint
// Pattern: /{festivalId}/available_beverage_types.json
const availableTypesMatch = url.pathname.match(/^\/([^\/]+)\/available_beverage_types\.json$/);
if (availableTypesMatch) {
return handleAvailableBeverageTypes(availableTypesMatch[1], request);
}
// Proxy the request to the upstream API
const upstreamUrl = UPSTREAM_URL + url.pathname + url.search;
try {
const response = await fetch(upstreamUrl, {
method: request.method,
headers: {
'User-Agent': 'Cambridge-Beer-Festival-App-Proxy/1.0',
},
});
// Clone the response and add CORS headers
const newHeaders = new Headers(response.headers);
setCorsHeaders(newHeaders, request);
// Ensure JSON responses explicitly declare UTF-8 encoding
// This prevents mojibake when non-ASCII characters (é, ö, ä, ñ) are present
const contentType = newHeaders.get('Content-Type');
if (contentType && contentType.includes('application/json') && !contentType.includes('charset')) {
newHeaders.set('Content-Type', 'application/json; charset=utf-8');
}
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders,
});
} catch (error) {
return new Response(JSON.stringify({ error: 'Proxy error', message: error.message }), {
status: 502,
headers: {
'Content-Type': 'application/json; charset=utf-8',
...getCorsHeaders(request),
},
});
}
},
};
/**
* Dynamically discovers available beverage types for a festival
* by fetching the directory listing from the upstream API
*
* @param {string} festivalId - The festival ID (e.g., 'cbf2025', 'cbfw2025')
* @param {Request} request - The original request for CORS handling
* @returns {Response} JSON response with available beverage types
*/
async function handleAvailableBeverageTypes(festivalId, request) {
try {
// Fetch the directory listing for this festival
const upstreamUrl = `${UPSTREAM_URL}/${festivalId}/`;
const response = await fetch(upstreamUrl, {
headers: {
'User-Agent': 'Cambridge-Beer-Festival-App-Proxy/1.0',
},
});
if (!response.ok) {
return new Response(JSON.stringify({
error: 'Festival not found',
festival_id: festivalId,
}), {
status: 404,
headers: {
'Content-Type': 'application/json; charset=utf-8',
...getCorsHeaders(request),
},
});
}
// Parse the HTML directory listing to find .json files
const html = await response.text();
const beverageTypes = parseDirectoryListingForBeverageTypes(html);
// Return the list of available beverage types
return new Response(JSON.stringify({
festival_id: festivalId,
available_beverage_types: beverageTypes,
timestamp: new Date().toISOString(),
}), {
status: 200,
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'public, max-age=3600', // Cache for 1 hour
...getCorsHeaders(request),
},
});
} catch (error) {
return new Response(JSON.stringify({
error: 'Failed to fetch beverage types',
message: error.message,
}), {
status: 500,
headers: {
'Content-Type': 'application/json; charset=utf-8',
...getCorsHeaders(request),
},
});
}
}
/**
* Parses an Apache-style directory listing HTML to extract beverage type JSON files
*
* @param {string} html - The HTML content of the directory listing
* @returns {string[]} Array of beverage type names (without .json extension)
*/
function parseDirectoryListingForBeverageTypes(html) {
const beverageTypes = [];
// Match href attributes that point to .json files
// Regex pattern: <a href="filename.json">
const jsonFilePattern = /<a href="([^"]+\.json)"/gi;
let match;
while ((match = jsonFilePattern.exec(html)) !== null) {
const filename = match[1];
// Skip the available_beverage_types.json itself to avoid recursion
if (filename === 'available_beverage_types.json') {
continue;
}
// Remove .json extension to get the beverage type name
const beverageType = filename.replace(/\.json$/, '');
beverageTypes.push(beverageType);
}
// Sort alphabetically for consistency
return beverageTypes.sort();
}
function handleCorsPreflight(request) {
const origin = request.headers.get('Origin') || '';
// Set shorter CORS preflight cache for staging/preview environments
// to prevent stale CORS responses after deployments
let maxAge = '300'; // 5 minutes for production
if (origin.endsWith('.staging-cambeerfestival.pages.dev') ||
origin.endsWith('.cambeerfestival.pages.dev') ||
origin === 'https://staging.cambeerfestival.app' ||
origin.endsWith('.trycloudflare.com') ||
origin.startsWith('http://localhost') ||
origin.startsWith('http://127.0.0.1')) {
maxAge = '10'; // 10 seconds for development/staging
}
return new Response(null, {
status: 204,
headers: {
...getCorsHeaders(request),
'Access-Control-Allow-Methods': 'GET, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': maxAge,
},
});
}
function getCorsHeaders(request) {
const origin = request.headers.get('Origin') || '';
// Allow listed origins (exact match)
if (ALLOWED_ORIGINS.includes(origin)) {
return {
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Credentials': 'true',
'Vary': 'Origin', // Tell caches to key by Origin header
};
}
// Allow Cloudflare Pages preview URLs (*.cambeerfestival.pages.dev)
// This includes staging (main.cambeerfestival.pages.dev) and PR previews
// Security note: This wildcard is safe because Cloudflare controls the .pages.dev
// namespace. Only our cambeerfestival project can create subdomains under
// cambeerfestival.pages.dev, preventing malicious domains from matching this pattern.
if (origin.endsWith('.cambeerfestival.pages.dev')) {
return {
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Credentials': 'true',
'Vary': 'Origin', // Tell caches to key by Origin header
};
}
// Allow Cloudflare Pages staging preview URLs (*.staging-cambeerfestival.pages.dev)
// This includes branch-based staging deployments
// Security note: Same as above - Cloudflare controls the .pages.dev namespace
if (origin.endsWith('.staging-cambeerfestival.pages.dev')) {
return {
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Credentials': 'true',
'Vary': 'Origin', // Tell caches to key by Origin header
};
}
// Allow Cloudflare Tunnel quick tunnels (*.trycloudflare.com)
// Used for local development with cloudflared tunnel
// Security note: These are temporary development tunnels controlled by Cloudflare.
// Only enable this in development/staging workers, not production.
if (origin.endsWith('.trycloudflare.com')) {
return {
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Credentials': 'true',
'Vary': 'Origin', // Tell caches to key by Origin header
};
}
// Reject all other origins by not including CORS headers
return {};
}
function setCorsHeaders(headers, request) {
const corsHeaders = getCorsHeaders(request);
for (const [key, value] of Object.entries(corsHeaders)) {
headers.set(key, value);
}
}