Spaces:
Sleeping

node-edge-2 / server.mjs
Leogron777
relay
4c119aa
Raw History Blame Contribute Delete
6.3 kB
/**
* server.mjs — Nucleus deployable RAM-only onion relay for FREE PaaS hosts.
*
* Self-contained single file. Mirrors the wire format of web/relay/relay.mjs and
* web/src/core/transport/onion.ts EXACTLY. It peels ONE onion layer per packet,
* then either forwards the inner blob to the next relay or — at the final hop —
* broadcasts it (padded to a constant 64 KiB) to its connected clients, who
* trial-decrypt. NOTHING is ever written to disk, and there is NO per-packet
* logging. The only state is a small bounded in-RAM replay cache.
*
* Difference from web/relay/relay.mjs: the WebSocket server is attached to an
* HTTP server that answers GET /health with 200 "ok" on the SAME port. That lets
* (a) the PaaS platform's health check pass, and
* (b) a free keep-alive pinger (cron-job.org / UptimeRobot) hit /health to keep
* a sleep-prone free instance awake,
* while the platform terminates TLS and proxies the WebSocket upgrade — so the
* app connects via wss://<your-host> with no certificate work on your side.
*
* Run:
* RELAY_PRIVATE_KEY=<64 hex chars> PORT=8080 node server.mjs
* - PORT: the platform injects its own $PORT (Render, Back4app, …); we honor it.
* Hugging Face Spaces expect 7860. Defaults to 8080 locally.
* - RELAY_PRIVATE_KEY: THIS relay's 32-byte X25519 private key (64 hex). Keep it
* ONLY in this host's environment. Its matching PUBLIC key goes in the app's
* relay-pool config. Generate a pair with web/relay/keygen.mjs.
*/
import http from 'node:http';
import { WebSocketServer, WebSocket } from 'ws';
import { x25519 } from '@noble/curves/ed25519';
import { hkdf } from '@noble/hashes/hkdf';
import { sha256 } from '@noble/hashes/sha256';
import { gcm } from '@noble/ciphers/aes';
import { randomBytes, bytesToHex } from '@noble/hashes/utils';
const MAGIC = Uint8Array.from([0x4e, 0x55, 0x43, 0x00]); // "NUC\0"
const SEEN_TTL_MS = 30_000; // replay window; legit retries re-wrap with fresh ephemerals
const SEEN_MAX = 8192; // bounded RAM, nothing on disk
const ONION_INFO = new TextEncoder().encode('nucleus-onion-v1');
const PACKET_TARGET = 65536; // constant broadcast size (size-hiding)
function unwrapLayer(packet, priv) {
let o = 0;
for (let i = 0; i < 4; i++) if (packet[o + i] !== MAGIC[i]) throw new Error('bad magic');
o += 4;
if (packet[o++] !== 0x01) throw new Error('bad version');
const dv = new DataView(packet.buffer, packet.byteOffset);
const hopLen = dv.getUint16(o, false); o += 2;
const nextHop = new TextDecoder().decode(packet.subarray(o, o + hopLen)); o += hopLen;
const ephemeralPub = packet.subarray(o, o + 32); o += 32;
o += 16; // qnnToken (relay-visible routing tag; not used for crypto here)
const payloadLen = dv.getUint32(o, false); o += 4;
const headerEnd = o;
const nonce = packet.subarray(o, o + 12); o += 12;
const ct = packet.subarray(o, o + payloadLen);
const header = packet.subarray(0, headerEnd);
const shared = x25519.getSharedSecret(priv, ephemeralPub);
const layerKey = hkdf(sha256, shared, ephemeralPub, ONION_INFO, 32);
const inner = gcm(layerKey, nonce, header).decrypt(ct); // throws on tamper / wrong relay
return { nextHop: nextHop === '' ? null : nextHop, inner };
}
function padToFixed(p) {
if (p.length >= PACKET_TARGET) return p;
const out = new Uint8Array(PACKET_TARGET);
out.set(p);
out.set(randomBytes(PACKET_TARGET - p.length), p.length);
return out;
}
// --- config from environment ------------------------------------------------
const PORT = Number(process.env.PORT || 8080);
const hex = (process.env.RELAY_PRIVATE_KEY || '').trim();
if (hex.length !== 64 || /[^0-9a-fA-F]/.test(hex)) {
console.error('FATAL: set RELAY_PRIVATE_KEY to a 64-hex-char X25519 private key (web/relay/keygen.mjs).');
process.exit(1);
}
const priv = Uint8Array.from(hex.match(/.{2}/g).map((h) => parseInt(h, 16)));
// --- RAM-only replay cache (audit L10) --------------------------------------
const forwards = new Map();
const seen = new Map(); // hex key → expiryMs
function isReplay(packet) {
const now = Date.now();
if (seen.size >= SEEN_MAX) {
for (const [k, exp] of seen) if (exp <= now) seen.delete(k);
if (seen.size >= SEEN_MAX) { const oldest = seen.keys().next().value; if (oldest) seen.delete(oldest); }
}
const key = bytesToHex(sha256(packet.length > 256 ? packet.subarray(0, 256) : packet));
const exp = seen.get(key);
if (exp !== undefined && exp > now) return true;
seen.set(key, now + SEEN_TTL_MS);
return false;
}
function forward(addr, payload) {
let out = forwards.get(addr);
if (!out) {
out = new WebSocket(addr);
const q = [];
out._q = q;
forwards.set(addr, out);
out.on('open', () => { for (const m of q) out.send(m); q.length = 0; });
out.on('close', () => forwards.delete(addr));
out.on('error', () => forwards.delete(addr));
}
if (out.readyState === WebSocket.OPEN) out.send(payload);
else out._q.push(payload);
}
// --- HTTP (health) + WebSocket (relay) on one port --------------------------
const server = http.createServer((req, res) => {
// Health endpoint for platform checks + keep-alive pingers. Returns no data and
// touches no state — it never reveals that this is a relay.
if (req.method === 'GET' && (req.url === '/health' || req.url === '/')) {
res.writeHead(200, { 'content-type': 'text/plain', 'cache-control': 'no-store' });
res.end('ok');
return;
}
res.writeHead(426, { 'content-type': 'text/plain' });
res.end('upgrade required');
});
const wss = new WebSocketServer({ server });
wss.on('connection', (sock) => {
sock.on('message', (data) => {
const packet = new Uint8Array(data);
if (isReplay(packet)) return; // drop replays before any crypto / broadcast
let dec;
try { dec = unwrapLayer(packet, priv); } catch { return; } // not for us / tampered
if (dec.nextHop === null) {
const padded = padToFixed(dec.inner);
for (const c of wss.clients) if (c !== sock && c.readyState === WebSocket.OPEN) c.send(padded);
} else {
forward(dec.nextHop, dec.inner);
}
});
});
server.listen(PORT, '0.0.0.0', () => {
console.log(`Nucleus relay listening on :${PORT} (RAM-only, no logging, GET /health = ok)`);
});