Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
611 lines (559 loc) · 20 KB
/
Copy pathserver.js
File metadata and controls
611 lines (559 loc) · 20 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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
// Compaxy - server only.
//
// There is no frontend and no build step: this process is the whole proxy. Ask
// it for a site and it fetches, rewrites and serves that site:
//
// http://127.0.0.1:5201/?url=https://example.com/
//
// That address is the whole interface, so the proxy drops straight into an
// iframe on any page:
//
// <iframe src="http://127.0.0.1:5201/?url=https://example.com/"></iframe>
//
// The ?url= entry point resolves the target and hands the browser a path-form
// address (/proxy/<scheme>/<host>/<path>). That extra hop is what keeps the
// proxy correct: the browser's own URL keeps the upstream site's real path, so
// relative references, forms and client-side routers resolve exactly as they do
// on the original site, and no rewrite has to guess what a URL meant.
import http from "node:http";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
normalizeTargetUrl,
toProxyUrl,
fromProxyRequest,
PROXY_PREFIX
} from "./src/urls.js";
import { handleProxy } from "./src/proxy.js";
import { handleUpgrade } from "./src/websocket.js";
import { stats as cacheStats } from "./src/cache.js";
import { blockedMessageForUrl, renderBlockedPage } from "./src/blocklist.js";
// PORT is only honoured when it is an actual port: environments that set PORT
// to an empty string or 0 ("pick anything") must still land on the default,
// because nothing could discover the random one.
const requestedPort = Number(process.env.PORT);
const usingEnvPort =
Number.isInteger(requestedPort) && requestedPort > 0;
const port = usingEnvPort ? requestedPort : 5201;
// Platforms such as Render inject PORT and probe 0.0.0.0 for a listening
// socket, so once a usable port comes from the environment we must bind every
// interface; a loopback-only bind is invisible to that probe and the deploy
// never finalizes. A plain local run (no usable PORT) stays on loopback.
const host =
process.env.HOST || (usingEnvPort ? "0.0.0.0" : "127.0.0.1");
const accessLog = process.env.COMPAXY_LOG === "1";
function logAccess(req, res, target) {
if (!accessLog) return;
res.on("finish", () => console.log(`${req.method} ${res.statusCode} ${target}`));
}
function sendText(res, status, body, type = "text/plain; charset=utf-8") {
res.writeHead(status, {
"content-type": type,
"content-length": Buffer.byteLength(body),
"cache-control": "no-store"
});
res.end(body);
}
function sendJson(res, status, value) {
sendText(res, status, JSON.stringify(value), "application/json; charset=utf-8");
}
// The brand artwork sits next to this file and is served by name index only, so
// no part of the request path ever reaches the filesystem. Each file is read
// once and held: the background alone is ~414 KB.
const PROJECT_ROOT = path.dirname(fileURLToPath(import.meta.url));
const ASSET_FILES = new Map([
["/background.png", "background.png"],
["/logo.png", "logo.png"],
["/favicon.png", "favicon.png"]
]);
const assetBodies = new Map();
function assetBody(file) {
if (!assetBodies.has(file)) {
try {
assetBodies.set(file, fs.readFileSync(path.join(PROJECT_ROOT, file)));
} catch (error) {
console.error(`Brand asset ${file} is missing: ${error.message}`);
return null;
}
}
return assetBodies.get(file);
}
// A blocked domain gets its configured message, not a generic error, so the
// operator can explain why the site is unavailable.
function sendBlocked(res, message) {
sendText(res, 403, renderBlockedPage(message), "text/html; charset=utf-8");
}
function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, (char) => ({
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
})[char]);
}
// The default screen: the brand splash, then the one field this proxy exists
// for. Everything is sized in vh so the stack shrinks with the window and the
// cards always clear the wordmark baked into background.png.
function entryPage(host) {
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Plutonium Compaxy</title>
<meta name="description" content="A server-side fetch-and-rewrite web proxy. Ask for a site with ?url= and it fetches, rewrites and serves it." />
<meta name="theme-color" content="#050508" />
<meta property="og:title" content="Plutonium Compaxy" />
<meta property="og:description" content="A server-side fetch-and-rewrite web proxy." />
<meta property="og:image" content="/background.png" />
<link rel="icon" type="image/png" href="/favicon.png" />
<link rel="apple-touch-icon" href="/favicon.png" />
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--text: #f5f5f7;
--muted: #9b9ba4;
--accent: #e8175d;
--ok: #3ecf8e;
--warn: #f5a524;
--err: #f2555a;
--card: rgba(6, 6, 10, 0.72);
--line: rgba(255, 255, 255, 0.10);
--mono: ui-monospace, "SF Mono", "Fira Code", Menlo, monospace;
}
html { background: #000; }
body {
min-height: 100%;
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
line-height: 1.6;
-webkit-font-smoothing: antialiased;
text-rendering: optimizeLegibility;
}
/* Fixed so the artwork stays put while short screens scroll; bottom-anchored
so the brand wordmark always sits on the bottom edge, never half-cropped.
Untinted: the image is drawn exactly as supplied. */
.backdrop {
position: fixed;
inset: 0;
z-index: -2;
background: #000 url("/background.png") center bottom / cover no-repeat;
}
.stage {
min-height: 100svh;
display: grid;
align-content: safe center;
justify-items: center;
gap: clamp(7px, 1vh, 11px);
/* background.png is exactly 2:1 and its Plutonium wordmark fills the lower
third. Under cover the image is max(50vw, 100svh) tall and the artwork
starts 34.8% of that above the bottom edge, so that band is reserved:
the cards sit above the brand instead of on top of it. */
padding:
clamp(28px, 5vh, 74px)
clamp(18px, 2vw, 28px)
calc(max(50vw, 100svh) * 0.348 + 4px)
clamp(18px, 2vw, 28px);
}
.card {
width: min(100%, 1160px);
padding: clamp(10px, 1.7vh, 20px) clamp(12px, 2.2vh, 24px);
background: var(--card);
border: 1px solid var(--line);
border-radius: 22px;
backdrop-filter: blur(22px) saturate(130%);
-webkit-backdrop-filter: blur(22px) saturate(130%);
box-shadow:
0 30px 80px -32px rgba(0, 0, 0, 0.95),
inset 0 1px 0 rgba(255, 255, 255, 0.06);
}
/* ---- 1. title ---------------------------------------------------------- */
.card--title {
display: flex;
align-items: center;
justify-content: center;
gap: clamp(14px, 1.8vw, 24px);
}
.card__mark {
flex: none;
width: clamp(38px, 5.4vh, 60px);
height: auto;
filter: drop-shadow(0 0 20px rgba(232, 23, 93, 0.3));
}
.card__eyebrow {
font-family: var(--mono);
font-size: clamp(0.76rem, 1.8vh, 0.98rem);
letter-spacing: 0.14em;
text-transform: uppercase;
color: rgba(232, 23, 93, 0.95);
margin-bottom: clamp(2px, 0.7vh, 6px);
}
.card__title {
font-size: clamp(1.5rem, 5.2vh, 3.2rem);
font-weight: 650;
letter-spacing: -0.03em;
line-height: 1.05;
}
/* ---- 2. search --------------------------------------------------------- */
.search__label {
display: block;
font-family: var(--mono);
font-size: clamp(0.6rem, 1.35vh, 0.7rem);
letter-spacing: 0.13em;
text-transform: uppercase;
color: rgba(255, 255, 255, 0.34);
margin-bottom: clamp(5px, 1vh, 9px);
}
.search__row { display: flex; gap: clamp(8px, 1vw, 12px); }
.search__input {
flex: 1 1 auto;
min-width: 0;
padding: clamp(9px, 1.6vh, 15px) clamp(12px, 1.2vw, 18px);
font: inherit;
font-size: clamp(0.84rem, 1.9vh, 1rem);
color: var(--text);
background: rgba(0, 0, 0, 0.45);
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 14px;
outline: none;
transition: border-color 0.15s ease, box-shadow 0.15s ease;
}
.search__input::placeholder { color: rgba(255, 255, 255, 0.28); }
.search__input:focus-visible {
border-color: rgba(232, 23, 93, 0.75);
box-shadow: 0 0 0 4px rgba(232, 23, 93, 0.14);
}
.search__go {
flex: none;
padding: 0 clamp(16px, 2vw, 26px);
font: inherit;
font-size: clamp(0.84rem, 1.9vh, 1rem);
font-weight: 600;
color: #fff;
cursor: pointer;
background: linear-gradient(180deg, #ef2a6b, #cf0f4e);
border: 0;
border-radius: 14px;
box-shadow: 0 12px 30px -14px rgba(232, 23, 93, 0.9);
transition: filter 0.15s ease, transform 0.1s ease;
}
.search__go:hover { filter: brightness(1.08); }
.search__go:active { transform: translateY(1px); }
.search__go:focus-visible {
outline: 2px solid rgba(232, 23, 93, 0.9);
outline-offset: 3px;
}
/* ---- 3. status -------------------------------------------------------- */
.status__head {
display: flex;
align-items: center;
gap: 11px;
}
.status__dot {
width: clamp(7px, 1.1vh, 9px);
height: clamp(7px, 1.1vh, 9px);
flex: none;
border-radius: 50%;
background: var(--warn);
box-shadow: 0 0 0 5px rgba(245, 165, 36, 0.14);
}
.status__state {
font-size: clamp(0.92rem, 2vh, 1.22rem);
font-weight: 600;
letter-spacing: -0.01em;
}
.status__latency {
font-family: var(--mono);
font-size: 0.76rem;
color: var(--muted);
}
.status__latency:empty { display: none; }
.status__link {
margin-left: auto;
font-family: var(--mono);
font-size: 0.74rem;
color: rgba(255, 255, 255, 0.34);
text-decoration: none;
transition: color 0.15s ease;
}
.status__link:hover,
.status__link:focus-visible { color: var(--accent); }
.status[data-state="ok"] .status__dot {
background: var(--ok);
box-shadow: 0 0 0 5px rgba(62, 207, 142, 0.16);
animation: pulse 2.6s ease-in-out infinite;
}
.status[data-state="error"] .status__dot {
background: var(--err);
box-shadow: 0 0 0 5px rgba(242, 85, 90, 0.16);
}
@keyframes pulse {
0%, 100% { box-shadow: 0 0 0 5px rgba(62, 207, 142, 0.16); }
50% { box-shadow: 0 0 0 8px rgba(62, 207, 142, 0.05); }
}
@media (prefers-reduced-motion: reduce) {
.status[data-state="ok"] .status__dot { animation: none; }
}
.checks {
display: grid;
/* One column per check, however many /healthz reports: two fill the row,
more wrap instead of leaving a bare track. */
grid-template-columns: repeat(auto-fit, minmax(min(100%, 140px), 1fr));
gap: clamp(4px, 0.9vh, 8px) 26px;
margin-top: clamp(7px, 1.5vh, 12px);
padding-top: clamp(7px, 1.4vh, 11px);
border-top: 1px solid rgba(255, 255, 255, 0.07);
list-style: none;
}
.checks[hidden] { display: none; }
.checks li {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
font-size: clamp(0.72rem, 1.6vh, 0.84rem);
}
.checks__name { color: rgba(245, 245, 247, 0.74); }
.checks__val {
font-family: var(--mono);
font-size: 0.72rem;
color: var(--muted);
white-space: nowrap;
}
.checks li[data-ok="true"] .checks__val { color: rgba(62, 207, 142, 0.92); }
.checks li[data-ok="false"] .checks__val { color: rgba(242, 85, 90, 0.95); }
.status__foot {
margin-top: clamp(6px, 1.2vh, 10px);
font-family: var(--mono);
font-size: clamp(0.6rem, 1.25vh, 0.68rem);
color: rgba(255, 255, 255, 0.3);
}
/* ---- 4. description --------------------------------------------------- */
.card__desc {
max-width: 68ch;
margin-inline: auto;
text-align: center;
color: var(--muted);
font-size: clamp(0.8rem, 1.7vh, 0.96rem);
line-height: 1.65;
}
.card__desc strong { color: rgba(245, 245, 247, 0.88); font-weight: 550; }
/* Short, wide windows (a 768p laptop minus browser chrome): cover would blow
the artwork up to nearly half the height, so scale the image by height
instead and reserve the correspondingly smaller band. */
@media (max-height: 700px) {
.backdrop {
background-size: auto 72%;
background-position: left bottom;
}
.stage { padding-bottom: calc(72vh * 0.348 + 8px); }
}
/* Portrait phones: cover would blow the wordmark up to a third of the screen
and crop it, so size the image by width instead and reserve 17.4vw. */
@media (max-width: 700px) {
.backdrop {
background-size: 100% auto;
background-position: left bottom;
}
.stage { padding-bottom: calc(50vw * 0.348 + 8px); }
/* vh-driven type would run enormous on a tall phone, so scale by width. */
.card__title { font-size: clamp(1.5rem, 7vw, 2.3rem); }
.card__eyebrow { font-size: clamp(0.62rem, 2.7vw, 0.82rem); letter-spacing: 0.1em; }
.search__row { flex-wrap: wrap; }
.search__go { flex: 1 1 auto; min-height: 44px; }
}
</style>
</head>
<body>
<div class="backdrop" aria-hidden="true"></div>
<main class="stage">
<section class="card card--title">
<img class="card__mark" src="/logo.png" alt="" width="58" height="58" />
<div>
<p class="card__eyebrow">${escapeHtml(host)}</p>
<h1 class="card__title">Plutonium Compaxy</h1>
</div>
</section>
<section class="card card--search">
<form onsubmit="location.replace('/?url=' + encodeURIComponent(this.q.value)); return false">
<label class="search__label" for="target">Proxy a site</label>
<div class="search__row">
<input class="search__input" id="target" name="q" type="text"
placeholder="https://example.com" autofocus required
autocomplete="off" spellcheck="false" />
<button class="search__go" type="submit">Go</button>
</div>
</form>
</section>
<section class="card status" data-state="checking" role="status" aria-live="polite">
<div class="status__head">
<span class="status__dot" aria-hidden="true"></span>
<span class="status__state">Checking status</span>
<span class="status__latency"></span>
<a class="status__link" href="/healthz">/healthz</a>
</div>
<ul class="checks" hidden></ul>
<p class="status__foot">Contacting the proxy\u2026</p>
</section>
<noscript><style>.status { display: none; }</style></noscript>
<section class="card card--desc">
<p class="card__desc">
Compaxy is a server-side web proxy. Supply a site with
<strong>?url=<address></strong> and it fetches, rewrites and serves that page,
mapping every link, asset and redirect back onto its own origin. Enter an
address above, or point an iframe at the same route. There is no frontend and
no build step; the proxy process is the whole service.
</p>
</section>
</main>
<script>
(function () {
var card = document.querySelector('.status');
var state = card.querySelector('.status__state');
var latency = card.querySelector('.status__latency');
var list = card.querySelector('.checks');
var foot = card.querySelector('.status__foot');
var started = Date.now();
function settle(mode, label, ms, body) {
card.dataset.state = mode;
state.textContent = label;
latency.textContent = ms ? Math.max(1, Math.round(ms)) + ' ms' : '';
if (body && Array.isArray(body.components) && body.components.length) {
list.innerHTML = body.components.map(function (c) {
return '<li data-ok="' + (c.ok ? 'true' : 'false') + '">' +
'<span class="checks__name">' + c.name + '</span>' +
'<span class="checks__val">' + (c.ok ? 'ok' : 'down') + '</span>' +
'</li>';
}).join('');
list.hidden = false;
}
var at = new Date();
foot.textContent = 'Checked ' + at.toISOString().slice(11, 19) + ' UTC · GET /healthz';
}
fetch('/healthz', { cache: 'no-store', headers: { Accept: 'application/json' } })
.then(function (res) {
var ms = Date.now() - started;
return res.json().catch(function () { return null; }).then(function (body) {
if (!body) return settle('error', 'No response', ms, null);
settle(body.status === 'ok' ? 'ok' : 'error',
body.status === 'ok' ? 'Operational' : 'Degraded', ms, body);
});
})
.catch(function () {
card.dataset.state = 'error';
state.textContent = 'Unreachable';
latency.textContent = '';
foot.textContent = 'No response from /healthz';
});
})();
</script>
</body>
</html>`;
}
const server = http.createServer(async (req, res) => {
const requestUrl = new URL(req.url, `http://${req.headers.host}`);
try {
// Brand artwork for the entry screen, addressed by name only.
const assetFile = ASSET_FILES.get(requestUrl.pathname);
if (assetFile) {
const body = assetBody(assetFile);
if (!body) return sendText(res, 500, "Brand asset unavailable.\n");
res.writeHead(200, {
"content-type": "image/png",
"content-length": body.length,
"cache-control": "public, max-age=86400"
});
return res.end(body);
}
// What the entry screen's status card asks: the proxy answering this very
// request, and the response cache still inside its budget.
if (requestUrl.pathname === "/healthz") {
const cache = cacheStats();
return sendJson(res, 200, {
status: "ok",
uptime: Math.round(process.uptime()),
components: [
{ name: "proxy", ok: true },
{ name: "cache", ok: cache.bytes <= cache.budget }
],
cache
});
}
// Entry point: /?url=<address>. Resolve it, then serve the site from its
// own mirrored path so the browser's URL stays meaningful.
if (requestUrl.pathname === "/") {
if (!requestUrl.search) {
return sendText(
res,
200,
entryPage(requestUrl.host),
"text/html; charset=utf-8"
);
}
const raw = requestUrl.searchParams.get("url");
if (raw === null) {
return sendText(res, 400, "Missing ?url=<address>.\n");
}
let target;
try {
target = normalizeTargetUrl(raw);
} catch (error) {
return sendText(res, 400, `Cannot proxy that: ${error.message}\n`);
}
const blocked = blockedMessageForUrl(target);
if (blocked) {
return sendBlocked(res, blocked);
}
res.writeHead(302, { location: toProxyUrl(target), "cache-control": "no-store" });
return res.end();
}
if (requestUrl.pathname.startsWith(PROXY_PREFIX)) {
let target;
try {
target = fromProxyRequest(requestUrl.pathname, requestUrl.search);
} catch (error) {
return sendText(res, 400, error.message);
}
logAccess(req, res, target);
await handleProxy(req, res, target);
return;
}
sendText(res, 404, "Not found. Use /?url=<address> to proxy a site.\n");
} catch (error) {
if (!res.headersSent) {
sendText(res, 500, `Server error: ${error.message}\n`);
} else {
res.destroy();
}
}
});
server.on("upgrade", (req, socket, head) => {
// An upgrade hijacks this socket out of Node's HTTP machinery, so nothing
// else is listening for its errors. A client that drops mid-handshake must
// end its own connection only - never the process that serves every tab.
socket.on("error", () => socket.destroy());
const requestUrl = new URL(req.url, `http://${req.headers.host}`);
if (!requestUrl.pathname.startsWith(PROXY_PREFIX)) {
socket.destroy();
return;
}
let target;
try {
target = fromProxyRequest(requestUrl.pathname, requestUrl.search);
} catch {
socket.destroy();
return;
}
logAccess(req, { on() {} }, target);
handleUpgrade(req, socket, head, target).catch(() => socket.destroy());
});
server.on("error", (error) => {
console.error(`Server failed to start: ${error.message}`);
process.exit(1);
});
server.listen(port, host, () => {
console.log(`Compaxy running at http://${host}:${port}`);
console.log(`Embed it: <iframe src="http://${host}:${port}/?url=https://example.com/"></iframe>`);
});