taper / server /gateway.js
abr00kx's picture
Split server into modules (4c6bdcf9) (part 3)
42128a6 verified
Raw History Blame Contribute Delete
19 kB
// The gateway: the HTTP(S) server, the cover website, the web client under
// the secret gateway path, WebSocket upgrades (client gateway and
// federation), the client connection state machine (hello, identify,
// resume, heartbeat, rate limit) and central enforcement of the method
// table. Owns the HTTP server and the client WebSocket server.
// Trust boundary: everything from the network arrives here first. Each
// method declares what it needs and is checked in this order before its
// handler runs:
// public: true callable before identify (otherwise a live token is required)
// budget: [c, cost] charged to the account's daily counter `c` (quota.meter)
// strong: 'What' a fresh password proof (and key touch) first
// params: {...} checked in order: 'string', 'object', 'room' (an existing
// room, also giving `room`), {max, optional} (a string), or
// a function of the body
// joined: true the caller is joined to `room`
// and then run(params, ctx, body).
import http from 'node:http';
import https from 'node:https';
import { readFileSync, promises as fsp } from 'node:fs';
import { resolve as resolvePath, extname, sep } from 'node:path';
import { randomBytes, createPublicKey } from 'node:crypto';
import { WebSocketServer } from 'ws';
import { ROOM_VERSION, requireString, requireObject } from './events.js';
import { CLOSE } from './sessions.js';
import { tokenKey } from './auth.js';
import { b64url, now, errorBody, send } from './util.js';
const IDENTIFY_TIMEOUT_MS = 60_000;
const MAX_FRAME_BYTES = 256 * 1024;
// Everything that isn't the gateway, the federation path or discovery looks
// like an ordinary website: no Taper banners, headers or errors.
const COVER_TYPES = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', '.txt': 'text/plain; charset=utf-8', '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.woff2': 'font/woff2' };
const page = (title, text) => `<!doctype html>\n<html><head><meta charset="utf-8"><title>${title}</title></head>\n<body><h1>${title}</h1><p>${text}</p></body></html>\n`;
const DEFAULT_COVER = page('Welcome', 'This site is under construction.');
const NOT_FOUND = page('Not Found', 'The requested URL was not found on this server.');
// Only the files the client needs at runtime: no tests, manifests or READMEs.
const CLIENT_FILES = new Set([
'index.html', 'wasm-check.js', 'app.js', 'crypto.js', 'media.js', 'pow.js', 'opaque.js', 'account.js', 'device.js', 'webauthn.js', 'style.css',
'node_modules/@matrix-org/matrix-sdk-crypto-wasm/index.mjs',
'node_modules/@matrix-org/matrix-sdk-crypto-wasm/pkg/matrix_sdk_crypto_wasm_bg.js',
'node_modules/@matrix-org/matrix-sdk-crypto-wasm/pkg/matrix_sdk_crypto_wasm_bg.wasm',
'node_modules/@serenity-kit/opaque/esm/index.js',
]);
const CLIENT_TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.wasm': 'application/wasm' };
const refuse = (socket, status) => socket.end(`HTTP/1.1 ${status}\r\ncontent-length: 0\r\nconnection: close\r\n\r\n`);
export function create(app, methods) {
const { cfg } = app;
const { sessions } = app.state;
const { SERVER_NAME, GATEWAY_PATH, FED_PATH, PEERS, TLS, COVER_DIR, CLIENT_DIR, DMS_PATH, WELL_KNOWN } = cfg;
const LIMITS = cfg.limits;
const clientCache = new Map();
async function coverResponse(method, pathname) {
const html = 'text/html; charset=utf-8';
if (method !== 'GET' && method !== 'HEAD') return { status: 404, type: html, body: NOT_FOUND };
if (!COVER_DIR) return pathname === '/' ? { status: 200, type: html, body: DEFAULT_COVER } : { status: 404, type: html, body: NOT_FOUND };
let file = resolvePath(COVER_DIR, `.${decodeURIComponent(pathname)}`);
if (file !== COVER_DIR && !file.startsWith(COVER_DIR + sep)) return { status: 404, type: html, body: NOT_FOUND };
try {
if ((await fsp.stat(file)).isDirectory()) file = resolvePath(file, 'index.html');
return { status: 200, type: COVER_TYPES[extname(file)] ?? 'application/octet-stream', body: await fsp.readFile(file) };
} catch {
return { status: 404, type: html, body: NOT_FOUND };
}
}
async function serveClient(req, res, rel) {
if (!CLIENT_DIR || (req.method !== 'GET' && req.method !== 'HEAD')) return false;
const name = rel === '' ? 'index.html' : rel;
if (!CLIENT_FILES.has(name)) return false;
let body = clientCache.get(name);
if (!body) {
try { body = await fsp.readFile(resolvePath(CLIENT_DIR, name)); } catch { return false; }
// Tell the page it is hosted here, so it connects back to this path.
if (name === 'index.html') body = Buffer.from(body.toString('utf8').replace('<meta name="taper-gateway" content="">', '<meta name="taper-gateway" content="same-origin">'));
clientCache.set(name, body);
}
res.writeHead(200, {
'content-type': CLIENT_TYPES[extname(name)],
'content-length': body.length,
// The secret path must not leak through Referer, framing or sniffing.
'referrer-policy': 'no-referrer',
'x-content-type-options': 'nosniff',
'x-frame-options': 'DENY',
'cross-origin-opener-policy': 'same-origin',
'cross-origin-resource-policy': 'same-origin',
'cache-control': 'no-cache',
...(TLS ? { 'strict-transport-security': 'max-age=31536000' } : {}),
...(name === 'index.html' ? { 'content-security-policy': "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self'; img-src 'self' data: blob:; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" } : {}),
});
res.end(req.method === 'HEAD' ? undefined : body);
return true;
}
async function onHttpRequest(req, res) {
let pathname;
try { pathname = new URL(req.url, 'http://x').pathname; } catch { pathname = '/'; }
if (pathname === GATEWAY_PATH && CLIENT_DIR) {
res.writeHead(301, { location: `${GATEWAY_PATH}/`, 'referrer-policy': 'no-referrer' });
res.end();
return;
}
if (pathname.startsWith(`${GATEWAY_PATH}/`) && await serveClient(req, res, pathname.slice(GATEWAY_PATH.length + 1))) return;
// Server keys, for federation peers only: they live under the secret
// federation path.
if (PEERS.size && pathname === `${FED_PATH}/keys` && req.method === 'GET') {
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify(app.fed.serverKeysDoc()));
return;
}
if (DMS_PATH && pathname === DMS_PATH && req.method === 'POST' && await app.operator.dmsHttp(req, res)) return;
if (WELL_KNOWN && pathname === '/.well-known/taper/client') {
res.writeHead(200, { 'content-type': 'application/json', 'access-control-allow-origin': '*' });
res.end(JSON.stringify({ 't.gateway': { urls: [`${TLS ? 'wss' : 'ws'}://${req.headers.host}${GATEWAY_PATH}`] } }));
return;
}
let cover;
try { cover = await coverResponse(req.method, pathname); } catch { cover = { status: 404, type: 'text/html; charset=utf-8', body: NOT_FOUND }; }
res.writeHead(cover.status, { 'content-type': cover.type, 'content-length': Buffer.byteLength(cover.body) });
res.end(req.method === 'HEAD' ? undefined : cover.body);
}
const tlsContext = () => ({ cert: readFileSync(cfg.TLS_CERT), key: readFileSync(cfg.TLS_KEY), ...cfg.TLS_OPTIONS });
const httpServer = TLS ? https.createServer(tlsContext(), onHttpRequest) : http.createServer(onHttpRequest);
// No compression: permessage-deflate on a socket mixing tokens and
// attacker-influenced content invites CRIME/BREACH-style length leaks.
const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false, maxPayload: MAX_FRAME_BYTES });
let unauthConns = 0;
httpServer.on('upgrade', (req, socket, head) => {
// Until a WebSocket owns the socket, a reset would be an unhandled 'error' that ends the process.
socket.on('error', () => socket.destroy());
let pathname;
try {
pathname = new URL(req.url, 'http://x').pathname;
} catch {
refuse(socket, '400 Bad Request');
return;
}
if (pathname === FED_PATH && PEERS.size) {
if (!app.fed.accept(req, socket, head)) refuse(socket, '503 Service Unavailable');
return;
}
if (pathname !== GATEWAY_PATH) {
// Answer as the cover website would answer any other request.
coverResponse(req.method, pathname).then((cover) => {
if (socket.destroyed) return;
socket.write(`HTTP/1.1 ${cover.status} ${cover.status === 200 ? 'OK' : 'Not Found'}\r\ncontent-type: ${cover.type}\r\ncontent-length: ${Buffer.byteLength(cover.body)}\r\ndate: ${new Date().toUTCString()}\r\nconnection: close\r\n\r\n`);
socket.end(cover.body);
}, () => socket.destroy());
return;
}
if (cfg.MAX_UNAUTH_CONNS > 0 && unauthConns >= cfg.MAX_UNAUTH_CONNS) {
refuse(socket, '503 Service Unavailable');
return;
}
wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req));
});
// Check a method's declared parameters, in order.
function checkParams(spec, body) {
const p = {};
for (const [name, kind] of Object.entries(spec.params ?? {})) {
if (typeof kind === 'function') p[name] = kind(body);
else if (kind === 'object') p[name] = requireObject(body, name);
else if (kind === 'room') p.room = app.rooms.get(p[name] = requireString(body, name));
else p[name] = requireString(body, name, kind === 'string' ? undefined : kind);
}
return p;
}
async function call(conn, ws, frame, method) {
const spec = methods[method];
const body = frame.body ?? {};
let ctx;
if (spec.public) {
ctx = { frame, binding: conn.id, origin: conn.origin, conn };
} else {
if (!conn.session) return { error: { errcode: 'T_MISSING_TOKEN', error: 'Identify first' } };
if (!app.auth.lookupToken(conn.token)) return { close: [CLOSE.AUTH_FAILED, 'Access token no longer valid'] };
ctx = { user_id: conn.session.user_id, device_id: conn.session.device_id, session: conn.session, token: conn.token, origin: conn.origin };
if (spec.budget) app.quota.meter(spec.budget, body, frame, ctx.user_id, conn.session.session_id);
if (spec.strong) app.auth.requireStrong(ctx, body, spec.strong);
}
const p = checkParams(spec, body);
if (spec.joined) app.rooms.requireJoined(p.room, ctx.user_id);
return { body: await spec.run(p, ctx, body) };
}
wss.on('connection', (ws, req) => {
// Same: one client's malformed or oversized frame must never take the server down.
ws.on('error', () => ws.terminate());
unauthConns++;
const conn = {
// The page that opened the socket (browsers always say; other clients don't).
origin: req.headers.origin ?? '',
id: b64url(randomBytes(16)), // binds pre-login challenges to this connection
session: null,
token: null,
countedUnauth: true,
loginStarts: 0,
tokens: LIMITS.rate_burst,
lastRefill: now(),
heartbeatTimer: null,
// Each connection gets its own interval (within ±20% of the base), so
// heartbeats don't share a fingerprintable period.
heartbeatMs: Math.round(cfg.HEARTBEAT_INTERVAL_MS * (0.8 + 0.4 * Math.random())),
identifyTimer: setTimeout(() => ws.close(CLOSE.NOT_AUTHENTICATED, 'Identify timeout'), IDENTIFY_TIMEOUT_MS),
};
const markAuthed = () => {
if (conn.countedUnauth) { conn.countedUnauth = false; unauthConns = Math.max(0, unauthConns - 1); }
};
const resetHeartbeat = () => {
clearTimeout(conn.heartbeatTimer);
conn.heartbeatTimer = setTimeout(() => ws.close(CLOSE.TIMED_OUT, 'Heartbeat timeout'), conn.heartbeatMs * 1.5);
};
resetHeartbeat();
send(ws, {
op: 'hello',
body: { heartbeat_interval_ms: conn.heartbeatMs, server_name: SERVER_NAME, gateway_version: 1, room_version: ROOM_VERSION, retention_ms: cfg.RETENTION_MS, connection_id: conn.id },
});
const takeToken = () => {
const t = now();
conn.tokens = Math.min(LIMITS.rate_burst, conn.tokens + ((t - conn.lastRefill) / 1000) * LIMITS.rate_per_sec);
conn.lastRefill = t;
if (conn.tokens < 1) return Math.ceil(((1 - conn.tokens) / LIMITS.rate_per_sec) * 1000);
conn.tokens -= 1;
return 0;
};
// The token in an identify or resume frame, if it is live; else null.
const authenticate = (body) => {
let auth;
try {
const token = requireString(body, 'access_token', { max: 512 });
auth = app.auth.lookupToken(token);
if (!auth) return null;
conn.token = token;
} catch { return null; }
clearTimeout(conn.identifyTimer);
markAuthed();
return auth;
};
ws.on('message', async (data, isBinary) => {
if (isBinary) {
if (!conn.session || !app.media.onBinaryFrame(conn.session.user_id, data)) ws.close(CLOSE.DECODE_ERROR, 'Unexpected binary frame');
return;
}
let frame;
try {
frame = JSON.parse(data.toString('utf8'));
if (!frame || typeof frame !== 'object' || typeof frame.op !== 'string') throw new Error('shape');
} catch {
ws.close(CLOSE.DECODE_ERROR, 'Frames must be JSON objects with an "op"');
return;
}
switch (frame.op) {
case 'heartbeat':
resetHeartbeat();
send(ws, { op: 'heartbeat_ack' });
return;
case 'noop':
// High-risk cover traffic (Cryptography and Transport, "Timing"):
// always accepted silently, bounded only by the per-connection rate limit.
takeToken();
return;
case 'identify': {
if (conn.session) return ws.close(CLOSE.ALREADY_AUTHENTICATED, 'Already identified');
const auth = authenticate(frame.body);
if (!auth) return ws.close(CLOSE.AUTH_FAILED, 'Unknown access token');
const session = new app.sessions.Session(auth.user_id, auth.device_id, tokenKey(conn.token));
app.sessions.add(session);
session.attach(ws);
conn.session = session;
send(ws, {
op: 'ready',
body: {
session_id: session.session_id, user_id: auth.user_id, device_id: auth.device_id,
rooms: app.rooms.snapshot(auth.user_id),
one_time_key_counts: app.keys.countsFor(auth.user_id, auth.device_id),
},
});
app.keys.flushToDevice(session);
return;
}
case 'resume': {
if (conn.session) return ws.close(CLOSE.ALREADY_AUTHENTICATED, 'Already identified');
const auth = authenticate(frame.body);
if (!auth) return ws.close(CLOSE.AUTH_FAILED, 'Unknown access token');
const session = sessions.get(frame.body?.session_id);
const seq = frame.body?.seq;
// Resumable only if everything after `seq` is still in the buffer.
const oldestBuffered = session?.buffer[0]?.seq ?? Infinity;
const resumable = session && session.user_id === auth.user_id && session.device_id === auth.device_id
&& !session.ws && Number.isInteger(seq) && seq >= 0 && seq <= session.seq
&& (seq === session.seq || oldestBuffered <= seq + 1);
if (!resumable) return ws.close(CLOSE.INVALID_RESUME, 'Cannot resume; identify again');
session.attach(ws);
conn.session = session;
for (const d of session.buffer) if (d.seq > seq) send(ws, d);
send(ws, { op: 'resumed', body: { session_id: session.session_id, seq: session.seq } });
return;
}
case 'request': {
const id = frame.id;
const reply = (payload) => send(ws, { op: 'response', id, ...payload });
if (typeof id !== 'string' && typeof id !== 'number') return reply({ ok: false, error: { errcode: 'T_BAD_JSON', error: "Requests need an 'id'" } });
const wait = takeToken();
if (wait) return reply({ ok: false, error: { errcode: 'T_LIMIT_EXCEEDED', error: 'Slow down', retry_after_ms: wait } });
const method = frame.method;
if (typeof method !== 'string') return reply({ ok: false, error: { errcode: 'T_BAD_JSON', error: "Requests need a string 'method'" } });
if (!Object.hasOwn(methods, method)) return reply({ ok: false, error: { errcode: 'T_UNRECOGNIZED', error: `Unknown method '${method}'` } });
try {
const out = await call(conn, ws, frame, method);
if (out.close) return ws.close(...out.close);
reply(out.error ? { ok: false, error: out.error } : { ok: true, body: out.body });
} catch (err) {
reply({ ok: false, error: errorBody(err, method) });
}
return;
}
default:
ws.close(CLOSE.UNKNOWN_OP, `Unknown op '${frame.op}'`);
}
});
ws.on('close', () => {
clearTimeout(conn.heartbeatTimer);
clearTimeout(conn.identifyTimer);
markAuthed();
if (conn.session && conn.session.ws === ws) conn.session.detach();
});
});
// On shutdown, tell clients to reconnect elsewhere (here: wherever discovery points).
function shutdown() {
for (const ws of wss.clients) {
send(ws, { op: 'reconnect', body: { url: null, reason: 'Server shutting down' } });
ws.close(CLOSE.RECONNECT, 'Reconnect');
}
app.fed.closeAll();
app.operator.unlinkSocket();
httpServer.close(() => { app.disk.close(); process.exit(0); });
setTimeout(() => process.exit(0), 2000).unref();
}
// Reload the TLS certificate and key (after a renewal) without dropping
// connections: `kill -HUP`. A bad pair is refused and the old one kept.
function reloadTls() {
if (!TLS) return;
try {
const context = tlsContext();
createPublicKey(context.key); // throws on an unreadable key
httpServer.setSecureContext(context);
console.log('Reloaded TLS certificate');
} catch (e) {
console.error(`Keeping the old TLS certificate: ${e.message}`);
}
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
process.on('SIGHUP', reloadTls);
return {
httpServer,
terminateAll() { for (const ws of wss.clients) ws.terminate(); httpServer.close(); },
listen() {
httpServer.listen(cfg.PORT, cfg.HOST, () => {
// A configured path is a secret: logs (often readable by an admin group) get only its start.
const shownPath = cfg.GATEWAY_PATH_SET ? `${GATEWAY_PATH.slice(0, 5)}…` : GATEWAY_PATH;
console.log(`Taper gateway on ${TLS ? 'wss' : 'ws'}://${cfg.HOST}:${cfg.PORT}${shownPath} (server name ${SERVER_NAME}${TLS ? ', TLS 1.3, X25519MLKEM768 preferred' : ', plaintext: loopback only'})`);
});
},
};
}