// connection-key — the capability that routes an SSE client's POSTs. // // The server mints a key for each event stream and sends it as the // stream's first event, which only the client holding the stream reads. // A POST names its connection by that key. The key is a secret: it never // appears in a URL or a log. // // `ConnectionKey` is branded with an unexported symbol, so the only values // of the type come from the two constructors here, beside the one format. import { randomHex } from "@kyneta/random" declare const connectionKeyBrand: unique symbol /** A server-minted key naming one SSE connection. */ export type ConnectionKey = string & { readonly [connectionKeyBrand]: true } /** `sse-` and 32 lowercase hex digits. */ const FORMAT = /^sse-[0-9a-f]{32}$/ /** A fresh key from 128 cryptographically random bits. Used only by the server. */ export function mintConnectionKey(): ConnectionKey { return `sse-${randomHex(16)}` as ConnectionKey } /** * Read a key received from the server, or `undefined` if `s` is not one. * Used only by the client. */ export function parseConnectionKey(s: string): ConnectionKey | undefined { return FORMAT.test(s) ? (s as ConnectionKey) : undefined } /** The SSE event that carries the key, first on every stream. */ export const CONNECTION_KEY_EVENT = "kyneta-connection" /** The request header a POST names its connection in. */ export const CONNECTION_KEY_HEADER = "X-Kyneta-Connection"