@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,161 @@
1
+ /**
2
+ * Cross-Origin Resource Sharing (CORS) for the Weft server.
3
+ *
4
+ * The server supports browser clients such as external dashboards and the
5
+ * documented browser runtime (Service Worker + IndexedDB). When those run on a
6
+ * different origin than the API, the browser enforces CORS — and with no policy
7
+ * configured it blocks every cross-origin call. This module supplies an
8
+ * opt-in, **safe by default** policy: when `serve()` is called without a `cors`
9
+ * option, the server emits no `Access-Control-*` headers at all (same-origin
10
+ * only). It never defaults to `Access-Control-Allow-Origin: *`.
11
+ *
12
+ * Three pieces wire into the request pipeline:
13
+ * - {@link buildPreflightResponse} answers `OPTIONS` preflight requests
14
+ * before authentication runs (browsers never send credentials on
15
+ * preflight, so auth-gating it would break CORS).
16
+ * - {@link decorateResponseWithCors} adds the response headers for actual
17
+ * (non-preflight) requests.
18
+ * - {@link isOriginAllowed} gates WebSocket upgrades, which CORS does not
19
+ * otherwise protect.
20
+ *
21
+ * Origins are compared as canonical origin tuples (`scheme://host[:port]`)
22
+ * via the URL parser, so case, default-port elision, and trailing slashes do
23
+ * not cause spurious mismatches. The literal `Origin: null` (sandboxed iframe,
24
+ * `file://`) never matches an allowlist entry.
25
+ *
26
+ * @module server/runtime/cors
27
+ */
28
+ /**
29
+ * Operator-supplied CORS policy. Attach to `serve({ cors })`. Omitting it is
30
+ * the safe default — the server emits no `Access-Control-*` headers and only
31
+ * same-origin browser requests succeed; it never defaults to a wildcard origin.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * import { type CorsOptions } from '@lostgradient/backchannel';
36
+ * import { serve } from '@lostgradient/weft';
37
+ * import { Engine } from '@lostgradient/weft';
38
+ * import { MemoryStorage } from '@lostgradient/storage';
39
+ *
40
+ * const cors: CorsOptions = {
41
+ * allowedOrigins: ['https://dashboard.example.com'],
42
+ * credentials: true,
43
+ * };
44
+ *
45
+ * await using engine = new Engine({ storage: new MemoryStorage() });
46
+ * await using server = serve({ engine, port: 0, cors });
47
+ * void server;
48
+ * ```
49
+ */
50
+ export interface CorsOptions {
51
+ /**
52
+ * Origins permitted to make cross-origin requests. Either an explicit
53
+ * allowlist (compared as canonical origins) or a predicate that receives
54
+ * the raw `Origin` header value. The single-element sentinel `['*']` means
55
+ * "any origin" and is only legal when `credentials` is not `true`.
56
+ *
57
+ * Omitting this (or an empty array) allows no cross-origin requests.
58
+ *
59
+ * Note: the array form canonicalizes both the allowlist and the incoming
60
+ * origin (so case, default-port elision, and trailing slashes do not matter).
61
+ * The predicate form receives the **raw** `Origin` header value with no
62
+ * canonicalization — apply `canonicalizeOrigin` yourself if you need the same
63
+ * normalization for case-insensitive or default-port comparisons.
64
+ */
65
+ readonly allowedOrigins?: ReadonlyArray<string> | ((origin: string) => boolean);
66
+ /** Methods advertised in preflight responses. Defaults to the common verbs plus `OPTIONS`. */
67
+ readonly allowedMethods?: ReadonlyArray<string>;
68
+ /**
69
+ * Request headers a client may send. Defaults to `Authorization, Content-Type, Last-Event-ID,
70
+ * Cache-Control` plus the MCP request headers `Mcp-Protocol-Version`, `Mcp-Method`, and
71
+ * `Mcp-Name`, which a browser MCP client sends to `/mcp`. An explicit list replaces the default,
72
+ * so include those three when it should admit browser MCP clients.
73
+ */
74
+ readonly allowedHeaders?: ReadonlyArray<string>;
75
+ /** Response headers exposed to client scripts via `Access-Control-Expose-Headers`. */
76
+ readonly exposedHeaders?: ReadonlyArray<string>;
77
+ /** Whether credentialed requests are allowed. When `true`, the origin is never wildcarded. */
78
+ readonly credentials?: boolean;
79
+ /** Preflight cache lifetime in seconds (`Access-Control-Max-Age`). Defaults to 600. */
80
+ readonly maxAgeSeconds?: number;
81
+ }
82
+ /**
83
+ * A CorsOptions normalized into the exact strings the response builders emit,
84
+ * so the per-request hot path does no defaulting or array joining.
85
+ */
86
+ export type ResolvedCorsPolicy = {
87
+ /** Whether an origin is allowed. */
88
+ readonly matchOrigin: (origin: string) => boolean;
89
+ /** Whether every origin is allowed. */
90
+ readonly allowsAnyOrigin: boolean;
91
+ /** Pre-joined `Access-Control-Allow-Methods` value emitted in preflight responses. */
92
+ readonly allowedMethodsHeader: string;
93
+ /** Uppercased method names, for O(1) validation of the preflight's requested method. */
94
+ readonly allowedMethodSet: ReadonlySet<string>;
95
+ /** Pre-joined `Access-Control-Allow-Headers` value emitted in preflight responses. */
96
+ readonly allowedHeadersHeader: string;
97
+ /** Lowercased header names, for O(1) validation of the preflight's requested headers. */
98
+ readonly allowedHeaderSet: ReadonlySet<string>;
99
+ /** The `Access-Control-Expose-Headers` value, or null. */
100
+ readonly exposedHeadersHeader: string | null;
101
+ /** Whether credentialed requests are allowed. */
102
+ readonly credentials: boolean;
103
+ /** How long a browser may cache the preflight, in seconds. */
104
+ readonly maxAgeSeconds: number;
105
+ };
106
+ /**
107
+ * Canonicalize an origin string to its `scheme://host[:port]` tuple. Returns
108
+ * `null` for the literal `"null"`, empty input, or anything the URL parser
109
+ * rejects — those must never match an allowlist entry. Default ports are
110
+ * elided by the URL parser, so `https://x:443` and `https://x` compare equal.
111
+ */
112
+ export declare function canonicalizeOrigin(value: string): string | null;
113
+ /**
114
+ * Resolve a `CorsOptions` (already validated by {@link validateCorsOptions})
115
+ * into the precomputed policy used per request. When `auth` is configured the
116
+ * caller passes `requireAuthorizationHeader: true` so `Authorization` is
117
+ * always advertised in `Access-Control-Allow-Headers`.
118
+ */
119
+ export declare function resolveCorsPolicy(options: CorsOptions, requireAuthorizationHeader?: boolean): ResolvedCorsPolicy;
120
+ /**
121
+ * Whether a request's `Origin` header is permitted by the policy. The literal
122
+ * `Origin: null` (sandboxed iframe, `file://`, some redirects) is rejected
123
+ * unconditionally — even under a wildcard policy — so a sandboxed page can
124
+ * never be treated as an allowed origin.
125
+ */
126
+ export declare function isOriginAllowed(policy: ResolvedCorsPolicy, origin: string | null): boolean;
127
+ /** True when the request is a CORS preflight (an `OPTIONS` with the request-method hint). */
128
+ export declare function isPreflightRequest(request: Request): boolean;
129
+ /**
130
+ * Build the preflight (`OPTIONS`) response. Always returns a bounded 204 so
131
+ * the path is cheap and stateless — it emits `Access-Control-*` headers only
132
+ * when the origin is allowed AND the requested method and headers are within
133
+ * policy; otherwise the 204 carries no CORS headers and the browser blocks the
134
+ * real request. `Vary` covers all three request dimensions a shared cache
135
+ * could key on, and `Cache-Control: no-store` keeps a proxy from reusing one
136
+ * origin's decision for another.
137
+ */
138
+ export declare function buildPreflightResponse(policy: ResolvedCorsPolicy, request: Request): Response;
139
+ /**
140
+ * Add CORS response headers to an actual (non-preflight) response when the
141
+ * request carried an allowed `Origin`. Mutates and returns the same response.
142
+ * Always sets `Vary: Origin` (appending to any existing value) so caches do
143
+ * not serve one origin's headers to another.
144
+ */
145
+ export declare function decorateResponseWithCors(policy: ResolvedCorsPolicy, request: Request, response: Response): Response;
146
+ /**
147
+ * Validate a `CorsOptions` at `serve()` time so misconfigurations fail before
148
+ * the port binds. Throws `Error` on:
149
+ * - `credentials: true` combined with a wildcard origin (illegal per spec);
150
+ * - a wildcard origin paired with an `Authorization` allowed-header (lets any
151
+ * origin read responses to bearer-token requests — almost never intended).
152
+ *
153
+ * `authConfigured` must mirror what `serve()` passes as `requireAuthorizationHeader`
154
+ * to {@link resolveCorsPolicy}: when `auth` is set, `Authorization` is auto-added
155
+ * to the effective allowed-headers, so the wildcard + `Authorization` check has to
156
+ * account for that even when the operator did not list it explicitly. Validating
157
+ * against `options.allowedHeaders` alone would let `cors: { allowedOrigins: ['*'],
158
+ * allowedHeaders: ['Content-Type'] }` pass under `auth` and then resolve to a policy
159
+ * that allows bearer tokens under a wildcard origin.
160
+ */
161
+ export declare function validateCorsOptions(options: CorsOptions, authConfigured?: boolean): void;
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Cross-Origin Resource Sharing (CORS) for the Weft server.
3
+ *
4
+ * The server supports browser clients such as external dashboards and the
5
+ * documented browser runtime (Service Worker + IndexedDB). When those run on a
6
+ * different origin than the API, the browser enforces CORS — and with no policy
7
+ * configured it blocks every cross-origin call. This module supplies an
8
+ * opt-in, **safe by default** policy: when `serve()` is called without a `cors`
9
+ * option, the server emits no `Access-Control-*` headers at all (same-origin
10
+ * only). It never defaults to `Access-Control-Allow-Origin: *`.
11
+ *
12
+ * Three pieces wire into the request pipeline:
13
+ * - {@link buildPreflightResponse} answers `OPTIONS` preflight requests
14
+ * before authentication runs (browsers never send credentials on
15
+ * preflight, so auth-gating it would break CORS).
16
+ * - {@link decorateResponseWithCors} adds the response headers for actual
17
+ * (non-preflight) requests.
18
+ * - {@link isOriginAllowed} gates WebSocket upgrades, which CORS does not
19
+ * otherwise protect.
20
+ *
21
+ * Origins are compared as canonical origin tuples (`scheme://host[:port]`)
22
+ * via the URL parser, so case, default-port elision, and trailing slashes do
23
+ * not cause spurious mismatches. The literal `Origin: null` (sandboxed iframe,
24
+ * `file://`) never matches an allowlist entry.
25
+ *
26
+ * @module server/runtime/cors
27
+ */
28
+ const DEFAULT_ALLOWED_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
29
+ const DEFAULT_ALLOWED_HEADERS = [
30
+ 'Authorization',
31
+ 'Content-Type',
32
+ 'Last-Event-ID',
33
+ 'Cache-Control',
34
+ // A 2026-07-28 MCP client names its protocol, method, and tool in headers the SDK requires.
35
+ 'Mcp-Protocol-Version',
36
+ 'Mcp-Method',
37
+ 'Mcp-Name',
38
+ ];
39
+ const DEFAULT_MAX_AGE_SECONDS = 600;
40
+ const WILDCARD_ORIGIN = '*';
41
+ /**
42
+ * Canonicalize an origin string to its `scheme://host[:port]` tuple. Returns
43
+ * `null` for the literal `"null"`, empty input, or anything the URL parser
44
+ * rejects — those must never match an allowlist entry. Default ports are
45
+ * elided by the URL parser, so `https://x:443` and `https://x` compare equal.
46
+ */
47
+ export function canonicalizeOrigin(value) {
48
+ const trimmed = value.trim();
49
+ if (trimmed === '' || trimmed === 'null') {
50
+ return null;
51
+ }
52
+ try {
53
+ const parsed = new URL(trimmed);
54
+ // `URL.origin` is already lowercased on host and elides default ports. A
55
+ // non-special scheme (no authority) yields the string "null" — reject it.
56
+ return parsed.origin === 'null' ? null : parsed.origin;
57
+ }
58
+ catch {
59
+ return null;
60
+ }
61
+ }
62
+ /** Build the origin-matching predicate from the configured allowlist. */
63
+ function buildOriginMatcher(allowedOrigins) {
64
+ if (typeof allowedOrigins === 'function') {
65
+ return { match: allowedOrigins, allowsAny: false };
66
+ }
67
+ const list = allowedOrigins ?? [];
68
+ if (list.length === 1 && list[0] === WILDCARD_ORIGIN) {
69
+ return { match: () => true, allowsAny: true };
70
+ }
71
+ // Pre-canonicalize the allowlist once. A non-canonicalizable entry simply
72
+ // never matches (it is dropped from the set), which fails closed.
73
+ const canonical = new Set();
74
+ for (const entry of list) {
75
+ const normalized = canonicalizeOrigin(entry);
76
+ if (normalized !== null) {
77
+ canonical.add(normalized);
78
+ }
79
+ }
80
+ return {
81
+ match: (origin) => {
82
+ const normalized = canonicalizeOrigin(origin);
83
+ return normalized !== null && canonical.has(normalized);
84
+ },
85
+ allowsAny: false,
86
+ };
87
+ }
88
+ /**
89
+ * Resolve a `CorsOptions` (already validated by {@link validateCorsOptions})
90
+ * into the precomputed policy used per request. When `auth` is configured the
91
+ * caller passes `requireAuthorizationHeader: true` so `Authorization` is
92
+ * always advertised in `Access-Control-Allow-Headers`.
93
+ */
94
+ export function resolveCorsPolicy(options, requireAuthorizationHeader = false) {
95
+ const { match, allowsAny } = buildOriginMatcher(options.allowedOrigins);
96
+ const methods = options.allowedMethods ?? DEFAULT_ALLOWED_METHODS;
97
+ const headerList = [...(options.allowedHeaders ?? DEFAULT_ALLOWED_HEADERS)];
98
+ if (requireAuthorizationHeader &&
99
+ !headerList.some((header) => header.toLowerCase() === 'authorization')) {
100
+ headerList.push('Authorization');
101
+ }
102
+ // CORS header and method names are case-insensitive per the Fetch spec, so
103
+ // the lookup sets normalize case once here and compare normalized at request
104
+ // time. Headers lowercase, methods uppercase (their conventional forms).
105
+ const allowedHeaderSet = new Set(headerList.map((header) => header.toLowerCase()));
106
+ const allowedMethodSet = new Set(methods.map((method) => method.toUpperCase()));
107
+ const exposed = options.exposedHeaders ?? [];
108
+ return {
109
+ matchOrigin: match,
110
+ allowsAnyOrigin: allowsAny,
111
+ allowedMethodsHeader: methods.join(', '),
112
+ allowedMethodSet,
113
+ allowedHeadersHeader: headerList.join(', '),
114
+ allowedHeaderSet,
115
+ exposedHeadersHeader: exposed.length > 0 ? exposed.join(', ') : null,
116
+ credentials: options.credentials === true,
117
+ maxAgeSeconds: options.maxAgeSeconds ?? DEFAULT_MAX_AGE_SECONDS,
118
+ };
119
+ }
120
+ /**
121
+ * Whether a request's `Origin` header is permitted by the policy. The literal
122
+ * `Origin: null` (sandboxed iframe, `file://`, some redirects) is rejected
123
+ * unconditionally — even under a wildcard policy — so a sandboxed page can
124
+ * never be treated as an allowed origin.
125
+ */
126
+ export function isOriginAllowed(policy, origin) {
127
+ if (origin === null || origin.trim() === 'null' || origin.trim() === '') {
128
+ return false;
129
+ }
130
+ return policy.matchOrigin(origin);
131
+ }
132
+ /**
133
+ * The value to emit in `Access-Control-Allow-Origin`. Credentialed responses
134
+ * must echo the exact request origin (the wildcard is illegal with
135
+ * credentials); non-credentialed wildcard policies may answer `*`.
136
+ */
137
+ function allowOriginValue(policy, requestOrigin) {
138
+ if (policy.allowsAnyOrigin && !policy.credentials) {
139
+ return WILDCARD_ORIGIN;
140
+ }
141
+ return requestOrigin;
142
+ }
143
+ /** True when the request is a CORS preflight (an `OPTIONS` with the request-method hint). */
144
+ export function isPreflightRequest(request) {
145
+ return (request.method === 'OPTIONS' && request.headers.get('access-control-request-method') !== null);
146
+ }
147
+ /**
148
+ * Build the preflight (`OPTIONS`) response. Always returns a bounded 204 so
149
+ * the path is cheap and stateless — it emits `Access-Control-*` headers only
150
+ * when the origin is allowed AND the requested method and headers are within
151
+ * policy; otherwise the 204 carries no CORS headers and the browser blocks the
152
+ * real request. `Vary` covers all three request dimensions a shared cache
153
+ * could key on, and `Cache-Control: no-store` keeps a proxy from reusing one
154
+ * origin's decision for another.
155
+ */
156
+ export function buildPreflightResponse(policy, request) {
157
+ const baseHeaders = {
158
+ Vary: 'Origin, Access-Control-Request-Method, Access-Control-Request-Headers',
159
+ 'Cache-Control': 'no-store',
160
+ };
161
+ const denied = new Response(null, { status: 204, headers: baseHeaders });
162
+ const origin = request.headers.get('origin');
163
+ if (origin === null || !isOriginAllowed(policy, origin)) {
164
+ return denied;
165
+ }
166
+ const requestedMethod = request.headers.get('access-control-request-method');
167
+ if (requestedMethod === null || !policy.allowedMethodSet.has(requestedMethod.toUpperCase())) {
168
+ return denied;
169
+ }
170
+ const requestedHeaders = parseRequestedHeaders(request.headers.get('access-control-request-headers'));
171
+ if (!requestedHeaders.every((header) => policy.allowedHeaderSet.has(header))) {
172
+ return denied;
173
+ }
174
+ // Origin is narrowed to `string` here by the guards above.
175
+ const headers = {
176
+ ...baseHeaders,
177
+ 'Access-Control-Allow-Origin': allowOriginValue(policy, origin),
178
+ 'Access-Control-Allow-Methods': policy.allowedMethodsHeader,
179
+ 'Access-Control-Allow-Headers': policy.allowedHeadersHeader,
180
+ 'Access-Control-Max-Age': String(policy.maxAgeSeconds),
181
+ };
182
+ if (policy.credentials) {
183
+ headers['Access-Control-Allow-Credentials'] = 'true';
184
+ }
185
+ return new Response(null, { status: 204, headers });
186
+ }
187
+ /**
188
+ * Add CORS response headers to an actual (non-preflight) response when the
189
+ * request carried an allowed `Origin`. Mutates and returns the same response.
190
+ * Always sets `Vary: Origin` (appending to any existing value) so caches do
191
+ * not serve one origin's headers to another.
192
+ */
193
+ export function decorateResponseWithCors(policy, request, response) {
194
+ const origin = request.headers.get('origin');
195
+ if (origin === null || !isOriginAllowed(policy, origin)) {
196
+ return response;
197
+ }
198
+ appendVary(response.headers, 'Origin');
199
+ response.headers.set('Access-Control-Allow-Origin', allowOriginValue(policy, origin));
200
+ if (policy.credentials) {
201
+ response.headers.set('Access-Control-Allow-Credentials', 'true');
202
+ }
203
+ if (policy.exposedHeadersHeader !== null) {
204
+ response.headers.set('Access-Control-Expose-Headers', policy.exposedHeadersHeader);
205
+ }
206
+ return response;
207
+ }
208
+ /** Parse a comma-separated `Access-Control-Request-Headers` value into lowercase tokens. */
209
+ function parseRequestedHeaders(value) {
210
+ if (value === null || value.trim() === '') {
211
+ return [];
212
+ }
213
+ return value
214
+ .split(',')
215
+ .map((header) => header.trim().toLowerCase())
216
+ .filter((header) => header !== '');
217
+ }
218
+ /** Append a token to the `Vary` header without clobbering existing entries. */
219
+ function appendVary(headers, token) {
220
+ const existing = headers.get('Vary');
221
+ if (existing === null || existing.trim() === '') {
222
+ headers.set('Vary', token);
223
+ return;
224
+ }
225
+ const tokens = existing.split(',').map((entry) => entry.trim().toLowerCase());
226
+ if (tokens.includes(token.toLowerCase()) || tokens.includes('*')) {
227
+ return;
228
+ }
229
+ headers.set('Vary', `${existing}, ${token}`);
230
+ }
231
+ /**
232
+ * Validate a `CorsOptions` at `serve()` time so misconfigurations fail before
233
+ * the port binds. Throws `Error` on:
234
+ * - `credentials: true` combined with a wildcard origin (illegal per spec);
235
+ * - a wildcard origin paired with an `Authorization` allowed-header (lets any
236
+ * origin read responses to bearer-token requests — almost never intended).
237
+ *
238
+ * `authConfigured` must mirror what `serve()` passes as `requireAuthorizationHeader`
239
+ * to {@link resolveCorsPolicy}: when `auth` is set, `Authorization` is auto-added
240
+ * to the effective allowed-headers, so the wildcard + `Authorization` check has to
241
+ * account for that even when the operator did not list it explicitly. Validating
242
+ * against `options.allowedHeaders` alone would let `cors: { allowedOrigins: ['*'],
243
+ * allowedHeaders: ['Content-Type'] }` pass under `auth` and then resolve to a policy
244
+ * that allows bearer tokens under a wildcard origin.
245
+ */
246
+ export function validateCorsOptions(options, authConfigured = false) {
247
+ const allowed = options.allowedOrigins;
248
+ const isWildcard = Array.isArray(allowed) && allowed.length === 1 && allowed[0] === WILDCARD_ORIGIN;
249
+ if (!isWildcard) {
250
+ return;
251
+ }
252
+ if (options.credentials === true) {
253
+ throw new Error('serve({ cors }): allowedOrigins ["*"] cannot be combined with credentials: true — ' +
254
+ 'a wildcard origin is illegal for credentialed CORS. List explicit origins instead.');
255
+ }
256
+ const headers = options.allowedHeaders ?? DEFAULT_ALLOWED_HEADERS;
257
+ const allowsAuthorizationHeader = authConfigured || headers.some((header) => header.toLowerCase() === 'authorization');
258
+ if (allowsAuthorizationHeader) {
259
+ throw new Error('serve({ cors }): allowedOrigins ["*"] combined with an Authorization allowed-header lets ' +
260
+ 'any web origin send bearer tokens and read the response. List explicit origins, or drop ' +
261
+ 'Authorization from allowedHeaders if the wildcard is truly intended for a public API. ' +
262
+ '(When serve({ auth }) is configured, Authorization is always an allowed header, so a ' +
263
+ 'wildcard origin is rejected regardless of allowedHeaders.)');
264
+ }
265
+ }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Generates a typed client for any operation catalog.
3
+ *
4
+ * The core, {@link createOperationClientSources}, takes a catalog snapshot and the options that
5
+ * name the catalog's package, its server and its connection, and returns the generated files as a
6
+ * map from file name to source. It reads no file and imports no formatter: the caller writes the
7
+ * files and passes the formatter, so the package depends on neither `prettier` nor a file system.
8
+ * The generated client imports `@lostgradient/backchannel/client` for its runtime.
9
+ *
10
+ * @module generator
11
+ */
12
+ import type { CatalogOperationSnapshot, CatalogSnapshot } from "../index.js";
13
+ import { type OperationDomainName } from "./operation-client-domains.js";
14
+ export type { OperationDomainName } from "./operation-client-domains.js";
15
+ /**
16
+ * How the generated factory reaches its server: the connection type the factory takes, the
17
+ * function that turns a connection into a transport, and the words that document both.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import type { OperationClientConnection } from '@lostgradient/backchannel/generator';
22
+ *
23
+ * const connection: OperationClientConnection = {
24
+ * typeName: 'JsonRpcHttpConnection',
25
+ * transportName: 'httpJsonRpcTransport',
26
+ * importSpecifier: '@lostgradient/backchannel/client',
27
+ * description: ['Pass the base URL of the handler.'],
28
+ * example: "{ baseUrl: 'https://api.example.test' }",
29
+ * };
30
+ * console.log(connection.typeName);
31
+ * ```
32
+ */
33
+ export type OperationClientConnection = {
34
+ /** The name of the connection type the generated factory takes. */
35
+ readonly typeName: string;
36
+ /** The name of the function that turns a connection into a `CatalogTransport`. */
37
+ readonly transportName: string;
38
+ /** The module the connection type and the transport function are imported from. */
39
+ readonly importSpecifier: string;
40
+ /** The factory parameter's default, such as `{}`; absent when the connection is required. */
41
+ readonly defaultValue?: string | undefined;
42
+ /** The lines of prose that say how the connection resolves, for the factory's documentation. */
43
+ readonly description: readonly string[];
44
+ /** The source of an example connection, for the factory's documentation; may span lines. */
45
+ readonly example: string;
46
+ };
47
+ /**
48
+ * Operation names the generated documentation uses in its examples. Each defaults to a name the
49
+ * snapshot holds, so a catalog that names none still gets examples that refer to its own
50
+ * operations.
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * import type { OperationClientExamples } from '@lostgradient/backchannel/generator';
55
+ *
56
+ * const examples: OperationClientExamples = { list: 'probe.list', cancel: 'probe.cancel' };
57
+ * console.log(examples.list);
58
+ * ```
59
+ */
60
+ export type OperationClientExamples = {
61
+ /** An operation callable over JSON-RPC that takes and returns data. */
62
+ readonly list?: string | undefined;
63
+ /** An operation callable over JSON-RPC, for the example that checks callability. */
64
+ readonly callable?: string | undefined;
65
+ /** An operation whose input type the examples name. */
66
+ readonly cancel?: string | undefined;
67
+ /** An operation served over REST only, for the example of a client over every operation. */
68
+ readonly restOnly?: string | undefined;
69
+ /** A subscription, for the example that iterates its events. */
70
+ readonly subscription?: string | undefined;
71
+ };
72
+ /**
73
+ * Which subscriptions get a generated method, and where their route is served. A catalog composed
74
+ * from two hosts lists the subscriptions of both, but only one host serves the route its client
75
+ * reaches, so `include` picks that host's operations and `pathPrefix` names where it mounts them.
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * import type { OperationClientSubscriptionRoutes } from '@lostgradient/backchannel/generator';
80
+ *
81
+ * const routes: OperationClientSubscriptionRoutes = {
82
+ * include: (operation) => operation.name.startsWith('probe.'),
83
+ * pathPrefix: '/probe/v1/subscriptions',
84
+ * };
85
+ * console.log(routes.pathPrefix);
86
+ * ```
87
+ */
88
+ export type OperationClientSubscriptionRoutes = {
89
+ /** Whether a subscription gets a method. Defaults to every subscription with an HTTP route. */
90
+ readonly include?: ((operation: CatalogOperationSnapshot) => boolean) | undefined;
91
+ /** The path the routes are served under, before the operation name. Defaults to `/v1/subscriptions`. */
92
+ readonly pathPrefix?: string | undefined;
93
+ };
94
+ /**
95
+ * What {@link createOperationClientSources} needs to know about the catalog's package, beyond its
96
+ * snapshot. Nothing here is specific to one catalog: a package names itself, its server, its
97
+ * factory and its connection, and says where the generated files go and how to format them.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * import type { OperationClientOptions } from '@lostgradient/backchannel/generator';
102
+ *
103
+ * const options: OperationClientOptions = {
104
+ * packageName: '@example/probe',
105
+ * serverName: 'Probe',
106
+ * factoryName: 'createProbeClient',
107
+ * outputDirectory: 'src/client/generated',
108
+ * format: async (source) => source,
109
+ * };
110
+ * console.log(options.factoryName);
111
+ * ```
112
+ */
113
+ export type OperationClientOptions = {
114
+ /** The package the generated examples import from. */
115
+ readonly packageName: string;
116
+ /** What the documentation calls the server: `a remote ${serverName} server`. */
117
+ readonly serverName: string;
118
+ /** The name of the generated factory, such as `createProbeClient`. */
119
+ readonly factoryName: string;
120
+ /** The directory the files are written to, which the formatter resolves its configuration from. */
121
+ readonly outputDirectory: string;
122
+ /** The name of the main generated file. Defaults to `operation-client.generated.ts`. */
123
+ readonly outputFile?: string | undefined;
124
+ /** Select generated entry points; domain and shared types are always emitted. */
125
+ readonly entries?: readonly ('client' | 'portable' | 'fetch' | 'behaviors' | 'svelte')[] | undefined;
126
+ /** Emit only the operation type map in the main client entry. */
127
+ readonly typeOnlyClient?: boolean | undefined;
128
+ /** Exclude command bindings when a consumer supplies its own actions. */
129
+ readonly svelteCommands?: boolean | undefined;
130
+ /** Omit generic provider exports when a consumer supplies its own provider. */
131
+ readonly svelteProvider?: boolean | undefined;
132
+ /** Export only shared types directly referenced by operation entries. */
133
+ readonly referencedSharedTypesOnly?: boolean | undefined;
134
+ /** Emit transport-injected and Fetch entries alongside the existing client. */
135
+ readonly portableEntries?: boolean | undefined;
136
+ /** Emit bindings for declared behavior using the optional Svelte runtime. */
137
+ readonly svelte?: boolean | undefined;
138
+ /** The module the generated client imports its runtime from. Defaults to `@lostgradient/backchannel/client`. */
139
+ readonly runtimeSpecifier?: string | undefined;
140
+ /** The prefix the server serves its REST paths under, which the client's paths omit. Defaults to none. */
141
+ readonly restPathPrefix?: string | undefined;
142
+ /** Catalog tags whose REST-only operations the generic JSON request transport cannot carry. */
143
+ readonly excludedRestTags?: readonly string[] | undefined;
144
+ /** How the factory reaches its server. Defaults to a base URL and headers over JSON-RPC HTTP. */
145
+ readonly connection?: OperationClientConnection | undefined;
146
+ /** Operation names for the examples. */
147
+ readonly examples?: OperationClientExamples | undefined;
148
+ /** Groups operations into generated files. Defaults to the operation's first tag. */
149
+ readonly domainName?: OperationDomainName | undefined;
150
+ /**
151
+ * Whether to emit a method for each subscription the generic handler serves over Server-Sent
152
+ * Events at `GET ${routePrefix}/:operationName`. `'generic'` emits one for every operation of kind
153
+ * `subscription` whose HTTP route is enabled; `'none'`, the default, emits none. The methods open
154
+ * their stream with the connection's `baseUrl`, `headers` and `fetch`, so a custom `connection`
155
+ * must have them.
156
+ */
157
+ readonly subscriptions?: 'generic' | 'none' | undefined;
158
+ /** Narrows the subscription methods, and says where their route is served. */
159
+ readonly subscriptionRoutes?: OperationClientSubscriptionRoutes | undefined;
160
+ /** Formats one generated file. The package imports no formatter, so the caller brings it. */
161
+ readonly format: (source: string, filePath: string) => Promise<string>;
162
+ };
163
+ /**
164
+ * Generate a typed client from a catalog snapshot: one file of types per domain, a file of shared
165
+ * type aliases when any repeat, and the main file that holds the operation names, the REST
166
+ * bindings, the type maps and the factory. Output is deterministic for a given snapshot and
167
+ * options, so a checked-in copy can be compared against a fresh run.
168
+ *
169
+ * @example
170
+ * ```ts
171
+ * import { createOperationClientSources } from '@lostgradient/backchannel/generator';
172
+ *
173
+ * const sources = await createOperationClientSources(
174
+ * { generatedBy: 'weft catalog snapshot', version: 1, operations: [] },
175
+ * {
176
+ * packageName: '@example/probe',
177
+ * serverName: 'Probe',
178
+ * factoryName: 'createProbeClient',
179
+ * outputDirectory: 'src/client/generated',
180
+ * format: async (source) => source,
181
+ * },
182
+ * );
183
+ * console.log([...sources.keys()]);
184
+ * ```
185
+ */
186
+ export declare function createOperationClientSources(snapshot: CatalogSnapshot, options: OperationClientOptions): Promise<ReadonlyMap<string, string>>;