Spaces:
Sleeping
Sleeping
Leogron777 commited on
Commit ·
4c119aa
1
Parent(s): 83afe2d
relay
Browse filesFiles changed (4)
- DockerfileAdded+21
- README.md+6-4
- package.jsonAdded+20
- server.mjsAdded+141
123456789101112131415161718192021# Nucleus relay — RAM-only onion forwarder. No volumes, nothing persisted.# Used by Back4app Containers and Hugging Face Spaces (Docker SDK).## Render does NOT need this file (it auto-detects Node from package.json).## The relay honors the platform's injected $PORT. Hugging Face Spaces require the# app to listen on 7860 and the container to run as a non-root user — both set# below. Back4app injects its own $PORT, which overrides ENV PORT at runtime.FROM node:20-alpine
WORKDIR /appCOPY package.json ./RUN npm install --omit=devCOPY server.mjs ./
# Hugging Face default app port + non-root user (harmless on other platforms).ENV PORT=7860EXPOSE 7860USER 1000
CMD ["node", "server.mjs"]12345678910---title: Node Edge 2emoji: 🏆colorFrom: purplecolorTo: graysdk: dockerpinned: false---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112---title: Node Edge 1emoji: 😻colorFrom: yellowcolorTo: pinksdk: dockerapp_port: 7860pinned: falseshort_description: Node WebSocket service---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
1234567891011121314151617181920{ "name": "nucleus-relay", "version": "1.0.0", "private": true, "type": "module", "description": "Nucleus RAM-only onion relay — deployable to free PaaS hosts.", "main": "server.mjs", "scripts": { "start": "node server.mjs" }, "engines": { "node": ">=18" }, "dependencies": { "@noble/ciphers": "^1.2.1", "@noble/curves": "^1.8.1", "@noble/hashes": "^1.7.1", "ws": "^8.21.0" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141/** * 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 ephemeralsconst SEEN_MAX = 8192; // bounded RAM, nothing on diskconst 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 → expiryMsfunction 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)`);});DockerfileAdded+21
README.md+6-4
package.jsonAdded+20
server.mjsAdded+141