axiam-sdk 1.3.0 → 1.4.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 (58) hide show
  1. package/README.md +130 -14
  2. package/dist/amqp/index.d.cts +384 -17
  3. package/dist/amqp/index.d.ts +384 -17
  4. package/dist/amqp/index.js +639 -66
  5. package/dist/amqp/index.js.map +1 -1
  6. package/dist/amqp/index.mjs +631 -67
  7. package/dist/amqp/index.mjs.map +1 -1
  8. package/dist/{authzCore-D-hquWSI.d.ts → authzCore-Ced9zDIV.d.ts} +49 -12
  9. package/dist/{authzCore-CqXzLNmT.d.cts → authzCore-Des2NcKA.d.cts} +49 -12
  10. package/dist/browser/index.d.cts +1 -1
  11. package/dist/browser/index.d.ts +1 -1
  12. package/dist/{client-CaurIxje.d.ts → client-C1kRISf8.d.ts} +15 -1
  13. package/dist/{client-Bp7riC4k.d.cts → client-Dpd864N9.d.cts} +15 -1
  14. package/dist/{cookieJar-oKazfbN1.d.cts → cookieJar-CeH2FZIT.d.cts} +3 -3
  15. package/dist/{cookieJar-DC4GLKrJ.d.ts → cookieJar-DPx9Qtcf.d.ts} +3 -3
  16. package/dist/grpc/index.d.cts +5 -5
  17. package/dist/grpc/index.d.ts +5 -5
  18. package/dist/grpc/index.js +249 -18
  19. package/dist/grpc/index.js.map +1 -1
  20. package/dist/grpc/index.mjs +249 -18
  21. package/dist/grpc/index.mjs.map +1 -1
  22. package/dist/index.d.cts +2 -2
  23. package/dist/index.d.ts +2 -2
  24. package/dist/index.js +29 -3
  25. package/dist/index.js.map +1 -1
  26. package/dist/index.mjs +29 -3
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/{jwks-CTVpOWzI.d.cts → jwks-CQtWokVd.d.cts} +62 -7
  29. package/dist/{jwks-CTVpOWzI.d.ts → jwks-CQtWokVd.d.ts} +62 -7
  30. package/dist/middleware/index.d.cts +220 -43
  31. package/dist/middleware/index.d.ts +220 -43
  32. package/dist/middleware/index.js +587 -149
  33. package/dist/middleware/index.js.map +1 -1
  34. package/dist/middleware/index.mjs +579 -150
  35. package/dist/middleware/index.mjs.map +1 -1
  36. package/dist/nestjs/index.d.cts +18 -4
  37. package/dist/nestjs/index.d.ts +18 -4
  38. package/dist/nestjs/index.js +20 -1
  39. package/dist/nestjs/index.js.map +1 -1
  40. package/dist/nestjs/index.mjs +19 -2
  41. package/dist/nestjs/index.mjs.map +1 -1
  42. package/dist/node/index.d.cts +5 -5
  43. package/dist/node/index.d.ts +5 -5
  44. package/dist/node/index.js +351 -66
  45. package/dist/node/index.js.map +1 -1
  46. package/dist/node/index.mjs +348 -67
  47. package/dist/node/index.mjs.map +1 -1
  48. package/dist/{oidcState-CZhj0MBP.d.ts → oidcState-CzpXPAHF.d.ts} +54 -14
  49. package/dist/{oidcState-EnEJmoF5.d.cts → oidcState-XOYEMQP6.d.cts} +54 -14
  50. package/dist/rest/index.d.cts +3 -3
  51. package/dist/rest/index.d.ts +3 -3
  52. package/dist/rest/index.js +29 -3
  53. package/dist/rest/index.js.map +1 -1
  54. package/dist/rest/index.mjs +29 -3
  55. package/dist/rest/index.mjs.map +1 -1
  56. package/dist/{session-CeIUXgpE.d.cts → session-DoQzoChX.d.cts} +1 -1
  57. package/dist/{session-Beo11VT_.d.ts → session-Z-6IyaSU.d.ts} +1 -1
  58. package/package.json +10 -10
@@ -115,6 +115,9 @@ function verifyPayload(key, payloadJson, signatureHex) {
115
115
  if (received.length !== expected.length) return false;
116
116
  return timingSafeEqual(received, expected);
117
117
  }
118
+ function decodeUtf8Strict(bytes) {
119
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
120
+ }
118
121
 
119
122
  // src/amqp/messages.ts
120
123
  var HMAC_SIGNED_MESSAGE_TYPES = ["AuthzRequest", "AuditEventMessage"];
@@ -168,95 +171,240 @@ var InMemoryNonceStore = class {
168
171
  }
169
172
  }
170
173
  };
171
- function checkReplayProtection(body, skewMs, nonceStore) {
172
- const keyVersion = body.key_version;
173
- if (typeof keyVersion !== "number" || keyVersion < 2) {
174
- return "key_version";
174
+ var UUID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
175
+ var RFC3339 = /^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/;
176
+ function decodesAs(kinds, body) {
177
+ for (const [name, value] of Object.entries(body)) {
178
+ switch (kinds[name]) {
179
+ case "uuid":
180
+ if (typeof value !== "string" || !UUID.test(value)) return false;
181
+ break;
182
+ case "string":
183
+ if (typeof value !== "string") return false;
184
+ break;
185
+ case "u8":
186
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 255) return false;
187
+ break;
188
+ case "timestamp":
189
+ if (typeof value !== "string" || !RFC3339.test(value) || Number.isNaN(Date.parse(value))) return false;
190
+ break;
191
+ case "json":
192
+ if (value === null) return false;
193
+ break;
194
+ default:
195
+ return false;
196
+ }
197
+ }
198
+ return true;
199
+ }
200
+ var EVENT_SPECS = {
201
+ AuthzRequest: {
202
+ layout: ["correlation_id", "tenant_id", "subject_id", "action", "resource_id", "scope?", "key_version", "nonce", "issued_at"],
203
+ kinds: {
204
+ correlation_id: "uuid",
205
+ tenant_id: "uuid",
206
+ subject_id: "uuid",
207
+ action: "string",
208
+ resource_id: "uuid",
209
+ scope: "string",
210
+ key_version: "u8",
211
+ nonce: "uuid",
212
+ issued_at: "timestamp"
213
+ }
214
+ },
215
+ AuditEventMessage: {
216
+ layout: [
217
+ "tenant_id",
218
+ "actor_id",
219
+ "actor_type",
220
+ "action",
221
+ "resource_id?",
222
+ "outcome",
223
+ "ip_address?",
224
+ "metadata?",
225
+ "key_version",
226
+ "nonce",
227
+ "issued_at"
228
+ ],
229
+ kinds: {
230
+ tenant_id: "uuid",
231
+ actor_id: "uuid",
232
+ actor_type: "string",
233
+ action: "string",
234
+ resource_id: "uuid",
235
+ outcome: "string",
236
+ ip_address: "string",
237
+ metadata: "json",
238
+ key_version: "u8",
239
+ nonce: "uuid",
240
+ issued_at: "timestamp"
241
+ }
175
242
  }
176
- const issuedAtRaw = body.issued_at;
177
- if (typeof issuedAtRaw !== "string") {
178
- return "issued_at";
243
+ };
244
+ function checkReplayProtection(body, skewMs, nonceStore) {
245
+ if (body.key_version < 2) return "key_version";
246
+ if (Math.abs(Date.now() - Date.parse(body.issued_at)) > skewMs) return "stale";
247
+ if (nonceStore.checkAndRecord(body.nonce, skewMs * 2)) return "replay";
248
+ return void 0;
249
+ }
250
+ var TRAILING_SIGNATURE = /,"hmac_signature":"([0-9a-fA-F]{64})"\}$/;
251
+ function matchesSignedLayout(names, layout) {
252
+ let i = 0;
253
+ for (const declared of layout) {
254
+ const optional = declared.endsWith("?");
255
+ const name = optional ? declared.slice(0, -1) : declared;
256
+ if (i < names.length && names[i] === name) i += 1;
257
+ else if (!optional) return false;
179
258
  }
180
- const issuedAtMs = Date.parse(issuedAtRaw);
181
- if (Number.isNaN(issuedAtMs) || Math.abs(Date.now() - issuedAtMs) > skewMs) {
182
- return "issued_at";
259
+ return i === names.length;
260
+ }
261
+ function assertConsumeConfig(options, where) {
262
+ if (typeof options?.tenantId !== "string" || options.tenantId === "") {
263
+ throw new TypeError(`${where}: options.tenantId (the consumer's own tenant) is required`);
183
264
  }
184
- const nonce = body.nonce;
185
- if (typeof nonce !== "string" || nonce.length === 0) {
186
- return "nonce";
265
+ if (!Object.prototype.hasOwnProperty.call(EVENT_SPECS, options.eventType)) {
266
+ throw new TypeError(`${where}: options.eventType must be 'AuthzRequest' or 'AuditEventMessage'`);
187
267
  }
188
- if (nonceStore.checkAndRecord(nonce, skewMs * 2)) {
189
- return "nonce";
268
+ }
269
+ function hasDuplicateKey(text) {
270
+ const stack = [];
271
+ let i = 0;
272
+ const n = text.length;
273
+ while (i < n) {
274
+ const c = text[i];
275
+ if (c === '"') {
276
+ let j = i + 1;
277
+ while (j < n && text[j] !== '"') {
278
+ j += text[j] === "\\" ? 2 : 1;
279
+ }
280
+ const raw = text.slice(i, j + 1);
281
+ i = j + 1;
282
+ const top = stack[stack.length - 1];
283
+ if (top !== void 0 && top !== null) {
284
+ let k = i;
285
+ while (k < n && /\s/.test(text[k])) k += 1;
286
+ if (text[k] === ":") {
287
+ const key = JSON.parse(raw);
288
+ if (top.has(key)) return true;
289
+ top.add(key);
290
+ }
291
+ }
292
+ continue;
293
+ }
294
+ if (c === "{") stack.push(/* @__PURE__ */ new Set());
295
+ else if (c === "[") stack.push(null);
296
+ else if (c === "}" || c === "]") stack.pop();
297
+ i += 1;
190
298
  }
191
- return void 0;
299
+ return false;
192
300
  }
193
- async function verifyAndDispatch(channel, msg, signingKey, handler, options = {}) {
194
- const { logger, strict = true } = options;
301
+ async function verifyAndDispatch(channel, msg, signingKey, handler, options) {
302
+ assertConsumeConfig(options, "verifyAndDispatch()");
303
+ const { logger } = options;
304
+ const spec = EVENT_SPECS[options.eventType];
305
+ const refuse = (reason) => {
306
+ try {
307
+ channel.nack(msg, false, false);
308
+ } catch {
309
+ }
310
+ try {
311
+ logger?.warn("axiam_sdk.security", `AMQP event discarded (${reason})`, {
312
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
313
+ exchange: msg.fields.exchange,
314
+ routingKey: msg.fields.routingKey,
315
+ tenantId: options.tenantId,
316
+ reason
317
+ });
318
+ } catch {
319
+ }
320
+ };
321
+ let text;
322
+ try {
323
+ text = decodeUtf8Strict(msg.content);
324
+ } catch {
325
+ refuse("malformed");
326
+ return;
327
+ }
328
+ let whole;
329
+ try {
330
+ whole = JSON.parse(text);
331
+ } catch {
332
+ whole = void 0;
333
+ }
334
+ if (typeof whole !== "object" || whole === null || Array.isArray(whole) || !text.startsWith("{") || !text.endsWith("}")) {
335
+ refuse("malformed");
336
+ return;
337
+ }
338
+ if (!Object.prototype.hasOwnProperty.call(whole, "hmac_signature")) {
339
+ refuse("unsigned");
340
+ return;
341
+ }
342
+ if (hasDuplicateKey(text)) {
343
+ refuse("malformed");
344
+ return;
345
+ }
346
+ const trailing = TRAILING_SIGNATURE.exec(msg.content.toString("latin1"));
347
+ const sig = whole.hmac_signature;
348
+ if (trailing === null || sig !== trailing[1]) {
349
+ refuse("malformed");
350
+ return;
351
+ }
352
+ const canonical = Buffer.concat([msg.content.subarray(0, trailing.index), Buffer.from("}", "ascii")]);
195
353
  let body;
196
354
  try {
197
- body = JSON.parse(msg.content.toString("utf8"));
355
+ body = JSON.parse(decodeUtf8Strict(canonical));
198
356
  } catch {
199
- logger?.warn("axiam_sdk.security", "AMQP message body failed JSON parse; nacking without requeue", {
200
- exchange: msg.fields.exchange,
201
- routingKey: msg.fields.routingKey
202
- });
203
- channel.nack(msg, false, false);
357
+ refuse("malformed");
204
358
  return;
205
359
  }
206
- const sig = typeof body.hmac_signature === "string" ? body.hmac_signature : void 0;
207
- delete body.hmac_signature;
208
- const canonical = Buffer.from(JSON.stringify(body), "utf8");
209
- let verified;
210
- if (sig !== void 0) {
211
- verified = verifyPayload(signingKey, canonical, sig);
212
- } else {
213
- verified = !strict;
360
+ if (!matchesSignedLayout(Object.keys(body), spec.layout)) {
361
+ refuse("malformed");
362
+ return;
214
363
  }
215
- if (!verified) {
216
- const tenantContext = {};
217
- if (typeof body.tenant_id === "string") tenantContext.tenantId = body.tenant_id;
218
- logger?.warn("axiam_sdk.security", "AMQP HMAC verification failed; nacking without requeue", {
219
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
220
- exchange: msg.fields.exchange,
221
- routingKey: msg.fields.routingKey,
222
- ...tenantContext
223
- });
224
- channel.nack(msg, false, false);
364
+ if (!verifyPayload(signingKey, canonical, trailing[1])) {
365
+ refuse("signature");
366
+ return;
367
+ }
368
+ const keyVersionToken = /,"key_version":([^,]*),"nonce":"[^"]*","issued_at":"[^"]*"\}$/.exec(
369
+ canonical.toString("utf8")
370
+ );
371
+ if (keyVersionToken === null || !/^\d+$/.test(keyVersionToken[1]) || !decodesAs(spec.kinds, body)) {
372
+ refuse("malformed");
225
373
  return;
226
374
  }
227
375
  const skewMs = options.skewMs ?? DEFAULT_REPLAY_SKEW_MS;
228
376
  const nonceStore = options.nonceStore ?? new InMemoryNonceStore();
229
- const replayRejectReason = checkReplayProtection(body, skewMs, nonceStore);
230
- if (replayRejectReason) {
231
- const tenantContext = {};
232
- if (typeof body.tenant_id === "string") tenantContext.tenantId = body.tenant_id;
233
- logger?.warn(
234
- "axiam_sdk.security",
235
- `AMQP v2 replay-protection check failed (${replayRejectReason}); nacking without requeue`,
236
- {
237
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
238
- exchange: msg.fields.exchange,
239
- routingKey: msg.fields.routingKey,
240
- ...tenantContext
241
- }
242
- );
243
- channel.nack(msg, false, false);
377
+ const gate = checkReplayProtection(body, skewMs, nonceStore);
378
+ if (gate !== void 0) {
379
+ refuse(gate);
244
380
  return;
245
381
  }
246
382
  try {
247
383
  await handler(body);
248
384
  } catch (err) {
249
- logger?.warn("axiam_sdk.security", "AMQP handler threw; nacking without requeue", {
250
- exchange: msg.fields.exchange,
251
- routingKey: msg.fields.routingKey,
252
- error: err instanceof Error ? err.message : String(err)
253
- });
254
- channel.nack(msg, false, false);
385
+ try {
386
+ channel.nack(msg, false, false);
387
+ } catch {
388
+ }
389
+ try {
390
+ logger?.warn("axiam_sdk.security", "AMQP handler threw; nacking without requeue", {
391
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
392
+ exchange: msg.fields.exchange,
393
+ routingKey: msg.fields.routingKey,
394
+ tenantId: options.tenantId,
395
+ error: err instanceof Error ? err.name : "non-Error"
396
+ });
397
+ } catch {
398
+ }
255
399
  return;
256
400
  }
257
- channel.ack(msg);
401
+ try {
402
+ channel.ack(msg);
403
+ } catch {
404
+ }
258
405
  }
259
- async function consume(amqpUrl, queue, signingKey, handler, options = {}) {
406
+ async function consume(amqpUrl, queue, signingKey, handler, options) {
407
+ assertConsumeConfig(options, "consume()");
260
408
  const socketOptions = buildAmqpConnectOptions(amqpUrl, options.tls, "consume() amqpUrl");
261
409
  const connection = await amqp.connect(amqpUrl, socketOptions);
262
410
  const channel = await connection.createChannel();
@@ -267,9 +415,425 @@ async function consume(amqpUrl, queue, signingKey, handler, options = {}) {
267
415
  };
268
416
  await channel.consume(queue, (msg) => {
269
417
  if (!msg) return;
270
- void verifyAndDispatch(channel, msg, signingKey.expose(), handler, sharedOptions);
418
+ verifyAndDispatch(channel, msg, signingKey.expose(), handler, sharedOptions).catch(() => {
419
+ try {
420
+ channel.nack(msg, false, false);
421
+ } catch {
422
+ }
423
+ try {
424
+ sharedOptions.logger?.warn("axiam_sdk.security", "AMQP event discarded (malformed)", {
425
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
426
+ exchange: msg.fields.exchange,
427
+ routingKey: msg.fields.routingKey,
428
+ tenantId: sharedOptions.tenantId,
429
+ reason: "malformed"
430
+ });
431
+ } catch {
432
+ }
433
+ });
271
434
  });
272
435
  }
436
+ var TRAILING_SIGNATURE2 = /,"hmac_signature":"([0-9a-fA-F]{64})"\}$/;
437
+ var isString = (value) => typeof value === "string";
438
+ var AuthzResponseVerifier = class {
439
+ #subkey;
440
+ #tenantId;
441
+ #tenantConfigured;
442
+ #replyQueue;
443
+ #logger;
444
+ /** correlation_id → nonce of each outstanding request. */
445
+ #outstanding = /* @__PURE__ */ new Map();
446
+ /** @param options the tenant, its subkey, and the reply queue's name. */
447
+ constructor(options) {
448
+ this.#subkey = options.subkey;
449
+ this.#tenantConfigured = options.tenantId;
450
+ this.#tenantId = options.tenantId.toLowerCase();
451
+ this.#replyQueue = options.replyQueue;
452
+ this.#logger = options.logger;
453
+ }
454
+ /**
455
+ * Register a published request whose answer is awaited. Its `tenant_id`
456
+ * must be this verifier's tenant.
457
+ *
458
+ * @throws RangeError when the request names another tenant.
459
+ */
460
+ expect(request) {
461
+ if (request.tenant_id.toLowerCase() !== this.#tenantId) {
462
+ throw new RangeError("AuthzResponseVerifier.expect: the request names another tenant");
463
+ }
464
+ this.#outstanding.set(request.correlation_id, request.nonce);
465
+ }
466
+ /** Stop waiting for `correlationId` (for example on the caller's own timeout). */
467
+ forget(correlationId) {
468
+ this.#outstanding.delete(correlationId);
469
+ }
470
+ /** Number of requests still awaiting an answer. */
471
+ get pending() {
472
+ return this.#outstanding.size;
473
+ }
474
+ /**
475
+ * Verify one received response body (CONTRACT.md §8 rules 1–4). On
476
+ * acceptance the matching request is retired, so a second response for it
477
+ * is dropped. On any failure nothing is retired — the genuine answer may
478
+ * still arrive — and a security event is logged without either signature.
479
+ *
480
+ * @param delivery where the body was read from; the security event names
481
+ * its exchange and routing key (§8 rule 4). {@link settle} passes it.
482
+ * Without it the event reports `''` and `options.replyQueue` (`''` when
483
+ * that is not set either).
484
+ */
485
+ verify(body, delivery) {
486
+ let whole;
487
+ let text;
488
+ try {
489
+ text = decodeUtf8Strict(body);
490
+ whole = JSON.parse(text);
491
+ } catch {
492
+ return this.#refuse("malformed", delivery);
493
+ }
494
+ if (typeof whole !== "object" || whole === null || Array.isArray(whole) || !text.startsWith("{")) {
495
+ return this.#refuse("malformed", delivery);
496
+ }
497
+ if (!Object.prototype.hasOwnProperty.call(whole, "hmac_signature")) {
498
+ return this.#refuse("unsigned", delivery);
499
+ }
500
+ const match = TRAILING_SIGNATURE2.exec(body.toString("latin1"));
501
+ if (!match) {
502
+ return this.#refuse("malformed", delivery);
503
+ }
504
+ const canonical = Buffer.concat([body.subarray(0, match.index), Buffer.from("}", "ascii")]);
505
+ let parsed;
506
+ try {
507
+ parsed = JSON.parse(decodeUtf8Strict(canonical));
508
+ } catch {
509
+ return this.#refuse("malformed", delivery);
510
+ }
511
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
512
+ return this.#refuse("malformed", delivery);
513
+ }
514
+ const r = parsed;
515
+ if (!isString(r.correlation_id) || typeof r.allowed !== "boolean" || !isString(r.tenant_id) || !isString(r.nonce) || Object.prototype.hasOwnProperty.call(r, "hmac_signature")) {
516
+ return this.#refuse("malformed", delivery);
517
+ }
518
+ const expected = createHmac("sha256", this.#subkey.expose()).update(canonical).digest();
519
+ const received = Buffer.from(match[1], "hex");
520
+ if (received.length !== expected.length || !timingSafeEqual(received, expected)) {
521
+ return this.#refuse("signature", delivery);
522
+ }
523
+ if (r.reason !== void 0 && !isString(r.reason) || r.reason_code !== void 0 && !isString(r.reason_code)) {
524
+ return this.#refuse("malformed", delivery);
525
+ }
526
+ if (r.tenant_id.toLowerCase() !== this.#tenantId) {
527
+ return this.#refuse("tenant", delivery);
528
+ }
529
+ const nonce = this.#outstanding.get(r.correlation_id);
530
+ if (nonce === void 0 || nonce !== r.nonce) {
531
+ return this.#refuse("unknown_request", delivery);
532
+ }
533
+ this.#outstanding.delete(r.correlation_id);
534
+ return {
535
+ accepted: true,
536
+ response: {
537
+ correlation_id: r.correlation_id,
538
+ allowed: r.allowed,
539
+ ...r.reason !== void 0 ? { reason: r.reason } : {},
540
+ ...r.reason_code !== void 0 ? { reason_code: r.reason_code } : {},
541
+ tenant_id: r.tenant_id,
542
+ nonce: r.nonce
543
+ }
544
+ };
545
+ }
546
+ /**
547
+ * {@link verify} a delivery read from a queue, then ack it when accepted
548
+ * and nack it **without requeue** when discarded (§8 rule 4).
549
+ */
550
+ settle(channel, msg) {
551
+ const verdict = this.verify(msg.content, {
552
+ exchange: msg.fields.exchange,
553
+ routingKey: msg.fields.routingKey
554
+ });
555
+ try {
556
+ if (verdict.accepted) {
557
+ channel.ack(msg);
558
+ } else {
559
+ channel.nack(msg, false, false);
560
+ }
561
+ } catch {
562
+ }
563
+ return verdict;
564
+ }
565
+ #refuse(reason, delivery) {
566
+ try {
567
+ this.#logger?.warn(
568
+ "axiam_sdk.security",
569
+ `AMQP authorization response discarded (${reason})`,
570
+ this.#eventContext(reason, delivery)
571
+ );
572
+ } catch {
573
+ }
574
+ return { accepted: false, reason };
575
+ }
576
+ /**
577
+ * The §8 discard event (consumer obligation 4): exactly timestamp, exchange,
578
+ * routing key, the requester's OWN tenant and the reason code. Nothing read
579
+ * from the body, no signature value, no nonce.
580
+ */
581
+ #eventContext(reason, delivery) {
582
+ const routingKey = delivery !== void 0 ? delivery.routingKey : this.#replyQueue ?? "";
583
+ return {
584
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
585
+ exchange: delivery !== void 0 ? delivery.exchange : "",
586
+ routingKey,
587
+ tenantId: this.#tenantConfigured,
588
+ reason
589
+ };
590
+ }
591
+ };
592
+ var AUTHZ_REQUEST_QUEUE = "axiam.authz.request";
593
+ var AUTHZ_KEY_VERSION = 2;
594
+ var DEFAULT_AUTHZ_TIMEOUT_MS = 1e4;
595
+ var SERVER_QUEUE_PREFIX = "axiam.";
596
+ var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
597
+ var UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
598
+ var MAX_TIMEOUT_MS = 2 ** 31 - 1;
599
+ function assertTimeout(timeoutMs) {
600
+ if (timeoutMs === void 0) return;
601
+ if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMEOUT_MS) {
602
+ throw new RangeError(`axiam: authz requester timeoutMs must be a finite number in (0, ${MAX_TIMEOUT_MS}]`);
603
+ }
604
+ }
605
+ var AuthzRequesterClosedError = class extends Error {
606
+ constructor() {
607
+ super("axiam: authz requester is closed");
608
+ this.name = "AuthzRequesterClosedError";
609
+ }
610
+ };
611
+ function normalizeUuid(value, what) {
612
+ if (!UUID_RE.test(value)) {
613
+ throw new TypeError(`axiam: ${what} is not a UUID`);
614
+ }
615
+ return value.toLowerCase();
616
+ }
617
+ function buildAuthzRequest(subkey, fields) {
618
+ for (const s of [fields.action, ...fields.scope !== void 0 ? [fields.scope] : []]) {
619
+ if (typeof s !== "string" || LONE_SURROGATE.test(s)) {
620
+ throw new TypeError("axiam: action and scope must be well-formed strings");
621
+ }
622
+ }
623
+ const body = {
624
+ correlation_id: normalizeUuid(fields.correlationId, "correlation_id"),
625
+ tenant_id: normalizeUuid(fields.tenantId, "tenant_id"),
626
+ subject_id: normalizeUuid(fields.subjectId, "subject_id"),
627
+ action: fields.action,
628
+ resource_id: normalizeUuid(fields.resourceId, "resource_id")
629
+ };
630
+ if (fields.scope !== void 0) body.scope = fields.scope;
631
+ body.key_version = AUTHZ_KEY_VERSION;
632
+ body.nonce = normalizeUuid(fields.nonce, "nonce");
633
+ body.issued_at = fields.issuedAt.toISOString().replace(/\.\d{3}Z$/, "Z");
634
+ const canonical = JSON.stringify(body);
635
+ const signature = createHmac("sha256", subkey).update(Buffer.from(canonical, "utf8")).digest("hex");
636
+ return Buffer.from(`${canonical.slice(0, -1)},"hmac_signature":"${signature}"}`, "utf8");
637
+ }
638
+ var AuthzRequester = class {
639
+ #channel;
640
+ #options;
641
+ #tenantId;
642
+ #replyTo;
643
+ #verifier;
644
+ #pending = /* @__PURE__ */ new Map();
645
+ #consumerTag;
646
+ #closed = false;
647
+ #onClose;
648
+ /** @internal Use {@link createAuthzRequester}. */
649
+ constructor(channel, options, tenantId, replyTo) {
650
+ this.#channel = channel;
651
+ this.#options = options;
652
+ this.#tenantId = tenantId;
653
+ this.#replyTo = replyTo;
654
+ this.#verifier = new AuthzResponseVerifier({
655
+ subkey: options.subkey,
656
+ tenantId,
657
+ replyQueue: replyTo,
658
+ ...options.logger !== void 0 ? { logger: options.logger } : {}
659
+ });
660
+ }
661
+ /** The private reply queue every request names in `reply_to`. */
662
+ get replyTo() {
663
+ return this.#replyTo;
664
+ }
665
+ /** Number of checks still awaiting an answer. */
666
+ get pending() {
667
+ return this.#pending.size;
668
+ }
669
+ /** @internal Start consuming the reply queue. */
670
+ async start(onClose) {
671
+ this.#onClose = onClose;
672
+ const { consumerTag } = await this.#channel.consume(this.#replyTo, (msg) => this.#handle(msg), {
673
+ noAck: false,
674
+ exclusive: true
675
+ });
676
+ this.#consumerTag = consumerTag;
677
+ }
678
+ /**
679
+ * Ask whether `subjectId` may perform `action` on `resourceId` and wait for
680
+ * the verified answer. A response that fails verification or binding is
681
+ * discarded and the check keeps waiting for the genuine one: a failed
682
+ * verification is never an allow and never completes the request.
683
+ *
684
+ * @throws AuthzRequesterClosedError once {@link close} was called or the reply queue went away.
685
+ * @throws NetworkError on a publish failure or when no verified answer arrives in time.
686
+ */
687
+ async check(input) {
688
+ if (this.#closed) {
689
+ throw new AuthzRequesterClosedError();
690
+ }
691
+ const correlationId = randomUUID();
692
+ const nonce = randomUUID();
693
+ const body = buildAuthzRequest(this.#options.subkey.expose(), {
694
+ correlationId,
695
+ tenantId: this.#tenantId,
696
+ subjectId: input.subjectId,
697
+ action: input.action,
698
+ resourceId: input.resourceId,
699
+ ...input.scope !== void 0 ? { scope: input.scope } : {},
700
+ nonce,
701
+ issuedAt: (this.#options.now ?? (() => /* @__PURE__ */ new Date()))()
702
+ });
703
+ return new Promise((resolve, reject2) => {
704
+ const timeoutMs = this.#options.timeoutMs ?? DEFAULT_AUTHZ_TIMEOUT_MS;
705
+ let timer;
706
+ const onAbort = () => finish(() => reject2(new NetworkError("axiam: authz check aborted")));
707
+ const finish = (settle) => {
708
+ if (timer !== void 0) clearTimeout(timer);
709
+ input.signal?.removeEventListener("abort", onAbort);
710
+ this.#pending.delete(correlationId);
711
+ this.#verifier.forget(correlationId);
712
+ settle();
713
+ };
714
+ this.#pending.set(correlationId, {
715
+ resolve: (d) => finish(() => resolve(d)),
716
+ reject: (e) => finish(() => reject2(e))
717
+ });
718
+ this.#verifier.expect({ correlation_id: correlationId, nonce, tenant_id: this.#tenantId });
719
+ timer = setTimeout(
720
+ () => finish(() => reject2(new NetworkError("axiam: no verified authz answer before the timeout"))),
721
+ timeoutMs
722
+ );
723
+ if (input.signal) {
724
+ if (input.signal.aborted) {
725
+ onAbort();
726
+ return;
727
+ }
728
+ input.signal.addEventListener("abort", onAbort, { once: true });
729
+ }
730
+ try {
731
+ this.#channel.sendToQueue(AUTHZ_REQUEST_QUEUE, body, {
732
+ correlationId,
733
+ replyTo: this.#replyTo,
734
+ contentType: "application/json"
735
+ });
736
+ } catch (err) {
737
+ finish(() => reject2(new NetworkError("axiam: failed to publish authz request", err)));
738
+ }
739
+ });
740
+ }
741
+ /**
742
+ * Stop accepting answers: every outstanding and later check rejects with
743
+ * {@link AuthzRequesterClosedError}. The reply queue is exclusive and
744
+ * auto-delete, so the broker removes it with its consumer. Idempotent.
745
+ */
746
+ async close() {
747
+ if (this.#closed) return;
748
+ this.#closed = true;
749
+ for (const p of [...this.#pending.values()]) {
750
+ p.reject(new AuthzRequesterClosedError());
751
+ }
752
+ if (this.#consumerTag !== void 0 && this.#channel.cancel) {
753
+ try {
754
+ await this.#channel.cancel(this.#consumerTag);
755
+ } catch {
756
+ }
757
+ }
758
+ await this.#onClose?.();
759
+ }
760
+ #handle(msg) {
761
+ if (msg === null) {
762
+ void this.close();
763
+ return;
764
+ }
765
+ try {
766
+ if (this.#closed) {
767
+ this.#channel.nack(msg, false, false);
768
+ return;
769
+ }
770
+ const verdict = this.#verifier.settle(this.#channel, msg);
771
+ if (!verdict.accepted) {
772
+ return;
773
+ }
774
+ const pending = this.#pending.get(verdict.response.correlation_id);
775
+ pending?.resolve({
776
+ allowed: verdict.response.allowed,
777
+ ...verdict.response.reason !== void 0 ? { reason: verdict.response.reason } : {},
778
+ ...verdict.response.reason_code !== void 0 ? { reasonCode: verdict.response.reason_code } : {}
779
+ });
780
+ } catch {
781
+ }
782
+ }
783
+ };
784
+ async function createAuthzRequester(channel, options) {
785
+ return createOn(channel, options);
786
+ }
787
+ async function createOn(channel, options, onClose) {
788
+ const tenantId = normalizeUuid(options.tenantId, "authz requester tenant_id");
789
+ if (options.subkey.expose().length === 0) {
790
+ throw new TypeError("axiam: authz requester needs the tenant subkey");
791
+ }
792
+ assertTimeout(options.timeoutMs);
793
+ const { queue } = await channel.assertQueue("", { exclusive: true, autoDelete: true, durable: false });
794
+ if (typeof queue !== "string" || queue.length === 0 || queue.startsWith(SERVER_QUEUE_PREFIX)) {
795
+ throw new Error(`axiam: authz reply queue ${JSON.stringify(queue)} is not a private queue`);
796
+ }
797
+ const requester = new AuthzRequester(channel, options, tenantId, queue);
798
+ await requester.start(onClose);
799
+ return requester;
800
+ }
801
+ async function connectAuthzRequester(amqpUrl, options) {
802
+ const socketOptions = buildAmqpConnectOptions(amqpUrl, options.tls, "connectAuthzRequester() amqpUrl");
803
+ const connection = await amqp.connect(amqpUrl, socketOptions);
804
+ let requester;
805
+ let gone = false;
806
+ const onError = (source) => (err) => {
807
+ options.logger?.warn("axiam_sdk.amqp", `AMQP authz requester ${source} error`, {
808
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
809
+ reason: err instanceof Error ? err.message : "unknown"
810
+ });
811
+ };
812
+ const onGone = () => {
813
+ gone = true;
814
+ void requester?.close();
815
+ };
816
+ connection.on("error", onError("connection"));
817
+ connection.on("close", onGone);
818
+ try {
819
+ const channel = await connection.createChannel();
820
+ channel.on("error", onError("channel"));
821
+ channel.on("close", onGone);
822
+ requester = await createOn(channel, options, async () => {
823
+ try {
824
+ await connection.close();
825
+ } catch {
826
+ }
827
+ });
828
+ if (gone) {
829
+ await requester.close();
830
+ }
831
+ return requester;
832
+ } catch (err) {
833
+ await connection.close().catch(() => void 0);
834
+ throw err;
835
+ }
836
+ }
273
837
 
274
838
  // src/amqp/reactor/registry.ts
275
839
  var REACTOR_EVENTS = {
@@ -745,6 +1309,6 @@ function reactorHandlers(...groups) {
745
1309
  };
746
1310
  }
747
1311
 
748
- export { DEFAULT_REACTOR_MAX_IN_FLIGHT, DEFAULT_REACTOR_TIMEOUT_MS, DEFAULT_REPLAY_SKEW_MS, EVENT_REGISTRY, HMAC_SIGNED_MESSAGE_TYPES, InMemoryNonceStore, MAX_REACTOR_TIMEOUT_MS, MIN_REACTOR_TIMEOUT_MS, REACTOR_EVENTS, REACTOR_EXCHANGE, REACTOR_FRESHNESS_SKEW_MS, REACTOR_KEY_VERSION, Sensitive, abstain, allow, assertAmqpsUrl, buildAmqpConnectOptions, buildReactorReply, canonicalEventBytes, canonicalReplyBytes, chainedPatch, consume, defaultFailurePolicyFor, deny, dispatchReactorDelivery, eventSpec, hookableEvents, isFresh, mutate, patchFieldAllowed, reactorHandlers, reactorQueueName, reactorReplySignatureValid, reactorRoutingKey, reactorServe, requireStepUp, signPayload, signReactorReply, signingKeyFingerprint, specForEvent, toChronoRfc3339, verifyAndDispatch, verifyEvent, verifyPayload };
1312
+ export { AUTHZ_REQUEST_QUEUE, AuthzRequester, AuthzRequesterClosedError, AuthzResponseVerifier, DEFAULT_AUTHZ_TIMEOUT_MS, DEFAULT_REACTOR_MAX_IN_FLIGHT, DEFAULT_REACTOR_TIMEOUT_MS, DEFAULT_REPLAY_SKEW_MS, EVENT_REGISTRY, HMAC_SIGNED_MESSAGE_TYPES, InMemoryNonceStore, MAX_REACTOR_TIMEOUT_MS, MIN_REACTOR_TIMEOUT_MS, REACTOR_EVENTS, REACTOR_EXCHANGE, REACTOR_FRESHNESS_SKEW_MS, REACTOR_KEY_VERSION, Sensitive, abstain, allow, assertAmqpsUrl, buildAmqpConnectOptions, buildAuthzRequest, buildReactorReply, canonicalEventBytes, canonicalReplyBytes, chainedPatch, connectAuthzRequester, consume, createAuthzRequester, decodeUtf8Strict, defaultFailurePolicyFor, deny, dispatchReactorDelivery, eventSpec, hookableEvents, isFresh, mutate, patchFieldAllowed, reactorHandlers, reactorQueueName, reactorReplySignatureValid, reactorRoutingKey, reactorServe, requireStepUp, signPayload, signReactorReply, signingKeyFingerprint, specForEvent, toChronoRfc3339, verifyAndDispatch, verifyEvent, verifyPayload };
749
1313
  //# sourceMappingURL=index.mjs.map
750
1314
  //# sourceMappingURL=index.mjs.map