@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,347 @@
1
+ /**
2
+ * Runtime JSON-RPC stdio session.
3
+ *
4
+ * `runStdioSession({ input, output, admission, registry, engine, feed, ... })`
5
+ * drives the `weft rpc-stdio` CLI subcommand. It implements the stable
6
+ * JSON-RPC stdio transport: reading newline-delimited JSON frames from
7
+ * `input`, running each through the JSON-RPC dispatcher, and writing
8
+ * responses to `output`.
9
+ *
10
+ * Admission is mandatory:
11
+ * - `{ kind: 'startup-token', token }` — the first frame must be a
12
+ * `weft.authenticate` call whose `params.token` matches. On match,
13
+ * the session principal is `stdio-local` with admin scopes. On
14
+ * mismatch, the session returns `exit 2` without starting.
15
+ * - `{ kind: 'allow-unauthenticated-local-admin' }` — session starts
16
+ * immediately with a `stdio-local` principal. The CLI flag that
17
+ * enables this reads "grants full engine access to any local
18
+ * process that can spawn this binary" in both the help text and
19
+ * the startup log.
20
+ * - `{ kind: 'require-one' }` — neither flag supplied → exit 2.
21
+ *
22
+ * The session is a thin wrapper over the WS session: the only real
23
+ * difference is the transport (newline-delimited stdin/stdout instead
24
+ * of a socket) and the admission gate. Subscribe / unsubscribe and all
25
+ * the JSON-RPC semantics come from the shared session.
26
+ */
27
+ import { timingSafeEqualText } from "./internal/cryptography/index.js";
28
+ import { faultErrorData } from "./fault-to-json-rpc.js";
29
+ import { splitNewlineDelimitedBuffer } from "./json-rpc-framing.js";
30
+ import { JSON_RPC_ERROR_CODES, JSON_RPC_VERSION } from "./json-rpc-protocol.js";
31
+ import { createJsonRpcWebSocketSession, } from "./json-rpc-websocket.js";
32
+ import { isPlainObject } from "./json-schema-utilities.js";
33
+ import { principalFromStdioLocal } from "./principal.js";
34
+ const AUTHENTICATE_METHOD = 'weft.authenticate';
35
+ const DEFAULT_MAX_FRAME_BYTES = 1_048_576;
36
+ /** Serves one JSON-RPC session over a pair of streams, after admitting the peer. */
37
+ export async function runStdioSession(options) {
38
+ if (options.admission.kind === 'require-one') {
39
+ return {
40
+ exitCode: 2,
41
+ reason: 'stdio session admission required: pass --startup-token <hex> or --allow-unauthenticated-local-admin',
42
+ };
43
+ }
44
+ const maxFrameBytes = options.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
45
+ const io = createSessionIO(options.output);
46
+ const reader = options.input.getReader();
47
+ const decoder = new TextDecoder('utf-8');
48
+ let buffer = '';
49
+ if (options.admission.kind === 'startup-token') {
50
+ const outcome = await runStartupTokenAdmission(reader, decoder, buffer, maxFrameBytes, options.admission.token, io);
51
+ if (outcome.kind === 'fail') {
52
+ await io.drainWrites();
53
+ await closeWriterSilent(io.writer);
54
+ return outcome.result;
55
+ }
56
+ buffer = outcome.remainder;
57
+ }
58
+ const principal = principalFromStdioLocal(options.scopeVocabulary);
59
+ const session = createJsonRpcWebSocketSession({
60
+ registry: options.registry,
61
+ engine: options.engine,
62
+ principal,
63
+ emitter: io.emitter,
64
+ feed: options.feed,
65
+ discoverDocument: options.discoverDocument,
66
+ // Dispatch operations as `jsonRpcStdio`, not `jsonRpcWebSocket`,
67
+ // so the transport-availability check in `executeOperation`
68
+ // evaluates the right flag for this session. Operations
69
+ // configured with `jsonRpcStdio: false` must be rejected on
70
+ // stdio even if their WS flag is true, and vice versa.
71
+ transport: 'jsonRpcStdio',
72
+ ...(options.maxFrameBytes !== undefined ? { maxFrameBytes: options.maxFrameBytes } : {}),
73
+ ...(options.maxSubscriptions !== undefined
74
+ ? { maxSubscriptions: options.maxSubscriptions }
75
+ : {}),
76
+ });
77
+ try {
78
+ // Drain any complete frames already in the buffer before the next
79
+ // read — without this, a client that pipelined the auth frame and
80
+ // the first call frame in one chunk would see the call frame sit
81
+ // in `buffer` until either another chunk arrives or EOF.
82
+ buffer = await drainCompleteFramesFromBuffer(buffer, session);
83
+ buffer = await runMainReadLoop(reader, decoder, buffer, maxFrameBytes, session, io);
84
+ }
85
+ finally {
86
+ await session.close();
87
+ await io.drainWrites();
88
+ await closeWriterSilent(io.writer);
89
+ }
90
+ return { exitCode: 0 };
91
+ }
92
+ /**
93
+ * Build the writer + ordered write-chain + emitter bundle. Every write
94
+ * (admission frames, dispatcher results, subscription notifications)
95
+ * goes through the same serialized chain so ordering is preserved and
96
+ * `drainWrites()` before close waits for pending frames.
97
+ */
98
+ function createSessionIO(output) {
99
+ const writer = output.getWriter();
100
+ const encoder = new TextEncoder();
101
+ let writeChain = Promise.resolve();
102
+ function enqueueWrite(text) {
103
+ const next = writeChain.then(() => writer.write(encoder.encode(text)));
104
+ writeChain = next.catch(() => {
105
+ // Swallow here so the chain keeps advancing; callers that
106
+ // specifically want to know a write failed can await the
107
+ // returned promise directly.
108
+ });
109
+ return next;
110
+ }
111
+ return {
112
+ writer,
113
+ writeFrame: (message) => enqueueWrite(JSON.stringify(message) + '\n'),
114
+ emitter: {
115
+ send(message) {
116
+ // Fire-and-forget at the call site, but the write lands in the
117
+ // serialized queue so ordering is preserved and the final
118
+ // `drainWrites()` before `writer.close()` awaits every pending
119
+ // frame.
120
+ void enqueueWrite(message + '\n');
121
+ },
122
+ },
123
+ // `writeChain` only ever holds `Promise.resolve()` or a `.catch()`-handled promise, so it
124
+ // cannot reject; a write failure surfaces to the caller through `enqueueWrite`'s own promise.
125
+ drainWrites: async () => {
126
+ await writeChain;
127
+ },
128
+ };
129
+ }
130
+ async function runStartupTokenAdmission(reader, decoder, initialBuffer, maxFrameBytes, expectedToken, io) {
131
+ const first = await readOneFrame(reader, decoder, initialBuffer, maxFrameBytes);
132
+ if (first.kind === 'closed') {
133
+ return {
134
+ kind: 'fail',
135
+ result: { exitCode: 2, reason: 'stdio session closed before authenticate frame' },
136
+ };
137
+ }
138
+ if (first.kind === 'overflow') {
139
+ await io.writeFrame({
140
+ jsonrpc: JSON_RPC_VERSION,
141
+ error: {
142
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
143
+ message: 'authenticate frame exceeds maxFrameBytes',
144
+ data: faultErrorData('InvalidParams'),
145
+ },
146
+ id: null,
147
+ });
148
+ return {
149
+ kind: 'fail',
150
+ result: { exitCode: 2, reason: 'authenticate frame exceeds maxFrameBytes' },
151
+ };
152
+ }
153
+ let parsed;
154
+ try {
155
+ parsed = JSON.parse(first.line);
156
+ }
157
+ catch {
158
+ await io.writeFrame({
159
+ jsonrpc: JSON_RPC_VERSION,
160
+ error: { code: JSON_RPC_ERROR_CODES.PARSE_ERROR, message: 'Parse error' },
161
+ id: null,
162
+ });
163
+ return {
164
+ kind: 'fail',
165
+ result: { exitCode: 2, reason: 'first frame was not valid JSON' },
166
+ };
167
+ }
168
+ const shapeFault = classifyAuthenticateShape(parsed);
169
+ if (shapeFault) {
170
+ await io.writeFrame(shapeFault.frame);
171
+ return { kind: 'fail', result: shapeFault.result };
172
+ }
173
+ const asObject = parsed;
174
+ const params = asObject['params'];
175
+ const providedToken = isPlainObject(params) ? params['token'] : undefined;
176
+ if (typeof providedToken !== 'string' || !timingSafeEqualText(providedToken, expectedToken)) {
177
+ const id = asId(asObject['id']);
178
+ await io.writeFrame({
179
+ jsonrpc: JSON_RPC_VERSION,
180
+ error: {
181
+ code: JSON_RPC_ERROR_CODES.UNAUTHORIZED,
182
+ message: 'startup token mismatch',
183
+ data: faultErrorData('Unauthorized'),
184
+ },
185
+ id,
186
+ });
187
+ return { kind: 'fail', result: { exitCode: 2, reason: 'startup token mismatch' } };
188
+ }
189
+ const id = asId(asObject['id']);
190
+ await io.writeFrame({ jsonrpc: JSON_RPC_VERSION, result: {}, id });
191
+ return { kind: 'ok', remainder: first.remainder };
192
+ }
193
+ function classifyAuthenticateShape(parsed) {
194
+ if (isPlainObject(parsed) &&
195
+ parsed['jsonrpc'] === JSON_RPC_VERSION &&
196
+ parsed['method'] === AUTHENTICATE_METHOD) {
197
+ return null;
198
+ }
199
+ const id = isPlainObject(parsed) ? asId(parsed['id']) : null;
200
+ return {
201
+ frame: {
202
+ jsonrpc: JSON_RPC_VERSION,
203
+ error: {
204
+ code: JSON_RPC_ERROR_CODES.UNAUTHORIZED,
205
+ message: 'first frame must be weft.authenticate',
206
+ data: faultErrorData('Unauthorized'),
207
+ },
208
+ id,
209
+ },
210
+ result: { exitCode: 2, reason: 'first frame was not weft.authenticate' },
211
+ };
212
+ }
213
+ async function runMainReadLoop(reader, decoder, initialBuffer, maxFrameBytes, session, io) {
214
+ let buffer = initialBuffer;
215
+ // After emitting an overflow fault, we cannot trust that the byte
216
+ // stream's next frame boundary is real — the attacker could have
217
+ // crafted the oversized payload so a synthetic `\n` + fresh JSON
218
+ // appears later in the same logical frame. Discard bytes until we
219
+ // see a newline *in the continuation*, then resume normal framing
220
+ // on whatever follows.
221
+ let discardingOversize = false;
222
+ while (true) {
223
+ const result = await reader.read();
224
+ if (result.done) {
225
+ if (buffer.trim().length > 0) {
226
+ // A partial frame without a trailing newline is a framing
227
+ // violation on a stream whose contract is newline-delimited.
228
+ // Emit a parse-error before the `finally` closes the writer,
229
+ // so the client sees why the last call never got a response.
230
+ await io.writeFrame({
231
+ jsonrpc: JSON_RPC_VERSION,
232
+ error: {
233
+ code: JSON_RPC_ERROR_CODES.PARSE_ERROR,
234
+ message: 'unterminated frame at stream close',
235
+ },
236
+ id: null,
237
+ });
238
+ }
239
+ return '';
240
+ }
241
+ buffer += decoder.decode(result.value, { stream: true });
242
+ if (discardingOversize) {
243
+ const resumeIndex = buffer.indexOf('\n');
244
+ if (resumeIndex === -1) {
245
+ buffer = '';
246
+ continue;
247
+ }
248
+ buffer = buffer.slice(resumeIndex + 1);
249
+ discardingOversize = false;
250
+ }
251
+ if (buffer.length > maxFrameBytes && buffer.indexOf('\n') === -1) {
252
+ // A frame with no newline has exceeded the size cap. Emit a
253
+ // single InvalidRequest, discard the oversized prefix, and
254
+ // ignore everything up to the next newline boundary — we can't
255
+ // trust that the next frame start is where the client says it
256
+ // is, so resynchronize on the next delimiter rather than
257
+ // letting the attacker pick where framing resumes.
258
+ await io.writeFrame({
259
+ jsonrpc: JSON_RPC_VERSION,
260
+ error: {
261
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
262
+ message: 'frame exceeds maxFrameBytes',
263
+ data: faultErrorData('InvalidParams'),
264
+ },
265
+ id: null,
266
+ });
267
+ buffer = '';
268
+ discardingOversize = true;
269
+ continue;
270
+ }
271
+ const framed = splitNewlineDelimitedBuffer(buffer, '');
272
+ buffer = framed.buffer;
273
+ for (const line of framed.lines) {
274
+ await session.handleMessage(line);
275
+ }
276
+ }
277
+ }
278
+ /**
279
+ * Read exactly one complete newline-terminated frame from `reader`,
280
+ * starting from `initialBuffer`. Enforces `maxFrameBytes` so an
281
+ * attacker cannot force unbounded memory growth before admission
282
+ * completes. The remainder is the raw slice of the buffer after the
283
+ * first newline — no lossy reconstruction.
284
+ */
285
+ async function readOneFrame(reader, decoder, initialBuffer, maxFrameBytes) {
286
+ let buffer = initialBuffer;
287
+ while (true) {
288
+ const newlineIndex = buffer.indexOf('\n');
289
+ if (newlineIndex !== -1) {
290
+ if (newlineIndex > maxFrameBytes)
291
+ return { kind: 'overflow' };
292
+ const line = buffer.slice(0, newlineIndex).trim();
293
+ const remainder = buffer.slice(newlineIndex + 1);
294
+ if (line.length === 0) {
295
+ // Blank framing artifact — keep reading for a real frame.
296
+ buffer = remainder;
297
+ continue;
298
+ }
299
+ return { kind: 'ok', line, remainder };
300
+ }
301
+ if (buffer.length > maxFrameBytes)
302
+ return { kind: 'overflow' };
303
+ const result = await reader.read();
304
+ if (result.done)
305
+ return { kind: 'closed' };
306
+ buffer += decoder.decode(result.value, { stream: true });
307
+ }
308
+ }
309
+ /**
310
+ * Drain any complete frames already present in `buffer` (no new
311
+ * reads) through `session.handleMessage`. Returns the leftover
312
+ * partial-frame buffer. Used immediately after admission so a
313
+ * pipelined auth+call chunk is processed without waiting for more
314
+ * input.
315
+ */
316
+ async function drainCompleteFramesFromBuffer(buffer, session) {
317
+ const framed = splitNewlineDelimitedBuffer(buffer, '');
318
+ for (const line of framed.lines) {
319
+ await session.handleMessage(line);
320
+ }
321
+ return framed.buffer;
322
+ }
323
+ async function closeWriterSilent(writer) {
324
+ try {
325
+ await writer.close();
326
+ }
327
+ catch {
328
+ // Writer may already be closed/errored; nothing to do.
329
+ }
330
+ }
331
+ function asId(value) {
332
+ if (value === null)
333
+ return null;
334
+ if (typeof value === 'string')
335
+ return value;
336
+ if (typeof value === 'number' && Number.isFinite(value))
337
+ return value;
338
+ return null;
339
+ }
340
+ /**
341
+ * Constant-time string comparison. Length leak is intentional and
342
+ * acceptable here (tokens are fixed-size hex in the intended
343
+ * deployment) — the goal is to prevent a per-character timing oracle
344
+ * on same-length candidates. For startup-token mode the attacker
345
+ * would need to already control the stdin side, so this is
346
+ * defense-in-depth rather than a load-bearing mitigation.
347
+ */
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Zod to JSON Schema, for the generic operation layer.
3
+ *
4
+ * Every operation declares its input, output and event schemas as Zod types, so the documents and
5
+ * the catalog snapshot convert only those. Weft's public schema converter
6
+ * (`definitionSchemaToJsonSchema`, which also converts Valibot and structural schemas) delegates its
7
+ * Zod branch here, so the two never disagree.
8
+ *
9
+ * @module server/zod-json-schema
10
+ */
11
+ import { z } from 'zod';
12
+ /**
13
+ * Which side of a schema to describe: `'input'` is what the schema accepts, `'output'` is what it
14
+ * validates to.
15
+ */
16
+ export type ZodJsonSchemaDirection = 'input' | 'output';
17
+ /** Convert a Zod schema to a JSON Schema fragment without a `$schema` dialect marker. */
18
+ export declare function zodToJsonSchema(schema: z.ZodType, direction?: ZodJsonSchemaDirection): Record<string, unknown>;
19
+ /** Drop the `$schema` dialect marker so a fragment embeds in a larger document. */
20
+ export declare function stripDialect(object: Record<string, unknown>): Record<string, unknown>;
21
+ /** Narrow a converter's result to a JSON Schema object, or fail loudly. */
22
+ export declare function requirePlainObject(value: unknown, vendor?: string): Record<string, unknown>;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Zod to JSON Schema, for the generic operation layer.
3
+ *
4
+ * Every operation declares its input, output and event schemas as Zod types, so the documents and
5
+ * the catalog snapshot convert only those. Weft's public schema converter
6
+ * (`definitionSchemaToJsonSchema`, which also converts Valibot and structural schemas) delegates its
7
+ * Zod branch here, so the two never disagree.
8
+ *
9
+ * @module server/zod-json-schema
10
+ */
11
+ import { z } from 'zod';
12
+ /** Convert a Zod schema to a JSON Schema fragment without a `$schema` dialect marker. */
13
+ export function zodToJsonSchema(schema, direction = 'input') {
14
+ // `io` decides whether a `.default()` field is required: the input side
15
+ // leaves it optional, the output side always carries it. Zod also stops
16
+ // closing plain objects (`additionalProperties: false`) on the input side;
17
+ // the override restores that so published contracts keep the closed shape
18
+ // they had before `io` was forwarded and only `required` changes.
19
+ const result = z.toJSONSchema(schema, {
20
+ unrepresentable: 'any',
21
+ io: direction,
22
+ override: ({ zodSchema, jsonSchema }) => {
23
+ if (direction !== 'input' || !(zodSchema instanceof z.ZodObject))
24
+ return;
25
+ if (!zodSchema.def.catchall && jsonSchema.additionalProperties === undefined) {
26
+ jsonSchema.additionalProperties = false;
27
+ }
28
+ },
29
+ });
30
+ return stripDialect(requirePlainObject(result));
31
+ }
32
+ /** Drop the `$schema` dialect marker so a fragment embeds in a larger document. */
33
+ export function stripDialect(object) {
34
+ if (!('$schema' in object))
35
+ return object;
36
+ const result = { ...object };
37
+ delete result['$schema'];
38
+ return result;
39
+ }
40
+ /** Narrow a converter's result to a JSON Schema object, or fail loudly. */
41
+ export function requirePlainObject(value, vendor = 'zod') {
42
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
43
+ return value;
44
+ }
45
+ // Fail loudly: silently swapping a non-object converter result for `{}`
46
+ // would emit unconstrained schemas in OpenRPC / OpenAPI / AsyncAPI output.
47
+ throw new Error(`definitionSchemaToJsonSchema: ${vendor} converter returned a non-object ` +
48
+ `(${typeof value}). Expected a JSON Schema object.`);
49
+ }
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@lostgradient/backchannel",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "A transport-neutral operation layer: define an operation once, then serve it over REST, JSON-RPC (HTTP, WebSocket, stdio) and Server-Sent Events, with its OpenAPI, OpenRPC and AsyncAPI documents generated from the catalog. It imports no Bun or Node API.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "sideEffects": false,
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/stevekinney/corvidae.git",
11
+ "directory": "packages/backchannel"
12
+ },
13
+ "engines": {
14
+ "node": ">=22",
15
+ "bun": ">=1.4.0"
16
+ },
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./client": {
23
+ "types": "./dist/client/index.d.ts",
24
+ "default": "./dist/client/index.js"
25
+ },
26
+ "./generator": {
27
+ "types": "./dist/generator.d.ts",
28
+ "default": "./dist/generator.js"
29
+ },
30
+ "./internals": {
31
+ "types": "./dist/internals.d.ts",
32
+ "default": "./dist/internals.js"
33
+ }
34
+ },
35
+ "dependencies": {
36
+ "@lostgradient/credentials": "0.1.0"
37
+ },
38
+ "peerDependencies": {
39
+ "zod": "^4.6.6"
40
+ }
6
41
  }