@lostgradient/backchannel 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +62 -2
  3. package/dist/access-policy-metadata.d.ts +92 -0
  4. package/dist/access-policy-metadata.js +87 -0
  5. package/dist/asyncapi-channels.d.ts +46 -0
  6. package/dist/asyncapi-channels.js +399 -0
  7. package/dist/asyncapi.d.ts +40 -0
  8. package/dist/asyncapi.js +165 -0
  9. package/dist/authentication/api-key.d.ts +4 -0
  10. package/dist/authentication/api-key.js +114 -0
  11. package/dist/authentication/audit.d.ts +115 -0
  12. package/dist/authentication/audit.js +75 -0
  13. package/dist/authentication/credential-verifiers.d.ts +60 -0
  14. package/dist/authentication/credential-verifiers.js +102 -0
  15. package/dist/authentication/crypto.d.ts +7 -0
  16. package/dist/authentication/crypto.js +140 -0
  17. package/dist/authentication/index.d.ts +80 -0
  18. package/dist/authentication/index.js +212 -0
  19. package/dist/authentication/rate-limiter.d.ts +133 -0
  20. package/dist/authentication/rate-limiter.js +124 -0
  21. package/dist/authentication/redaction.d.ts +72 -0
  22. package/dist/authentication/redaction.js +118 -0
  23. package/dist/authentication/rotating-api-key-store.d.ts +127 -0
  24. package/dist/authentication/rotating-api-key-store.js +126 -0
  25. package/dist/authentication/types.d.ts +337 -0
  26. package/dist/authentication/types.js +26 -0
  27. package/dist/authentication.d.ts +1 -0
  28. package/dist/authentication.js +1 -0
  29. package/dist/authorization-scope.d.ts +109 -0
  30. package/dist/authorization-scope.js +144 -0
  31. package/dist/authorization.d.ts +55 -0
  32. package/dist/authorization.js +134 -0
  33. package/dist/bind-feed-lifetime.d.ts +45 -0
  34. package/dist/bind-feed-lifetime.js +55 -0
  35. package/dist/byte-arrays.d.ts +5 -0
  36. package/dist/byte-arrays.js +9 -0
  37. package/dist/client/catalog-client.d.ts +285 -0
  38. package/dist/client/catalog-client.js +74 -0
  39. package/dist/client/in-process-transport.d.ts +19 -0
  40. package/dist/client/in-process-transport.js +136 -0
  41. package/dist/client/index.d.ts +14 -0
  42. package/dist/client/index.js +14 -0
  43. package/dist/client/json-rpc-http-transport.d.ts +118 -0
  44. package/dist/client/json-rpc-http-transport.js +127 -0
  45. package/dist/client/server-sent-event-parser.d.ts +55 -0
  46. package/dist/client/server-sent-event-parser.js +78 -0
  47. package/dist/client/sse-subscription-transport.d.ts +72 -0
  48. package/dist/client/sse-subscription-transport.js +224 -0
  49. package/dist/client/subscription-client.d.ts +122 -0
  50. package/dist/client/subscription-client.js +28 -0
  51. package/dist/connection-lease.d.ts +10 -0
  52. package/dist/connection-lease.js +8 -0
  53. package/dist/discovery-filter.d.ts +13 -0
  54. package/dist/discovery-filter.js +16 -0
  55. package/dist/discovery-info.d.ts +94 -0
  56. package/dist/discovery-info.js +38 -0
  57. package/dist/event-selector.d.ts +7 -0
  58. package/dist/event-selector.js +7 -0
  59. package/dist/fault-code.d.ts +84 -0
  60. package/dist/fault-code.js +114 -0
  61. package/dist/fault-remediation.d.ts +30 -0
  62. package/dist/fault-remediation.js +52 -0
  63. package/dist/fault-to-http.d.ts +11 -0
  64. package/dist/fault-to-http.js +13 -0
  65. package/dist/fault-to-json-rpc.d.ts +53 -0
  66. package/dist/fault-to-json-rpc.js +143 -0
  67. package/dist/fault-wire-safety.d.ts +45 -0
  68. package/dist/fault-wire-safety.js +72 -0
  69. package/dist/generator.d.ts +9 -0
  70. package/dist/generator.js +9 -0
  71. package/dist/handler/auth-context-principal.d.ts +37 -0
  72. package/dist/handler/auth-context-principal.js +67 -0
  73. package/dist/handler/authentication-responses.d.ts +23 -0
  74. package/dist/handler/authentication-responses.js +34 -0
  75. package/dist/handler/json-responses.d.ts +15 -0
  76. package/dist/handler/json-responses.js +32 -0
  77. package/dist/handler/operation-handler-authentication.d.ts +64 -0
  78. package/dist/handler/operation-handler-authentication.js +58 -0
  79. package/dist/handler/operation-handler-discovery.d.ts +29 -0
  80. package/dist/handler/operation-handler-discovery.js +55 -0
  81. package/dist/handler/operation-handler-mounts.d.ts +100 -0
  82. package/dist/handler/operation-handler-mounts.js +134 -0
  83. package/dist/handler/operation-handler-subscription.d.ts +34 -0
  84. package/dist/handler/operation-handler-subscription.js +112 -0
  85. package/dist/handler/operation-handler.d.ts +162 -0
  86. package/dist/handler/operation-handler.js +236 -0
  87. package/dist/handler/workspace-release.d.ts +6 -0
  88. package/dist/handler/workspace-release.js +75 -0
  89. package/dist/in-memory-replay-live-backend.d.ts +47 -0
  90. package/dist/in-memory-replay-live-backend.js +129 -0
  91. package/dist/index.d.ts +37 -0
  92. package/dist/index.js +30 -0
  93. package/dist/internal/cryptography/encryption.d.ts +108 -0
  94. package/dist/internal/cryptography/encryption.js +241 -0
  95. package/dist/internal/cryptography/hash.d.ts +72 -0
  96. package/dist/internal/cryptography/hash.js +233 -0
  97. package/dist/internal/cryptography/index.d.ts +4 -0
  98. package/dist/internal/cryptography/index.js +2 -0
  99. package/dist/internals.d.ts +58 -0
  100. package/dist/internals.js +54 -0
  101. package/dist/json-rpc-dispatch.d.ts +88 -0
  102. package/dist/json-rpc-dispatch.js +154 -0
  103. package/dist/json-rpc-framing.d.ts +42 -0
  104. package/dist/json-rpc-framing.js +50 -0
  105. package/dist/json-rpc-http.d.ts +36 -0
  106. package/dist/json-rpc-http.js +191 -0
  107. package/dist/json-rpc-parse.d.ts +69 -0
  108. package/dist/json-rpc-parse.js +206 -0
  109. package/dist/json-rpc-protocol.d.ts +76 -0
  110. package/dist/json-rpc-protocol.js +54 -0
  111. package/dist/json-rpc-session-runtime.d.ts +55 -0
  112. package/dist/json-rpc-session-runtime.js +111 -0
  113. package/dist/json-rpc-websocket-subscription-pump.d.ts +9 -0
  114. package/dist/json-rpc-websocket-subscription-pump.js +46 -0
  115. package/dist/json-rpc-websocket-subscriptions.d.ts +10 -0
  116. package/dist/json-rpc-websocket-subscriptions.js +33 -0
  117. package/dist/json-rpc-websocket-types.d.ts +34 -0
  118. package/dist/json-rpc-websocket-types.js +1 -0
  119. package/dist/json-rpc-websocket-validation.d.ts +45 -0
  120. package/dist/json-rpc-websocket-validation.js +154 -0
  121. package/dist/json-rpc-websocket.d.ts +20 -0
  122. package/dist/json-rpc-websocket.js +363 -0
  123. package/dist/json-schema-utilities.d.ts +5 -0
  124. package/dist/json-schema-utilities.js +17 -0
  125. package/dist/mcp-discovery-names.d.ts +11 -0
  126. package/dist/mcp-discovery-names.js +11 -0
  127. package/dist/openapi-canonical-json.d.ts +10 -0
  128. package/dist/openapi-canonical-json.js +23 -0
  129. package/dist/openapi-error-responses.d.ts +15 -0
  130. package/dist/openapi-error-responses.js +104 -0
  131. package/dist/openapi-schemas.d.ts +17 -0
  132. package/dist/openapi-schemas.js +94 -0
  133. package/dist/openapi.d.ts +60 -0
  134. package/dist/openapi.js +351 -0
  135. package/dist/openrpc-document-schema.d.ts +255 -0
  136. package/dist/openrpc-document-schema.js +84 -0
  137. package/dist/openrpc-errors.d.ts +93 -0
  138. package/dist/openrpc-errors.js +134 -0
  139. package/dist/openrpc.d.ts +66 -0
  140. package/dist/openrpc.js +260 -0
  141. package/dist/operation-catalog/behavior-types.d.ts +34 -0
  142. package/dist/operation-catalog/behavior-types.js +1 -0
  143. package/dist/operation-catalog/behavior-validation.d.ts +3 -0
  144. package/dist/operation-catalog/behavior-validation.js +298 -0
  145. package/dist/operation-catalog/dispatch-allowlist.d.ts +4 -0
  146. package/dist/operation-catalog/dispatch-allowlist.js +7 -0
  147. package/dist/operation-catalog/dispatch-preparation.d.ts +24 -0
  148. package/dist/operation-catalog/dispatch-preparation.js +49 -0
  149. package/dist/operation-catalog/index.d.ts +19 -0
  150. package/dist/operation-catalog/index.js +17 -0
  151. package/dist/operation-catalog/operation-dispatch.d.ts +14 -0
  152. package/dist/operation-catalog/operation-dispatch.js +115 -0
  153. package/dist/operation-catalog/operation-interceptors.d.ts +15 -0
  154. package/dist/operation-catalog/operation-interceptors.js +1 -0
  155. package/dist/operation-catalog/operation-metadata.d.ts +5 -0
  156. package/dist/operation-catalog/operation-metadata.js +104 -0
  157. package/dist/operation-catalog/pipeline-helpers.d.ts +70 -0
  158. package/dist/operation-catalog/pipeline-helpers.js +242 -0
  159. package/dist/operation-catalog/pipeline-stages.d.ts +23 -0
  160. package/dist/operation-catalog/pipeline-stages.js +226 -0
  161. package/dist/operation-catalog/pipeline.d.ts +7 -0
  162. package/dist/operation-catalog/pipeline.js +33 -0
  163. package/dist/operation-catalog/registry.d.ts +17 -0
  164. package/dist/operation-catalog/registry.js +132 -0
  165. package/dist/operation-catalog/stream-pipeline.d.ts +37 -0
  166. package/dist/operation-catalog/stream-pipeline.js +129 -0
  167. package/dist/operation-catalog/subscription-lifecycle.d.ts +6 -0
  168. package/dist/operation-catalog/subscription-lifecycle.js +27 -0
  169. package/dist/operation-catalog/types.d.ts +392 -0
  170. package/dist/operation-catalog/types.js +40 -0
  171. package/dist/operation-catalog/universal-faults.d.ts +11 -0
  172. package/dist/operation-catalog/universal-faults.js +15 -0
  173. package/dist/operation-catalog-snapshot.d.ts +215 -0
  174. package/dist/operation-catalog-snapshot.js +128 -0
  175. package/dist/operation-catalog.d.ts +1 -0
  176. package/dist/operation-catalog.js +1 -0
  177. package/dist/operation-description-audit.d.ts +44 -0
  178. package/dist/operation-description-audit.js +90 -0
  179. package/dist/operation-fault-helpers.d.ts +21 -0
  180. package/dist/operation-fault-helpers.js +32 -0
  181. package/dist/operation-fault.d.ts +245 -0
  182. package/dist/operation-fault.js +235 -0
  183. package/dist/operation-registry.d.ts +46 -0
  184. package/dist/operation-registry.js +46 -0
  185. package/dist/operations/closable-iterable.d.ts +23 -0
  186. package/dist/operations/closable-iterable.js +51 -0
  187. package/dist/operations/get-principal.d.ts +106 -0
  188. package/dist/operations/get-principal.js +107 -0
  189. package/dist/operations/sse-stream.d.ts +67 -0
  190. package/dist/operations/sse-stream.js +264 -0
  191. package/dist/principal.d.ts +253 -0
  192. package/dist/principal.js +254 -0
  193. package/dist/replay-live-feed-internals.d.ts +47 -0
  194. package/dist/replay-live-feed-internals.js +215 -0
  195. package/dist/replay-live-feed-types.d.ts +66 -0
  196. package/dist/replay-live-feed-types.js +7 -0
  197. package/dist/replay-live-feed.d.ts +49 -0
  198. package/dist/replay-live-feed.js +126 -0
  199. package/dist/rest-binding.d.ts +215 -0
  200. package/dist/rest-binding.js +95 -0
  201. package/dist/rest-body.d.ts +17 -0
  202. package/dist/rest-body.js +95 -0
  203. package/dist/route-model.d.ts +305 -0
  204. package/dist/route-model.js +320 -0
  205. package/dist/runtime/cors.d.ts +161 -0
  206. package/dist/runtime/cors.js +265 -0
  207. package/dist/scripts/generate-operation-client.d.ts +186 -0
  208. package/dist/scripts/generate-operation-client.js +561 -0
  209. package/dist/scripts/operation-behaviors.d.ts +3 -0
  210. package/dist/scripts/operation-behaviors.js +16 -0
  211. package/dist/scripts/operation-client-aliases.d.ts +32 -0
  212. package/dist/scripts/operation-client-aliases.js +255 -0
  213. package/dist/scripts/operation-client-domains.d.ts +21 -0
  214. package/dist/scripts/operation-client-domains.js +74 -0
  215. package/dist/scripts/operation-client-schema.d.ts +46 -0
  216. package/dist/scripts/operation-client-schema.js +310 -0
  217. package/dist/scripts/operation-client-svelte.d.ts +3 -0
  218. package/dist/scripts/operation-client-svelte.js +61 -0
  219. package/dist/sequence-cursor.d.ts +46 -0
  220. package/dist/sequence-cursor.js +62 -0
  221. package/dist/sse-error-payload-schema.d.ts +12 -0
  222. package/dist/sse-error-payload-schema.js +33 -0
  223. package/dist/stdio-session.d.ts +71 -0
  224. package/dist/stdio-session.js +347 -0
  225. package/dist/zod-json-schema.d.ts +22 -0
  226. package/dist/zod-json-schema.js +49 -0
  227. package/package.json +38 -3
@@ -0,0 +1,67 @@
1
+ import { type OperationFault, type RestFaultResponseOptions } from "../operation-fault.js";
2
+ import { type Cursor } from "../sequence-cursor.js";
3
+ export type ServerSentEventTimerScheduler = (callback: () => void, intervalMs: number) => () => void;
4
+ export type ServerSentEventHeartbeatOptions = {
5
+ readonly intervalMs: number;
6
+ readonly schedule?: ServerSentEventTimerScheduler;
7
+ readonly now?: () => number;
8
+ };
9
+ type ServerSentEventEnvelope = {
10
+ readonly kind: string;
11
+ readonly cursor: string;
12
+ readonly emittedAtMs: number;
13
+ };
14
+ type EventEnvelopeSSEStreamOptions<TEnvelope extends ServerSentEventEnvelope> = {
15
+ readonly iterable: AsyncIterable<TEnvelope>;
16
+ readonly close: () => Promise<void>;
17
+ readonly ready?: Promise<void>;
18
+ readonly heartbeat?: ServerSentEventHeartbeatOptions;
19
+ readonly signal?: AbortSignal;
20
+ /**
21
+ * Ends the response cleanly once this many milliseconds have passed, so a
22
+ * client resumes with `Last-Event-ID`. Armed through the heartbeat's
23
+ * `schedule`, which keeps one timer seam for tests.
24
+ */
25
+ readonly maxDurationMs?: number;
26
+ };
27
+ /** How often a quiet event stream sends a `ping`, so a connection that is open is never silent for longer. */
28
+ export declare const DEFAULT_SSE_HEARTBEAT_INTERVAL_MS = 15000;
29
+ export declare const SSE_ACCEPT_REQUIRED_MESSAGE = "Accept header must include text/event-stream";
30
+ export declare function acceptsServerSentEvents(acceptHeader: string | null): boolean;
31
+ /** Throws unless the request accepts `text/event-stream`. */
32
+ export declare function requireServerSentEventsAccept(request: Request): void;
33
+ /**
34
+ * Validate an SSE reconnect cursor taken from a `Last-Event-ID` header or
35
+ * `fromCursor` query parameter. Returns `undefined` for an absent value and
36
+ * throws an `InvalidParams` fault for a malformed one. Shared by every SSE
37
+ * binding so cursor validation stays defined in exactly one place.
38
+ */
39
+ export declare function readServerSentEventsCursor(value: string | null): Cursor | undefined;
40
+ /** Shapes a fault into the response a Server-Sent Events route answers with. */
41
+ export declare function shapeServerSentEventsFault(fault: OperationFault, options?: Pick<RestFaultResponseOptions, 'isKnownErrorCode'>): Response;
42
+ /** Format a single Server-Sent Events message. */
43
+ export declare function formatServerSentEvent(event: {
44
+ readonly id?: string;
45
+ readonly event?: string;
46
+ readonly data: string;
47
+ }): string;
48
+ /**
49
+ * Convert a replay-plus-live event envelope iterable into an SSE byte stream.
50
+ * Event envelopes advance the client cursor via `id`; heartbeat pings do not.
51
+ */
52
+ export declare function createEventEnvelopeSSEStream<TEnvelope extends ServerSentEventEnvelope>(options: EventEnvelopeSSEStreamOptions<TEnvelope>): ReadableStream<Uint8Array>;
53
+ /**
54
+ * Wrap a list of stored stream chunks as a Server-Sent Events stream. Each
55
+ * chunk gets emitted as a `token` event keyed by `chunk.sequence`; chunks
56
+ * whose mapped text is `null` are skipped. After the chunks, a single
57
+ * `done` event with empty data is emitted and the controller closes.
58
+ *
59
+ * Used by REST `shapeSuccess` for the streaming routes (`streamSSE`,
60
+ * `getStreamChunks` when negotiated to `text/event-stream`).
61
+ */
62
+ export declare function createStoredChunkSSEStream<TChunk extends {
63
+ readonly sequence: number;
64
+ }>(chunks: ReadonlyArray<TChunk>, mapChunkToText: (chunk: TChunk) => string | null): ReadableStream<Uint8Array>;
65
+ /** Standard headers for an SSE response. */
66
+ export declare const SSE_RESPONSE_HEADERS: Readonly<Record<string, string>>;
67
+ export {};
@@ -0,0 +1,264 @@
1
+ import { faultWireAdvice } from "../fault-remediation.js";
2
+ import { extractFaultDataPayload } from "../fault-to-json-rpc.js";
3
+ import { wireSafeFault } from "../fault-wire-safety.js";
4
+ import { invalidParamsFault, isOperationFault } from "../operation-fault-helpers.js";
5
+ import { shapeRestFaultAsJson, } from "../operation-fault.js";
6
+ import { decodeCursor } from "../sequence-cursor.js";
7
+ const textEncoder = new TextEncoder();
8
+ /** How often a quiet event stream sends a `ping`, so a connection that is open is never silent for longer. */
9
+ export const DEFAULT_SSE_HEARTBEAT_INTERVAL_MS = 15_000;
10
+ export const SSE_ACCEPT_REQUIRED_MESSAGE = 'Accept header must include text/event-stream';
11
+ export function acceptsServerSentEvents(acceptHeader) {
12
+ if (acceptHeader === null)
13
+ return false;
14
+ for (const entry of acceptHeader.split(',')) {
15
+ const mediaType = entry.split(';', 1)[0]?.trim().toLowerCase();
16
+ if (mediaType === 'text/event-stream' || mediaType === 'text/*' || mediaType === '*/*') {
17
+ return true;
18
+ }
19
+ }
20
+ return false;
21
+ }
22
+ /** Throws unless the request accepts `text/event-stream`. */
23
+ export function requireServerSentEventsAccept(request) {
24
+ if (!acceptsServerSentEvents(request.headers.get('Accept'))) {
25
+ throw invalidParamsFault(SSE_ACCEPT_REQUIRED_MESSAGE);
26
+ }
27
+ }
28
+ /**
29
+ * Validate an SSE reconnect cursor taken from a `Last-Event-ID` header or
30
+ * `fromCursor` query parameter. Returns `undefined` for an absent value and
31
+ * throws an `InvalidParams` fault for a malformed one. Shared by every SSE
32
+ * binding so cursor validation stays defined in exactly one place.
33
+ */
34
+ export function readServerSentEventsCursor(value) {
35
+ if (value === null)
36
+ return undefined;
37
+ if (decodeCursor(value) === null)
38
+ throw invalidParamsFault('Invalid cursor');
39
+ return value;
40
+ }
41
+ /** Shapes a fault into the response a Server-Sent Events route answers with. */
42
+ export function shapeServerSentEventsFault(fault, options = {}) {
43
+ if (fault.code === 'InvalidParams' && fault.message === SSE_ACCEPT_REQUIRED_MESSAGE) {
44
+ return shapeRestFaultAsJson(fault, { ...options, status: 406 });
45
+ }
46
+ return shapeRestFaultAsJson(fault, options);
47
+ }
48
+ /** Format a single Server-Sent Events message. */
49
+ export function formatServerSentEvent(event) {
50
+ const lines = [];
51
+ if (event.id !== undefined)
52
+ lines.push(`id: ${event.id}`);
53
+ if (event.event !== undefined)
54
+ lines.push(`event: ${event.event}`);
55
+ const dataLines = event.data.split('\n');
56
+ for (const line of dataLines) {
57
+ lines.push(`data: ${line}`);
58
+ }
59
+ lines.push('');
60
+ return lines.join('\n') + '\n';
61
+ }
62
+ function scheduleInterval(callback, intervalMs) {
63
+ const timer = setInterval(callback, intervalMs);
64
+ return () => {
65
+ clearInterval(timer);
66
+ };
67
+ }
68
+ function encodeFrame(frame) {
69
+ return textEncoder.encode(formatServerSentEvent(frame));
70
+ }
71
+ /** What an error frame says of a failure that discloses nothing: the masked internal error. */
72
+ const MASKED_FAULT = {
73
+ code: 'EngineFailure',
74
+ message: 'Internal server error',
75
+ data: {},
76
+ };
77
+ /**
78
+ * The `event: error` frame for a stream that fails after it started: the fault's `code`, `message`
79
+ * and allowlisted `data`, with the `retryable` (always) and `remediation` (when set) every other
80
+ * transport sends. A failure that is not an operation fault, an `EngineFailure`, and a fault whose
81
+ * data JSON cannot carry are the masked internal error, which never carries a remediation.
82
+ */
83
+ function sanitizedErrorFrame(error) {
84
+ const fault = isOperationFault(error) ? wireSafeFault(error) : MASKED_FAULT;
85
+ if (fault.code === 'EngineFailure') {
86
+ const { retryable } = faultWireAdvice(MASKED_FAULT);
87
+ return {
88
+ event: 'error',
89
+ data: JSON.stringify({ code: 'EngineFailure', message: MASKED_FAULT.message, retryable }),
90
+ };
91
+ }
92
+ const { retryable, remediation } = faultWireAdvice(fault);
93
+ return {
94
+ event: 'error',
95
+ data: JSON.stringify({
96
+ code: fault.code,
97
+ message: fault.message,
98
+ data: extractFaultDataPayload(fault),
99
+ retryable,
100
+ ...(remediation === undefined ? {} : { remediation }),
101
+ }),
102
+ };
103
+ }
104
+ function heartbeatOptions(options) {
105
+ return {
106
+ intervalMs: options?.intervalMs ?? DEFAULT_SSE_HEARTBEAT_INTERVAL_MS,
107
+ schedule: options?.schedule ?? scheduleInterval,
108
+ now: options?.now ?? Date.now,
109
+ };
110
+ }
111
+ /**
112
+ * Convert a replay-plus-live event envelope iterable into an SSE byte stream.
113
+ * Event envelopes advance the client cursor via `id`; heartbeat pings do not.
114
+ */
115
+ export function createEventEnvelopeSSEStream(options) {
116
+ let cleanup = null;
117
+ return new ReadableStream({
118
+ start(controller) {
119
+ let closed = false;
120
+ let clearHeartbeat = null;
121
+ let clearDeadline = null;
122
+ const closeResources = async () => {
123
+ if (closed)
124
+ return;
125
+ closed = true;
126
+ if (clearHeartbeat !== null) {
127
+ clearHeartbeat();
128
+ clearHeartbeat = null;
129
+ }
130
+ if (clearDeadline !== null) {
131
+ clearDeadline();
132
+ clearDeadline = null;
133
+ }
134
+ options.signal?.removeEventListener('abort', onAbort);
135
+ try {
136
+ await options.close();
137
+ }
138
+ catch {
139
+ // A close hook must not throw during response cancellation.
140
+ }
141
+ };
142
+ cleanup = closeResources;
143
+ const enqueue = (frame) => {
144
+ if (closed)
145
+ return;
146
+ try {
147
+ controller.enqueue(encodeFrame(frame));
148
+ }
149
+ catch {
150
+ void closeResources();
151
+ }
152
+ };
153
+ const onAbort = () => {
154
+ void closeResources();
155
+ };
156
+ if (options.signal?.aborted) {
157
+ void closeResources();
158
+ controller.close();
159
+ return;
160
+ }
161
+ options.signal?.addEventListener('abort', onAbort, { once: true });
162
+ const heartbeat = heartbeatOptions(options.heartbeat);
163
+ const enqueuePing = (data) => {
164
+ enqueue({
165
+ event: 'ping',
166
+ data: JSON.stringify(data),
167
+ });
168
+ };
169
+ if (options.ready !== undefined) {
170
+ void options.ready.then(() => {
171
+ enqueuePing({ emittedAtMs: heartbeat.now(), replayComplete: true });
172
+ return undefined;
173
+ }, () => undefined);
174
+ }
175
+ if (heartbeat.intervalMs > 0) {
176
+ clearHeartbeat = heartbeat.schedule(() => {
177
+ enqueuePing({ emittedAtMs: heartbeat.now() });
178
+ }, heartbeat.intervalMs);
179
+ }
180
+ if (options.maxDurationMs !== undefined) {
181
+ // The scheduler is interval-shaped, so a second tick is possible
182
+ // before the cleanup cancels it; ending twice is a no-op.
183
+ clearDeadline = heartbeat.schedule(() => {
184
+ // Release the timers and mark the stream closed synchronously, end
185
+ // the response, and only then let the (possibly stalled) close hook
186
+ // run on its own: a hook that never settles must not hold the
187
+ // connection open.
188
+ const released = closeResources();
189
+ try {
190
+ controller.close();
191
+ }
192
+ catch {
193
+ // The stream may already have ended.
194
+ }
195
+ void released;
196
+ }, options.maxDurationMs);
197
+ }
198
+ void (async () => {
199
+ try {
200
+ for await (const envelope of options.iterable) {
201
+ enqueue({
202
+ id: envelope.cursor,
203
+ event: envelope.kind,
204
+ data: JSON.stringify(envelope),
205
+ });
206
+ }
207
+ }
208
+ catch (error) {
209
+ enqueue(sanitizedErrorFrame(error));
210
+ }
211
+ finally {
212
+ await closeResources();
213
+ try {
214
+ controller.close();
215
+ }
216
+ catch {
217
+ // The client may have already canceled the stream.
218
+ }
219
+ }
220
+ })();
221
+ },
222
+ cancel() {
223
+ return cleanup?.();
224
+ },
225
+ });
226
+ }
227
+ /**
228
+ * Wrap a list of stored stream chunks as a Server-Sent Events stream. Each
229
+ * chunk gets emitted as a `token` event keyed by `chunk.sequence`; chunks
230
+ * whose mapped text is `null` are skipped. After the chunks, a single
231
+ * `done` event with empty data is emitted and the controller closes.
232
+ *
233
+ * Used by REST `shapeSuccess` for the streaming routes (`streamSSE`,
234
+ * `getStreamChunks` when negotiated to `text/event-stream`).
235
+ */
236
+ export function createStoredChunkSSEStream(chunks, mapChunkToText) {
237
+ return new ReadableStream({
238
+ start(controller) {
239
+ for (const chunk of chunks) {
240
+ const text = mapChunkToText(chunk);
241
+ if (text === null) {
242
+ continue;
243
+ }
244
+ controller.enqueue(textEncoder.encode(formatServerSentEvent({
245
+ id: String(chunk.sequence),
246
+ event: 'token',
247
+ data: text,
248
+ })));
249
+ }
250
+ controller.enqueue(textEncoder.encode(formatServerSentEvent({
251
+ event: 'done',
252
+ data: '',
253
+ })));
254
+ controller.close();
255
+ },
256
+ });
257
+ }
258
+ /** Standard headers for an SSE response. */
259
+ export const SSE_RESPONSE_HEADERS = {
260
+ 'Content-Type': 'text/event-stream; charset=utf-8',
261
+ 'Cache-Control': 'no-cache, no-transform',
262
+ Connection: 'keep-alive',
263
+ 'X-Accel-Buffering': 'no',
264
+ };
@@ -0,0 +1,253 @@
1
+ /**
2
+ * AuthenticatedPrincipal construction and the Principal discriminated union.
3
+ *
4
+ * Principals are the transport-neutral representation of "who made this call."
5
+ * Every transport edge (REST, JSON-RPC HTTP, JSON-RPC WS upgrade, stdio
6
+ * admission) validates credentials and produces exactly one of these shapes
7
+ * before any operation pipeline runs.
8
+ *
9
+ * Credential *validation* (signature verification, expiry, revocation, format
10
+ * checks) is the transport edge's responsibility — these factories assume the
11
+ * inputs they receive describe a credential that has already been accepted.
12
+ * This stable principal model ensures consistent authentication across all
13
+ * transport layers.
14
+ *
15
+ * The discriminator string for API keys is `'api-key'` (kebab-case) to match
16
+ * the existing `AuthMethod` literal in `authentication.ts`. Keep them aligned;
17
+ * the bridge from `AuthResult` to `Principal` relies on byte-identical strings.
18
+ */
19
+ import { type AdditionalScopeSet, type AuthorizationScope, type ScopeVocabulary } from "./authorization-scope.js";
20
+ /**
21
+ * Raw JWT payload — intentionally loose; individual claim access is
22
+ * type-guarded at read sites. **Non-authoritative for authorization
23
+ * decisions.** Use `principal.subject` and `principal.scopes` (both
24
+ * derived and normalized at construction time) instead. The `claims`
25
+ * bag is preserved for debugging and pass-through.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * import { principalFromJwtClaims, type JwtClaims } from '@lostgradient/backchannel';
30
+ *
31
+ * const claims: JwtClaims = {
32
+ * sub: 'user-123',
33
+ * scope: 'inventory:read',
34
+ * };
35
+ * const principal = principalFromJwtClaims(claims);
36
+ * console.log(principal.subject);
37
+ * ```
38
+ */
39
+ export type JwtClaims = Record<string, unknown>;
40
+ /** A host-resolved identity snapshot, distinct from the credential that authenticated it. */
41
+ export type WorkspaceIdentity = {
42
+ /** Version of this resolved identity contract. */
43
+ readonly version: 1;
44
+ /** Stable identity of the runtime's one workspace. */
45
+ readonly workspaceId: string;
46
+ /** Stable directory identity, independent of a credential's method or rotation. */
47
+ readonly actorId: string;
48
+ /** User membership, a limited service actor, or the explicitly composed local owner. */
49
+ readonly actorKind: 'user' | 'service' | 'local';
50
+ /** Opaque durable resource owner; resolving a credential never rewrites stored owners. */
51
+ readonly owner: string;
52
+ /** Equality-only token scoped to this workspace and actor; changes with membership authority. */
53
+ readonly membershipRevision: string;
54
+ /** Workspace permissions; deployment operation is granted only by trusted local composition. */
55
+ readonly capabilities: readonly ('workspace:use' | 'workspace:manage' | 'deployment:operate')[];
56
+ };
57
+ /**
58
+ * An authenticated caller — JWT, API key, or mTLS. Carries the granted scope
59
+ * set and a `hasScope` accessor; downstream code should narrow to this shape
60
+ * via `isAuthenticated` before calling `hasScope`.
61
+ *
62
+ * The privileged `'stdio-local'` principal is for local stdio admission and
63
+ * carries the full local-admin scope set. It is exported for embedders that
64
+ * implement their own local admission gate; public transports should not mint
65
+ * it for remote callers.
66
+ *
67
+ * The `'unauthenticated-local'` principal is what a `serve()` with no
68
+ * authentication gives every request: nobody is identified, so it is the
69
+ * single-user model, and it holds every built-in scope.
70
+ *
71
+ * @example
72
+ * ```ts
73
+ * import { principalFromApiKey, type AuthenticatedPrincipal } from '@lostgradient/backchannel';
74
+ *
75
+ * const principal: AuthenticatedPrincipal = principalFromApiKey({
76
+ * subject: 'local-tool',
77
+ * scopes: ['inventory:read'],
78
+ * });
79
+ * console.log(principal.method);
80
+ * ```
81
+ */
82
+ export type AuthenticatedPrincipal = {
83
+ /** Supplied by the host after credential verification, never by request metadata. */
84
+ readonly workspace?: WorkspaceIdentity;
85
+ /** How the principal authenticated. */
86
+ readonly method: 'jwt' | 'api-key' | 'mtls' | 'stdio-local' | 'unauthenticated-local' | 'browser-session' | 'connector-token';
87
+ /** The scopes the principal holds. */
88
+ readonly scopes: ReadonlySet<AuthorizationScope>;
89
+ /** The verified JWT claims, when the method is `jwt`. */
90
+ readonly claims: JwtClaims | undefined;
91
+ /** The normalized subject, when the credential names one. */
92
+ readonly subject: string | undefined;
93
+ /** Whether the principal holds a scope. */
94
+ hasScope(scope: AuthorizationScope): boolean;
95
+ };
96
+ /**
97
+ * An unauthenticated caller. Has no scopes and no `hasScope` method —
98
+ * deliberate, so callers MUST narrow via `isAuthenticated` before any
99
+ * scope-bearing access.
100
+ *
101
+ * @example
102
+ * ```ts
103
+ * import { anonymousPrincipal, type UnauthenticatedPrincipal } from '@lostgradient/backchannel';
104
+ *
105
+ * const principal: UnauthenticatedPrincipal = anonymousPrincipal();
106
+ * console.log(principal.method);
107
+ * ```
108
+ */
109
+ export type UnauthenticatedPrincipal = {
110
+ /** Always `unauthenticated`. */
111
+ readonly method: 'unauthenticated';
112
+ };
113
+ /**
114
+ * The full principal union used everywhere below the transport edge.
115
+ *
116
+ * @example
117
+ * ```ts
118
+ * import { anonymousPrincipal, type Principal } from '@lostgradient/backchannel';
119
+ *
120
+ * const principal: Principal = anonymousPrincipal();
121
+ * console.log(principal.method);
122
+ * ```
123
+ */
124
+ export type Principal = AuthenticatedPrincipal | UnauthenticatedPrincipal;
125
+ /**
126
+ * Build an `AuthenticatedPrincipal` from a JWT claims payload. Scopes come
127
+ * from the `scope`, `scp`, and `permissions` claims; only scopes in the host vocabulary and
128
+ * those in `options.additionalScopes` (the package scopes the admitting
129
+ * handler registered) are kept.
130
+ *
131
+ * @example
132
+ * ```ts
133
+ * import { createScopeVocabulary, principalFromJwtClaims } from '@lostgradient/backchannel';
134
+ *
135
+ * const scopeVocabulary = createScopeVocabulary(['inventory:read', 'inventory:write']);
136
+ * const principal = principalFromJwtClaims(
137
+ * { sub: 'user-123', scope: 'inventory:read inventory:write' },
138
+ * { scopeVocabulary },
139
+ * );
140
+ * console.log(principal.hasScope('inventory:read'));
141
+ * ```
142
+ */
143
+ export declare function principalFromJwtClaims(claims: JwtClaims, options?: {
144
+ readonly additionalScopes?: AdditionalScopeSet;
145
+ readonly scopeVocabulary?: ScopeVocabulary;
146
+ }): AuthenticatedPrincipal;
147
+ /**
148
+ * Build an `AuthenticatedPrincipal` from an API-key admission result.
149
+ *
150
+ * @example
151
+ * ```ts
152
+ * import { principalFromApiKey } from '@lostgradient/backchannel';
153
+ *
154
+ * const principal = principalFromApiKey({
155
+ * subject: 'automation',
156
+ * scopes: ['inventory:read'],
157
+ * });
158
+ * console.log(principal.subject);
159
+ * ```
160
+ */
161
+ export declare function principalFromApiKey(options: {
162
+ subject: string;
163
+ scopes: ReadonlyArray<AuthorizationScope>;
164
+ }): AuthenticatedPrincipal;
165
+ /**
166
+ * Build an `AuthenticatedPrincipal` from an mTLS admission result.
167
+ *
168
+ * @example
169
+ * ```ts
170
+ * import { principalFromMutualTls } from '@lostgradient/backchannel';
171
+ *
172
+ * const principal = principalFromMutualTls({
173
+ * subject: 'client-cert-subject',
174
+ * scopes: ['settings:read'],
175
+ * });
176
+ * console.log(principal.method);
177
+ * ```
178
+ */
179
+ export declare function principalFromMutualTls(options: {
180
+ subject: string;
181
+ scopes: ReadonlyArray<AuthorizationScope>;
182
+ }): AuthenticatedPrincipal;
183
+ /**
184
+ * The single unauthenticated principal.
185
+ *
186
+ * @example
187
+ * ```ts
188
+ * import { anonymousPrincipal } from '@lostgradient/backchannel';
189
+ *
190
+ * const principal = anonymousPrincipal();
191
+ * console.log(principal.method);
192
+ * ```
193
+ */
194
+ export declare function anonymousPrincipal(): UnauthenticatedPrincipal;
195
+ /**
196
+ * Build the privileged `stdio-local` principal for the Phase 13
197
+ * runtime stdio subcommand. Admission is gated at the CLI boundary
198
+ * (`--startup-token <hex>` or `--allow-unauthenticated-local-admin`);
199
+ * once admitted, the session has every scope in the host’s vocabulary because it's
200
+ * running as a local process that can already invoke the binary directly.
201
+ * It holds no package scope: no handler's `additionalScopes` reach it, so
202
+ * an operation that requires a package scope is `Forbidden` to it.
203
+ *
204
+ * @example
205
+ * ```ts
206
+ * import { createScopeVocabulary, principalFromStdioLocal } from '@lostgradient/backchannel';
207
+ *
208
+ * const vocabulary = createScopeVocabulary(['inventory:write']);
209
+ * const principal = principalFromStdioLocal(vocabulary);
210
+ * console.log(principal.hasScope('inventory:write'));
211
+ * ```
212
+ */
213
+ export declare function principalFromStdioLocal(vocabulary?: ScopeVocabulary): AuthenticatedPrincipal;
214
+ /**
215
+ * Build the principal a `serve()` with no authentication gives every request.
216
+ * The server identifies no caller, so every caller is the one local user and
217
+ * holds every scope supplied by the host, so every built-in
218
+ * operation is reachable. It holds no package scope, as with `stdio-local`, so
219
+ * an operation that needs a scope registered through `additionalScopes` still
220
+ * needs a credential holding it. The same instance is returned every time, so
221
+ * two requests compare as the same owner.
222
+ *
223
+ * @example
224
+ * ```ts
225
+ * import { createScopeVocabulary, principalFromUnauthenticatedLocal } from '@lostgradient/backchannel';
226
+ *
227
+ * const vocabulary = createScopeVocabulary(['inventory:write']);
228
+ * const principal = principalFromUnauthenticatedLocal(vocabulary);
229
+ * console.log(principal.method); // 'unauthenticated-local'
230
+ * console.log(principal.hasScope('inventory:write')); // true
231
+ * ```
232
+ */
233
+ export declare function principalFromUnauthenticatedLocal(vocabulary?: ScopeVocabulary): AuthenticatedPrincipal;
234
+ /**
235
+ * Whether a principal was rebuilt from a credential the caller presented on
236
+ * this request and names that caller distinctly (`jwt`, `api-key`, or `mtls`
237
+ * with a subject of its own). Only such a principal separates one caller from
238
+ * another by itself.
239
+ *
240
+ * `stdio-local` and `unauthenticated-local` are minted by the host and shared
241
+ * by every caller it serves, an anonymous principal is a shared singleton, and
242
+ * the shared fallback subjects ({@link SHARED_API_KEY_SUBJECT},
243
+ * {@link SHARED_MUTUAL_TLS_SUBJECT}) are common to every static key or mTLS
244
+ * caller, so none of them is credential-backed: a session bound to one needs a
245
+ * per-session secret of its own to be isolated from other callers.
246
+ */
247
+ export declare function isCredentialBacked(principal: Principal): boolean;
248
+ /** The subject every statically configured API key is admitted under. */
249
+ export declare const SHARED_API_KEY_SUBJECT = "api-key-caller";
250
+ /** The subject an mTLS caller is admitted under when it carries no identity of its own. */
251
+ export declare const SHARED_MUTUAL_TLS_SUBJECT = "mtls-caller";
252
+ /** Type guard separating authenticated from unauthenticated principals. */
253
+ export declare function isAuthenticated(principal: Principal): principal is AuthenticatedPrincipal;