@7h3/protocol 0.5.4 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -107,7 +107,7 @@ async function b(e, t) {
107
107
  async function x(e, t, n) {
108
108
  return ue(e, t, n);
109
109
  }
110
- async function me(e, t, n = "local-dev-key") {
110
+ async function S(e, t, n = "local-dev-key") {
111
111
  let r = await se(_(e), t);
112
112
  return {
113
113
  ...e,
@@ -118,13 +118,13 @@ async function me(e, t, n = "local-dev-key") {
118
118
  }
119
119
  };
120
120
  }
121
- async function S(e, t) {
121
+ async function C(e, t) {
122
122
  return !e.signature || e.signature.alg !== "HS256" ? !1 : ce(_({
123
123
  header: e.header,
124
124
  body: e.body
125
125
  }), e.signature.value, t);
126
126
  }
127
- async function C(e, t, n = "local-ed25519-key") {
127
+ async function w(e, t, n = "local-ed25519-key") {
128
128
  let r = await le(_(e), t);
129
129
  return {
130
130
  ...e,
@@ -135,21 +135,21 @@ async function C(e, t, n = "local-ed25519-key") {
135
135
  }
136
136
  };
137
137
  }
138
- async function w(e, t) {
138
+ async function T(e, t) {
139
139
  return !e.signature || e.signature.alg !== "ED25519" ? !1 : ue(_({
140
140
  header: e.header,
141
141
  body: e.body
142
142
  }), e.signature.value, t);
143
143
  }
144
- async function he(e, t) {
145
- return !e.signature || e.signature.alg !== t.alg ? !1 : t.alg === "HS256" ? S(e, t.secret) : w(e, t.publicKey);
144
+ async function me(e, t) {
145
+ return !e.signature || e.signature.alg !== t.alg ? !1 : t.alg === "HS256" ? C(e, t.secret) : T(e, t.publicKey);
146
146
  }
147
- async function ge(e, t, n) {
147
+ async function he(e, t, n) {
148
148
  return !t || t.alg !== n.alg ? !1 : n.alg === "HS256" ? fe(e, t.value, n.secret) : x(e, t.value, n.publicKey);
149
149
  }
150
- var _e = 864e5;
151
- function T(e, t = Date.now()) {
152
- let n = [], r = e.header ?? {}, i = e.body ?? {}, a = typeof r.version == "string" ? r.version : "", o = typeof r.messageId == "string" ? r.messageId : "", s = typeof r.sender == "string" ? r.sender : "", c = typeof r.nonce == "string" ? r.nonce : "", l = typeof r.timestampMs == "number" ? r.timestampMs : 0, u = typeof r.ttlMs == "number" ? r.ttlMs : 0, d = typeof i.content == "string" ? i.content : "";
150
+ var ge = 864e5, _e = 3e4;
151
+ function E(e, t = Date.now()) {
152
+ let n = [], r = e.header ?? {}, i = e.body ?? {}, a = typeof r.version == "string" ? r.version : "", o = typeof r.messageId == "string" ? r.messageId : "", s = typeof r.sender == "string" ? r.sender : "", c = typeof r.nonce == "string" ? r.nonce : "", l = typeof r.timestampMs == "number" && Number.isFinite(r.timestampMs) ? r.timestampMs : NaN, u = typeof r.ttlMs == "number" && Number.isFinite(r.ttlMs) ? r.ttlMs : NaN, d = typeof i.content == "string" ? i.content : "";
153
153
  return a !== "7h3/0.1" && n.push({
154
154
  level: "error",
155
155
  message: `Unsupported protocol version '${a}'`
@@ -162,13 +162,22 @@ function T(e, t = Date.now()) {
162
162
  }), c.trim() || n.push({
163
163
  level: "error",
164
164
  message: "Missing nonce — replay protection requires a unique nonce per message"
165
- }), u <= 0 && n.push({
165
+ }), Number.isFinite(l) || n.push({
166
+ level: "error",
167
+ message: "timestampMs must be a finite number"
168
+ }), Number.isFinite(u) ? (u <= 0 && n.push({
166
169
  level: "error",
167
170
  message: "ttlMs must be greater than zero"
168
171
  }), u > 864e5 && n.push({
169
172
  level: "error",
170
- message: `ttlMs exceeds maximum allowed ${_e} ms`
171
- }), l + u < t && n.push({
173
+ message: `ttlMs exceeds maximum allowed ${ge} ms`
174
+ })) : n.push({
175
+ level: "error",
176
+ message: "ttlMs must be a finite number"
177
+ }), Number.isFinite(l) && l > t + 3e4 && n.push({
178
+ level: "error",
179
+ message: `timestampMs is more than ${_e} ms in the future`
180
+ }), Number.isFinite(l) && Number.isFinite(u) && l + u < t && n.push({
172
181
  level: "error",
173
182
  message: "Message TTL expired"
174
183
  }), d.trim() || n.push({
@@ -176,7 +185,7 @@ function T(e, t = Date.now()) {
176
185
  message: "Empty content payload"
177
186
  }), n;
178
187
  }
179
- function E(e) {
188
+ function D(e) {
180
189
  let t = e.nowMs ?? Date.now();
181
190
  return {
182
191
  header: {
@@ -223,10 +232,10 @@ function je(e) {
223
232
  function Me(e) {
224
233
  return e === 1 ? "HS256" : e === 2 ? "ED25519" : null;
225
234
  }
226
- function D(e) {
235
+ function O(e) {
227
236
  return { bytes: ke(e) };
228
237
  }
229
- function O(e) {
238
+ function k(e) {
230
239
  return e ? 4 + e.bytes.byteLength : 0;
231
240
  }
232
241
  var Ne = class {
@@ -289,7 +298,7 @@ var Ne = class {
289
298
  }
290
299
  };
291
300
  function Fe(e) {
292
- let t = (e.header.recipient ? Se : 0) | (e.body.capability ? Ce : 0) | (e.body.correlationId ? we : 0) | (e.signature ? Te : 0), n = D(e.header.version), r = D(e.header.messageId), i = D(e.header.sender), a = D(e.header.nonce), o = D(e.body.intent), s = D(e.body.content), c = e.header.recipient ? D(e.header.recipient) : null, l = e.body.capability ? D(e.body.capability) : null, u = e.body.correlationId ? D(e.body.correlationId) : null, d = e.signature ? D(e.signature.keyId) : null, f = e.signature ? D(e.signature.value) : null, p = new Ne(ye.byteLength + 1 + 1 + 8 + 4 + O(n) + O(r) + O(i) + O(a) + O(o) + O(s) + O(c) + O(l) + O(u) + +!!e.signature + O(d) + O(f));
301
+ let t = (e.header.recipient ? Se : 0) | (e.body.capability ? Ce : 0) | (e.body.correlationId ? we : 0) | (e.signature ? Te : 0), n = O(e.header.version), r = O(e.header.messageId), i = O(e.header.sender), a = O(e.header.nonce), o = O(e.body.intent), s = O(e.body.content), c = e.header.recipient ? O(e.header.recipient) : null, l = e.body.capability ? O(e.body.capability) : null, u = e.body.correlationId ? O(e.body.correlationId) : null, d = e.signature ? O(e.signature.keyId) : null, f = e.signature ? O(e.signature.value) : null, p = new Ne(ye.byteLength + 1 + 1 + 8 + 4 + k(n) + k(r) + k(i) + k(a) + k(o) + k(s) + k(c) + k(l) + k(u) + +!!e.signature + k(d) + k(f));
293
302
  return p.writeBytes(ye), p.writeU8(be), p.writeU8(t), p.writeU64(e.header.timestampMs), p.writeU32(e.header.ttlMs), p.writeString(n), p.writeString(r), p.writeString(i), p.writeString(a), p.writeString(o), p.writeString(s), c && p.writeString(c), l && p.writeString(l), u && p.writeString(u), e.signature && d && f && (p.writeU8(je(e.signature.alg)), p.writeString(d), p.writeString(f)), p.finish();
294
303
  }
295
304
  function Ie(e, t = {}) {
@@ -430,7 +439,7 @@ var Le = class {
430
439
  this.items[t] = l, this.items[r] = c, t = r;
431
440
  }
432
441
  }
433
- }, k = class {
442
+ }, A = class {
434
443
  entries = /* @__PURE__ */ new Map();
435
444
  maxEntries;
436
445
  expiries = new Le();
@@ -467,16 +476,18 @@ var Le = class {
467
476
  consume(e, t = Date.now()) {
468
477
  this.prune(t);
469
478
  let n = this.makeKey(e), r = this.entries.get(n);
470
- if (r && r > t) return {
479
+ if (r !== void 0 && (!Number.isFinite(r) || r > t)) return {
471
480
  ok: !1,
472
481
  reason: "Replay detected for sender/messageId/nonce"
473
482
  };
474
- this.entries.size >= this.maxEntries && this.evictOne();
475
483
  let i = e.header.timestampMs + e.header.ttlMs;
476
- return this.entries.set(n, i), this.expiries.push({
484
+ return Number.isFinite(i) ? (this.entries.size >= this.maxEntries && this.evictOne(), this.entries.set(n, i), this.expiries.push({
477
485
  key: n,
478
486
  expiresAt: i
479
- }), { ok: !0 };
487
+ }), { ok: !0 }) : {
488
+ ok: !1,
489
+ reason: "Cannot track replay protection for a non-finite timestampMs/ttlMs"
490
+ };
480
491
  }
481
492
  consumeMany(e, t = Date.now()) {
482
493
  return e.map((e) => this.consume(e, t));
@@ -491,9 +502,12 @@ var Le = class {
491
502
  }
492
503
  async consume(e, t = Date.now()) {
493
504
  let n = this.makeKey(e), r = e.header.timestampMs + e.header.ttlMs;
494
- return await this.store.reserve(n, r, t) ? { ok: !0 } : {
505
+ return Number.isFinite(r) ? await this.store.reserve(n, r, t) ? { ok: !0 } : {
495
506
  ok: !1,
496
507
  reason: "Replay detected for sender/messageId/nonce"
508
+ } : {
509
+ ok: !1,
510
+ reason: "Cannot track replay protection for a non-finite timestampMs/ttlMs"
497
511
  };
498
512
  }
499
513
  async consumeMany(e, t = Date.now()) {
@@ -627,13 +641,13 @@ function Ge(e) {
627
641
  };
628
642
  }
629
643
  }
630
- function Ke(e, t = "json") {
644
+ function j(e, t = "json") {
631
645
  return t === "binary" ? Fe(e) : JSON.stringify(t === "compact" ? We(e) : e);
632
646
  }
633
- function qe(e, t = "compact") {
647
+ function Ke(e, t = "compact") {
634
648
  return JSON.stringify(t === "compact" ? e.map(We) : e);
635
649
  }
636
- function Je(e) {
650
+ function qe(e) {
637
651
  try {
638
652
  let t = JSON.parse(e);
639
653
  return Array.isArray(t) ? t.map((e) => He(e) ? {
@@ -670,7 +684,7 @@ function Je(e) {
670
684
  }];
671
685
  }
672
686
  }
673
- async function A(e, t = {}) {
687
+ async function M(e, t = {}) {
674
688
  let n = t.nowMs ?? Date.now(), r = t.requireSignature ?? !0, i = t.maxClockSkewMs ?? 3e4;
675
689
  async function a(e) {
676
690
  t.telemetry && await t.telemetry({
@@ -688,7 +702,7 @@ async function A(e, t = {}) {
688
702
  phase: "decoded",
689
703
  sender: o.envelope.header.sender,
690
704
  messageId: o.envelope.header.messageId
691
- }), o.envelope.header.timestampMs > n + i) {
705
+ }), !Number.isFinite(o.envelope.header.timestampMs) || o.envelope.header.timestampMs > n + i) {
692
706
  let e = "Message timestamp exceeds allowed clock skew", t = [{
693
707
  level: "error",
694
708
  message: e
@@ -704,7 +718,7 @@ async function A(e, t = {}) {
704
718
  envelope: o.envelope
705
719
  };
706
720
  }
707
- let s = [...T(o.envelope, n)];
721
+ let s = [...E(o.envelope, n)];
708
722
  if (s.some((e) => e.level === "error")) return await a({
709
723
  phase: "rejected_validation",
710
724
  sender: o.envelope.header.sender,
@@ -761,7 +775,7 @@ async function A(e, t = {}) {
761
775
  diagnostics: s,
762
776
  envelope: o.envelope
763
777
  };
764
- if (!await ge(_({
778
+ if (!await he(_({
765
779
  header: o.envelope.header,
766
780
  body: o.envelope.body
767
781
  }), o.envelope.signature, c)) return s.push({
@@ -803,7 +817,7 @@ async function A(e, t = {}) {
803
817
  envelope: o.envelope
804
818
  };
805
819
  }
806
- async function Ye(e, t = {}) {
820
+ async function Je(e, t = {}) {
807
821
  let n = Math.max(1, Math.floor(t.batchConcurrency ?? Infinity));
808
822
  return (async (e) => {
809
823
  let r = Array(e.length), i = 0, a = Number.isFinite(n) ? Math.min(n, e.length) : e.length;
@@ -812,48 +826,48 @@ async function Ye(e, t = {}) {
812
826
  let n = i;
813
827
  i += 1;
814
828
  let a = e[n];
815
- a && typeof a == "object" && "ok" in a && "diagnostics" in a && "envelope" in a ? r[n] = a : r[n] = await A(a, t);
829
+ a && typeof a == "object" && "ok" in a && "diagnostics" in a && "envelope" in a ? r[n] = a : r[n] = await M(a, t);
816
830
  }
817
831
  })), await t.telemetry?.({
818
832
  phase: "batch_summary",
819
833
  nowMs: t.nowMs ?? Date.now(),
820
834
  reason: `items=${e.length};accepted=${r.filter((e) => e?.ok).length}`
821
835
  }), r;
822
- })(typeof e == "string" ? Je(e).map((e) => e.ok && e.envelope ? e.envelope : e) : e);
836
+ })(typeof e == "string" ? qe(e).map((e) => e.ok && e.envelope ? e.envelope : e) : e);
823
837
  }
824
- var Xe = class {
838
+ var Ye = class {
825
839
  options;
826
840
  constructor(e = {}) {
827
841
  this.options = {
828
842
  ...e,
829
- replayCache: e.replayCache ?? new k(),
843
+ replayCache: e.replayCache ?? new A(),
830
844
  verificationMaterialCache: e.verificationMaterialCache ?? new ze()
831
845
  };
832
846
  }
833
847
  receive(e, t = Date.now()) {
834
- return A(e, {
848
+ return M(e, {
835
849
  ...this.options,
836
850
  nowMs: t
837
851
  });
838
852
  }
839
853
  receiveBatch(e, t = Date.now()) {
840
- return Ye(e, {
854
+ return Je(e, {
841
855
  ...this.options,
842
856
  nowMs: t
843
857
  });
844
858
  }
845
859
  };
846
- async function Ze(e) {
847
- return me(E(e), e.secret, e.keyId);
860
+ async function Xe(e) {
861
+ return S(D(e), e.secret, e.keyId);
848
862
  }
849
863
  //#endregion
850
864
  //#region src/protocolCapabilities.ts
851
- var Qe = [
865
+ var Ze = [
852
866
  "binary",
853
867
  "compact",
854
868
  "json"
855
- ], $e = ["fast", "receipt"];
856
- function et(e) {
869
+ ], Qe = ["fast", "receipt"];
870
+ function $e(e) {
857
871
  return {
858
872
  agent: e.agent,
859
873
  capabilities: e.capabilities ?? [],
@@ -862,10 +876,10 @@ function et(e) {
862
876
  ackModes: e.ackModes ?? ["receipt"]
863
877
  };
864
878
  }
865
- function tt(e) {
879
+ function et(e) {
866
880
  return JSON.stringify(e);
867
881
  }
868
- function nt(e) {
882
+ function tt(e) {
869
883
  try {
870
884
  let t = JSON.parse(e);
871
885
  return typeof t.agent != "string" || !Array.isArray(t.capabilities) || !Array.isArray(t.wireFormats) || !Array.isArray(t.ackModes) || typeof t.batchMax != "number" || t.batchMax < 1 ? null : {
@@ -879,8 +893,8 @@ function nt(e) {
879
893
  return null;
880
894
  }
881
895
  }
882
- function rt(e, t) {
883
- let n = Qe.find((n) => e.wireFormats.includes(n) && t.wireFormats.includes(n)) ?? "compact", r = $e.find((n) => e.ackModes.includes(n) && t.ackModes.includes(n)) ?? "receipt";
896
+ function nt(e, t) {
897
+ let n = Ze.find((n) => e.wireFormats.includes(n) && t.wireFormats.includes(n)) ?? "compact", r = Qe.find((n) => e.ackModes.includes(n) && t.ackModes.includes(n)) ?? "receipt";
884
898
  return {
885
899
  wireFormat: n,
886
900
  batchMax: Math.max(1, Math.min(e.batchMax, t.batchMax)),
@@ -889,7 +903,7 @@ function rt(e, t) {
889
903
  }
890
904
  //#endregion
891
905
  //#region src/keyRotation.ts
892
- var it = class {
906
+ var rt = class {
893
907
  records;
894
908
  constructor(e = []) {
895
909
  this.records = [...e];
@@ -908,12 +922,12 @@ var it = class {
908
922
  return this.records.filter((r) => r.sender === t && r.keyId === e.keyId && r.alg === e.alg && r.status !== "revoked" && r.notBeforeMs <= n && n < r.notAfterMs).sort((e, t) => t.notBeforeMs - e.notBeforeMs)[0]?.material;
909
923
  }
910
924
  };
911
- function at(e, t = () => Date.now()) {
925
+ function it(e, t = () => Date.now()) {
912
926
  return async (n, r) => e.resolveVerificationMaterial(n, r, t());
913
927
  }
914
928
  //#endregion
915
929
  //#region src/protocolAgent.ts
916
- var ot = class {
930
+ var at = class {
917
931
  agentId;
918
932
  outboundSecret;
919
933
  keyId;
@@ -927,13 +941,13 @@ var ot = class {
927
941
  resolveInboundSecret;
928
942
  onTask;
929
943
  constructor(e) {
930
- this.agentId = e.agentId, this.outboundSecret = e.outboundSecret, this.keyId = e.keyId ?? `${e.agentId}-k1`, this.capabilities = e.capabilities ?? [], this.supportedWireFormats = e.supportedWireFormats ?? ["compact", "json"], this.maxBatchSize = e.maxBatchSize ?? 1, this.ackModes = e.ackModes ?? ["receipt"], this.requireSignature = e.requireSignature ?? !0, this.replayCache = e.replayCache ?? new k(), this.sharedSecrets = e.sharedSecrets ?? {}, this.resolveInboundSecret = e.resolveInboundSecret, this.onTask = e.onTask;
944
+ this.agentId = e.agentId, this.outboundSecret = e.outboundSecret, this.keyId = e.keyId ?? `${e.agentId}-k1`, this.capabilities = e.capabilities ?? [], this.supportedWireFormats = e.supportedWireFormats ?? ["compact", "json"], this.maxBatchSize = e.maxBatchSize ?? 1, this.ackModes = e.ackModes ?? ["receipt"], this.requireSignature = e.requireSignature ?? !0, this.replayCache = e.replayCache ?? new A(), this.sharedSecrets = e.sharedSecrets ?? {}, this.resolveInboundSecret = e.resolveInboundSecret, this.onTask = e.onTask;
931
945
  }
932
946
  async inboundSecretResolver(e, t) {
933
947
  return this.resolveInboundSecret ? this.resolveInboundSecret(e, t) : this.sharedSecrets[t];
934
948
  }
935
949
  async createSignedIntent(e) {
936
- return me(E({
950
+ return S(D({
937
951
  sender: this.agentId,
938
952
  recipient: e.recipient,
939
953
  intent: e.intent,
@@ -947,7 +961,7 @@ var ot = class {
947
961
  }), this.outboundSecret, this.keyId);
948
962
  }
949
963
  async receiveAndRespond(e, t = Date.now()) {
950
- let n = await A(e, {
964
+ let n = await M(e, {
951
965
  nowMs: t,
952
966
  requireSignature: this.requireSignature,
953
967
  replayCache: this.replayCache,
@@ -978,7 +992,7 @@ var ot = class {
978
992
  if (e.body.intent === "CAPS") return this.createSignedIntent({
979
993
  recipient: e.header.sender,
980
994
  intent: "RESULT",
981
- content: tt(et({
995
+ content: et($e({
982
996
  agent: this.agentId,
983
997
  capabilities: this.capabilities,
984
998
  wireFormats: this.supportedWireFormats,
@@ -1006,14 +1020,14 @@ var ot = class {
1006
1020
  }
1007
1021
  return null;
1008
1022
  }
1009
- }, st = class {
1023
+ }, ot = class {
1010
1024
  session;
1011
1025
  wireFormat;
1012
1026
  constructor(e) {
1013
- this.session = new ot(e), this.wireFormat = e.wireFormat ?? "compact";
1027
+ this.session = new at(e), this.wireFormat = e.wireFormat ?? "compact";
1014
1028
  }
1015
1029
  toRaw(e) {
1016
- return Ke(e, this.wireFormat);
1030
+ return j(e, this.wireFormat);
1017
1031
  }
1018
1032
  async createRawIntent(e) {
1019
1033
  let t = await this.session.createSignedIntent(e);
@@ -1027,12 +1041,12 @@ var ot = class {
1027
1041
  return r.response && await t(this.toRaw(r.response), r.response), r;
1028
1042
  }
1029
1043
  };
1030
- function ct(e) {
1031
- return new st(e);
1044
+ function st(e) {
1045
+ return new ot(e);
1032
1046
  }
1033
1047
  //#endregion
1034
1048
  //#region src/frameworkAdapters.ts
1035
- async function lt(e, t, n = {}) {
1049
+ async function ct(e, t, n = {}) {
1036
1050
  return e.createRawIntent({
1037
1051
  recipient: n.recipient,
1038
1052
  intent: "TASK",
@@ -1041,7 +1055,7 @@ async function lt(e, t, n = {}) {
1041
1055
  correlationId: n.correlationId
1042
1056
  });
1043
1057
  }
1044
- function ut(e) {
1058
+ function lt(e) {
1045
1059
  return {
1046
1060
  content: e.body.content,
1047
1061
  name: e.body.intent,
@@ -1055,7 +1069,7 @@ function ut(e) {
1055
1069
  }
1056
1070
  };
1057
1071
  }
1058
- async function dt(e, t, n = {}) {
1072
+ async function ut(e, t, n = {}) {
1059
1073
  return e.createRawIntent({
1060
1074
  recipient: n.recipient,
1061
1075
  intent: "TASK",
@@ -1064,7 +1078,7 @@ async function dt(e, t, n = {}) {
1064
1078
  correlationId: n.correlationId
1065
1079
  });
1066
1080
  }
1067
- function ft(e) {
1081
+ function dt(e) {
1068
1082
  return {
1069
1083
  role: e.body.intent === "TASK" ? "user" : "assistant",
1070
1084
  content: e.body.content,
@@ -1077,15 +1091,15 @@ function ft(e) {
1077
1091
  }
1078
1092
  };
1079
1093
  }
1080
- function pt(e) {
1094
+ function ft(e) {
1081
1095
  return `mcp.${e}`;
1082
1096
  }
1083
- async function mt(e, t, n = {}) {
1097
+ async function pt(e, t, n = {}) {
1084
1098
  async function r(e) {
1085
1099
  n.onPolicyEvent && await n.onPolicyEvent(e);
1086
1100
  }
1087
1101
  if (n.allowedMethods && !n.allowedMethods.includes(t.method)) {
1088
- let e = n.methodToCapability ? n.methodToCapability(t.method) : pt(t.method), i = {
1102
+ let e = n.methodToCapability ? n.methodToCapability(t.method) : ft(t.method), i = {
1089
1103
  intent: "TASK",
1090
1104
  recipient: n.recipient,
1091
1105
  capability: e,
@@ -1100,7 +1114,7 @@ async function mt(e, t, n = {}) {
1100
1114
  reason: "method_not_allowed"
1101
1115
  }), Error(`JSON-RPC method '${t.method}' is not allowed`);
1102
1116
  }
1103
- let i = n.methodToCapability ? n.methodToCapability(t.method) : pt(t.method), a = {
1117
+ let i = n.methodToCapability ? n.methodToCapability(t.method) : ft(t.method), a = {
1104
1118
  intent: "TASK",
1105
1119
  recipient: n.recipient,
1106
1120
  capability: i,
@@ -1154,7 +1168,7 @@ async function mt(e, t, n = {}) {
1154
1168
  })
1155
1169
  });
1156
1170
  }
1157
- function ht(e, t, n = {}) {
1171
+ function mt(e, t, n = {}) {
1158
1172
  if (e.body.intent === "ERROR") return {
1159
1173
  jsonrpc: "2.0",
1160
1174
  id: t,
@@ -1181,16 +1195,16 @@ function ht(e, t, n = {}) {
1181
1195
  }
1182
1196
  //#endregion
1183
1197
  //#region src/runtimePolicy.ts
1184
- function gt(e) {
1198
+ function ht(e) {
1185
1199
  return typeof e == "object" && !!e && !Array.isArray(e);
1186
1200
  }
1187
- function _t(e, t) {
1201
+ function gt(e, t) {
1188
1202
  if (typeof e != "string" || e.trim().length === 0) throw Error(`Invalid runtime policy: '${t}' must be a non-empty string`);
1189
1203
  return e;
1190
1204
  }
1191
- function vt(e) {
1192
- if (!gt(e)) throw Error("Invalid runtime policy: root must be an object");
1193
- let t = _t(e.version, "version"), n = _t(e.name, "name"), r = _t(e.status, "status");
1205
+ function _t(e) {
1206
+ if (!ht(e)) throw Error("Invalid runtime policy: root must be an object");
1207
+ let t = gt(e.version, "version"), n = gt(e.name, "name"), r = gt(e.status, "status");
1194
1208
  return {
1195
1209
  ...e,
1196
1210
  version: t,
@@ -1198,7 +1212,7 @@ function vt(e) {
1198
1212
  status: r
1199
1213
  };
1200
1214
  }
1201
- function yt(e) {
1215
+ function vt(e) {
1202
1216
  let t;
1203
1217
  try {
1204
1218
  t = JSON.parse(e);
@@ -1206,9 +1220,9 @@ function yt(e) {
1206
1220
  let t = e instanceof Error ? e.message : String(e);
1207
1221
  throw Error(`Invalid runtime policy JSON: ${t}`, { cause: e });
1208
1222
  }
1209
- return vt(t);
1223
+ return _t(t);
1210
1224
  }
1211
- async function bt(e) {
1225
+ async function yt(e) {
1212
1226
  if (typeof fetch == "function") {
1213
1227
  let t = await fetch(e);
1214
1228
  if (!t.ok) throw Error(`Failed to fetch runtime policy at '${e}': ${t.status} ${t.statusText}`);
@@ -1216,26 +1230,26 @@ async function bt(e) {
1216
1230
  }
1217
1231
  throw Error("No default runtime file reader available in this environment. Provide 'readTextFile' in loadRuntimePolicy(options).");
1218
1232
  }
1219
- async function xt(e = {}) {
1233
+ async function bt(e = {}) {
1220
1234
  let t = e.path ?? "AI_RUNTIME_POLICY.json";
1221
- return yt(await (e.readTextFile ?? bt)(t));
1235
+ return vt(await (e.readTextFile ?? yt)(t));
1222
1236
  }
1223
1237
  //#endregion
1224
1238
  //#region src/policyEnforcer.ts
1225
- function St(e, t) {
1239
+ function xt(e, t) {
1226
1240
  if (!Array.isArray(e) || e.length !== 2) throw Error(`Invalid policy tuning range '${t}': expected [min,max]`);
1227
1241
  let n = Number(e[0]), r = Number(e[1]);
1228
1242
  if (!Number.isFinite(n) || !Number.isFinite(r) || n <= 0 || r < n) throw Error(`Invalid policy tuning range '${t}': expected positive ascending numbers`);
1229
1243
  return [Math.floor(n), Math.floor(r)];
1230
1244
  }
1231
- function Ct(e) {
1245
+ function St(e) {
1232
1246
  return e === "http" || e === "ws" || e === "http-binary" || e === "http-batch" || e === "http-binary-batch" || e === "ws-batch" || e === "ws-binary" || e === "ws-binary-batch";
1233
1247
  }
1234
- function wt(e) {
1248
+ function Ct(e) {
1235
1249
  let t = Number((e.slo_defaults ?? {}).drop_pct_max ?? .1), n = Number((e.slo_defaults ?? {}).p99_ms_max ?? 20), r = Number((e.tuning ?? {}).max_retry_attempts ?? 3), i = Array.isArray((e.tuning ?? {}).retriable_status_codes) ? (e.tuning ?? {}).retriable_status_codes.map((e) => Number(e)).filter((e) => Number.isFinite(e)) : [503], a = e.tuning ?? {}, o = a.batch_size, s = a.inflight_cap, c = a.retry_backoff_ms, l = (e) => ({
1236
- batchSizeRange: St(o?.[`${e}_traffic`], `batch_size.${e}_traffic`),
1237
- inflightCapRange: St(s?.[`${e}_traffic`], `inflight_cap.${e}_traffic`),
1238
- retryBackoffMsRange: St(c?.[`${e}_traffic`], `retry_backoff_ms.${e}_traffic`)
1250
+ batchSizeRange: xt(o?.[`${e}_traffic`], `batch_size.${e}_traffic`),
1251
+ inflightCapRange: xt(s?.[`${e}_traffic`], `inflight_cap.${e}_traffic`),
1252
+ retryBackoffMsRange: xt(c?.[`${e}_traffic`], `retry_backoff_ms.${e}_traffic`)
1239
1253
  });
1240
1254
  function u(e) {
1241
1255
  return e.concurrency >= 100 ? "http-binary-batch" : e.latencySensitive ? "ws-batch" : e.compatibilityFirst ? "http" : "ws-batch";
@@ -1272,28 +1286,28 @@ function wt(e) {
1272
1286
  }
1273
1287
  };
1274
1288
  }
1275
- async function j(e = {}) {
1276
- let t = await xt(e);
1289
+ async function N(e = {}) {
1290
+ let t = await bt(e);
1277
1291
  return {
1278
1292
  policy: t,
1279
- enforcer: wt(t)
1293
+ enforcer: Ct(t)
1280
1294
  };
1281
1295
  }
1282
- function Tt(e) {
1283
- return Ct(e);
1296
+ function wt(e) {
1297
+ return St(e);
1284
1298
  }
1285
1299
  //#endregion
1286
1300
  //#region src/mcpGateway.ts
1287
- var Et = [
1301
+ var Tt = [
1288
1302
  "tools/call",
1289
1303
  "resources/read",
1290
1304
  "prompts/get"
1291
1305
  ];
1292
- function Dt(e) {
1306
+ function Et(e) {
1293
1307
  return JSON.stringify(e);
1294
1308
  }
1295
- function M(e, t, n) {
1296
- return Dt({
1309
+ function Dt(e, t, n) {
1310
+ return Et({
1297
1311
  jsonrpc: "2.0",
1298
1312
  id: e,
1299
1313
  error: {
@@ -1315,26 +1329,26 @@ function kt(e) {
1315
1329
  return e.includes("not allowed") ? -32601 : e.includes("not authorized") ? -32001 : e.includes("rate-limited") ? -32002 : -32603;
1316
1330
  }
1317
1331
  function At(e) {
1318
- let t = e.gatewayAgentId ?? "agent.gateway", n = e.workerAgentId ?? "agent.worker", r = e.allowedMethods ?? Et, i = e.workerCapabilityPrefix ?? "mcp.", a = e.gatewayWireFormat ?? "compact", o = e.workerWireFormat ?? "compact";
1332
+ let t = e.gatewayAgentId ?? "agent.gateway", n = e.workerAgentId ?? "agent.worker", r = e.allowedMethods ?? Tt, i = e.workerCapabilityPrefix ?? "mcp.", a = e.gatewayWireFormat ?? "compact", o = e.workerWireFormat ?? "compact";
1319
1333
  async function s(t) {
1320
1334
  e.onAuditEvent && await e.onAuditEvent({
1321
1335
  ...t,
1322
1336
  timestampMs: Date.now()
1323
1337
  });
1324
1338
  }
1325
- let c = ct({
1339
+ let c = st({
1326
1340
  agentId: t,
1327
1341
  outboundSecret: e.sharedSecret,
1328
1342
  sharedSecrets: { [n]: e.sharedSecret },
1329
1343
  wireFormat: a
1330
- }), l = ct({
1344
+ }), l = st({
1331
1345
  agentId: n,
1332
1346
  outboundSecret: e.sharedSecret,
1333
1347
  sharedSecrets: { [t]: e.sharedSecret },
1334
1348
  wireFormat: o,
1335
1349
  onTask: async (e) => ({
1336
1350
  intent: "RESULT",
1337
- content: Dt({
1351
+ content: Et({
1338
1352
  ok: !0,
1339
1353
  capability: e.body.capability,
1340
1354
  content: e.body.content
@@ -1352,7 +1366,7 @@ function At(e) {
1352
1366
  phase: "request_error",
1353
1367
  code: -32600,
1354
1368
  message: "Invalid Request"
1355
- }), M(null, -32600, "Invalid Request");
1369
+ }), Dt(null, -32600, "Invalid Request");
1356
1370
  a = t.id, await s({
1357
1371
  phase: "request_received",
1358
1372
  id: t.id,
@@ -1373,7 +1387,7 @@ function At(e) {
1373
1387
  policy: e
1374
1388
  });
1375
1389
  }
1376
- }, u = await mt(c, t, o), d = null;
1390
+ }, u = await pt(c, t, o), d = null;
1377
1391
  if (await l.handleRaw(u, async (e) => {
1378
1392
  d = e;
1379
1393
  }), !d) return await s({
@@ -1382,7 +1396,7 @@ function At(e) {
1382
1396
  method: t.method,
1383
1397
  code: -32603,
1384
1398
  message: "AIP worker did not produce a response"
1385
- }), M(a, -32603, "AIP worker did not produce a response");
1399
+ }), Dt(a, -32603, "AIP worker did not produce a response");
1386
1400
  let f = await c.receiveRaw(d);
1387
1401
  return !f.ok || !f.received ? (await s({
1388
1402
  phase: "verification_failed",
@@ -1390,11 +1404,11 @@ function At(e) {
1390
1404
  method: t.method,
1391
1405
  code: -32603,
1392
1406
  message: "AIP verification failed"
1393
- }), M(a, -32603, "AIP verification failed")) : (await s({
1407
+ }), Dt(a, -32603, "AIP verification failed")) : (await s({
1394
1408
  phase: "request_success",
1395
1409
  id: t.id,
1396
1410
  method: t.method
1397
- }), Dt(ht(f.received, t.id)));
1411
+ }), Et(mt(f.received, t.id)));
1398
1412
  } catch (e) {
1399
1413
  let t = e instanceof Error ? e.message : "Internal error", n = kt(t);
1400
1414
  return await s({
@@ -1402,13 +1416,13 @@ function At(e) {
1402
1416
  id: a,
1403
1417
  code: n,
1404
1418
  message: t
1405
- }), M(a, n, t);
1419
+ }), Dt(a, n, t);
1406
1420
  }
1407
1421
  } };
1408
1422
  }
1409
1423
  async function jt(e) {
1410
1424
  if (!e.runtimePolicy?.enabled) return At(e);
1411
- let { enforcer: t } = await j(e.runtimePolicy.options);
1425
+ let { enforcer: t } = await N(e.runtimePolicy.options);
1412
1426
  t.assertInvariant({
1413
1427
  signatureVerification: !0,
1414
1428
  canonicalization: !0,
@@ -1443,7 +1457,7 @@ var Mt = class {
1443
1457
  this.options = e;
1444
1458
  }
1445
1459
  async loadInitial() {
1446
- let e = await j(this.options);
1460
+ let e = await N(this.options);
1447
1461
  return this.snapshot = {
1448
1462
  ...e,
1449
1463
  loadedAtMs: Date.now()
@@ -1456,7 +1470,7 @@ var Mt = class {
1456
1470
  async refresh() {
1457
1471
  let e = this.snapshot;
1458
1472
  try {
1459
- let e = await j(this.options);
1473
+ let e = await N(this.options);
1460
1474
  return this.snapshot = {
1461
1475
  ...e,
1462
1476
  loadedAtMs: Date.now()
@@ -1693,7 +1707,7 @@ function Gt(e, t, n = {}) {
1693
1707
  }
1694
1708
  //#endregion
1695
1709
  //#region src/mcpWrapper.ts
1696
- function N(e, t, n) {
1710
+ function Kt(e, t, n) {
1697
1711
  return {
1698
1712
  jsonrpc: "2.0",
1699
1713
  id: e,
@@ -1703,20 +1717,20 @@ function N(e, t, n) {
1703
1717
  }
1704
1718
  };
1705
1719
  }
1706
- function Kt(e, t) {
1720
+ function qt(e, t) {
1707
1721
  return {
1708
- requireSignature: !0,
1709
1722
  ...e.receive,
1723
+ requireSignature: !0,
1710
1724
  replayCache: t
1711
1725
  };
1712
1726
  }
1713
- function qt(e, t) {
1714
- let n = t.wireFormat ?? "compact", r = t.ttlMs ?? 6e4, i = Kt(t, t.receive?.replayCache ?? new k());
1727
+ function Jt(e, t) {
1728
+ let n = t.wireFormat ?? "compact", r = t.ttlMs ?? 6e4, i = qt(t, t.receive?.replayCache ?? new A());
1715
1729
  async function a(e) {
1716
- return Ke(await t.sign(e), n);
1730
+ return j(await t.sign(e), n);
1717
1731
  }
1718
1732
  function o(e, n, i, o) {
1719
- return a(E({
1733
+ return a(D({
1720
1734
  sender: t.selfAgentId,
1721
1735
  recipient: e,
1722
1736
  intent: n,
@@ -1726,29 +1740,29 @@ function qt(e, t) {
1726
1740
  }));
1727
1741
  }
1728
1742
  return async (n) => {
1729
- let r = await A(n, i), a = r.envelope?.header.sender, s = r.envelope?.header.messageId;
1730
- if (!r.ok || !r.envelope) return o(a, "ERROR", N(null, -32600, r.diagnostics.find((e) => e.level === "error")?.message ?? "AIP verification failed"), s);
1731
- if (r.envelope.header.recipient !== t.selfAgentId) return o(a, "ERROR", N(null, -32600, "Recipient mismatch: envelope not addressed to this agent"), s);
1743
+ let r = await M(n, i), a = r.envelope?.header.sender, s = r.envelope?.header.messageId;
1744
+ if (!r.ok || !r.envelope) return o(a, "ERROR", Kt(null, -32600, r.diagnostics.find((e) => e.level === "error")?.message ?? "AIP verification failed"), s);
1745
+ if (r.envelope.header.recipient !== t.selfAgentId) return o(a, "ERROR", Kt(null, -32600, "Recipient mismatch: envelope not addressed to this agent"), s);
1732
1746
  let c;
1733
1747
  try {
1734
1748
  c = JSON.parse(r.envelope.body.content);
1735
1749
  } catch {
1736
- return o(a, "ERROR", N(null, -32700, "Parse error: envelope body is not JSON-RPC"), s);
1750
+ return o(a, "ERROR", Kt(null, -32700, "Parse error: envelope body is not JSON-RPC"), s);
1737
1751
  }
1738
1752
  let l;
1739
1753
  try {
1740
1754
  l = await e(c);
1741
1755
  } catch (e) {
1742
- l = N(c.id ?? null, -32603, e instanceof Error ? e.message : "Internal error");
1756
+ l = Kt(c.id ?? null, -32603, e instanceof Error ? e.message : "Internal error");
1743
1757
  }
1744
1758
  return o(r.envelope.header.sender, "RESULT", l, s);
1745
1759
  };
1746
1760
  }
1747
- function Jt(e) {
1748
- let t = e.wireFormat ?? "compact", n = e.ttlMs ?? 6e4, r = Kt(e, e.receive?.replayCache ?? new k());
1761
+ function Yt(e) {
1762
+ let t = e.wireFormat ?? "compact", n = e.ttlMs ?? 6e4, r = qt(e, e.receive?.replayCache ?? new A());
1749
1763
  return {
1750
1764
  async encodeRequest(r) {
1751
- let i = E({
1765
+ let i = D({
1752
1766
  sender: e.selfAgentId,
1753
1767
  recipient: e.peerAgentId,
1754
1768
  intent: "TASK",
@@ -1756,12 +1770,12 @@ function Jt(e) {
1756
1770
  ttlMs: n
1757
1771
  });
1758
1772
  return {
1759
- raw: Ke(await e.sign(i), t),
1773
+ raw: j(await e.sign(i), t),
1760
1774
  messageId: i.header.messageId
1761
1775
  };
1762
1776
  },
1763
1777
  async decodeResponse(t, n = {}) {
1764
- let i = await A(t, r);
1778
+ let i = await M(t, r);
1765
1779
  if (!i.ok || !i.envelope) {
1766
1780
  let e = i.diagnostics.find((e) => e.level === "error")?.message ?? "unknown";
1767
1781
  throw Error(`AIP response verification failed: ${e}`);
@@ -1773,8 +1787,8 @@ function Jt(e) {
1773
1787
  }
1774
1788
  };
1775
1789
  }
1776
- function Yt(e, t) {
1777
- let n = Jt(t);
1790
+ function Xt(e, t) {
1791
+ let n = Yt(t);
1778
1792
  return async (t) => {
1779
1793
  let { raw: r, messageId: i } = await n.encodeRequest(t);
1780
1794
  return n.decodeResponse(await e(r), { expectCorrelationId: i });
@@ -1782,11 +1796,11 @@ function Yt(e, t) {
1782
1796
  }
1783
1797
  //#endregion
1784
1798
  //#region src/mcpTransports.ts
1785
- function Xt(e) {
1799
+ function Zt(e) {
1786
1800
  if (typeof e != "string") throw Error("stdio adapter supports json/compact (string) wire formats; use the HTTP adapter for binary");
1787
1801
  return e;
1788
1802
  }
1789
- function Zt(t, n = {}) {
1803
+ function Qt(t, n = {}) {
1790
1804
  let r = n.input ?? process.stdin, i = n.output ?? process.stdout, a = e.createInterface({
1791
1805
  input: r,
1792
1806
  crlfDelay: Infinity
@@ -1795,7 +1809,7 @@ function Zt(t, n = {}) {
1795
1809
  r && (o = o.then(async () => {
1796
1810
  try {
1797
1811
  let e = await t(r);
1798
- i.write(`${Xt(e)}\n`);
1812
+ i.write(`${Zt(e)}\n`);
1799
1813
  } catch (e) {
1800
1814
  n.onError?.(e);
1801
1815
  }
@@ -1805,7 +1819,7 @@ function Zt(t, n = {}) {
1805
1819
  a.off("line", s), a.close();
1806
1820
  } };
1807
1821
  }
1808
- function Qt(t) {
1822
+ function $t(t) {
1809
1823
  let n = e.createInterface({
1810
1824
  input: t.input,
1811
1825
  crlfDelay: Infinity
@@ -1817,7 +1831,7 @@ function Qt(t) {
1817
1831
  };
1818
1832
  return n.on("line", i), {
1819
1833
  send(e) {
1820
- let n = Xt(e);
1834
+ let n = Zt(e);
1821
1835
  return new Promise((e) => {
1822
1836
  r.push(e), t.output.write(`${n}\n`);
1823
1837
  });
@@ -1827,7 +1841,7 @@ function Qt(t) {
1827
1841
  }
1828
1842
  };
1829
1843
  }
1830
- function $t(e, t = {}) {
1844
+ function en(e, t = {}) {
1831
1845
  return (n, r) => {
1832
1846
  let i = [];
1833
1847
  n.on("data", (e) => i.push(e)), n.on("error", () => {
@@ -1851,7 +1865,7 @@ function $t(e, t = {}) {
1851
1865
  });
1852
1866
  };
1853
1867
  }
1854
- function en(e) {
1868
+ function tn(e) {
1855
1869
  let t = e.fetchImpl ?? fetch, n = e.binary ? "application/octet-stream" : "application/json";
1856
1870
  return { async send(r) {
1857
1871
  let i = await t(e.url, {
@@ -1867,12 +1881,12 @@ function en(e) {
1867
1881
  }
1868
1882
  //#endregion
1869
1883
  //#region src/keyRegistry.ts
1870
- function tn(e) {
1884
+ function nn(e) {
1871
1885
  return { async getPublicKey(t) {
1872
1886
  return e[t] ?? null;
1873
1887
  } };
1874
1888
  }
1875
- function nn(...e) {
1889
+ function rn(...e) {
1876
1890
  return {
1877
1891
  async getPublicKey(t) {
1878
1892
  for (let n of e) {
@@ -1891,7 +1905,7 @@ function nn(...e) {
1891
1905
  }
1892
1906
  };
1893
1907
  }
1894
- function rn(e, t) {
1908
+ function an(e, t) {
1895
1909
  let n = t?.ttlMs ?? 6e4, r = /* @__PURE__ */ new Map();
1896
1910
  async function i(e, t) {
1897
1911
  let i = Date.now(), a = r.get(e);
@@ -1913,18 +1927,18 @@ function rn(e, t) {
1913
1927
  }
1914
1928
  //#endregion
1915
1929
  //#region src/cborCodec.ts
1916
- var P = new TextEncoder(), an = new TextDecoder(), F = 0, on = 1, sn = 2, I = 3, cn = 4, ln = 5, un = 7, dn = 244, fn = 245, pn = 246, mn = 24, hn = 25, gn = 26, _n = 27, vn = 27, yn = class {
1930
+ var P = new TextEncoder(), on = new TextDecoder(), F = 0, sn = 1, cn = 2, I = 3, ln = 4, un = 5, dn = 7, fn = 244, pn = 245, mn = 246, hn = 24, gn = 25, _n = 26, vn = 27, yn = 27, bn = class {
1917
1931
  chunks = [];
1918
1932
  encode(e) {
1919
1933
  return this.chunks = [], this._encode(e), this._concat();
1920
1934
  }
1921
1935
  _encode(e) {
1922
1936
  if (e == null) {
1923
- this.chunks.push(new Uint8Array([pn]));
1937
+ this.chunks.push(new Uint8Array([mn]));
1924
1938
  return;
1925
1939
  }
1926
1940
  if (typeof e == "boolean") {
1927
- this.chunks.push(new Uint8Array([e ? fn : dn]));
1941
+ this.chunks.push(new Uint8Array([e ? pn : fn]));
1928
1942
  return;
1929
1943
  }
1930
1944
  if (typeof e == "number") {
@@ -1962,7 +1976,7 @@ var P = new TextEncoder(), an = new TextDecoder(), F = 0, on = 1, sn = 2, I = 3,
1962
1976
  new DataView(t).setFloat64(0, e, !1), this.chunks.push(new Uint8Array(t));
1963
1977
  return;
1964
1978
  }
1965
- e >= 0 ? this._encodeHead(F, e) : this._encodeHead(on, -1 - e);
1979
+ e >= 0 ? this._encodeHead(F, e) : this._encodeHead(sn, -1 - e);
1966
1980
  }
1967
1981
  _float64Header() {
1968
1982
  return new Uint8Array([251]);
@@ -1972,10 +1986,10 @@ var P = new TextEncoder(), an = new TextDecoder(), F = 0, on = 1, sn = 2, I = 3,
1972
1986
  this._encodeHead(I, t.length), this.chunks.push(t);
1973
1987
  }
1974
1988
  _encodeByteString(e) {
1975
- this._encodeHead(sn, e.length), this.chunks.push(e);
1989
+ this._encodeHead(cn, e.length), this.chunks.push(e);
1976
1990
  }
1977
1991
  _encodeArray(e) {
1978
- this._encodeHead(cn, e.length);
1992
+ this._encodeHead(ln, e.length);
1979
1993
  for (let t of e) this._encode(t);
1980
1994
  }
1981
1995
  _encodeMapFromAnyEntries(e) {
@@ -1992,7 +2006,7 @@ var P = new TextEncoder(), an = new TextDecoder(), F = 0, on = 1, sn = 2, I = 3,
1992
2006
  value: t
1993
2007
  };
1994
2008
  });
1995
- t.sort((e, t) => this._compareBytes(e.keyEncoded, t.keyEncoded)), this._encodeHead(ln, t.length);
2009
+ t.sort((e, t) => this._compareBytes(e.keyEncoded, t.keyEncoded)), this._encodeHead(un, t.length);
1996
2010
  for (let { key: e, value: n } of t) {
1997
2011
  if (typeof e == "number" && Number.isInteger(e)) this._encodeHead(F, e);
1998
2012
  else {
@@ -2011,7 +2025,7 @@ var P = new TextEncoder(), an = new TextDecoder(), F = 0, on = 1, sn = 2, I = 3,
2011
2025
  value: t
2012
2026
  };
2013
2027
  });
2014
- t.sort((e, t) => this._compareBytes(e.keyEncoded, t.keyEncoded)), this._encodeHead(ln, t.length);
2028
+ t.sort((e, t) => this._compareBytes(e.keyEncoded, t.keyEncoded)), this._encodeHead(un, t.length);
2015
2029
  for (let { keyBytes: e, value: n } of t) this._encodeHead(I, e.length), this.chunks.push(e), this._encode(n);
2016
2030
  }
2017
2031
  _compareBytes(e, t) {
@@ -2032,60 +2046,70 @@ var P = new TextEncoder(), an = new TextDecoder(), F = 0, on = 1, sn = 2, I = 3,
2032
2046
  _encodeHeadBytes(e, t) {
2033
2047
  let n = e << 5;
2034
2048
  if (t <= 23) return new Uint8Array([n | t]);
2035
- if (t <= 255) return new Uint8Array([n | mn, t]);
2049
+ if (t <= 255) return new Uint8Array([n | hn, t]);
2036
2050
  if (t <= 65535) {
2037
2051
  let e = /* @__PURE__ */ new ArrayBuffer(3), r = new DataView(e);
2038
- return r.setUint8(0, n | hn), r.setUint16(1, t, !1), new Uint8Array(e);
2052
+ return r.setUint8(0, n | gn), r.setUint16(1, t, !1), new Uint8Array(e);
2039
2053
  }
2040
2054
  if (t <= 4294967295) {
2041
2055
  let e = /* @__PURE__ */ new ArrayBuffer(5), r = new DataView(e);
2042
- return r.setUint8(0, n | gn), r.setUint32(1, t, !1), new Uint8Array(e);
2056
+ return r.setUint8(0, n | _n), r.setUint32(1, t, !1), new Uint8Array(e);
2043
2057
  }
2044
2058
  let r = /* @__PURE__ */ new ArrayBuffer(9), i = new DataView(r);
2045
- return i.setUint8(0, n | _n), i.setBigUint64(1, BigInt(t), !1), new Uint8Array(r);
2059
+ return i.setUint8(0, n | vn), i.setBigUint64(1, BigInt(t), !1), new Uint8Array(r);
2046
2060
  }
2047
2061
  _concat() {
2048
2062
  let e = this.chunks.reduce((e, t) => e + t.length, 0), t = new Uint8Array(e), n = 0;
2049
2063
  for (let e of this.chunks) t.set(e, n), n += e.length;
2050
2064
  return t;
2051
2065
  }
2052
- }, bn = class {
2066
+ }, xn = 64, Sn = class {
2053
2067
  data;
2054
2068
  offset = 0;
2069
+ depth = 0;
2055
2070
  decode(e) {
2056
- return this.data = e, this.offset = 0, this._decode();
2071
+ return this.data = e, this.offset = 0, this.depth = 0, this._decode();
2057
2072
  }
2058
2073
  _decode() {
2074
+ if (this.depth >= 64) throw Error("CborDecoder: nesting depth exceeds maximum of 64");
2075
+ this.depth++;
2076
+ try {
2077
+ return this._decodeItem();
2078
+ } finally {
2079
+ this.depth--;
2080
+ }
2081
+ }
2082
+ _decodeItem() {
2059
2083
  let e = this._readByte(), t = e >> 5 & 7, n = e & 31;
2060
2084
  switch (t) {
2061
2085
  case F: return this._decodeUint(n);
2062
- case on: return -1 - this._decodeUint(n);
2063
- case sn: {
2086
+ case sn: return -1 - this._decodeUint(n);
2087
+ case cn: {
2064
2088
  let e = this._decodeUint(n);
2065
2089
  return this._readBytes(e);
2066
2090
  }
2067
2091
  case I: {
2068
2092
  let e = this._decodeUint(n), t = this._readBytes(e);
2069
- return an.decode(t);
2093
+ return on.decode(t);
2070
2094
  }
2071
- case cn: {
2095
+ case ln: {
2072
2096
  let e = this._decodeUint(n), t = [];
2073
2097
  for (let n = 0; n < e; n++) t.push(this._decode());
2074
2098
  return t;
2075
2099
  }
2076
- case ln: {
2077
- let e = this._decodeUint(n), t = {};
2100
+ case un: {
2101
+ let e = this._decodeUint(n), t = Object.create(null);
2078
2102
  for (let n = 0; n < e; n++) {
2079
2103
  let e = this._decode();
2080
2104
  t[String(e)] = this._decode();
2081
2105
  }
2082
2106
  return t;
2083
2107
  }
2084
- case un:
2108
+ case dn:
2085
2109
  if (n === 20) return !1;
2086
2110
  if (n === 21) return !0;
2087
2111
  if (n === 22) return null;
2088
- if (n === vn) {
2112
+ if (n === yn) {
2089
2113
  let e = this._readBytes(8);
2090
2114
  return new DataView(e.buffer, e.byteOffset, 8).getFloat64(0, !1);
2091
2115
  }
@@ -2095,16 +2119,16 @@ var P = new TextEncoder(), an = new TextDecoder(), F = 0, on = 1, sn = 2, I = 3,
2095
2119
  }
2096
2120
  _decodeUint(e) {
2097
2121
  if (e <= 23) return e;
2098
- if (e === mn) return this._readByte();
2099
- if (e === hn) {
2122
+ if (e === hn) return this._readByte();
2123
+ if (e === gn) {
2100
2124
  let e = this._readBytes(2);
2101
2125
  return new DataView(e.buffer, e.byteOffset, 2).getUint16(0, !1);
2102
2126
  }
2103
- if (e === gn) {
2127
+ if (e === _n) {
2104
2128
  let e = this._readBytes(4);
2105
2129
  return new DataView(e.buffer, e.byteOffset, 4).getUint32(0, !1);
2106
2130
  }
2107
- if (e === _n) {
2131
+ if (e === vn) {
2108
2132
  let e = this._readBytes(8);
2109
2133
  return Number(new DataView(e.buffer, e.byteOffset, 8).getBigUint64(0, !1));
2110
2134
  }
@@ -2120,16 +2144,16 @@ var P = new TextEncoder(), an = new TextDecoder(), F = 0, on = 1, sn = 2, I = 3,
2120
2144
  return this.offset += e, t;
2121
2145
  }
2122
2146
  };
2123
- function xn(e) {
2124
- return new yn().encode(e);
2147
+ function Cn(e) {
2148
+ return new bn().encode(e);
2125
2149
  }
2126
- function Sn(e) {
2127
- return new bn().decode(e);
2150
+ function wn(e) {
2151
+ return new Sn().decode(e);
2128
2152
  }
2129
2153
  //#endregion
2130
2154
  //#region src/envelopeCbor.ts
2131
- var Cn = "application/7h3-cbor";
2132
- function wn(e) {
2155
+ var Tn = "application/7h3-cbor";
2156
+ function En(e) {
2133
2157
  let t = /* @__PURE__ */ new Map();
2134
2158
  t.set(1, e.header.version), t.set(2, e.header.messageId), t.set(3, e.header.timestampMs), t.set(4, e.header.ttlMs), t.set(5, e.header.sender), e.header.recipient !== void 0 && t.set(6, e.header.recipient), t.set(7, e.header.nonce);
2135
2159
  let n = /* @__PURE__ */ new Map();
@@ -2141,10 +2165,21 @@ function wn(e) {
2141
2165
  let e = /* @__PURE__ */ new Map();
2142
2166
  e.set(1, i.alg), e.set(2, i.keyId), e.set(3, i.value), r.set(3, e);
2143
2167
  }
2144
- return xn(r);
2168
+ return Cn(r);
2169
+ }
2170
+ function L(e, t) {
2171
+ if (typeof e != "string") throw Error(`decodeEnvelopeCbor: ${t} must be a string`);
2172
+ return e;
2173
+ }
2174
+ function Dn(e, t) {
2175
+ if (e !== void 0) return L(e, t);
2145
2176
  }
2146
- function Tn(e) {
2147
- let t = Sn(e);
2177
+ function On(e, t) {
2178
+ if (typeof e != "number" || !Number.isFinite(e)) throw Error(`decodeEnvelopeCbor: ${t} must be a finite number`);
2179
+ return e;
2180
+ }
2181
+ function kn(e) {
2182
+ let t = wn(e);
2148
2183
  if (!t || typeof t != "object" || Array.isArray(t)) throw Error("decodeEnvelopeCbor: expected a map at top level");
2149
2184
  let n = t, r = n[1];
2150
2185
  if (!r || typeof r != "object" || Array.isArray(r)) throw Error("decodeEnvelopeCbor: missing header map (key 1)");
@@ -2152,38 +2187,42 @@ function Tn(e) {
2152
2187
  if (!a || typeof a != "object" || Array.isArray(a)) throw Error("decodeEnvelopeCbor: missing body map (key 2)");
2153
2188
  let o = a, s = {
2154
2189
  header: {
2155
- version: i[1],
2156
- messageId: i[2],
2157
- timestampMs: i[3],
2158
- ttlMs: i[4],
2159
- sender: i[5],
2160
- nonce: i[7]
2190
+ version: L(i[1], "header.version"),
2191
+ messageId: L(i[2], "header.messageId"),
2192
+ timestampMs: On(i[3], "header.timestampMs"),
2193
+ ttlMs: On(i[4], "header.ttlMs"),
2194
+ sender: L(i[5], "header.sender"),
2195
+ nonce: L(i[7], "header.nonce")
2161
2196
  },
2162
2197
  body: {
2163
- intent: o[1],
2164
- content: o[2]
2165
- }
2166
- };
2167
- i[6] !== void 0 && (s.header.recipient = i[6]), o[3] !== void 0 && (s.body.capability = o[3]), o[4] !== void 0 && (s.body.correlationId = o[4]);
2168
- let c = n[3];
2169
- if (c != null) {
2170
- if (typeof c != "object" || Array.isArray(c)) throw Error("decodeEnvelopeCbor: expected signature map at key 3");
2171
- let e = c;
2198
+ intent: L(o[1], "body.intent"),
2199
+ content: L(o[2], "body.content")
2200
+ }
2201
+ }, c = Dn(i[6], "header.recipient");
2202
+ c !== void 0 && (s.header.recipient = c);
2203
+ let l = Dn(o[3], "body.capability");
2204
+ l !== void 0 && (s.body.capability = l);
2205
+ let u = Dn(o[4], "body.correlationId");
2206
+ u !== void 0 && (s.body.correlationId = u);
2207
+ let d = n[3];
2208
+ if (d != null) {
2209
+ if (typeof d != "object" || Array.isArray(d)) throw Error("decodeEnvelopeCbor: expected signature map at key 3");
2210
+ let e = d;
2172
2211
  s.signature = {
2173
- alg: e[1],
2174
- keyId: e[2],
2175
- value: e[3]
2212
+ alg: L(e[1], "signature.alg"),
2213
+ keyId: L(e[2], "signature.keyId"),
2214
+ value: L(e[3], "signature.value")
2176
2215
  };
2177
2216
  }
2178
2217
  return s;
2179
2218
  }
2180
2219
  //#endregion
2181
2220
  //#region src/httpBinding.ts
2182
- var En = "x-7h3-envelope";
2183
- async function Dn(e, t, n) {
2221
+ var An = "x-7h3-envelope";
2222
+ async function jn(e, t, n) {
2184
2223
  let r = t.headerName ?? "x-7h3-envelope", i = (Array.isArray(e["content-type"]) ? e["content-type"][0] : e["content-type"]) ?? "", a;
2185
2224
  if (i.includes("7h3-cbor") && n instanceof Uint8Array) try {
2186
- a = Tn(n);
2225
+ a = kn(n);
2187
2226
  } catch (e) {
2188
2227
  return {
2189
2228
  ok: !1,
@@ -2213,7 +2252,7 @@ async function Dn(e, t, n) {
2213
2252
  detail: "missing required fields"
2214
2253
  };
2215
2254
  if (t.strictTtl ?? !0) {
2216
- let e = T(a).filter((e) => e.level === "error");
2255
+ let e = E(a).filter((e) => e.level === "error");
2217
2256
  if (e.length > 0) return {
2218
2257
  ok: !1,
2219
2258
  reason: "ttl-expired",
@@ -2221,6 +2260,11 @@ async function Dn(e, t, n) {
2221
2260
  };
2222
2261
  }
2223
2262
  let o = a.header.sender, s = a.signature.alg;
2263
+ if (!t.keyRegistry) return {
2264
+ ok: !1,
2265
+ reason: "unknown-sender",
2266
+ detail: "no key registry configured"
2267
+ };
2224
2268
  if (s === "ED25519") {
2225
2269
  let e = await t.keyRegistry.getPublicKey(o);
2226
2270
  if (!e) return {
@@ -2228,7 +2272,7 @@ async function Dn(e, t, n) {
2228
2272
  reason: "unknown-sender",
2229
2273
  detail: o
2230
2274
  };
2231
- if (!await w(a, e)) return {
2275
+ if (!await T(a, e)) return {
2232
2276
  ok: !1,
2233
2277
  reason: "invalid-signature"
2234
2278
  };
@@ -2239,7 +2283,7 @@ async function Dn(e, t, n) {
2239
2283
  reason: "unknown-sender",
2240
2284
  detail: a.signature.keyId
2241
2285
  };
2242
- if (!await S(a, e)) return {
2286
+ if (!await C(a, e)) return {
2243
2287
  ok: !1,
2244
2288
  reason: "invalid-signature"
2245
2289
  };
@@ -2253,24 +2297,24 @@ async function Dn(e, t, n) {
2253
2297
  envelope: a
2254
2298
  };
2255
2299
  }
2256
- async function On(e, t, n) {
2257
- let r = await C(e, t);
2300
+ async function Mn(e, t, n) {
2301
+ let r = await w(e, t);
2258
2302
  if (n?.format === "cbor") {
2259
- let e = wn(r);
2303
+ let e = En(r);
2260
2304
  return {
2261
- headers: { "content-type": Cn },
2305
+ headers: { "content-type": Tn },
2262
2306
  body: e
2263
2307
  };
2264
2308
  }
2265
2309
  return { headers: { [n?.headerName ?? "x-7h3-envelope"]: JSON.stringify(r) } };
2266
2310
  }
2267
- async function kn(e, t, n, r) {
2268
- let i = await me(e, t, n);
2311
+ async function Nn(e, t, n, r) {
2312
+ let i = await S(e, t, n);
2269
2313
  return { headers: { [r?.headerName ?? "x-7h3-envelope"]: JSON.stringify(i) } };
2270
2314
  }
2271
- function An(e) {
2315
+ function Pn(e) {
2272
2316
  return async function(t, n, r) {
2273
- let i = await Dn(t.headers, e);
2317
+ let i = await jn(t.headers, e);
2274
2318
  if (!i.ok) {
2275
2319
  n.status(401).json({
2276
2320
  error: "7h3: request verification failed",
@@ -2282,13 +2326,13 @@ function An(e) {
2282
2326
  t["7h3Envelope"] = i.envelope, r();
2283
2327
  };
2284
2328
  }
2285
- async function jn(e, t, n, r) {
2286
- let { headers: i } = await On(t, n, r), a = new Headers(e.headers);
2329
+ async function Fn(e, t, n, r) {
2330
+ let { headers: i } = await Mn(t, n, r), a = new Headers(e.headers);
2287
2331
  for (let [e, t] of Object.entries(i)) a.set(e, t);
2288
2332
  return new Request(e, { headers: a });
2289
2333
  }
2290
- async function Mn(e, t) {
2291
- return jn(e, E({
2334
+ async function In(e, t) {
2335
+ return Fn(e, D({
2292
2336
  sender: t.sender,
2293
2337
  recipient: t.recipient,
2294
2338
  ttlMs: t.ttlMs ?? 6e4,
@@ -2298,49 +2342,68 @@ async function Mn(e, t) {
2298
2342
  }
2299
2343
  //#endregion
2300
2344
  //#region src/webhookBinding.ts
2301
- var L = "x-7h3-sig", R = "x-7h3-ts", Nn = 3e5;
2302
- function Pn(e, t) {
2345
+ var R = "x-7h3-sig", z = "x-7h3-ts", Ln = 3e5, Rn = class {
2346
+ seen = /* @__PURE__ */ new Map();
2347
+ maxEntries;
2348
+ constructor(e = 1e4) {
2349
+ this.maxEntries = e;
2350
+ }
2351
+ prune(e) {
2352
+ for (let [t, n] of this.seen) n <= e && this.seen.delete(t);
2353
+ }
2354
+ consume(e, t, n) {
2355
+ this.prune(n);
2356
+ let r = this.seen.get(e);
2357
+ if (r !== void 0 && r > n) return !1;
2358
+ if (this.seen.size >= this.maxEntries) {
2359
+ let e = this.seen.keys().next().value;
2360
+ e !== void 0 && this.seen.delete(e);
2361
+ }
2362
+ return this.seen.set(e, t), !0;
2363
+ }
2364
+ };
2365
+ function B(e, t) {
2303
2366
  return `${e}.${t}`;
2304
2367
  }
2305
- async function Fn(e, t) {
2306
- let n = typeof e == "string" ? e : new TextDecoder().decode(e), r = Date.now(), i = await b(Pn(r, n), t.privateKey);
2368
+ async function zn(e, t) {
2369
+ let n = typeof e == "string" ? e : new TextDecoder().decode(e), r = Date.now(), i = await b(B(r, n), t.privateKey);
2307
2370
  return {
2308
- [L]: i,
2309
- [R]: String(r)
2371
+ [R]: i,
2372
+ [z]: String(r)
2310
2373
  };
2311
2374
  }
2312
- async function In(e, t) {
2313
- let n = typeof e == "string" ? e : new TextDecoder().decode(e), r = Date.now(), i = await de(Pn(r, n), t.secret);
2375
+ async function Bn(e, t) {
2376
+ let n = typeof e == "string" ? e : new TextDecoder().decode(e), r = Date.now(), i = await de(B(r, n), t.secret);
2314
2377
  return {
2315
- [L]: i,
2316
- [R]: String(r)
2378
+ [R]: i,
2379
+ [z]: String(r)
2317
2380
  };
2318
2381
  }
2319
- async function Ln(e, t, n) {
2320
- let r = typeof e == "string" ? e : new TextDecoder().decode(e), i = t[L], a = t[R];
2382
+ async function Vn(e, t, n) {
2383
+ let r = typeof e == "string" ? e : new TextDecoder().decode(e), i = t[R], a = t[z];
2321
2384
  if (!i || !a) return !1;
2322
2385
  let o = Number(a);
2323
2386
  if (!Number.isFinite(o)) return !1;
2324
- let s = n.maxAgeMs ?? 3e5;
2325
- return Date.now() - o > s ? !1 : x(Pn(o, r), i, n.publicKey);
2387
+ let s = n.maxAgeMs ?? 3e5, c = Date.now();
2388
+ return !(c - o > s || !await x(B(o, r), i, n.publicKey) || n.replayCache && !await n.replayCache.consume(i, o + s, c));
2326
2389
  }
2327
- async function Rn(e, t, n) {
2328
- let r = typeof e == "string" ? e : new TextDecoder().decode(e), i = t[L], a = t[R];
2390
+ async function Hn(e, t, n) {
2391
+ let r = typeof e == "string" ? e : new TextDecoder().decode(e), i = t[R], a = t[z];
2329
2392
  if (!i || !a) return !1;
2330
2393
  let o = Number(a);
2331
2394
  if (!Number.isFinite(o)) return !1;
2332
- let s = n.maxAgeMs ?? 3e5;
2333
- return Date.now() - o > s ? !1 : fe(Pn(o, r), i, n.secret);
2395
+ let s = n.maxAgeMs ?? 3e5, c = Date.now();
2396
+ return !(c - o > s || !await fe(B(o, r), i, n.secret) || n.replayCache && !await n.replayCache.consume(i, o + s, c));
2334
2397
  }
2335
- async function zn(e, t, n) {
2336
- if (!await Ln(e, t, n)) throw Error("7h3: webhook signature verification failed");
2398
+ async function Un(e, t, n) {
2399
+ if (!await Vn(e, t, n)) throw Error("7h3: webhook signature verification failed");
2337
2400
  return JSON.parse(e);
2338
2401
  }
2339
2402
  //#endregion
2340
2403
  //#region src/queueBinding.ts
2341
- async function Bn(e, t) {
2404
+ async function Wn(e, t) {
2342
2405
  let n = t.ttlMs ?? 36e5, r = typeof e == "string" ? e : JSON.stringify(e), i = {
2343
- envelope: await C(E({
2406
+ envelope: await w(D({
2344
2407
  sender: t.sender,
2345
2408
  recipient: t.recipient,
2346
2409
  intent: "TASK",
@@ -2351,7 +2414,7 @@ async function Bn(e, t) {
2351
2414
  };
2352
2415
  return JSON.stringify(i);
2353
2416
  }
2354
- async function Vn(e, t) {
2417
+ async function Gn(e, t) {
2355
2418
  let n;
2356
2419
  try {
2357
2420
  n = JSON.parse(e);
@@ -2361,10 +2424,10 @@ async function Vn(e, t) {
2361
2424
  if (!n.envelope || typeof n.envelope != "object") throw Error("Queue message missing envelope");
2362
2425
  let r = t.nowMs ?? Date.now();
2363
2426
  if (t.strictTtl ?? !0) {
2364
- let e = T(n.envelope, r).filter((e) => e.level === "error");
2427
+ let e = E(n.envelope, r).filter((e) => e.level === "error");
2365
2428
  if (e.length > 0) throw Error(`Queue message failed validation: ${e.map((e) => e.message).join("; ")}`);
2366
2429
  }
2367
- if (!await w(n.envelope, t.publicKey)) throw Error("Queue message signature verification failed");
2430
+ if (!await T(n.envelope, t.publicKey)) throw Error("Queue message signature verification failed");
2368
2431
  if (t.replayCache) {
2369
2432
  let e = await t.replayCache.consume(n.envelope, r);
2370
2433
  if (!e.ok) throw Error(e.reason ?? "Queue message replay detected");
@@ -2374,10 +2437,10 @@ async function Vn(e, t) {
2374
2437
  envelope: n.envelope
2375
2438
  };
2376
2439
  }
2377
- async function Hn(e, t) {
2440
+ async function Kn(e, t) {
2378
2441
  return Promise.all(e.map(async (e) => {
2379
2442
  try {
2380
- let { payload: n, envelope: r } = await Vn(e, t);
2443
+ let { payload: n, envelope: r } = await Gn(e, t);
2381
2444
  return {
2382
2445
  ok: !0,
2383
2446
  payload: n,
@@ -2394,87 +2457,87 @@ async function Hn(e, t) {
2394
2457
  }
2395
2458
  //#endregion
2396
2459
  //#region src/stream.ts
2397
- var Un = "x-7h3-stream", z = new TextEncoder();
2398
- function B() {
2460
+ var qn = "x-7h3-stream", V = new TextEncoder();
2461
+ function H() {
2399
2462
  if (typeof crypto > "u" || !crypto.subtle) throw Error("Web Crypto API is not available in this runtime");
2400
2463
  return crypto.subtle;
2401
2464
  }
2402
- function Wn() {
2465
+ function Jn() {
2403
2466
  return globalThis.Buffer;
2404
2467
  }
2405
- function V(e) {
2406
- let t = Wn();
2468
+ function U(e) {
2469
+ let t = Jn();
2407
2470
  return (t ? t.from(e).toString("base64") : btoa(String.fromCharCode(...e))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
2408
2471
  }
2409
- function H(e) {
2410
- let t = e.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(e.length / 4) * 4, "="), n = Wn();
2472
+ function W(e) {
2473
+ let t = e.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(e.length / 4) * 4, "="), n = Jn();
2411
2474
  if (n) return new Uint8Array(n.from(t, "base64"));
2412
2475
  let r = atob(t), i = new Uint8Array(r.length);
2413
2476
  for (let e = 0; e < r.length; e++) i[e] = r.charCodeAt(e);
2414
2477
  return i;
2415
2478
  }
2416
- function U(e) {
2479
+ function G(e) {
2417
2480
  return e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength);
2418
2481
  }
2419
- function Gn() {
2482
+ function Yn() {
2420
2483
  let e = /* @__PURE__ */ new Uint8Array(16);
2421
- return crypto.getRandomValues(e), V(e);
2484
+ return crypto.getRandomValues(e), U(e);
2422
2485
  }
2423
- var W = /* @__PURE__ */ new Map(), Kn = 128;
2424
- function qn(e, t) {
2425
- let n = `${e}:${t}`, r = W.get(n);
2486
+ var K = /* @__PURE__ */ new Map(), Xn = 128;
2487
+ function Zn(e, t) {
2488
+ let n = `${e}:${t}`, r = K.get(n);
2426
2489
  if (r) return r;
2427
- W.size >= Kn && W.clear();
2428
- let i = B(), a = H(e), o = (async () => {
2429
- let e = await i.importKey("raw", U(a), "HKDF", !1, ["deriveBits"]), n = await i.deriveBits({
2490
+ K.size >= Xn && K.clear();
2491
+ let i = H(), a = W(e), o = (async () => {
2492
+ let e = await i.importKey("raw", G(a), "HKDF", !1, ["deriveBits"]), n = await i.deriveBits({
2430
2493
  name: "HKDF",
2431
2494
  hash: "SHA-256",
2432
- salt: z.encode(t),
2433
- info: z.encode("7h3-stream/1")
2495
+ salt: V.encode(t),
2496
+ info: V.encode("7h3-stream/1")
2434
2497
  }, e, 256);
2435
2498
  return i.importKey("raw", n, {
2436
2499
  name: "HMAC",
2437
2500
  hash: "SHA-256"
2438
2501
  }, !1, ["sign"]);
2439
2502
  })();
2440
- return o.catch(() => W.delete(n)), W.set(n, o), o;
2503
+ return o.catch(() => K.delete(n)), K.set(n, o), o;
2441
2504
  }
2442
- var G = /* @__PURE__ */ new Map(), Jn = 64;
2443
- function Yn(e) {
2444
- let t = G.get(e);
2505
+ var q = /* @__PURE__ */ new Map(), Qn = 64;
2506
+ function $n(e) {
2507
+ let t = q.get(e);
2445
2508
  if (t) return t;
2446
- G.size >= Jn && G.clear();
2447
- let n = B().importKey("pkcs8", U(H(e)), { name: "Ed25519" }, !1, ["sign"]).catch((t) => {
2448
- throw G.delete(e), t;
2509
+ q.size >= Qn && q.clear();
2510
+ let n = H().importKey("pkcs8", G(W(e)), { name: "Ed25519" }, !1, ["sign"]).catch((t) => {
2511
+ throw q.delete(e), t;
2449
2512
  });
2450
- return G.set(e, n), n;
2513
+ return q.set(e, n), n;
2451
2514
  }
2452
- var K = /* @__PURE__ */ new Map(), Xn = 64;
2453
- function Zn(e) {
2454
- let t = K.get(e);
2515
+ var J = /* @__PURE__ */ new Map(), er = 64;
2516
+ function tr(e) {
2517
+ let t = J.get(e);
2455
2518
  if (t) return t;
2456
- K.size >= Xn && K.clear();
2457
- let n = B().importKey("spki", U(H(e)), { name: "Ed25519" }, !1, ["verify"]).catch((t) => {
2458
- throw K.delete(e), t;
2519
+ J.size >= er && J.clear();
2520
+ let n = H().importKey("spki", G(W(e)), { name: "Ed25519" }, !1, ["verify"]).catch((t) => {
2521
+ throw J.delete(e), t;
2459
2522
  });
2460
- return K.set(e, n), n;
2523
+ return J.set(e, n), n;
2461
2524
  }
2462
- function Qn(e) {
2525
+ function nr(e) {
2463
2526
  let t = e.map((e) => `${e.i}:${e.d}`);
2464
- return z.encode(t.join("\n"));
2527
+ return V.encode(t.join("\n"));
2465
2528
  }
2466
- async function $n(e) {
2467
- let t = await B().digest("SHA-256", U(e));
2529
+ async function rr(e) {
2530
+ let t = await H().digest("SHA-256", G(e));
2468
2531
  return new Uint8Array(t);
2469
2532
  }
2470
- var q = class {
2533
+ var ir = class {
2471
2534
  opts;
2472
2535
  seq = 0;
2473
2536
  accum = [];
2474
2537
  hmacKeyPromise = null;
2475
2538
  constructor(e) {
2476
2539
  this.opts = {
2477
- nonce: e.nonce ?? Gn(),
2540
+ nonce: e.nonce ?? Yn(),
2478
2541
  keyId: e.keyId ?? "stream-key",
2479
2542
  ...e
2480
2543
  };
@@ -2483,11 +2546,11 @@ var q = class {
2483
2546
  return this.opts.nonce;
2484
2547
  }
2485
2548
  getHmacKey() {
2486
- return this.hmacKeyPromise ||= qn(this.opts.privateKey, this.opts.nonce), this.hmacKeyPromise;
2549
+ return this.hmacKeyPromise ||= Zn(this.opts.privateKey, this.opts.nonce), this.hmacKeyPromise;
2487
2550
  }
2488
2551
  async computeChunkHmac(e, t) {
2489
- let n = B(), r = await this.getHmacKey(), i = `${this.opts.nonce}:${e}:${t}`, a = await n.sign("HMAC", r, z.encode(i));
2490
- return V(new Uint8Array(a));
2552
+ let n = H(), r = await this.getHmacKey(), i = `${this.opts.nonce}:${e}:${t}`, a = await n.sign("HMAC", r, V.encode(i));
2553
+ return U(new Uint8Array(a));
2491
2554
  }
2492
2555
  async writeChunk(e) {
2493
2556
  let t = this.seq++, n = await this.computeChunkHmac(t, e);
@@ -2502,17 +2565,17 @@ var q = class {
2502
2565
  };
2503
2566
  }
2504
2567
  async finalize() {
2505
- let e = B(), t = await Yn(this.opts.privateKey), n = await $n(Qn(this.accum)), r = await e.sign("Ed25519", t, U(n)), i = V(new Uint8Array(r)), a = this.seq;
2568
+ let e = H(), t = await $n(this.opts.privateKey), n = await rr(nr(this.accum)), r = await e.sign("Ed25519", t, G(n)), i = U(new Uint8Array(r)), a = this.seq;
2506
2569
  return {
2507
2570
  i: a,
2508
2571
  d: "",
2509
- h: await this.computeChunkHmac(a, V(n)),
2572
+ h: await this.computeChunkHmac(a, U(n)),
2510
2573
  f: !0,
2511
2574
  sig: i,
2512
2575
  kid: this.opts.keyId
2513
2576
  };
2514
2577
  }
2515
- }, er = class {
2578
+ }, ar = class {
2516
2579
  opts;
2517
2580
  expectedSeq = 0;
2518
2581
  accum = [];
@@ -2533,7 +2596,7 @@ var q = class {
2533
2596
  } : e.i === this.expectedSeq ? (this.expectedSeq++, this.accum.push({
2534
2597
  i: e.i,
2535
2598
  d: e.d
2536
- }), this.totalBytes += z.encode(e.d).length, { ok: !0 }) : {
2599
+ }), this.totalBytes += V.encode(e.d).length, { ok: !0 }) : {
2537
2600
  ok: !1,
2538
2601
  reason: `sequence error: expected ${this.expectedSeq}, got ${e.i}`
2539
2602
  };
@@ -2547,17 +2610,17 @@ var q = class {
2547
2610
  ok: !1,
2548
2611
  reason: "missing signature on final chunk"
2549
2612
  };
2550
- let t = B(), n;
2613
+ let t = H(), n;
2551
2614
  try {
2552
- n = await Zn(this.opts.publicKey);
2615
+ n = await tr(this.opts.publicKey);
2553
2616
  } catch {
2554
2617
  return {
2555
2618
  ok: !1,
2556
2619
  reason: "invalid public key"
2557
2620
  };
2558
2621
  }
2559
- let r = await $n(Qn(this.accum)), i = H(e.sig);
2560
- return await t.verify("Ed25519", n, U(i), U(r)) ? {
2622
+ let r = await rr(nr(this.accum)), i = W(e.sig);
2623
+ return await t.verify("Ed25519", n, G(i), G(r)) ? {
2561
2624
  ok: !0,
2562
2625
  totalBytes: this.totalBytes,
2563
2626
  chunkCount: this.accum.length
@@ -2567,20 +2630,20 @@ var q = class {
2567
2630
  };
2568
2631
  }
2569
2632
  };
2570
- function tr(e) {
2571
- return new q(e);
2633
+ function or(e) {
2634
+ return new ir(e);
2572
2635
  }
2573
- function nr(e) {
2574
- return new er(e);
2636
+ function sr(e) {
2637
+ return new ar(e);
2575
2638
  }
2576
- async function rr(e, t) {
2577
- let n = new q(t), r = [];
2639
+ async function cr(e, t) {
2640
+ let n = new ir(t), r = [];
2578
2641
  if (Array.isArray(e)) for (let t of e) r.push(await n.writeChunk(t));
2579
2642
  else for await (let t of e) r.push(await n.writeChunk(t));
2580
2643
  return r.push(await n.finalize()), r;
2581
2644
  }
2582
- async function ir(e, t) {
2583
- let n = new er(t), r = e.slice(0, -1), i = e[e.length - 1];
2645
+ async function lr(e, t) {
2646
+ let n = new ar(t), r = e.slice(0, -1), i = e[e.length - 1];
2584
2647
  if (e.length === 0) return {
2585
2648
  ok: !1,
2586
2649
  reason: "empty chunk array — missing final frame"
@@ -2606,10 +2669,10 @@ async function ir(e, t) {
2606
2669
  }
2607
2670
  return n.finalize(i);
2608
2671
  }
2609
- function ar(e) {
2672
+ function ur(e) {
2610
2673
  return JSON.stringify(e);
2611
2674
  }
2612
- function or(e) {
2675
+ function dr(e) {
2613
2676
  let t;
2614
2677
  try {
2615
2678
  t = JSON.parse(e);
@@ -2636,7 +2699,7 @@ function or(e) {
2636
2699
  }
2637
2700
  //#endregion
2638
2701
  //#region src/wsBinding.ts
2639
- function sr(e, t) {
2702
+ function fr(e, t) {
2640
2703
  let n = 0, r = [], i = [];
2641
2704
  function a(e, n) {
2642
2705
  t.onVerifyFail?.(e, n);
@@ -2660,15 +2723,22 @@ function sr(e, t) {
2660
2723
  a(/* @__PURE__ */ Error(`unknown sender: ${o}`), n);
2661
2724
  return;
2662
2725
  }
2663
- if (!await w(i, s).catch(() => !1)) {
2726
+ if (!await T(i, s).catch(() => !1)) {
2664
2727
  a(/* @__PURE__ */ Error("invalid signature"), n);
2665
2728
  return;
2666
2729
  }
2667
- let c = T(i);
2730
+ let c = E(i);
2668
2731
  if (c.some((e) => e.level === "error")) {
2669
2732
  a(/* @__PURE__ */ Error(`envelope invalid: ${c.map((e) => e.message).join("; ")}`), n);
2670
2733
  return;
2671
2734
  }
2735
+ if (t.replayCache) {
2736
+ let e = await t.replayCache.consume(i);
2737
+ if (!e.ok) {
2738
+ a(Error(e.reason ?? "replay detected"), n);
2739
+ return;
2740
+ }
2741
+ }
2672
2742
  let l = i.body.content;
2673
2743
  try {
2674
2744
  l = JSON.parse(i.body.content);
@@ -2682,7 +2752,7 @@ function sr(e, t) {
2682
2752
  return n;
2683
2753
  },
2684
2754
  async send(r) {
2685
- let i = typeof r == "string" ? r : JSON.stringify(r), a = await C(E({
2755
+ let i = typeof r == "string" ? r : JSON.stringify(r), a = await w(D({
2686
2756
  sender: t.sender,
2687
2757
  recipient: t.recipient,
2688
2758
  ttlMs: t.ttlMs ?? 3e4,
@@ -2700,28 +2770,28 @@ function sr(e, t) {
2700
2770
  }
2701
2771
  };
2702
2772
  }
2703
- function cr(e, t) {
2704
- let n = new q(t), r = async (t) => {
2773
+ function pr(e, t) {
2774
+ let n = new ir(t), r = async (t) => {
2705
2775
  let r = typeof t.data == "string" ? t.data : t.data.toString("utf8"), i = await n.writeChunk(r);
2706
- e.send(ar(i));
2776
+ e.send(ur(i));
2707
2777
  }, i = async () => {
2708
2778
  e.removeEventListener("message", r), e.removeEventListener("close", i);
2709
2779
  let t = await n.finalize();
2710
- e.send(ar(t));
2780
+ e.send(ur(t));
2711
2781
  };
2712
2782
  return e.addEventListener("message", r), e.addEventListener("close", i), n;
2713
2783
  }
2714
- function lr(e, t) {
2784
+ function mr(e, t) {
2715
2785
  return new Promise((n, r) => {
2716
2786
  let i = [], a = async (e) => {
2717
2787
  let a = typeof e.data == "string" ? e.data : e.data.toString("utf8"), o;
2718
2788
  try {
2719
- o = or(a);
2789
+ o = dr(a);
2720
2790
  } catch (e) {
2721
2791
  s(), r(e);
2722
2792
  return;
2723
2793
  }
2724
- i.push(o), o.f && (s(), n(await ir(i, t)));
2794
+ i.push(o), o.f && (s(), n(await lr(i, t)));
2725
2795
  }, o = () => {
2726
2796
  s(), n({
2727
2797
  ok: !1,
@@ -2736,9 +2806,9 @@ function lr(e, t) {
2736
2806
  }
2737
2807
  //#endregion
2738
2808
  //#region src/grpcBinding.ts
2739
- var ur = "7h3-envelope-bin";
2740
- async function dr(e) {
2741
- let t = await C(E({
2809
+ var hr = "7h3-envelope-bin";
2810
+ async function gr(e) {
2811
+ let t = await w(D({
2742
2812
  sender: e.sender,
2743
2813
  recipient: e.recipient,
2744
2814
  ttlMs: e.ttlMs ?? 6e4,
@@ -2747,7 +2817,7 @@ async function dr(e) {
2747
2817
  }), e.privateKey);
2748
2818
  return { [e.metadataKey ?? "7h3-envelope-bin"]: JSON.stringify(t) };
2749
2819
  }
2750
- async function fr(e, t) {
2820
+ async function _r(e, t) {
2751
2821
  let n = e[t.metadataKey ?? "7h3-envelope-bin"], r = Array.isArray(n) ? n[0] : n instanceof Uint8Array ? new TextDecoder().decode(n) : n;
2752
2822
  if (!r) return {
2753
2823
  ok: !1,
@@ -2764,7 +2834,7 @@ async function fr(e, t) {
2764
2834
  message: "7h3: malformed envelope metadata"
2765
2835
  };
2766
2836
  }
2767
- if (t.strictTtl !== !1 && T(i).some((e) => e.level === "error")) return {
2837
+ if (t.strictTtl !== !1 && E(i).some((e) => e.level === "error")) return {
2768
2838
  ok: !1,
2769
2839
  code: 4,
2770
2840
  message: "7h3: envelope expired or invalid"
@@ -2782,7 +2852,7 @@ async function fr(e, t) {
2782
2852
  code: 16,
2783
2853
  message: `7h3: unknown sender ${a}`
2784
2854
  };
2785
- if (!await w(i, e)) return {
2855
+ if (!await T(i, e)) return {
2786
2856
  ok: !1,
2787
2857
  code: 16,
2788
2858
  message: "7h3: invalid signature"
@@ -2794,7 +2864,7 @@ async function fr(e, t) {
2794
2864
  code: 16,
2795
2865
  message: "7h3: unknown key"
2796
2866
  };
2797
- if (!await S(i, e)) return {
2867
+ if (!await C(i, e)) return {
2798
2868
  ok: !1,
2799
2869
  code: 16,
2800
2870
  message: "7h3: invalid signature"
@@ -2809,39 +2879,39 @@ async function fr(e, t) {
2809
2879
  envelope: i
2810
2880
  };
2811
2881
  }
2812
- function pr(e, t) {
2882
+ function vr(e, t) {
2813
2883
  return async (n) => {
2814
- let r = await fr(n.metadata, t);
2884
+ let r = await _r(n.metadata, t);
2815
2885
  if (!r.ok) throw Object.assign(Error(r.message), { code: r.code });
2816
2886
  return n["7h3Envelope"] = r.envelope, e(n);
2817
2887
  };
2818
2888
  }
2819
2889
  //#endregion
2820
2890
  //#region src/keyInfra.ts
2821
- function mr(e) {
2891
+ function yr(e) {
2822
2892
  return JSON.stringify(e);
2823
2893
  }
2824
- function hr(e) {
2894
+ function br(e) {
2825
2895
  let t = JSON.parse(e);
2826
2896
  if (t.version !== "7h3/0.1") throw Error(`unsupported version: ${t.version}`);
2827
2897
  return t;
2828
2898
  }
2829
- async function gr(e, t) {
2899
+ async function xr(e, t) {
2830
2900
  let n = e.replace(/\/$/, "") + "/.well-known/7h3-keys", r = new AbortController(), i = t?.timeout ? setTimeout(() => r.abort(), t.timeout) : void 0;
2831
2901
  try {
2832
2902
  let e = await fetch(n, { signal: r.signal });
2833
2903
  if (!e.ok) throw Error(`HTTP ${e.status} from ${n}`);
2834
- return hr(await e.text());
2904
+ return br(await e.text());
2835
2905
  } finally {
2836
2906
  i !== void 0 && clearTimeout(i);
2837
2907
  }
2838
2908
  }
2839
- function _r(e) {
2909
+ function Sr(e) {
2840
2910
  let t = /* @__PURE__ */ new Map(), n = e?.cacheMs ?? 6e4, r = e?.timeout ?? 5e3;
2841
2911
  async function i(e) {
2842
2912
  let i = Date.now(), a = t.get(e);
2843
2913
  if (a && a.expiresAt > i) return a.doc;
2844
- let o = await gr(e, { timeout: r });
2914
+ let o = await xr(e, { timeout: r });
2845
2915
  return t.set(e, {
2846
2916
  doc: o,
2847
2917
  expiresAt: i + n
@@ -2858,7 +2928,7 @@ function _r(e) {
2858
2928
  }
2859
2929
  } };
2860
2930
  }
2861
- var vr = class {
2931
+ var Cr = class {
2862
2932
  maxAgeMs;
2863
2933
  overlapMs;
2864
2934
  keys = [];
@@ -2905,10 +2975,10 @@ var vr = class {
2905
2975
  toKeyRegistry() {
2906
2976
  return { getPublicKey: async (e) => {
2907
2977
  let t = Date.now();
2908
- return this.keys.find((n) => n.id === e && (!n.expiresAt || n.expiresAt > t))?.publicKey ?? this.getCurrentKey()?.publicKey ?? null;
2978
+ return this.keys.find((n) => n.id === e && (!n.expiresAt || n.expiresAt > t))?.publicKey ?? null;
2909
2979
  } };
2910
2980
  }
2911
- }, yr = class {
2981
+ }, wr = class {
2912
2982
  revoked = /* @__PURE__ */ new Map();
2913
2983
  revoke(e, t) {
2914
2984
  this.revoked.set(e, {
@@ -2933,11 +3003,15 @@ var vr = class {
2933
3003
  wrapRegistry(e) {
2934
3004
  return {
2935
3005
  getPublicKey: async (t) => this.isRevoked(t) ? null : e.getPublicKey(t),
2936
- getSharedSecret: e.getSharedSecret?.bind(e)
3006
+ getSharedSecret: e.getSharedSecret ? async (t, n) => this.isRevoked(t) || this.isRevoked(n) ? null : e.getSharedSecret(t, n) : void 0
2937
3007
  };
2938
3008
  }
2939
- }, br = class {
3009
+ }, Tr = class {
2940
3010
  windows = /* @__PURE__ */ new Map();
3011
+ maxKeys;
3012
+ constructor(e = {}) {
3013
+ this.maxKeys = e.maxKeys ?? 5e4;
3014
+ }
2941
3015
  check(e, t, n = Date.now()) {
2942
3016
  let r = n - t.windowMs, i = (this.windows.get(e) ?? []).filter((e) => e > r), a = i.length, o = a < t.requests;
2943
3017
  return {
@@ -2948,7 +3022,13 @@ var vr = class {
2948
3022
  }
2949
3023
  consume(e, t, n = Date.now()) {
2950
3024
  let r = n - t.windowMs, i = (this.windows.get(e) ?? []).filter((e) => e > r), a = i.length < t.requests;
2951
- return a && (i.push(n), this.windows.set(e, i)), {
3025
+ if (a && i.push(n), i.length > 0) for (this.windows.delete(e), this.windows.set(e, i); this.windows.size > this.maxKeys;) {
3026
+ let e = this.windows.keys().next().value;
3027
+ if (e === void 0) break;
3028
+ this.windows.delete(e);
3029
+ }
3030
+ else this.windows.delete(e);
3031
+ return {
2952
3032
  allowed: a,
2953
3033
  remaining: Math.max(0, t.requests - i.length),
2954
3034
  resetMs: i.length > 0 ? Math.max(0, i[0] + t.windowMs - n) : 0
@@ -2960,10 +3040,10 @@ var vr = class {
2960
3040
  clear() {
2961
3041
  this.windows.clear();
2962
3042
  }
2963
- }, xr = new br();
3043
+ }, Er = new Tr();
2964
3044
  //#endregion
2965
3045
  //#region src/routePolicy.ts
2966
- function J(e, t) {
3046
+ function Dr(e, t) {
2967
3047
  let n = "^", r = 0;
2968
3048
  for (; r < e.length;) {
2969
3049
  let t = e[r];
@@ -2971,18 +3051,18 @@ function J(e, t) {
2971
3051
  }
2972
3052
  return n += "$", new RegExp(n).test(t);
2973
3053
  }
2974
- function Sr(e, t) {
2975
- for (let n of e) if (J(n.path, t)) return n;
3054
+ function Or(e, t) {
3055
+ for (let n of e) if (Dr(n.path, t)) return n;
2976
3056
  return null;
2977
3057
  }
2978
- function Cr(e, t) {
3058
+ function kr(e, t) {
2979
3059
  return !e.allowedSenders || e.allowedSenders.length === 0 || e.allowedSenders.includes(t);
2980
3060
  }
2981
3061
  //#endregion
2982
3062
  //#region src/signedResponse.ts
2983
- var wr = "x-7h3-response";
2984
- async function Tr(e, t) {
2985
- let n = await C(E({
3063
+ var Ar = "x-7h3-response";
3064
+ async function jr(e, t) {
3065
+ let n = await w(D({
2986
3066
  sender: t.sender,
2987
3067
  recipient: t.recipient,
2988
3068
  intent: "RESULT",
@@ -2990,10 +3070,10 @@ async function Tr(e, t) {
2990
3070
  correlationId: t.correlationId,
2991
3071
  ttlMs: t.ttlMs ?? 6e4
2992
3072
  }), t.privateKey);
2993
- return { headers: { [wr]: JSON.stringify(n) } };
3073
+ return { headers: { [Ar]: JSON.stringify(n) } };
2994
3074
  }
2995
- async function Er(e, t, n) {
2996
- let r = t[wr], i = Array.isArray(r) ? r[0] : r;
3075
+ async function Mr(e, t, n) {
3076
+ let r = t[Ar], i = Array.isArray(r) ? r[0] : r;
2997
3077
  if (!i) return {
2998
3078
  ok: !1,
2999
3079
  reason: "missing-header"
@@ -3012,7 +3092,7 @@ async function Er(e, t, n) {
3012
3092
  ok: !1,
3013
3093
  reason: "ttl-expired",
3014
3094
  envelope: a
3015
- } : await w(a, n.publicKey) ? a.body.content === e ? {
3095
+ } : await T(a, n.publicKey) ? a.body.content === e ? {
3016
3096
  ok: !0,
3017
3097
  envelope: a
3018
3098
  } : {
@@ -3027,21 +3107,21 @@ async function Er(e, t, n) {
3027
3107
  }
3028
3108
  //#endregion
3029
3109
  //#region src/telemetry.ts
3030
- function Y(e) {
3110
+ function Nr(e) {
3031
3111
  return !e || Object.keys(e).length === 0 ? "__default__" : Object.entries(e).sort(([e], [t]) => e.localeCompare(t)).map(([e, t]) => `${e}=${t}`).join(",");
3032
3112
  }
3033
- function Dr(e) {
3113
+ function Pr(e) {
3034
3114
  return !e || Object.keys(e).length === 0 ? "" : `{${Object.entries(e).sort(([e], [t]) => e.localeCompare(t)).map(([e, t]) => `${e}="${t}"`).join(",")}}`;
3035
3115
  }
3036
- var X = class {
3116
+ var Y = class {
3037
3117
  counts = /* @__PURE__ */ new Map();
3038
3118
  labelSets = /* @__PURE__ */ new Map();
3039
3119
  increment(e) {
3040
- let t = Y(e);
3120
+ let t = Nr(e);
3041
3121
  this.counts.set(t, (this.counts.get(t) ?? 0) + 1), this.labelSets.has(t) || this.labelSets.set(t, e);
3042
3122
  }
3043
3123
  value(e) {
3044
- return this.counts.get(Y(e)) ?? 0;
3124
+ return this.counts.get(Nr(e)) ?? 0;
3045
3125
  }
3046
3126
  entries() {
3047
3127
  let e = [];
@@ -3051,7 +3131,7 @@ var X = class {
3051
3131
  });
3052
3132
  return e;
3053
3133
  }
3054
- }, Or = class {
3134
+ }, Fr = class {
3055
3135
  bucketBounds;
3056
3136
  states = /* @__PURE__ */ new Map();
3057
3137
  labelSets = /* @__PURE__ */ new Map();
@@ -3071,7 +3151,7 @@ var X = class {
3071
3151
  this.bucketBounds = [...e].sort((e, t) => e - t);
3072
3152
  }
3073
3153
  observe(e, t) {
3074
- let n = Y(t);
3154
+ let n = Nr(t);
3075
3155
  this.states.has(n) || (this.states.set(n, {
3076
3156
  count: 0,
3077
3157
  sum: 0,
@@ -3081,7 +3161,7 @@ var X = class {
3081
3161
  r.count++, r.sum += e, r.observations.push(e);
3082
3162
  }
3083
3163
  snapshot(e) {
3084
- let t = Y(e), n = this.states.get(t) ?? {
3164
+ let t = Nr(e), n = this.states.get(t) ?? {
3085
3165
  count: 0,
3086
3166
  sum: 0,
3087
3167
  observations: []
@@ -3107,9 +3187,9 @@ var X = class {
3107
3187
  getBounds() {
3108
3188
  return [...this.bucketBounds];
3109
3189
  }
3110
- }, kr = class {
3111
- verifications_total = new X();
3112
- verification_duration_ms = new Or([
3190
+ }, Ir = class {
3191
+ verifications_total = new Y();
3192
+ verification_duration_ms = new Fr([
3113
3193
  .1,
3114
3194
  .5,
3115
3195
  1,
@@ -3118,20 +3198,20 @@ var X = class {
3118
3198
  50,
3119
3199
  100
3120
3200
  ]);
3121
- rate_limit_hits_total = new X();
3122
- sender_denials_total = new X();
3123
- replay_detections_total = new X();
3124
- audit_entries_total = new X();
3125
- active_connections = new X();
3126
- }, Z = new kr();
3127
- function Ar(e, t = "7h3") {
3201
+ rate_limit_hits_total = new Y();
3202
+ sender_denials_total = new Y();
3203
+ replay_detections_total = new Y();
3204
+ audit_entries_total = new Y();
3205
+ active_connections = new Y();
3206
+ }, X = new Ir();
3207
+ function Lr(e, t = "7h3") {
3128
3208
  let n = [];
3129
3209
  function r(e, r, i) {
3130
3210
  let a = `${t}_${e}`;
3131
3211
  n.push(`# HELP ${a} ${r}`), n.push(`# TYPE ${a} counter`);
3132
3212
  let o = i.entries();
3133
3213
  if (o.length === 0) n.push(`${a} 0`);
3134
- else for (let { labels: e, value: t } of o) e && Object.keys(e).length > 0 ? n.push(`${a}${Dr(e)} ${t}`) : n.push(`${a} ${t}`);
3214
+ else for (let { labels: e, value: t } of o) e && Object.keys(e).length > 0 ? n.push(`${a}${Pr(e)} ${t}`) : n.push(`${a} ${t}`);
3135
3215
  }
3136
3216
  function i(e, r, i) {
3137
3217
  let a = `${t}_${e}`;
@@ -3141,7 +3221,7 @@ function Ar(e, t = "7h3") {
3141
3221
  for (let e of i.getBounds()) n.push(`${a}_bucket{le="${e}"} 0`);
3142
3222
  n.push(`${a}_bucket{le="+Inf"} 0`), n.push(`${a}_sum 0`), n.push(`${a}_count 0`);
3143
3223
  } else for (let { labels: e, snapshot: t } of o) {
3144
- let r = e && Object.keys(e).length > 0 ? Dr(e) : "";
3224
+ let r = e && Object.keys(e).length > 0 ? Pr(e) : "";
3145
3225
  for (let [e, i] of Object.entries(t.buckets)) {
3146
3226
  if (e === "+Inf") continue;
3147
3227
  let t = r ? r.slice(0, -1) + `,le="${e}"}` : `{le="${e}"}`;
@@ -3153,28 +3233,28 @@ function Ar(e, t = "7h3") {
3153
3233
  }
3154
3234
  return r("verifications_total", "Total number of AIP envelope verifications, by result, algorithm, and transport", e.verifications_total), i("verification_duration_ms", "Verification latency in milliseconds", e.verification_duration_ms), r("rate_limit_hits_total", "Total number of rate-limit rejections, by sender and path", e.rate_limit_hits_total), r("sender_denials_total", "Total number of sender-denied (403) rejections, by sender and path", e.sender_denials_total), r("replay_detections_total", "Total number of replay-detected events, by transport", e.replay_detections_total), r("audit_entries_total", "Total number of audit log entries written, by type", e.audit_entries_total), r("active_connections", "Current active connections, by transport (WS/gRPC)", e.active_connections), n.join("\n") + "\n";
3155
3235
  }
3156
- function jr(e = "/metrics", t = Z, n = "7h3") {
3236
+ function Rr(e = "/metrics", t = X, n = "7h3") {
3157
3237
  return (r, i, a) => {
3158
3238
  if (r.url === e && (r.method === "GET" || r.method === void 0)) {
3159
- let e = Ar(t, n);
3239
+ let e = Lr(t, n);
3160
3240
  i.writeHead(200, { "content-type": "text/plain; version=0.0.4; charset=utf-8" }), i.end(e);
3161
3241
  } else a();
3162
3242
  };
3163
3243
  }
3164
3244
  //#endregion
3165
3245
  //#region src/capability.ts
3166
- var Mr = "x-7h3-capability";
3167
- function Nr(e) {
3246
+ var zr = "x-7h3-capability";
3247
+ function Br(e) {
3168
3248
  let t = [];
3169
3249
  return e.maxDelegations !== void 0 && t.push(`"maxDelegations":${e.maxDelegations}`), e.methods !== void 0 && t.push(`"methods":${JSON.stringify(e.methods)}`), t.push(`"pathGlob":${JSON.stringify(e.pathGlob)}`), `{${t.join(",")}}`;
3170
3250
  }
3171
- function Q(e) {
3251
+ function Z(e) {
3172
3252
  let t = [];
3173
3253
  t.push(`"delegationDepth":${e.delegationDepth}`), t.push(`"expiresAt":${e.expiresAt}`), t.push(`"id":${JSON.stringify(e.id)}`), t.push(`"issuedAt":${e.issuedAt}`), t.push(`"issuer":${JSON.stringify(e.issuer)}`), t.push(`"keyId":${JSON.stringify(e.keyId)}`), e.maxDelegations !== void 0 && t.push(`"maxDelegations":${e.maxDelegations}`), e.parentTokenId !== void 0 && t.push(`"parentTokenId":${JSON.stringify(e.parentTokenId)}`);
3174
- let n = `[${e.scopes.map(Nr).join(",")}]`;
3254
+ let n = `[${e.scopes.map(Br).join(",")}]`;
3175
3255
  return t.push(`"scopes":${n}`), t.push(`"subject":${JSON.stringify(e.subject)}`), t.push(`"version":${JSON.stringify(e.version)}`), `{${t.join(",")}}`;
3176
3256
  }
3177
- async function Pr(e) {
3257
+ async function Vr(e) {
3178
3258
  let t = Date.now(), n = `cap-${t}-${y(6)}`, r = e.keyId ?? `${e.issuerId}-key`, i = e.maxDelegations ?? 0, a = {
3179
3259
  id: n,
3180
3260
  version: "7h3-cap/1",
@@ -3186,32 +3266,46 @@ async function Pr(e) {
3186
3266
  delegationDepth: 0,
3187
3267
  maxDelegations: i,
3188
3268
  keyId: r
3189
- }, o = await b(Q(a), e.issuerPrivateKey);
3269
+ }, o = await b(Z(a), e.issuerPrivateKey);
3190
3270
  return {
3191
3271
  ...a,
3192
3272
  signature: o
3193
3273
  };
3194
3274
  }
3195
- function Fr(e, t) {
3196
- if (!J(t.pathGlob, e.pathGlob)) return !1;
3275
+ function Hr(e, t) {
3276
+ return e === t || t === "*" && e !== "**";
3277
+ }
3278
+ function Ur(e, t) {
3279
+ let n = e.split("/"), r = t.split("/"), i = 0;
3280
+ for (let e of r) {
3281
+ if (e === "**") return i < n.length;
3282
+ if (i >= n.length) return !1;
3283
+ let t = n[i];
3284
+ if (t === "**" || !Hr(t, e)) return !1;
3285
+ i += 1;
3286
+ }
3287
+ return i === n.length;
3288
+ }
3289
+ function Wr(e, t) {
3290
+ if (!Ur(e.pathGlob, t.pathGlob)) return !1;
3197
3291
  if (t.methods !== void 0) {
3198
3292
  if (e.methods === void 0) return !1;
3199
3293
  for (let n of e.methods) if (!t.methods.includes(n)) return !1;
3200
3294
  }
3201
3295
  return !0;
3202
3296
  }
3203
- function Ir(e, t) {
3204
- for (let n of e) if (!t.some((e) => Fr(n, e))) return !1;
3297
+ function Gr(e, t) {
3298
+ for (let n of e) if (!t.some((e) => Wr(n, e))) return !1;
3205
3299
  return !0;
3206
3300
  }
3207
- async function Lr(e) {
3301
+ async function Kr(e) {
3208
3302
  let { parentToken: t, delegatorId: n, newSubject: r } = e;
3209
3303
  if (n !== t.subject) throw Error(`delegatorId '${n}' does not match parentToken.subject '${t.subject}'`);
3210
3304
  let i = Date.now();
3211
3305
  if (i >= t.expiresAt) throw Error("Parent token is expired");
3212
3306
  if (t.maxDelegations !== void 0 && t.maxDelegations <= 0) throw Error("Parent token does not allow further delegation (maxDelegations=0)");
3213
3307
  let a = e.scopes ?? t.scopes;
3214
- if (!Ir(a, t.scopes)) throw Error("Delegated scopes exceed parent token scopes");
3308
+ if (!Gr(a, t.scopes)) throw Error("Delegated scopes exceed parent token scopes");
3215
3309
  let o = t.expiresAt - i;
3216
3310
  if (e.ttlMs > o) throw Error(`Delegated ttlMs (${e.ttlMs}) exceeds parent token remaining TTL (${o})`);
3217
3311
  let s = `cap-${i}-${y(6)}`, c = e.keyId ?? `${n}-key`, l = t.maxDelegations === void 0 ? void 0 : t.maxDelegations - 1, u = {
@@ -3226,18 +3320,18 @@ async function Lr(e) {
3226
3320
  parentTokenId: t.id,
3227
3321
  maxDelegations: l,
3228
3322
  keyId: c
3229
- }, d = await b(Q(u), e.delegatorPrivateKey);
3323
+ }, d = await b(Z(u), e.delegatorPrivateKey);
3230
3324
  return {
3231
3325
  ...u,
3232
3326
  signature: d
3233
3327
  };
3234
3328
  }
3235
- async function Rr(e, t, n) {
3329
+ async function qr(e, t, n) {
3236
3330
  if ((n?.now ?? Date.now()) >= e.expiresAt) return !1;
3237
3331
  let { signature: r, ...i } = e;
3238
- return x(Q(i), r, t);
3332
+ return x(Z(i), r, t);
3239
3333
  }
3240
- async function zr(e, t, n) {
3334
+ async function Jr(e, t, n) {
3241
3335
  if (e.length === 0) return {
3242
3336
  ok: !1,
3243
3337
  reason: "empty-chain"
@@ -3263,6 +3357,18 @@ async function zr(e, t, n) {
3263
3357
  ok: !1,
3264
3358
  reason: `chain-broken: token[${n}].delegationDepth ${i.delegationDepth} !== ${t.delegationDepth + 1}`
3265
3359
  };
3360
+ if (t.maxDelegations !== void 0 && t.maxDelegations <= 0) return {
3361
+ ok: !1,
3362
+ reason: `chain-broken: token[${n - 1}] does not permit further delegation (maxDelegations=0)`
3363
+ };
3364
+ if (i.expiresAt > t.expiresAt) return {
3365
+ ok: !1,
3366
+ reason: `chain-broken: token[${n}].expiresAt exceeds token[${n - 1}].expiresAt`
3367
+ };
3368
+ if (!Gr(i.scopes, t.scopes)) return {
3369
+ ok: !1,
3370
+ reason: `chain-broken: token[${n}].scopes exceed token[${n - 1}].scopes`
3371
+ };
3266
3372
  }
3267
3373
  if (r >= i.expiresAt) return {
3268
3374
  ok: !1,
@@ -3274,13 +3380,13 @@ async function zr(e, t, n) {
3274
3380
  reason: `no-public-key-for-issuer:${i.issuer}`
3275
3381
  };
3276
3382
  let { signature: o, ...s } = i;
3277
- if (!await x(Q(s), o, a)) return {
3383
+ if (!await x(Z(s), o, a)) return {
3278
3384
  ok: !1,
3279
3385
  reason: `invalid-signature-at-index:${n}`
3280
3386
  };
3281
3387
  }
3282
3388
  let i = e[e.length - 1];
3283
- return n?.requiredPathGlob !== void 0 && !Br(i, n.requiredPathGlob, n.requiredMethod) ? {
3389
+ return n?.requiredPathGlob !== void 0 && !Yr(i, n.requiredPathGlob, n.requiredMethod) ? {
3284
3390
  ok: !1,
3285
3391
  reason: "leaf-token-does-not-cover-required-scope"
3286
3392
  } : {
@@ -3289,85 +3395,151 @@ async function zr(e, t, n) {
3289
3395
  chain: e
3290
3396
  };
3291
3397
  }
3292
- function Br(e, t, n) {
3293
- for (let r of e.scopes) if (J(r.pathGlob, t) && (r.methods === void 0 || n === void 0 || r.methods.includes(n.toUpperCase()))) return !0;
3398
+ function Yr(e, t, n) {
3399
+ for (let r of e.scopes) if (Dr(r.pathGlob, t) && (r.methods === void 0 || n !== void 0 && r.methods.includes(n.toUpperCase()))) return !0;
3294
3400
  return !1;
3295
3401
  }
3296
- function Vr(e) {
3402
+ function Xr(e) {
3297
3403
  return JSON.stringify(e);
3298
3404
  }
3299
- function Hr(e) {
3405
+ function Zr(e) {
3300
3406
  return JSON.parse(e);
3301
3407
  }
3302
3408
  //#endregion
3303
3409
  //#region src/gateway.ts
3304
- var Ur = class {
3410
+ function Qr(e) {
3411
+ if (!e.startsWith("/")) return null;
3412
+ let t = e;
3413
+ for (let e = 0; e < 5; e++) {
3414
+ let e;
3415
+ try {
3416
+ e = decodeURIComponent(t);
3417
+ } catch {
3418
+ return null;
3419
+ }
3420
+ if (e === t) break;
3421
+ t = e;
3422
+ }
3423
+ if (/%[0-9a-fA-F]{2}/.test(t) || /[\x00-\x1f]/.test(t)) return null;
3424
+ let n = t.split("/"), r = [];
3425
+ for (let e of n) if (!(e === "" || e === ".")) {
3426
+ if (e === "..") {
3427
+ if (r.length === 0) return null;
3428
+ r.pop();
3429
+ continue;
3430
+ }
3431
+ r.push(e);
3432
+ }
3433
+ return "/" + r.join("/");
3434
+ }
3435
+ var $r = class {
3305
3436
  config;
3306
3437
  rateLimiter;
3307
3438
  constructor(e) {
3308
- this.config = e, this.rateLimiter = new br(), !e.replayStore && (e.policies ?? []).some((e) => e.require !== "none") && console.warn("[7h3-protocol] createGateway(): no replayStore configured with signature-requiring policies. Nonce/replay protection will not survive multiple gateway instances or restarts. See docs/GATEWAY.md#production-safety.");
3439
+ this.config = e, this.rateLimiter = new Tr(), !e.replayStore && (e.policies ?? []).some((e) => e.require !== "none") && console.warn("[7h3-protocol] createGateway(): no replayStore configured with signature-requiring policies. Nonce/replay protection will not survive multiple gateway instances or restarts. See docs/GATEWAY.md#production-safety.");
3440
+ }
3441
+ async checkSenderAndRateLimit(e, t, n, r, i) {
3442
+ if (e && !kr(e, t)) {
3443
+ let e = performance.now() - i;
3444
+ return X.verifications_total.increment({
3445
+ result: "fail",
3446
+ alg: n,
3447
+ transport: "http"
3448
+ }), X.verification_duration_ms.observe(e), X.sender_denials_total.increment({
3449
+ sender: t,
3450
+ path: r.path
3451
+ }), {
3452
+ ok: !1,
3453
+ status: 403,
3454
+ reason: "sender-denied"
3455
+ };
3456
+ }
3457
+ if (e?.rateLimit && !(this.config.rateLimitStore ? await this.config.rateLimitStore.consume(t, e.rateLimit) : this.rateLimiter.consume(t, e.rateLimit)).allowed) {
3458
+ let e = performance.now() - i;
3459
+ return X.verifications_total.increment({
3460
+ result: "fail",
3461
+ alg: n,
3462
+ transport: "http"
3463
+ }), X.verification_duration_ms.observe(e), X.rate_limit_hits_total.increment({
3464
+ sender: t,
3465
+ path: r.path
3466
+ }), {
3467
+ ok: !1,
3468
+ status: 429,
3469
+ reason: "rate-limited"
3470
+ };
3471
+ }
3472
+ return null;
3309
3473
  }
3310
3474
  async verify(e) {
3311
- let t = performance.now(), n = Sr(this.config.policies ?? [], e.path);
3312
- if (n?.require === "none" || !n && (this.config.defaultPolicy ?? "allow") === "allow") {
3475
+ let t = performance.now(), n = Qr(e.path);
3476
+ if (n === null) return {
3477
+ ok: !1,
3478
+ status: 400,
3479
+ reason: "invalid-path"
3480
+ };
3481
+ let r = Or(this.config.policies ?? [], n);
3482
+ if (r?.require === "none" || !r && (this.config.defaultPolicy ?? "allow") === "allow") {
3313
3483
  let e = performance.now() - t;
3314
- return Z.verifications_total.increment({
3484
+ return X.verifications_total.increment({
3315
3485
  result: "ok",
3316
3486
  alg: "none",
3317
3487
  transport: "http"
3318
- }), Z.verification_duration_ms.observe(e), {
3488
+ }), X.verification_duration_ms.observe(e), {
3319
3489
  ok: !0,
3320
3490
  sender: ""
3321
3491
  };
3322
3492
  }
3323
3493
  if (this.config.capabilityRegistry) {
3324
- let n = e.headers[Mr], r = Array.isArray(n) ? n[0] : n;
3325
- if (r) try {
3326
- let n = await zr(Hr(r), this.config.capabilityRegistry, {
3494
+ let n = e.headers[zr], i = Array.isArray(n) ? n[0] : n;
3495
+ if (i) try {
3496
+ let n = await Jr(Zr(i), this.config.capabilityRegistry, {
3327
3497
  requiredPathGlob: e.path,
3328
3498
  requiredMethod: e.method
3329
3499
  });
3330
- if (n.ok && Br(n.token, e.path, e.method)) {
3331
- let e = performance.now() - t;
3332
- return Z.verifications_total.increment({
3500
+ if (n.ok && Yr(n.token, e.path, e.method)) {
3501
+ let i = n.token.subject, a = await this.checkSenderAndRateLimit(r, i, "ED25519", e, t);
3502
+ if (a) return a;
3503
+ let o = performance.now() - t;
3504
+ return X.verifications_total.increment({
3333
3505
  result: "ok",
3334
3506
  alg: "ED25519",
3335
3507
  transport: "http"
3336
- }), Z.verification_duration_ms.observe(e), {
3508
+ }), X.verification_duration_ms.observe(o), {
3337
3509
  ok: !0,
3338
- sender: n.token.subject
3510
+ sender: i
3339
3511
  };
3340
3512
  }
3341
- let i = performance.now() - t;
3342
- return Z.verifications_total.increment({
3513
+ let a = performance.now() - t;
3514
+ return X.verifications_total.increment({
3343
3515
  result: "fail",
3344
3516
  alg: "none",
3345
3517
  transport: "http"
3346
- }), Z.verification_duration_ms.observe(i), {
3518
+ }), X.verification_duration_ms.observe(a), {
3347
3519
  ok: !1,
3348
3520
  status: 401,
3349
3521
  reason: n.ok ? "capability-scope-mismatch" : n.reason
3350
3522
  };
3351
3523
  } catch {
3352
3524
  let e = performance.now() - t;
3353
- return Z.verifications_total.increment({
3525
+ return X.verifications_total.increment({
3354
3526
  result: "fail",
3355
3527
  alg: "none",
3356
3528
  transport: "http"
3357
- }), Z.verification_duration_ms.observe(e), {
3529
+ }), X.verification_duration_ms.observe(e), {
3358
3530
  ok: !1,
3359
3531
  status: 401,
3360
3532
  reason: "invalid-capability-chain"
3361
3533
  };
3362
3534
  }
3363
3535
  }
3364
- if (!n && (this.config.defaultPolicy ?? "allow") === "deny") {
3536
+ if (!r && (this.config.defaultPolicy ?? "allow") === "deny") {
3365
3537
  let n = performance.now() - t;
3366
- return Z.verifications_total.increment({
3538
+ return X.verifications_total.increment({
3367
3539
  result: "fail",
3368
3540
  alg: "none",
3369
3541
  transport: "http"
3370
- }), Z.verification_duration_ms.observe(n), Z.sender_denials_total.increment({
3542
+ }), X.verification_duration_ms.observe(n), X.sender_denials_total.increment({
3371
3543
  sender: "",
3372
3544
  path: e.path
3373
3545
  }), {
@@ -3376,82 +3548,54 @@ var Ur = class {
3376
3548
  reason: "no-matching-policy"
3377
3549
  };
3378
3550
  }
3379
- let r = await Dn(e.headers, {
3551
+ let i = await jn(e.headers, {
3380
3552
  keyRegistry: this.config.keyRegistry,
3381
3553
  headerName: this.config.headerName
3382
3554
  });
3383
- if (!r.ok) {
3555
+ if (!i.ok) {
3384
3556
  let e = performance.now() - t;
3385
- return Z.verifications_total.increment({
3557
+ return X.verifications_total.increment({
3386
3558
  result: "fail",
3387
3559
  alg: "none",
3388
3560
  transport: "http"
3389
- }), Z.verification_duration_ms.observe(e), {
3561
+ }), X.verification_duration_ms.observe(e), {
3390
3562
  ok: !1,
3391
3563
  status: 401,
3392
- reason: r.reason
3564
+ reason: i.reason
3393
3565
  };
3394
3566
  }
3395
- let i = r.envelope, a = i.header.sender, o = i.header.messageId, s = i.signature?.alg ?? "none";
3396
- if (this.config.replayStore && await this.config.replayStore.check(i.header.nonce, i.header.ttlMs)) return {
3567
+ let a = i.envelope, o = a.header.sender, s = a.header.messageId, c = a.signature?.alg ?? "none";
3568
+ if (this.config.replayStore && await this.config.replayStore.check(a.header.nonce, a.header.ttlMs)) return {
3397
3569
  ok: !1,
3398
3570
  status: 401,
3399
3571
  reason: "replay-detected"
3400
3572
  };
3401
- if (n && n.require !== "any") {
3402
- let e = i.signature?.alg, r = n.require === "ed25519" && e !== "ED25519", a = n.require === "hmac" && e !== "HS256";
3403
- if (r || a) {
3573
+ if (r && r.require !== "any") {
3574
+ let e = a.signature?.alg, n = r.require === "ed25519" && e !== "ED25519", i = r.require === "hmac" && e !== "HS256";
3575
+ if (n || i) {
3404
3576
  let e = performance.now() - t;
3405
- return Z.verifications_total.increment({
3577
+ return X.verifications_total.increment({
3406
3578
  result: "fail",
3407
- alg: s,
3579
+ alg: c,
3408
3580
  transport: "http"
3409
- }), Z.verification_duration_ms.observe(e), {
3581
+ }), X.verification_duration_ms.observe(e), {
3410
3582
  ok: !1,
3411
3583
  status: 401,
3412
3584
  reason: "invalid-signature"
3413
3585
  };
3414
3586
  }
3415
3587
  }
3416
- if (n && !Cr(n, a)) {
3417
- let n = performance.now() - t;
3418
- return Z.verifications_total.increment({
3419
- result: "fail",
3420
- alg: s,
3421
- transport: "http"
3422
- }), Z.verification_duration_ms.observe(n), Z.sender_denials_total.increment({
3423
- sender: a,
3424
- path: e.path
3425
- }), {
3426
- ok: !1,
3427
- status: 403,
3428
- reason: "sender-denied"
3429
- };
3430
- }
3431
- if (n?.rateLimit && !(this.config.rateLimitStore ? await this.config.rateLimitStore.consume(a, n.rateLimit) : this.rateLimiter.consume(a, n.rateLimit)).allowed) {
3432
- let n = performance.now() - t;
3433
- return Z.verifications_total.increment({
3434
- result: "fail",
3435
- alg: s,
3436
- transport: "http"
3437
- }), Z.verification_duration_ms.observe(n), Z.rate_limit_hits_total.increment({
3438
- sender: a,
3439
- path: e.path
3440
- }), {
3441
- ok: !1,
3442
- status: 429,
3443
- reason: "rate-limited"
3444
- };
3445
- }
3446
- let c = performance.now() - t;
3447
- return Z.verifications_total.increment({
3588
+ let l = await this.checkSenderAndRateLimit(r, o, c, e, t);
3589
+ if (l) return l;
3590
+ let u = performance.now() - t;
3591
+ return X.verifications_total.increment({
3448
3592
  result: "ok",
3449
- alg: s,
3593
+ alg: c,
3450
3594
  transport: "http"
3451
- }), Z.verification_duration_ms.observe(c), {
3595
+ }), X.verification_duration_ms.observe(u), {
3452
3596
  ok: !0,
3453
- sender: a,
3454
- envelopeId: o
3597
+ sender: o,
3598
+ envelopeId: s
3455
3599
  };
3456
3600
  }
3457
3601
  async handle(e) {
@@ -3461,43 +3605,43 @@ var Ur = class {
3461
3605
  headers: { "content-type": "application/json" },
3462
3606
  body: JSON.stringify({ error: t.reason })
3463
3607
  };
3464
- let n = this.config.upstream.replace(/\/$/, "") + e.path, r = {};
3465
- for (let [t, n] of Object.entries(e.headers)) r[t] = Array.isArray(n) ? n[0] : n;
3466
- t.sender && (r["x-7h3-sender"] = t.sender), r["x-7h3-verified"] = "true";
3467
- let i = await fetch(n, {
3608
+ let n = Qr(e.path), r = this.config.upstream.replace(/\/$/, "") + n, i = {};
3609
+ for (let [t, n] of Object.entries(e.headers)) i[t] = Array.isArray(n) ? n[0] : n;
3610
+ t.sender && (i["x-7h3-sender"] = t.sender, i["x-7h3-verified"] = "true");
3611
+ let a = await fetch(r, {
3468
3612
  method: e.method,
3469
- headers: r,
3613
+ headers: i,
3470
3614
  body: e.body
3471
- }), a = await i.text(), o = { "content-type": i.headers.get("content-type") ?? "application/json" };
3615
+ }), o = await a.text(), s = { "content-type": a.headers.get("content-type") ?? "application/json" };
3472
3616
  if (this.config.privateKey !== void 0 && (this.config.signResponses ?? !0) && this.config.sender !== void 0) {
3473
- let e = await Tr(a, {
3617
+ let e = await jr(o, {
3474
3618
  privateKey: this.config.privateKey,
3475
3619
  sender: this.config.sender,
3476
3620
  recipient: t.sender || void 0
3477
3621
  });
3478
- Object.assign(o, e.headers);
3622
+ Object.assign(s, e.headers);
3479
3623
  }
3480
3624
  return {
3481
- status: i.status,
3482
- headers: o,
3483
- body: a
3625
+ status: a.status,
3626
+ headers: s,
3627
+ body: o
3484
3628
  };
3485
3629
  }
3486
3630
  getRateLimiter() {
3487
3631
  return this.rateLimiter;
3488
3632
  }
3489
3633
  };
3490
- function Wr(e) {
3491
- return new Ur(e);
3634
+ function ei(e) {
3635
+ return new $r(e);
3492
3636
  }
3493
- function Gr(e) {
3637
+ function ti(e) {
3494
3638
  if (e.defaultPolicy !== "deny") throw Error("createProductionGateway(): defaultPolicy must be explicitly 'deny'. Unmatched routes must never be forwarded unverified in production.");
3495
3639
  if (!e.replayStore) throw Error("createProductionGateway(): replayStore is required. Use a shared store (Redis/KV/Durable Object) so nonce replay protection survives multiple instances and restarts.");
3496
- return new Ur(e);
3640
+ return new $r(e);
3497
3641
  }
3498
3642
  //#endregion
3499
3643
  //#region src/auditLog.ts
3500
- function Kr(e) {
3644
+ function ni(e) {
3501
3645
  let t = [
3502
3646
  `"id":${JSON.stringify(e.id)}`,
3503
3647
  `"timestampMs":${e.timestampMs}`,
@@ -3505,7 +3649,7 @@ function Kr(e) {
3505
3649
  ];
3506
3650
  return e.sender !== void 0 && t.push(`"sender":${JSON.stringify(e.sender)}`), e.path !== void 0 && t.push(`"path":${JSON.stringify(e.path)}`), e.method !== void 0 && t.push(`"method":${JSON.stringify(e.method)}`), e.envelopeId !== void 0 && t.push(`"envelopeId":${JSON.stringify(e.envelopeId)}`), e.failReason !== void 0 && t.push(`"failReason":${JSON.stringify(e.failReason)}`), e.upstream !== void 0 && t.push(`"upstream":${JSON.stringify(e.upstream)}`), e.responseStatus !== void 0 && t.push(`"responseStatus":${e.responseStatus}`), `{${t.join(",")}}`;
3507
3651
  }
3508
- var qr = class {
3652
+ var ri = class {
3509
3653
  entries = [];
3510
3654
  privateKey;
3511
3655
  maxEntries;
@@ -3517,7 +3661,7 @@ var qr = class {
3517
3661
  id: `audit-${Date.now()}-${y(5)}`,
3518
3662
  timestampMs: Date.now(),
3519
3663
  ...e
3520
- }, n = await b(Kr(t), this.privateKey), r = {
3664
+ }, n = await b(ni(t), this.privateKey), r = {
3521
3665
  ...t,
3522
3666
  entrySignature: n
3523
3667
  };
@@ -3528,7 +3672,7 @@ var qr = class {
3528
3672
  return e?.type !== void 0 && (t = t.filter((t) => t.type === e.type)), e?.sender !== void 0 && (t = t.filter((t) => t.sender === e.sender)), e?.since !== void 0 && (t = t.filter((t) => t.timestampMs >= e.since)), e?.limit !== void 0 && (t = t.slice(-e.limit)), t;
3529
3673
  }
3530
3674
  async verify(e, t) {
3531
- return x(Kr({
3675
+ return x(ni({
3532
3676
  id: e.id,
3533
3677
  timestampMs: e.timestampMs,
3534
3678
  type: e.type,
@@ -3544,7 +3688,7 @@ var qr = class {
3544
3688
  size() {
3545
3689
  return this.entries.length;
3546
3690
  }
3547
- }, Jr = class {
3691
+ }, ii = class {
3548
3692
  async log(e) {}
3549
3693
  async query(e) {
3550
3694
  return [];
@@ -3556,25 +3700,25 @@ var qr = class {
3556
3700
  return 0;
3557
3701
  }
3558
3702
  };
3559
- function Yr(e, t) {
3560
- return new qr(e, t?.maxEntries);
3703
+ function ai(e, t) {
3704
+ return new ri(e, t?.maxEntries);
3561
3705
  }
3562
3706
  //#endregion
3563
3707
  //#region src/otel.ts
3564
- var Xr = null;
3565
- function Zr(e) {
3566
- Xr = e;
3708
+ var oi = null;
3709
+ function si(e) {
3710
+ oi = e;
3567
3711
  }
3568
- function Qr() {
3569
- if (Xr === null) return null;
3712
+ function ci() {
3713
+ if (oi === null) return null;
3570
3714
  try {
3571
- return Xr.getTracer("7h3/protocol");
3715
+ return oi.getTracer("7h3/protocol");
3572
3716
  } catch {
3573
3717
  return null;
3574
3718
  }
3575
3719
  }
3576
- async function $r(e, t) {
3577
- let n = Qr();
3720
+ async function li(e, t) {
3721
+ let n = ci();
3578
3722
  if (n === null) return e(null);
3579
3723
  let r = n.startSpan("7h3.verify", t);
3580
3724
  try {
@@ -3585,8 +3729,8 @@ async function $r(e, t) {
3585
3729
  r.end();
3586
3730
  }
3587
3731
  }
3588
- async function ei(e) {
3589
- let t = Qr();
3732
+ async function ui(e) {
3733
+ let t = ci();
3590
3734
  if (t === null) return e(null);
3591
3735
  let n = t.startSpan("7h3.audit.write");
3592
3736
  try {
@@ -3599,64 +3743,64 @@ async function ei(e) {
3599
3743
  }
3600
3744
  //#endregion
3601
3745
  //#region src/encryption.ts
3602
- function ti(e) {
3746
+ function Q(e) {
3603
3747
  return Buffer.from(e).toString("base64url");
3604
3748
  }
3605
3749
  function $(e) {
3606
3750
  return Buffer.from(e, "base64url");
3607
3751
  }
3608
- var ni = Buffer.from("302e020100300506032b656e04220420", "hex"), ri = Buffer.from("302a300506032b656e032100", "hex");
3609
- function ii(e) {
3752
+ var di = Buffer.from("302e020100300506032b656e04220420", "hex"), fi = Buffer.from("302a300506032b656e032100", "hex");
3753
+ function pi(e) {
3610
3754
  let t = $(e);
3611
3755
  return r({
3612
- key: Buffer.concat([ni, t]),
3756
+ key: Buffer.concat([di, t]),
3613
3757
  format: "der",
3614
3758
  type: "pkcs8"
3615
3759
  });
3616
3760
  }
3617
- function ai(e) {
3761
+ function mi(e) {
3618
3762
  let t = $(e);
3619
3763
  return i({
3620
- key: Buffer.concat([ri, t]),
3764
+ key: Buffer.concat([fi, t]),
3621
3765
  format: "der",
3622
3766
  type: "spki"
3623
3767
  });
3624
3768
  }
3625
- function oi() {
3769
+ function hi() {
3626
3770
  let { privateKey: e, publicKey: t } = o("x25519"), n = e.export({ format: "jwk" });
3627
3771
  return {
3628
3772
  publicKey: t.export({ format: "jwk" }).x,
3629
3773
  privateKey: n.d
3630
3774
  };
3631
3775
  }
3632
- function si(e, t, n) {
3776
+ function gi(e, t, n) {
3633
3777
  let r = s("sha256", a({
3634
- privateKey: ii(e),
3635
- publicKey: ai(t)
3778
+ privateKey: pi(e),
3779
+ publicKey: mi(t)
3636
3780
  }), $(n), Buffer.from("7h3-enc/1", "utf8"), 32);
3637
3781
  return Buffer.from(r);
3638
3782
  }
3639
- function ci(e, n) {
3640
- let r = oi(), i = c(12), a = ti(i), o = si(r.privateKey, n, a), s = Buffer.from(JSON.stringify(e), "utf8"), l = t("chacha20-poly1305", o, i, { authTagLength: 16 }), u = Buffer.concat([l.update(s), l.final()]), d = l.getAuthTag(), f = {
3783
+ function _i(e, n) {
3784
+ let r = hi(), i = c(12), a = Q(i), o = gi(r.privateKey, n, a), s = Buffer.from(JSON.stringify(e), "utf8"), l = t("chacha20-poly1305", o, i, { authTagLength: 16 }), u = Buffer.concat([l.update(s), l.final()]), d = l.getAuthTag(), f = {
3641
3785
  ephemeralPublic: r.publicKey,
3642
3786
  nonce: a,
3643
- ciphertext: ti(u),
3644
- tag: ti(d)
3787
+ ciphertext: Q(u),
3788
+ tag: Q(d)
3645
3789
  };
3646
3790
  return {
3647
- encryptedContent: ti(Buffer.from(JSON.stringify(f), "utf8")),
3791
+ encryptedContent: Q(Buffer.from(JSON.stringify(f), "utf8")),
3648
3792
  ephemeralPublic: r.publicKey
3649
3793
  };
3650
3794
  }
3651
- function li(e, t) {
3652
- let r = $(e).toString("utf8"), { ephemeralPublic: i, nonce: a, ciphertext: o, tag: s } = JSON.parse(r), c = si(t, i, a), l = $(a), u = $(o), d = $(s), f = n("chacha20-poly1305", c, l, { authTagLength: 16 });
3795
+ function vi(e, t) {
3796
+ let r = $(e).toString("utf8"), { ephemeralPublic: i, nonce: a, ciphertext: o, tag: s } = JSON.parse(r), c = gi(t, i, a), l = $(a), u = $(o), d = $(s), f = n("chacha20-poly1305", c, l, { authTagLength: 16 });
3653
3797
  f.setAuthTag(d);
3654
3798
  let p = Buffer.concat([f.update(u), f.final()]);
3655
3799
  return JSON.parse(p.toString("utf8"));
3656
3800
  }
3657
- async function ui(e, t) {
3658
- let { encryptedContent: n } = ci(e.body, t.recipientX25519PublicKey);
3659
- return C({
3801
+ async function yi(e, t) {
3802
+ let { encryptedContent: n } = _i(e.body, t.recipientX25519PublicKey);
3803
+ return w({
3660
3804
  header: e.header,
3661
3805
  body: {
3662
3806
  intent: "ENCRYPTED",
@@ -3666,12 +3810,12 @@ async function ui(e, t) {
3666
3810
  }
3667
3811
  }, t.senderEd25519PrivateKey);
3668
3812
  }
3669
- async function di(e, t) {
3670
- if (!await w(e, t.senderEd25519PublicKey)) throw Error("7h3/encryption: Ed25519 signature verification failed");
3813
+ async function bi(e, t) {
3814
+ if (!await T(e, t.senderEd25519PublicKey)) throw Error("7h3/encryption: Ed25519 signature verification failed");
3671
3815
  return {
3672
3816
  envelope: e,
3673
- body: li(e.body.content, t.recipientX25519PrivateKey)
3817
+ body: vi(e.body.content, t.recipientX25519PrivateKey)
3674
3818
  };
3675
3819
  }
3676
3820
  //#endregion
3677
- export { ot as AgentSession, st as AipAgentAdapter, Mr as CAP_HEADER, Cn as CBOR_CONTENT_TYPE, bn as CborDecoder, yn as CborEncoder, Rt as ClusterRedisReplayStore, En as DEFAULT_HEADER, xe as DEFAULT_MAX_BINARY_ENVELOPE_BYTES, Re as DistributedReplayCache, ur as GRPC_METADATA_KEY, qr as InMemoryAuditLog, It as InMemoryRedisLikeClient, k as InMemoryReplayCache, Ut as InMemoryRevocationStore, ze as InMemoryVerificationMaterialCache, vr as KeyRotationManager, _e as MAX_TTL_MS, Jr as NoopAuditLog, Ur as Protocol7h3Gateway, kr as Protocol7h3Metrics, wr as RESPONSE_HEADER, Lt as RedisReplayStore, yr as RevocationRegistry, it as RollingKeyring, Mt as RuntimePolicyManager, Un as STREAM_HEADER, Xe as SessionTransport, er as SignedStreamReader, q as SignedStreamWriter, X as SimpleCounter, Or as SimpleHistogram, br as SlidingWindowRateLimiter, Nn as WEBHOOK_DEFAULT_TTL_MS, L as WEBHOOK_SIG_HEADER, R as WEBHOOK_TS_HEADER, j as bootstrapRuntimePolicyEnforcer, Q as canonicalizeCapabilityToken, _ as canonicalizeEnvelope, zn as consumeWebhook, ct as createAipAgentAdapter, et as createAipCapabilities, At as createAipMcpGatewayRuntime, jt as createAipMcpGatewayRuntimeWithPolicy, Yr as createAuditLog, rn as createCachingKeyRegistry, Vt as createClusterReplayStore, nn as createCompositeKeyRegistry, E as createEnvelope, Wr as createGateway, _r as createHttpKeyRegistry, en as createHttpMcpClient, $t as createHttpMcpHandler, An as createHttpMiddleware, at as createKeyringSignatureResolver, Jt as createMcpClientCodec, jr as createMetricsMiddleware, wt as createPolicyEnforcer, Gr as createProductionGateway, mt as createRawTaskFromJsonRpc, lt as createRawTaskFromLangChain, dt as createRawTaskFromLlamaIndex, zt as createRedisReplayStore, Wt as createRedisRevocationStore, Mn as createSignedFetchRequest, Ze as createSignedMessage, tr as createSignedStream, cr as createSignedWebSocketStream, tn as createStaticKeyRegistry, Qt as createStdioMcpClient, nr as createStreamVerifier, Sn as decodeCbor, Ge as decodeEnvelope, Je as decodeEnvelopeBatch, Ie as decodeEnvelopeBinary, Tn as decodeEnvelopeCbor, or as decodeStreamChunk, li as decryptBody, Lr as delegateCapabilityToken, si as deriveEncryptionKey, tt as encodeAipCapabilities, xn as encodeCbor, Ke as encodeEnvelope, qe as encodeEnvelopeBatch, Fe as encodeEnvelopeBinary, wn as encodeEnvelopeCbor, ar as encodeStreamChunk, ci as encryptBody, gr as fetchWellKnownKeys, pe as generateEd25519KeypairBase64Url, oi as generateX25519KeyPair, Qr as getOtelTracer, Pt as getRuntimeTuningPreset, xr as globalRateLimiter, Cr as isAllowedSender, Tt as isRuntimeMode, Pr as issueCapabilityToken, xt as loadRuntimePolicy, J as matchGlob, Sr as matchPolicy, Z as metrics, rt as negotiateAipCapabilities, di as openEnvelope, nt as parseAipCapabilities, Hr as parseCapabilityChain, yt as parseRuntimePolicyJson, hr as parseWellKnownKeys, y as randomHex, A as receiveEnvelope, Ye as receiveEnvelopeBatch, lr as receiveSignedWebSocketStream, Ft as recommendPolicyAdjustments, Ar as renderPrometheusText, ui as sealEnvelope, Vr as serializeCapabilityChain, Zt as serveMcpOverStdio, mr as serveWellKnownKeys, Zr as setOtelProvider, b as signCanonicalPayloadEd25519, de as signCanonicalPayloadHmac, C as signEnvelopeEd25519, me as signEnvelopeHmac, jn as signFetchRequest, dr as signGrpcCall, On as signHttpRequest, kn as signHttpRequestHmac, Bn as signQueueMessage, Tr as signResponse, rr as signStream, Fn as signWebhook, In as signWebhookHmac, ht as toJsonRpcResponse, ut as toLangChainMessage, ft as toLlamaIndexMessage, Br as tokenMatchesScope, T as validateEnvelope, vt as validateRuntimePolicy, x as verifyCanonicalPayloadEd25519, fe as verifyCanonicalPayloadHmac, ge as verifyCanonicalPayloadSignature, zr as verifyCapabilityChain, Rr as verifyCapabilityToken, w as verifyEnvelopeEd25519, S as verifyEnvelopeHmac, he as verifyEnvelopeSignature, fr as verifyGrpcCall, Dn as verifyHttpEnvelope, Hn as verifyQueueBatch, Vn as verifyQueueMessage, Er as verifyResponse, ir as verifyStream, Ln as verifyWebhook, Rn as verifyWebhookHmac, ei as withAuditSpan, pr as withGrpcVerification, Gt as withRevocationCheck, $r as withVerificationSpan, Yt as wrapMcpClient, qt as wrapMcpServer, sr as wrapWebSocket };
3821
+ export { at as AgentSession, ot as AipAgentAdapter, zr as CAP_HEADER, Tn as CBOR_CONTENT_TYPE, Sn as CborDecoder, bn as CborEncoder, Rt as ClusterRedisReplayStore, An as DEFAULT_HEADER, xe as DEFAULT_MAX_BINARY_ENVELOPE_BYTES, Re as DistributedReplayCache, hr as GRPC_METADATA_KEY, ri as InMemoryAuditLog, It as InMemoryRedisLikeClient, A as InMemoryReplayCache, Ut as InMemoryRevocationStore, ze as InMemoryVerificationMaterialCache, Rn as InMemoryWebhookReplayCache, Cr as KeyRotationManager, xn as MAX_CBOR_DEPTH, _e as MAX_CLOCK_SKEW_MS, ge as MAX_TTL_MS, ii as NoopAuditLog, $r as Protocol7h3Gateway, Ir as Protocol7h3Metrics, Ar as RESPONSE_HEADER, Lt as RedisReplayStore, wr as RevocationRegistry, rt as RollingKeyring, Mt as RuntimePolicyManager, qn as STREAM_HEADER, Ye as SessionTransport, ar as SignedStreamReader, ir as SignedStreamWriter, Y as SimpleCounter, Fr as SimpleHistogram, Tr as SlidingWindowRateLimiter, Ln as WEBHOOK_DEFAULT_TTL_MS, R as WEBHOOK_SIG_HEADER, z as WEBHOOK_TS_HEADER, N as bootstrapRuntimePolicyEnforcer, Z as canonicalizeCapabilityToken, _ as canonicalizeEnvelope, Un as consumeWebhook, st as createAipAgentAdapter, $e as createAipCapabilities, At as createAipMcpGatewayRuntime, jt as createAipMcpGatewayRuntimeWithPolicy, ai as createAuditLog, an as createCachingKeyRegistry, Vt as createClusterReplayStore, rn as createCompositeKeyRegistry, D as createEnvelope, ei as createGateway, Sr as createHttpKeyRegistry, tn as createHttpMcpClient, en as createHttpMcpHandler, Pn as createHttpMiddleware, it as createKeyringSignatureResolver, Yt as createMcpClientCodec, Rr as createMetricsMiddleware, Ct as createPolicyEnforcer, ti as createProductionGateway, pt as createRawTaskFromJsonRpc, ct as createRawTaskFromLangChain, ut as createRawTaskFromLlamaIndex, zt as createRedisReplayStore, Wt as createRedisRevocationStore, In as createSignedFetchRequest, Xe as createSignedMessage, or as createSignedStream, pr as createSignedWebSocketStream, nn as createStaticKeyRegistry, $t as createStdioMcpClient, sr as createStreamVerifier, wn as decodeCbor, Ge as decodeEnvelope, qe as decodeEnvelopeBatch, Ie as decodeEnvelopeBinary, kn as decodeEnvelopeCbor, dr as decodeStreamChunk, vi as decryptBody, Kr as delegateCapabilityToken, gi as deriveEncryptionKey, et as encodeAipCapabilities, Cn as encodeCbor, j as encodeEnvelope, Ke as encodeEnvelopeBatch, Fe as encodeEnvelopeBinary, En as encodeEnvelopeCbor, ur as encodeStreamChunk, _i as encryptBody, xr as fetchWellKnownKeys, pe as generateEd25519KeypairBase64Url, hi as generateX25519KeyPair, ci as getOtelTracer, Pt as getRuntimeTuningPreset, Er as globalRateLimiter, kr as isAllowedSender, wt as isRuntimeMode, Vr as issueCapabilityToken, bt as loadRuntimePolicy, Dr as matchGlob, Or as matchPolicy, X as metrics, nt as negotiateAipCapabilities, Qr as normalizeGatewayPath, bi as openEnvelope, tt as parseAipCapabilities, Zr as parseCapabilityChain, vt as parseRuntimePolicyJson, br as parseWellKnownKeys, y as randomHex, M as receiveEnvelope, Je as receiveEnvelopeBatch, mr as receiveSignedWebSocketStream, Ft as recommendPolicyAdjustments, Lr as renderPrometheusText, yi as sealEnvelope, Xr as serializeCapabilityChain, Qt as serveMcpOverStdio, yr as serveWellKnownKeys, si as setOtelProvider, b as signCanonicalPayloadEd25519, de as signCanonicalPayloadHmac, w as signEnvelopeEd25519, S as signEnvelopeHmac, Fn as signFetchRequest, gr as signGrpcCall, Mn as signHttpRequest, Nn as signHttpRequestHmac, Wn as signQueueMessage, jr as signResponse, cr as signStream, zn as signWebhook, Bn as signWebhookHmac, mt as toJsonRpcResponse, lt as toLangChainMessage, dt as toLlamaIndexMessage, Yr as tokenMatchesScope, E as validateEnvelope, _t as validateRuntimePolicy, x as verifyCanonicalPayloadEd25519, fe as verifyCanonicalPayloadHmac, he as verifyCanonicalPayloadSignature, Jr as verifyCapabilityChain, qr as verifyCapabilityToken, T as verifyEnvelopeEd25519, C as verifyEnvelopeHmac, me as verifyEnvelopeSignature, _r as verifyGrpcCall, jn as verifyHttpEnvelope, Kn as verifyQueueBatch, Gn as verifyQueueMessage, Mr as verifyResponse, lr as verifyStream, Vn as verifyWebhook, Hn as verifyWebhookHmac, ui as withAuditSpan, vr as withGrpcVerification, Gt as withRevocationCheck, li as withVerificationSpan, Xt as wrapMcpClient, Jt as wrapMcpServer, fr as wrapWebSocket };