@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,23 @@
1
+ /**
2
+ * What a handler does with an authentication result: the context a successful one admits and the
3
+ * 401 a rejected one receives. Shared by `serve()`'s request gate and the engine-independent
4
+ * handler's authenticator, so the two forward the same principal and claims, and the body and the
5
+ * `WWW-Authenticate` challenge cannot drift apart.
6
+ *
7
+ * @module server/handler/authentication-responses
8
+ */
9
+ import type { AuthContext, AuthResult } from "../authentication.js";
10
+ /**
11
+ * The context a successful, non-public authentication result admits. One
12
+ * mapping for `serve()`'s gate and for the engine-independent handler's
13
+ * authenticator, so the two forward the same principal and claims.
14
+ */
15
+ export declare function authContextFromAuthResult(authResult: Extract<AuthResult, {
16
+ authenticated: true;
17
+ }>): AuthContext;
18
+ /**
19
+ * The 401 a rejected credential receives. Shared by `serve()`'s gate and the
20
+ * engine-independent handler's authenticator so the body and the
21
+ * `WWW-Authenticate` challenge cannot drift apart.
22
+ */
23
+ export declare function unauthorizedResponse(error: string): Response;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * What a handler does with an authentication result: the context a successful one admits and the
3
+ * 401 a rejected one receives. Shared by `serve()`'s request gate and the engine-independent
4
+ * handler's authenticator, so the two forward the same principal and claims, and the body and the
5
+ * `WWW-Authenticate` challenge cannot drift apart.
6
+ *
7
+ * @module server/handler/authentication-responses
8
+ */
9
+ /**
10
+ * The context a successful, non-public authentication result admits. One
11
+ * mapping for `serve()`'s gate and for the engine-independent handler's
12
+ * authenticator, so the two forward the same principal and claims.
13
+ */
14
+ export function authContextFromAuthResult(authResult) {
15
+ return {
16
+ method: authResult.method,
17
+ ...(authResult.claims !== undefined ? { claims: authResult.claims } : {}),
18
+ ...(authResult.principal !== undefined ? { principal: authResult.principal } : {}),
19
+ };
20
+ }
21
+ /**
22
+ * The 401 a rejected credential receives. Shared by `serve()`'s gate and the
23
+ * engine-independent handler's authenticator so the body and the
24
+ * `WWW-Authenticate` challenge cannot drift apart.
25
+ */
26
+ export function unauthorizedResponse(error) {
27
+ return new Response(JSON.stringify({ error }), {
28
+ status: 401,
29
+ headers: {
30
+ 'Content-Type': 'application/json',
31
+ 'WWW-Authenticate': 'Bearer',
32
+ },
33
+ });
34
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The JSON, error and content-negotiated responses a handler builds, with no codec of its own: a
3
+ * host that serves a binary encoding passes the encoder.
4
+ *
5
+ * @module server/handler/json-responses
6
+ */
7
+ /** Builds a JSON response with the given body and status, 200 by default. */
8
+ export declare function jsonResponse(body: unknown, status?: number): Response;
9
+ /** Builds a JSON error response with the given message and status. */
10
+ export declare function errorResponse(message: string, status: number): Response;
11
+ /**
12
+ * Answer as `application/msgpack` when the request accepts it and the host supplied an encoder,
13
+ * and as JSON otherwise.
14
+ */
15
+ export declare function negotiatedJsonOrBinary(request: Request, body: unknown, status: number, encodeBinary: ((value: unknown) => Uint8Array) | undefined): Response;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The JSON, error and content-negotiated responses a handler builds, with no codec of its own: a
3
+ * host that serves a binary encoding passes the encoder.
4
+ *
5
+ * @module server/handler/json-responses
6
+ */
7
+ import { copyBytesToArrayBuffer } from "../byte-arrays.js";
8
+ /** Builds a JSON response with the given body and status, 200 by default. */
9
+ export function jsonResponse(body, status = 200) {
10
+ return new Response(JSON.stringify(body), {
11
+ status,
12
+ headers: { 'Content-Type': 'application/json' },
13
+ });
14
+ }
15
+ /** Builds a JSON error response with the given message and status. */
16
+ export function errorResponse(message, status) {
17
+ return jsonResponse({ error: message }, status);
18
+ }
19
+ /**
20
+ * Answer as `application/msgpack` when the request accepts it and the host supplied an encoder,
21
+ * and as JSON otherwise.
22
+ */
23
+ export function negotiatedJsonOrBinary(request, body, status, encodeBinary) {
24
+ const accept = request.headers.get('Accept') ?? '';
25
+ if (encodeBinary !== undefined && accept.includes('application/msgpack')) {
26
+ return new Response(copyBytesToArrayBuffer(encodeBinary(body)), {
27
+ status,
28
+ headers: { 'Content-Type': 'application/msgpack' },
29
+ });
30
+ }
31
+ return jsonResponse(body, status);
32
+ }
@@ -0,0 +1,64 @@
1
+ import { type AuthConfig, type AuthContext } from "../authentication.js";
2
+ import { type PackageAuthorizationScope, type ScopeVocabulary } from "../authorization-scope.js";
3
+ /**
4
+ * Resolves the caller of one request for `createOperationHandler`. Resolve to
5
+ * an {@link AuthContext} to admit the request, or to a `Response` (usually a
6
+ * 401) to refuse it; a `Response` is returned to the caller as-is.
7
+ */
8
+ export type OperationHandlerAuthenticate = (request: Request) => Promise<AuthContext | Response>;
9
+ /**
10
+ * The authenticator `createOperationHandlerAuthenticator` builds: an
11
+ * `authenticate` hook plus `ready`, which settles once the credential keys
12
+ * have been imported and rejects when one cannot be. Await it at startup to
13
+ * fail the way `serve()` does, rather than answering every request with a 500
14
+ * for the life of the process.
15
+ */
16
+ export type OperationHandlerAuthenticator = OperationHandlerAuthenticate & {
17
+ readonly ready: Promise<void>;
18
+ };
19
+ /** Options for {@link createOperationHandlerAuthenticator}. */
20
+ export type OperationHandlerAuthenticatorOptions = {
21
+ /** Scopes issued by this host. */
22
+ readonly scopeVocabulary?: ScopeVocabulary;
23
+ /**
24
+ * Package scopes the handler's operations require beyond Weft's built-in
25
+ * vocabulary, such as `bureau.tasks:read`. The authenticator retains them
26
+ * from JWT `scope`, `scp`, and `permissions` claims, from
27
+ * `defaultApiKeyScopes`, and from the principal `resolveApiKeyPrincipal`
28
+ * returns; any other unknown scope is dropped. They belong to this
29
+ * authenticator alone. Same rules and the same validation as
30
+ * `serve({ additionalScopes })`.
31
+ */
32
+ readonly additionalScopes?: readonly PackageAuthorizationScope[];
33
+ };
34
+ /**
35
+ * Build the `authenticate` hook for `createOperationHandler` from Weft's
36
+ * API-key, JWT, and mTLS schemes.
37
+ *
38
+ * It admits and refuses exactly as `serve({ auth })` does: the same
39
+ * `createAuthenticator` underneath, the same forwarded principal, and the same
40
+ * 401 (body and `WWW-Authenticate` challenge) for a rejected credential. A bad
41
+ * `config` or `additionalScopes` entry throws here, synchronously, before the
42
+ * handler serves a request, and so does a `config.publicPaths`: the handler owns
43
+ * public paths. A key that cannot be imported rejects `ready`.
44
+ *
45
+ * mTLS is admitted only on positive evidence of a verified client certificate,
46
+ * and a fetch handler has no transport to supply it, so a request there is
47
+ * never admitted by `mtls`.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * import { createOperationHandler, createOperationHandlerAuthenticator } from '@lostgradient/backchannel';
52
+ *
53
+ * const handler = createOperationHandler({
54
+ * operations: [],
55
+ * host: {},
56
+ * authenticate: createOperationHandlerAuthenticator(
57
+ * { apiKeys: ['s3cr3t'], defaultApiKeyScopes: ['inventory:read'] },
58
+ * { additionalScopes: ['bureau.tasks:read'] },
59
+ * ),
60
+ * });
61
+ * void handler;
62
+ * ```
63
+ */
64
+ export declare function createOperationHandlerAuthenticator(config: AuthConfig, options?: OperationHandlerAuthenticatorOptions): OperationHandlerAuthenticator;
@@ -0,0 +1,58 @@
1
+ import { createAuthenticator, validateAuthConfig, } from "../authentication.js";
2
+ import { createAdditionalScopeSet, } from "../authorization-scope.js";
3
+ import { authContextFromAuthResult, unauthorizedResponse } from "./authentication-responses.js";
4
+ /**
5
+ * Build the `authenticate` hook for `createOperationHandler` from Weft's
6
+ * API-key, JWT, and mTLS schemes.
7
+ *
8
+ * It admits and refuses exactly as `serve({ auth })` does: the same
9
+ * `createAuthenticator` underneath, the same forwarded principal, and the same
10
+ * 401 (body and `WWW-Authenticate` challenge) for a rejected credential. A bad
11
+ * `config` or `additionalScopes` entry throws here, synchronously, before the
12
+ * handler serves a request, and so does a `config.publicPaths`: the handler owns
13
+ * public paths. A key that cannot be imported rejects `ready`.
14
+ *
15
+ * mTLS is admitted only on positive evidence of a verified client certificate,
16
+ * and a fetch handler has no transport to supply it, so a request there is
17
+ * never admitted by `mtls`.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * import { createOperationHandler, createOperationHandlerAuthenticator } from '@lostgradient/backchannel';
22
+ *
23
+ * const handler = createOperationHandler({
24
+ * operations: [],
25
+ * host: {},
26
+ * authenticate: createOperationHandlerAuthenticator(
27
+ * { apiKeys: ['s3cr3t'], defaultApiKeyScopes: ['inventory:read'] },
28
+ * { additionalScopes: ['bureau.tasks:read'] },
29
+ * ),
30
+ * });
31
+ * void handler;
32
+ * ```
33
+ */
34
+ export function createOperationHandlerAuthenticator(config, options = {}) {
35
+ validateAuthConfig(config);
36
+ if (config.publicPaths !== undefined) {
37
+ throw new Error('createOperationHandlerAuthenticator: config.publicPaths is not accepted. Public paths ' +
38
+ "are decided in one place, `createOperationHandler({ publicPaths })` and each mount's " +
39
+ '`publicPaths`; the authenticator itself has none.');
40
+ }
41
+ createAdditionalScopeSet(options.additionalScopes);
42
+ // The authenticator's built-in public paths (`/v1/metrics`, `/.well-known/*`)
43
+ // would admit those requests unauthenticated at a mount that never declared
44
+ // them, so the inner authenticator is given none.
45
+ const authenticatorPromise = createAuthenticator({ ...config, publicPaths: [] }, options);
46
+ // A key that fails to import rejects `ready` and every request. Neither is
47
+ // reported as an unhandled rejection while nothing is awaiting it yet.
48
+ const ready = authenticatorPromise.then(() => undefined);
49
+ ready.catch(() => undefined);
50
+ const authenticate = async (request) => {
51
+ const authenticator = await authenticatorPromise;
52
+ const result = await authenticator(request);
53
+ if (!result.authenticated)
54
+ return unauthorizedResponse(result.error);
55
+ return authContextFromAuthResult(result);
56
+ };
57
+ return Object.assign(authenticate, { ready });
58
+ }
@@ -0,0 +1,29 @@
1
+ import type { DiscoveryInfo } from "../discovery-info.js";
2
+ import type { OperationRegistry } from "../operation-catalog.js";
3
+ export type OperationHandlerDocuments = {
4
+ readonly openApi: () => Record<string, unknown>;
5
+ readonly openRpc: () => Record<string, unknown>;
6
+ readonly asyncApi: () => Record<string, unknown>;
7
+ };
8
+ /**
9
+ * The three discovery documents for the handler's own registry, and for the
10
+ * surface the handler really serves, which is narrower than Weft's:
11
+ *
12
+ * - OpenAPI lists the direct routes the handler answers (health and the three
13
+ * documents), none of Weft's REST bindings, and not metrics, `api-catalog`,
14
+ * or `mcp.json`.
15
+ * - OpenRPC declares `http` and `websocket`, carries no MCP metadata, and is
16
+ * the document `rpc.discover` answers with.
17
+ * - AsyncAPI lists each `transports.http` subscription as a Server-Sent Events
18
+ * channel at `/v1/subscriptions/<operation name>` and nothing else.
19
+ *
20
+ * Generated on first use and kept: the registry is immutable once the handler
21
+ * is constructed.
22
+ */
23
+ export declare function createOperationHandlerDocuments(options: {
24
+ readonly registry: OperationRegistry;
25
+ readonly discoveryInfo: DiscoveryInfo | undefined;
26
+ readonly authenticates: boolean;
27
+ /** The resolved public paths; the OpenAPI document marks only these as needing no credentials. */
28
+ readonly publicPaths: ReadonlySet<string>;
29
+ }): OperationHandlerDocuments;
@@ -0,0 +1,55 @@
1
+ import { generateAsyncApiDocument } from "../asyncapi.js";
2
+ import { generateOpenApiDocument } from "../openapi.js";
3
+ import { generateOpenRpcDocument } from "../openrpc.js";
4
+ /**
5
+ * The three discovery documents for the handler's own registry, and for the
6
+ * surface the handler really serves, which is narrower than Weft's:
7
+ *
8
+ * - OpenAPI lists the direct routes the handler answers (health and the three
9
+ * documents), none of Weft's REST bindings, and not metrics, `api-catalog`,
10
+ * or `mcp.json`.
11
+ * - OpenRPC declares `http` and `websocket`, carries no MCP metadata, and is
12
+ * the document `rpc.discover` answers with.
13
+ * - AsyncAPI lists each `transports.http` subscription as a Server-Sent Events
14
+ * channel at `/v1/subscriptions/<operation name>` and nothing else.
15
+ *
16
+ * Generated on first use and kept: the registry is immutable once the handler
17
+ * is constructed.
18
+ */
19
+ export function createOperationHandlerDocuments(options) {
20
+ const { registry, discoveryInfo } = options;
21
+ const info = discoveryInfo === undefined ? {} : { discoveryInfo };
22
+ // Anonymous-only handlers advertise no credential scheme.
23
+ const supportedSchemes = options.authenticates
24
+ ? undefined
25
+ : new Set();
26
+ return {
27
+ openApi: lazily(() => generateOpenApiDocument({
28
+ registry,
29
+ restBindings: [],
30
+ directRoutes: ['healthCheck', 'openApiDocument', 'openRpcDocument', 'asyncApiDocument'],
31
+ publicPaths: options.publicPaths,
32
+ ...(supportedSchemes === undefined ? {} : { supportedSchemes }),
33
+ ...info,
34
+ })),
35
+ openRpc: lazily(() => generateOpenRpcDocument({
36
+ registry,
37
+ transports: ['http', 'websocket'],
38
+ includeMcpMetadata: false,
39
+ ...info,
40
+ })),
41
+ asyncApi: lazily(() => generateAsyncApiDocument({
42
+ registry,
43
+ restBindings: [],
44
+ subscriptionTransport: 'http-route',
45
+ ...info,
46
+ })),
47
+ };
48
+ }
49
+ function lazily(generate) {
50
+ let document;
51
+ return () => {
52
+ document ??= generate();
53
+ return document;
54
+ };
55
+ }
@@ -0,0 +1,100 @@
1
+ import type { DispatchResult, ErasedOperation, executeSubscription, OperationRegistry } from "../operation-catalog.js";
2
+ import type { Principal } from "../principal.js";
3
+ /**
4
+ * One registered operation as a mounted adapter sees it: what it needs to
5
+ * describe the operation in its own protocol (an MCP bridge lists tools from
6
+ * these), and nothing that would let it run the operation outside the pipeline.
7
+ */
8
+ export type OperationHandlerMountOperation = Pick<ErasedOperation, 'name' | 'summary' | 'description' | 'mcpExposable' | 'mcpTool' | 'destructive' | 'inputSchema' | 'outputSchema' | 'unknownKeyPolicy' | 'kind' | 'behavior' | 'access' | 'parameterizedAccess'>;
9
+ /**
10
+ * Which transport a mounted adapter's dispatch is attributed to. `http-rest` is the default;
11
+ * `mcp` admits exactly the operations the catalog marks `mcpExposable`.
12
+ */
13
+ export type OperationHandlerMountDispatchOptions = {
14
+ /** The transport the dispatch runs as: `http-rest` by default, or `mcp`. */
15
+ readonly transport?: 'http-rest' | 'mcp';
16
+ /** Cancellation of the protocol-level call, combined with the request signal. */
17
+ readonly signal?: AbortSignal;
18
+ };
19
+ /**
20
+ * What an adapter mounted on the operation handler receives with each request.
21
+ *
22
+ * An adapter translates its protocol and the catalog executes: `dispatch` and
23
+ * `subscribe` run the full catalog pipeline (transport, access policy,
24
+ * parsing, `authorize`, output validation) as the resolved `principal`, over
25
+ * the `http-rest` transport unless the adapter names `mcp`. An adapter that
26
+ * bypassed them and reached into the host directly would also bypass access
27
+ * policy.
28
+ */
29
+ export type OperationHandlerMountContext = {
30
+ /** The caller `authenticate` resolved, or the anonymous principal on a public path. */
31
+ readonly principal: Principal;
32
+ /** Every registered operation, in registration order. */
33
+ readonly operations: ReadonlyArray<OperationHandlerMountOperation>;
34
+ /** Runs one unary catalog operation through the full pipeline, as this principal. */
35
+ readonly dispatch: (operationName: string, input: unknown, options?: OperationHandlerMountDispatchOptions) => Promise<DispatchResult<unknown>>;
36
+ /** Runs one `subscription` catalog operation through the full pipeline, as this principal. */
37
+ readonly subscribe: (operationName: string, input: unknown, options?: OperationHandlerMountDispatchOptions) => ReturnType<typeof executeSubscription>;
38
+ };
39
+ /**
40
+ * A protocol adapter (A2A, AG-UI, an MCP bridge) mounted on the handler. It
41
+ * is not a catalog operation and appears in none of the discovery documents.
42
+ */
43
+ export type OperationHandlerMount = {
44
+ /**
45
+ * Path prefix this adapter owns, for example `/a2a`. It handles a request
46
+ * whose path equals the prefix or begins with `<prefix>/`.
47
+ */
48
+ readonly pathPrefix: string;
49
+ /**
50
+ * Exact paths, anywhere in the URL space, that skip `authenticate`, such as
51
+ * `/.well-known/agent-card.json`. The mount also handles them.
52
+ */
53
+ readonly publicPaths?: ReadonlyArray<string>;
54
+ /**
55
+ * Decides, for a path under `pathPrefix`, whether it skips `authenticate`: for routes a fixed
56
+ * list cannot name, such as an Agent Card at `<prefix>/<agent>/.well-known/agent-card.json`
57
+ * for an agent published after construction. It is consulted only for paths the prefix covers,
58
+ * so a mount cannot make another route public.
59
+ */
60
+ readonly isPublicPath?: (pathname: string) => boolean;
61
+ /** Answers a request under the mount's path prefix. */
62
+ readonly fetch: (request: Request, context: OperationHandlerMountContext) => Promise<Response>;
63
+ };
64
+ /**
65
+ * Every path the handler answers itself. A mount prefix may not overlap one,
66
+ * and a mount's public path may not be one or sit beneath one.
67
+ */
68
+ export declare const OPERATION_HANDLER_CATALOG_ROUTE_PATHS: ReadonlyArray<string>;
69
+ /** Whether `path` is `prefix` or lies beneath it at a segment boundary. */
70
+ export declare function isAtOrUnder(path: string, prefix: string): boolean;
71
+ export type ResolvedMounts = {
72
+ /** The mount that handles `pathname`, if any. */
73
+ readonly match: (pathname: string) => OperationHandlerMount | undefined;
74
+ /** Every mount public path, normalized. */
75
+ readonly publicPaths: ReadonlySet<string>;
76
+ /** Whether `pathname` skips authentication: a public path, or one its mount's predicate passes. */
77
+ readonly isPublic: (pathname: string) => boolean;
78
+ };
79
+ /**
80
+ * The paths the handler itself answers without authentication unless the host
81
+ * says otherwise: health and the three discovery documents.
82
+ */
83
+ export declare const DEFAULT_OPERATION_HANDLER_PUBLIC_PATHS: ReadonlyArray<string>;
84
+ /**
85
+ * Validate the handler's own `publicPaths` once, at construction, with the
86
+ * rules a mount's `publicPaths` follow: an entry is an absolute path that
87
+ * names a route the handler serves exactly, a fixed route or
88
+ * `/v1/subscriptions/<name>` for a registered subscription (anything else is
89
+ * inert and almost certainly a typo). A mount can never claim such a path, because a mount
90
+ * prefix or public path that equals or lies beneath a catalog route is refused
91
+ * at construction, so an unauthenticated path always has exactly one owner.
92
+ */
93
+ export declare function resolveHandlerPublicPaths(paths: ReadonlyArray<string>, registry: OperationRegistry): ReadonlySet<string>;
94
+ /**
95
+ * Validate the mounts once, at construction, the way `createOperationRegistry`
96
+ * rejects duplicate operation names: an adapter must not shadow a native
97
+ * route or another adapter, and an unauthenticated path must have exactly one
98
+ * owner.
99
+ */
100
+ export declare function resolveMounts(mounts: ReadonlyArray<OperationHandlerMount>): ResolvedMounts;
@@ -0,0 +1,134 @@
1
+ import { GENERIC_SUBSCRIPTION_ROUTE_PREFIX } from "../route-model.js";
2
+ /**
3
+ * Every path the handler answers itself. A mount prefix may not overlap one,
4
+ * and a mount's public path may not be one or sit beneath one.
5
+ */
6
+ export const OPERATION_HANDLER_CATALOG_ROUTE_PATHS = [
7
+ '/jsonrpc',
8
+ GENERIC_SUBSCRIPTION_ROUTE_PREFIX,
9
+ '/openapi.json',
10
+ '/openrpc.json',
11
+ '/asyncapi.json',
12
+ '/v1/health',
13
+ ];
14
+ /** Whether `path` is `prefix` or lies beneath it at a segment boundary. */
15
+ export function isAtOrUnder(path, prefix) {
16
+ return path === prefix || path.startsWith(`${prefix}/`);
17
+ }
18
+ function overlaps(left, right) {
19
+ return isAtOrUnder(left, right) || isAtOrUnder(right, left);
20
+ }
21
+ function stripTrailingSlashes(path) {
22
+ return path.length > 1 ? path.replace(/\/+$/, '') : path;
23
+ }
24
+ function assertMountPath(path, description) {
25
+ const normalized = stripTrailingSlashes(path);
26
+ if (!/^\/[^\s?#]+$/.test(normalized)) {
27
+ throw new Error(`createOperationHandler: ${description} ${JSON.stringify(path)} must be an absolute path ` +
28
+ 'with no query or fragment, and cannot be the root');
29
+ }
30
+ return normalized;
31
+ }
32
+ /**
33
+ * The paths the handler itself answers without authentication unless the host
34
+ * says otherwise: health and the three discovery documents.
35
+ */
36
+ export const DEFAULT_OPERATION_HANDLER_PUBLIC_PATHS = [
37
+ '/v1/health',
38
+ '/openapi.json',
39
+ '/openrpc.json',
40
+ '/asyncapi.json',
41
+ ];
42
+ /**
43
+ * Validate the handler's own `publicPaths` once, at construction, with the
44
+ * rules a mount's `publicPaths` follow: an entry is an absolute path that
45
+ * names a route the handler serves exactly, a fixed route or
46
+ * `/v1/subscriptions/<name>` for a registered subscription (anything else is
47
+ * inert and almost certainly a typo). A mount can never claim such a path, because a mount
48
+ * prefix or public path that equals or lies beneath a catalog route is refused
49
+ * at construction, so an unauthenticated path always has exactly one owner.
50
+ */
51
+ export function resolveHandlerPublicPaths(paths, registry) {
52
+ const resolved = new Set();
53
+ for (const path of paths) {
54
+ const normalized = assertMountPath(path, 'publicPaths entry');
55
+ if (!servesExactly(normalized, registry)) {
56
+ throw new Error(`createOperationHandler: publicPaths entry "${normalized}" is not a route the handler serves. ` +
57
+ `Use one of ${FIXED_ROUTE_PATHS.join(', ')}, or ${GENERIC_SUBSCRIPTION_ROUTE_PREFIX}/<name> ` +
58
+ 'for a registered subscription operation');
59
+ }
60
+ resolved.add(normalized);
61
+ }
62
+ return resolved;
63
+ }
64
+ const FIXED_ROUTE_PATHS = OPERATION_HANDLER_CATALOG_ROUTE_PATHS.filter((route) => route !== GENERIC_SUBSCRIPTION_ROUTE_PREFIX);
65
+ /** A fixed route, or the subscription route for an operation that is registered. */
66
+ function servesExactly(path, registry) {
67
+ if (FIXED_ROUTE_PATHS.includes(path))
68
+ return true;
69
+ const subscriptionPrefix = `${GENERIC_SUBSCRIPTION_ROUTE_PREFIX}/`;
70
+ if (!path.startsWith(subscriptionPrefix))
71
+ return false;
72
+ return registry.get(path.slice(subscriptionPrefix.length))?.kind === 'subscription';
73
+ }
74
+ /**
75
+ * Validate the mounts once, at construction, the way `createOperationRegistry`
76
+ * rejects duplicate operation names: an adapter must not shadow a native
77
+ * route or another adapter, and an unauthenticated path must have exactly one
78
+ * owner.
79
+ */
80
+ export function resolveMounts(mounts) {
81
+ const normalized = mounts.map((mount) => ({
82
+ mount,
83
+ pathPrefix: assertMountPath(mount.pathPrefix, 'mount pathPrefix'),
84
+ publicPaths: (mount.publicPaths ?? []).map((path) => assertMountPath(path, 'mount publicPaths entry')),
85
+ }));
86
+ for (const [index, entry] of normalized.entries()) {
87
+ assertPrefixIsFree(entry, normalized.slice(0, index));
88
+ assertPublicPathsAreFree(entry, normalized.filter((other) => other !== entry));
89
+ }
90
+ const publicPaths = new Set(normalized.flatMap((entry) => entry.publicPaths));
91
+ return {
92
+ publicPaths,
93
+ isPublic(pathname) {
94
+ if (publicPaths.has(pathname))
95
+ return true;
96
+ const owner = normalized.find((entry) => isAtOrUnder(pathname, entry.pathPrefix));
97
+ return owner?.mount.isPublicPath?.(pathname) === true;
98
+ },
99
+ match(pathname) {
100
+ for (const entry of normalized) {
101
+ if (isAtOrUnder(pathname, entry.pathPrefix) || entry.publicPaths.includes(pathname)) {
102
+ return entry.mount;
103
+ }
104
+ }
105
+ return undefined;
106
+ },
107
+ };
108
+ }
109
+ function assertPrefixIsFree(entry, earlier) {
110
+ for (const route of OPERATION_HANDLER_CATALOG_ROUTE_PATHS) {
111
+ if (overlaps(entry.pathPrefix, route)) {
112
+ throw new Error(`createOperationHandler: mount pathPrefix "${entry.pathPrefix}" overlaps the catalog route "${route}"`);
113
+ }
114
+ }
115
+ for (const other of earlier) {
116
+ if (overlaps(entry.pathPrefix, other.pathPrefix)) {
117
+ throw new Error(`createOperationHandler: mount pathPrefix "${entry.pathPrefix}" overlaps the mount "${other.pathPrefix}"`);
118
+ }
119
+ }
120
+ }
121
+ function assertPublicPathsAreFree(entry, others) {
122
+ for (const publicPath of entry.publicPaths) {
123
+ for (const route of OPERATION_HANDLER_CATALOG_ROUTE_PATHS) {
124
+ if (isAtOrUnder(publicPath, route)) {
125
+ throw new Error(`createOperationHandler: mount publicPaths entry "${publicPath}" is the catalog route "${route}" or lies beneath it`);
126
+ }
127
+ }
128
+ for (const other of others) {
129
+ if (isAtOrUnder(publicPath, other.pathPrefix) || other.publicPaths.includes(publicPath)) {
130
+ throw new Error(`createOperationHandler: mount publicPaths entry "${publicPath}" of "${entry.pathPrefix}" belongs to the mount "${other.pathPrefix}"`);
131
+ }
132
+ }
133
+ }
134
+ }
@@ -0,0 +1,34 @@
1
+ import { type OperationRegistry } from "../operation-catalog.js";
2
+ import { type ServerSentEventHeartbeatOptions } from "../operations/sse-stream.js";
3
+ import type { Principal } from "../principal.js";
4
+ /** How long one response may stream before the handler ends it: fifteen minutes. */
5
+ export declare const DEFAULT_MAX_STREAM_DURATION_MS = 900000;
6
+ export type SubscriptionRouteContext = {
7
+ readonly registry: OperationRegistry;
8
+ readonly host: unknown;
9
+ readonly principal: Principal;
10
+ readonly maxStreamDurationMs: number;
11
+ readonly heartbeat: ServerSentEventHeartbeatOptions | undefined;
12
+ /** The host's error-code vocabulary (see `FaultPolicy.isKnownErrorCode`). */
13
+ readonly isKnownErrorCode?: ((value: string) => boolean) | undefined;
14
+ };
15
+ /**
16
+ * Map a query string onto a subscription's input. Every value is a string; a
17
+ * key that repeats becomes an array of its values in order. Nothing is coerced
18
+ * to a number or a boolean: a schema that wants one declares `z.coerce`.
19
+ *
20
+ * The record has no prototype, so a `__proto__` key is an ordinary own key
21
+ * that the operation's unknown-key policy then rejects or strips, rather than
22
+ * a write to the prototype.
23
+ */
24
+ export declare function subscriptionInputFromQuery(searchParams: URLSearchParams): Record<string, string | string[]>;
25
+ /**
26
+ * Serve `GET /v1/subscriptions/:operationName`: the catalog subscription
27
+ * `operationName` as Server-Sent Events, resumable with `Last-Event-ID`.
28
+ *
29
+ * A fetch handler cannot accept a WebSocket, so this is how a subscription
30
+ * reaches a plain HTTP client. The operation runs through the same pipeline as
31
+ * every other transport (`executeSubscription`), so access policy, `authorize`,
32
+ * and input parsing are not reimplemented here.
33
+ */
34
+ export declare function handleSubscriptionRequest(request: Request, operationName: string, context: SubscriptionRouteContext): Promise<Response>;