Files

87 lines
2.5 KiB
TypeScript

import type { IncomingMessage, ServerResponse } from "node:http";
import { sendJson } from "../_lib/httpUtils.ts";
import {
EventSignatureError,
MalformedEventError,
pullEvents,
pushEvents,
} from "../_lib/eventRelayStore.ts";
const MAX_SYNC_BODY_BYTES = 4 * 1024 * 1024;
async function readJsonBody(
req: IncomingMessage,
limitBytes: number,
): Promise<unknown> {
const chunks: Buffer[] = [];
let total = 0;
for await (const chunk of req) {
total += (chunk as Buffer).length;
if (total > limitBytes) {
req.destroy();
throw new MalformedEventError("request body exceeds size limit");
}
chunks.push(chunk as Buffer);
}
const raw = Buffer.concat(chunks, total).toString("utf8");
if (raw.length === 0) return {};
try {
return JSON.parse(raw);
} catch {
throw new MalformedEventError("request body is not valid JSON");
}
}
/**
* Generic signed-event relay (backend-expansion todo 2). A single POST both
* pushes a batch of signed events and pulls everything since a cursor:
* request `{ push?: WireEventEntry[], pullCursor?: number }`
* response `{ stored: number, entries: WireEventEntry[], cursor: number }`
*
* It is a pure relay - it verifies each pushed event's own signature and never
* signs, mutates, or counter-signs anything. A malformed batch is a 400 and a
* forged/tampered signature is a 422; neither is ever stored, and neither is a
* generic 500.
*/
export default async function handler(
req: IncomingMessage,
res: ServerResponse,
): Promise<void> {
if (req.method !== "POST") {
sendJson(res, 405, { error: "method not allowed, use POST" });
return;
}
try {
const body = await readJsonBody(req, MAX_SYNC_BODY_BYTES);
if (typeof body !== "object" || body === null) {
throw new MalformedEventError("request body must be a JSON object");
}
const { push, pullCursor } = body as {
push?: unknown;
pullCursor?: unknown;
};
let stored = 0;
if (push !== undefined) {
if (!Array.isArray(push)) {
throw new MalformedEventError("push must be an array of events");
}
stored = await pushEvents(push);
}
const { entries, cursor } = pullEvents(pullCursor);
sendJson(res, 200, { stored, entries, cursor });
} catch (err) {
if (err instanceof EventSignatureError) {
sendJson(res, 422, { error: err.message });
return;
}
if (err instanceof MalformedEventError) {
sendJson(res, 400, { error: err.message });
return;
}
sendJson(res, 500, { error: "failed to relay events" });
}
}