Spaces:
Sleeping

File size: 6,300 Bytes
06d3542
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * 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)`);
});