scoped-execution-protocol 0.0.0-stage → 2.0.0-rc.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/dist/apps.d.ts +90 -0
- package/dist/apps.js +231 -0
- package/dist/bridges/a2a.d.ts +55 -0
- package/dist/bridges/a2a.js +360 -0
- package/dist/bridges/agui.d.ts +25 -0
- package/dist/bridges/agui.js +82 -0
- package/dist/bridges/host.d.ts +36 -0
- package/dist/bridges/host.js +93 -0
- package/dist/bridges/http.d.ts +12 -0
- package/dist/bridges/http.js +55 -0
- package/dist/bridges/index.d.ts +7 -0
- package/dist/bridges/index.js +7 -0
- package/dist/bridges/mcp-proxy.d.ts +39 -0
- package/dist/bridges/mcp-proxy.js +122 -0
- package/dist/bridges/mcp.d.ts +88 -0
- package/dist/bridges/mcp.js +571 -0
- package/dist/bridges/providers.d.ts +16 -0
- package/dist/bridges/providers.js +9 -0
- package/dist/canonical.d.ts +3 -0
- package/dist/canonical.js +46 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +10 -0
- package/dist/kernel.d.ts +416 -0
- package/dist/kernel.js +1927 -0
- package/dist/pending.d.ts +56 -0
- package/dist/pending.js +72 -0
- package/dist/policy.d.ts +20 -0
- package/dist/policy.js +100 -0
- package/dist/privacy.d.ts +52 -0
- package/dist/privacy.js +273 -0
- package/dist/state.d.ts +59 -0
- package/dist/state.js +125 -0
- package/dist/store.d.ts +59 -0
- package/dist/store.js +270 -0
- package/dist/transport.d.ts +108 -0
- package/dist/transport.js +358 -0
- package/dist/types.d.ts +167 -0
- package/dist/types.js +98 -0
- package/package.json +69 -6
- package/README.md +0 -3
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
import { canonicalJson, contentHash } from "./canonical.js";
|
|
2
|
+
import { SXPError } from "./types.js";
|
|
3
|
+
import { DEFAULT_MAX_NONCES, replayCapacityExceeded } from "./state.js";
|
|
4
|
+
export const CORE_PROFILE = "sxp:core/0.1";
|
|
5
|
+
export const MAX_FRAME_BYTES = 16 * 1024 * 1024;
|
|
6
|
+
export const MAX_RAILS_CACHE_ENTRIES = 256;
|
|
7
|
+
/**
|
|
8
|
+
* Remembers envelope IDs for `ttlMs`: in memory by default (bounded by `maxEntries`), or in a `StateStore` to
|
|
9
|
+
* survive restarts and share the window between workers (for example `FileStateStore`).
|
|
10
|
+
*
|
|
11
|
+
* With the default memory a check is synchronous. With a store it returns whatever the store returns, so await it.
|
|
12
|
+
*
|
|
13
|
+
* It never forgets an ID that is still inside `ttlMs`. Expired IDs are dropped first; if the window is still full of
|
|
14
|
+
* live IDs it throws `REPLAY_CAPACITY_EXCEEDED` and records nothing, because evicting a live ID would let a captured
|
|
15
|
+
* envelope be replayed. The sender retries with a new envelope.
|
|
16
|
+
*/
|
|
17
|
+
export class ReplayGuard {
|
|
18
|
+
maxEntries;
|
|
19
|
+
ttlMs;
|
|
20
|
+
store;
|
|
21
|
+
seen = new Map();
|
|
22
|
+
constructor(opts) {
|
|
23
|
+
this.maxEntries = opts?.maxEntries ?? DEFAULT_MAX_NONCES;
|
|
24
|
+
if (!Number.isSafeInteger(this.maxEntries) || this.maxEntries < 1)
|
|
25
|
+
throw new RangeError("maxEntries must be a positive integer.");
|
|
26
|
+
this.ttlMs = opts?.ttlMs ?? 300_000;
|
|
27
|
+
this.store = opts?.store;
|
|
28
|
+
}
|
|
29
|
+
checkAndRecord(envelopeId, nowMs = Date.now()) {
|
|
30
|
+
if (this.store) {
|
|
31
|
+
const reject = () => {
|
|
32
|
+
throw new SXPError("REPLAY_DETECTED", `REPLAY_DETECTED: Duplicate envelope id ${envelopeId}`);
|
|
33
|
+
};
|
|
34
|
+
const marked = this.store.checkAndMarkNonce(envelopeId, { ttlMs: this.ttlMs, nowMs });
|
|
35
|
+
if (typeof marked === "boolean")
|
|
36
|
+
return marked ? undefined : reject();
|
|
37
|
+
return marked.then((isNew) => (isNew ? undefined : reject()));
|
|
38
|
+
}
|
|
39
|
+
const cutoff = nowMs - this.ttlMs;
|
|
40
|
+
for (const [id, ts] of this.seen) {
|
|
41
|
+
if (ts >= cutoff)
|
|
42
|
+
break;
|
|
43
|
+
this.seen.delete(id);
|
|
44
|
+
}
|
|
45
|
+
if (this.seen.has(envelopeId)) {
|
|
46
|
+
throw new SXPError("REPLAY_DETECTED", `REPLAY_DETECTED: Duplicate envelope id ${envelopeId}`);
|
|
47
|
+
}
|
|
48
|
+
if (this.seen.size >= this.maxEntries)
|
|
49
|
+
throw replayCapacityExceeded();
|
|
50
|
+
this.seen.set(envelopeId, nowMs);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export const WIRE_HINT_TARGET = "SXP-Target";
|
|
54
|
+
export const WIRE_HINT_EFFECT = "SXP-Effect";
|
|
55
|
+
const MAX_WIRE_HINT_BYTES = 512;
|
|
56
|
+
const ENCODED_HINT_PREFIX = "=?base64?";
|
|
57
|
+
const ENCODED_HINT_SUFFIX = "?=";
|
|
58
|
+
const VISIBLE_ASCII = /^[\x21-\x7e]+$/;
|
|
59
|
+
/**
|
|
60
|
+
* Header-safe form of a routing hint (`SXP-Target`, `SXP-Effect`), or `undefined` if it is too long to be useful.
|
|
61
|
+
* Visible ASCII is sent as is; anything else, including a value that merely looks encoded, is base64 wrapped so a
|
|
62
|
+
* hostile target name can never inject a header line.
|
|
63
|
+
*/
|
|
64
|
+
export function encodeWireHint(value) {
|
|
65
|
+
try {
|
|
66
|
+
encodeURIComponent(value); // throws on a lone surrogate, which UTF-8 cannot carry faithfully
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
const bytes = new TextEncoder().encode(value);
|
|
72
|
+
if (bytes.byteLength > MAX_WIRE_HINT_BYTES)
|
|
73
|
+
return undefined;
|
|
74
|
+
const looksEncoded = value.startsWith(ENCODED_HINT_PREFIX) && value.endsWith(ENCODED_HINT_SUFFIX);
|
|
75
|
+
if (!looksEncoded && VISIBLE_ASCII.test(value))
|
|
76
|
+
return value;
|
|
77
|
+
return ENCODED_HINT_PREFIX + btoa(Array.from(bytes, (b) => String.fromCharCode(b)).join("")) + ENCODED_HINT_SUFFIX;
|
|
78
|
+
}
|
|
79
|
+
export function decodeWireHint(header) {
|
|
80
|
+
// The encoder only ever emits visible ASCII, so anything else (spaces included) is malformed or a merged duplicate.
|
|
81
|
+
if (header.length > 4 * MAX_WIRE_HINT_BYTES || !VISIBLE_ASCII.test(header))
|
|
82
|
+
throw new SXPError("INVALID_FRAME", "Malformed routing hint.");
|
|
83
|
+
if (!header.startsWith(ENCODED_HINT_PREFIX) || !header.endsWith(ENCODED_HINT_SUFFIX))
|
|
84
|
+
return header;
|
|
85
|
+
try {
|
|
86
|
+
const encoded = header.slice(ENCODED_HINT_PREFIX.length, header.length - ENCODED_HINT_SUFFIX.length);
|
|
87
|
+
const binary = atob(encoded);
|
|
88
|
+
if (btoa(binary) !== encoded)
|
|
89
|
+
throw new Error("non-canonical base64");
|
|
90
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)));
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
throw new SXPError("INVALID_FRAME", "Malformed routing hint.");
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Reject a request whose advisory routing headers disagree with its (already authenticated) envelope.
|
|
98
|
+
* The headers sit outside the HMAC, so they are never trusted: they let a gateway route or rate-limit on target
|
|
99
|
+
* and effect without parsing the body, and this check keeps the body from saying something else.
|
|
100
|
+
*/
|
|
101
|
+
export function checkWireHints(envelope, hints) {
|
|
102
|
+
const expected = [[WIRE_HINT_TARGET, envelope.payload?.target], [WIRE_HINT_EFFECT, envelope.effect]];
|
|
103
|
+
for (const [name, actual] of expected) {
|
|
104
|
+
const hint = hints[name];
|
|
105
|
+
if (hint !== undefined && hint !== actual)
|
|
106
|
+
throw new SXPError("WIRE_HINT_MISMATCH", `${name} header does not match the request.`);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Reject a request whose `payload.iat_ms` is missing, malformed, or more than `windowMs` from now.
|
|
111
|
+
* The window is symmetric, so a `ReplayGuard` must remember IDs for at least `2 * windowMs`:
|
|
112
|
+
* nothing outside the window is accepted and nothing inside it twice.
|
|
113
|
+
*/
|
|
114
|
+
export function checkFreshness(payload, windowMs, nowMs = Date.now()) {
|
|
115
|
+
const iat = payload.iat_ms;
|
|
116
|
+
if (typeof iat !== "number" || !Number.isSafeInteger(iat) || iat < 0 || Math.abs(nowMs - iat) > windowMs) {
|
|
117
|
+
throw new SXPError("STALE_ENVELOPE", "Request iat_ms is missing, malformed or outside the freshness window.");
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
function envelopeBody(env) {
|
|
121
|
+
return {
|
|
122
|
+
causal_parent: env.causal_parent,
|
|
123
|
+
capability: env.capability,
|
|
124
|
+
budget: env.budget,
|
|
125
|
+
effect: env.effect,
|
|
126
|
+
rails: env.rails,
|
|
127
|
+
provenance: env.provenance,
|
|
128
|
+
profile: env.profile,
|
|
129
|
+
payload: env.payload,
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
function toSecretBytes(secret) {
|
|
133
|
+
const src = typeof secret === "string" ? new TextEncoder().encode(secret) : secret;
|
|
134
|
+
const buf = new ArrayBuffer(src.byteLength);
|
|
135
|
+
const out = new Uint8Array(buf);
|
|
136
|
+
out.set(src);
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
export async function signEnvelope(envelope, secret) {
|
|
140
|
+
const key = await globalThis.crypto.subtle.importKey("raw", toSecretBytes(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
141
|
+
const sigBuf = await globalThis.crypto.subtle.sign("HMAC", key, new TextEncoder().encode(canonicalJson(envelopeBody(envelope))));
|
|
142
|
+
const hex = Array.from(new Uint8Array(sigBuf))
|
|
143
|
+
.map((b) => b.toString(16).padStart(2, "0"))
|
|
144
|
+
.join("");
|
|
145
|
+
return `hmac-sha256:${hex}`;
|
|
146
|
+
}
|
|
147
|
+
export async function verifyEnvelope(envelope, secret, signature) {
|
|
148
|
+
if (!signature || !signature.startsWith("hmac-sha256:"))
|
|
149
|
+
return false;
|
|
150
|
+
const hex = signature.slice("hmac-sha256:".length);
|
|
151
|
+
if (!/^[0-9a-f]{64}$/i.test(hex))
|
|
152
|
+
return false;
|
|
153
|
+
const sigBytes = new Uint8Array(new ArrayBuffer(32));
|
|
154
|
+
for (let i = 0; i < 32; i++)
|
|
155
|
+
sigBytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
156
|
+
const key = await globalThis.crypto.subtle.importKey("raw", toSecretBytes(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
|
|
157
|
+
return globalThis.crypto.subtle.verify("HMAC", key, sigBytes, new TextEncoder().encode(canonicalJson(envelopeBody(envelope))));
|
|
158
|
+
}
|
|
159
|
+
export function negotiate0rttProfile(localSupported, remoteSupported) {
|
|
160
|
+
const remoteSet = new Set(remoteSupported);
|
|
161
|
+
for (const candidate of localSupported) {
|
|
162
|
+
if (remoteSet.has(candidate))
|
|
163
|
+
return { active: candidate, supported: [...localSupported] };
|
|
164
|
+
}
|
|
165
|
+
return { active: CORE_PROFILE, supported: [...localSupported] };
|
|
166
|
+
}
|
|
167
|
+
export async function encodeNdjsonFrame(envelope, railsCache, signingSecret) {
|
|
168
|
+
let obj = { ...envelope };
|
|
169
|
+
if (signingSecret !== undefined) {
|
|
170
|
+
obj = { ...obj, $sig: await signEnvelope(envelope, signingSecret) };
|
|
171
|
+
}
|
|
172
|
+
if (railsCache && envelope.rails.length > 0) {
|
|
173
|
+
const rh = await contentHash(envelope.rails);
|
|
174
|
+
if (railsCache.has(rh))
|
|
175
|
+
obj = { ...obj, rails: [{ $rails_ref: rh }] };
|
|
176
|
+
else if (railsCache.size < MAX_RAILS_CACHE_ENTRIES)
|
|
177
|
+
railsCache.set(rh, envelope.rails);
|
|
178
|
+
}
|
|
179
|
+
return canonicalJson(obj) + "\n";
|
|
180
|
+
}
|
|
181
|
+
export async function decodeNdjsonFrame(line, railsCache, opts) {
|
|
182
|
+
const maxBytes = opts?.maxFrameBytes ?? MAX_FRAME_BYTES;
|
|
183
|
+
if (new TextEncoder().encode(line).byteLength > maxBytes) {
|
|
184
|
+
throw new SXPError("FRAME_TOO_LARGE", `NDJSON frame exceeds max size (${maxBytes} bytes).`);
|
|
185
|
+
}
|
|
186
|
+
const rawObj = JSON.parse(line.trim());
|
|
187
|
+
if (rawObj === null || typeof rawObj !== "object" || Array.isArray(rawObj))
|
|
188
|
+
throw new SXPError("INVALID_FRAME", "Wire frame must contain an envelope object.");
|
|
189
|
+
const wireSig = typeof rawObj.$sig === "string" ? rawObj.$sig : undefined;
|
|
190
|
+
delete rawObj.$sig;
|
|
191
|
+
const fields = ["id", "causal_parent", "capability", "budget", "effect", "rails", "provenance", "profile", "payload"];
|
|
192
|
+
if (Object.keys(rawObj).length !== fields.length || fields.some((field) => !Object.hasOwn(rawObj, field))) {
|
|
193
|
+
throw new SXPError("INVALID_FRAME", "Wire frame has missing or unexpected envelope fields.");
|
|
194
|
+
}
|
|
195
|
+
if ([rawObj.capability, rawObj.budget, rawObj.profile, rawObj.payload].some((field) => field === null || typeof field !== "object" || Array.isArray(field)) || !Array.isArray(rawObj.rails)) {
|
|
196
|
+
throw new SXPError("INVALID_FRAME", "Wire envelope contains invalid field types.");
|
|
197
|
+
}
|
|
198
|
+
const env = rawObj;
|
|
199
|
+
let usedRef = false;
|
|
200
|
+
if (railsCache && env.rails.length === 1 && env.rails[0] && typeof env.rails[0] === "object" && "$rails_ref" in env.rails[0]) {
|
|
201
|
+
const rh = env.rails[0].$rails_ref;
|
|
202
|
+
const cached = railsCache.get(rh);
|
|
203
|
+
if (!cached)
|
|
204
|
+
throw new SXPError("INVALID_FRAME", `Missing cached rails for ref ${rh}`);
|
|
205
|
+
env.rails = cached;
|
|
206
|
+
usedRef = true;
|
|
207
|
+
}
|
|
208
|
+
const { id, ...body } = env;
|
|
209
|
+
const expected = await contentHash(body);
|
|
210
|
+
if (id !== expected)
|
|
211
|
+
throw new SXPError("INVALID_FRAME", "Envelope integrity error: declared ID does not match the wire body.");
|
|
212
|
+
const fullEnv = { ...env, id: expected };
|
|
213
|
+
if (opts?.signingSecret !== undefined) {
|
|
214
|
+
if (!wireSig || !(await verifyEnvelope(fullEnv, opts.signingSecret, wireSig))) {
|
|
215
|
+
throw new SXPError("INVALID_ENVELOPE_SIGNATURE", "INVALID_ENVELOPE_SIGNATURE: Wire envelope failed HMAC verification.");
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (opts?.verifyFn) {
|
|
219
|
+
if (!wireSig || !(await opts.verifyFn(fullEnv, wireSig))) {
|
|
220
|
+
throw new SXPError("INVALID_ENVELOPE_SIGNATURE", "INVALID_ENVELOPE_SIGNATURE: Wire envelope failed verifier check.");
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
if (railsCache && !usedRef && Array.isArray(fullEnv.rails) && fullEnv.rails.length > 0 && railsCache.size < MAX_RAILS_CACHE_ENTRIES) {
|
|
224
|
+
railsCache.set(await contentHash(fullEnv.rails), fullEnv.rails);
|
|
225
|
+
}
|
|
226
|
+
return fullEnv;
|
|
227
|
+
}
|
|
228
|
+
function limitBytes(maxBytes) {
|
|
229
|
+
let bytes = 0;
|
|
230
|
+
return new TransformStream({
|
|
231
|
+
transform(chunk, controller) {
|
|
232
|
+
bytes += chunk.byteLength;
|
|
233
|
+
if (bytes > maxBytes)
|
|
234
|
+
throw new SXPError("FRAME_TOO_LARGE", "HTTP body exceeds the frame limit.");
|
|
235
|
+
controller.enqueue(chunk);
|
|
236
|
+
},
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
export async function readFrame(message, limit, decompressRequest = false) {
|
|
240
|
+
const { body, headers } = message;
|
|
241
|
+
if (!body)
|
|
242
|
+
throw new SXPError("INVALID_FRAME", "A streaming body is required.");
|
|
243
|
+
if (Number(headers.get("content-length")) > limit) {
|
|
244
|
+
await body.cancel();
|
|
245
|
+
throw new SXPError("FRAME_TOO_LARGE", "HTTP body exceeds the frame limit.");
|
|
246
|
+
}
|
|
247
|
+
const encoding = headers.get("content-encoding")?.toLowerCase();
|
|
248
|
+
let stream = body.pipeThrough(limitBytes(limit));
|
|
249
|
+
if (decompressRequest && encoding && encoding !== "identity") {
|
|
250
|
+
if (encoding !== "deflate") {
|
|
251
|
+
await stream.cancel();
|
|
252
|
+
throw new SXPError("INVALID_FRAME", "Unsupported content encoding.");
|
|
253
|
+
}
|
|
254
|
+
stream = stream.pipeThrough(new DecompressionStream("deflate")).pipeThrough(limitBytes(limit));
|
|
255
|
+
}
|
|
256
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(await new Response(stream).arrayBuffer());
|
|
257
|
+
}
|
|
258
|
+
export function createSxpFetchHandler(kernel, opts) {
|
|
259
|
+
const limit = opts?.maxFrameBytes ?? MAX_FRAME_BYTES;
|
|
260
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > MAX_FRAME_BYTES)
|
|
261
|
+
throw new RangeError("Invalid frame limit.");
|
|
262
|
+
const secret = opts?.signingSecret;
|
|
263
|
+
if (secret?.length === 0 || (secret === undefined && !opts?.allowUnsigned)) {
|
|
264
|
+
throw new Error("Provide a wire signing secret or explicitly enable unsigned requests.");
|
|
265
|
+
}
|
|
266
|
+
const windowMs = opts?.freshnessWindowMs;
|
|
267
|
+
if (windowMs !== undefined && (!Number.isSafeInteger(windowMs) || windowMs < 1)) {
|
|
268
|
+
throw new RangeError("freshnessWindowMs must be a positive integer.");
|
|
269
|
+
}
|
|
270
|
+
const guard = opts?.replayGuard ?? new ReplayGuard(windowMs === undefined ? undefined : { ttlMs: Math.max(300_000, 2 * windowMs) });
|
|
271
|
+
if (windowMs !== undefined && guard.ttlMs < 2 * windowMs) {
|
|
272
|
+
throw new RangeError("The ReplayGuard must remember IDs for at least twice the freshness window.");
|
|
273
|
+
}
|
|
274
|
+
const railsCache = opts?.railsCache ?? new Map();
|
|
275
|
+
return async (req) => {
|
|
276
|
+
try {
|
|
277
|
+
const line = await readFrame(req, limit, true);
|
|
278
|
+
const wireHints = {};
|
|
279
|
+
for (const name of [WIRE_HINT_TARGET, WIRE_HINT_EFFECT]) {
|
|
280
|
+
const value = req.headers.get(name);
|
|
281
|
+
if (value !== null)
|
|
282
|
+
wireHints[name] = decodeWireHint(value);
|
|
283
|
+
}
|
|
284
|
+
const reply = await kernel.handleEnvelope(line, {
|
|
285
|
+
signingSecret: opts?.signingSecret,
|
|
286
|
+
replayGuard: guard,
|
|
287
|
+
callerClearance: opts?.callerClearance,
|
|
288
|
+
railsCache,
|
|
289
|
+
freshnessWindowMs: windowMs,
|
|
290
|
+
wireHints,
|
|
291
|
+
});
|
|
292
|
+
// Independent HTTP clients do not share the receiver's rails cache.
|
|
293
|
+
const body = await encodeNdjsonFrame(reply, undefined, opts?.signingSecret);
|
|
294
|
+
if (new TextEncoder().encode(body).byteLength > limit)
|
|
295
|
+
throw new SXPError("FRAME_TOO_LARGE", "Reply exceeds the frame limit.");
|
|
296
|
+
return new Response(body, { headers: {
|
|
297
|
+
"content-type": "application/x-sxp-ndjson+json",
|
|
298
|
+
"x-sxp-profiles": kernel.supportedProfiles.join(","),
|
|
299
|
+
} });
|
|
300
|
+
}
|
|
301
|
+
catch (err) {
|
|
302
|
+
const code = err instanceof SXPError ? err.code : "INVALID_FRAME";
|
|
303
|
+
// Every other wire error is the sender's fault (400). A full replay window is the receiver's: retry later.
|
|
304
|
+
return Response.json({ error: { code } }, { status: code === "FRAME_TOO_LARGE" ? 413 : code === "REPLAY_CAPACITY_EXCEEDED" ? 503 : 400 });
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
export class SxpHttpClient {
|
|
309
|
+
endpointUrl;
|
|
310
|
+
supportedProfiles;
|
|
311
|
+
signingSecret;
|
|
312
|
+
fetchFn;
|
|
313
|
+
railsCache = new Map();
|
|
314
|
+
constructor(endpointUrl, opts) {
|
|
315
|
+
const parsed = new URL(endpointUrl);
|
|
316
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
317
|
+
throw new Error(`Only http:// and https:// URLs are permitted (got ${endpointUrl}).`);
|
|
318
|
+
}
|
|
319
|
+
this.endpointUrl = endpointUrl;
|
|
320
|
+
this.supportedProfiles = opts?.supportedProfiles ?? [CORE_PROFILE];
|
|
321
|
+
this.signingSecret = opts?.signingSecret;
|
|
322
|
+
const defaultFetch = globalThis.fetch;
|
|
323
|
+
if (!opts?.fetchFn && !defaultFetch)
|
|
324
|
+
throw new Error("No fetch implementation available.");
|
|
325
|
+
this.fetchFn = opts?.fetchFn ?? defaultFetch;
|
|
326
|
+
}
|
|
327
|
+
async sendAndReceive(envelope) {
|
|
328
|
+
const body = await encodeNdjsonFrame(envelope, undefined, this.signingSecret);
|
|
329
|
+
if (envelope.rails.length && this.railsCache.size < MAX_RAILS_CACHE_ENTRIES) {
|
|
330
|
+
this.railsCache.set(await contentHash(envelope.rails), structuredClone(envelope.rails));
|
|
331
|
+
}
|
|
332
|
+
const headers = {
|
|
333
|
+
"Content-Type": "application/x-sxp-ndjson+json",
|
|
334
|
+
"X-SXP-Profiles": this.supportedProfiles.join(","),
|
|
335
|
+
};
|
|
336
|
+
if (this.signingSecret !== undefined) {
|
|
337
|
+
headers["X-SXP-Signature"] = await signEnvelope(envelope, this.signingSecret);
|
|
338
|
+
}
|
|
339
|
+
const target = envelope.payload?.target;
|
|
340
|
+
const hints = [[WIRE_HINT_TARGET, typeof target === "string" ? target : undefined], [WIRE_HINT_EFFECT, envelope.effect]];
|
|
341
|
+
for (const [name, value] of hints) {
|
|
342
|
+
const hint = typeof value === "string" && value ? encodeWireHint(value) : undefined;
|
|
343
|
+
if (hint !== undefined)
|
|
344
|
+
headers[name] = hint;
|
|
345
|
+
}
|
|
346
|
+
const resp = await this.fetchFn(this.endpointUrl, { method: "POST", headers, body });
|
|
347
|
+
const text = await readFrame(resp, MAX_FRAME_BYTES);
|
|
348
|
+
if (resp.status >= 400) {
|
|
349
|
+
throw new Error(`SXP HTTP error ${resp.status}: ${text}`);
|
|
350
|
+
}
|
|
351
|
+
const remoteHdr = resp.headers.get("x-sxp-profiles") ?? CORE_PROFILE;
|
|
352
|
+
const remoteProfiles = remoteHdr.split(",").map((s) => s.trim()).filter(Boolean);
|
|
353
|
+
const reply = await decodeNdjsonFrame(text, this.railsCache, { signingSecret: this.signingSecret });
|
|
354
|
+
if (reply.causal_parent !== envelope.id)
|
|
355
|
+
throw new SXPError("INVALID_REPLY", "Reply does not match the request.");
|
|
356
|
+
return { reply, profile: negotiate0rttProfile(this.supportedProfiles, remoteProfiles) };
|
|
357
|
+
}
|
|
358
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
export declare const SXP_VERSION = "2.0.0";
|
|
2
|
+
export type TaintLevel = "instruction" | "trusted_data" | "untrusted_data";
|
|
3
|
+
export type DataClassification = "public" | "internal" | "confidential" | "restricted";
|
|
4
|
+
export type EffectClass = "read" | "idempotent" | "soft_hold" | "best_effort_undo" | "unverified_write" | "irreversible";
|
|
5
|
+
export type ProjectionMode = "standard" | "compact" | "flat" | "unified";
|
|
6
|
+
export declare const EFFECT_RANK: Record<EffectClass, number>;
|
|
7
|
+
export declare const TAINT_RANK: Record<TaintLevel, number>;
|
|
8
|
+
export declare const CLASSIFICATION_RANK: Record<DataClassification, number>;
|
|
9
|
+
export interface DataPolicy {
|
|
10
|
+
classification: DataClassification;
|
|
11
|
+
residency?: string | null;
|
|
12
|
+
residencies?: string[];
|
|
13
|
+
allowed_purposes?: string[];
|
|
14
|
+
ephemeral?: boolean;
|
|
15
|
+
ttl_ms?: number | null;
|
|
16
|
+
pii_fields?: string[];
|
|
17
|
+
}
|
|
18
|
+
export interface Clearance {
|
|
19
|
+
max_classification: DataClassification;
|
|
20
|
+
allowed_residencies: string[];
|
|
21
|
+
allowed_purposes: string[];
|
|
22
|
+
}
|
|
23
|
+
export interface CapabilityToken {
|
|
24
|
+
token_id: string;
|
|
25
|
+
issuer: string;
|
|
26
|
+
subject: string;
|
|
27
|
+
taint: TaintLevel;
|
|
28
|
+
allowed_actions: string[];
|
|
29
|
+
allowed_scopes: string[];
|
|
30
|
+
max_effect: EffectClass;
|
|
31
|
+
expires_at_ms: number | null;
|
|
32
|
+
credential_ref?: string | null;
|
|
33
|
+
credential_scopes?: string[];
|
|
34
|
+
clearance?: Clearance;
|
|
35
|
+
signature: string | null;
|
|
36
|
+
}
|
|
37
|
+
export interface BudgetLimit {
|
|
38
|
+
wall_ms?: number | null;
|
|
39
|
+
tokens?: number | null;
|
|
40
|
+
cost_micros?: number | null;
|
|
41
|
+
depth?: number | null;
|
|
42
|
+
reserve_ratio?: number;
|
|
43
|
+
}
|
|
44
|
+
export interface HardRail {
|
|
45
|
+
id: string;
|
|
46
|
+
kind: "max_numeric_arg" | "require_preview" | "require_human_approval" | "block_tainted_egress" | "deny_domains" | "custom";
|
|
47
|
+
description: string;
|
|
48
|
+
params: Record<string, unknown>;
|
|
49
|
+
signature?: string | null;
|
|
50
|
+
validator?: (action: string, args: Record<string, unknown>, effect: EffectClass) => string | null;
|
|
51
|
+
}
|
|
52
|
+
export declare const HardRail: {
|
|
53
|
+
custom(id: string, description: string, validator: NonNullable<HardRail["validator"]>): HardRail;
|
|
54
|
+
blockTaintedEgress(opts?: {
|
|
55
|
+
allowHumanApproved?: boolean;
|
|
56
|
+
}): HardRail;
|
|
57
|
+
};
|
|
58
|
+
export interface ProvenanceRoot {
|
|
59
|
+
hash: string;
|
|
60
|
+
origin: string;
|
|
61
|
+
substrate: string;
|
|
62
|
+
weight: number;
|
|
63
|
+
verified: boolean;
|
|
64
|
+
signature?: string | null;
|
|
65
|
+
}
|
|
66
|
+
export interface Provenance {
|
|
67
|
+
roots: ProvenanceRoot[];
|
|
68
|
+
substrate: string;
|
|
69
|
+
}
|
|
70
|
+
export interface ProfileDescriptor {
|
|
71
|
+
active: string;
|
|
72
|
+
supported: string[];
|
|
73
|
+
}
|
|
74
|
+
export interface CoreEnvelope {
|
|
75
|
+
id: string;
|
|
76
|
+
causal_parent: string | null;
|
|
77
|
+
capability: CapabilityToken;
|
|
78
|
+
budget: BudgetLimit;
|
|
79
|
+
effect: EffectClass;
|
|
80
|
+
rails: HardRail[];
|
|
81
|
+
provenance: Provenance | null;
|
|
82
|
+
profile: ProfileDescriptor;
|
|
83
|
+
payload: Record<string, unknown>;
|
|
84
|
+
}
|
|
85
|
+
export interface RefHandle {
|
|
86
|
+
ref_id: string;
|
|
87
|
+
short_id: string;
|
|
88
|
+
label: string;
|
|
89
|
+
taint: TaintLevel;
|
|
90
|
+
policy: DataPolicy;
|
|
91
|
+
byte_size: number;
|
|
92
|
+
l0_summary: string;
|
|
93
|
+
l0_keys: string[];
|
|
94
|
+
unprojected_fields: string[];
|
|
95
|
+
anomalies: string[];
|
|
96
|
+
provenance: Provenance | null;
|
|
97
|
+
created_at_ms: number;
|
|
98
|
+
expires_at_ms: number | null;
|
|
99
|
+
}
|
|
100
|
+
export interface ElicitationRequest {
|
|
101
|
+
elicit_id: string;
|
|
102
|
+
source_id: string;
|
|
103
|
+
kind: "disambiguate" | "consent" | "2fa" | "input";
|
|
104
|
+
prompt: string;
|
|
105
|
+
input_schema: Record<string, unknown>;
|
|
106
|
+
expires_at_ms: number;
|
|
107
|
+
status: "pending" | "resolved" | "declined" | "expired";
|
|
108
|
+
response?: Record<string, unknown>;
|
|
109
|
+
}
|
|
110
|
+
export declare class SXPError extends Error {
|
|
111
|
+
readonly code: string;
|
|
112
|
+
readonly recoveryHint?: string;
|
|
113
|
+
constructor(code: string, message: string, recoveryHint?: string);
|
|
114
|
+
toDiagnostic(): string;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Throw from a tool only when it can PROVE nothing was committed (it refused before any remote effect).
|
|
118
|
+
*
|
|
119
|
+
* It is the one failure that lets the kernel refund the call's spend reservation. Anything else a tool throws (a
|
|
120
|
+
* timeout, a broken connection, an unexpected error) does not prove the effect did not happen, so the reservation
|
|
121
|
+
* stays counted against the cap as `uncertain` until the host reconciles it.
|
|
122
|
+
*/
|
|
123
|
+
export declare class NotCommittedError extends SXPError {
|
|
124
|
+
constructor(message?: string, recoveryHint?: string);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* A call with spend at stake failed in a way that does not prove the effect did not happen. The reservation stays
|
|
128
|
+
* counted against the cap. `receipt` identifies it: once the host has checked the external system,
|
|
129
|
+
* `kernel.reconcileSpend(receipt, { committed })` confirms the charge or releases it.
|
|
130
|
+
*/
|
|
131
|
+
export declare class OutcomeUncertainError extends SXPError {
|
|
132
|
+
readonly receipt?: string;
|
|
133
|
+
constructor(message: string, recoveryHint?: string, opts?: {
|
|
134
|
+
receipt?: string;
|
|
135
|
+
cause?: unknown;
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
/** A credential problem a host can fix by obtaining consent, with the scopes it must ask for. */
|
|
139
|
+
export declare class ScopeError extends SXPError {
|
|
140
|
+
readonly requiredScopes: string[];
|
|
141
|
+
readonly target?: string;
|
|
142
|
+
protected constructor(code: "AUTH_REQUIRED" | "INSUFFICIENT_SCOPE", message: string, requiredScopes?: Iterable<unknown>, opts?: {
|
|
143
|
+
target?: string;
|
|
144
|
+
recoveryHint?: string;
|
|
145
|
+
});
|
|
146
|
+
toDict(): {
|
|
147
|
+
code: string;
|
|
148
|
+
required_scopes: string[];
|
|
149
|
+
target: string | null;
|
|
150
|
+
};
|
|
151
|
+
/** Rebuild with the same concrete class, so `instanceof` and the code survive call-scoped scrubbing. */
|
|
152
|
+
scrubbed(scrub: (value: string) => string): ScopeError;
|
|
153
|
+
}
|
|
154
|
+
/** No usable credential for the target. The host should run its own consent flow, then retry. */
|
|
155
|
+
export declare class AuthRequiredError extends ScopeError {
|
|
156
|
+
constructor(message: string, requiredScopes?: Iterable<unknown>, opts?: {
|
|
157
|
+
target?: string;
|
|
158
|
+
recoveryHint?: string;
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/** A credential exists but lacks scopes. The host should request incremental consent, then retry. */
|
|
162
|
+
export declare class InsufficientScopeError extends ScopeError {
|
|
163
|
+
constructor(message: string, requiredScopes?: Iterable<unknown>, opts?: {
|
|
164
|
+
target?: string;
|
|
165
|
+
recoveryHint?: string;
|
|
166
|
+
});
|
|
167
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
export const SXP_VERSION = "2.0.0";
|
|
2
|
+
export const EFFECT_RANK = {
|
|
3
|
+
read: 0, idempotent: 1, soft_hold: 2, best_effort_undo: 3, unverified_write: 4, irreversible: 5,
|
|
4
|
+
};
|
|
5
|
+
export const TAINT_RANK = {
|
|
6
|
+
instruction: 0, trusted_data: 1, untrusted_data: 2,
|
|
7
|
+
};
|
|
8
|
+
export const CLASSIFICATION_RANK = {
|
|
9
|
+
public: 0, internal: 1, confidential: 2, restricted: 3,
|
|
10
|
+
};
|
|
11
|
+
export const HardRail = {
|
|
12
|
+
custom(id, description, validator) {
|
|
13
|
+
return { id, description, kind: "custom", params: {}, validator };
|
|
14
|
+
},
|
|
15
|
+
blockTaintedEgress(opts) {
|
|
16
|
+
return { id: "block_tainted_egress", description: "Block actions after untrusted reads", kind: "block_tainted_egress",
|
|
17
|
+
params: { allow_human_approved: opts?.allowHumanApproved === true } };
|
|
18
|
+
},
|
|
19
|
+
};
|
|
20
|
+
export class SXPError extends Error {
|
|
21
|
+
code;
|
|
22
|
+
recoveryHint;
|
|
23
|
+
constructor(code, message, recoveryHint) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.code = code;
|
|
26
|
+
this.recoveryHint = recoveryHint;
|
|
27
|
+
}
|
|
28
|
+
toDiagnostic() {
|
|
29
|
+
return this.recoveryHint ? `Blocked (${this.code}): ${this.message} ${this.recoveryHint}` : `Blocked (${this.code}): ${this.message}`;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Throw from a tool only when it can PROVE nothing was committed (it refused before any remote effect).
|
|
34
|
+
*
|
|
35
|
+
* It is the one failure that lets the kernel refund the call's spend reservation. Anything else a tool throws (a
|
|
36
|
+
* timeout, a broken connection, an unexpected error) does not prove the effect did not happen, so the reservation
|
|
37
|
+
* stays counted against the cap as `uncertain` until the host reconciles it.
|
|
38
|
+
*/
|
|
39
|
+
export class NotCommittedError extends SXPError {
|
|
40
|
+
constructor(message = "The call was rejected before anything was committed.", recoveryHint) {
|
|
41
|
+
super("NOT_COMMITTED", message, recoveryHint);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* A call with spend at stake failed in a way that does not prove the effect did not happen. The reservation stays
|
|
46
|
+
* counted against the cap. `receipt` identifies it: once the host has checked the external system,
|
|
47
|
+
* `kernel.reconcileSpend(receipt, { committed })` confirms the charge or releases it.
|
|
48
|
+
*/
|
|
49
|
+
export class OutcomeUncertainError extends SXPError {
|
|
50
|
+
receipt;
|
|
51
|
+
constructor(message, recoveryHint, opts) {
|
|
52
|
+
super("OUTCOME_UNCERTAIN", message, recoveryHint);
|
|
53
|
+
this.receipt = opts?.receipt;
|
|
54
|
+
if (opts?.cause !== undefined)
|
|
55
|
+
this.cause = opts.cause;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const MAX_SCOPES = 32;
|
|
59
|
+
/** Scope names come from hosts and upstream servers, so bound them and keep them on one line. */
|
|
60
|
+
function cleanScopes(scopes) {
|
|
61
|
+
const out = new Set();
|
|
62
|
+
for (const scope of Array.from(scopes).slice(0, MAX_SCOPES)) {
|
|
63
|
+
const clean = String(scope).replace(/[\u0000-\u001f\u007f\u0085\u2028\u2029]+/g, " ").trim().slice(0, 256);
|
|
64
|
+
if (clean)
|
|
65
|
+
out.add(clean);
|
|
66
|
+
}
|
|
67
|
+
return [...out].sort();
|
|
68
|
+
}
|
|
69
|
+
/** A credential problem a host can fix by obtaining consent, with the scopes it must ask for. */
|
|
70
|
+
export class ScopeError extends SXPError {
|
|
71
|
+
requiredScopes;
|
|
72
|
+
target;
|
|
73
|
+
constructor(code, message, requiredScopes = [], opts) {
|
|
74
|
+
super(code, message, opts?.recoveryHint ?? "Ask the user to consent to the listed scopes, then retry the call.");
|
|
75
|
+
this.requiredScopes = cleanScopes(requiredScopes);
|
|
76
|
+
this.target = opts?.target === undefined ? undefined : String(opts.target).replace(/[\u0000-\u001f\u007f\u0085\u2028\u2029]+/g, " ").slice(0, 256);
|
|
77
|
+
}
|
|
78
|
+
toDict() {
|
|
79
|
+
return { code: this.code, required_scopes: [...this.requiredScopes], target: this.target ?? null };
|
|
80
|
+
}
|
|
81
|
+
/** Rebuild with the same concrete class, so `instanceof` and the code survive call-scoped scrubbing. */
|
|
82
|
+
scrubbed(scrub) {
|
|
83
|
+
const Rebuilt = this.constructor;
|
|
84
|
+
return new Rebuilt(scrub(this.message), this.requiredScopes.map(scrub), { target: this.target === undefined ? undefined : scrub(this.target), recoveryHint: this.recoveryHint === undefined ? undefined : scrub(this.recoveryHint) });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
/** No usable credential for the target. The host should run its own consent flow, then retry. */
|
|
88
|
+
export class AuthRequiredError extends ScopeError {
|
|
89
|
+
constructor(message, requiredScopes = [], opts) {
|
|
90
|
+
super("AUTH_REQUIRED", message, requiredScopes, opts);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/** A credential exists but lacks scopes. The host should request incremental consent, then retry. */
|
|
94
|
+
export class InsufficientScopeError extends ScopeError {
|
|
95
|
+
constructor(message, requiredScopes = [], opts) {
|
|
96
|
+
super("INSUFFICIENT_SCOPE", message, requiredScopes, opts);
|
|
97
|
+
}
|
|
98
|
+
}
|