Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,64 @@
# @toolctrl/realtime
`@toolctrl/realtime` is the public package boundary for typed realtime notification events, server-side Server-Sent Events (SSE) serialization, and the browser-facing subscriber. Downstream API and UI code should import from the package entrypoint only; internal source files are not part of the contract.
## Public contract
The package exports:
- `REALTIME_EVENT_NAMES` for stable event names: `notification.snapshot`, `notification.update`, `keepalive`, and `error`.
- `NotificationStreamItem` and realtime event types for notification snapshots, updates, keepalives, and redacted errors.
- `validateRealtimeEvent(input)` and `isRealtimeEvent(input)` for runtime validation before publishing or consuming events.
- `serializeRealtimeEvent(input, options)` for deterministic SSE frames with cursor `id:` lines and optional non-negative `retry:` hints.
- `serializeRealtimeComment(comment)` for keepalive comments.
- `subscribeToRealtime(options)` for browser subscribers that validate SSE JSON before dispatching typed snapshot, update, keepalive, and error callbacks.
## Diagnostics and secret handling
Realtime error events are diagnostics, not raw exception transports. Error payloads must stay limited to `requestId`, `cursor`, optional tenant/user identifiers, `code`, and a stable non-secret `message`.
Do not include provider payloads, tokens, cookies, authorization headers, API keys, request bodies, stack traces, raw exception messages, or arbitrary metadata in realtime events. Runtime validation rejects unsupported and secret-like keys so SSE frames can be shared with subscribers without leaking credentials or provider details.
The browser subscriber reports status transitions (`connecting`, `open`, `reconnecting`, `closed`) and redacted diagnostics through callbacks. Parse, validation, callback, EventSource, and reconnect diagnostics may include the event name, cursor, request id, retry attempt, or reconnect delay when those fields are already valid, but they must not include raw SSE payloads, headers, stack traces, tokens, provider payloads, or arbitrary metadata.
## API publisher example
```ts
import { REALTIME_EVENT_NAMES, serializeRealtimeEvent, type NotificationStreamItem } from "@toolctrl/realtime";
export function publishNotificationUpdate(item: NotificationStreamItem, requestId: string) {
return serializeRealtimeEvent(
{
event: REALTIME_EVENT_NAMES.notificationUpdate,
cursor: item.cursor,
requestId,
tenantId: item.tenantId,
userId: item.userId,
item,
},
{ retry: 5000 },
);
}
```
## UI subscriber example
```ts
import { subscribeToRealtime } from "@toolctrl/realtime";
const subscriber = subscribeToRealtime({
url: "https://api.example.com/v1/notifications/stream",
reconnect: { baseDelayMs: 1000, maxDelayMs: 30000, maxRetries: 5 },
onStatus: (status) => updateConnectionBadge(status),
onDiagnostic: (diagnostic) => logRealtimeDiagnostic(diagnostic),
onSnapshot: (event) => renderNotifications(event.items),
onUpdate: (event) => upsertNotification(event.item),
onKeepalive: (event) => markStreamAlive(event.requestId),
onError: (event) => showStreamError(event.message),
});
// Later, for route changes or component unmounts:
subscriber.close();
```
Importing from internal files such as `@toolctrl/realtime/src/events`, `@toolctrl/realtime/src/server`, or `@toolctrl/realtime/src/client` is unsupported; use `@toolctrl/realtime` so future internal refactors do not break downstream slices.
@@ -0,0 +1,20 @@
{
"name": "@toolctrl/realtime",
"version": "0.0.0",
"private": true,
"type": "module",
"sideEffects": false,
"exports": {
".": "./src/index.ts"
},
"scripts": {
"build": "pnpm run typecheck",
"test": "vitest run src",
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"devDependencies": {
"@types/node": "^25.0.0",
"typescript": "^5.3.2",
"vitest": "^3.2.4"
}
}
@@ -0,0 +1,180 @@
import { describe, expect, it } from "vitest";
import {
REALTIME_EVENT_NAMES,
isRealtimeEvent,
serializeRealtimeComment,
serializeRealtimeEvent,
subscribeToRealtime,
validateRealtimeEvent,
type NotificationStreamItem,
type RealtimeMessageEvent,
} from "./index.js";
const item: NotificationStreamItem = {
id: "delivery_boundary_1",
cursor: "2026-05-08T20:00:00.000Z:delivery_boundary_1",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "billing",
messageKey: "invoice.ready",
status: "PENDING",
attemptsMade: 0,
createdAt: "2026-05-08T19:59:00.000Z",
updatedAt: "2026-05-08T20:00:00.000Z",
sentAt: null,
readAt: null,
};
const baseEvent = {
cursor: item.cursor,
requestId: "req_boundary_1",
tenantId: "tenant_1",
userId: "user_1",
};
class FakeEventSource {
static instances: FakeEventSource[] = [];
onopen: (() => void) | null = null;
onmessage: ((event: RealtimeMessageEvent) => void) | null = null;
onerror: ((event: unknown) => void) | null = null;
closed = false;
constructor(readonly url: string | URL) {
FakeEventSource.instances.push(this);
}
emitMessage(data: unknown): void {
this.onmessage?.({ data: typeof data === "string" ? data : JSON.stringify(data) });
}
close(): void {
this.closed = true;
}
}
describe("public realtime package boundary", () => {
it("subscribes to notification updates through the entrypoint with redacted invalid diagnostics", () => {
FakeEventSource.instances = [];
const updates: NotificationStreamItem[] = [];
const diagnostics: unknown[] = [];
const subscriber = subscribeToRealtime({
url: "/api/notifications/stream",
EventSource: FakeEventSource,
reconnect: { enabled: false },
onUpdate: (event) => updates.push(event.item),
onDiagnostic: (diagnostic) => diagnostics.push(diagnostic),
});
const source = FakeEventSource.instances[0];
expect(source?.url).toBe("/api/notifications/stream");
expect(subscriber.currentSource).toBe(source);
source.emitMessage({ ...baseEvent, event: REALTIME_EVENT_NAMES.notificationUpdate, item });
source.emitMessage({ ...baseEvent, event: REALTIME_EVENT_NAMES.notificationUpdate, item: { ...item, providerPayload: "token=secret" } });
expect(updates).toEqual([item]);
expect(diagnostics).toEqual([
{
phase: "validation",
message: "notification item contains secret-like key: [redacted]",
eventName: REALTIME_EVENT_NAMES.notificationUpdate,
cursor: item.cursor,
requestId: "req_boundary_1",
},
]);
expect(JSON.stringify(diagnostics)).not.toMatch(/providerPayload|token=secret|authorization|Bearer/i);
subscriber.close();
expect(source.closed).toBe(true);
});
it("validates snapshot, update, error, and keepalive events from the entrypoint", () => {
expect(
validateRealtimeEvent({
...baseEvent,
event: REALTIME_EVENT_NAMES.notificationSnapshot,
items: [item],
}),
).toEqual({
...baseEvent,
event: REALTIME_EVENT_NAMES.notificationSnapshot,
items: [item],
});
expect(
validateRealtimeEvent({
...baseEvent,
event: REALTIME_EVENT_NAMES.notificationUpdate,
item,
}),
).toEqual({
...baseEvent,
event: REALTIME_EVENT_NAMES.notificationUpdate,
item,
});
expect(validateRealtimeEvent({ ...baseEvent, event: REALTIME_EVENT_NAMES.keepalive })).toEqual({ ...baseEvent, event: REALTIME_EVENT_NAMES.keepalive });
expect(validateRealtimeEvent({ ...baseEvent, event: REALTIME_EVENT_NAMES.error, code: "STREAM_FAILED", message: "Notification stream failed." })).toEqual({
...baseEvent,
event: REALTIME_EVENT_NAMES.error,
code: "STREAM_FAILED",
message: "Notification stream failed.",
});
});
it("publishes deterministic SSE frames through exported server APIs", () => {
const snapshotFrame = serializeRealtimeEvent({
...baseEvent,
event: REALTIME_EVENT_NAMES.notificationSnapshot,
items: [item],
});
expect(snapshotFrame).toBe(
`id: ${item.cursor}\nevent: notification.snapshot\ndata: {"event":"notification.snapshot","cursor":"${item.cursor}","requestId":"req_boundary_1","tenantId":"tenant_1","userId":"user_1","items":[{"id":"delivery_boundary_1","cursor":"${item.cursor}","tenantId":"tenant_1","userId":"user_1","channel":"IN_APP","category":"billing","messageKey":"invoice.ready","status":"PENDING","attemptsMade":0,"createdAt":"2026-05-08T19:59:00.000Z","updatedAt":"2026-05-08T20:00:00.000Z","sentAt":null,"readAt":null}]}\n\n`,
);
expect(
serializeRealtimeEvent(
{
...baseEvent,
event: REALTIME_EVENT_NAMES.notificationUpdate,
item: { ...item, status: "SENT", attemptsMade: 1, sentAt: "2026-05-08T20:01:00.000Z" },
},
{ retry: 3000 },
),
).toContain("retry: 3000\nid: 2026-05-08T20:00:00.000Z:delivery_boundary_1\nevent: notification.update\n");
expect(serializeRealtimeComment("keepalive req_boundary_1")).toBe(": keepalive req_boundary_1\n\n");
expect(serializeRealtimeEvent({ ...baseEvent, event: REALTIME_EVENT_NAMES.keepalive })).toContain("event: keepalive\n");
expect(serializeRealtimeEvent({ ...baseEvent, event: REALTIME_EVENT_NAMES.error, code: "STREAM_FAILED", message: "Notification stream failed." })).toContain(
'event: error\ndata: {"event":"error"',
);
});
it("rejects secret-bearing public inputs and keeps diagnostics redacted", () => {
expect(isRealtimeEvent({ ...baseEvent, event: REALTIME_EVENT_NAMES.notificationUpdate, item: { ...item, providerPayload: "token=secret" } })).toBe(false);
expect(() =>
serializeRealtimeEvent({
...baseEvent,
event: REALTIME_EVENT_NAMES.error,
code: "STREAM_FAILED",
message: "Notification stream failed.",
authorizationHeader: "Bearer secret",
}),
).toThrow(/secret-like key/);
const frame = serializeRealtimeEvent({
...baseEvent,
event: REALTIME_EVENT_NAMES.error,
code: "STREAM_FAILED",
message: "Notification stream failed.",
});
expect(frame).not.toMatch(/token|authorization|providerPayload|Bearer secret/i);
});
});
@@ -0,0 +1,292 @@
import { describe, expect, it, vi } from "vitest";
import { REALTIME_EVENT_NAMES, type NotificationStreamItem } from "./events.js";
import {
subscribeToRealtime,
type RealtimeEventSourceLike,
type RealtimeMessageEvent,
type RealtimeReconnectScheduler,
type RealtimeSubscriberDiagnostic,
type RealtimeSubscriberOptions,
} from "./client.js";
const item: NotificationStreamItem = {
id: "delivery_client_1",
cursor: "2026-05-08T20:00:00.000Z:delivery_client_1",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "billing",
messageKey: "invoice.ready",
status: "SENT",
attemptsMade: 1,
createdAt: "2026-05-08T19:59:00.000Z",
updatedAt: "2026-05-08T20:00:00.000Z",
sentAt: "2026-05-08T20:00:00.000Z",
readAt: null,
};
const baseEvent = {
cursor: item.cursor,
requestId: "req_client_1",
tenantId: "tenant_1",
userId: "user_1",
};
class FakeScheduler implements RealtimeReconnectScheduler {
private nextHandle = 1;
readonly timers = new Map<number, () => void>();
readonly delays: number[] = [];
readonly cleared: number[] = [];
setTimeout(callback: () => void, delayMs: number): number {
const handle = this.nextHandle;
this.nextHandle += 1;
this.timers.set(handle, callback);
this.delays.push(delayMs);
return handle;
}
clearTimeout(handle: unknown): void {
if (typeof handle === "number") {
this.cleared.push(handle);
this.timers.delete(handle);
}
}
runNext(): void {
const [handle, callback] = [...this.timers.entries()][0] ?? [];
if (handle === undefined || callback === undefined) {
throw new Error("No pending reconnect timer.");
}
this.timers.delete(handle);
callback();
}
}
class FakeEventSource implements RealtimeEventSourceLike {
static instances: FakeEventSource[] = [];
readonly listeners = new Map<string, Array<(event: RealtimeMessageEvent) => void>>();
onopen: (() => void) | null = null;
onmessage: ((event: RealtimeMessageEvent) => void) | null = null;
onerror: ((event: unknown) => void) | null = null;
closed = false;
constructor(readonly url: string | URL) {
FakeEventSource.instances.push(this);
}
open(): void {
this.onopen?.();
}
emit(data: unknown): void {
this.onmessage?.({ data: typeof data === "string" ? data : JSON.stringify(data) });
}
emitNamed(type: string, data: unknown): void {
const message = { data: typeof data === "string" ? data : JSON.stringify(data), type };
for (const listener of this.listeners.get(type) ?? []) {
listener(message);
}
}
addEventListener(type: string, listener: (event: RealtimeMessageEvent) => void): void {
const listeners = this.listeners.get(type) ?? [];
listeners.push(listener);
this.listeners.set(type, listeners);
}
fail(): void {
this.onerror?.({});
}
close(): void {
this.closed = true;
}
}
function createSubscriber(overrides: Partial<RealtimeSubscriberOptions> = {}) {
FakeEventSource.instances = [];
const diagnostics: RealtimeSubscriberDiagnostic[] = [];
const statuses: string[] = [];
const subscriber = subscribeToRealtime({
...overrides,
url: overrides.url ?? "https://example.test/stream",
EventSource: overrides.EventSource ?? FakeEventSource,
onDiagnostic: (diagnostic) => diagnostics.push(diagnostic),
onStatus: (status) => statuses.push(status),
});
const source = FakeEventSource.instances[0];
return { diagnostics, source, statuses, subscriber };
}
function createScheduledSubscriber(options: Partial<RealtimeSubscriberOptions> = {}) {
const scheduler = new FakeScheduler();
const result = createSubscriber({
...options,
reconnect: { baseDelayMs: 100, maxDelayMs: 250, maxRetries: 3, ...options.reconnect, scheduler },
});
return { ...result, scheduler };
}
describe("realtime client subscriber", () => {
it("creates one EventSource instance and dispatches typed realtime events", () => {
const onSnapshot = vi.fn();
const onUpdate = vi.fn();
const onKeepalive = vi.fn();
const onError = vi.fn();
const { diagnostics, source, statuses } = createSubscriber({ onSnapshot, onUpdate, onKeepalive, onError });
source.open();
source.emitNamed(REALTIME_EVENT_NAMES.notificationSnapshot, { ...baseEvent, event: REALTIME_EVENT_NAMES.notificationSnapshot, items: [item] });
source.emitNamed(REALTIME_EVENT_NAMES.notificationUpdate, { ...baseEvent, event: REALTIME_EVENT_NAMES.notificationUpdate, item });
source.emitNamed(REALTIME_EVENT_NAMES.keepalive, { ...baseEvent, event: REALTIME_EVENT_NAMES.keepalive });
source.emitNamed(REALTIME_EVENT_NAMES.error, { ...baseEvent, event: REALTIME_EVENT_NAMES.error, code: "STREAM_FAILED", message: "Notification stream failed." });
expect(FakeEventSource.instances).toHaveLength(1);
expect([...source.listeners.keys()]).toEqual([
REALTIME_EVENT_NAMES.notificationSnapshot,
REALTIME_EVENT_NAMES.notificationUpdate,
REALTIME_EVENT_NAMES.keepalive,
REALTIME_EVENT_NAMES.error,
]);
expect(statuses).toEqual(["connecting", "open"]);
expect(onSnapshot).toHaveBeenCalledWith({ ...baseEvent, event: REALTIME_EVENT_NAMES.notificationSnapshot, items: [item] });
expect(onUpdate).toHaveBeenCalledWith({ ...baseEvent, event: REALTIME_EVENT_NAMES.notificationUpdate, item });
expect(onKeepalive).toHaveBeenCalledWith({ ...baseEvent, event: REALTIME_EVENT_NAMES.keepalive });
expect(onError).toHaveBeenCalledWith({ ...baseEvent, event: REALTIME_EVENT_NAMES.error, code: "STREAM_FAILED", message: "Notification stream failed." });
expect(diagnostics).toEqual([]);
});
it("reports malformed JSON and validation failures with redacted diagnostics", () => {
const { diagnostics, source } = createSubscriber();
source.emit("{not-json");
source.emit({ ...baseEvent, event: "notification.unknown", authorizationHeader: "Bearer secret-token" });
source.emit({ ...baseEvent, event: REALTIME_EVENT_NAMES.notificationUpdate, item: { ...item, providerPayload: "super-secret-token" } });
expect(diagnostics).toEqual([
{ phase: "parse", message: expect.stringContaining("[redacted]") },
{
phase: "validation",
message: "event must be a supported realtime event name",
eventName: "notification.unknown",
cursor: item.cursor,
requestId: "req_client_1",
},
{
phase: "validation",
message: "notification item contains secret-like key: [redacted]",
eventName: REALTIME_EVENT_NAMES.notificationUpdate,
cursor: item.cursor,
requestId: "req_client_1",
},
]);
expect(JSON.stringify(diagnostics)).not.toMatch(/secret-token|super-secret-token|Bearer/i);
});
it("reports EventSource and callback exceptions without exposing stack traces", () => {
const onUpdate = vi.fn(() => {
throw new Error("callback leaked token=abc123");
});
const { diagnostics, source } = createSubscriber({ reconnect: { enabled: false }, onUpdate });
source.fail();
source.emit({ ...baseEvent, event: REALTIME_EVENT_NAMES.notificationUpdate, item });
expect(diagnostics).toEqual([
{ phase: "eventsource", message: "EventSource reported an error." },
{
phase: "callback",
message: "callback leaked token=abc123",
eventName: REALTIME_EVENT_NAMES.notificationUpdate,
cursor: item.cursor,
requestId: "req_client_1",
},
]);
expect(JSON.stringify(diagnostics)).not.toContain("Error:");
});
it("closes explicitly once and ignores later messages or duplicate close calls", () => {
const onKeepalive = vi.fn();
const { source, statuses, subscriber } = createSubscriber({ onKeepalive });
subscriber.close();
subscriber.close();
source.open();
source.fail();
source.emit({ ...baseEvent, event: REALTIME_EVENT_NAMES.keepalive });
expect(source.closed).toBe(true);
expect(statuses).toEqual(["connecting", "closed"]);
expect(onKeepalive).not.toHaveBeenCalled();
});
it("schedules deterministic capped reconnects and replaces failed sources", () => {
const { diagnostics, scheduler, source, statuses } = createScheduledSubscriber();
source.fail();
expect(source.closed).toBe(true);
expect(scheduler.delays).toEqual([100]);
expect(scheduler.timers.size).toBe(1);
expect(FakeEventSource.instances).toHaveLength(1);
expect(statuses).toEqual(["connecting", "reconnecting"]);
expect(diagnostics).toContainEqual({ phase: "reconnect", message: "Realtime reconnect scheduled.", retryAttempt: 1, delayMs: 100 });
scheduler.runNext();
const retrySource = FakeEventSource.instances[1];
expect(FakeEventSource.instances).toHaveLength(2);
expect(retrySource.closed).toBe(false);
expect(statuses).toEqual(["connecting", "reconnecting", "connecting"]);
});
it("stops reconnecting after maxRetries is reached", () => {
const { diagnostics, scheduler, source, statuses } = createScheduledSubscriber({ reconnect: { baseDelayMs: 50, maxDelayMs: 75, maxRetries: 2 } });
source.fail();
scheduler.runNext();
FakeEventSource.instances[1].fail();
scheduler.runNext();
FakeEventSource.instances[2].fail();
expect(FakeEventSource.instances).toHaveLength(3);
expect(scheduler.delays).toEqual([50, 75]);
expect(scheduler.timers.size).toBe(0);
expect(diagnostics).toContainEqual({ phase: "reconnect", message: "Realtime reconnect retry limit reached.", retryAttempt: 2 });
expect(statuses.at(-1)).toBe("closed");
});
it("resets retry attempts after a successful open", () => {
const { diagnostics, scheduler, source } = createScheduledSubscriber({ reconnect: { baseDelayMs: 100, maxDelayMs: 1_000, maxRetries: 3 } });
source.fail();
scheduler.runNext();
FakeEventSource.instances[1].open();
FakeEventSource.instances[1].fail();
expect(scheduler.delays).toEqual([100, 100]);
expect(diagnostics).toContainEqual({ phase: "reconnect", message: "Realtime reconnect scheduled.", retryAttempt: 1, delayMs: 100 });
});
it("cancels pending reconnects and prevents future sources after explicit close", () => {
const { scheduler, source, statuses, subscriber } = createScheduledSubscriber();
source.fail();
subscriber.close();
expect(source.closed).toBe(true);
expect(scheduler.timers.size).toBe(0);
expect(scheduler.cleared).toEqual([1]);
expect(statuses).toEqual(["connecting", "reconnecting", "closed"]);
expect(() => scheduler.runNext()).toThrow("No pending reconnect timer.");
expect(FakeEventSource.instances).toHaveLength(1);
});
});
@@ -0,0 +1,320 @@
import { REALTIME_EVENT_NAMES, validateRealtimeEvent, type KeepaliveEvent, type NotificationSnapshotEvent, type NotificationUpdateEvent, type RealtimeErrorEvent } from "./events.js";
export type RealtimeSubscriberStatus = "connecting" | "open" | "reconnecting" | "closed";
export type RealtimeSubscriberDiagnostic = {
phase: "parse" | "validation" | "callback" | "eventsource" | "reconnect";
message: string;
eventName?: string;
cursor?: string;
requestId?: string;
retryAttempt?: number;
delayMs?: number;
};
export type RealtimeMessageEvent = {
data: string;
type?: string;
};
export type RealtimeEventSourceLike = {
onopen: (() => void) | null;
onmessage: ((event: RealtimeMessageEvent) => void) | null;
onerror: ((event: unknown) => void) | null;
addEventListener?: (type: string, listener: (event: RealtimeMessageEvent) => void) => void;
close: () => void;
};
export type RealtimeEventSourceConstructor = new (url: string | URL) => RealtimeEventSourceLike;
export type RealtimeReconnectScheduler = {
setTimeout: (callback: () => void, delayMs: number) => unknown;
clearTimeout: (handle: unknown) => void;
};
export type RealtimeReconnectOptions = {
enabled?: boolean;
baseDelayMs?: number;
maxDelayMs?: number;
maxRetries?: number;
scheduler?: RealtimeReconnectScheduler;
};
export type RealtimeSubscriberOptions = {
url: string | URL;
EventSource?: RealtimeEventSourceConstructor;
reconnect?: RealtimeReconnectOptions;
onStatus?: (status: RealtimeSubscriberStatus) => void;
onDiagnostic?: (diagnostic: RealtimeSubscriberDiagnostic) => void;
onSnapshot?: (event: NotificationSnapshotEvent) => void;
onUpdate?: (event: NotificationUpdateEvent) => void;
onKeepalive?: (event: KeepaliveEvent) => void;
onError?: (event: RealtimeErrorEvent) => void;
};
export type RealtimeSubscriber = {
readonly source: RealtimeEventSourceLike;
readonly currentSource: RealtimeEventSourceLike;
close: () => void;
};
type ParsedEventShape = {
event?: unknown;
cursor?: unknown;
requestId?: unknown;
};
const MAX_DIAGNOSTIC_MESSAGE_LENGTH = 160;
const DEFAULT_RECONNECT_BASE_DELAY_MS = 1_000;
const DEFAULT_RECONNECT_MAX_DELAY_MS = 30_000;
const DEFAULT_RECONNECT_MAX_RETRIES = 5;
export function subscribeToRealtime(options: RealtimeSubscriberOptions): RealtimeSubscriber {
const EventSourceConstructor = options.EventSource ?? getGlobalEventSource();
const reconnect = normalizeReconnectOptions(options.reconnect);
let closed = false;
let retryAttempts = 0;
let reconnectTimer: unknown;
let source = connect();
function connect(): RealtimeEventSourceLike {
clearReconnectTimer();
const nextSource = new EventSourceConstructor(options.url);
emitStatus(options, "connecting");
nextSource.onopen = () => {
if (!closed) {
retryAttempts = 0;
emitStatus(options, "open");
}
};
nextSource.onmessage = (message) => {
if (!closed) {
handleMessage(options, message);
}
};
registerNamedRealtimeEventListeners(nextSource, options, () => closed);
nextSource.onerror = () => {
if (!closed) {
handleEventSourceError(nextSource);
}
};
return nextSource;
}
function handleEventSourceError(failedSource: RealtimeEventSourceLike): void {
emitDiagnostic(options, { phase: "eventsource", message: "EventSource reported an error." });
failedSource.close();
if (!reconnect.enabled) {
emitStatus(options, "closed");
return;
}
if (retryAttempts >= reconnect.maxRetries) {
emitDiagnostic(options, {
phase: "reconnect",
message: "Realtime reconnect retry limit reached.",
retryAttempt: retryAttempts,
});
emitStatus(options, "closed");
return;
}
retryAttempts += 1;
const delayMs = reconnectDelay(retryAttempts, reconnect.baseDelayMs, reconnect.maxDelayMs);
emitDiagnostic(options, {
phase: "reconnect",
message: "Realtime reconnect scheduled.",
retryAttempt: retryAttempts,
delayMs,
});
emitStatus(options, "reconnecting");
reconnectTimer = reconnect.scheduler.setTimeout(() => {
reconnectTimer = undefined;
if (!closed) {
source = connect();
}
}, delayMs);
}
function clearReconnectTimer(): void {
if (reconnectTimer !== undefined) {
reconnect.scheduler.clearTimeout(reconnectTimer);
reconnectTimer = undefined;
}
}
return {
get source() {
return source;
},
get currentSource() {
return source;
},
close: () => {
if (closed) {
return;
}
closed = true;
clearReconnectTimer();
source.close();
emitStatus(options, "closed");
},
};
}
function registerNamedRealtimeEventListeners(
source: RealtimeEventSourceLike,
options: RealtimeSubscriberOptions,
isClosed: () => boolean
): void {
if (typeof source.addEventListener !== "function") {
return;
}
for (const eventName of Object.values(REALTIME_EVENT_NAMES)) {
source.addEventListener(eventName, (message) => {
if (!isClosed()) {
handleMessage(options, message);
}
});
}
}
type NormalizedRealtimeReconnectOptions = Required<RealtimeReconnectOptions>;
function normalizeReconnectOptions(options: RealtimeReconnectOptions | undefined): NormalizedRealtimeReconnectOptions {
const baseDelayMs = normalizePositiveInteger(options?.baseDelayMs, DEFAULT_RECONNECT_BASE_DELAY_MS);
return {
enabled: options?.enabled ?? true,
baseDelayMs,
maxDelayMs: Math.max(baseDelayMs, normalizePositiveInteger(options?.maxDelayMs, DEFAULT_RECONNECT_MAX_DELAY_MS)),
maxRetries: normalizeNonNegativeInteger(options?.maxRetries, DEFAULT_RECONNECT_MAX_RETRIES),
scheduler: options?.scheduler ?? globalReconnectScheduler,
};
}
function reconnectDelay(retryAttempt: number, baseDelayMs: number, maxDelayMs: number): number {
return Math.min(maxDelayMs, baseDelayMs * 2 ** (retryAttempt - 1));
}
function normalizePositiveInteger(value: number | undefined, fallback: number): number {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
}
function normalizeNonNegativeInteger(value: number | undefined, fallback: number): number {
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
}
const globalReconnectScheduler: RealtimeReconnectScheduler = {
setTimeout: (callback, delayMs) => globalThis.setTimeout(callback, delayMs),
clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof globalThis.setTimeout>),
};
function handleMessage(options: RealtimeSubscriberOptions, message: RealtimeMessageEvent): void {
let parsed: unknown;
try {
parsed = JSON.parse(message.data);
} catch {
emitDiagnostic(options, { phase: "parse", message: "Malformed realtime event JSON: [redacted]" });
return;
}
try {
const event = validateRealtimeEvent(parsed);
switch (event.event) {
case REALTIME_EVENT_NAMES.notificationSnapshot:
invokeCallback(options, "onSnapshot", event);
return;
case REALTIME_EVENT_NAMES.notificationUpdate:
invokeCallback(options, "onUpdate", event);
return;
case REALTIME_EVENT_NAMES.keepalive:
invokeCallback(options, "onKeepalive", event);
return;
case REALTIME_EVENT_NAMES.error:
invokeCallback(options, "onError", event);
return;
}
} catch (error) {
emitDiagnostic(options, {
...extractDiagnosticContext(parsed),
phase: "validation",
message: redactedErrorMessage(error),
});
}
}
function invokeCallback<Event>(options: RealtimeSubscriberOptions, key: keyof RealtimeSubscriberOptions, event: Event): void {
const callback = options[key];
if (typeof callback !== "function") {
return;
}
try {
(callback as (event: Event) => void)(event);
} catch (error) {
emitDiagnostic(options, {
...extractDiagnosticContext(event),
phase: "callback",
message: redactedErrorMessage(error),
});
}
}
function emitStatus(options: RealtimeSubscriberOptions, status: RealtimeSubscriberStatus): void {
options.onStatus?.(status);
}
function emitDiagnostic(options: RealtimeSubscriberOptions, diagnostic: RealtimeSubscriberDiagnostic): void {
options.onDiagnostic?.(diagnostic);
}
function extractDiagnosticContext(input: unknown): Pick<RealtimeSubscriberDiagnostic, "eventName" | "cursor" | "requestId"> {
if (!isRecord(input)) {
return {};
}
const event = input as ParsedEventShape;
return {
eventName: typeof event.event === "string" ? event.event : undefined,
cursor: typeof event.cursor === "string" ? event.cursor : undefined,
requestId: typeof event.requestId === "string" ? event.requestId : undefined,
};
}
function redactedErrorMessage(error: unknown): string {
if (!(error instanceof Error)) {
return "Realtime subscriber rejected an invalid event.";
}
return error.message.replace(/: .+$/u, ": [redacted]").slice(0, MAX_DIAGNOSTIC_MESSAGE_LENGTH);
}
function getGlobalEventSource(): RealtimeEventSourceConstructor {
const constructor = globalThis.EventSource as RealtimeEventSourceConstructor | undefined;
if (constructor === undefined) {
throw new Error("EventSource is not available; provide an EventSource option.");
}
return constructor;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
@@ -0,0 +1,146 @@
import { describe, expect, it } from "vitest";
import { REALTIME_EVENT_NAMES, isRealtimeEvent, validateRealtimeEvent, type NotificationStreamItem } from "./events.js";
const item: NotificationStreamItem = {
id: "delivery_1",
cursor: "2026-05-08T20:00:00.000Z:delivery_1",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "billing",
messageKey: "invoice.ready",
status: "SENT",
attemptsMade: 1,
createdAt: "2026-05-08T19:59:00.000Z",
updatedAt: "2026-05-08T20:00:00.000Z",
sentAt: "2026-05-08T20:00:00.000Z",
readAt: null,
};
describe("realtime event contract", () => {
it("accepts and normalizes a public notification snapshot", () => {
expect(
validateRealtimeEvent({
event: REALTIME_EVENT_NAMES.notificationSnapshot,
cursor: "2026-05-08T20:00:00.000Z:delivery_1",
requestId: "req_1",
tenantId: "tenant_1",
userId: "user_1",
items: [item],
}),
).toEqual({
event: REALTIME_EVENT_NAMES.notificationSnapshot,
cursor: "2026-05-08T20:00:00.000Z:delivery_1",
requestId: "req_1",
tenantId: "tenant_1",
userId: "user_1",
items: [item],
});
});
it("accepts update, keepalive, and redacted error envelopes", () => {
expect(
validateRealtimeEvent({
event: REALTIME_EVENT_NAMES.notificationUpdate,
cursor: item.cursor,
requestId: "req_skipped",
item: { ...item, status: "SKIPPED", attemptsMade: 0, sentAt: null },
}),
).toMatchObject({ event: REALTIME_EVENT_NAMES.notificationUpdate, item: expect.objectContaining({ status: "SKIPPED" }) });
expect(
validateRealtimeEvent({
event: REALTIME_EVENT_NAMES.notificationUpdate,
cursor: item.cursor,
requestId: "req_2",
item,
}),
).toMatchObject({ event: REALTIME_EVENT_NAMES.notificationUpdate, item });
expect(
validateRealtimeEvent({
event: REALTIME_EVENT_NAMES.keepalive,
cursor: item.cursor,
requestId: "req_3",
}),
).toEqual({ event: REALTIME_EVENT_NAMES.keepalive, cursor: item.cursor, requestId: "req_3" });
expect(
validateRealtimeEvent({
event: REALTIME_EVENT_NAMES.error,
cursor: item.cursor,
requestId: "req_4",
code: "STREAM_FAILED",
message: "Notification stream failed.",
}),
).toEqual({
event: REALTIME_EVENT_NAMES.error,
cursor: item.cursor,
requestId: "req_4",
code: "STREAM_FAILED",
message: "Notification stream failed.",
});
});
it("rejects invalid event names and malformed identifiers", () => {
expect(() => validateRealtimeEvent({ event: "notification", cursor: item.cursor, requestId: "req_1", items: [] })).toThrow(
/supported realtime event name/,
);
expect(() => validateRealtimeEvent({ event: REALTIME_EVENT_NAMES.keepalive, cursor: 123, requestId: "req_1" })).toThrow(/cursor/);
expect(() => validateRealtimeEvent({ event: REALTIME_EVENT_NAMES.keepalive, cursor: item.cursor, requestId: "" })).toThrow(/requestId/);
expect(isRealtimeEvent({ event: "notification", cursor: item.cursor, requestId: "req_1" })).toBe(false);
});
it("rejects malformed items and unsupported public fields", () => {
expect(() =>
validateRealtimeEvent({
event: REALTIME_EVENT_NAMES.notificationSnapshot,
cursor: item.cursor,
requestId: "req_1",
items: [{ ...item, channel: "EMAIL" }],
}),
).toThrow(/IN_APP/);
expect(() =>
validateRealtimeEvent({
event: REALTIME_EVENT_NAMES.notificationSnapshot,
cursor: item.cursor,
requestId: "req_1",
items: [{ ...item, status: "DELIVERED" }],
}),
).toThrow(/supported notification status/);
expect(() =>
validateRealtimeEvent({
event: REALTIME_EVENT_NAMES.notificationSnapshot,
cursor: item.cursor,
requestId: "req_1",
items: [{ ...item, providerMessageId: "provider_1" }],
}),
).toThrow(/secret-like key/);
});
it("rejects metadata leakage attempts on envelopes and error diagnostics", () => {
expect(() =>
validateRealtimeEvent({
event: REALTIME_EVENT_NAMES.notificationUpdate,
cursor: item.cursor,
requestId: "req_1",
item,
authorizationHeader: "Bearer token",
}),
).toThrow(/secret-like key/);
expect(() =>
validateRealtimeEvent({
event: REALTIME_EVENT_NAMES.error,
cursor: item.cursor,
requestId: "req_1",
code: "STREAM_FAILED",
message: "Notification stream failed.",
stack: "Error: provider token abc",
}),
).toThrow(/secret-like key/);
});
});
@@ -0,0 +1,237 @@
export const REALTIME_EVENT_NAMES = {
notificationSnapshot: "notification.snapshot",
notificationUpdate: "notification.update",
keepalive: "keepalive",
error: "error",
} as const;
export type RealtimeEventName = (typeof REALTIME_EVENT_NAMES)[keyof typeof REALTIME_EVENT_NAMES];
export type NotificationDeliveryStatus = "PENDING" | "SENT" | "FAILED" | "SKIPPED" | "READ";
export type NotificationChannel = "IN_APP";
export type NotificationStreamCursor = string;
export type NotificationStreamItem = {
id: string;
cursor: NotificationStreamCursor;
tenantId?: string | null;
userId?: string | null;
channel: NotificationChannel;
category: string;
messageKey: string;
status: NotificationDeliveryStatus;
attemptsMade: number;
createdAt: string;
updatedAt: string;
sentAt?: string | null;
readAt?: string | null;
};
export type RealtimeEventBase = {
event: RealtimeEventName;
cursor: string;
requestId: string;
tenantId?: string | null;
userId?: string | null;
};
export type NotificationSnapshotEvent = RealtimeEventBase & {
event: typeof REALTIME_EVENT_NAMES.notificationSnapshot;
items: NotificationStreamItem[];
};
export type NotificationUpdateEvent = RealtimeEventBase & {
event: typeof REALTIME_EVENT_NAMES.notificationUpdate;
item: NotificationStreamItem;
};
export type KeepaliveEvent = RealtimeEventBase & {
event: typeof REALTIME_EVENT_NAMES.keepalive;
};
export type RealtimeErrorEvent = RealtimeEventBase & {
event: typeof REALTIME_EVENT_NAMES.error;
code: string;
message: string;
};
export type RealtimeEvent = NotificationSnapshotEvent | NotificationUpdateEvent | KeepaliveEvent | RealtimeErrorEvent;
const REALTIME_EVENT_NAME_VALUES = new Set<RealtimeEventName>(Object.values(REALTIME_EVENT_NAMES));
const NOTIFICATION_STATUSES = new Set<NotificationDeliveryStatus>(["PENDING", "SENT", "FAILED", "SKIPPED", "READ"]);
const SECRET_KEY_PATTERN = /authorization|cookie|password|secret|token|api[-_]?key|payload|provider|exception|stack|header|body|metadata/i;
const ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
const MAX_STRING_LENGTH = 500;
const MAX_ITEMS_PER_EVENT = 100;
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function assertAllowedKeys(value: Record<string, unknown>, allowedKeys: ReadonlySet<string>, label: string): void {
for (const key of Object.keys(value)) {
if (SECRET_KEY_PATTERN.test(key)) {
throw new Error(`${label} contains secret-like key: ${key}`);
}
if (!allowedKeys.has(key)) {
throw new Error(`${label} contains unsupported key: ${key}`);
}
}
}
function normalizeRequiredString(value: unknown, label: string): string {
if (typeof value !== "string") {
throw new Error(`${label} must be a string`);
}
const normalized = value.trim();
if (!normalized) {
throw new Error(`${label} must not be empty`);
}
if (normalized.length > MAX_STRING_LENGTH) {
throw new Error(`${label} is too long`);
}
return normalized;
}
function normalizeOptionalString(value: unknown, label: string): string | null | undefined {
if (value === undefined) {
return undefined;
}
if (value === null) {
return null;
}
return normalizeRequiredString(value, label);
}
function normalizeOptionalIsoDate(value: unknown, label: string): string | null | undefined {
if (value === undefined) {
return undefined;
}
if (value === null) {
return null;
}
const normalized = normalizeRequiredString(value, label);
if (!ISO_DATE_PATTERN.test(normalized) || Number.isNaN(Date.parse(normalized))) {
throw new Error(`${label} must be an ISO timestamp`);
}
return normalized;
}
function normalizeStatus(value: unknown): NotificationDeliveryStatus {
if (typeof value !== "string" || !NOTIFICATION_STATUSES.has(value as NotificationDeliveryStatus)) {
throw new Error("item.status must be a supported notification status");
}
return value as NotificationDeliveryStatus;
}
function normalizeAttemptsMade(value: unknown): number {
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
throw new Error("item.attemptsMade must be a non-negative integer");
}
return value;
}
function normalizeItem(value: unknown): NotificationStreamItem {
if (!isRecord(value)) {
throw new Error("notification item must be an object");
}
assertAllowedKeys(
value,
new Set(["id", "cursor", "tenantId", "userId", "channel", "category", "messageKey", "status", "attemptsMade", "createdAt", "updatedAt", "sentAt", "readAt"]),
"notification item",
);
if (value.channel !== "IN_APP") {
throw new Error("item.channel must be IN_APP");
}
return {
id: normalizeRequiredString(value.id, "item.id"),
cursor: normalizeRequiredString(value.cursor, "item.cursor"),
tenantId: normalizeOptionalString(value.tenantId, "item.tenantId") ?? null,
userId: normalizeOptionalString(value.userId, "item.userId") ?? null,
channel: "IN_APP",
category: normalizeRequiredString(value.category, "item.category"),
messageKey: normalizeRequiredString(value.messageKey, "item.messageKey"),
status: normalizeStatus(value.status),
attemptsMade: normalizeAttemptsMade(value.attemptsMade),
createdAt: normalizeOptionalIsoDate(value.createdAt, "item.createdAt") ?? "",
updatedAt: normalizeOptionalIsoDate(value.updatedAt, "item.updatedAt") ?? "",
sentAt: normalizeOptionalIsoDate(value.sentAt, "item.sentAt") ?? null,
readAt: normalizeOptionalIsoDate(value.readAt, "item.readAt") ?? null,
};
}
function normalizeBase(value: Record<string, unknown>): RealtimeEventBase {
const event = value.event;
if (typeof event !== "string" || !REALTIME_EVENT_NAME_VALUES.has(event as RealtimeEventName)) {
throw new Error("event must be a supported realtime event name");
}
return {
event: event as RealtimeEventName,
cursor: normalizeRequiredString(value.cursor, "cursor"),
requestId: normalizeRequiredString(value.requestId, "requestId"),
tenantId: normalizeOptionalString(value.tenantId, "tenantId"),
userId: normalizeOptionalString(value.userId, "userId"),
};
}
export function validateRealtimeEvent(input: unknown): RealtimeEvent {
if (!isRecord(input)) {
throw new Error("realtime event must be an object");
}
const base = normalizeBase(input);
switch (base.event) {
case REALTIME_EVENT_NAMES.notificationSnapshot: {
assertAllowedKeys(input, new Set(["event", "cursor", "requestId", "tenantId", "userId", "items"]), "snapshot event");
if (!Array.isArray(input.items)) {
throw new Error("snapshot event items must be an array");
}
if (input.items.length > MAX_ITEMS_PER_EVENT) {
throw new Error("snapshot event contains too many items");
}
return { ...base, event: REALTIME_EVENT_NAMES.notificationSnapshot, items: input.items.map(normalizeItem) };
}
case REALTIME_EVENT_NAMES.notificationUpdate:
assertAllowedKeys(input, new Set(["event", "cursor", "requestId", "tenantId", "userId", "item"]), "update event");
return { ...base, event: REALTIME_EVENT_NAMES.notificationUpdate, item: normalizeItem(input.item) };
case REALTIME_EVENT_NAMES.keepalive:
assertAllowedKeys(input, new Set(["event", "cursor", "requestId", "tenantId", "userId"]), "keepalive event");
return { ...base, event: REALTIME_EVENT_NAMES.keepalive };
case REALTIME_EVENT_NAMES.error:
assertAllowedKeys(input, new Set(["event", "cursor", "requestId", "tenantId", "userId", "code", "message"]), "error event");
return {
...base,
event: REALTIME_EVENT_NAMES.error,
code: normalizeRequiredString(input.code, "code"),
message: normalizeRequiredString(input.message, "message"),
};
}
}
export function isRealtimeEvent(input: unknown): input is RealtimeEvent {
try {
validateRealtimeEvent(input);
return true;
} catch {
return false;
}
}
@@ -0,0 +1,90 @@
import { describe, expect, it } from "vitest";
import { REALTIME_EVENT_NAMES, type NotificationStreamItem } from "./events.js";
import {
assertNotificationEventInAppScope,
assertNotificationItemInAppScope,
normalizeNotificationStreamScope,
redactNotificationGuardDiagnostic,
} from "./guards.js";
const item: NotificationStreamItem = {
id: "delivery_guard_1",
cursor: "2026-05-08T20:00:00.000Z:delivery_guard_1",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "billing",
messageKey: "invoice.ready",
status: "SENT",
attemptsMade: 1,
createdAt: "2026-05-08T19:59:00.000Z",
updatedAt: "2026-05-08T20:00:00.000Z",
sentAt: "2026-05-08T20:00:00.000Z",
readAt: null,
};
const scope = { tenantId: "tenant_1", userId: "user_1" };
describe("notification stream guards", () => {
it("normalizes trimmed valid stream scope", () => {
expect(normalizeNotificationStreamScope({ tenantId: " tenant_1 ", userId: " user_1 ", afterCursor: " cursor_1 " })).toEqual({
tenantId: "tenant_1",
userId: "user_1",
afterCursor: "cursor_1",
});
});
it("rejects missing or blank tenant and user scope", () => {
expect(() => normalizeNotificationStreamScope({ userId: "user_1" })).toThrow(/tenantId is required/);
expect(() => normalizeNotificationStreamScope({ tenantId: " ", userId: "user_1" })).toThrow(/tenantId must not be empty/);
expect(() => normalizeNotificationStreamScope({ tenantId: "tenant_1" })).toThrow(/userId is required/);
expect(() => normalizeNotificationStreamScope({ tenantId: "tenant_1", userId: "\t" })).toThrow(/userId must not be empty/);
});
it("rejects non-IN_APP notification items", () => {
expect(() => assertNotificationItemInAppScope({ ...item, channel: "EMAIL" as "IN_APP" }, scope)).toThrow(/IN_APP/);
});
it("rejects tenant and user mismatches between stream scope and items", () => {
expect(() => assertNotificationItemInAppScope({ ...item, tenantId: "tenant_2" }, scope)).toThrow(/item\.tenantId/);
expect(() => assertNotificationItemInAppScope({ ...item, userId: "user_2" }, scope)).toThrow(/item\.userId/);
});
it("rejects tenant and user mismatches between stream scope and events", () => {
expect(() =>
assertNotificationEventInAppScope(
{
event: REALTIME_EVENT_NAMES.notificationSnapshot,
cursor: item.cursor,
requestId: "req_guard_1",
tenantId: "tenant_2",
userId: "user_1",
items: [item],
},
scope,
),
).toThrow(/event\.tenantId/);
expect(() =>
assertNotificationEventInAppScope(
{
event: REALTIME_EVENT_NAMES.notificationUpdate,
cursor: item.cursor,
requestId: "req_guard_2",
tenantId: "tenant_1",
userId: "user_1",
item: { ...item, userId: "user_2" },
},
scope,
),
).toThrow(/item\.userId/);
});
it("redacts secret-like guard diagnostic text", () => {
const diagnostic = redactNotificationGuardDiagnostic(new Error("provider payload token=secret Bearer abc123 should not leak"));
expect(diagnostic).toContain("[redacted]");
expect(diagnostic).not.toMatch(/provider|payload|token=secret|Bearer abc123/i);
});
});
@@ -0,0 +1,98 @@
import { type NotificationStreamItem, type NotificationChannel, type RealtimeEvent } from "./events.js";
export type NotificationStreamScope = {
tenantId: string;
userId: string;
afterCursor?: string;
};
export type NotificationStreamScopeInput = {
tenantId?: unknown;
userId?: unknown;
afterCursor?: unknown;
};
const MAX_SCOPE_VALUE_LENGTH = 500;
const SECRET_VALUE_PATTERN = /bearer\s+[a-z0-9._~+\-/]+=*|api[-_]?key\s*[:=]\s*\S+|token\s*[:=]\s*\S+|password\s*[:=]\s*\S+|secret\s*[:=]\s*\S+|authorization\s*[:=]\s*\S+|provider|metadata|payload|exception|stack/gi;
export function normalizeNotificationStreamScope(input: NotificationStreamScopeInput): NotificationStreamScope {
const tenantId = normalizeRequiredScopeString(input.tenantId, "tenantId");
const userId = normalizeRequiredScopeString(input.userId, "userId");
const afterCursor = normalizeOptionalScopeString(input.afterCursor, "afterCursor");
return afterCursor === undefined ? { tenantId, userId } : { tenantId, userId, afterCursor };
}
export function assertNotificationItemInAppScope(item: NotificationStreamItem, scope: NotificationStreamScope): void {
assertInAppChannel(item.channel);
assertScopeValueMatches(item.tenantId, scope.tenantId, "item.tenantId");
assertScopeValueMatches(item.userId, scope.userId, "item.userId");
}
export function assertNotificationEventInAppScope(event: RealtimeEvent, scope: NotificationStreamScope): void {
assertScopeValueMatches(event.tenantId, scope.tenantId, "event.tenantId");
assertScopeValueMatches(event.userId, scope.userId, "event.userId");
switch (event.event) {
case "notification.snapshot":
for (const item of event.items) {
assertNotificationItemInAppScope(item, scope);
}
return;
case "notification.update":
assertNotificationItemInAppScope(event.item, scope);
return;
case "keepalive":
case "error":
return;
}
}
export function redactNotificationGuardDiagnostic(value: unknown): string {
const message = value instanceof Error ? value.message : String(value);
return message.replace(SECRET_VALUE_PATTERN, "[redacted]").replace(/: .+$/u, ": [redacted]").slice(0, 160);
}
function normalizeRequiredScopeString(value: unknown, label: string): string {
const normalized = normalizeOptionalScopeString(value, label);
if (normalized === undefined) {
throw new Error(`${label} is required`);
}
return normalized;
}
function normalizeOptionalScopeString(value: unknown, label: string): string | undefined {
if (value === undefined || value === null) {
return undefined;
}
if (typeof value !== "string") {
throw new Error(`${label} must be a string`);
}
const normalized = value.trim();
if (!normalized) {
throw new Error(`${label} must not be empty`);
}
if (normalized.length > MAX_SCOPE_VALUE_LENGTH) {
throw new Error(`${label} is too long`);
}
return normalized;
}
function assertInAppChannel(channel: NotificationChannel): void {
if (channel !== "IN_APP") {
throw new Error("item.channel must be IN_APP");
}
}
function assertScopeValueMatches(actual: string | null | undefined, expected: string, label: string): void {
if (actual !== expected) {
throw new Error(`${label} does not match notification stream scope`);
}
}
@@ -0,0 +1,12 @@
import { describe, expect, it } from "vitest";
describe("@toolctrl/realtime public entrypoint", () => {
it("exports realtime event contract bindings", async () => {
const entrypoint = await import("./index.js");
expect(entrypoint.REALTIME_EVENT_NAMES.notificationSnapshot).toBe("notification.snapshot");
expect(entrypoint.validateRealtimeEvent).toBeTypeOf("function");
expect(entrypoint.isRealtimeEvent).toBeTypeOf("function");
expect(entrypoint.subscribeToRealtime).toBeTypeOf("function");
});
});
@@ -0,0 +1,4 @@
export * from "./client.js";
export * from "./events.js";
export * from "./guards.js";
export * from "./server.js";
@@ -0,0 +1,115 @@
import { describe, expect, it } from "vitest";
import { REALTIME_EVENT_NAMES, type NotificationStreamItem } from "./events.js";
import { serializeRealtimeComment, serializeRealtimeEvent } from "./server.js";
const item: NotificationStreamItem = {
id: "delivery_1",
cursor: "2026-05-08T20:00:00.000Z:delivery_1",
tenantId: "tenant_1",
userId: "user_1",
channel: "IN_APP",
category: "billing",
messageKey: "invoice.ready",
status: "SENT",
attemptsMade: 1,
createdAt: "2026-05-08T19:59:00.000Z",
updatedAt: "2026-05-08T20:00:00.000Z",
sentAt: "2026-05-08T20:00:00.000Z",
readAt: null,
};
const baseEvent = {
cursor: item.cursor,
requestId: "req_1",
tenantId: "tenant_1",
userId: "user_1",
};
describe("SSE realtime serialization", () => {
it("serializes deterministic snapshot frames with cursor ids", () => {
expect(
serializeRealtimeEvent({
...baseEvent,
event: REALTIME_EVENT_NAMES.notificationSnapshot,
items: [item],
}),
).toBe(
`id: ${item.cursor}\nevent: notification.snapshot\ndata: {"event":"notification.snapshot","cursor":"${item.cursor}","requestId":"req_1","tenantId":"tenant_1","userId":"user_1","items":[{"id":"delivery_1","cursor":"${item.cursor}","tenantId":"tenant_1","userId":"user_1","channel":"IN_APP","category":"billing","messageKey":"invoice.ready","status":"SENT","attemptsMade":1,"createdAt":"2026-05-08T19:59:00.000Z","updatedAt":"2026-05-08T20:00:00.000Z","sentAt":"2026-05-08T20:00:00.000Z","readAt":null}]}\n\n`,
);
});
it("serializes updates with retry hints before event data", () => {
expect(
serializeRealtimeEvent(
{
...baseEvent,
event: REALTIME_EVENT_NAMES.notificationUpdate,
item,
},
{ retry: 5000 },
),
).toBe(
`retry: 5000\nid: ${item.cursor}\nevent: notification.update\ndata: {"event":"notification.update","cursor":"${item.cursor}","requestId":"req_1","tenantId":"tenant_1","userId":"user_1","item":{"id":"delivery_1","cursor":"${item.cursor}","tenantId":"tenant_1","userId":"user_1","channel":"IN_APP","category":"billing","messageKey":"invoice.ready","status":"SENT","attemptsMade":1,"createdAt":"2026-05-08T19:59:00.000Z","updatedAt":"2026-05-08T20:00:00.000Z","sentAt":"2026-05-08T20:00:00.000Z","readAt":null}}\n\n`,
);
});
it("serializes keepalive comments and keepalive events", () => {
expect(serializeRealtimeComment("keepalive req_1")).toBe(": keepalive req_1\n\n");
expect(
serializeRealtimeEvent({
event: REALTIME_EVENT_NAMES.keepalive,
cursor: item.cursor,
requestId: "req_keepalive",
}),
).toBe(`id: ${item.cursor}\nevent: keepalive\ndata: {"event":"keepalive","cursor":"${item.cursor}","requestId":"req_keepalive"}\n\n`);
});
it("serializes redacted error diagnostics without secret material", () => {
const frame = serializeRealtimeEvent({
event: REALTIME_EVENT_NAMES.error,
cursor: item.cursor,
requestId: "req_error",
code: "STREAM_FAILED",
message: "Notification stream failed.",
});
expect(frame).toBe(
`id: ${item.cursor}\nevent: error\ndata: {"event":"error","cursor":"${item.cursor}","requestId":"req_error","code":"STREAM_FAILED","message":"Notification stream failed."}\n\n`,
);
expect(frame).not.toContain("token");
expect(frame).not.toContain("authorization");
});
it("fails validation before serializing invalid events and secret-like fields", () => {
expect(() =>
serializeRealtimeEvent({
...baseEvent,
event: REALTIME_EVENT_NAMES.notificationSnapshot,
items: [{ ...item, providerPayload: "token=secret" }],
}),
).toThrow(/secret-like key/);
expect(() =>
serializeRealtimeEvent({
event: REALTIME_EVENT_NAMES.error,
cursor: item.cursor,
requestId: "req_error",
code: "STREAM_FAILED",
message: "Notification stream failed.",
authorizationHeader: "Bearer secret",
}),
).toThrow(/secret-like key/);
});
it("rejects invalid retry hints and newline injection", () => {
expect(() => serializeRealtimeEvent({ event: REALTIME_EVENT_NAMES.keepalive, cursor: item.cursor, requestId: "req_1" }, { retry: -1 })).toThrow(
/retry/,
);
expect(() => serializeRealtimeComment("keepalive\nevent: error")).toThrow(/newline/);
expect(() => serializeRealtimeEvent({ event: REALTIME_EVENT_NAMES.keepalive, cursor: `${item.cursor}\nevent: error`, requestId: "req_1" })).toThrow(
/newline/,
);
});
});
@@ -0,0 +1,43 @@
import { validateRealtimeEvent, type RealtimeEvent } from "./events.js";
export type RealtimeSseSerializeOptions = {
retry?: number;
};
export function serializeRealtimeComment(comment: string): string {
const sanitizedComment = sanitizeSseLine(comment, "comment");
return `: ${sanitizedComment}\n\n`;
}
export function serializeRealtimeEvent(input: unknown, options: RealtimeSseSerializeOptions = {}): string {
const event = validateRealtimeEvent(input);
const retryLine = serializeRetry(options.retry);
const data = JSON.stringify(toSerializableRealtimeEvent(event));
return `${retryLine}id: ${sanitizeSseLine(event.cursor, "cursor")}\nevent: ${event.event}\ndata: ${data}\n\n`;
}
function serializeRetry(retry: number | undefined): string {
if (retry === undefined) {
return "";
}
if (!Number.isInteger(retry) || retry < 0) {
throw new Error("retry must be a non-negative integer");
}
return `retry: ${retry}\n`;
}
function sanitizeSseLine(value: string, label: string): string {
if (value.includes("\n") || value.includes("\r")) {
throw new Error(`${label} must not contain newline characters`);
}
return value;
}
function toSerializableRealtimeEvent(event: RealtimeEvent): RealtimeEvent {
return event;
}
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"allowJs": false,
"allowImportingTsExtensions": false,
"lib": ["ES2022"],
"module": "NodeNext",
"moduleResolution": "NodeNext",
"noEmit": true,
"types": ["node"]
},
"include": ["src/**/*.ts"]
}