@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,235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transport-neutral fault model for the operation pipeline.
|
|
3
|
+
*
|
|
4
|
+
* `OperationFault` is what `executeOperation` returns when a request fails.
|
|
5
|
+
* It carries a stable `code` (the discriminator), a human-readable `message`
|
|
6
|
+
* for logs, and a typed `data` payload narrowed per-code via discriminated
|
|
7
|
+
* union — so transport adapters can serialize the fault into the exact
|
|
8
|
+
* wire shape their protocol expects without a string-sniffing layer.
|
|
9
|
+
*
|
|
10
|
+
* Two pure mapper functions translate the fault into a transport-specific
|
|
11
|
+
* shape:
|
|
12
|
+
* - `faultToHttpResponse(fault)` for REST.
|
|
13
|
+
* - `faultToJsonRpcError(fault)` for the JSON-RPC transports.
|
|
14
|
+
* Both consume `OperationFault` directly; serialization is not a method on
|
|
15
|
+
* the fault class because that would force every transport to know about
|
|
16
|
+
* every other transport's wire shape.
|
|
17
|
+
*
|
|
18
|
+
* **Scope.** The union covers operation-pipeline faults — what
|
|
19
|
+
* `executeOperation` produces. Pure protocol-frame errors (JSON parse
|
|
20
|
+
* failure, invalid JSON-RPC request envelope) live in the JSON-RPC parser
|
|
21
|
+
* and use the spec-mandated reserved codes (-32700 / -32600); they do NOT
|
|
22
|
+
* pass through this fault model. The v1 union is open for additive
|
|
23
|
+
* extension — future codes (e.g. `PreconditionFailed`, `PayloadTooLarge`,
|
|
24
|
+
* `ResourceExhausted`) can be added without breaking existing serializers
|
|
25
|
+
* because the per-code mapping tables are exhaustive `Record<FaultCode, T>`
|
|
26
|
+
* and the JSON-RPC payload extractor is an exhaustive switch.
|
|
27
|
+
*
|
|
28
|
+
* **Every fault has a `data` field.** Even codes with no payload-specific
|
|
29
|
+
* detail (`NotImplemented`, `EngineFailure`) carry `data: {}` so transport
|
|
30
|
+
* adapters never branch on `data === undefined`. This uniformity is what
|
|
31
|
+
* lets the exhaustive switch in `extractFaultDataPayload` stay small.
|
|
32
|
+
*
|
|
33
|
+
* The stable fault model with transport-neutral code, message, and typed
|
|
34
|
+
* `data` payload forms the basis of cross-transport parity: every fault is
|
|
35
|
+
* serialized consistently across REST and JSON-RPC transports.
|
|
36
|
+
*/
|
|
37
|
+
import {} from "./fault-code.js";
|
|
38
|
+
import { faultWireAdvice } from "./fault-remediation.js";
|
|
39
|
+
import { usableRetryAfterSeconds, wireSafeFault } from "./fault-wire-safety.js";
|
|
40
|
+
/**
|
|
41
|
+
* HTTP status code for each fault, used by `faultToHttpResponse`. Values
|
|
42
|
+
* align with REST conventions; both `NotImplemented` and
|
|
43
|
+
* `UnsupportedTransport` map to 501 because the caller asked for something
|
|
44
|
+
* the server cannot fulfill.
|
|
45
|
+
*/
|
|
46
|
+
export const FAULT_CODE_TO_HTTP_STATUS = Object.freeze({
|
|
47
|
+
Unauthorized: 401,
|
|
48
|
+
Forbidden: 403,
|
|
49
|
+
NotFound: 404,
|
|
50
|
+
Conflict: 409,
|
|
51
|
+
Unprocessable: 422,
|
|
52
|
+
// 504, not `Request Timeout`: a user agent may repeat a request answered `Request Timeout` (RFC 9110
|
|
53
|
+
// §15.5.9), and browsers do, so a timed-out `POST` would run again. No user agent replays a `504`.
|
|
54
|
+
Timeout: 504,
|
|
55
|
+
PayloadTooLarge: 413,
|
|
56
|
+
NotImplemented: 501,
|
|
57
|
+
UnsupportedTransport: 501,
|
|
58
|
+
SubscriptionOverflow: 500,
|
|
59
|
+
InvalidParams: 400,
|
|
60
|
+
MethodNotFound: 404,
|
|
61
|
+
StaleRevision: 409,
|
|
62
|
+
RateLimited: 429,
|
|
63
|
+
Unavailable: 503,
|
|
64
|
+
UnsupportedCapability: 501,
|
|
65
|
+
EngineFailure: 500,
|
|
66
|
+
});
|
|
67
|
+
/**
|
|
68
|
+
* Format an `InvalidParams` fault as a single human-readable error string
|
|
69
|
+
* suitable for the body of a JSON response. Joins each Zod issue as
|
|
70
|
+
* `path: message` (or just `message` at the root) with `; ` separators.
|
|
71
|
+
*/
|
|
72
|
+
export function formatInvalidParamsMessage(fault) {
|
|
73
|
+
return fault.data.issues
|
|
74
|
+
.map((issue) => {
|
|
75
|
+
const path = issue.path.join('.');
|
|
76
|
+
return path.length > 0 ? `${path}: ${issue.message}` : issue.message;
|
|
77
|
+
})
|
|
78
|
+
.join('; ');
|
|
79
|
+
}
|
|
80
|
+
const NO_REST_FAULT_DATA = Object.freeze({});
|
|
81
|
+
/**
|
|
82
|
+
* REST is a deliberately smaller disclosure boundary than JSON-RPC. This
|
|
83
|
+
* exhaustive table is deny-by-default: adding a new `FaultCode` cannot compile
|
|
84
|
+
* until its REST-visible fields are reviewed explicitly.
|
|
85
|
+
*/
|
|
86
|
+
const REST_FAULT_DATA_EXTRACTORS = {
|
|
87
|
+
Unauthorized: () => NO_REST_FAULT_DATA,
|
|
88
|
+
Forbidden: () => NO_REST_FAULT_DATA,
|
|
89
|
+
NotFound: (data) => filterDefined({
|
|
90
|
+
resource: data.resource,
|
|
91
|
+
identifier: data.identifier === undefined || data.identifier.length === 0 ? undefined : data.identifier,
|
|
92
|
+
}),
|
|
93
|
+
Conflict: (data) => filterDefined({
|
|
94
|
+
reason: data.publicReason,
|
|
95
|
+
missingTypes: data.missingTypes === undefined ? undefined : [...data.missingTypes],
|
|
96
|
+
missingWorkflowCount: data.missingWorkflowCount,
|
|
97
|
+
samplesTruncated: data.samplesTruncated,
|
|
98
|
+
currentGeneration: data.currentGeneration,
|
|
99
|
+
compatibilityReasons: data.compatibilityReasons === undefined ? undefined : [...data.compatibilityReasons],
|
|
100
|
+
sourceValidationReasons: data.sourceValidationReasons === undefined ? undefined : [...data.sourceValidationReasons],
|
|
101
|
+
}),
|
|
102
|
+
Unprocessable: () => NO_REST_FAULT_DATA,
|
|
103
|
+
PayloadTooLarge: (data) => ({ maxBytes: data.maxBytes }),
|
|
104
|
+
Timeout: (data) => filterDefined({ operationName: data.operationName, updateId: data.updateId }),
|
|
105
|
+
NotImplemented: () => NO_REST_FAULT_DATA,
|
|
106
|
+
UnsupportedTransport: (data) => ({
|
|
107
|
+
transport: data.transport,
|
|
108
|
+
supported: [...data.supported],
|
|
109
|
+
}),
|
|
110
|
+
SubscriptionOverflow: (data) => ({ droppedCount: data.droppedCount }),
|
|
111
|
+
InvalidParams: (data) => data.issues.length === 0
|
|
112
|
+
? NO_REST_FAULT_DATA
|
|
113
|
+
: {
|
|
114
|
+
issues: data.issues.map((issue) => ({
|
|
115
|
+
path: [...issue.path],
|
|
116
|
+
message: issue.message,
|
|
117
|
+
code: issue.code,
|
|
118
|
+
})),
|
|
119
|
+
},
|
|
120
|
+
MethodNotFound: (data) => ({ method: data.method }),
|
|
121
|
+
// Typed data lets a REST client tell "re-read and retry" (`StaleRevision`)
|
|
122
|
+
// from a plain `Conflict`, and learn when to retry. `Unavailable.reason` is
|
|
123
|
+
// internal detail and stays JSON-RPC only.
|
|
124
|
+
StaleRevision: (data) => ({
|
|
125
|
+
currentRevision: data.currentRevision,
|
|
126
|
+
...(data.expectedRevision === undefined ? {} : { expectedRevision: data.expectedRevision }),
|
|
127
|
+
}),
|
|
128
|
+
RateLimited: (data) => filterDefined({ retryAfterSeconds: usableRetryAfterSeconds(data.retryAfterSeconds) }),
|
|
129
|
+
Unavailable: (data) => filterDefined({ retryAfterSeconds: usableRetryAfterSeconds(data.retryAfterSeconds) }),
|
|
130
|
+
UnsupportedCapability: (data) => ({ capability: data.capability }),
|
|
131
|
+
};
|
|
132
|
+
/**
|
|
133
|
+
* Map an `OperationFault` to the canonical additive REST body:
|
|
134
|
+
* `{ error, weftCode?, data?, retryable, remediation? }`. The existing string `error` and optional
|
|
135
|
+
* fine-grained `weftCode` (the host's error code, never a {@link FaultCode})
|
|
136
|
+
* remain unchanged; `data` contains only fields from the audited allowlist
|
|
137
|
+
* above. JSON-RPC uses its own broader projection, whose `data.weftCode` is the
|
|
138
|
+
* coarse `FaultCode`.
|
|
139
|
+
*
|
|
140
|
+
* `EngineFailure` is a hard exception: its exact body remains
|
|
141
|
+
* `{ "error": "Internal server error", "retryable": false }`, regardless of response overrides.
|
|
142
|
+
*/
|
|
143
|
+
export function shapeOperationFaultAsJson(fault, options = {}) {
|
|
144
|
+
const message = options.message ??
|
|
145
|
+
(fault.code === 'InvalidParams' ? formatInvalidParamsMessage(fault) : undefined);
|
|
146
|
+
return shapeRestFaultAsJson(fault, { ...options, ...(message === undefined ? {} : { message }) });
|
|
147
|
+
}
|
|
148
|
+
/** Canonical REST response used by bindings and route-dispatch fallback. */
|
|
149
|
+
export function shapeRestFaultAsJson(fault, options = {}) {
|
|
150
|
+
const safeFault = wireSafeFault(fault);
|
|
151
|
+
const body = shapeRestFaultBody(safeFault, options);
|
|
152
|
+
const status = safeFault.code === 'EngineFailure'
|
|
153
|
+
? 500
|
|
154
|
+
: (options.status ?? FAULT_CODE_TO_HTTP_STATUS[safeFault.code]);
|
|
155
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
156
|
+
const retryAfter = retryAfterHeaderValue(safeFault);
|
|
157
|
+
if (retryAfter !== undefined)
|
|
158
|
+
headers['Retry-After'] = retryAfter;
|
|
159
|
+
return new Response(JSON.stringify(body), { status, headers });
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* The `Retry-After` delay-seconds value for a fault that carries
|
|
163
|
+
* `retryAfterSeconds`. A non-finite or negative value is dropped rather than
|
|
164
|
+
* emitted as a malformed header, and a fraction rounds up so a client never
|
|
165
|
+
* retries earlier than the server asked.
|
|
166
|
+
*/
|
|
167
|
+
function retryAfterHeaderValue(fault) {
|
|
168
|
+
if (fault.code !== 'RateLimited' && fault.code !== 'Unavailable')
|
|
169
|
+
return undefined;
|
|
170
|
+
const seconds = usableRetryAfterSeconds(fault.data.retryAfterSeconds);
|
|
171
|
+
return seconds === undefined ? undefined : String(Math.ceil(seconds));
|
|
172
|
+
}
|
|
173
|
+
/** Build the audited canonical REST body. */
|
|
174
|
+
function shapeRestFaultBody(fault, options) {
|
|
175
|
+
const { retryable, remediation } = faultWireAdvice(fault);
|
|
176
|
+
if (fault.code === 'EngineFailure')
|
|
177
|
+
return { error: 'Internal server error', retryable };
|
|
178
|
+
const error = options.message ?? fault.message;
|
|
179
|
+
const weftCode = weftCodeFromFaultData(fault.data, options.isKnownErrorCode);
|
|
180
|
+
const data = restDataFromFault(fault);
|
|
181
|
+
return {
|
|
182
|
+
error,
|
|
183
|
+
...(weftCode === undefined ? {} : { weftCode }),
|
|
184
|
+
...(Object.keys(data).length > 0 ? { data } : {}),
|
|
185
|
+
retryable,
|
|
186
|
+
...(remediation === undefined ? {} : { remediation }),
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
function restDataFromFault(fault) {
|
|
190
|
+
// The table maps every discriminant to the matching data extractor. TypeScript
|
|
191
|
+
// cannot preserve that correlation through a dynamic lookup, so this narrow
|
|
192
|
+
// assertion reconnects the already-exhaustive key/value relationship.
|
|
193
|
+
const extractor = REST_FAULT_DATA_EXTRACTORS[fault.code];
|
|
194
|
+
return extractor(fault.data);
|
|
195
|
+
}
|
|
196
|
+
function weftCodeFromFaultData(data, isKnownErrorCode) {
|
|
197
|
+
const weftCode = typeof data === 'object' && data !== null
|
|
198
|
+
? data.weftCode
|
|
199
|
+
: undefined;
|
|
200
|
+
if (typeof weftCode !== 'string')
|
|
201
|
+
return undefined;
|
|
202
|
+
return isKnownErrorCode === undefined || isKnownErrorCode(weftCode) ? weftCode : undefined;
|
|
203
|
+
}
|
|
204
|
+
function filterDefined(input) {
|
|
205
|
+
const output = {};
|
|
206
|
+
for (const [key, value] of Object.entries(input)) {
|
|
207
|
+
if (value !== undefined)
|
|
208
|
+
output[key] = value;
|
|
209
|
+
}
|
|
210
|
+
return output;
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* JSON-RPC error code for each fault. Reserved codes (-32700..-32603) keep
|
|
214
|
+
* the spec meanings (`InvalidParams`, `MethodNotFound`); Weft domain codes
|
|
215
|
+
* live in -32010..-32099 documented per design decision 4.
|
|
216
|
+
*/
|
|
217
|
+
export const FAULT_CODE_TO_JSON_RPC_CODE = Object.freeze({
|
|
218
|
+
Unauthorized: -32010,
|
|
219
|
+
Forbidden: -32011,
|
|
220
|
+
NotFound: -32020,
|
|
221
|
+
Conflict: -32021,
|
|
222
|
+
Unprocessable: -32022,
|
|
223
|
+
Timeout: -32023,
|
|
224
|
+
PayloadTooLarge: -32024,
|
|
225
|
+
NotImplemented: -32025,
|
|
226
|
+
UnsupportedTransport: -32030,
|
|
227
|
+
SubscriptionOverflow: -32031,
|
|
228
|
+
EngineFailure: -32099,
|
|
229
|
+
InvalidParams: -32602,
|
|
230
|
+
MethodNotFound: -32601,
|
|
231
|
+
StaleRevision: -32026,
|
|
232
|
+
RateLimited: -32027,
|
|
233
|
+
Unavailable: -32028,
|
|
234
|
+
UnsupportedCapability: -32029,
|
|
235
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { z } from 'zod';
|
|
2
|
+
import { type AuthorizationDecision, type DispatchContext, type DispatchResult, type OperationContext, type OperationDefinitionBase, type StreamOperationInvocation, type SubscriptionOperationInvocation } from "./operation-catalog/types.js";
|
|
3
|
+
export { isValidOperationName, validateOperationName } from "./operation-catalog/types.js";
|
|
4
|
+
type SchemaOperationInputBase<InputSchema extends z.ZodObject, OutputSchema extends z.ZodType, Host> = Omit<OperationDefinitionBase<z.output<InputSchema>, z.input<OutputSchema>, z.output<OutputSchema>, Host>, 'tags' | 'inputSchema' | 'outputSchema' | 'authorize'> & {
|
|
5
|
+
readonly inputSchema: InputSchema;
|
|
6
|
+
readonly outputSchema: OutputSchema;
|
|
7
|
+
readonly tags?: ReadonlyArray<string>;
|
|
8
|
+
readonly authorize?: (context: OperationContext<NoInfer<z.output<InputSchema>>, Host>) => Promise<AuthorizationDecision>;
|
|
9
|
+
};
|
|
10
|
+
type UnaryOperationInput<InputSchema extends z.ZodObject, OutputSchema extends z.ZodType, Host = unknown> = SchemaOperationInputBase<InputSchema, OutputSchema, Host> & {
|
|
11
|
+
readonly kind?: 'unary';
|
|
12
|
+
readonly eventSchema?: never;
|
|
13
|
+
readonly invoke: (context: OperationContext<NoInfer<z.output<InputSchema>>, Host>) => Promise<NoInfer<z.input<OutputSchema>>>;
|
|
14
|
+
};
|
|
15
|
+
type StreamOperationInput<InputSchema extends z.ZodObject, OutputSchema extends z.ZodType, EventSchema extends z.ZodType, Host = unknown> = SchemaOperationInputBase<InputSchema, OutputSchema, Host> & {
|
|
16
|
+
readonly kind: 'stream';
|
|
17
|
+
readonly eventSchema: EventSchema;
|
|
18
|
+
readonly invoke: (context: OperationContext<NoInfer<z.output<InputSchema>>, Host>) => Promise<NoInfer<z.input<OutputSchema>> | StreamOperationInvocation<NoInfer<z.input<EventSchema>>>>;
|
|
19
|
+
};
|
|
20
|
+
type SubscriptionOperationInput<InputSchema extends z.ZodObject, OutputSchema extends z.ZodType, EventSchema extends z.ZodType, Host = unknown> = SchemaOperationInputBase<InputSchema, OutputSchema, Host> & {
|
|
21
|
+
readonly kind: 'subscription';
|
|
22
|
+
readonly eventSchema: EventSchema;
|
|
23
|
+
readonly invoke: (context: OperationContext<NoInfer<z.output<InputSchema>>, Host>) => Promise<SubscriptionOperationInvocation<NoInfer<z.input<EventSchema>>, NoInfer<z.input<OutputSchema>>>>;
|
|
24
|
+
};
|
|
25
|
+
/** What {@link defineOperation} accepts: the unary, stream or subscription authoring shape, selected by `kind`. */
|
|
26
|
+
export type OperationDefinitionInput<InputSchema extends z.ZodObject, OutputSchema extends z.ZodType, EventSchema extends z.ZodType = never, Host = unknown> = UnaryOperationInput<InputSchema, OutputSchema, Host> | StreamOperationInput<InputSchema, OutputSchema, EventSchema, Host> | SubscriptionOperationInput<InputSchema, OutputSchema, EventSchema, Host>;
|
|
27
|
+
type DispatchEntry<Host> = {
|
|
28
|
+
readonly tags: ReadonlyArray<string>;
|
|
29
|
+
readonly dispatch: (rawInput: unknown, context: DispatchContext<Host>) => Promise<DispatchResult<unknown>>;
|
|
30
|
+
/** Validate input and authorize this operation without running its callback. */
|
|
31
|
+
readonly checkPolicy: (rawInput: unknown, context: DispatchContext<Host>) => Promise<DispatchResult<void>>;
|
|
32
|
+
};
|
|
33
|
+
/** The result of {@link defineOperation} for a `kind: 'unary'` operation. */
|
|
34
|
+
export type UnarySchemaOperationDefinition<InputSchema extends z.ZodObject, OutputSchema extends z.ZodType, Host = unknown> = UnaryOperationInput<InputSchema, OutputSchema, Host> & DispatchEntry<Host>;
|
|
35
|
+
/** The result of {@link defineOperation} for a `kind: 'stream'` operation. */
|
|
36
|
+
export type StreamSchemaOperationDefinition<InputSchema extends z.ZodObject, OutputSchema extends z.ZodType, EventSchema extends z.ZodType, Host = unknown> = StreamOperationInput<InputSchema, OutputSchema, EventSchema, Host> & DispatchEntry<Host>;
|
|
37
|
+
/** The result of {@link defineOperation} for a `kind: 'subscription'` operation. */
|
|
38
|
+
export type SubscriptionSchemaOperationDefinition<InputSchema extends z.ZodObject, OutputSchema extends z.ZodType, EventSchema extends z.ZodType, Host = unknown> = SubscriptionOperationInput<InputSchema, OutputSchema, EventSchema, Host> & DispatchEntry<Host>;
|
|
39
|
+
/** The result of {@link defineOperation}: an operation of any kind, carrying its frozen metadata and its dispatch entry. */
|
|
40
|
+
export type SchemaOperationDefinition<InputSchema extends z.ZodObject, OutputSchema extends z.ZodType, EventSchema extends z.ZodType = never, Host = unknown> = UnarySchemaOperationDefinition<InputSchema, OutputSchema, Host> | StreamSchemaOperationDefinition<InputSchema, OutputSchema, EventSchema, Host> | SubscriptionSchemaOperationDefinition<InputSchema, OutputSchema, EventSchema, Host>;
|
|
41
|
+
/** Derive authoring contracts from schemas and capture one immutable dispatch policy. */
|
|
42
|
+
export declare function defineOperation<InputSchema extends z.ZodObject, OutputSchema extends z.ZodType, Host = unknown>(input: UnaryOperationInput<InputSchema, OutputSchema, Host>): UnarySchemaOperationDefinition<InputSchema, OutputSchema, Host>;
|
|
43
|
+
/** Defines a stream operation. */
|
|
44
|
+
export declare function defineOperation<InputSchema extends z.ZodObject, OutputSchema extends z.ZodType, EventSchema extends z.ZodType, Host = unknown>(input: StreamOperationInput<InputSchema, OutputSchema, EventSchema, Host>): StreamSchemaOperationDefinition<InputSchema, OutputSchema, EventSchema, Host>;
|
|
45
|
+
/** Defines a subscription operation. */
|
|
46
|
+
export declare function defineOperation<InputSchema extends z.ZodObject, OutputSchema extends z.ZodType, EventSchema extends z.ZodType, Host = unknown>(input: SubscriptionOperationInput<InputSchema, OutputSchema, EventSchema, Host>): SubscriptionSchemaOperationDefinition<InputSchema, OutputSchema, EventSchema, Host>;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { checkOperationPolicy, dispatchOperation } from "./operation-catalog/operation-dispatch.js";
|
|
2
|
+
import { snapshotOperationMetadata } from "./operation-catalog/operation-metadata.js";
|
|
3
|
+
import { validateOperationName, } from "./operation-catalog/types.js";
|
|
4
|
+
export { isValidOperationName, validateOperationName } from "./operation-catalog/types.js";
|
|
5
|
+
export function defineOperation(input) {
|
|
6
|
+
validateOperationName(input.name);
|
|
7
|
+
const metadata = snapshotOperationMetadata({ ...input, tags: input.tags ?? [] });
|
|
8
|
+
const fields = {
|
|
9
|
+
...metadata,
|
|
10
|
+
inputSchema: input.inputSchema,
|
|
11
|
+
outputSchema: input.outputSchema,
|
|
12
|
+
...(input.authorize === undefined ? {} : { authorize: input.authorize }),
|
|
13
|
+
};
|
|
14
|
+
if (input.kind === 'stream') {
|
|
15
|
+
const operation = Object.freeze({
|
|
16
|
+
...fields,
|
|
17
|
+
kind: input.kind,
|
|
18
|
+
eventSchema: input.eventSchema,
|
|
19
|
+
invoke: input.invoke,
|
|
20
|
+
});
|
|
21
|
+
return Object.freeze({
|
|
22
|
+
...operation,
|
|
23
|
+
dispatch: (rawInput, context) => dispatchOperation(operation, { rawInput, context }),
|
|
24
|
+
checkPolicy: (rawInput, context) => checkOperationPolicy(operation, rawInput, context),
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
if (input.kind === 'subscription') {
|
|
28
|
+
const operation = Object.freeze({
|
|
29
|
+
...fields,
|
|
30
|
+
kind: input.kind,
|
|
31
|
+
eventSchema: input.eventSchema,
|
|
32
|
+
invoke: input.invoke,
|
|
33
|
+
});
|
|
34
|
+
return Object.freeze({
|
|
35
|
+
...operation,
|
|
36
|
+
dispatch: (rawInput, context) => dispatchOperation(operation, { rawInput, context }),
|
|
37
|
+
checkPolicy: (rawInput, context) => checkOperationPolicy(operation, rawInput, context),
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
const operation = Object.freeze({ ...fields, kind: 'unary', invoke: input.invoke });
|
|
41
|
+
return Object.freeze({
|
|
42
|
+
...operation,
|
|
43
|
+
dispatch: (rawInput, context) => dispatchOperation(operation, { rawInput, context }),
|
|
44
|
+
checkPolicy: (rawInput, context) => checkOperationPolicy(operation, rawInput, context),
|
|
45
|
+
});
|
|
46
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An async iterable a consumer can close, and one that also says when its replay is complete.
|
|
3
|
+
* Imports nothing, so every host that serves a replay-and-live feed can build one.
|
|
4
|
+
*
|
|
5
|
+
* @module server/operations/closable-iterable
|
|
6
|
+
*/
|
|
7
|
+
export type ClosableAsyncIterable<T> = AsyncIterable<T> & {
|
|
8
|
+
close(): Promise<void>;
|
|
9
|
+
};
|
|
10
|
+
/** A closable async iterable that also exposes `replayComplete`, which settles once the replay part of a replay-and-live feed has been delivered. */
|
|
11
|
+
export type ReplayAwareClosableIterable<T> = ClosableAsyncIterable<T> & {
|
|
12
|
+
readonly replayComplete: Promise<void>;
|
|
13
|
+
};
|
|
14
|
+
type ReplayAwareClosableIterableOptions = {
|
|
15
|
+
readonly close: () => void | Promise<void>;
|
|
16
|
+
};
|
|
17
|
+
/** Wraps an async iterable source so a consumer can close it and await `replayComplete`. */
|
|
18
|
+
export declare function createReplayAwareClosableIterable<T>(createSource: (onReplayComplete: () => void) => AsyncIterable<T>, options: ReplayAwareClosableIterableOptions): ReplayAwareClosableIterable<T>;
|
|
19
|
+
/** Whether a value is an async iterable with a `close` method. */
|
|
20
|
+
export declare function isClosableAsyncIterable<T>(value: unknown): value is ClosableAsyncIterable<T>;
|
|
21
|
+
/** Whether a value is a closable async iterable that also exposes `replayComplete`. */
|
|
22
|
+
export declare function isReplayAwareClosableIterable<T>(value: unknown): value is ReplayAwareClosableIterable<T>;
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An async iterable a consumer can close, and one that also says when its replay is complete.
|
|
3
|
+
* Imports nothing, so every host that serves a replay-and-live feed can build one.
|
|
4
|
+
*
|
|
5
|
+
* @module server/operations/closable-iterable
|
|
6
|
+
*/
|
|
7
|
+
/** Wraps an async iterable source so a consumer can close it and await `replayComplete`. */
|
|
8
|
+
export function createReplayAwareClosableIterable(createSource, options) {
|
|
9
|
+
const replayComplete = Promise.withResolvers();
|
|
10
|
+
let closePromise;
|
|
11
|
+
const close = () => {
|
|
12
|
+
if (closePromise !== undefined)
|
|
13
|
+
return closePromise;
|
|
14
|
+
closePromise = Promise.resolve().then(options.close);
|
|
15
|
+
return closePromise;
|
|
16
|
+
};
|
|
17
|
+
let source;
|
|
18
|
+
try {
|
|
19
|
+
source = createSource(() => replayComplete.resolve());
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
void close();
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
25
|
+
return {
|
|
26
|
+
async *[Symbol.asyncIterator]() {
|
|
27
|
+
try {
|
|
28
|
+
for await (const value of source)
|
|
29
|
+
yield value;
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
await close();
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
replayComplete: replayComplete.promise,
|
|
36
|
+
close,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/** Whether a value is an async iterable with a `close` method. */
|
|
40
|
+
export function isClosableAsyncIterable(value) {
|
|
41
|
+
if (typeof value !== 'object' || value === null)
|
|
42
|
+
return false;
|
|
43
|
+
const candidate = value;
|
|
44
|
+
return typeof candidate.close === 'function';
|
|
45
|
+
}
|
|
46
|
+
/** Whether a value is a closable async iterable that also exposes `replayComplete`. */
|
|
47
|
+
export function isReplayAwareClosableIterable(value) {
|
|
48
|
+
return (isClosableAsyncIterable(value) &&
|
|
49
|
+
'replayComplete' in value &&
|
|
50
|
+
value.replayComplete instanceof Promise);
|
|
51
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `weft.system.principal` operation + REST binding.
|
|
3
|
+
*
|
|
4
|
+
* Reports the caller's own resolved principal: the authentication method,
|
|
5
|
+
* the normalized subject, the granted scope set, and any host-resolved workspace identity. Public access by
|
|
6
|
+
* design — introspection has to work for every credential state to be
|
|
7
|
+
* useful (a dashboard probes its principal before it knows anything), and
|
|
8
|
+
* an unauthenticated caller learns only what it already knows: that it is
|
|
9
|
+
* anonymous with no scopes. The response is strictly principal-shaped —
|
|
10
|
+
* nothing about the server's auth configuration (key inventory,
|
|
11
|
+
* `unauthenticatedAccess` posture, JWT issuers) is exposed.
|
|
12
|
+
*/
|
|
13
|
+
import { z } from 'zod';
|
|
14
|
+
import { type ScopeVocabulary } from "../authorization-scope.js";
|
|
15
|
+
import type { UnknownRestBinding } from "../rest-binding.js";
|
|
16
|
+
declare const getPrincipalInput: z.ZodObject<{}, z.core.$strip>;
|
|
17
|
+
declare const getPrincipalOutput: (vocabulary: ScopeVocabulary) => z.ZodObject<{
|
|
18
|
+
workspace: z.ZodOptional<z.ZodObject<{
|
|
19
|
+
version: z.ZodLiteral<1>;
|
|
20
|
+
workspaceId: z.ZodString;
|
|
21
|
+
actorId: z.ZodString;
|
|
22
|
+
actorKind: z.ZodEnum<{
|
|
23
|
+
user: "user";
|
|
24
|
+
service: "service";
|
|
25
|
+
local: "local";
|
|
26
|
+
}>;
|
|
27
|
+
owner: z.ZodString;
|
|
28
|
+
membershipRevision: z.ZodString;
|
|
29
|
+
capabilities: z.ZodArray<z.ZodEnum<{
|
|
30
|
+
"workspace:use": "workspace:use";
|
|
31
|
+
"workspace:manage": "workspace:manage";
|
|
32
|
+
"deployment:operate": "deployment:operate";
|
|
33
|
+
}>>;
|
|
34
|
+
}, z.core.$strip>>;
|
|
35
|
+
method: z.ZodEnum<{
|
|
36
|
+
jwt: "jwt";
|
|
37
|
+
"api-key": "api-key";
|
|
38
|
+
mtls: "mtls";
|
|
39
|
+
"stdio-local": "stdio-local";
|
|
40
|
+
"unauthenticated-local": "unauthenticated-local";
|
|
41
|
+
"browser-session": "browser-session";
|
|
42
|
+
"connector-token": "connector-token";
|
|
43
|
+
unauthenticated: "unauthenticated";
|
|
44
|
+
}>;
|
|
45
|
+
subject: z.ZodNullable<z.ZodString>;
|
|
46
|
+
scopes: z.ZodArray<z.ZodString | z.ZodUnion<readonly [z.ZodEnum<{
|
|
47
|
+
[x: string]: string;
|
|
48
|
+
}>, z.ZodString]>>;
|
|
49
|
+
}, z.core.$strip>;
|
|
50
|
+
export type GetPrincipalInput = z.infer<typeof getPrincipalInput>;
|
|
51
|
+
/**
|
|
52
|
+
* Output of `weft.system.principal`: the caller's authentication method,
|
|
53
|
+
* normalized subject (`null` when the credential carries none), and granted
|
|
54
|
+
* scopes, sorted. Anonymous callers receive `method: 'unauthenticated'`
|
|
55
|
+
* with an empty scope list.
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* ```ts
|
|
59
|
+
* import { type GetPrincipalOutput } from '@lostgradient/backchannel';
|
|
60
|
+
*
|
|
61
|
+
* const anonymous: GetPrincipalOutput = {
|
|
62
|
+
* method: 'unauthenticated',
|
|
63
|
+
* subject: null,
|
|
64
|
+
* scopes: [],
|
|
65
|
+
* };
|
|
66
|
+
* console.log(anonymous.method);
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
export type GetPrincipalOutput = z.infer<ReturnType<typeof getPrincipalOutput>>;
|
|
70
|
+
/** The operation that reports the caller's resolved principal and granted scopes; public, so an unauthenticated caller gets the `unauthenticated` method rather than an error. */
|
|
71
|
+
export declare function createGetPrincipalOperation(vocabulary: ScopeVocabulary): import("../operation-registry.js").UnarySchemaOperationDefinition<z.ZodObject<{}, z.core.$strip>, z.ZodObject<{
|
|
72
|
+
workspace: z.ZodOptional<z.ZodObject<{
|
|
73
|
+
version: z.ZodLiteral<1>;
|
|
74
|
+
workspaceId: z.ZodString;
|
|
75
|
+
actorId: z.ZodString;
|
|
76
|
+
actorKind: z.ZodEnum<{
|
|
77
|
+
user: "user";
|
|
78
|
+
service: "service";
|
|
79
|
+
local: "local";
|
|
80
|
+
}>;
|
|
81
|
+
owner: z.ZodString;
|
|
82
|
+
membershipRevision: z.ZodString;
|
|
83
|
+
capabilities: z.ZodArray<z.ZodEnum<{
|
|
84
|
+
"workspace:use": "workspace:use";
|
|
85
|
+
"workspace:manage": "workspace:manage";
|
|
86
|
+
"deployment:operate": "deployment:operate";
|
|
87
|
+
}>>;
|
|
88
|
+
}, z.core.$strip>>;
|
|
89
|
+
method: z.ZodEnum<{
|
|
90
|
+
jwt: "jwt";
|
|
91
|
+
"api-key": "api-key";
|
|
92
|
+
mtls: "mtls";
|
|
93
|
+
"stdio-local": "stdio-local";
|
|
94
|
+
"unauthenticated-local": "unauthenticated-local";
|
|
95
|
+
"browser-session": "browser-session";
|
|
96
|
+
"connector-token": "connector-token";
|
|
97
|
+
unauthenticated: "unauthenticated";
|
|
98
|
+
}>;
|
|
99
|
+
subject: z.ZodNullable<z.ZodString>;
|
|
100
|
+
scopes: z.ZodArray<z.ZodString | z.ZodUnion<readonly [z.ZodEnum<{
|
|
101
|
+
[x: string]: string;
|
|
102
|
+
}>, z.ZodString]>>;
|
|
103
|
+
}, z.core.$strip>, unknown>;
|
|
104
|
+
/** The REST binding of {@link createGetPrincipalOperation}. */
|
|
105
|
+
export declare const getPrincipalRestBinding: UnknownRestBinding;
|
|
106
|
+
export {};
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `weft.system.principal` operation + REST binding.
|
|
3
|
+
*
|
|
4
|
+
* Reports the caller's own resolved principal: the authentication method,
|
|
5
|
+
* the normalized subject, the granted scope set, and any host-resolved workspace identity. Public access by
|
|
6
|
+
* design — introspection has to work for every credential state to be
|
|
7
|
+
* useful (a dashboard probes its principal before it knows anything), and
|
|
8
|
+
* an unauthenticated caller learns only what it already knows: that it is
|
|
9
|
+
* anonymous with no scopes. The response is strictly principal-shaped —
|
|
10
|
+
* nothing about the server's auth configuration (key inventory,
|
|
11
|
+
* `unauthenticatedAccess` posture, JWT issuers) is exposed.
|
|
12
|
+
*/
|
|
13
|
+
import { z } from 'zod';
|
|
14
|
+
import { PACKAGE_AUTHORIZATION_SCOPE_PATTERN, } from "../authorization-scope.js";
|
|
15
|
+
import { shapeOperationFaultAsJson } from "../operation-fault.js";
|
|
16
|
+
import { defineOperation } from "../operation-registry.js";
|
|
17
|
+
const principalMethodSchema = z.enum([
|
|
18
|
+
'jwt',
|
|
19
|
+
'api-key',
|
|
20
|
+
'browser-session',
|
|
21
|
+
'connector-token',
|
|
22
|
+
'mtls',
|
|
23
|
+
'stdio-local',
|
|
24
|
+
'unauthenticated-local',
|
|
25
|
+
'unauthenticated',
|
|
26
|
+
]);
|
|
27
|
+
const getPrincipalInput = z.object({});
|
|
28
|
+
const packageScopeSchema = z.string().regex(PACKAGE_AUTHORIZATION_SCOPE_PATTERN);
|
|
29
|
+
const getPrincipalOutput = (vocabulary) => z.object({
|
|
30
|
+
workspace: z
|
|
31
|
+
.object({
|
|
32
|
+
version: z.literal(1),
|
|
33
|
+
workspaceId: z.string(),
|
|
34
|
+
actorId: z.string(),
|
|
35
|
+
actorKind: z.enum(['user', 'service', 'local']),
|
|
36
|
+
owner: z.string(),
|
|
37
|
+
membershipRevision: z.string(),
|
|
38
|
+
capabilities: z.array(z.enum(['workspace:use', 'workspace:manage', 'deployment:operate'])),
|
|
39
|
+
})
|
|
40
|
+
.optional(),
|
|
41
|
+
method: principalMethodSchema,
|
|
42
|
+
subject: z.string().nullable(),
|
|
43
|
+
// Built-in scopes, or a package scope a handler registered through
|
|
44
|
+
// `additionalScopes`. The schema is shared by every handler, so it accepts
|
|
45
|
+
// any well-formed package scope; the authenticator is what limits a
|
|
46
|
+
// principal to the scopes its own handler registered.
|
|
47
|
+
scopes: z.array(vocabulary.scopes.length === 0
|
|
48
|
+
? packageScopeSchema
|
|
49
|
+
: z.union([z.enum(vocabulary.scopes), packageScopeSchema])),
|
|
50
|
+
});
|
|
51
|
+
/** The operation that reports the caller's resolved principal and granted scopes; public, so an unauthenticated caller gets the `unauthenticated` method rather than an error. */
|
|
52
|
+
export function createGetPrincipalOperation(vocabulary) {
|
|
53
|
+
return defineOperation({
|
|
54
|
+
name: 'weft.system.principal',
|
|
55
|
+
mcpExposable: false,
|
|
56
|
+
summary: "Report the caller's resolved principal and granted scopes",
|
|
57
|
+
description: "Report the caller's own resolved principal: the authentication method ('jwt', 'api-key', " +
|
|
58
|
+
"'browser-session', 'connector-token', 'mtls', 'stdio-local', 'unauthenticated-local', or 'unauthenticated'), the normalized subject " +
|
|
59
|
+
'when one exists, and ' +
|
|
60
|
+
'the granted authorization scopes, sorted. Public access: an unauthenticated caller ' +
|
|
61
|
+
"receives method 'unauthenticated' with an empty scope list rather than an error, so " +
|
|
62
|
+
'clients can distinguish "no credential" from "credential with few scopes" without probing ' +
|
|
63
|
+
"other operations. A server with no authentication reports 'unauthenticated-local' holding " +
|
|
64
|
+
'every scope. A workspace-aware host also reports its resolved workspace identity, stable actor, ' +
|
|
65
|
+
'opaque owner, membership revision and capabilities. Never exposes server auth configuration.',
|
|
66
|
+
destructive: false,
|
|
67
|
+
tags: ['System'],
|
|
68
|
+
inputSchema: getPrincipalInput,
|
|
69
|
+
outputSchema: getPrincipalOutput(vocabulary),
|
|
70
|
+
access: { kind: 'public' },
|
|
71
|
+
discoverable: true,
|
|
72
|
+
transports: { http: true, jsonRpcHttp: true, jsonRpcWebSocket: true, jsonRpcStdio: true },
|
|
73
|
+
unknownKeyPolicy: { http: 'strip', jsonRpc: 'reject' },
|
|
74
|
+
invoke: async ({ principal }) => {
|
|
75
|
+
if (principal.method === 'unauthenticated') {
|
|
76
|
+
return { method: 'unauthenticated', subject: null, scopes: [] };
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
method: principal.method,
|
|
80
|
+
...(principal.workspace === undefined
|
|
81
|
+
? {}
|
|
82
|
+
: {
|
|
83
|
+
workspace: {
|
|
84
|
+
...principal.workspace,
|
|
85
|
+
capabilities: [...principal.workspace.capabilities],
|
|
86
|
+
},
|
|
87
|
+
}),
|
|
88
|
+
subject: principal.subject ?? null,
|
|
89
|
+
// Sorted for a deterministic wire shape — `scopes` is a Set whose
|
|
90
|
+
// iteration order is credential-construction order, which callers
|
|
91
|
+
// must not come to depend on.
|
|
92
|
+
scopes: [...principal.scopes].toSorted(),
|
|
93
|
+
};
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
/** The REST binding of {@link createGetPrincipalOperation}. */
|
|
98
|
+
export const getPrincipalRestBinding = {
|
|
99
|
+
method: 'GET',
|
|
100
|
+
path: '/v1/principal',
|
|
101
|
+
pathParamNames: [],
|
|
102
|
+
operationName: 'weft.system.principal',
|
|
103
|
+
inputSources: {},
|
|
104
|
+
extractInput: async () => ({}),
|
|
105
|
+
success: { kind: 'json', status: 200 },
|
|
106
|
+
shapeFault: shapeOperationFaultAsJson,
|
|
107
|
+
};
|