fix(auth): remove JWT from SSE query strings and align CORS preflight with #633 (#660)

Applies #660 (remove ?token= query extraction, switch web SSE to fetch+
Authorization Bearer, drop client-written auth cookie) cleanly on top of #633's
same-origin CORS policy. Preserves #633's same-origin ACAO + Vary: Origin while
allowing Authorization and Last-Event-ID on same-origin preflights, aligns
openSSE 401 cookie clearing attributes, and updates the upload.test.mjs and
traffic-stream.test.mjs harnesses for @/lib/sse (SSEStream stub + EventTarget,
Event, MessageEvent, AbortController in VM context).

Co-authored-by: Coff0xc <184964491+Coff0xc@users.noreply.github.com>
This commit is contained in:
BaaRai 2026-11-28 18:38:34 +01:00
parent 814b603fca
commit 4af245b3f4
16 changed files with 516 additions and 32 deletions

View file

@ -272,8 +272,8 @@ func (s *Server) approver(r *http.Request) string {
return jwtSubject(tok, s.jwtKey)
}
// extractToken reads the JWT from Authorization: Bearer header,
// artex_token cookie, or ?token= query param (for SSE connections).
// extractToken reads the JWT from Authorization: Bearer or the session cookie.
// URLs must never carry reusable session credentials, including for SSE.
func extractToken(r *http.Request) string {
if h := r.Header.Get("Authorization"); strings.HasPrefix(h, "Bearer ") {
return strings.TrimPrefix(h, "Bearer ")
@ -281,12 +281,12 @@ func extractToken(r *http.Request) string {
if c, err := r.Cookie("artex_token"); err == nil && c.Value != "" {
return c.Value
}
return r.URL.Query().Get("token")
return ""
}
// cookieAuthenticated reports whether extractToken takes the session from the
// artex_token cookie. The browser attaches that cookie on its own, to requests
// a foreign page makes as well; a bearer or query token is put there by the caller.
// a foreign page makes as well; a bearer token is put there by the caller.
func cookieAuthenticated(r *http.Request) bool {
if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") {
return false

View file

@ -0,0 +1,68 @@
package server
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestSessionTokenNeverAuthenticatesFromURL(t *testing.T) {
s := &Server{jwtKey: []byte("0123456789abcdef0123456789abcdef")}
token, err := signJWT(s.jwtKey)
if err != nil {
t.Fatal(err)
}
h := s.requireAuth(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) }))
for _, path := range []string{"/api/tasks", "/api/logs/stream", "/api/exploration/activity/stream?task=1", "/api/side-questions/1/events", "/api/browser/stream"} {
for _, method := range []string{http.MethodGet, http.MethodPost} {
t.Run(method+path, func(t *testing.T) {
r := httptest.NewRequest(method, path, nil)
q := r.URL.Query()
q.Set("token", token)
r.URL.RawQuery = q.Encode()
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
if w.Code != http.StatusUnauthorized {
t.Fatalf("query credential accepted: %d", w.Code)
}
r.Header.Set("Authorization", "Bearer "+token)
w = httptest.NewRecorder()
h.ServeHTTP(w, r)
if w.Code != http.StatusNoContent {
t.Fatalf("header credential refused: %d", w.Code)
}
})
}
}
}
func TestSSEBearerPreflight(t *testing.T) {
// Same-origin preflight receives 204 with Authorization and Last-Event-ID allowed.
r := httptest.NewRequest(http.MethodOptions, "http://example.com/api/logs/stream", nil)
r.Header.Set("Origin", "http://example.com")
r.Header.Set("Access-Control-Request-Headers", "authorization,last-event-id")
w := httptest.NewRecorder()
cors(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Fatal("preflight reached handler") })).ServeHTTP(w, r)
if w.Code != http.StatusNoContent {
t.Fatalf("same-origin preflight status=%d", w.Code)
}
if got := w.Header().Get("Access-Control-Allow-Origin"); got != "http://example.com" {
t.Fatalf("same-origin ACAO=%q, want http://example.com", got)
}
if got := w.Header().Get("Access-Control-Allow-Headers"); got != "Content-Type, Authorization, Last-Event-ID" {
t.Fatalf("SSE credential/cursor headers not allowed: %q", got)
}
// Cross-origin preflight must NOT receive ACAO or Allow-Headers (interacts with #633).
xr := httptest.NewRequest(http.MethodOptions, "http://example.com/api/logs/stream", nil)
xr.Header.Set("Origin", "http://localhost:3000")
xr.Header.Set("Access-Control-Request-Headers", "authorization,last-event-id")
xw := httptest.NewRecorder()
cors(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })).ServeHTTP(xw, xr)
if got := xw.Header().Get("Access-Control-Allow-Origin"); got != "" {
t.Fatalf("cross-origin preflight echoed ACAO=%q", got)
}
if got := xw.Header().Get("Access-Control-Allow-Headers"); got != "" {
t.Fatalf("cross-origin preflight echoed ACAH=%q", got)
}
}

View file

@ -89,12 +89,12 @@ func TestCookieStateChangeNeedsSameOrigin(t *testing.T) {
}
}
// The token in the query string is a credential the caller holds, like the
// bearer token; with the cookie also present the cookie is the one used.
// Query credentials are refused; with the cookie present the cookie is used
// and still requires the same-origin CSRF check.
rec := httptest.NewRecorder()
h.ServeHTTP(rec, csrfRequest("POST", "/api/mcp?token="+tok, "", map[string]string{"Origin": "https://evil.example"}))
if rec.Code != 204 {
t.Errorf("query token, foreign Origin: status=%d, want 204", rec.Code)
if rec.Code != 401 {
t.Errorf("query token, foreign Origin: status=%d, want 401", rec.Code)
}
rec = httptest.NewRecorder()
h.ServeHTTP(rec, csrfRequest("POST", "/api/mcp?token="+tok, "", map[string]string{"Cookie": tok, "Origin": "https://evil.example"}))

View file

@ -4752,7 +4752,7 @@ func cors(next http.Handler) http.Handler {
if allowed {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, Last-Event-ID")
if r.Method == http.MethodOptions {
w.WriteHeader(204)
return

View file

@ -19,7 +19,8 @@
"test:upload": "node --test scripts/upload.test.mjs",
"test:traffic-stream": "node --test scripts/traffic-stream.test.mjs",
"test:i18n": "node scripts/check-i18n.mjs && node --test scripts/i18n.test.mjs",
"test:bash": "node --test src/lib/bash-exit-status.test.mjs"
"test:bash": "node --test src/lib/bash-exit-status.test.mjs",
"test:sse": "node --test scripts/sse.test.mjs"
},
"lint-staged": {
"*.{js,ts,jsx,tsx}": [

28
web/scripts/auth.test.mjs Normal file
View file

@ -0,0 +1,28 @@
import ts from "typescript";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import vm from "node:vm";
const output = ts.transpileModule(readFileSync(new URL("../src/lib/auth.ts", import.meta.url), "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
}).outputText;
test("HTTPS marks the session cookie Secure while local HTTP remains usable", () => {
for (const protocol of ["https:", "http:"]) {
const storage = new Map();
const document = { cookie: "" };
const exports = {};
vm.runInNewContext(output, {
exports,
document,
window: { location: { protocol } },
localStorage: { setItem: (k, v) => storage.set(k, v) },
});
exports.auth.setToken("synthetic-session");
assert.equal(storage.get("artex_token"), "synthetic-session");
assert.equal(document.cookie.includes("; Secure"), protocol === "https:");
assert.ok(document.cookie.includes("SameSite=Lax"));
}
});

211
web/scripts/sse.test.mjs Normal file
View file

@ -0,0 +1,211 @@
import ts from "typescript";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { test } from "node:test";
import { setImmediate } from "node:timers/promises";
const source = readFileSync(new URL("../src/lib/sse.ts", import.meta.url), "utf8");
const output = ts.transpileModule(source, {
compilerOptions: { module: ts.ModuleKind.ES2022, target: ts.ScriptTarget.ES2022 },
}).outputText;
const { SSEParser, SSEStream } = await import(`data:text/javascript,${encodeURIComponent(output)}`);
test("SSE parses chunked CRLF, named events, multiline data and cursors", () => {
const events = [],
cursors = [],
retries = [];
const parser = new SSEParser(
"old",
(e) => events.push(e),
(id) => cursors.push(id),
(delay) => retries.push(delay),
);
for (const chunk of [
":heartbeat\r",
"\nevent: snapshot\r\nid: 7\r\ndata: first\r",
"\ndata: 中文\r\n\r",
"\nid: bad\0id\ndata: second\n\n",
"id:\n\nretry: 250\nretry: nope\n\n",
"data: incomplete",
])
parser.feed(chunk);
assert.deepEqual(
events.map((e) => [e.type, e.data, e.lastEventId]),
[
["snapshot", "first\n中文", "7"],
["message", "second", "7"],
],
);
assert.deepEqual(cursors, ["7", "7", "", ""]);
assert.deepEqual(retries, [250]);
});
test("SSE sends headers, reconnects with the cursor and fresh token, then aborts", async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
const requests = [];
let token = "first-secret";
let secondBody;
t.mock.method(globalThis, "fetch", async (url, init) => {
requests.push({ url, init });
return new Response(
new ReadableStream({
start(controller) {
if (requests.length === 1) {
controller.enqueue(new TextEncoder().encode("retry: 100\nid: 42\ndata: first\n\n"));
controller.close();
} else secondBody = controller;
},
}),
{ headers: { "Content-Type": "text/event-stream; charset=utf-8" } },
);
});
const stream = new SSEStream(
"https://local.test/api/logs/stream?since=0",
() => token,
() => assert.fail("unauthorized"),
);
const received = [];
stream.onmessage = (e) => received.push(e.data);
await setImmediate();
assert.deepEqual(received, ["first"]);
assert.equal(requests[0].url, "https://local.test/api/logs/stream?since=0");
assert.equal(requests[0].init.headers.Authorization, "Bearer first-secret");
assert.equal(requests[0].init.redirect, "error");
assert.equal(requests[0].init.credentials, "same-origin");
token = "rotated-secret";
t.mock.timers.tick(100);
await setImmediate();
assert.equal(requests.length, 2);
assert.equal(requests[1].init.headers["Last-Event-ID"], "42");
assert.equal(requests[1].init.headers.Authorization, "Bearer rotated-secret");
stream.close();
assert.equal(requests[1].init.signal.aborted, true);
secondBody.close();
await setImmediate();
t.mock.timers.tick(60000);
assert.equal(requests.length, 2);
});
test("401 stops retries and clears authentication once; 403 and 204 also stop", async (t) => {
for (const status of [401, 403, 204]) {
await t.test(String(status), async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
let requests = 0,
unauthorized = 0,
errors = 0;
t.mock.method(globalThis, "fetch", async () => {
requests++;
return new Response(null, { status });
});
const stream = new SSEStream(
"/api/logs/stream",
() => "secret",
() => unauthorized++,
);
stream.onerror = () => errors++;
await setImmediate();
t.mock.timers.tick(60000);
assert.equal(requests, 1);
assert.equal(unauthorized, status === 401 ? 1 : 0);
assert.equal(errors, status === 204 ? 0 : 1);
stream.close();
});
}
});
test("close in a message callback suppresses further buffered events", async (t) => {
t.mock.method(
globalThis,
"fetch",
async () => new Response("data: one\n\ndata: two\n\n", { headers: { "Content-Type": "text/event-stream" } }),
);
const stream = new SSEStream(
"/api/logs/stream",
() => "secret",
() => assert.fail("unexpected authentication failure"),
);
const events = [];
stream.onmessage = (e) => {
events.push(e.data);
stream.close();
};
await setImmediate();
assert.deepEqual(events, ["one"]);
});
test("same-origin cookie authentication remains usable without a bearer token", async (t) => {
let request;
t.mock.method(globalThis, "fetch", async (url, init) => {
request = { url, init };
return new Response("data: cookie stream\n\n", { headers: { "Content-Type": "text/event-stream" } });
});
const stream = new SSEStream(
"/api/logs/stream",
() => null,
() => assert.fail("unauthorized"),
);
const events = [];
stream.onmessage = (e) => {
events.push(e.data);
stream.close();
};
await setImmediate();
assert.equal(request.url, "/api/logs/stream");
assert.equal(request.init.credentials, "same-origin");
assert.equal(request.init.headers.Authorization, undefined);
assert.deepEqual(events, ["cookie stream"]);
});
test("streaming decoder handles a split UTF-8 character and ignores a BOM", async (t) => {
const bytes = new TextEncoder().encode("\ufeffevent: snapshot\ndata: 中文\n\n");
t.mock.method(
globalThis,
"fetch",
async () =>
new Response(
new ReadableStream({
start(controller) {
for (const byte of bytes) controller.enqueue(new Uint8Array([byte]));
controller.close();
},
}),
{ headers: { "Content-Type": "text/event-stream" } },
),
);
const stream = new SSEStream(
"/api/side-questions/1/events",
() => "secret",
() => assert.fail("unexpected authentication failure"),
);
const events = [];
stream.addEventListener("snapshot", (e) => {
events.push(e.data);
stream.close();
});
await setImmediate();
assert.deepEqual(events, ["中文"]);
});
test("persistent errors wait before reconnecting and close cancels the retry", async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
let requests = 0;
t.mock.method(globalThis, "fetch", async () => {
requests++;
throw new Error("network unavailable");
});
const stream = new SSEStream(
"/api/logs/stream",
() => "secret",
() => assert.fail("unexpected authentication failure"),
);
await setImmediate();
t.mock.timers.tick(2999);
assert.equal(requests, 1);
t.mock.timers.tick(1);
await setImmediate();
assert.equal(requests, 2);
stream.close();
t.mock.timers.tick(60000);
assert.equal(requests, 2);
});

View file

@ -26,6 +26,10 @@ function loadModule(file) {
URL,
URLSearchParams,
TextEncoder,
EventTarget,
Event,
MessageEvent,
AbortController,
structuredClone,
setTimeout: (callback) => callback(),
require: (name) => {

View file

@ -21,6 +21,7 @@ function setup(mock = false) {
require(name) {
if (name === "@/lib/mock/enabled") return { MOCK: mock };
if (name === "@/lib/mock/handler") return { mockHandle: () => assert.fail("unexpected mock request") };
if (name === "@/lib/sse") return { SSEStream: class {} };
// English passthrough: assertions below match the source (English) messages.
if (name === "@/i18n")
return { t: (key, vars) => key.replace(/\{(\w+)\}/g, (m, k) => (vars && k in vars ? String(vars[k]) : m)) };

View file

@ -22,7 +22,7 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { t } from "@/i18n";
import { api, sseUrl } from "@/lib/api";
import { api, openSSE } from "@/lib/api";
import { MOCK } from "@/lib/mock/enabled";
import type { SharedBrowserAction, SharedBrowserInput, SharedBrowserStatus } from "@/lib/types";
import { cn } from "@/lib/utils";
@ -92,12 +92,12 @@ export default function SharedBrowserPage() {
// Live view: status and frame events.
React.useEffect(() => {
if (MOCK) return;
let es: EventSource | null = null;
let es: ReturnType<typeof openSSE> | null = null;
let closed = false;
const open = () => {
es = new EventSource(sseUrl("/api/browser/stream"));
es = openSSE("/api/browser/stream");
es.onopen = () => setConnected(true);
es.onerror = () => setConnected(false); // EventSource reconnects by itself
es.onerror = () => setConnected(false); // The stream reconnects by itself.
es.onmessage = (e) => {
try {
const ev = JSON.parse(e.data) as

View file

@ -50,7 +50,7 @@ import { Spinner } from "@/components/ui/spinner";
import { Textarea } from "@/components/ui/textarea";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { useSideQuestions } from "@/hooks/use-side-questions";
import { api, sseUrl } from "@/lib/api";
import { api, openSSE } from "@/lib/api";
import { shouldSubmitOnKey, useChatSendMode } from "@/lib/chat-send-mode";
import { formatBytes, formatDurationMs, formatTokens } from "@/lib/format";
import { MOCK } from "@/lib/mock/enabled";
@ -637,7 +637,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
// Refs backing SSE/loading without re-render churn.
const snapshotRef = React.useRef(0); // task-level snapshot cursor → SSE since=
const esRef = React.useRef<EventSource | null>(null);
const esRef = React.useRef<ReturnType<typeof openSSE> | null>(null);
const activeKeyRef = React.useRef(mainSessionKey(0)); // current session key (for SSE dispatch/unread)
const atBottomRef = React.useRef(true); // transcript pinned to bottom?
const llmToastSeqRef = React.useRef<Set<number>>(new Set());
@ -963,9 +963,7 @@ export function SessionsTab({ taskId, taskPaused = false }: { taskId: string; ta
};
});
// Open the single task SSE from the snapshot cursor.
const es = new EventSource(
sseUrl(`/api/exploration/activity/stream?task=${encodeURIComponent(taskId)}&since=${snapshotRef.current}`),
);
const es = openSSE(`/api/exploration/activity/stream?task=${encodeURIComponent(taskId)}&since=${snapshotRef.current}`);
esRef.current = es;
es.onopen = () => setSseLive(true);
es.onerror = () => setSseLive(false); // EventSource auto-reconnects; DB compensates the gap

View file

@ -3,7 +3,7 @@
import * as React from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { sseUrl } from "@/lib/api";
import { openSSE } from "@/lib/api";
import { MOCK } from "@/lib/mock/enabled";
import type { LogLine } from "@/lib/types";
import { cn } from "@/lib/utils";
@ -65,7 +65,7 @@ export default function LogsPage() {
setLines(MOCK_LOGS);
return;
}
const es = new EventSource(sseUrl("/api/logs/stream?since=0"));
const es = openSSE("/api/logs/stream?since=0");
es.onmessage = (e) => {
if (pausedRef.current) return;
try {

View file

@ -5,7 +5,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { t } from "@/i18n";
import { sseUrl } from "@/lib/api";
import { openSSE } from "@/lib/api";
import { isBtwCommand, type SideExchange, type SideHistory, sideAPI } from "@/lib/side-questions";
import { setVisibleInterval } from "@/lib/polling";
@ -130,7 +130,7 @@ export function useSideQuestions(parent: string | null) {
useEffect(() => {
if (!runningID) return;
const version = epoch.current;
const stream = new EventSource(sseUrl(`/api/side-questions/${runningID}/events`));
const stream = openSSE(`/api/side-questions/${runningID}/events`);
stream.addEventListener("snapshot", (event) => {
if (version !== epoch.current) return;
try {

View file

@ -7,6 +7,7 @@ import { t } from "@/i18n";
import type { ChatMention } from "@/lib/chat-mentions";
import { MOCK } from "@/lib/mock/enabled";
import { mockHandle } from "@/lib/mock/handler";
import { SSEStream } from "@/lib/sse";
import type {
ActiveFindingRetest,
Activity,
@ -160,7 +161,7 @@ export async function http<T>(path: string, init?: RequestInit): Promise<T> {
if (r.status === 401) {
if (typeof window !== "undefined") {
localStorage.removeItem("artex_token");
document.cookie = "artex_token=; path=/; max-age=0";
document.cookie = `artex_token=; path=/; max-age=0; SameSite=Lax${window.location.protocol === "https:" ? "; Secure" : ""}`;
window.location.href = "/login";
}
throw new Error(t("Unauthorized"));
@ -197,9 +198,8 @@ export async function http<T>(path: string, init?: RequestInit): Promise<T> {
// to the Go backend on :8787, whose CORS is open.
//
// Override either default with NEXT_PUBLIC_SSE_BASE (set it to "" to force same-origin).
// A same-origin stream sends the artex_token cookie. The query token is added only
// when base is non-empty, which is the dev connection to :8787: that origin cannot
// send the cookie.
// openSSE sends Authorization on both same-origin and direct development streams;
// a reusable session token never becomes part of the URL.
// mockReport returns a canned Markdown report for the demo.
function mockReport(_task?: string): string {
return `# ARTEX Penetration Test Report — Acme Corp
@ -232,9 +232,15 @@ export function sseUrl(path: string): string {
if (!base) {
return path;
}
const token = getToken();
const sep = path.includes("?") ? "&" : "?";
return token ? `${base}${path}${sep}token=${encodeURIComponent(token)}` : `${base}${path}`;
return `${base}${path}`;
}
export function openSSE(path: string): SSEStream {
return new SSEStream(sseUrl(path), getToken, () => {
localStorage.removeItem("artex_token");
document.cookie = `artex_token=; path=/; max-age=0; SameSite=Lax${window.location.protocol === "https:" ? "; Secure" : ""}`;
window.location.href = "/login";
});
}
const get = <T>(p: string) => http<T>(p);
@ -981,7 +987,7 @@ export const api = {
if (r.status === 401) {
if (typeof window !== "undefined") {
localStorage.removeItem("artex_token");
document.cookie = "artex_token=; path=/; max-age=0";
document.cookie = `artex_token=; path=/; max-age=0; SameSite=Lax${window.location.protocol === "https:" ? "; Secure" : ""}`;
window.location.href = "/login";
}
throw new Error(t("Unauthorized"));

View file

@ -20,7 +20,8 @@ export const auth = {
setToken(token: string): void {
localStorage.setItem(TOKEN_KEY, token);
// Also write a cookie for the Next.js middleware to read server-side
document.cookie = `${TOKEN_KEY}=${encodeURIComponent(token)}; path=/; max-age=${COOKIE_MAX_AGE}; SameSite=Lax`;
const secure = window.location.protocol === "https:" ? "; Secure" : "";
document.cookie = `${TOKEN_KEY}=${encodeURIComponent(token)}; path=/; max-age=${COOKIE_MAX_AGE}; SameSite=Lax${secure}`;
},
clearToken(): void {

166
web/src/lib/sse.ts Normal file
View file

@ -0,0 +1,166 @@
// Fetch-based SSE keeps bearer credentials in headers, including across origins.
// Native EventSource cannot set Authorization and would put the session in a URL.
const MAX_EVENT_CHARS = 8 * 1024 * 1024;
export class SSEParser {
private line: string;
private skipLF: boolean;
private data: string;
private event: string;
private id: string;
constructor(
lastEventID: string,
private emit: (event: MessageEvent) => void,
private cursor: (id: string) => void,
private retry: (delay: number) => void,
) {
this.line = "";
this.skipLF = false;
this.data = "";
this.event = "";
this.id = lastEventID;
}
feed(chunk: string): void {
for (const char of chunk) {
if (this.skipLF) {
this.skipLF = false;
if (char === "\n") continue;
}
if (char === "\r" || char === "\n") {
this.consumeLine();
this.skipLF = char === "\r";
} else {
this.line += char;
if (this.line.length + this.data.length > MAX_EVENT_CHARS) throw new Error("SSE event too large");
}
}
}
private consumeLine(): void {
const line = this.line;
this.line = "";
if (line === "") {
this.cursor(this.id);
if (this.data !== "") {
this.emit(new MessageEvent(this.event || "message", { data: this.data.slice(0, -1), lastEventId: this.id }));
}
this.data = "";
this.event = "";
return;
}
if (line.startsWith(":")) return;
const colon = line.indexOf(":");
const field = colon < 0 ? line : line.slice(0, colon);
let value = colon < 0 ? "" : line.slice(colon + 1);
if (value.startsWith(" ")) value = value.slice(1);
switch (field) {
case "data":
this.data += `${value}\n`;
break;
case "event":
this.event = value;
break;
case "id":
if (!value.includes("\0")) this.id = value;
break;
case "retry":
if (/^\d+$/.test(value)) this.retry(Math.max(100, Math.min(60000, Number(value))));
break;
}
}
}
export class SSEStream extends EventTarget {
onopen: ((event: Event) => void) | null = null;
onmessage: ((event: MessageEvent) => void) | null = null;
onerror: ((event: Event) => void) | null = null;
private controller = new AbortController();
private timer: ReturnType<typeof setTimeout> | undefined;
private lastEventID: string;
private retryDelay = 3000;
constructor(
private url: string,
private getToken: () => string | null,
private unauthorized: () => void,
) {
super();
this.lastEventID = "";
void this.connect();
}
close(): void {
this.controller.abort();
clearTimeout(this.timer);
}
private event(event: Event): void {
if (this.controller.signal.aborted) return;
if (event.type === "open") this.onopen?.(event);
else if (event.type === "error") this.onerror?.(event);
else if (event.type === "message") this.onmessage?.(event as MessageEvent);
this.dispatchEvent(event);
}
private async connect(): Promise<void> {
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
try {
const headers: Record<string, string> = { Accept: "text/event-stream" };
const token = this.getToken();
if (token) headers.Authorization = `Bearer ${token}`;
if (this.lastEventID) headers["Last-Event-ID"] = this.lastEventID;
const response = await fetch(this.url, {
headers,
signal: this.controller.signal,
credentials: "same-origin",
cache: "no-store",
redirect: "error",
});
if (response.status === 401 || response.status === 403 || response.status === 204) {
if (response.status !== 204) this.event(new Event("error"));
this.close();
if (response.status === 401) this.unauthorized();
return;
}
if (
!response.ok ||
!response.headers.get("Content-Type")?.toLowerCase().startsWith("text/event-stream") ||
!response.body
) {
await response.body?.cancel();
throw new Error("SSE connection failed");
}
this.event(new Event("open"));
const parser = new SSEParser(
this.lastEventID,
(event) => this.event(event),
(id) => {
this.lastEventID = id;
},
(delay) => {
this.retryDelay = delay;
},
);
const decoder = new TextDecoder();
reader = response.body.getReader();
while (!this.controller.signal.aborted) {
const { done, value } = await reader.read();
if (done) break;
parser.feed(decoder.decode(value, { stream: true }));
}
} catch {
// Network loss and malformed responses retry; close/401 abort permanently.
} finally {
await reader?.cancel().catch(() => {
// An already-failed reader may reject cancellation too.
});
reader?.releaseLock();
if (!this.controller.signal.aborted) {
this.event(new Event("error"));
if (!this.controller.signal.aborted) this.timer = setTimeout(() => void this.connect(), this.retryDelay);
}
}
}
}