@cotal-ai/core 0.166.3 → 0.168.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/dist/agent-endpoint.d.ts +242 -0
- package/dist/agent-endpoint.d.ts.map +1 -0
- package/dist/agent-endpoint.js +183 -0
- package/dist/agent-endpoint.js.map +1 -0
- package/dist/backup-config.d.ts +2 -2
- package/dist/endpoint-call.d.ts +36 -1
- package/dist/endpoint-call.d.ts.map +1 -1
- package/dist/endpoint-call.js +218 -116
- package/dist/endpoint-call.js.map +1 -1
- package/dist/endpoint-cluster.d.ts +6 -1
- package/dist/endpoint-cluster.d.ts.map +1 -1
- package/dist/endpoint-cluster.js +25 -1
- package/dist/endpoint-cluster.js.map +1 -1
- package/dist/endpoint-delivery-lease.d.ts +184 -0
- package/dist/endpoint-delivery-lease.d.ts.map +1 -0
- package/dist/endpoint-delivery-lease.js +270 -0
- package/dist/endpoint-delivery-lease.js.map +1 -0
- package/dist/endpoint-envelope.d.ts +4 -3
- package/dist/endpoint-envelope.d.ts.map +1 -1
- package/dist/endpoint-envelope.js +19 -2
- package/dist/endpoint-envelope.js.map +1 -1
- package/dist/endpoint-grants.d.ts +31 -1
- package/dist/endpoint-grants.d.ts.map +1 -1
- package/dist/endpoint-grants.js +62 -1
- package/dist/endpoint-grants.js.map +1 -1
- package/dist/endpoint-presence.d.ts +296 -0
- package/dist/endpoint-presence.d.ts.map +1 -0
- package/dist/endpoint-presence.js +784 -0
- package/dist/endpoint-presence.js.map +1 -0
- package/dist/endpoint-provenance.d.ts +11 -0
- package/dist/endpoint-provenance.d.ts.map +1 -0
- package/dist/endpoint-provenance.js +20 -0
- package/dist/endpoint-provenance.js.map +1 -0
- package/dist/endpoint-serve.d.ts +76 -2
- package/dist/endpoint-serve.d.ts.map +1 -1
- package/dist/endpoint-serve.js +332 -147
- package/dist/endpoint-serve.js.map +1 -1
- package/dist/endpoint-service.d.ts +5 -1
- package/dist/endpoint-service.d.ts.map +1 -1
- package/dist/endpoint-service.js +2 -1
- package/dist/endpoint-service.js.map +1 -1
- package/dist/endpoint-subjects.d.ts +76 -2
- package/dist/endpoint-subjects.d.ts.map +1 -1
- package/dist/endpoint-subjects.js +113 -2
- package/dist/endpoint-subjects.js.map +1 -1
- package/dist/endpoint-verbs.d.ts +1 -1
- package/dist/endpoint-verbs.d.ts.map +1 -1
- package/dist/endpoint-verbs.js +1 -1
- package/dist/endpoint-verbs.js.map +1 -1
- package/dist/endpoint.d.ts +132 -188
- package/dist/endpoint.d.ts.map +1 -1
- package/dist/endpoint.js +380 -790
- package/dist/endpoint.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/peer-label.d.ts +6 -5
- package/dist/peer-label.d.ts.map +1 -1
- package/dist/peer-label.js +7 -6
- package/dist/peer-label.js.map +1 -1
- package/dist/provision-jwt.d.ts +518 -0
- package/dist/provision-jwt.d.ts.map +1 -0
- package/dist/provision-jwt.js +641 -0
- package/dist/provision-jwt.js.map +1 -0
- package/dist/provision-permissions.d.ts +72 -0
- package/dist/provision-permissions.d.ts.map +1 -0
- package/dist/provision-permissions.js +2009 -0
- package/dist/provision-permissions.js.map +1 -0
- package/dist/provision-resources.d.ts +66 -0
- package/dist/provision-resources.d.ts.map +1 -0
- package/dist/provision-resources.js +61 -0
- package/dist/provision-resources.js.map +1 -0
- package/dist/provision-server-config.d.ts +115 -0
- package/dist/provision-server-config.d.ts.map +1 -0
- package/dist/provision-server-config.js +169 -0
- package/dist/provision-server-config.js.map +1 -0
- package/dist/provision.d.ts +19 -701
- package/dist/provision.d.ts.map +1 -1
- package/dist/provision.js +4 -2835
- package/dist/provision.js.map +1 -1
- package/dist/subjects.d.ts +3 -2
- package/dist/subjects.d.ts.map +1 -1
- package/dist/subjects.js +10 -2
- package/dist/subjects.js.map +1 -1
- package/dist/types.d.ts +11 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/endpoint-serve.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { spacePrefix } from "./subjects.js";
|
|
2
|
-
import { endpointToken, assertCommandToken, assertLifecycleToken, epClassQueueGroup, deriveReplySubject, parseEpSubject, EP_RAIL_V1, } from "./endpoint-subjects.js";
|
|
2
|
+
import { endpointToken, assertCommandToken, assertLifecycleToken, epClassQueueGroup, deriveReplySubject, parseEpSubject, EP_RAIL_V1, EP_PRINCIPAL_AUTHORITIES, derivePrincipalReplySubject, epPrincipalServeFilter, isPrincipalAuthority, } from "./endpoint-subjects.js";
|
|
3
3
|
import { EpEnvelopeError, parseEndpointRequest, checkRequestSubjectAgreement, assertClassMatches, assertArgsValid, assertOutputValid, EP_BIND_REFUSED, EP_TARGET_UNMAPPED, } from "./endpoint-envelope.js";
|
|
4
|
-
import { compileContract, assertCompiledContract, VOID_SCHEMA } from "./schema-profile.js";
|
|
4
|
+
import { compileContract, assertCompiledContract, singleDocumentClosure, VOID_SCHEMA } from "./schema-profile.js";
|
|
5
5
|
import { assertServeGrantAuthorized } from "./endpoint-service.js";
|
|
6
|
+
import { parseClusterDocument } from "./endpoint-cluster.js";
|
|
6
7
|
import { GOVERNED_TRAIT_URNS, TRAIT_GUARDED, TRAIT_PRICED, assertGovernedSurfaceFor, assertGovernedPreEffect, } from "./endpoint-traits.js";
|
|
7
8
|
import { parseDescribeObservation } from "./endpoint-describe-observation.js";
|
|
9
|
+
import { carriesStoredProvenance } from "./endpoint-provenance.js";
|
|
8
10
|
const describeContexts = new WeakMap();
|
|
9
11
|
/**
|
|
10
12
|
* §13.2/§13.3 INCARNATION ADMISSION — the responder's own answer to "am I the instance this
|
|
@@ -20,7 +22,7 @@ const describeContexts = new WeakMap();
|
|
|
20
22
|
* someone else); a different EPOCH on the same instance is `expired`, as everywhere else.
|
|
21
23
|
*
|
|
22
24
|
* Both refusals carry {@link EP_BIND_REFUSED}, meaning NOTHING RAN — true only while this stays
|
|
23
|
-
* ahead of every effect in `
|
|
25
|
+
* ahead of every effect in `runRequest`, including the governed gate, which may consume a one-use
|
|
24
26
|
* priced proof.
|
|
25
27
|
*/
|
|
26
28
|
function assertBoundIncarnation(env, identity) {
|
|
@@ -126,6 +128,123 @@ async function assertTargetModeAuthorized(env, parsed, opts) {
|
|
|
126
128
|
? `the durable spawner record does not name the caller as ${t.owner}.${t.actor}'s spawner (SPEC 13.2: child mode is a fresh spawner check, never the grant alone)`
|
|
127
129
|
: `the authorization ledger holds no live grant for this caller on ${t.owner}.${t.actor} (SPEC 13.2: ledger mode is a fresh ledger read, fail closed)`);
|
|
128
130
|
}
|
|
131
|
+
const enc = new TextEncoder();
|
|
132
|
+
const dec = new TextDecoder();
|
|
133
|
+
function successReply(id, data) {
|
|
134
|
+
return { v: 1, id, ok: true, ...(data !== undefined ? { data } : {}) };
|
|
135
|
+
}
|
|
136
|
+
function encodeReply(reply) {
|
|
137
|
+
return enc.encode(JSON.stringify(reply));
|
|
138
|
+
}
|
|
139
|
+
/** One request through the shared pipeline: subject parse, envelope parse, subject agreement, the
|
|
140
|
+
* route's addressee check, class match, digest binding, the route's admission, args validation, the
|
|
141
|
+
* route's seam checks, dispatch, the outcome stamp, and the derived reply. */
|
|
142
|
+
async function runRequest(nc, steps, pick, msg) {
|
|
143
|
+
const receivedAtMonotonicMs = performance.now();
|
|
144
|
+
const parsed = steps.parse(msg.subject);
|
|
145
|
+
if (!parsed)
|
|
146
|
+
return; // no sender: MUST NOT be handled (§13.2)
|
|
147
|
+
let env;
|
|
148
|
+
let dispatched = false;
|
|
149
|
+
let returned = false;
|
|
150
|
+
let reply;
|
|
151
|
+
try {
|
|
152
|
+
const original = JSON.parse(dec.decode(msg.data));
|
|
153
|
+
env = parseEndpointRequest(original);
|
|
154
|
+
checkRequestSubjectAgreement(env, parsed);
|
|
155
|
+
// §13.2 FIRST among the semantic gates, and deliberately ahead of the command's own class,
|
|
156
|
+
// contract, and args: whether this instance is the addressee at all is settled before
|
|
157
|
+
// anything is said about the command it names. It also has to precede the governed gate,
|
|
158
|
+
// which can consume a one-use priced proof — the refusal claims nothing ran, so nothing may.
|
|
159
|
+
steps.addressed(env, parsed);
|
|
160
|
+
// A route served by one subscription for every command meets a command it does not serve.
|
|
161
|
+
const def = pick(parsed);
|
|
162
|
+
if (def === undefined)
|
|
163
|
+
throw new EpEnvelopeError("unimplemented", `command "${parsed.command}" is not served here`);
|
|
164
|
+
assertClassMatches(env, def.class);
|
|
165
|
+
bindContract(env, def);
|
|
166
|
+
// §13.2: the command admits only its declared form — before args validation, so an
|
|
167
|
+
// unadmitted form learns nothing about the input contract.
|
|
168
|
+
steps.admit(parsed, def);
|
|
169
|
+
// §13.7: args validate against the input schema BEFORE any effect (bad-request).
|
|
170
|
+
assertArgsValid(def.validate.args, env.args);
|
|
171
|
+
const obligations = await steps.beforeEffect(env, parsed, def);
|
|
172
|
+
const requestId = env.id;
|
|
173
|
+
const ctx = steps.context({
|
|
174
|
+
parsed, env, def, subject: msg.subject, original, receivedAtMonotonicMs, obligations,
|
|
175
|
+
replyFits: (data, ceiling) => {
|
|
176
|
+
const maxPayload = nc.info?.max_payload;
|
|
177
|
+
if (!Number.isSafeInteger(maxPayload) || maxPayload === undefined || maxPayload <= 0)
|
|
178
|
+
throw new EpEnvelopeError("unavailable", "the serving connection has no valid payload ceiling");
|
|
179
|
+
if (!Number.isSafeInteger(ceiling) || ceiling <= 0)
|
|
180
|
+
throw new EpEnvelopeError("failed-precondition", "reply byte ceiling must be a positive safe integer");
|
|
181
|
+
return encodeReply(successReply(requestId, data)).byteLength <= Math.min(ceiling, maxPayload);
|
|
182
|
+
},
|
|
183
|
+
});
|
|
184
|
+
dispatched = true;
|
|
185
|
+
if (!env.replyExpected) {
|
|
186
|
+
await def.handler(ctx);
|
|
187
|
+
return; // cast: the responder MUST NOT reply (§13.5)
|
|
188
|
+
}
|
|
189
|
+
const data = await def.handler(ctx);
|
|
190
|
+
returned = true;
|
|
191
|
+
// §13.7: the reply validates against the output schema BEFORE it is published, under the
|
|
192
|
+
// same fixed budget as args — an invalid reply is a server bug and fails loud, never
|
|
193
|
+
// reaches the caller as success.
|
|
194
|
+
assertOutputValid(def.validate.output, data);
|
|
195
|
+
reply = successReply(env.id, data);
|
|
196
|
+
}
|
|
197
|
+
catch (err) {
|
|
198
|
+
if (env && !env.replyExpected)
|
|
199
|
+
return; // a failed cast stays silent (§13.5 at-most-once)
|
|
200
|
+
const error = err instanceof EpEnvelopeError
|
|
201
|
+
? err.toEpError()
|
|
202
|
+
: { code: "internal", message: err?.message ?? String(err) };
|
|
203
|
+
// §13.3: a refusal raised before dispatch MUST say nothing ran, one raised after the handler
|
|
204
|
+
// returned MUST say it ran, and an omitted outcome reads as `unknown`. Deciding it here, from
|
|
205
|
+
// where the loop stands, covers every check on either side of the handler, including one
|
|
206
|
+
// added later and a body that never parsed into an envelope. A handler's own throw keeps
|
|
207
|
+
// whatever outcome it stated: the loop cannot tell how far it got.
|
|
208
|
+
// The id echoes the request where one parsed; the reply subject is already nonce-scoped
|
|
209
|
+
// to exactly this request's caller, so attribution never rides the echo.
|
|
210
|
+
const stated = !dispatched ? "not-executed" : returned ? "executed" : undefined;
|
|
211
|
+
reply = { v: 1, id: env?.id ?? "invalid", ok: false, error: stated === undefined ? error : { ...error, outcome: stated } };
|
|
212
|
+
}
|
|
213
|
+
// Replacing a reply that cannot be serialized or published changes nothing about whether the
|
|
214
|
+
// command ran, so each replacement below keeps the outcome the replaced reply stated, and a
|
|
215
|
+
// success states `executed`.
|
|
216
|
+
const outcome = reply.ok ? "executed" : reply.error?.outcome;
|
|
217
|
+
let bytes;
|
|
218
|
+
try {
|
|
219
|
+
bytes = encodeReply(reply);
|
|
220
|
+
}
|
|
221
|
+
catch (err) {
|
|
222
|
+
// A non-serializable payload or refusal detail (cycle, BigInt) must not silently drop the reply.
|
|
223
|
+
const fallback = { v: 1, id: reply.id, ok: false, error: { code: "internal", message: `the reply does not serialize: ${err.message}`, ...(outcome !== undefined ? { outcome } : {}) } };
|
|
224
|
+
bytes = enc.encode(JSON.stringify(fallback));
|
|
225
|
+
}
|
|
226
|
+
const replySubject = steps.replySubject(parsed);
|
|
227
|
+
try {
|
|
228
|
+
nc.publish(replySubject, bytes);
|
|
229
|
+
}
|
|
230
|
+
catch (err) {
|
|
231
|
+
// The publish itself refused the message — a reply over the broker's `max_payload` is the
|
|
232
|
+
// reachable case, and a VALID payload can reach here now that the §13.8 validate budget
|
|
233
|
+
// reports instead of refusing (that throw used to stop an oversized output before it was
|
|
234
|
+
// ever encoded, which masked this path). `runRequest()` is invoked from a subscription
|
|
235
|
+
// callback whose rejection is swallowed by design, so an escaping throw here does not surface
|
|
236
|
+
// anywhere: it leaves the caller with SILENCE until its own deadline. That is precisely the
|
|
237
|
+
// outcome the non-serializable branch above already exists to prevent, so it gets the same
|
|
238
|
+
// treatment. The replacement fits by construction — its message is one integer and a
|
|
239
|
+
// bounded string — and `resource-exhausted` matches the §13.4 fact preflight, which refuses
|
|
240
|
+
// an over-`max_payload` acceptance loudly rather than spilling it.
|
|
241
|
+
const refused = {
|
|
242
|
+
v: 1, id: reply.id, ok: false,
|
|
243
|
+
error: { code: "resource-exhausted", message: `the serialized reply is ${bytes.length} bytes and the broker refused it (${err?.message ?? String(err)}); a reply that cannot be published is refused loudly, never dropped`, ...(outcome !== undefined ? { outcome } : {}) },
|
|
244
|
+
};
|
|
245
|
+
nc.publish(replySubject, enc.encode(JSON.stringify(refused)));
|
|
246
|
+
}
|
|
247
|
+
}
|
|
129
248
|
/**
|
|
130
249
|
* Serve an authorized instance's granted commands on the three §13.2 rails, exactly the
|
|
131
250
|
* per-command forms the serve credential grants (§13.9 {@link epServeSubscribeRows}): the class
|
|
@@ -171,6 +290,12 @@ export function serveEndpoint(nc, space, serve, commands, describe, opts = {}) {
|
|
|
171
290
|
assertServeGrantAuthorized(serve); // §13.9: the serve table consumes ONLY registry-authorized serve authority
|
|
172
291
|
if (serve.space !== space)
|
|
173
292
|
throw new Error(`the serve artifact was authorized for space "${serve.space}", not "${space}" (SPEC 13.9)`);
|
|
293
|
+
// SPEC 13.21: a command that declares principal-route authority words is served on that route
|
|
294
|
+
// only. Default deny both ways, as for modes: a service route never serves one.
|
|
295
|
+
for (const cmd of serve.commands) {
|
|
296
|
+
if (serve.surface[cmd].authorities !== undefined)
|
|
297
|
+
throw new Error(`command "${cmd}" declares principal-route authorities; a service route never serves it (SPEC 13.21)`);
|
|
298
|
+
}
|
|
174
299
|
const identity = { endpoint: serve.endpoint, instanceId: serve.instanceId, epoch: serve.epoch };
|
|
175
300
|
const e = endpointToken(identity.endpoint);
|
|
176
301
|
const iId = assertLifecycleToken(identity.instanceId, "instanceId");
|
|
@@ -293,40 +418,15 @@ export function serveEndpoint(nc, space, serve, commands, describe, opts = {}) {
|
|
|
293
418
|
const p = spacePrefix(space);
|
|
294
419
|
const subs = [];
|
|
295
420
|
const pending = new Set();
|
|
296
|
-
const enc = new TextEncoder();
|
|
297
|
-
function successReply(id, data) {
|
|
298
|
-
return { v: 1, id, ok: true, ...(data !== undefined ? { data } : {}) };
|
|
299
|
-
}
|
|
300
|
-
function encodeReply(reply) {
|
|
301
|
-
return enc.encode(JSON.stringify(reply));
|
|
302
|
-
}
|
|
303
|
-
const dec = new TextDecoder();
|
|
304
421
|
const needsDescribeContext = describe.public !== true;
|
|
305
|
-
const
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
let reply;
|
|
314
|
-
try {
|
|
315
|
-
const originalEnvelope = JSON.parse(dec.decode(msg.data));
|
|
316
|
-
env = parseEndpointRequest(originalEnvelope);
|
|
317
|
-
checkRequestSubjectAgreement(env, parsed);
|
|
318
|
-
// §13.2 FIRST among the semantic gates, and deliberately ahead of the command's own class,
|
|
319
|
-
// contract, and args: whether this instance is the addressee at all is settled before
|
|
320
|
-
// anything is said about the command it names. It also has to precede the governed gate,
|
|
321
|
-
// which can consume a one-use priced proof — the refusal claims nothing ran, so nothing may.
|
|
322
|
-
assertBoundIncarnation(env, identity);
|
|
323
|
-
assertClassMatches(env, def.class);
|
|
324
|
-
bindContract(env, def);
|
|
325
|
-
// §13.2: the command admits only its REGISTERED target modes — before args validation,
|
|
326
|
-
// so an unadmitted mode learns nothing about the input contract.
|
|
327
|
-
assertModeAdmitted(parsed, def);
|
|
328
|
-
// §13.7: args validate against the input schema BEFORE any effect (bad-request).
|
|
329
|
-
assertArgsValid(def.validate.args, env.args);
|
|
422
|
+
const steps = {
|
|
423
|
+
parse: (subject) => {
|
|
424
|
+
const parsed = parseEpSubject(subject);
|
|
425
|
+
return parsed && parsed.plane === "request" ? parsed : null;
|
|
426
|
+
},
|
|
427
|
+
addressed: (env) => assertBoundIncarnation(env, identity),
|
|
428
|
+
admit: (parsed, def) => assertModeAdmitted(parsed, def),
|
|
429
|
+
beforeEffect: async (env, parsed, def) => {
|
|
330
430
|
// §13.3/§13.9: target currency resolves against the FRESH mapping immediately before
|
|
331
431
|
// effect — static agreement is not currency; casts have effects too.
|
|
332
432
|
await assertTargetCurrent(env, opts.resolveTarget);
|
|
@@ -338,127 +438,57 @@ export function serveEndpoint(nc, space, serve, commands, describe, opts = {}) {
|
|
|
338
438
|
// the handler.
|
|
339
439
|
if (parsed.target?.mode === "child" || parsed.target?.mode === "ledger")
|
|
340
440
|
await assertTargetCurrent(env, opts.resolveTarget);
|
|
441
|
+
if (!def.governed)
|
|
442
|
+
return undefined;
|
|
341
443
|
// §13.7/§13.9 governed pre-effect gate, for calls AND casts (casts have effects too):
|
|
342
444
|
// guard-then-priced, every anomalous answer refuses, both seams bounded. Construction
|
|
343
445
|
// refused a governed def without enforcement, so the snapshot is present and total here.
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
446
|
+
const { obligations } = await assertGovernedPreEffect({
|
|
447
|
+
enforcement: enforcement,
|
|
448
|
+
endpoint: identity.endpoint,
|
|
449
|
+
command: def.command,
|
|
450
|
+
caller: parsed.caller,
|
|
451
|
+
requestId: env.id,
|
|
452
|
+
space,
|
|
453
|
+
...(env.auth !== undefined ? { auth: env.auth } : {}),
|
|
454
|
+
...(env.deadlineMs !== undefined ? { deadlineMs: env.deadlineMs } : {}),
|
|
455
|
+
});
|
|
456
|
+
// §13.2/§13.3 TOCTOU: the gate AWAITED guard/proof, so a target mapping or child/ledger
|
|
457
|
+
// grant can have rotated since the last currency read — re-resolve currency, re-run the
|
|
458
|
+
// dynamic authorization, and then (because the child/ledger authorization is ITSELF an
|
|
459
|
+
// await the mapping can rotate during) re-resolve currency a FINAL time immediately
|
|
460
|
+
// before the effect. This is the SAME currency → auth → currency discipline the
|
|
461
|
+
// pre-gate path above follows; currency → auth alone leaves the last await unfenced.
|
|
462
|
+
// A one-use priced proof MAY be consumed before this refusal fires: fail-closed, no
|
|
463
|
+
// effect occurs, and the caller retries with a fresh request id and proof.
|
|
464
|
+
await assertTargetCurrent(env, opts.resolveTarget);
|
|
465
|
+
await assertTargetModeAuthorized(env, parsed, opts);
|
|
466
|
+
if (parsed.target?.mode === "child" || parsed.target?.mode === "ledger")
|
|
364
467
|
await assertTargetCurrent(env, opts.resolveTarget);
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
}
|
|
369
|
-
const requestId = env.id;
|
|
468
|
+
return obligations;
|
|
469
|
+
},
|
|
470
|
+
context: ({ parsed, env, def, subject, original, receivedAtMonotonicMs, obligations, replyFits }) => {
|
|
370
471
|
const ctx = {
|
|
371
472
|
identity, subject: parsed, request: env, receivedAtMonotonicMs,
|
|
372
473
|
...(obligations !== undefined ? { obligations } : {}),
|
|
373
|
-
replyFits
|
|
374
|
-
const maxPayload = nc.info?.max_payload;
|
|
375
|
-
if (!Number.isSafeInteger(maxPayload) || maxPayload === undefined || maxPayload <= 0)
|
|
376
|
-
throw new EpEnvelopeError("unavailable", "the serving connection has no valid payload ceiling");
|
|
377
|
-
if (!Number.isSafeInteger(ceiling) || ceiling <= 0)
|
|
378
|
-
throw new EpEnvelopeError("failed-precondition", "reply byte ceiling must be a positive safe integer");
|
|
379
|
-
return encodeReply(successReply(requestId, data)).byteLength <= Math.min(ceiling, maxPayload);
|
|
380
|
-
},
|
|
474
|
+
replyFits,
|
|
381
475
|
};
|
|
382
476
|
if (def.command === "describe" && needsDescribeContext) {
|
|
383
|
-
const observed = parseDescribeObservation(space,
|
|
384
|
-
describeContexts.set(ctx, Object.freeze({ subject
|
|
477
|
+
const observed = parseDescribeObservation(space, subject, original);
|
|
478
|
+
describeContexts.set(ctx, Object.freeze({ subject, fingerprint: observed.fingerprint,
|
|
385
479
|
identity: Object.freeze({ ...identity }), receivedAtMonotonicMs, replyExpected: observed.replyExpected,
|
|
386
480
|
...(observed.deadlineMs === undefined ? {} : { deadlineMs: observed.deadlineMs }) }));
|
|
387
481
|
}
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
return; // cast: the responder MUST NOT reply (§13.5)
|
|
392
|
-
}
|
|
393
|
-
const data = await def.handler(ctx);
|
|
394
|
-
returned = true;
|
|
395
|
-
// §13.7: the reply validates against the output schema BEFORE it is published, under the
|
|
396
|
-
// same fixed budget as args — an invalid reply is a server bug and fails loud, never
|
|
397
|
-
// reaches the caller as success.
|
|
398
|
-
assertOutputValid(def.validate.output, data);
|
|
399
|
-
reply = successReply(env.id, data);
|
|
400
|
-
}
|
|
401
|
-
catch (err) {
|
|
402
|
-
if (env && !env.replyExpected)
|
|
403
|
-
return; // a failed cast stays silent (§13.5 at-most-once)
|
|
404
|
-
const error = err instanceof EpEnvelopeError
|
|
405
|
-
? err.toEpError()
|
|
406
|
-
: { code: "internal", message: err?.message ?? String(err) };
|
|
407
|
-
// §13.3: a refusal raised before dispatch MUST say nothing ran, one raised after the handler
|
|
408
|
-
// returned MUST say it ran, and an omitted outcome reads as `unknown`. Deciding it here, from
|
|
409
|
-
// where the loop stands, covers every check on either side of the handler, including one
|
|
410
|
-
// added later and a body that never parsed into an envelope. A handler's own throw keeps
|
|
411
|
-
// whatever outcome it stated: the loop cannot tell how far it got.
|
|
412
|
-
// The id echoes the request where one parsed; the reply subject is already nonce-scoped
|
|
413
|
-
// to exactly this request's caller, so attribution never rides the echo.
|
|
414
|
-
const stated = !dispatched ? "not-executed" : returned ? "executed" : undefined;
|
|
415
|
-
reply = { v: 1, id: env?.id ?? "invalid", ok: false, error: stated === undefined ? error : { ...error, outcome: stated } };
|
|
416
|
-
}
|
|
417
|
-
// Replacing a reply that cannot be serialized or published changes nothing about whether the
|
|
418
|
-
// command ran, so each replacement below keeps the outcome the replaced reply stated, and a
|
|
419
|
-
// success states `executed`.
|
|
420
|
-
const outcome = reply.ok ? "executed" : reply.error?.outcome;
|
|
421
|
-
let bytes;
|
|
422
|
-
try {
|
|
423
|
-
bytes = encodeReply(reply);
|
|
424
|
-
}
|
|
425
|
-
catch (err) {
|
|
426
|
-
// A non-serializable payload or refusal detail (cycle, BigInt) must not silently drop the reply.
|
|
427
|
-
const fallback = { v: 1, id: reply.id, ok: false, error: { code: "internal", message: `the reply does not serialize: ${err.message}`, ...(outcome !== undefined ? { outcome } : {}) } };
|
|
428
|
-
bytes = enc.encode(JSON.stringify(fallback));
|
|
429
|
-
}
|
|
430
|
-
const replySubject = deriveReplySubject(space, parsed, identity);
|
|
431
|
-
try {
|
|
432
|
-
nc.publish(replySubject, bytes);
|
|
433
|
-
}
|
|
434
|
-
catch (err) {
|
|
435
|
-
// The publish itself refused the message — a reply over the broker's `max_payload` is the
|
|
436
|
-
// reachable case, and a VALID payload can reach here now that the §13.8 validate budget
|
|
437
|
-
// reports instead of refusing (that throw used to stop an oversized output before it was
|
|
438
|
-
// ever encoded, which masked this path). `handle()` is invoked from a subscription callback
|
|
439
|
-
// whose rejection is swallowed by design, so an escaping throw here does not surface
|
|
440
|
-
// anywhere: it leaves the caller with SILENCE until its own deadline. That is precisely the
|
|
441
|
-
// outcome the non-serializable branch above already exists to prevent, so it gets the same
|
|
442
|
-
// treatment. The replacement fits by construction — its message is one integer and a
|
|
443
|
-
// bounded string — and `resource-exhausted` matches the §13.4 fact preflight, which refuses
|
|
444
|
-
// an over-`max_payload` acceptance loudly rather than spilling it.
|
|
445
|
-
const refused = {
|
|
446
|
-
v: 1, id: reply.id, ok: false,
|
|
447
|
-
error: { code: "resource-exhausted", message: `the serialized reply is ${bytes.length} bytes and the broker refused it (${err?.message ?? String(err)}); a reply that cannot be published is refused loudly, never dropped`, ...(outcome !== undefined ? { outcome } : {}) },
|
|
448
|
-
};
|
|
449
|
-
nc.publish(replySubject, enc.encode(JSON.stringify(refused)));
|
|
450
|
-
}
|
|
482
|
+
return ctx;
|
|
483
|
+
},
|
|
484
|
+
replySubject: (parsed) => deriveReplySubject(space, parsed, identity),
|
|
451
485
|
};
|
|
452
486
|
for (const def of defs) {
|
|
453
487
|
const cmd = def.command;
|
|
454
488
|
const cb = (_err, msg) => {
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
for (const [name] of msg.headers ?? [])
|
|
459
|
-
if (/^Nats-(Stream|Subject|Sequence|Time-Stamp)$/i.test(name))
|
|
460
|
-
return;
|
|
461
|
-
const run = handle(def, msg).catch(() => { });
|
|
489
|
+
if (carriesStoredProvenance(msg))
|
|
490
|
+
return;
|
|
491
|
+
const run = runRequest(nc, steps, () => def, msg).catch(() => { });
|
|
462
492
|
pending.add(run);
|
|
463
493
|
void run.finally(() => pending.delete(run));
|
|
464
494
|
};
|
|
@@ -483,6 +513,154 @@ export function serveEndpoint(nc, space, serve, commands, describe, opts = {}) {
|
|
|
483
513
|
},
|
|
484
514
|
};
|
|
485
515
|
}
|
|
516
|
+
/**
|
|
517
|
+
* Serve a principal's own command set on the principal route (SPEC 13.21), on one connection.
|
|
518
|
+
* `Endpoint.servePrincipal` is the entry point an agent uses: it adds the refusals for an open mesh
|
|
519
|
+
* and a static credential, re-binds on every replaced connection and owns the presence field.
|
|
520
|
+
*
|
|
521
|
+
* The cluster is a core constant, not a registration: construction parses it and refuses a command
|
|
522
|
+
* that declares no `authorities`, one that is not ephemeral, one with a governed trait (this route
|
|
523
|
+
* has no governed gate), and a set of defs that is not exactly the cluster's commands with compiled
|
|
524
|
+
* contracts equal to the declared digests. `describe` is built here: it answers the cluster inline,
|
|
525
|
+
* the same answer for every caller, and admits every authority word.
|
|
526
|
+
*
|
|
527
|
+
* The subscription is this process's own head with no queue group. Each request runs the shared
|
|
528
|
+
* pipeline: a head that is not this process is dropped with no reply, the subject's authority word
|
|
529
|
+
* MUST be one the command declares (`permission-denied`), and the reply goes to the subject derived
|
|
530
|
+
* from this process and the parsed caller, never to a transport reply field.
|
|
531
|
+
*/
|
|
532
|
+
export function servePrincipalRoute(nc, space, self, serve) {
|
|
533
|
+
const filter = epPrincipalServeFilter(space, serve.endpoint, self);
|
|
534
|
+
const cluster = parseClusterDocument(serve.cluster);
|
|
535
|
+
const declared = new Map(cluster.commands.map((c) => [c.name, c]));
|
|
536
|
+
for (const c of cluster.commands) {
|
|
537
|
+
if (c.authorities === undefined)
|
|
538
|
+
throw new Error(`command "${c.name}" declares no authorities; a command is served on the principal route only when it lists the words it admits (SPEC 13.21)`);
|
|
539
|
+
if (c.class !== "ephemeral")
|
|
540
|
+
throw new Error(`command "${c.name}" is class "${c.class}"; the principal route serves ephemeral commands only (SPEC 13.21)`);
|
|
541
|
+
const governed = (c.traits ?? []).filter((t) => GOVERNED_TRAIT_URNS.includes(t));
|
|
542
|
+
if (governed.length > 0)
|
|
543
|
+
throw new Error(`command "${c.name}" declares governed trait(s) ${governed.join(", ")}; the principal route has no governed gate, and a governed command is never served unenforced (SPEC 13.7)`);
|
|
544
|
+
}
|
|
545
|
+
const defs = [];
|
|
546
|
+
for (const def of serve.handlers) {
|
|
547
|
+
assertCommandToken(def.command);
|
|
548
|
+
if (def.command === "describe")
|
|
549
|
+
throw new Error("describe is reserved and built from the cluster; a custom describe def is refused (SPEC 13.21)");
|
|
550
|
+
if (defs.some((d) => d.command === def.command))
|
|
551
|
+
throw new Error(`command "${def.command}" is served twice`);
|
|
552
|
+
const decl = declared.get(def.command);
|
|
553
|
+
if (decl === undefined)
|
|
554
|
+
throw new Error(`command "${def.command}" is not in the cluster; the served table is exactly the cluster's commands (SPEC 13.21)`);
|
|
555
|
+
const input = assertCompiledContract(def.contract?.input, `command "${def.command}" input contract`);
|
|
556
|
+
const output = assertCompiledContract(def.contract?.output, `command "${def.command}" output contract`);
|
|
557
|
+
if (input.closureDigest !== decl.inputDigest || output.closureDigest !== decl.outputDigest)
|
|
558
|
+
throw new Error(`command "${def.command}" compiled contracts ${input.closureDigest}/${output.closureDigest} do not equal the declared ${decl.inputDigest}/${decl.outputDigest} (SPEC 13.7)`);
|
|
559
|
+
defs.push({
|
|
560
|
+
command: def.command, class: "ephemeral",
|
|
561
|
+
digests: { input: decl.inputDigest, output: decl.outputDigest },
|
|
562
|
+
validate: { args: input.validate, output: output.validate },
|
|
563
|
+
authorities: new Set(decl.authorities),
|
|
564
|
+
handler: def.handler,
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
for (const c of cluster.commands)
|
|
568
|
+
if (!defs.some((d) => d.command === c.name))
|
|
569
|
+
throw new Error(`command "${c.name}" has no def; a declared command nobody serves is a construction bug (SPEC 13.21)`);
|
|
570
|
+
const answer = deepFreeze({
|
|
571
|
+
public: true,
|
|
572
|
+
descriptor: {
|
|
573
|
+
endpoint: serve.endpoint,
|
|
574
|
+
owner: self.owner,
|
|
575
|
+
protocol: { v: 1 },
|
|
576
|
+
clusters: [{
|
|
577
|
+
digest: singleDocumentClosure(serve.cluster).closureDigest,
|
|
578
|
+
commands: cluster.commands.map((c) => c.name),
|
|
579
|
+
document: structuredClone(serve.cluster),
|
|
580
|
+
}],
|
|
581
|
+
},
|
|
582
|
+
});
|
|
583
|
+
defs.push({
|
|
584
|
+
command: "describe",
|
|
585
|
+
class: "ephemeral",
|
|
586
|
+
validate: describeValidators(),
|
|
587
|
+
authorities: new Set(EP_PRINCIPAL_AUTHORITIES),
|
|
588
|
+
handler: () => answer,
|
|
589
|
+
});
|
|
590
|
+
const byCommand = new Map(defs.map((d) => [d.command, d]));
|
|
591
|
+
const steps = {
|
|
592
|
+
parse: (subject) => {
|
|
593
|
+
const parsed = parseEpSubject(subject);
|
|
594
|
+
if (!parsed || parsed.plane !== "principal-request")
|
|
595
|
+
return null;
|
|
596
|
+
// The addressee check on this route: a request whose head is not this process was not
|
|
597
|
+
// addressed to it and is dropped with no reply. It needs only the subject, so it runs here.
|
|
598
|
+
const h = parsed.principal;
|
|
599
|
+
if (parsed.endpoint !== serve.endpoint || h.owner !== self.owner || h.actor !== self.actor || h.uid !== self.uid || h.runtimeId !== self.runtimeId)
|
|
600
|
+
return null;
|
|
601
|
+
return parsed;
|
|
602
|
+
},
|
|
603
|
+
addressed: () => { },
|
|
604
|
+
admit: (parsed, def) => {
|
|
605
|
+
if (!isPrincipalAuthority(parsed.authority) || !def.authorities.has(parsed.authority))
|
|
606
|
+
throw new EpEnvelopeError("permission-denied", `command "${def.command}" does not admit the "${parsed.authority}" authority; a command serves only the words its declaration lists (SPEC 13.21)`);
|
|
607
|
+
},
|
|
608
|
+
beforeEffect: async () => undefined,
|
|
609
|
+
context: ({ parsed, env, receivedAtMonotonicMs, replyFits }) => ({
|
|
610
|
+
endpoint: serve.endpoint, principal: self, caller: parsed.caller, authority: parsed.authority,
|
|
611
|
+
request: env, receivedAtMonotonicMs, replyFits,
|
|
612
|
+
}),
|
|
613
|
+
replySubject: (parsed) => derivePrincipalReplySubject(space, parsed, self),
|
|
614
|
+
};
|
|
615
|
+
const pending = new Set();
|
|
616
|
+
let refusal;
|
|
617
|
+
let markRefused;
|
|
618
|
+
const refused = new Promise((resolve) => { markRefused = resolve; });
|
|
619
|
+
const sub = nc.subscribe(filter, {
|
|
620
|
+
callback: (err, msg) => {
|
|
621
|
+
if (err) {
|
|
622
|
+
if (refusal === undefined) {
|
|
623
|
+
refusal = new EpEnvelopeError("permission-denied", `the broker refused this process's subscription to its principal-route subject "${filter}": ${err.message}. The credential holds no serve row for it, which a credential minted before the rows existed does not; reconnect after the auth service runs a release that mints them (SPEC 13.21)`);
|
|
624
|
+
markRefused(refusal);
|
|
625
|
+
}
|
|
626
|
+
return;
|
|
627
|
+
}
|
|
628
|
+
if (carriesStoredProvenance(msg))
|
|
629
|
+
return;
|
|
630
|
+
const run = runRequest(nc, steps, (parsed) => byCommand.get(parsed.command), msg).catch(() => { });
|
|
631
|
+
pending.add(run);
|
|
632
|
+
void run.finally(() => pending.delete(run));
|
|
633
|
+
},
|
|
634
|
+
});
|
|
635
|
+
// A refused subscription arrives as the broker's `-ERR`, which it writes before the `PONG` that
|
|
636
|
+
// answers the flush, and nats-core hands it to the callback above before it settles the flush.
|
|
637
|
+
const check = async () => {
|
|
638
|
+
await nc.flush();
|
|
639
|
+
if (refusal !== undefined)
|
|
640
|
+
throw refusal;
|
|
641
|
+
};
|
|
642
|
+
const ready = check();
|
|
643
|
+
ready.catch(() => { });
|
|
644
|
+
return {
|
|
645
|
+
filter,
|
|
646
|
+
ready,
|
|
647
|
+
refused,
|
|
648
|
+
check,
|
|
649
|
+
async stop() {
|
|
650
|
+
const gone = nc.closed().then(() => undefined);
|
|
651
|
+
await Promise.race([sub.drain().catch(() => undefined), gone]);
|
|
652
|
+
await Promise.allSettled([...pending]);
|
|
653
|
+
},
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
function deepFreeze(v) {
|
|
657
|
+
if (v !== null && typeof v === "object") {
|
|
658
|
+
for (const child of Object.values(v))
|
|
659
|
+
deepFreeze(child);
|
|
660
|
+
Object.freeze(v);
|
|
661
|
+
}
|
|
662
|
+
return v;
|
|
663
|
+
}
|
|
486
664
|
/** The declared {@link DescribeAnswer} output schema. The answer's own two fields are closed;
|
|
487
665
|
* the descriptor level is deliberately OPEN to additive evolution (§13.7: protocol.v stays 1
|
|
488
666
|
* across additive changes), with the identity, protocol pin, digest grammar, and non-empty
|
|
@@ -519,17 +697,24 @@ const DESCRIBE_ANSWER_SCHEMA = {
|
|
|
519
697
|
},
|
|
520
698
|
},
|
|
521
699
|
};
|
|
700
|
+
let describeCompiled;
|
|
522
701
|
/** The reserved describe's compiled validators (§13.7): the canonical VOID input (a describe
|
|
523
702
|
* carrying any args is `bad-request` at the same pre-effect seam as every command, BEFORE the
|
|
524
703
|
* authorization-view lookup) and the declared {@link DescribeAnswer} output. Compiled once,
|
|
525
704
|
* lazily, through the same profile compiler every registered contract rides. */
|
|
526
|
-
let describeValidate;
|
|
527
705
|
function describeValidators() {
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
706
|
+
const c = describeContracts();
|
|
707
|
+
return { args: c.input.validate, output: c.output.validate };
|
|
708
|
+
}
|
|
709
|
+
/** The reserved describe's compiled contracts: the canonical void input and the declared
|
|
710
|
+
* {@link DescribeAnswer} output. A caller validates a describe answer with the output, and pins
|
|
711
|
+
* neither digest on the request (§13.7). */
|
|
712
|
+
export function describeContracts() {
|
|
713
|
+
describeCompiled ??= Object.freeze({
|
|
714
|
+
input: compileContract({ root: VOID_SCHEMA }),
|
|
715
|
+
output: compileContract({ root: DESCRIBE_ANSWER_SCHEMA }),
|
|
716
|
+
});
|
|
717
|
+
return describeCompiled;
|
|
533
718
|
}
|
|
534
719
|
/** The reserved describe handler (internal: {@link serveEndpoint} is the only constructor —
|
|
535
720
|
* §13.7 makes describe mandatory and this seam non-replaceable). The authorization policy is
|