128 lines
4.9 KiB
TypeScript
128 lines
4.9 KiB
TypeScript
import { Elysia, t } from "elysia";
|
|
import { timingSafeEqual } from "crypto";
|
|
import sql from "../db";
|
|
import { resolveKey } from "./auth";
|
|
|
|
function safeTokenCompare(a: string | undefined, b: string | undefined): boolean {
|
|
if (!a || !b) return false;
|
|
const bufA = Buffer.from(a);
|
|
const bufB = Buffer.from(b);
|
|
if (bufA.length !== bufB.length) return false;
|
|
return timingSafeEqual(bufA, bufB);
|
|
}
|
|
|
|
// ── SSE bus ───────────────────────────────────────────────────────────────────
|
|
type SSEController = ReadableStreamDefaultController<Uint8Array>;
|
|
const bus = new Map<string, Set<SSEController>>(); // keyed by accountId
|
|
const enc = new TextEncoder();
|
|
|
|
function publish(accountId: string, data: object) {
|
|
const subs = bus.get(accountId);
|
|
if (!subs?.size) return;
|
|
const msg = enc.encode(`data: ${JSON.stringify(data)}\n\n`);
|
|
for (const ctrl of subs) {
|
|
try { ctrl.enqueue(msg); } catch { subs.delete(ctrl); }
|
|
}
|
|
}
|
|
|
|
function makeSSEStream(accountId: string): Response {
|
|
let ctrl: SSEController;
|
|
let heartbeat: Timer;
|
|
const stream = new ReadableStream<Uint8Array>({
|
|
start(c) {
|
|
ctrl = c;
|
|
if (!bus.has(accountId)) bus.set(accountId, new Set());
|
|
bus.get(accountId)!.add(ctrl);
|
|
ctrl.enqueue(enc.encode(": connected\n\n"));
|
|
heartbeat = setInterval(() => {
|
|
try { ctrl.enqueue(enc.encode(": heartbeat\n\n")); } catch { clearInterval(heartbeat); }
|
|
}, 10_000);
|
|
},
|
|
cancel() {
|
|
clearInterval(heartbeat);
|
|
bus.get(accountId)?.delete(ctrl);
|
|
if (bus.get(accountId)?.size === 0) bus.delete(accountId);
|
|
},
|
|
});
|
|
return new Response(stream, {
|
|
headers: {
|
|
"Content-Type": "text/event-stream",
|
|
"Cache-Control": "no-cache",
|
|
"Connection": "keep-alive",
|
|
"X-Accel-Buffering": "no",
|
|
},
|
|
});
|
|
}
|
|
|
|
// ── Routes ────────────────────────────────────────────────────────────────────
|
|
export const ingest = new Elysia()
|
|
|
|
// Internal: called by Rust monitor runner
|
|
.post("/internal/ingest", async ({ body, headers, error }) => {
|
|
const token = headers["x-monitor-token"];
|
|
if (!safeTokenCompare(token, process.env.MONITOR_TOKEN)) return error(401, { error: "Unauthorized" });
|
|
|
|
// Validate monitor exists
|
|
const [monitor_check] = await sql`SELECT id FROM monitors WHERE id = ${body.monitor_id}`;
|
|
if (!monitor_check) return error(404, { error: "Monitor not found" });
|
|
|
|
const meta = body.meta ? { ...body.meta } : {};
|
|
if (body.cert_expiry_days != null) meta.cert_expiry_days = body.cert_expiry_days;
|
|
|
|
const scheduledAt = body.scheduled_at ? new Date(body.scheduled_at) : null;
|
|
const jitterMs = body.jitter_ms ?? null;
|
|
|
|
const [ping] = await sql`
|
|
INSERT INTO pings (monitor_id, scheduled_at, jitter_ms, status_code, latency_ms, up, error, meta)
|
|
VALUES (
|
|
${body.monitor_id},
|
|
${scheduledAt},
|
|
${jitterMs},
|
|
${body.status_code ?? null},
|
|
${body.latency_ms ?? null},
|
|
${body.up},
|
|
${body.error ?? null},
|
|
${Object.keys(meta).length > 0 ? sql.json(meta) : null}
|
|
)
|
|
RETURNING *
|
|
`;
|
|
|
|
// Look up account and publish to account-level bus
|
|
const [monitor] = await sql`SELECT account_id FROM monitors WHERE id = ${body.monitor_id}`;
|
|
if (monitor) publish(monitor.account_id, ping);
|
|
|
|
return { ok: true };
|
|
}, {
|
|
body: t.Object({
|
|
monitor_id: t.String(),
|
|
scheduled_at: t.Optional(t.Nullable(t.String())),
|
|
jitter_ms: t.Optional(t.Nullable(t.Number())),
|
|
status_code: t.Optional(t.Number()),
|
|
latency_ms: t.Optional(t.Number()),
|
|
up: t.Boolean(),
|
|
error: t.Optional(t.Nullable(t.String())),
|
|
cert_expiry_days: t.Optional(t.Nullable(t.Number())),
|
|
meta: t.Optional(t.Any()),
|
|
}),
|
|
detail: { hide: true },
|
|
})
|
|
|
|
// SSE: single stream for all of the account's monitors
|
|
.get("/account/stream", async ({ headers, cookie }) => {
|
|
const authHeader = headers["authorization"] ?? "";
|
|
const bearer = authHeader.match(/^bearer\s+(.+)$/i)?.[1]?.trim();
|
|
const key = bearer ?? cookie?.pingql_key?.value;
|
|
|
|
if (!key) return new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 });
|
|
|
|
const resolved = await resolveKey(key);
|
|
if (!resolved) return new Response(JSON.stringify({ error: "Unauthorized" }), { status: 401 });
|
|
|
|
const limit = Number(process.env.MAX_SSE_PER_ACCOUNT ?? 10);
|
|
if ((bus.get(resolved.accountId)?.size ?? 0) >= limit) {
|
|
return new Response(JSON.stringify({ error: "Too many connections" }), { status: 429 });
|
|
}
|
|
|
|
return makeSSEStream(resolved.accountId);
|
|
}, { detail: { hide: true } });
|