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