@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.
- package/LICENSE +21 -0
- package/README.md +62 -2
- package/dist/access-policy-metadata.d.ts +92 -0
- package/dist/access-policy-metadata.js +87 -0
- package/dist/asyncapi-channels.d.ts +46 -0
- package/dist/asyncapi-channels.js +399 -0
- package/dist/asyncapi.d.ts +40 -0
- package/dist/asyncapi.js +165 -0
- package/dist/authentication/api-key.d.ts +4 -0
- package/dist/authentication/api-key.js +114 -0
- package/dist/authentication/audit.d.ts +115 -0
- package/dist/authentication/audit.js +75 -0
- package/dist/authentication/credential-verifiers.d.ts +60 -0
- package/dist/authentication/credential-verifiers.js +102 -0
- package/dist/authentication/crypto.d.ts +7 -0
- package/dist/authentication/crypto.js +140 -0
- package/dist/authentication/index.d.ts +80 -0
- package/dist/authentication/index.js +212 -0
- package/dist/authentication/rate-limiter.d.ts +133 -0
- package/dist/authentication/rate-limiter.js +124 -0
- package/dist/authentication/redaction.d.ts +72 -0
- package/dist/authentication/redaction.js +118 -0
- package/dist/authentication/rotating-api-key-store.d.ts +127 -0
- package/dist/authentication/rotating-api-key-store.js +126 -0
- package/dist/authentication/types.d.ts +337 -0
- package/dist/authentication/types.js +26 -0
- package/dist/authentication.d.ts +1 -0
- package/dist/authentication.js +1 -0
- package/dist/authorization-scope.d.ts +109 -0
- package/dist/authorization-scope.js +144 -0
- package/dist/authorization.d.ts +55 -0
- package/dist/authorization.js +134 -0
- package/dist/bind-feed-lifetime.d.ts +45 -0
- package/dist/bind-feed-lifetime.js +55 -0
- package/dist/byte-arrays.d.ts +5 -0
- package/dist/byte-arrays.js +9 -0
- package/dist/client/catalog-client.d.ts +285 -0
- package/dist/client/catalog-client.js +74 -0
- package/dist/client/in-process-transport.d.ts +19 -0
- package/dist/client/in-process-transport.js +136 -0
- package/dist/client/index.d.ts +14 -0
- package/dist/client/index.js +14 -0
- package/dist/client/json-rpc-http-transport.d.ts +118 -0
- package/dist/client/json-rpc-http-transport.js +127 -0
- package/dist/client/server-sent-event-parser.d.ts +55 -0
- package/dist/client/server-sent-event-parser.js +78 -0
- package/dist/client/sse-subscription-transport.d.ts +72 -0
- package/dist/client/sse-subscription-transport.js +224 -0
- package/dist/client/subscription-client.d.ts +122 -0
- package/dist/client/subscription-client.js +28 -0
- package/dist/connection-lease.d.ts +10 -0
- package/dist/connection-lease.js +8 -0
- package/dist/discovery-filter.d.ts +13 -0
- package/dist/discovery-filter.js +16 -0
- package/dist/discovery-info.d.ts +94 -0
- package/dist/discovery-info.js +38 -0
- package/dist/event-selector.d.ts +7 -0
- package/dist/event-selector.js +7 -0
- package/dist/fault-code.d.ts +84 -0
- package/dist/fault-code.js +114 -0
- package/dist/fault-remediation.d.ts +30 -0
- package/dist/fault-remediation.js +52 -0
- package/dist/fault-to-http.d.ts +11 -0
- package/dist/fault-to-http.js +13 -0
- package/dist/fault-to-json-rpc.d.ts +53 -0
- package/dist/fault-to-json-rpc.js +143 -0
- package/dist/fault-wire-safety.d.ts +45 -0
- package/dist/fault-wire-safety.js +72 -0
- package/dist/generator.d.ts +9 -0
- package/dist/generator.js +9 -0
- package/dist/handler/auth-context-principal.d.ts +37 -0
- package/dist/handler/auth-context-principal.js +67 -0
- package/dist/handler/authentication-responses.d.ts +23 -0
- package/dist/handler/authentication-responses.js +34 -0
- package/dist/handler/json-responses.d.ts +15 -0
- package/dist/handler/json-responses.js +32 -0
- package/dist/handler/operation-handler-authentication.d.ts +64 -0
- package/dist/handler/operation-handler-authentication.js +58 -0
- package/dist/handler/operation-handler-discovery.d.ts +29 -0
- package/dist/handler/operation-handler-discovery.js +55 -0
- package/dist/handler/operation-handler-mounts.d.ts +100 -0
- package/dist/handler/operation-handler-mounts.js +134 -0
- package/dist/handler/operation-handler-subscription.d.ts +34 -0
- package/dist/handler/operation-handler-subscription.js +112 -0
- package/dist/handler/operation-handler.d.ts +162 -0
- package/dist/handler/operation-handler.js +236 -0
- package/dist/handler/workspace-release.d.ts +6 -0
- package/dist/handler/workspace-release.js +75 -0
- package/dist/in-memory-replay-live-backend.d.ts +47 -0
- package/dist/in-memory-replay-live-backend.js +129 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +30 -0
- package/dist/internal/cryptography/encryption.d.ts +108 -0
- package/dist/internal/cryptography/encryption.js +241 -0
- package/dist/internal/cryptography/hash.d.ts +72 -0
- package/dist/internal/cryptography/hash.js +233 -0
- package/dist/internal/cryptography/index.d.ts +4 -0
- package/dist/internal/cryptography/index.js +2 -0
- package/dist/internals.d.ts +58 -0
- package/dist/internals.js +54 -0
- package/dist/json-rpc-dispatch.d.ts +88 -0
- package/dist/json-rpc-dispatch.js +154 -0
- package/dist/json-rpc-framing.d.ts +42 -0
- package/dist/json-rpc-framing.js +50 -0
- package/dist/json-rpc-http.d.ts +36 -0
- package/dist/json-rpc-http.js +191 -0
- package/dist/json-rpc-parse.d.ts +69 -0
- package/dist/json-rpc-parse.js +206 -0
- package/dist/json-rpc-protocol.d.ts +76 -0
- package/dist/json-rpc-protocol.js +54 -0
- package/dist/json-rpc-session-runtime.d.ts +55 -0
- package/dist/json-rpc-session-runtime.js +111 -0
- package/dist/json-rpc-websocket-subscription-pump.d.ts +9 -0
- package/dist/json-rpc-websocket-subscription-pump.js +46 -0
- package/dist/json-rpc-websocket-subscriptions.d.ts +10 -0
- package/dist/json-rpc-websocket-subscriptions.js +33 -0
- package/dist/json-rpc-websocket-types.d.ts +34 -0
- package/dist/json-rpc-websocket-types.js +1 -0
- package/dist/json-rpc-websocket-validation.d.ts +45 -0
- package/dist/json-rpc-websocket-validation.js +154 -0
- package/dist/json-rpc-websocket.d.ts +20 -0
- package/dist/json-rpc-websocket.js +363 -0
- package/dist/json-schema-utilities.d.ts +5 -0
- package/dist/json-schema-utilities.js +17 -0
- package/dist/mcp-discovery-names.d.ts +11 -0
- package/dist/mcp-discovery-names.js +11 -0
- package/dist/openapi-canonical-json.d.ts +10 -0
- package/dist/openapi-canonical-json.js +23 -0
- package/dist/openapi-error-responses.d.ts +15 -0
- package/dist/openapi-error-responses.js +104 -0
- package/dist/openapi-schemas.d.ts +17 -0
- package/dist/openapi-schemas.js +94 -0
- package/dist/openapi.d.ts +60 -0
- package/dist/openapi.js +351 -0
- package/dist/openrpc-document-schema.d.ts +255 -0
- package/dist/openrpc-document-schema.js +84 -0
- package/dist/openrpc-errors.d.ts +93 -0
- package/dist/openrpc-errors.js +134 -0
- package/dist/openrpc.d.ts +66 -0
- package/dist/openrpc.js +260 -0
- package/dist/operation-catalog/behavior-types.d.ts +34 -0
- package/dist/operation-catalog/behavior-types.js +1 -0
- package/dist/operation-catalog/behavior-validation.d.ts +3 -0
- package/dist/operation-catalog/behavior-validation.js +298 -0
- package/dist/operation-catalog/dispatch-allowlist.d.ts +4 -0
- package/dist/operation-catalog/dispatch-allowlist.js +7 -0
- package/dist/operation-catalog/dispatch-preparation.d.ts +24 -0
- package/dist/operation-catalog/dispatch-preparation.js +49 -0
- package/dist/operation-catalog/index.d.ts +19 -0
- package/dist/operation-catalog/index.js +17 -0
- package/dist/operation-catalog/operation-dispatch.d.ts +14 -0
- package/dist/operation-catalog/operation-dispatch.js +115 -0
- package/dist/operation-catalog/operation-interceptors.d.ts +15 -0
- package/dist/operation-catalog/operation-interceptors.js +1 -0
- package/dist/operation-catalog/operation-metadata.d.ts +5 -0
- package/dist/operation-catalog/operation-metadata.js +104 -0
- package/dist/operation-catalog/pipeline-helpers.d.ts +70 -0
- package/dist/operation-catalog/pipeline-helpers.js +242 -0
- package/dist/operation-catalog/pipeline-stages.d.ts +23 -0
- package/dist/operation-catalog/pipeline-stages.js +226 -0
- package/dist/operation-catalog/pipeline.d.ts +7 -0
- package/dist/operation-catalog/pipeline.js +33 -0
- package/dist/operation-catalog/registry.d.ts +17 -0
- package/dist/operation-catalog/registry.js +132 -0
- package/dist/operation-catalog/stream-pipeline.d.ts +37 -0
- package/dist/operation-catalog/stream-pipeline.js +129 -0
- package/dist/operation-catalog/subscription-lifecycle.d.ts +6 -0
- package/dist/operation-catalog/subscription-lifecycle.js +27 -0
- package/dist/operation-catalog/types.d.ts +392 -0
- package/dist/operation-catalog/types.js +40 -0
- package/dist/operation-catalog/universal-faults.d.ts +11 -0
- package/dist/operation-catalog/universal-faults.js +15 -0
- package/dist/operation-catalog-snapshot.d.ts +215 -0
- package/dist/operation-catalog-snapshot.js +128 -0
- package/dist/operation-catalog.d.ts +1 -0
- package/dist/operation-catalog.js +1 -0
- package/dist/operation-description-audit.d.ts +44 -0
- package/dist/operation-description-audit.js +90 -0
- package/dist/operation-fault-helpers.d.ts +21 -0
- package/dist/operation-fault-helpers.js +32 -0
- package/dist/operation-fault.d.ts +245 -0
- package/dist/operation-fault.js +235 -0
- package/dist/operation-registry.d.ts +46 -0
- package/dist/operation-registry.js +46 -0
- package/dist/operations/closable-iterable.d.ts +23 -0
- package/dist/operations/closable-iterable.js +51 -0
- package/dist/operations/get-principal.d.ts +106 -0
- package/dist/operations/get-principal.js +107 -0
- package/dist/operations/sse-stream.d.ts +67 -0
- package/dist/operations/sse-stream.js +264 -0
- package/dist/principal.d.ts +253 -0
- package/dist/principal.js +254 -0
- package/dist/replay-live-feed-internals.d.ts +47 -0
- package/dist/replay-live-feed-internals.js +215 -0
- package/dist/replay-live-feed-types.d.ts +66 -0
- package/dist/replay-live-feed-types.js +7 -0
- package/dist/replay-live-feed.d.ts +49 -0
- package/dist/replay-live-feed.js +126 -0
- package/dist/rest-binding.d.ts +215 -0
- package/dist/rest-binding.js +95 -0
- package/dist/rest-body.d.ts +17 -0
- package/dist/rest-body.js +95 -0
- package/dist/route-model.d.ts +305 -0
- package/dist/route-model.js +320 -0
- package/dist/runtime/cors.d.ts +161 -0
- package/dist/runtime/cors.js +265 -0
- package/dist/scripts/generate-operation-client.d.ts +186 -0
- package/dist/scripts/generate-operation-client.js +561 -0
- package/dist/scripts/operation-behaviors.d.ts +3 -0
- package/dist/scripts/operation-behaviors.js +16 -0
- package/dist/scripts/operation-client-aliases.d.ts +32 -0
- package/dist/scripts/operation-client-aliases.js +255 -0
- package/dist/scripts/operation-client-domains.d.ts +21 -0
- package/dist/scripts/operation-client-domains.js +74 -0
- package/dist/scripts/operation-client-schema.d.ts +46 -0
- package/dist/scripts/operation-client-schema.js +310 -0
- package/dist/scripts/operation-client-svelte.d.ts +3 -0
- package/dist/scripts/operation-client-svelte.js +61 -0
- package/dist/sequence-cursor.d.ts +46 -0
- package/dist/sequence-cursor.js +62 -0
- package/dist/sse-error-payload-schema.d.ts +12 -0
- package/dist/sse-error-payload-schema.js +33 -0
- package/dist/stdio-session.d.ts +71 -0
- package/dist/stdio-session.js +347 -0
- package/dist/zod-json-schema.d.ts +22 -0
- package/dist/zod-json-schema.js +49 -0
- package/package.json +38 -3
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-platform cryptographic hashing utilities.
|
|
3
|
+
*
|
|
4
|
+
* - `sha256Hex` uses the Web Crypto API and works in all environments (browser, Node, Bun, Deno).
|
|
5
|
+
* - `sha256HexSync` is synchronous and works in Bun and in Node.js 20.16.0+ (20.x line) or 22.3.0+ (throws in browsers
|
|
6
|
+
* and in older Node.js, where `process.getBuiltinModule` does not exist — use the async `sha256Hex`
|
|
7
|
+
* there instead, or supply a `require`-based runtime override; see below).
|
|
8
|
+
* - `hmacSha256HexSync` signs text with HMAC-SHA-256 under the same Bun/Node 20.16.0+ (20.x) or 22.3.0+ requirement.
|
|
9
|
+
* - `timingSafeEqualHex` compares hex digests without leaking the first differing byte (same
|
|
10
|
+
* Bun/Node 20.16.0+ (20.x) or 22.3.0+ requirement as the other synchronous helpers).
|
|
11
|
+
* - `createIncrementalHash` returns a streaming hasher for accumulating data across multiple
|
|
12
|
+
* `.update()` calls (same Bun/Node 20.16.0+ (20.x) or 22.3.0+ requirement).
|
|
13
|
+
*
|
|
14
|
+
* The synchronous helpers read `node:crypto` via `process.getBuiltinModule` rather than a literal
|
|
15
|
+
* `require(...)` call, specifically so that bundling this package for a browser build never injects
|
|
16
|
+
* a `createRequire`/`node:module` shim (see AB-31). That trades away support for Node.js versions
|
|
17
|
+
* outside `^20.16.0 || >=22.3.0` for the synchronous path; a caller that must support older Node can
|
|
18
|
+
* still supply its own loader via the `corvidae.cryptography.hash.runtime` global override
|
|
19
|
+
* (see `getHashRuntimeOverride` below) — set `{ require: (specifier) => require(specifier) }` from
|
|
20
|
+
* a CommonJS entry point where a real `require` exists.
|
|
21
|
+
*/
|
|
22
|
+
const runtimeOverrideSymbol = Symbol.for('corvidae.cryptography.hash.runtime');
|
|
23
|
+
function getHashRuntimeOverride() {
|
|
24
|
+
const value = globalThis[runtimeOverrideSymbol];
|
|
25
|
+
return isHashRuntimeOverride(value) ? value : undefined;
|
|
26
|
+
}
|
|
27
|
+
function isHashRuntimeOverride(value) {
|
|
28
|
+
if (typeof value !== 'object' || value === null)
|
|
29
|
+
return false;
|
|
30
|
+
return (hasOptionalProperty(value, 'require', isOptionalModuleLoader) &&
|
|
31
|
+
hasOptionalProperty(value, 'getBuiltinModule', isOptionalModuleLoader));
|
|
32
|
+
}
|
|
33
|
+
function hasOptionalProperty(value, key, isValid) {
|
|
34
|
+
return !Reflect.has(value, key) || isValid(Reflect.get(value, key));
|
|
35
|
+
}
|
|
36
|
+
function isOptionalModuleLoader(value) {
|
|
37
|
+
return value === undefined || isModuleLoader(value);
|
|
38
|
+
}
|
|
39
|
+
function isModuleLoader(value) {
|
|
40
|
+
return typeof value === 'function';
|
|
41
|
+
}
|
|
42
|
+
function isNodeCrypto(value) {
|
|
43
|
+
if (typeof value !== 'object' || value === null)
|
|
44
|
+
return false;
|
|
45
|
+
return (hasOptionalProperty(value, 'createHash', isOptionalFunction) &&
|
|
46
|
+
hasOptionalProperty(value, 'createHmac', isOptionalFunction) &&
|
|
47
|
+
hasOptionalProperty(value, 'timingSafeEqual', isOptionalFunction));
|
|
48
|
+
}
|
|
49
|
+
function isOptionalFunction(value) {
|
|
50
|
+
return value === undefined || typeof value === 'function';
|
|
51
|
+
}
|
|
52
|
+
function getBuiltinModuleFn() {
|
|
53
|
+
const runtimeOverride = getHashRuntimeOverride();
|
|
54
|
+
if (runtimeOverride && 'getBuiltinModule' in runtimeOverride) {
|
|
55
|
+
return runtimeOverride.getBuiltinModule;
|
|
56
|
+
}
|
|
57
|
+
const runtime = Reflect.get(globalThis, 'process');
|
|
58
|
+
if (typeof runtime !== 'object' || runtime === null || !('getBuiltinModule' in runtime)) {
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
const loader = runtime.getBuiltinModule;
|
|
62
|
+
return isModuleLoader(loader) ? loader.bind(runtime) : undefined;
|
|
63
|
+
}
|
|
64
|
+
function requireNodeCrypto() {
|
|
65
|
+
const runtimeOverride = getHashRuntimeOverride();
|
|
66
|
+
const injectedLoader = runtimeOverride?.require;
|
|
67
|
+
if (injectedLoader) {
|
|
68
|
+
const module = injectedLoader('node:crypto');
|
|
69
|
+
if (isNodeCrypto(module))
|
|
70
|
+
return module;
|
|
71
|
+
throw new Error('node:crypto is not available in this environment.');
|
|
72
|
+
}
|
|
73
|
+
// `process.getBuiltinModule` reads a Node/Bun builtin without a literal `require(...)` call,
|
|
74
|
+
// so ESM bundlers never see a reason to inject a `createRequire` shim for this file — a plain
|
|
75
|
+
// `require('node:crypto')` here would force that shim into every consumer's bundle, browser
|
|
76
|
+
// builds included, even when this function is never reached at runtime.
|
|
77
|
+
const builtinModule = getBuiltinModuleFn()?.('node:crypto');
|
|
78
|
+
if (isNodeCrypto(builtinModule))
|
|
79
|
+
return builtinModule;
|
|
80
|
+
throw new Error('node:crypto is not available in this environment.');
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Computes the SHA-256 hex digest of a string using the Web Crypto API.
|
|
84
|
+
* Works in all environments: browsers, Node.js, Bun, Deno.
|
|
85
|
+
*/
|
|
86
|
+
export async function sha256Hex(text) {
|
|
87
|
+
return sha256BytesHex(new TextEncoder().encode(text));
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Computes the SHA-256 hex digest of raw bytes using the Web Crypto API.
|
|
91
|
+
* Works in all environments: browsers, Node.js, Bun, Deno.
|
|
92
|
+
*
|
|
93
|
+
* Digesting bytes rather than a string is what lets a caller hash content it cannot decode —
|
|
94
|
+
* a bundled image or font, say — without first corrupting it through a lossy text round trip.
|
|
95
|
+
*/
|
|
96
|
+
export async function sha256BytesHex(data) {
|
|
97
|
+
// Passed through without copying: `crypto.subtle.digest` honors an `ArrayBufferView`'s
|
|
98
|
+
// `byteOffset` and `byteLength`, so a `Uint8Array` that is a window into a larger buffer already
|
|
99
|
+
// hashes only its own bytes.
|
|
100
|
+
const view = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
101
|
+
const buffer = await crypto.subtle.digest('SHA-256', view);
|
|
102
|
+
const bytes = new Uint8Array(buffer);
|
|
103
|
+
let hex = '';
|
|
104
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
105
|
+
hex += bytes[i].toString(16).padStart(2, '0');
|
|
106
|
+
}
|
|
107
|
+
return hex;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Computes the SHA-256 hex digest of a string synchronously.
|
|
111
|
+
* Uses `node:crypto`, which Bun and Node.js both provide.
|
|
112
|
+
* Throws in browser environments where no synchronous crypto API is available.
|
|
113
|
+
*/
|
|
114
|
+
export function sha256HexSync(text) {
|
|
115
|
+
try {
|
|
116
|
+
const { createHash } = requireNodeCrypto();
|
|
117
|
+
if (!createHash)
|
|
118
|
+
throw new Error('createHash is unavailable.');
|
|
119
|
+
return createHash('sha256').update(text).digest('hex');
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
throw new Error('sha256HexSync is not available in this environment. Use the async sha256Hex instead, which works everywhere via Web Crypto.');
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/** Computes the SHA-256 hex digest of raw bytes synchronously. */
|
|
126
|
+
export function sha256BytesHexSync(data) {
|
|
127
|
+
try {
|
|
128
|
+
const { createHash } = requireNodeCrypto();
|
|
129
|
+
if (!createHash)
|
|
130
|
+
throw new Error('createHash is unavailable.');
|
|
131
|
+
return createHash('sha256').update(data).digest('hex');
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
throw new Error('sha256BytesHexSync is not available in this environment. Use the async sha256BytesHex instead, which works everywhere via Web Crypto.');
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/** Computes a SHA-256 digest in the base64url representation PKCE requires. */
|
|
138
|
+
export function sha256Base64UrlSync(text) {
|
|
139
|
+
try {
|
|
140
|
+
const { createHash } = requireNodeCrypto();
|
|
141
|
+
if (!createHash)
|
|
142
|
+
throw new Error('createHash is unavailable.');
|
|
143
|
+
return createHash('sha256').update(text).digest('base64url');
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
throw new Error('sha256Base64UrlSync is not available in this environment.');
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Computes an HMAC-SHA-256 hex signature synchronously.
|
|
151
|
+
* Uses `node:crypto`, which Bun and Node.js both provide.
|
|
152
|
+
* Throws in browser environments where no synchronous HMAC API is available.
|
|
153
|
+
*/
|
|
154
|
+
export function hmacSha256HexSync(secret, text) {
|
|
155
|
+
try {
|
|
156
|
+
const { createHmac } = requireNodeCrypto();
|
|
157
|
+
if (!createHmac)
|
|
158
|
+
throw new Error('createHmac is unavailable.');
|
|
159
|
+
return createHmac('sha256', secret).update(text).digest('hex');
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
throw new Error('hmacSha256HexSync is not available in this environment. Use Web Crypto for browser-compatible HMAC signing.');
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Compares two hex strings with Node's timing-safe equality when available.
|
|
167
|
+
* Invalid hex strings and different-length values are never equal.
|
|
168
|
+
*/
|
|
169
|
+
export function timingSafeEqualHex(left, right) {
|
|
170
|
+
if (left.length !== right.length ||
|
|
171
|
+
left.length % 2 !== 0 ||
|
|
172
|
+
!/^[0-9a-f]+$/i.test(left) ||
|
|
173
|
+
!/^[0-9a-f]+$/i.test(right)) {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
const { timingSafeEqual } = requireNodeCrypto();
|
|
178
|
+
if (!timingSafeEqual)
|
|
179
|
+
throw new Error('timingSafeEqual is unavailable.');
|
|
180
|
+
const leftBytes = Uint8Array.from(left.match(/../g) ?? [], (byte) => Number.parseInt(byte, 16));
|
|
181
|
+
const rightBytes = Uint8Array.from(right.match(/../g) ?? [], (byte) => Number.parseInt(byte, 16));
|
|
182
|
+
return timingSafeEqual(leftBytes, rightBytes);
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
throw new Error('timingSafeEqualHex is not available in this environment.');
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/** Compares UTF-8 text with Node's timing-safe equality for equal-size inputs. */
|
|
189
|
+
export function timingSafeEqualText(left, right) {
|
|
190
|
+
const encoder = new TextEncoder();
|
|
191
|
+
const leftBytes = encoder.encode(left);
|
|
192
|
+
const rightBytes = encoder.encode(right);
|
|
193
|
+
if (leftBytes.length !== rightBytes.length)
|
|
194
|
+
return false;
|
|
195
|
+
try {
|
|
196
|
+
const { timingSafeEqual } = requireNodeCrypto();
|
|
197
|
+
if (!timingSafeEqual)
|
|
198
|
+
throw new Error('timingSafeEqual is unavailable.');
|
|
199
|
+
return timingSafeEqual(leftBytes, rightBytes);
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
throw new Error('timingSafeEqualText is not available in this environment.');
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Creates an incremental (streaming) hash for accumulating data across multiple `.update()` calls.
|
|
207
|
+
* Uses `node:crypto`, which Bun and Node.js both provide.
|
|
208
|
+
* Throws in browser environments where no synchronous streaming crypto API is available.
|
|
209
|
+
*
|
|
210
|
+
* @param algorithm - Hash algorithm to use. Default: `'sha256'`.
|
|
211
|
+
*/
|
|
212
|
+
export function createIncrementalHash(algorithm = 'sha256') {
|
|
213
|
+
let createHash;
|
|
214
|
+
try {
|
|
215
|
+
const available = requireNodeCrypto().createHash;
|
|
216
|
+
if (!available)
|
|
217
|
+
throw new Error('createHash is unavailable.');
|
|
218
|
+
createHash = available;
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
throw new Error('createIncrementalHash is not available in this environment. Use the async sha256Hex instead, which works everywhere via Web Crypto.');
|
|
222
|
+
}
|
|
223
|
+
// Outside the `try`, so an unsupported algorithm reports its own error rather than a missing runtime.
|
|
224
|
+
const hash = createHash(algorithm);
|
|
225
|
+
return {
|
|
226
|
+
update(data) {
|
|
227
|
+
hash.update(data);
|
|
228
|
+
},
|
|
229
|
+
digest() {
|
|
230
|
+
return hash.digest('hex');
|
|
231
|
+
},
|
|
232
|
+
};
|
|
233
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { CryptographyError, decrypt, decryptBytes, encrypt, exportEncryptionKey, generateEncryptionKey, importEncryptionKey, } from "./encryption.js";
|
|
2
|
+
export type { CryptographyErrorCode, EncryptedValue, EncryptionKey, ImportEncryptionKeyOptions, Keyring, } from "./encryption.js";
|
|
3
|
+
export { createIncrementalHash, hmacSha256HexSync, sha256Base64UrlSync, sha256BytesHex, sha256BytesHexSync, sha256Hex, sha256HexSync, timingSafeEqualHex, timingSafeEqualText, } from "./hash.js";
|
|
4
|
+
export type { IncrementalHash } from "./hash.js";
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export { CryptographyError, decrypt, decryptBytes, encrypt, exportEncryptionKey, generateEncryptionKey, importEncryptionKey, } from "./encryption.js";
|
|
2
|
+
export { createIncrementalHash, hmacSha256HexSync, sha256Base64UrlSync, sha256BytesHex, sha256BytesHexSync, sha256Hex, sha256HexSync, timingSafeEqualHex, timingSafeEqualText, } from "./hash.js";
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @lostgradient/backchannel/internals
|
|
3
|
+
*
|
|
4
|
+
* The plumbing a host needs to build on the operation layer. Unstable: a name here may change or move
|
|
5
|
+
* without notice, and nothing outside this repository should depend on it.
|
|
6
|
+
*/
|
|
7
|
+
export { buildOperationEntry, buildSseChannel, buildSseMessages, buildWebSocketChannel, buildWebSocketMessages, } from "./asyncapi-channels.js";
|
|
8
|
+
export { generateAsyncApiDocument, type AsyncApiOptions } from "./asyncapi.js";
|
|
9
|
+
export { importJWTKey, signJWT, verifyJWT } from "./authentication/crypto.js";
|
|
10
|
+
export { buildTLSOptions, tlsOptionsVerifyClientCertificates } from "./authentication/index.js";
|
|
11
|
+
export { DEFAULT_PUBLIC_PATHS, normalizeRequestPathname, type AuthContext, } from "./authentication/types.js";
|
|
12
|
+
export { createAdditionalScopeSet, filterRecognizedScopes, type AdditionalScopeSet, } from "./authorization-scope.js";
|
|
13
|
+
export { evaluateAccess, type AccessPolicy } from "./authorization.js";
|
|
14
|
+
export { copyBytesToArrayBuffer } from "./byte-arrays.js";
|
|
15
|
+
export type { ConnectionLease } from "./connection-lease.js";
|
|
16
|
+
export { isDiscoverable } from "./discovery-filter.js";
|
|
17
|
+
export type { EventSelector } from "./event-selector.js";
|
|
18
|
+
export { FAULT_CODE_RETRYABLE, isFaultRetryable } from "./fault-code.js";
|
|
19
|
+
export { MAX_REMEDIATION_LENGTH, assertValidRemediation, faultWireAdvice, remediationProblem, withRemediation, } from "./fault-remediation.js";
|
|
20
|
+
export { faultToHttpResponse } from "./fault-to-http.js";
|
|
21
|
+
export { faultErrorData, faultToJsonRpcError } from "./fault-to-json-rpc.js";
|
|
22
|
+
export { assertFiniteFaultData } from "./fault-wire-safety.js";
|
|
23
|
+
export { authContextFromAuthResult, unauthorizedResponse, } from "./handler/authentication-responses.js";
|
|
24
|
+
export { errorResponse, jsonResponse, negotiatedJsonOrBinary } from "./handler/json-responses.js";
|
|
25
|
+
export { dispatchJsonRpc } from "./json-rpc-dispatch.js";
|
|
26
|
+
export { handleJsonRpcHttpRequest } from "./json-rpc-http.js";
|
|
27
|
+
export { closeJsonRpcWebSocketSession, handleJsonRpcWebSocketMessage, openGenericJsonRpcWebSocketSession, workspaceEmitter, type JsonRpcSocketData, } from "./json-rpc-session-runtime.js";
|
|
28
|
+
export type { JsonRpcWebSocketEmitter, JsonRpcWebSocketSession, } from "./json-rpc-websocket-types.js";
|
|
29
|
+
export { createJsonRpcWebSocketSession } from "./json-rpc-websocket.js";
|
|
30
|
+
export { compareStrings } from "./json-schema-utilities.js";
|
|
31
|
+
export { MCP_TOOLS_LIST_METHOD } from "./mcp-discovery-names.js";
|
|
32
|
+
export { canonicalJson } from "./openapi-canonical-json.js";
|
|
33
|
+
export { buildErrorResponses } from "./openapi-error-responses.js";
|
|
34
|
+
export { emitBindings, generateOpenApiDocument, type OpenApiSecuritySchemeName, } from "./openapi.js";
|
|
35
|
+
export { OpenRpcDocumentSchema } from "./openrpc-document-schema.js";
|
|
36
|
+
export { buildOpenRpcComponentsErrors } from "./openrpc-errors.js";
|
|
37
|
+
export { generateOpenRpcDocument } from "./openrpc.js";
|
|
38
|
+
export { snapshotOperationCatalog } from "./operation-catalog-snapshot.js";
|
|
39
|
+
export { UndeclaredFaultError, classifyEngineError, transportToAvailabilityKey, transportToPolicyKey, } from "./operation-catalog/pipeline-helpers.js";
|
|
40
|
+
export { executeOperation } from "./operation-catalog/pipeline.js";
|
|
41
|
+
export { createOperationRegistry } from "./operation-catalog/registry.js";
|
|
42
|
+
export { SubscriptionElementValidationError, executeStream, } from "./operation-catalog/stream-pipeline.js";
|
|
43
|
+
export type { AuthorizationDecision, DispatchResult, ErasedOperation, OperationRegistry, ParameterizedAccessHint, PipelineTrace, PipelineTraceMarker, RegistrableOperation, } from "./operation-catalog/types.js";
|
|
44
|
+
export { UNIVERSAL_FAULT_DEFAULTS } from "./operation-catalog/universal-faults.js";
|
|
45
|
+
export { invalidParamsFault, isOperationFault } from "./operation-fault-helpers.js";
|
|
46
|
+
export { FAULT_CODE_TO_HTTP_STATUS, FAULT_CODE_TO_JSON_RPC_CODE, shapeOperationFaultAsJson, shapeRestFaultAsJson, type RestFaultResponseOptions, type TransportKind, } from "./operation-fault.js";
|
|
47
|
+
export { isClosableAsyncIterable, isReplayAwareClosableIterable, } from "./operations/closable-iterable.js";
|
|
48
|
+
export { getPrincipalRestBinding } from "./operations/get-principal.js";
|
|
49
|
+
export { DEFAULT_SSE_HEARTBEAT_INTERVAL_MS, SSE_RESPONSE_HEADERS, createEventEnvelopeSSEStream, createStoredChunkSSEStream, formatServerSentEvent, readServerSentEventsCursor, requireServerSentEventsAccept, shapeServerSentEventsFault, } from "./operations/sse-stream.js";
|
|
50
|
+
export { isAuthenticated } from "./principal.js";
|
|
51
|
+
export { ReplayWindowExceededError, createDurableSubscription, createSerialOperationQueue, } from "./replay-live-feed-internals.js";
|
|
52
|
+
export { MalformedRouteParameterError, bindingPathMatches, isRestBindingCompatibleWithOperation, type ParamSource, type ResponseShape, type RestBinding, type RestInputContext, type UnknownRestBinding, } from "./rest-binding.js";
|
|
53
|
+
export { DEFAULT_REST_MAX_BODY_BYTES, readOptionalRestJsonBody, readRestBodyBounded, readRestJsonBody, readRestTextBody, type RestBodyReadOptions, } from "./rest-body.js";
|
|
54
|
+
export { API_PREFIX, DIRECT_HTTP_ROUTES, JSON_RPC_PATH, MCP_STREAMABLE_HTTP_PATH, externalApiPath, overlapsReservedRoute, toOpenApiPath, toRegex, } from "./route-model.js";
|
|
55
|
+
export { buildPreflightResponse, decorateResponseWithCors, isOriginAllowed, isPreflightRequest, resolveCorsPolicy, validateCorsOptions, type ResolvedCorsPolicy, } from "./runtime/cors.js";
|
|
56
|
+
export { compareCursor, parseOptionalSequenceCursor } from "./sequence-cursor.js";
|
|
57
|
+
export { runStdioSession, type StdioAdmission, type StdioSessionResult } from "./stdio-session.js";
|
|
58
|
+
export { requirePlainObject, stripDialect, zodToJsonSchema } from "./zod-json-schema.js";
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @lostgradient/backchannel/internals
|
|
3
|
+
*
|
|
4
|
+
* The plumbing a host needs to build on the operation layer. Unstable: a name here may change or move
|
|
5
|
+
* without notice, and nothing outside this repository should depend on it.
|
|
6
|
+
*/
|
|
7
|
+
export { buildOperationEntry, buildSseChannel, buildSseMessages, buildWebSocketChannel, buildWebSocketMessages, } from "./asyncapi-channels.js";
|
|
8
|
+
export { generateAsyncApiDocument } from "./asyncapi.js";
|
|
9
|
+
export { importJWTKey, signJWT, verifyJWT } from "./authentication/crypto.js";
|
|
10
|
+
export { buildTLSOptions, tlsOptionsVerifyClientCertificates } from "./authentication/index.js";
|
|
11
|
+
export { DEFAULT_PUBLIC_PATHS, normalizeRequestPathname, } from "./authentication/types.js";
|
|
12
|
+
export { createAdditionalScopeSet, filterRecognizedScopes, } from "./authorization-scope.js";
|
|
13
|
+
export { evaluateAccess } from "./authorization.js";
|
|
14
|
+
export { copyBytesToArrayBuffer } from "./byte-arrays.js";
|
|
15
|
+
export { isDiscoverable } from "./discovery-filter.js";
|
|
16
|
+
export { FAULT_CODE_RETRYABLE, isFaultRetryable } from "./fault-code.js";
|
|
17
|
+
export { MAX_REMEDIATION_LENGTH, assertValidRemediation, faultWireAdvice, remediationProblem, withRemediation, } from "./fault-remediation.js";
|
|
18
|
+
export { faultToHttpResponse } from "./fault-to-http.js";
|
|
19
|
+
export { faultErrorData, faultToJsonRpcError } from "./fault-to-json-rpc.js";
|
|
20
|
+
export { assertFiniteFaultData } from "./fault-wire-safety.js";
|
|
21
|
+
export { authContextFromAuthResult, unauthorizedResponse, } from "./handler/authentication-responses.js";
|
|
22
|
+
export { errorResponse, jsonResponse, negotiatedJsonOrBinary } from "./handler/json-responses.js";
|
|
23
|
+
export { dispatchJsonRpc } from "./json-rpc-dispatch.js";
|
|
24
|
+
export { handleJsonRpcHttpRequest } from "./json-rpc-http.js";
|
|
25
|
+
export { closeJsonRpcWebSocketSession, handleJsonRpcWebSocketMessage, openGenericJsonRpcWebSocketSession, workspaceEmitter, } from "./json-rpc-session-runtime.js";
|
|
26
|
+
export { createJsonRpcWebSocketSession } from "./json-rpc-websocket.js";
|
|
27
|
+
export { compareStrings } from "./json-schema-utilities.js";
|
|
28
|
+
export { MCP_TOOLS_LIST_METHOD } from "./mcp-discovery-names.js";
|
|
29
|
+
export { canonicalJson } from "./openapi-canonical-json.js";
|
|
30
|
+
export { buildErrorResponses } from "./openapi-error-responses.js";
|
|
31
|
+
export { emitBindings, generateOpenApiDocument, } from "./openapi.js";
|
|
32
|
+
export { OpenRpcDocumentSchema } from "./openrpc-document-schema.js";
|
|
33
|
+
export { buildOpenRpcComponentsErrors } from "./openrpc-errors.js";
|
|
34
|
+
export { generateOpenRpcDocument } from "./openrpc.js";
|
|
35
|
+
export { snapshotOperationCatalog } from "./operation-catalog-snapshot.js";
|
|
36
|
+
export { UndeclaredFaultError, classifyEngineError, transportToAvailabilityKey, transportToPolicyKey, } from "./operation-catalog/pipeline-helpers.js";
|
|
37
|
+
export { executeOperation } from "./operation-catalog/pipeline.js";
|
|
38
|
+
export { createOperationRegistry } from "./operation-catalog/registry.js";
|
|
39
|
+
export { SubscriptionElementValidationError, executeStream, } from "./operation-catalog/stream-pipeline.js";
|
|
40
|
+
export { UNIVERSAL_FAULT_DEFAULTS } from "./operation-catalog/universal-faults.js";
|
|
41
|
+
export { invalidParamsFault, isOperationFault } from "./operation-fault-helpers.js";
|
|
42
|
+
export { FAULT_CODE_TO_HTTP_STATUS, FAULT_CODE_TO_JSON_RPC_CODE, shapeOperationFaultAsJson, shapeRestFaultAsJson, } from "./operation-fault.js";
|
|
43
|
+
export { isClosableAsyncIterable, isReplayAwareClosableIterable, } from "./operations/closable-iterable.js";
|
|
44
|
+
export { getPrincipalRestBinding } from "./operations/get-principal.js";
|
|
45
|
+
export { DEFAULT_SSE_HEARTBEAT_INTERVAL_MS, SSE_RESPONSE_HEADERS, createEventEnvelopeSSEStream, createStoredChunkSSEStream, formatServerSentEvent, readServerSentEventsCursor, requireServerSentEventsAccept, shapeServerSentEventsFault, } from "./operations/sse-stream.js";
|
|
46
|
+
export { isAuthenticated } from "./principal.js";
|
|
47
|
+
export { ReplayWindowExceededError, createDurableSubscription, createSerialOperationQueue, } from "./replay-live-feed-internals.js";
|
|
48
|
+
export { MalformedRouteParameterError, bindingPathMatches, isRestBindingCompatibleWithOperation, } from "./rest-binding.js";
|
|
49
|
+
export { DEFAULT_REST_MAX_BODY_BYTES, readOptionalRestJsonBody, readRestBodyBounded, readRestJsonBody, readRestTextBody, } from "./rest-body.js";
|
|
50
|
+
export { API_PREFIX, DIRECT_HTTP_ROUTES, JSON_RPC_PATH, MCP_STREAMABLE_HTTP_PATH, externalApiPath, overlapsReservedRoute, toOpenApiPath, toRegex, } from "./route-model.js";
|
|
51
|
+
export { buildPreflightResponse, decorateResponseWithCors, isOriginAllowed, isPreflightRequest, resolveCorsPolicy, validateCorsOptions, } from "./runtime/cors.js";
|
|
52
|
+
export { compareCursor, parseOptionalSequenceCursor } from "./sequence-cursor.js";
|
|
53
|
+
export { runStdioSession } from "./stdio-session.js";
|
|
54
|
+
export { requirePlainObject, stripDialect, zodToJsonSchema } from "./zod-json-schema.js";
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transport-neutral JSON-RPC dispatcher. Every JSON-RPC transport adapter
|
|
3
|
+
* (HTTP POST, WebSocket frame, stdio session) calls `dispatchJsonRpc`
|
|
4
|
+
* with the raw body and a dispatch context; the dispatcher parses the
|
|
5
|
+
* body, resolves each request via `executeOperation`, and produces the
|
|
6
|
+
* wire-level response shape.
|
|
7
|
+
*
|
|
8
|
+
* The stable JSON-RPC operation-catalog contract mandates sequential dispatch
|
|
9
|
+
* in request order. Response order matches request order by construction —
|
|
10
|
+
* notifications are dropped from the response array, so the returned
|
|
11
|
+
* indices are the non-notification request indices.
|
|
12
|
+
*
|
|
13
|
+
* Notifications invoke the operation (for side effects) but produce no
|
|
14
|
+
* response. An all-notification batch returns `kind: 'notification-batch'`
|
|
15
|
+
* so transport adapters can translate it to HTTP 204 / no-response
|
|
16
|
+
* appropriately.
|
|
17
|
+
*/
|
|
18
|
+
import { type JsonRpcResponse } from "./json-rpc-protocol.js";
|
|
19
|
+
import { type OperationRegistry } from "./operation-catalog.js";
|
|
20
|
+
import { type TransportKind } from "./operation-fault.js";
|
|
21
|
+
import { type Principal } from "./principal.js";
|
|
22
|
+
/** The registry, authenticated caller and adapter for one incoming frame. */
|
|
23
|
+
export type DispatchJsonRpcContext = {
|
|
24
|
+
/** The caller admitted by the adapter. */
|
|
25
|
+
readonly principal: Principal;
|
|
26
|
+
/** See `OperationContext.host`. */
|
|
27
|
+
readonly host: unknown;
|
|
28
|
+
/** Which JSON-RPC transport received the frame. */
|
|
29
|
+
readonly transport: Extract<TransportKind, 'jsonRpcHttp' | 'jsonRpcWebSocket' | 'jsonRpcStdio'>;
|
|
30
|
+
/** The operation catalog for the adapter. */
|
|
31
|
+
readonly registry: OperationRegistry;
|
|
32
|
+
/**
|
|
33
|
+
* Accept a subscription started by a single request. The adapter owns the
|
|
34
|
+
* iterable and must close it when delivery ends. Start delivery after writing
|
|
35
|
+
* the returned response so events cannot overtake the acknowledgement.
|
|
36
|
+
*/
|
|
37
|
+
readonly acceptSubscription?: (subscription: JsonRpcSubscription) => void;
|
|
38
|
+
/**
|
|
39
|
+
* The abort signal for a request or subscription, when the transport supplies one. HTTP
|
|
40
|
+
* forwards the `Request` signal, and framed sessions supply a signal for subscriptions.
|
|
41
|
+
* Operations read it as `OperationContext.signal`.
|
|
42
|
+
*/
|
|
43
|
+
readonly signal?: AbortSignal;
|
|
44
|
+
/**
|
|
45
|
+
* Produces the document `rpc.discover` answers with. Omitted, the
|
|
46
|
+
* dispatcher generates a plain OpenRPC document of the registry (HTTP and
|
|
47
|
+
* WebSocket methods, no MCP tools, no server title). Weft's server supplies
|
|
48
|
+
* its own (`createWeftDiscoverDocument`), and a handler that serves a
|
|
49
|
+
* narrower surface supplies the same document it serves at `/openrpc.json`,
|
|
50
|
+
* so the two never disagree.
|
|
51
|
+
*/
|
|
52
|
+
readonly discoverDocument?: () => Record<string, unknown>;
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Result of dispatching a JSON-RPC body. Shapes:
|
|
56
|
+
* - `single`: a single request → one response (success or error).
|
|
57
|
+
* - `notification`: a single notification → no response.
|
|
58
|
+
* - `batch`: a batch with at least one non-notification → an array of
|
|
59
|
+
* responses in request order.
|
|
60
|
+
* - `notification-batch`: a batch where every item is a notification
|
|
61
|
+
* → no response body on the wire (HTTP 204, etc.).
|
|
62
|
+
*/
|
|
63
|
+
export type DispatchJsonRpcResult = {
|
|
64
|
+
readonly kind: 'single';
|
|
65
|
+
readonly response: JsonRpcResponse;
|
|
66
|
+
} | {
|
|
67
|
+
readonly kind: 'notification';
|
|
68
|
+
} | {
|
|
69
|
+
readonly kind: 'batch';
|
|
70
|
+
readonly responses: ReadonlyArray<JsonRpcResponse>;
|
|
71
|
+
} | {
|
|
72
|
+
readonly kind: 'notification-batch';
|
|
73
|
+
};
|
|
74
|
+
/** A validated subscription that an adapter can deliver after acknowledging its start. */
|
|
75
|
+
export type JsonRpcSubscription = {
|
|
76
|
+
/** Lifecycle identifier used by the adapter. */
|
|
77
|
+
readonly subscriptionId: string;
|
|
78
|
+
/** The validated response that acknowledges startup. */
|
|
79
|
+
readonly envelope: unknown;
|
|
80
|
+
/** The validated events in delivery order. */
|
|
81
|
+
readonly iterable: AsyncIterable<unknown>;
|
|
82
|
+
/** Releases the subscription when delivery ends. */
|
|
83
|
+
readonly close: () => Promise<void>;
|
|
84
|
+
/** Signals the end of replay when the operation distinguishes replay and live events. */
|
|
85
|
+
readonly replayComplete?: Promise<void>;
|
|
86
|
+
};
|
|
87
|
+
/** Parse the raw body and dispatch each request. */
|
|
88
|
+
export declare function dispatchJsonRpc(body: unknown, context: DispatchJsonRpcContext): Promise<DispatchJsonRpcResult>;
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transport-neutral JSON-RPC dispatcher. Every JSON-RPC transport adapter
|
|
3
|
+
* (HTTP POST, WebSocket frame, stdio session) calls `dispatchJsonRpc`
|
|
4
|
+
* with the raw body and a dispatch context; the dispatcher parses the
|
|
5
|
+
* body, resolves each request via `executeOperation`, and produces the
|
|
6
|
+
* wire-level response shape.
|
|
7
|
+
*
|
|
8
|
+
* The stable JSON-RPC operation-catalog contract mandates sequential dispatch
|
|
9
|
+
* in request order. Response order matches request order by construction —
|
|
10
|
+
* notifications are dropped from the response array, so the returned
|
|
11
|
+
* indices are the non-notification request indices.
|
|
12
|
+
*
|
|
13
|
+
* Notifications invoke the operation (for side effects) but produce no
|
|
14
|
+
* response. An all-notification batch returns `kind: 'notification-batch'`
|
|
15
|
+
* so transport adapters can translate it to HTTP 204 / no-response
|
|
16
|
+
* appropriately.
|
|
17
|
+
*/
|
|
18
|
+
import { faultToJsonRpcError } from "./fault-to-json-rpc.js";
|
|
19
|
+
import { parseJsonRpcRequest } from "./json-rpc-parse.js";
|
|
20
|
+
import { JSON_RPC_VERSION, } from "./json-rpc-protocol.js";
|
|
21
|
+
import { generateOpenRpcDocument } from "./openrpc.js";
|
|
22
|
+
import { executeOperation, executeSubscription, } from "./operation-catalog.js";
|
|
23
|
+
import {} from "./operation-fault.js";
|
|
24
|
+
import {} from "./principal.js";
|
|
25
|
+
const DISCOVER_METHOD_NAME = 'rpc.discover';
|
|
26
|
+
/** Parse the raw body and dispatch each request. */
|
|
27
|
+
export async function dispatchJsonRpc(body, context) {
|
|
28
|
+
const parsed = parseJsonRpcRequest(body);
|
|
29
|
+
if (parsed.kind === 'parse-error') {
|
|
30
|
+
return {
|
|
31
|
+
kind: 'single',
|
|
32
|
+
response: {
|
|
33
|
+
jsonrpc: JSON_RPC_VERSION,
|
|
34
|
+
error: { code: parsed.code, message: parsed.message },
|
|
35
|
+
id: null,
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
if (parsed.kind === 'invalid-request') {
|
|
40
|
+
return {
|
|
41
|
+
kind: 'single',
|
|
42
|
+
response: {
|
|
43
|
+
jsonrpc: JSON_RPC_VERSION,
|
|
44
|
+
error: { code: parsed.code, message: parsed.message },
|
|
45
|
+
id: parsed.id,
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
if (parsed.kind === 'single') {
|
|
50
|
+
if (parsed.isNotification) {
|
|
51
|
+
// JSON-RPC 2.0 — id-less requests are notifications. The operation
|
|
52
|
+
// pipeline (auth, validation, invoke) still runs identically; the
|
|
53
|
+
// response is intentionally dropped per spec because the caller
|
|
54
|
+
// chose fire-and-forget. The criterion's "Notifications are opt-in
|
|
55
|
+
// per method" is a contract guarantee at the operation level: the
|
|
56
|
+
// operation runs the same code path regardless of id presence, so
|
|
57
|
+
// a caller who omits id by mistake still triggers auth/validation
|
|
58
|
+
// failures server-side (logged) — they just won't see a wire
|
|
59
|
+
// response. Mutating ops "default to request-response" because
|
|
60
|
+
// every caller-friendly client library includes id by default;
|
|
61
|
+
// notifications are an explicit caller opt-in by omitting it.
|
|
62
|
+
await dispatchSingle(parsed.request, context);
|
|
63
|
+
return { kind: 'notification' };
|
|
64
|
+
}
|
|
65
|
+
const response = await dispatchSingle(parsed.request, context);
|
|
66
|
+
return { kind: 'single', response };
|
|
67
|
+
}
|
|
68
|
+
return dispatchBatch(parsed, context);
|
|
69
|
+
}
|
|
70
|
+
async function dispatchBatch(parsed, context) {
|
|
71
|
+
// Batch size cap enforcement lives in `parseJsonRpcRequest` — the
|
|
72
|
+
// parser rejects batches over `MAX_JSON_RPC_BATCH_ITEMS` (100) with
|
|
73
|
+
// an `invalid-request` result BEFORE dispatch. Any batch that reaches
|
|
74
|
+
// this function is already within the cap.
|
|
75
|
+
const responses = [];
|
|
76
|
+
// Sequential dispatch in request order — stable operation-catalog contract.
|
|
77
|
+
for (const item of parsed.items) {
|
|
78
|
+
const response = await dispatchBatchItem(item, context);
|
|
79
|
+
if (response !== undefined)
|
|
80
|
+
responses.push(response);
|
|
81
|
+
}
|
|
82
|
+
if (responses.length === 0) {
|
|
83
|
+
return { kind: 'notification-batch' };
|
|
84
|
+
}
|
|
85
|
+
return { kind: 'batch', responses };
|
|
86
|
+
}
|
|
87
|
+
async function dispatchBatchItem(item, context) {
|
|
88
|
+
if (item.kind === 'invalid') {
|
|
89
|
+
return {
|
|
90
|
+
jsonrpc: JSON_RPC_VERSION,
|
|
91
|
+
error: { code: item.code, message: item.message },
|
|
92
|
+
id: item.id,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
if (item.isNotification) {
|
|
96
|
+
// JSON-RPC 2.0 — same contract as single notifications: pipeline
|
|
97
|
+
// runs, response dropped per spec.
|
|
98
|
+
await dispatchOne(item.request, context);
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
return dispatchOne(item.request, context);
|
|
102
|
+
}
|
|
103
|
+
async function dispatchOne(request, context) {
|
|
104
|
+
const id = request.id ?? null;
|
|
105
|
+
if (request.method === DISCOVER_METHOD_NAME) {
|
|
106
|
+
const document = context.discoverDocument?.() ??
|
|
107
|
+
generateOpenRpcDocument({
|
|
108
|
+
registry: context.registry,
|
|
109
|
+
transports: ['http', 'websocket'],
|
|
110
|
+
});
|
|
111
|
+
return { jsonrpc: JSON_RPC_VERSION, result: document, id };
|
|
112
|
+
}
|
|
113
|
+
const dispatch = {
|
|
114
|
+
principal: context.principal,
|
|
115
|
+
host: context.host,
|
|
116
|
+
transport: context.transport,
|
|
117
|
+
registry: context.registry,
|
|
118
|
+
...(context.signal === undefined ? {} : { signal: context.signal }),
|
|
119
|
+
};
|
|
120
|
+
const result = await executeOperation(request.method, request.params ?? {}, dispatch);
|
|
121
|
+
if (result.ok) {
|
|
122
|
+
return { jsonrpc: JSON_RPC_VERSION, result: result.value, id };
|
|
123
|
+
}
|
|
124
|
+
return faultResponse(result.fault, id);
|
|
125
|
+
}
|
|
126
|
+
function dispatchSingle(request, context) {
|
|
127
|
+
if (context.acceptSubscription !== undefined &&
|
|
128
|
+
context.registry.get(request.method)?.kind === 'subscription') {
|
|
129
|
+
return dispatchSubscriptionRequest(request, context, context.acceptSubscription);
|
|
130
|
+
}
|
|
131
|
+
return dispatchOne(request, context);
|
|
132
|
+
}
|
|
133
|
+
async function dispatchSubscriptionRequest(request, context, accept) {
|
|
134
|
+
const id = request.id ?? null;
|
|
135
|
+
const started = await executeSubscription(request.method, request.params ?? {}, context);
|
|
136
|
+
if (!started.ok)
|
|
137
|
+
return faultResponse(started.fault, id);
|
|
138
|
+
try {
|
|
139
|
+
accept(started.value);
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
await started.value.close().catch(() => { });
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
return { jsonrpc: JSON_RPC_VERSION, result: started.value.envelope, id };
|
|
146
|
+
}
|
|
147
|
+
function faultResponse(fault, id) {
|
|
148
|
+
const error = faultToJsonRpcError(fault);
|
|
149
|
+
return {
|
|
150
|
+
jsonrpc: JSON_RPC_VERSION,
|
|
151
|
+
error: { code: error.code, message: error.message, data: error.data },
|
|
152
|
+
id,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared newline-delimited framing helper for JSON-RPC over stdio.
|
|
3
|
+
*
|
|
4
|
+
* The runtime stdio subcommand consumes this helper to turn newline-delimited
|
|
5
|
+
* byte chunks into complete JSON-RPC frames. Phase 6 locked in the framing
|
|
6
|
+
* contract against the original inline buffer logic; Phase 7 extracted that
|
|
7
|
+
* logic into this pure function.
|
|
8
|
+
*
|
|
9
|
+
* Contract:
|
|
10
|
+
* - Input: `buffer` (leftover from the previous call) + `chunk` (new
|
|
11
|
+
* bytes decoded to string).
|
|
12
|
+
* - Output: an array of `lines` (complete, newline-terminated, trimmed,
|
|
13
|
+
* non-empty) plus a `buffer` to feed into the next call.
|
|
14
|
+
* - Split: on `\n`. `\r` is treated as surrounding whitespace and
|
|
15
|
+
* trimmed — standard `trim()` behavior. CRLF framing works
|
|
16
|
+
* transparently.
|
|
17
|
+
* - Blanks: lines that are empty after `trim()` are silently dropped.
|
|
18
|
+
* They are framing artifacts, not empty payloads — if every
|
|
19
|
+
* caller had to filter them, eventually one would forget and
|
|
20
|
+
* log a malformed-JSON warning on a legitimately blank frame.
|
|
21
|
+
*
|
|
22
|
+
* Pure: no I/O, no allocations beyond the returned arrays/string, no
|
|
23
|
+
* state. Safe to call from any context.
|
|
24
|
+
*
|
|
25
|
+
* **No built-in buffer bound.** A peer that never emits a newline can
|
|
26
|
+
* force the returned `buffer` to grow unboundedly across calls. The
|
|
27
|
+
* helper is deliberately primitive here — callers that cannot trust
|
|
28
|
+
* the peer (the Phase 13 runtime stdio session; any future network-
|
|
29
|
+
* facing consumer) MUST enforce their own max-frame cap and drop /
|
|
30
|
+
* fault the connection when the buffer exceeds it.
|
|
31
|
+
*/
|
|
32
|
+
export type FramingResult = {
|
|
33
|
+
readonly lines: ReadonlyArray<string>;
|
|
34
|
+
readonly buffer: string;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Append `chunk` to `buffer`, split off every complete newline-terminated
|
|
38
|
+
* frame, and return the extracted lines plus the leftover buffer.
|
|
39
|
+
*
|
|
40
|
+
* Lines are trimmed; empty lines (after trim) are dropped silently.
|
|
41
|
+
*/
|
|
42
|
+
export declare function splitNewlineDelimitedBuffer(buffer: string, chunk: string): FramingResult;
|