-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
321 lines (284 loc) · 10.6 KB
/
index.js
File metadata and controls
321 lines (284 loc) · 10.6 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import express from 'express';
const app = express();
const PORT = process.env.PORT || 3000;
const FETCH_TIMEOUT_MS = 10000;
// --- Helpers ---
// Patterns that identify non-public addresses — block these to prevent SSRF.
const PRIVATE_HOST_PATTERNS = [
/^localhost$/i,
/^127\./,
/^10\./,
/^192\.168\./,
/^172\.(1[6-9]|2\d|3[01])\./,
/^\[?::1\]?$/, // IPv6 loopback
/^\[?fc[0-9a-f]{2}:/i, // IPv6 unique-local (fc00::/7)
];
/**
* Returns { valid: true } for a URL that is safe to fetch, or
* { valid: false, reason: string } otherwise.
*
* Accepts any HTTPS URL whose hostname is not a private/loopback address,
* so Cloudinary CNAME and private-CDN hostnames all pass through.
*/
function validateFetchTarget(urlString) {
let parsed;
try {
parsed = new URL(urlString);
} catch {
return { valid: false, reason: 'Invalid URL — could not be parsed.' };
}
if (parsed.protocol !== 'https:') {
return { valid: false, reason: 'Only HTTPS URLs are supported.' };
}
const host = parsed.hostname;
if (PRIVATE_HOST_PATTERNS.some((p) => p.test(host))) {
return { valid: false, reason: 'Private, loopback, or link-local addresses are not allowed.' };
}
return { valid: true };
}
/**
* Constructs a Cloudinary delivery URL from its components.
*
* Supports three routing models:
*
* 1. Standard (default)
* https://res.cloudinary.com/{cloud_name}/{asset_type}/{delivery_type}/[transformation/]{public_id}
*
* 2. CNAME (custom_domain provided, private_cdn = false)
* https://{custom_domain}/{cloud_name}/{asset_type}/{delivery_type}/[transformation/]{public_id}
* The CNAME is mapped to res.cloudinary.com; the path is identical to standard.
*
* 3. Private CDN / subdomain delivery (private_cdn = true)
* No custom_domain → https://{cloud_name}-res.cloudinary.com/{asset_type}/{delivery_type}/[transformation/]{public_id}
* With custom_domain → https://{custom_domain}/{asset_type}/{delivery_type}/[transformation/]{public_id}
* The CDN handles cloud routing, so the cloud name is NOT in the path.
*/
function buildCloudinaryUrl(cloudName, assetType, deliveryType, transformation, publicId, customDomain, privateCdn) {
let origin;
if (privateCdn) {
// Private CDN / subdomain delivery — cloud name moves out of the path.
origin = customDomain
? `https://${customDomain}`
: `https://${encodeURIComponent(cloudName)}-res.cloudinary.com`;
} else {
// Standard or CNAME — cloud name stays in the path.
origin = customDomain
? `https://${customDomain}`
: 'https://res.cloudinary.com';
}
const segments = [origin];
if (!privateCdn) {
// Cloud name is part of the path for standard and CNAME delivery.
segments.push(encodeURIComponent(cloudName));
}
segments.push(encodeURIComponent(assetType));
segments.push(encodeURIComponent(deliveryType));
if (transformation && transformation.trim()) {
segments.push(transformation.trim());
}
// Public IDs may contain slashes and dots — preserve them as-is.
segments.push(publicId);
return segments.join('/');
}
/**
* Fetches only the response headers for a given URL (body is never read/buffered).
* Returns a structured result object.
*/
async function checkCloudinaryUrl(url) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
let response;
try {
response = await fetch(url, {
signal: controller.signal,
headers: { 'User-Agent': 'CloudinaryURLDebugger/1.0' },
});
} catch (err) {
clearTimeout(timer);
if (err.name === 'AbortError') {
return {
success: false,
http_status: null,
cld_error: null,
message: `Request timed out after ${FETCH_TIMEOUT_MS / 1000} seconds. The origin may be unreachable.`,
url,
};
}
return {
success: false,
http_status: null,
cld_error: null,
message: `Network error: ${err.message}`,
url,
};
} finally {
clearTimeout(timer);
}
// Cancel the body immediately — we only care about headers.
try { await response.body?.cancel(); } catch { /* ignore */ }
const cldError = response.headers.get('x-cld-error');
const status = response.status;
if (cldError) {
return {
success: false,
http_status: status,
cld_error: cldError,
message: `Cloudinary returned an error: ${cldError}`,
url,
};
}
if (response.ok) {
return {
success: true,
http_status: status,
cld_error: null,
message: 'The asset was delivered successfully. No Cloudinary errors were detected.',
url,
};
}
return {
success: false,
http_status: status,
cld_error: null,
message: `The request failed with HTTP ${status}. No x-cld-error header was present.`,
url,
};
}
// --- Routes ---
/**
* GET /debug-url
*
* Query params:
* url (required) — a Cloudinary delivery URL (res.cloudinary.com, a CNAME, or a private-CDN hostname)
*
* Examples:
* /debug-url?url=https://res.cloudinary.com/demo/image/upload/sample.jpg
* /debug-url?url=https://media.example.com/demo/image/upload/sample.jpg
* /debug-url?url=https://demo-res.cloudinary.com/image/upload/sample.jpg
*/
app.get('/debug-url', async (req, res) => {
const { url } = req.query;
if (!url) {
return res.status(400).json({
success: false,
error: 'Missing required query parameter: url',
usage: '/debug-url?url=https://res.cloudinary.com/{cloud_name}/...',
});
}
const check = validateFetchTarget(url);
if (!check.valid) {
return res.status(400).json({ success: false, error: check.reason });
}
const result = await checkCloudinaryUrl(url);
return res.json(result);
});
/**
* GET /debug-components
*
* Query params:
* cloud_name (required) — Cloudinary cloud name
* asset_type (required) — e.g. image, video, raw
* delivery_type (required) — e.g. upload, fetch, private, authenticated
* public_id (required) — public ID of the asset, including file extension if needed
* transformation (optional) — transformation string, e.g. w_300,c_fill
* custom_domain (optional) — custom hostname for CNAME or private-CDN delivery
* e.g. media.example.com
* private_cdn (optional) — set to "true" for private-CDN / subdomain delivery,
* where the cloud name is NOT part of the URL path.
* Without custom_domain this produces {cloud_name}-res.cloudinary.com.
* With custom_domain the CDN is assumed to handle cloud routing.
*
* Examples:
* Standard:
* /debug-components?cloud_name=demo&asset_type=image&delivery_type=upload&public_id=sample.jpg
* CNAME:
* /debug-components?cloud_name=demo&asset_type=image&delivery_type=upload&public_id=sample.jpg&custom_domain=media.example.com
* Private CDN (subdomain delivery, no custom domain):
* /debug-components?cloud_name=demo&asset_type=image&delivery_type=upload&public_id=sample.jpg&private_cdn=true
* Private CDN with custom domain:
* /debug-components?cloud_name=demo&asset_type=image&delivery_type=upload&public_id=sample.jpg&custom_domain=cdn.example.com&private_cdn=true
*/
app.get('/debug-components', async (req, res) => {
const {
cloud_name,
asset_type,
delivery_type,
transformation = '',
public_id,
custom_domain = '',
private_cdn = 'false',
} = req.query;
const missing = ['cloud_name', 'asset_type', 'delivery_type', 'public_id'].filter(
(p) => !req.query[p]
);
if (missing.length) {
return res.status(400).json({
success: false,
error: `Missing required query parameter(s): ${missing.join(', ')}`,
required: ['cloud_name', 'asset_type', 'delivery_type', 'public_id'],
optional: ['transformation', 'custom_domain', 'private_cdn'],
});
}
const isPrivateCdn = private_cdn === 'true' || private_cdn === '1';
if (custom_domain) {
// Validate the custom domain produces a safe HTTPS URL before building.
const domainCheck = validateFetchTarget(`https://${custom_domain}/`);
if (!domainCheck.valid) {
return res.status(400).json({ success: false, error: `Invalid custom_domain: ${domainCheck.reason}` });
}
}
const url = buildCloudinaryUrl(
cloud_name, asset_type, delivery_type, transformation, public_id, custom_domain, isPrivateCdn
);
const result = await checkCloudinaryUrl(url);
// Include the constructed URL so Fin can show it to the user.
result.constructed_url = url;
return res.json(result);
});
/**
* GET /
* API discovery — describes both endpoints for Fin's data connector schema.
*/
app.get('/', (_req, res) => {
res.json({
name: 'Cloudinary URL Debugger',
description:
'Checks Cloudinary delivery URLs and returns the x-cld-error response header to help diagnose delivery failures. The asset itself is never returned.',
endpoints: {
'/debug-url': {
method: 'GET',
description:
'Debug a full Cloudinary URL. Accepts res.cloudinary.com URLs, CNAME hostnames, and private-CDN hostnames.',
params: {
url: '(required) Full HTTPS Cloudinary delivery URL — res.cloudinary.com, a CNAME, or a private-CDN host',
},
},
'/debug-components': {
method: 'GET',
description:
'Construct a Cloudinary URL from its components and debug it. Supports standard, CNAME, and private-CDN delivery.',
params: {
cloud_name: '(required) Your Cloudinary cloud name',
asset_type: '(required) Asset type: image | video | raw',
delivery_type:
'(required) Delivery type: upload | fetch | private | authenticated | sprite | facebook | twitter | youtube | vimeo',
transformation:
'(optional) Transformation string, e.g. w_300,c_fill or f_auto,q_auto',
public_id:
'(required) Public ID of the asset, including file extension if not using f_auto',
custom_domain:
'(optional) Custom hostname for CNAME or private-CDN delivery, e.g. media.example.com',
private_cdn:
'(optional) Set to "true" for private-CDN / subdomain delivery where the cloud name is NOT in the URL path. Without custom_domain this produces a {cloud_name}-res.cloudinary.com URL.',
},
},
},
});
});
// Local dev — Vercel handles its own listener in production.
if (process.env.NODE_ENV !== 'production') {
app.listen(PORT, () => {
console.log(`Cloudinary URL Debugger listening on port ${PORT}`);
});
}
export default app;