@axonflow/sdk 9.1.0 → 9.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +238 -22
  2. package/dist/cjs/adapters/langgraph.d.ts.map +1 -1
  3. package/dist/cjs/adapters/langgraph.js +20 -0
  4. package/dist/cjs/adapters/langgraph.js.map +1 -1
  5. package/dist/cjs/authzen.d.ts +353 -0
  6. package/dist/cjs/authzen.d.ts.map +1 -0
  7. package/dist/cjs/authzen.js +901 -0
  8. package/dist/cjs/authzen.js.map +1 -0
  9. package/dist/cjs/client.d.ts +135 -9
  10. package/dist/cjs/client.d.ts.map +1 -1
  11. package/dist/cjs/client.js +397 -30
  12. package/dist/cjs/client.js.map +1 -1
  13. package/dist/cjs/heartbeat.d.ts +55 -4
  14. package/dist/cjs/heartbeat.d.ts.map +1 -1
  15. package/dist/cjs/heartbeat.js +86 -7
  16. package/dist/cjs/heartbeat.js.map +1 -1
  17. package/dist/cjs/index.d.ts +6 -0
  18. package/dist/cjs/index.d.ts.map +1 -1
  19. package/dist/cjs/index.js +55 -1
  20. package/dist/cjs/index.js.map +1 -1
  21. package/dist/cjs/read-identity.d.ts +267 -0
  22. package/dist/cjs/read-identity.d.ts.map +1 -0
  23. package/dist/cjs/read-identity.js +329 -0
  24. package/dist/cjs/read-identity.js.map +1 -0
  25. package/dist/cjs/telemetry.d.ts +176 -13
  26. package/dist/cjs/telemetry.d.ts.map +1 -1
  27. package/dist/cjs/telemetry.js +403 -37
  28. package/dist/cjs/telemetry.js.map +1 -1
  29. package/dist/cjs/types/authzen.gen.d.ts +407 -0
  30. package/dist/cjs/types/authzen.gen.d.ts.map +1 -0
  31. package/dist/cjs/types/authzen.gen.js +804 -0
  32. package/dist/cjs/types/authzen.gen.js.map +1 -0
  33. package/dist/cjs/types/config.d.ts +43 -1
  34. package/dist/cjs/types/config.d.ts.map +1 -1
  35. package/dist/cjs/types/hitl.js +1 -1
  36. package/dist/cjs/types/hitl.js.map +1 -1
  37. package/dist/cjs/version.d.ts +1 -1
  38. package/dist/cjs/version.js +1 -1
  39. package/dist/esm/adapters/langgraph.d.ts.map +1 -1
  40. package/dist/esm/adapters/langgraph.js +20 -0
  41. package/dist/esm/adapters/langgraph.js.map +1 -1
  42. package/dist/esm/authzen.d.ts +353 -0
  43. package/dist/esm/authzen.d.ts.map +1 -0
  44. package/dist/esm/authzen.js +886 -0
  45. package/dist/esm/authzen.js.map +1 -0
  46. package/dist/esm/client.d.ts +135 -9
  47. package/dist/esm/client.d.ts.map +1 -1
  48. package/dist/esm/client.js +397 -30
  49. package/dist/esm/client.js.map +1 -1
  50. package/dist/esm/heartbeat.d.ts +55 -4
  51. package/dist/esm/heartbeat.d.ts.map +1 -1
  52. package/dist/esm/heartbeat.js +85 -7
  53. package/dist/esm/heartbeat.js.map +1 -1
  54. package/dist/esm/index.d.ts +6 -0
  55. package/dist/esm/index.d.ts.map +1 -1
  56. package/dist/esm/index.js +17 -0
  57. package/dist/esm/index.js.map +1 -1
  58. package/dist/esm/read-identity.d.ts +267 -0
  59. package/dist/esm/read-identity.d.ts.map +1 -0
  60. package/dist/esm/read-identity.js +320 -0
  61. package/dist/esm/read-identity.js.map +1 -0
  62. package/dist/esm/telemetry.d.ts +176 -13
  63. package/dist/esm/telemetry.d.ts.map +1 -1
  64. package/dist/esm/telemetry.js +397 -37
  65. package/dist/esm/telemetry.js.map +1 -1
  66. package/dist/esm/types/authzen.gen.d.ts +407 -0
  67. package/dist/esm/types/authzen.gen.d.ts.map +1 -0
  68. package/dist/esm/types/authzen.gen.js +779 -0
  69. package/dist/esm/types/authzen.gen.js.map +1 -0
  70. package/dist/esm/types/config.d.ts +43 -1
  71. package/dist/esm/types/config.d.ts.map +1 -1
  72. package/dist/esm/types/hitl.js +1 -1
  73. package/dist/esm/types/hitl.js.map +1 -1
  74. package/dist/esm/version.d.ts +1 -1
  75. package/dist/esm/version.js +1 -1
  76. package/package.json +1 -1
@@ -0,0 +1,886 @@
1
+ /**
2
+ * AuthZEN-native authorization for the AxonFlow SDK.
3
+ *
4
+ * This is the surface the ADR-065 compatibility plan commits to in all five
5
+ * SDKs. It talks to `POST /api/v1/access/evaluation`, whose wire shape is
6
+ * generated from the platform's canonical contract (see
7
+ * `src/types/authzen.gen.ts`); nothing in this file re-states a field name or
8
+ * an enum value.
9
+ *
10
+ * ## What this replaces, and when
11
+ *
12
+ * Nothing yet. The existing decision surface (`decide`, `explainDecision` and
13
+ * the gateway/proxy methods) stays wire-stable through all of v11 and is not
14
+ * deprecated here. This is the surface to write NEW integrations against,
15
+ * because at v11 the engine behind it becomes the ADR-065 Policy Decision Point
16
+ * with no wire change — an integration written against it migrates once rather
17
+ * than twice. See `docs/AUTHZEN_MIGRATION_DRAFT.md`.
18
+ *
19
+ * ## The one thing worth knowing before you call it
20
+ *
21
+ * The server refuses anything it cannot evaluate rather than evaluating around
22
+ * it. Send a subject property, an unrecognised context member, or an argument
23
+ * beside the query, and you get an `AuthZENRefusal` naming the exact member —
24
+ * not a decision computed without it. That is deliberate: a decision that
25
+ * silently ignored an attribute would tell you the attribute was weighed when
26
+ * it was not, and every audit of that decision would inherit the claim.
27
+ *
28
+ * So treat an `AuthZENRefusal` as "fix the request", and retry only when
29
+ * `refusal.retryable` is true.
30
+ */
31
+ var _a;
32
+ import { AuthenticationError, AxonFlowError } from './errors.js';
33
+ import { AUTHZEN_ERROR_CODE_EVALUATION_UNAVAILABLE, AUTHZEN_ERROR_CODE_INCOMPLETE_EVALUATION, AUTHZEN_ERROR_CODE_MALFORMED_ENVELOPE, AUTHZEN_ERROR_CODE_UNEVALUABLE_ATTRIBUTE, AUTHZEN_OPERATIONAL_STATE_ALLOW, AUTHZEN_OPERATIONAL_STATE_ERROR, AUTHZEN_OPERATIONAL_STATE_VALUES, AUTHZEN_PROFILE_V1, AuthZENSchemaError, validateAuthZENEnvelope, validateAuthZENError, validateAuthZENResponse, } from './types/authzen.gen.js';
34
+ /**
35
+ * The marker every tri-state attribute carries. See {@link AuthZENAttribute}.
36
+ *
37
+ * Exported so a caller building attributes across a serialisation boundary can
38
+ * reconstruct one the SDK will still recognise.
39
+ */
40
+ export const AUTHZEN_ATTRIBUTE_MARKER = '__axonflow_authzen_attribute__';
41
+ /**
42
+ * AUTHZEN_PATH and AUTHZEN_PROFILE_HEADER are GENERATED (./types/authzen.gen) and
43
+ * re-exported here under the names this module has always had. They used to be
44
+ * literals in this file - the SDK's own copy of two strings the platform also
45
+ * wrote by hand - and nothing compared the copies (axonflow-enterprise#3603).
46
+ * The artifact now carries them, so a platform rename is a regenerate-and-diff
47
+ * failure rather than a runtime 404.
48
+ *
49
+ * The SDK always sends the profile header. AuthZEN 1.0's response is a bare
50
+ * boolean, and the four-valued state, the obligations and the approval challenge
51
+ * ride in the response context, which the server returns only to a caller that
52
+ * asked for it by version. This SDK understands the profile, so there is no
53
+ * reason to ask for less than it can read - and a response WITHOUT the context is
54
+ * therefore a protocol failure here rather than a decision with no obligations.
55
+ */
56
+ export { AUTHZEN_PATH, AUTHZEN_PROFILE_HEADER } from './types/authzen.gen.js';
57
+ import { AUTHZEN_PATH, AUTHZEN_PROFILE_HEADER } from './types/authzen.gen.js';
58
+ // ---------------------------------------------------------------------------
59
+ // Why an attribute could not be established.
60
+ // ---------------------------------------------------------------------------
61
+ //
62
+ // These mirror ADR-065's tri-state reason codes so an operator reading an SDK
63
+ // refusal and an operator reading a platform trace use the same words. They are
64
+ // CLIENT-LOCAL: an unknown attribute never reaches the wire, because the whole
65
+ // point is that the request is not sent. The reason is a free-form string on
66
+ // purpose — a closed set hand-copied from the platform would be a transcription
67
+ // that drifts, and it would buy nothing, since nothing on the far side reads it.
68
+ export const AUTHZEN_UNKNOWN_NOT_SUPPLIED = 'attribute_not_supplied';
69
+ export const AUTHZEN_UNKNOWN_RESOLUTION_FAILED = 'resolution_failed';
70
+ export const AUTHZEN_UNKNOWN_STALE = 'stale';
71
+ export const AUTHZEN_UNKNOWN_SCHEMA_MISMATCH = 'schema_mismatch';
72
+ export const AUTHZEN_UNKNOWN_CLOSURE_UNAVAILABLE = 'closure_unavailable';
73
+ export const AUTHZEN_UNKNOWN_CLOSURE_TRUNCATED = 'closure_truncated';
74
+ export const AUTHZEN_UNKNOWN_MALFORMED_VALUE = 'malformed_value';
75
+ export const AUTHZEN_UNKNOWN_REQUIRED_ABSENT = 'required_attribute_absent';
76
+ /**
77
+ * The request was NOT evaluated, and here is the typed reason why.
78
+ *
79
+ * A refusal is not a denial. `decision: false` says the request WAS evaluated
80
+ * and the answer was no; a refusal says no decision exists. Code that treats
81
+ * every error as a deny fails closed — which is safe — but will block traffic
82
+ * that should have been allowed once the request is corrected.
83
+ *
84
+ * `refusedBy` says who made the call. `'gateway'` is a refusal document the
85
+ * server sent; `'client'` is this SDK declining to send a request it can
86
+ * already see will not be evaluated — an attribute the caller could not
87
+ * resolve, or an evaluation with no subject. The code vocabulary is shared
88
+ * because the REASONS are shared: an incomplete evaluation is an incomplete
89
+ * evaluation whoever notices it first.
90
+ */
91
+ export class AuthZENRefusal extends AxonFlowError {
92
+ constructor(code, message, options) {
93
+ super(message, {
94
+ code,
95
+ pointer: options.pointer,
96
+ supported: options.supported,
97
+ requestId: options.requestId,
98
+ refusedBy: options.refusedBy,
99
+ });
100
+ this.name = 'AuthZENRefusal';
101
+ this.code = code;
102
+ this.pointer = options.pointer;
103
+ this.supported = options.supported;
104
+ this.requestId = options.requestId;
105
+ this.refusedBy = options.refusedBy;
106
+ Object.setPrototypeOf(this, AuthZENRefusal.prototype);
107
+ }
108
+ /** Build a refusal from the structured document the server sent. */
109
+ static fromBody(body) {
110
+ return new AuthZENRefusal(body.code, body.message, {
111
+ refusedBy: 'gateway',
112
+ pointer: body.pointer,
113
+ supported: body.supported,
114
+ requestId: body.request_id,
115
+ });
116
+ }
117
+ /**
118
+ * Whether sending the same request again could give a different answer.
119
+ *
120
+ * Only a dependency failure the GATEWAY reported is. Every other code names
121
+ * something about the request itself, which will not change on a retry — so
122
+ * a client that retries on any refusal burns its budget on requests that
123
+ * cannot succeed.
124
+ *
125
+ * A client-side refusal is never retryable, whatever its code: this SDK does
126
+ * not resolve the caller's attributes, so nothing it can do will change the
127
+ * answer. Reading retryability off the code alone would have told a caller to
128
+ * retry an attribute its own resolver failed to produce.
129
+ */
130
+ get retryable() {
131
+ return this.refusedBy === 'gateway' && this.code === AUTHZEN_ERROR_CODE_EVALUATION_UNAVAILABLE;
132
+ }
133
+ }
134
+ /**
135
+ * A 200 whose body this build cannot safely interpret.
136
+ *
137
+ * Deliberately NOT an `AuthZENRefusal`. A refusal carries the server's own
138
+ * typed code from a closed vocabulary the server owns; a response this build
139
+ * cannot read is not something the server said, and dressing it in a server
140
+ * code would tell the caller the gateway refused when it did not. The two also
141
+ * demand different actions: a refusal means fix the request, a protocol error
142
+ * means upgrade the SDK or go and look at the deployment.
143
+ *
144
+ * It is always fail-closed: no decision is returned, so a caller that lets it
145
+ * propagate blocks the operation.
146
+ */
147
+ export class AuthZENProtocolError extends AxonFlowError {
148
+ constructor(message) {
149
+ super(message);
150
+ this.name = 'AuthZENProtocolError';
151
+ Object.setPrototypeOf(this, AuthZENProtocolError.prototype);
152
+ }
153
+ }
154
+ /**
155
+ * One policy-visible attribute in exactly one of three states.
156
+ *
157
+ * `undefined` and `null` cannot express this. ADR-065's model has three:
158
+ *
159
+ * - `known` — the authoritative source returned a value. It is sent.
160
+ * - `absent` — the source successfully established that there is NO value.
161
+ * Absence is a FACT, not a failure, so the member is omitted and the request
162
+ * is sent: a policy that handles absence gets to handle it.
163
+ * - `unknown` — the value could not be established. The request is NOT sent.
164
+ * Sending it would have the gateway evaluate as though the attribute were
165
+ * absent, and the resulting decision — and every audit of it — would record
166
+ * that an attribute was weighed when nobody ever read it. That is the exact
167
+ * failure the whole surface refuses to commit, one hop earlier.
168
+ *
169
+ * Collapsing absent into unknown is the defect this type exists to prevent, and
170
+ * it is not hypothetical: on the platform side an ABSENT `subject.type` was
171
+ * read as the one supported value, so omitting the field bypassed the
172
+ * impersonation refusal that naming it correctly triggered.
173
+ *
174
+ * Where it may be used: inside the ATTRIBUTE bags — `context` on a request or a
175
+ * bulk envelope, and the `properties` bag on a subject, action or resource — at
176
+ * any depth. Not on the structural members (`subject.id`, `action.name`,
177
+ * `resource.type` …): those are the identity of the question being asked, not
178
+ * data about it, and an identity the caller cannot resolve is not an attribute
179
+ * whose absence a policy could evaluate — there is simply no request to make.
180
+ *
181
+ * @example
182
+ * ```typescript
183
+ * AuthZENAttribute.known('acme-corp');
184
+ * AuthZENAttribute.absent();
185
+ * AuthZENAttribute.unknown(AUTHZEN_UNKNOWN_RESOLUTION_FAILED);
186
+ * ```
187
+ */
188
+ export class AuthZENAttribute {
189
+ constructor(state, value, reason) {
190
+ /**
191
+ * The marker, carried as an ordinary ENUMERABLE property.
192
+ *
193
+ * Recognising an attribute by `instanceof` alone has a silent failure in the
194
+ * dangerous direction: a bundler that duplicated this package gives two
195
+ * distinct classes. A non-enumerable Symbol brand fixes that and introduces
196
+ * the same failure by another route - every ordinary copy strips it, so
197
+ * `structuredClone`, a spread, a JSON round trip or a worker boundary turned
198
+ * an UNKNOWN attribute back into ordinary data and SENT it. Measured against
199
+ * a live gateway.
200
+ *
201
+ * Recognising it by SHAPE alone has the mirror failure: a caller's own bag
202
+ * carrying `state`/`value`/`reason` is read as an attribute, and a legitimate
203
+ * request is refused with a message asserting the caller could not establish
204
+ * a value it did establish.
205
+ *
206
+ * An enumerable marker closes both. It survives every ordinary copy, and no
207
+ * caller's data carries it by accident. The Python sibling uses the same key
208
+ * for the same reason.
209
+ */
210
+ this[_a] = true;
211
+ this.state = state;
212
+ this.value = value;
213
+ this.reason = reason;
214
+ }
215
+ /** The source returned this value. */
216
+ static known(value) {
217
+ return new AuthZENAttribute('known', value, '');
218
+ }
219
+ /** The source established that there is no value. */
220
+ static absent() {
221
+ return new AuthZENAttribute('absent', undefined, '');
222
+ }
223
+ /**
224
+ * The value could not be established, for the named reason.
225
+ *
226
+ * The reason is mandatory. An unknown with no reason carries no more than
227
+ * `undefined` already did, and the whole point of the third state is that it
228
+ * says why.
229
+ */
230
+ static unknown(reason) {
231
+ if (!reason || reason.trim() === '') {
232
+ throw new AxonFlowError('an unknown attribute must name why it could not be established; an unknown with ' +
233
+ 'no reason carries no more information than undefined, which is the collapse ' +
234
+ 'this type exists to prevent');
235
+ }
236
+ return new AuthZENAttribute('unknown', undefined, reason);
237
+ }
238
+ /**
239
+ * Whether `value` is a tri-state attribute, however it was copied.
240
+ *
241
+ * See the marker above for why this is neither a bare `instanceof` nor a
242
+ * structural shape check.
243
+ *
244
+ * Recognition keys on the MARKER alone, deliberately, and not on the marker
245
+ * plus a state this build happens to know.
246
+ *
247
+ * Pairing them was a fail-open (#263). A document carrying
248
+ * `__axonflow_authzen_attribute__: true` with any other `state` — a newer
249
+ * producer's, or a corrupted one — was reported as NOT an attribute, and so
250
+ * was walked as ordinary data and sent on the wire, marker key and all. By
251
+ * the surface's own reasoning that document IS an attribute; it is one this
252
+ * build cannot interpret. Evaluating around it records an attribute nobody
253
+ * resolved as one that was weighed, and it leaks the marker convention to the
254
+ * gateway.
255
+ *
256
+ * Recognising it here routes it to the same refusal an `unknown` attribute
257
+ * gets: the resolver matches `known` and `absent` explicitly and refuses
258
+ * everything else, so an unrecognised state (including a missing one) refuses
259
+ * locally, non-retryably, with a pointer to the member — which is what the Go
260
+ * SDK does (sdk-go#210).
261
+ *
262
+ * A marker that is present but not boolean `true` stays data: only a positive
263
+ * self-identification counts, so a caller's own bag with a similarly-named key
264
+ * cannot be turned into a refusal.
265
+ */
266
+ static is(value) {
267
+ if (value instanceof AuthZENAttribute)
268
+ return true;
269
+ if (typeof value !== 'object' || value === null)
270
+ return false;
271
+ const candidate = value;
272
+ return candidate[AUTHZEN_ATTRIBUTE_MARKER] === true;
273
+ }
274
+ }
275
+ _a = AUTHZEN_ATTRIBUTE_MARKER;
276
+ /**
277
+ * The decision, with the readings a Policy Enforcement Point acts on.
278
+ *
279
+ * It implements the generated wire type rather than replacing it, so `decision`
280
+ * and `context` remain exactly what the server sent while the readings below
281
+ * stay in hand-written code the generator never has to know about.
282
+ */
283
+ export class AuthZENDecision {
284
+ constructor(response) {
285
+ this.decision = response.decision;
286
+ this.context = response.context;
287
+ }
288
+ /**
289
+ * Whether the enforcement point may proceed.
290
+ *
291
+ * Read this rather than `decision`. `decision` is AuthZEN 1.0's collapsed
292
+ * boolean; the operational STATE is what the policy engine actually produced,
293
+ * and exactly one state permits execution. Requiring both means a response
294
+ * whose boolean and state disagree can never be read as an allow — and such a
295
+ * response is refused before it gets here anyway, so this is the second of
296
+ * two locks rather than the only one.
297
+ *
298
+ * An allow with an undischarged MANDATORY obligation is not an allow. See
299
+ * `mandatoryObligations`.
300
+ */
301
+ get allowed() {
302
+ return (this.decision === true &&
303
+ this.context !== undefined &&
304
+ this.context.state === AUTHZEN_OPERATIONAL_STATE_ALLOW);
305
+ }
306
+ /**
307
+ * The four-valued operational state.
308
+ *
309
+ * `ERROR` when there is no context. Unreachable via `evaluate`, which refuses
310
+ * a context-less 200 before constructing this — but the type is public and a
311
+ * caller can build one by hand, and the safe reading of an outcome that
312
+ * carries no state is not ALLOW.
313
+ */
314
+ get state() {
315
+ return this.context ? this.context.state : AUTHZEN_OPERATIONAL_STATE_ERROR;
316
+ }
317
+ /**
318
+ * The id of the evaluation that DETERMINED this outcome.
319
+ *
320
+ * For a bulk envelope this is the entry that decided the meet, not the last
321
+ * one evaluated: it is the id an operator looks up to explain the answer.
322
+ */
323
+ get decisionId() {
324
+ return this.context?.decision_id;
325
+ }
326
+ /** The safe machine-readable reason code, when the server sent one. */
327
+ get reason() {
328
+ return this.context?.reason;
329
+ }
330
+ /** The coarse outcome category, when the server sent one. */
331
+ get category() {
332
+ return this.context?.category;
333
+ }
334
+ /** Instructions the enforcement point must discharge before proceeding. */
335
+ get obligations() {
336
+ return this.context?.obligations ?? [];
337
+ }
338
+ /**
339
+ * The obligations that are not optional.
340
+ *
341
+ * A mandatory obligation that cannot be discharged means the operation must
342
+ * NOT proceed, even though `allowed` is true. This SDK cannot make that call
343
+ * for you — whether your enforcement point can discharge a redaction is a
344
+ * fact about your seam, not about the decision — so it gives you the list and
345
+ * stays out of the way.
346
+ */
347
+ get mandatoryObligations() {
348
+ return this.obligations.filter(obligation => obligation.mandatory);
349
+ }
350
+ /** The approval challenge, when the state is CHALLENGE. */
351
+ get approval() {
352
+ return this.context?.approval;
353
+ }
354
+ }
355
+ // ---------------------------------------------------------------------------
356
+ // Tri-state resolution
357
+ // ---------------------------------------------------------------------------
358
+ // RFC 6901. A correlation key containing a slash would otherwise produce a
359
+ // pointer naming a member that does not exist, on the refusal whose entire
360
+ // diagnostic value is the pointer.
361
+ function escapePointerToken(token) {
362
+ return token.replace(/~/g, '~0').replace(/\//g, '~1');
363
+ }
364
+ class Unresolvable extends Error {
365
+ constructor(pointer, reason) {
366
+ super(pointer);
367
+ this.pointer = pointer;
368
+ this.reason = reason;
369
+ }
370
+ }
371
+ // Distinguishes "this member resolved to no value, drop it" from "this member
372
+ // resolved to the value null". They are different: a caller may legitimately
373
+ // send a JSON null, and reusing null for the drop signal would silently rewrite
374
+ // one into the other.
375
+ const DROP = Symbol('authzen.absent');
376
+ /**
377
+ * How deep an attribute bag may nest before the SDK stops walking it.
378
+ *
379
+ * Without a bound, a bag that refers to itself recurses until the engine gives
380
+ * up, and the caller gets a `RangeError` out of `evaluate` - an error type
381
+ * nothing documents and no enforcement point catches. A bound turns that into
382
+ * the same typed refusal every other malformed bag gets. 64 is far past
383
+ * anything a policy attribute path plausibly nests and far short of the stack.
384
+ */
385
+ const MAX_ATTRIBUTE_DEPTH = 64;
386
+ function resolveValue(value, pointer, depth = 0) {
387
+ if (depth > MAX_ATTRIBUTE_DEPTH) {
388
+ throw new Unresolvable(pointer, `nests deeper than ${MAX_ATTRIBUTE_DEPTH} levels, which this SDK will not walk; a bag ` +
389
+ `that refers to itself would otherwise recurse until the engine stopped`);
390
+ }
391
+ if (AuthZENAttribute.is(value)) {
392
+ if (value.state === 'known') {
393
+ // A known attribute may itself hold a container carrying more
394
+ // attributes; resolving the payload keeps the rule uniform rather than
395
+ // depending on how deeply a caller nested its resolver output.
396
+ return resolveValue(value.value, pointer, depth + 1);
397
+ }
398
+ if (value.state === 'absent')
399
+ return DROP;
400
+ throw new Unresolvable(pointer, value.reason);
401
+ }
402
+ if (Array.isArray(value)) {
403
+ // An ABSENT element is dropped from the list rather than left as a hole. A
404
+ // list with a gap in it is a different list, and the index a policy reads
405
+ // would shift under it either way; dropping is the reading that matches
406
+ // "there is no value here".
407
+ const items = [];
408
+ value.forEach((item, index) => {
409
+ const resolved = resolveValue(item, `${pointer}/${index}`, depth + 1);
410
+ if (resolved !== DROP)
411
+ items.push(resolved);
412
+ });
413
+ return items;
414
+ }
415
+ if (typeof value === 'object' && value !== null) {
416
+ const out = {};
417
+ Object.keys(value).forEach(key => {
418
+ const resolved = resolveValue(value[key], `${pointer}/${escapePointerToken(key)}`, depth + 1);
419
+ if (resolved === DROP)
420
+ return;
421
+ // defineProperty, not `out[key] = …`. A plain assignment to the key
422
+ // `__proto__` invokes the inherited setter instead of creating a member,
423
+ // so a context carrying `__proto__` - which `JSON.parse` produces as an
424
+ // ordinary own property - VANISHED from the request with no refusal.
425
+ // That is "mapped or refused, never silently ignored" broken by this SDK,
426
+ // in the one place the gateway cannot see it: the server refuses the
427
+ // member by name, and it never arrived. It reaches the wire now.
428
+ Object.defineProperty(out, key, {
429
+ value: resolved,
430
+ writable: true,
431
+ enumerable: true,
432
+ configurable: true,
433
+ });
434
+ });
435
+ return out;
436
+ }
437
+ return value;
438
+ }
439
+ /**
440
+ * Resolve one attribute bag.
441
+ *
442
+ * ABSENCE DOES NOT CASCADE. A bag whose every member resolved absent is sent as
443
+ * an empty object, not deleted: the bag is the caller's structure and the
444
+ * attributes are the data inside it, and an SDK that removed a container the
445
+ * caller placed would be editing the question rather than resolving the answer.
446
+ *
447
+ * The lever a caller wants sits one level in, which is where the attributes
448
+ * are: `{ args, correlation: AuthZENAttribute.absent() }` drops `correlation`
449
+ * and keeps everything else. Omitting the bag itself is ordinary TypeScript —
450
+ * do not pass it — because a bag that is not part of the question is not an
451
+ * attribute whose absence anything could evaluate.
452
+ */
453
+ function resolveBag(bag, pointer) {
454
+ if (bag === undefined)
455
+ return undefined;
456
+ return resolveValue(bag, pointer);
457
+ }
458
+ // Every member the caller wrote is CARRIED FORWARD, and only the attribute bags
459
+ // are rewritten.
460
+ //
461
+ // These functions used to whitelist-copy `{type, id, properties}`, which meant a
462
+ // member the contract does not declare - `{"type":"gateway","id":"g1",
463
+ // "department":"finance"}` - was deleted here, before the generated validator
464
+ // ran, and the request went out without it and without a refusal. The
465
+ // validator's own documentation says it "catches a member the caller invented
466
+ // before it becomes a 422"; the whitelist made that claim false for exactly
467
+ // those members. Python refuses them at model construction, so this was also a
468
+ // place the two SDKs answered the same request differently.
469
+ //
470
+ // Spreading means an invented member survives to `validateAuthZENEnvelope` and
471
+ // is refused by name, with its pointer.
472
+ function resolveSubject(subject, at) {
473
+ if (!subject)
474
+ return undefined;
475
+ return { ...subject, properties: resolveBag(subject.properties, `${at}/subject/properties`) };
476
+ }
477
+ function resolveAction(action, at) {
478
+ if (!action)
479
+ return undefined;
480
+ return { ...action, properties: resolveBag(action.properties, `${at}/action/properties`) };
481
+ }
482
+ function resolveResource(resource, at) {
483
+ if (!resource)
484
+ return undefined;
485
+ return { ...resource, properties: resolveBag(resource.properties, `${at}/resource/properties`) };
486
+ }
487
+ function resolveRequest(request, at) {
488
+ return {
489
+ ...request,
490
+ subject: resolveSubject(request.subject, at),
491
+ action: resolveAction(request.action, at),
492
+ resource: resolveResource(request.resource, at),
493
+ context: resolveBag(request.context, `${at}/context`),
494
+ };
495
+ }
496
+ /**
497
+ * Return the envelope with every tri-state attribute resolved to the wire.
498
+ *
499
+ * Throws `AuthZENRefusal` with `refusedBy: 'client'` and the JSON Pointer of
500
+ * the offending member when an attribute is UNKNOWN.
501
+ *
502
+ * The pointers match the server's own vocabulary — `/evaluation/...` for a
503
+ * singular envelope, `/evaluations/evaluations/<i>/...` for a plural entry — so
504
+ * a client-side refusal and a gateway refusal name the same member the same
505
+ * way, and a caller does not have to learn two pointer dialects.
506
+ */
507
+ export function resolveEnvelope(envelope) {
508
+ try {
509
+ // BOTH members are resolved when both are present, rather than the first
510
+ // one winning. Python's models refuse a two-member envelope at
511
+ // construction; TypeScript has no such moment, so an early return here
512
+ // would silently DROP the second member and send a request the caller did
513
+ // not write — and the exactly-one-of rule, which lives in the generated
514
+ // validator, would never see the violation it exists to refuse. One
515
+ // implementation of that rule, not two.
516
+ const out = {};
517
+ if (envelope.evaluation !== undefined && envelope.evaluation !== null) {
518
+ out.evaluation = resolveRequest(envelope.evaluation, '/evaluation');
519
+ }
520
+ if (envelope.evaluations !== undefined && envelope.evaluations !== null) {
521
+ const bulk = envelope.evaluations;
522
+ out.evaluations = {
523
+ subject: resolveSubject(bulk.subject, '/evaluations'),
524
+ action: resolveAction(bulk.action, '/evaluations'),
525
+ resource: resolveResource(bulk.resource, '/evaluations'),
526
+ context: resolveBag(bulk.context, '/evaluations/context'),
527
+ evaluations: (bulk.evaluations ?? []).map((entry, index) => resolveRequest(entry, `/evaluations/evaluations/${index}`)),
528
+ };
529
+ }
530
+ if (out.evaluation !== undefined || out.evaluations !== undefined) {
531
+ return out;
532
+ }
533
+ }
534
+ catch (err) {
535
+ if (!(err instanceof Unresolvable))
536
+ throw err;
537
+ throw new AuthZENRefusal(AUTHZEN_ERROR_CODE_UNEVALUABLE_ATTRIBUTE, `the attribute at ${err.pointer} could not be established (${err.reason}), so this ` +
538
+ `request was not sent. The gateway would have evaluated as though the attribute ` +
539
+ `had no value, and the decision — and every audit of it — would record that it ` +
540
+ `was considered when nothing read it. Establish the value, or send it as an ` +
541
+ `explicitly ABSENT attribute if the source proved there is none.`, { refusedBy: 'client', pointer: err.pointer });
542
+ }
543
+ throw new AuthZENRefusal(AUTHZEN_ERROR_CODE_MALFORMED_ENVELOPE, 'the envelope names neither an evaluation nor an evaluations member', { refusedBy: 'client', pointer: '' });
544
+ }
545
+ // ---------------------------------------------------------------------------
546
+ // Completeness
547
+ // ---------------------------------------------------------------------------
548
+ /**
549
+ * Check the one invariant the artifact says it cannot express.
550
+ *
551
+ * The artifact marks every member of `authzen_request` structurally optional,
552
+ * because a plural entry inherits anything it omits from the shared base.
553
+ * Whether the MERGED entry names a subject, an action and a resource is a
554
+ * cross-object property no per-object schema can carry, and the platform's own
555
+ * projection enforces it server-side.
556
+ *
557
+ * This is deliberately the ONLY thing checked here, and it is checked by
558
+ * PRESENCE alone. Everything else the server refuses — which action names are
559
+ * evaluable, which resource types exist, which correlation keys this deployment
560
+ * records — is deployment state the SDK does not have. A client that guessed at
561
+ * it would refuse requests a newer gateway accepts, and the caller would have
562
+ * no way to tell an SDK that is out of date from a request that is wrong.
563
+ */
564
+ function checkComplete(request, base, at) {
565
+ const missing = ['subject', 'action', 'resource'].filter(member => !request[member] && !(base && base[member]));
566
+ if (missing.length > 0) {
567
+ throw new AuthZENRefusal(AUTHZEN_ERROR_CODE_INCOMPLETE_EVALUATION, `after inheriting from the shared base this evaluation still has no ` +
568
+ `${missing.join(', ')}; there is nothing to evaluate`, { refusedBy: 'client', pointer: at });
569
+ }
570
+ const subject = request.subject ?? base?.subject;
571
+ if (subject && subject.id.trim() === '') {
572
+ throw new AuthZENRefusal(AUTHZEN_ERROR_CODE_INCOMPLETE_EVALUATION, 'the subject id must not be blank; a decision has to name the caller it was made for', { refusedBy: 'client', pointer: `${at}/subject/id` });
573
+ }
574
+ }
575
+ /** Refuse an envelope that cannot produce a decision, before the round trip. */
576
+ export function checkEnvelopeComplete(envelope) {
577
+ if (envelope.evaluation) {
578
+ checkComplete(envelope.evaluation, undefined, '/evaluation');
579
+ return;
580
+ }
581
+ if (envelope.evaluations) {
582
+ const bulk = envelope.evaluations;
583
+ const base = {
584
+ subject: bulk.subject,
585
+ action: bulk.action,
586
+ resource: bulk.resource,
587
+ context: bulk.context,
588
+ };
589
+ (bulk.evaluations ?? []).forEach((entry, index) => {
590
+ checkComplete(entry, base, `/evaluations/evaluations/${index}`);
591
+ });
592
+ }
593
+ }
594
+ // ---------------------------------------------------------------------------
595
+ // The response direction
596
+ // ---------------------------------------------------------------------------
597
+ /**
598
+ * Refuse a 200 this build cannot act on.
599
+ *
600
+ * Every check here closes a way for an un-actionable body to be read as an
601
+ * allow. A decoded response that is merely well-typed is not enough: the
602
+ * boolean and the state are two renderings of one outcome, and a build that
603
+ * trusts either alone will act on a decision the other contradicts.
604
+ */
605
+ function validateDecision(response, body) {
606
+ if (!response.context) {
607
+ throw new AuthZENProtocolError(`the server answered without the profile context. This SDK negotiates ` +
608
+ `${AUTHZEN_PROFILE_HEADER}: ${AUTHZEN_PROFILE_V1} on every request, so a response ` +
609
+ `carrying only the boolean means the gateway did not honour the negotiation — an ` +
610
+ `older build, or a proxy that dropped the header. The obligations and the approval ` +
611
+ `challenge that CONSTRAIN an allow ride in that payload, so an allow without it is ` +
612
+ `an allow whose mandatory conditions cannot be read. body=${body}`);
613
+ }
614
+ const context = response.context;
615
+ if (context.profile !== AUTHZEN_PROFILE_V1) {
616
+ throw new AuthZENProtocolError(`the server answered with AuthZEN profile '${context.profile}'; this build can only ` +
617
+ `interpret '${AUTHZEN_PROFILE_V1}'. The obligations and approval challenge that ` +
618
+ `constrain an allow are carried in that payload, so the decision cannot be acted ` +
619
+ `on safely. Upgrade the SDK.`);
620
+ }
621
+ if (!AUTHZEN_OPERATIONAL_STATE_VALUES.includes(context.state)) {
622
+ throw new AuthZENProtocolError(`the server reported the operational state '${context.state}', which this build does ` +
623
+ `not know. Under profile ${AUTHZEN_PROFILE_V1} the state set is closed, so a new ` +
624
+ `value means the response was produced by something this SDK cannot interpret — ` +
625
+ `and a state whose meaning is unknown must not be resolved into permission. ` +
626
+ `body=${body}`);
627
+ }
628
+ const executable = context.state === AUTHZEN_OPERATIONAL_STATE_ALLOW;
629
+ if (response.decision !== executable) {
630
+ throw new AuthZENProtocolError(`the decision boolean (${response.decision}) and the operational state ` +
631
+ `(${context.state}) disagree; exactly one state permits execution, so one of the ` +
632
+ `two renderings of this outcome is wrong and there is no safe way to choose ` +
633
+ `between them. body=${body}`);
634
+ }
635
+ if (!executable && context.obligations && context.obligations.length > 0) {
636
+ throw new AuthZENProtocolError(`the server attached obligations to a ${context.state} decision. Obligations ride ` +
637
+ `only on an executable decision: instructions on a refusal invite an enforcement ` +
638
+ `point to discharge them and proceed. body=${body}`);
639
+ }
640
+ // `schema_version` is deliberately NOT enforced. The PROFILE is the
641
+ // negotiated contract and is checked above; schema_version is carried so a
642
+ // support conversation can name the contract a deployment answered from.
643
+ // Enforcing both would mean the two have to be bumped in lockstep, and this
644
+ // SDK would start refusing decisions over a discrepancy that changes nothing
645
+ // it reads.
646
+ }
647
+ /**
648
+ * Validate the envelope, reporting a schema violation as a TYPED refusal.
649
+ *
650
+ * Shared by `evaluateEnvelope` and `toWire` so the two cannot answer the same
651
+ * malformed envelope differently. `toWire` used to leak the raw
652
+ * `AuthZENSchemaError` while `evaluateEnvelope` converted it, which made the
653
+ * function documented as "the exact document this SDK would send" throw
654
+ * something the send path never throws.
655
+ */
656
+ function validateEnvelopeOrRefuse(resolved) {
657
+ try {
658
+ return validateAuthZENEnvelope(stripUndefined(resolved), '');
659
+ }
660
+ catch (err) {
661
+ if (!(err instanceof AuthZENSchemaError))
662
+ throw err;
663
+ throw new AuthZENRefusal(AUTHZEN_ERROR_CODE_MALFORMED_ENVELOPE, err.message, {
664
+ refusedBy: 'client',
665
+ pointer: err.pointer,
666
+ });
667
+ }
668
+ }
669
+ /**
670
+ * Decode a structured refusal document, or undefined if the body is not one.
671
+ *
672
+ * Decoded LENIENTLY, unlike the decision path, and the asymmetry is deliberate.
673
+ * Strictness on a DECISION is a safety control: an unknown member means the
674
+ * server is speaking a profile this build cannot fully read, and the unread part
675
+ * may be the one that constrains an allow. A refusal constrains nothing - it
676
+ * says no decision exists - so the same strictness buys no safety and costs the
677
+ * caller the whole point of the surface: one additive field on the refusal
678
+ * envelope would degrade every typed refusal into a bare error, losing the code,
679
+ * the pointer, the supported set and the retryable signal on the one path whose
680
+ * entire purpose is to be branchable.
681
+ *
682
+ * Unknown members are dropped here, and the SHAPE is still checked: a body
683
+ * carrying no code or no message is not a refusal document and returns
684
+ * undefined, which sends the caller down the generic-error path rather than
685
+ * fabricating a refusal the server did not make.
686
+ */
687
+ const AUTHZEN_ERROR_MEMBERS = ['code', 'pointer', 'message', 'supported', 'request_id'];
688
+ function decodeRefusal(body) {
689
+ let parsed;
690
+ try {
691
+ parsed = JSON.parse(body);
692
+ }
693
+ catch {
694
+ return undefined;
695
+ }
696
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
697
+ return undefined;
698
+ const known = {};
699
+ AUTHZEN_ERROR_MEMBERS.forEach(member => {
700
+ const value = parsed[member];
701
+ if (value !== undefined)
702
+ known[member] = value;
703
+ });
704
+ try {
705
+ return validateAuthZENError(known, '');
706
+ }
707
+ catch {
708
+ return undefined;
709
+ }
710
+ }
711
+ /**
712
+ * Build an envelope: RESOLVE, check completeness, then validate.
713
+ *
714
+ * The counterpart of the Python sibling's `build_envelope`, and it exists for
715
+ * the same reason: `evaluate` and `evaluateAll` must not each assemble an
716
+ * envelope inline, or the two entry points drift on the order these steps run
717
+ * in - and that order decides which of two problems a caller with two problems
718
+ * is told about.
719
+ */
720
+ export function buildEnvelope(evaluation, evaluations) {
721
+ const envelope = {};
722
+ if (evaluation !== undefined)
723
+ envelope.evaluation = evaluation;
724
+ if (evaluations !== undefined)
725
+ envelope.evaluations = evaluations;
726
+ const resolved = resolveEnvelope(envelope);
727
+ if (resolved.evaluation === undefined || resolved.evaluations === undefined) {
728
+ checkEnvelopeComplete(resolved);
729
+ }
730
+ assertFullyResolved(resolved);
731
+ return validateEnvelopeOrRefuse(resolved);
732
+ }
733
+ /**
734
+ * Run one envelope through `send` and interpret the answer.
735
+ *
736
+ * `send` is the SDK's own transport — the same authenticated fetch wrapper,
737
+ * headers and heartbeat gate every other method uses. It is passed in rather
738
+ * than built here so this module owns the AuthZEN semantics and nothing else; a
739
+ * second transport would be a second place for credentials, timeouts and proxy
740
+ * configuration to drift out of step with the client the user configured.
741
+ */
742
+ export async function evaluateEnvelope(send, envelope) {
743
+ const resolved = resolveEnvelope(envelope);
744
+ // Completeness runs FIRST, so a missing subject/action/resource is reported
745
+ // as `incomplete_evaluation` for both envelope shapes. The generated
746
+ // validator would otherwise reach the singular member's own required set
747
+ // first and report the same mistake under a different code depending on
748
+ // which shape the caller used.
749
+ //
750
+ // Except when the envelope names BOTH members: its fault is not that an
751
+ // evaluation is incomplete, and answering "no action" for a request whose
752
+ // real problem is that it asks two questions at once sends the caller to the
753
+ // wrong member entirely.
754
+ if (resolved.evaluation === undefined || resolved.evaluations === undefined) {
755
+ checkEnvelopeComplete(resolved);
756
+ }
757
+ assertFullyResolved(resolved);
758
+ const wire = validateEnvelopeOrRefuse(resolved);
759
+ const { status, body } = await send(AUTHZEN_PATH, wire, {
760
+ [AUTHZEN_PROFILE_HEADER]: AUTHZEN_PROFILE_V1,
761
+ });
762
+ if (status === 401) {
763
+ // Authentication is answered by the gateway's own middleware, before the
764
+ // route runs, so it never carries an AuthZEN refusal document. Surfacing it
765
+ // as the SDK's existing AuthenticationError keeps one error for "your
766
+ // credentials are wrong" across every method on this client, instead of a
767
+ // second one only AuthZEN callers know to catch.
768
+ throw new AuthenticationError(`Invalid credentials for ${AUTHZEN_PATH}: ${body}`);
769
+ }
770
+ if (status !== 200) {
771
+ const refusal = decodeRefusal(body);
772
+ if (refusal)
773
+ throw AuthZENRefusal.fromBody(refusal);
774
+ // A non-OK body that is not a refusal document still surfaces as an error —
775
+ // never as a decision.
776
+ throw new AxonFlowError(`HTTP ${status} from ${AUTHZEN_PATH}: ${body}`);
777
+ }
778
+ let parsed;
779
+ try {
780
+ parsed = JSON.parse(body);
781
+ }
782
+ catch (err) {
783
+ throw new AuthZENProtocolError(`the decision could not be decoded: ${err.message}. body=${body}`);
784
+ }
785
+ let response;
786
+ try {
787
+ // Strict decoding on the success path. An unknown member in a decision is a
788
+ // server speaking a profile this build does not understand, and quietly
789
+ // dropping it would mean acting on a partial reading of an authorization
790
+ // decision. A TypeScript cast would do none of this — the interface is
791
+ // erased at runtime — which is why the validator is generated.
792
+ response = validateAuthZENResponse(parsed, '');
793
+ }
794
+ catch (err) {
795
+ throw new AuthZENProtocolError(`the decision could not be decoded: ${err.message}. body=${body}`);
796
+ }
797
+ validateDecision(response, body);
798
+ return new AuthZENDecision(response);
799
+ }
800
+ /**
801
+ * Drop `undefined` members so they are not serialised as `null`.
802
+ *
803
+ * `JSON.stringify` already omits an `undefined` property, but the generated
804
+ * validator runs BEFORE serialisation and would otherwise see the key present
805
+ * with an undefined value. Normalising here means the validator, the bytes on
806
+ * the wire and `toWire` below all describe the same document.
807
+ */
808
+ function stripUndefined(value) {
809
+ if (Array.isArray(value))
810
+ return value.map(stripUndefined);
811
+ if (typeof value === 'object' && value !== null) {
812
+ const out = {};
813
+ Object.entries(value).forEach(([key, item]) => {
814
+ if (item === undefined)
815
+ return;
816
+ // defineProperty for the same reason as the resolver: a plain assignment
817
+ // to the key `__proto__` invokes the inherited setter instead of creating
818
+ // a member, so the member would be dropped HERE even after the resolver
819
+ // carried it through. Two places, one rule.
820
+ Object.defineProperty(out, key, {
821
+ value: stripUndefined(item),
822
+ writable: true,
823
+ enumerable: true,
824
+ configurable: true,
825
+ });
826
+ });
827
+ return out;
828
+ }
829
+ return value;
830
+ }
831
+ /**
832
+ * Guarantee no tri-state attribute reaches the wire.
833
+ *
834
+ * `resolveEnvelope` walks every bag the contract declares, so on today's
835
+ * contract this has nothing to catch. It exists for the case that does not
836
+ * announce itself: a container kind added to the artifact later, or an attribute
837
+ * reaching a member the resolver does not visit. Without it that attribute is
838
+ * not a crash - `JSON.stringify` turns the instance into an ordinary
839
+ * `{"state": …, "value": …, "reason": …}` object - so the request is SENT,
840
+ * carrying a resolver's internal shape where the gateway expects a value, and an
841
+ * UNKNOWN attribute reaches the network after all.
842
+ *
843
+ * The Python sibling carries the same control, and had exactly this defect:
844
+ * there the check ran after serialisation and could never fire.
845
+ */
846
+ export function assertFullyResolved(value, path = '', depth = 0) {
847
+ if (depth > MAX_ATTRIBUTE_DEPTH) {
848
+ // Bounded for the same reason the resolver is, and by the same number. Two
849
+ // walkers that disagree on their bound is how a cycle reaching only the
850
+ // unbounded one comes back as a RangeError - the error type the bound
851
+ // exists to remove.
852
+ throw new AuthZENProtocolError(`the structure at ${path || '/'} nests deeper than ${MAX_ATTRIBUTE_DEPTH} levels; ` +
853
+ `this SDK will not walk it, and a structure that refers to itself would ` +
854
+ `otherwise recurse until the engine stopped`);
855
+ }
856
+ if (AuthZENAttribute.is(value)) {
857
+ throw new AuthZENProtocolError(`an unresolved AuthZENAttribute reached the wire at ${path || '/'}. Tri-state ` +
858
+ `attributes are only supported inside the context and properties bags; this one is ` +
859
+ `somewhere the resolver does not reach.`);
860
+ }
861
+ if (Array.isArray(value)) {
862
+ value.forEach((item, index) => assertFullyResolved(item, `${path}/${index}`, depth + 1));
863
+ return;
864
+ }
865
+ if (typeof value === 'object' && value !== null) {
866
+ Object.keys(value).forEach(key => {
867
+ assertFullyResolved(value[key], `${path}/${escapePointerToken(key)}`, depth + 1);
868
+ });
869
+ }
870
+ }
871
+ /**
872
+ * The exact document this SDK would send for `envelope`.
873
+ *
874
+ * Exported for tests and for support: "what did the SDK actually put on the
875
+ * wire" is the first question of every integration problem, and answering it by
876
+ * reading the client's source is how the answer ends up wrong.
877
+ */
878
+ export function toWire(envelope) {
879
+ const resolved = resolveEnvelope(envelope);
880
+ if (resolved.evaluation === undefined || resolved.evaluations === undefined) {
881
+ checkEnvelopeComplete(resolved);
882
+ }
883
+ assertFullyResolved(resolved);
884
+ return validateEnvelopeOrRefuse(resolved);
885
+ }
886
+ //# sourceMappingURL=authzen.js.map