fix: SSE via fetch for auth headers, remove query param auth, add heartbeat every 10s

This commit is contained in:
M1
2026-03-16 16:17:33 +04:00
parent 6d48a83560
commit 31d1fa7b04
3 changed files with 44 additions and 17 deletions
+9 -5
View File
@@ -17,14 +17,20 @@ function publish(monitorId: string, data: object) {
function makeSSEStream(monitorId: string): Response {
let ctrl: SSEController;
let heartbeat: Timer;
const stream = new ReadableStream<Uint8Array>({
start(c) {
ctrl = c;
if (!bus.has(monitorId)) bus.set(monitorId, new Set());
bus.get(monitorId)!.add(ctrl);
ctrl.enqueue(enc.encode(": connected\n\n"));
// Keepalive — prevents proxies/Cloudflare from closing idle connections
heartbeat = setInterval(() => {
try { ctrl.enqueue(enc.encode(": heartbeat\n\n")); } catch { clearInterval(heartbeat); }
}, 10_000);
},
cancel() {
clearInterval(heartbeat);
bus.get(monitorId)?.delete(ctrl);
if (bus.get(monitorId)?.size === 0) bus.delete(monitorId);
},
@@ -78,11 +84,9 @@ export const ingest = new Elysia()
detail: { hide: true },
})
// SSE: stream live pings — auth via Bearer header OR ?auth= query param
// (EventSource doesn't support custom headers, hence the query param fallback)
.get("/monitors/:id/stream", async ({ params, headers, query, error }) => {
const key = headers["authorization"]?.replace("Bearer ", "").trim()
?? (query.auth as string | undefined);
// SSE: stream live pings — auth via Bearer header
.get("/monitors/:id/stream", async ({ params, headers, error }) => {
const key = headers["authorization"]?.replace("Bearer ", "").trim();
if (!key) return error(401, { error: "Unauthorized" });