-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.js
More file actions
168 lines (155 loc) · 6.05 KB
/
Copy pathproxy.js
File metadata and controls
168 lines (155 loc) · 6.05 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
#!/usr/bin/env node
/**
* Minimal local relay for the SWOT Water Level Explorer.
*
* Only needed if your browser reports a CORS error when downloading granules
* directly from PO.DAAC. Run this on your own machine, tick "Route downloads
* through local proxy" in the page, and leave the proxy URL as the default
* (http://localhost:8787/).
*
* DESIGN: this relay holds no credentials by default — it forwards whatever
* Authorization header the browser sends (i.e. YOUR token, pasted into the
* page's token field), and just adds the CORS headers a browser needs plus
* NASA-host allowlisting. No environment variable is required for normal use.
*
* OPTIONAL: set EDL_TOKEN as a fallback (used only if the browser doesn't
* send its own Authorization header). Not needed by default.
*
* Usage:
* node proxy.js
* EDL_TOKEN=fallback_token node proxy.js (optional)
*
* No dependencies — uses only Node's built-in http/https modules.
*/
const http = require("http");
const https = require("https");
const { URL } = require("url");
const PORT = process.env.PORT || 8787;
const FALLBACK_TOKEN = process.env.EDL_TOKEN || "";
// Only these hosts (or subdomains of them) can be relayed to — stops this
// relay being used as a general-purpose open CORS proxy for other sites.
const ALLOWED_HOSTS = ["earthdata.nasa.gov", "nasa.gov", "proj.org"]; // proj.org: DVR90 datum grid, public data
function isAllowedHost(hostname) {
return ALLOWED_HOSTS.some((h) => hostname === h || hostname.endsWith("." + h));
}
// Only these hosts get the Authorization/bearer-token treatment. proj.org is
// a public, unauthenticated resource — forwarding an unrelated Earthdata
// token to it can get the request rejected by a host that doesn't expect it.
const NASA_HOSTS = ["earthdata.nasa.gov", "nasa.gov"];
function isNasaHost(hostname) {
return NASA_HOSTS.some((h) => hostname === h || hostname.endsWith("." + h));
}
if (FALLBACK_TOKEN) {
console.log("EDL_TOKEN fallback is set — used only for requests that don't supply their own token.");
}
const server = http.createServer((req, res) => {
// CORS preflight + headers for every response
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
// Without this, the browser's fetch() can't read Content-Length on a
// cross-origin response, so the page can't show a real progress %.
res.setHeader("Access-Control-Expose-Headers", "Content-Length, Content-Type");
if (req.method === "OPTIONS") {
res.writeHead(204);
res.end();
return;
}
const reqUrl = new URL(req.url, `http://localhost:${PORT}`);
if (reqUrl.pathname !== "/fetch") {
res.writeHead(404);
res.end("Not found. Use /fetch?u=<encoded target url>");
return;
}
const target = reqUrl.searchParams.get("u");
if (!target) {
res.writeHead(400);
res.end("Missing ?u= target URL");
return;
}
let targetUrl;
try {
targetUrl = new URL(target);
} catch (e) {
res.writeHead(400);
res.end("Malformed target URL.");
return;
}
if (!isAllowedHost(targetUrl.hostname)) {
res.writeHead(403);
res.end(`Refusing to relay to "${targetUrl.hostname}" — only NASA/Earthdata/PROJ hosts are allowed.`);
return;
}
if (!isNasaHost(targetUrl.hostname)) {
// Public, unauthenticated resource (e.g. the DVR90 grid) — no auth
// header at all, regardless of what the browser attached to this
// relay request.
console.log("Relaying (no auth):", target);
fetchThroughNoAuth(target, res, 0);
return;
}
const authHeader = req.headers["authorization"] || (FALLBACK_TOKEN ? `Bearer ${FALLBACK_TOKEN}` : null);
if (!authHeader) {
res.writeHead(401);
res.end("No Earthdata token provided. Paste your own token into the page's token field.");
return;
}
console.log("Relaying:", target);
fetchThrough(target, authHeader, res, 0);
});
function fetchThrough(targetUrl, authHeader, res, redirectCount) {
if (redirectCount > 5) {
res.writeHead(508);
res.end("Too many redirects");
return;
}
const u = new URL(targetUrl);
const client = u.protocol === "http:" ? http : https;
const upstreamReq = client.get(
u,
{ headers: { Authorization: authHeader } },
(upstreamRes) => {
if ([301, 302, 303, 307, 308].includes(upstreamRes.statusCode) && upstreamRes.headers.location) {
// NASA's distribution layer commonly redirects to a signed S3 URL;
// don't forward the bearer token to that second hop.
fetchThroughNoAuth(upstreamRes.headers.location, res, redirectCount + 1);
return;
}
res.writeHead(upstreamRes.statusCode, {
"Content-Type": upstreamRes.headers["content-type"] || "application/octet-stream",
"Content-Length": upstreamRes.headers["content-length"],
"Access-Control-Allow-Origin": "*",
"Access-Control-Expose-Headers": "Content-Length, Content-Type",
});
upstreamRes.pipe(res);
}
);
upstreamReq.on("error", (err) => {
res.writeHead(502);
res.end("Upstream error: " + err.message);
});
}
function fetchThroughNoAuth(targetUrl, res, redirectCount) {
const u = new URL(targetUrl);
const client = u.protocol === "http:" ? http : https;
const upstreamReq = client.get(u, (upstreamRes) => {
if ([301, 302, 303, 307, 308].includes(upstreamRes.statusCode) && upstreamRes.headers.location) {
fetchThroughNoAuth(upstreamRes.headers.location, res, redirectCount + 1);
return;
}
res.writeHead(upstreamRes.statusCode, {
"Content-Type": upstreamRes.headers["content-type"] || "application/octet-stream",
"Content-Length": upstreamRes.headers["content-length"],
"Access-Control-Allow-Origin": "*",
"Access-Control-Expose-Headers": "Content-Length, Content-Type",
});
upstreamRes.pipe(res);
});
upstreamReq.on("error", (err) => {
res.writeHead(502);
res.end("Upstream error: " + err.message);
});
}
server.listen(PORT, () => {
console.log(`Relay listening on http://localhost:${PORT} (target: /fetch?u=<url>)`);
});