@7h3/protocol 0.5.3 → 0.5.6

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
@@ -1,14 +1,7 @@
1
- //#region \0rolldown/runtime.js
2
- var e = Object.create, t = Object.defineProperty, n = Object.getOwnPropertyDescriptor, r = Object.getOwnPropertyNames, i = Object.getPrototypeOf, a = Object.prototype.hasOwnProperty, o = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t.exports), s = (e, i, o, s) => {
3
- if (i && typeof i == "object" || typeof i == "function") for (var c = r(i), l = 0, u = c.length, d; l < u; l++) d = c[l], !a.call(e, d) && d !== o && t(e, d, {
4
- get: ((e) => i[e]).bind(null, d),
5
- enumerable: !(s = n(i, d)) || s.enumerable
6
- });
7
- return e;
8
- }, c = (n, r, a) => (a = n == null ? {} : e(i(n)), s(r || !n || !n.__esModule ? t(a, "default", {
9
- value: n,
10
- enumerable: !0
11
- }) : a, n)), l = new TextEncoder(), u = 256, d = /* @__PURE__ */ new Map(), f = 256, p = /* @__PURE__ */ new Map(), m = /* @__PURE__ */ new Map();
1
+ import e from "node:readline";
2
+ import { createCipheriv as t, createDecipheriv as n, createPrivateKey as r, createPublicKey as i, diffieHellman as a, generateKeyPairSync as o, hkdfSync as s, randomBytes as c } from "node:crypto";
3
+ //#region src/protocol.ts
4
+ var l = new TextEncoder(), u = 256, d = /* @__PURE__ */ new Map(), f = 256, p = /* @__PURE__ */ new Map(), m = /* @__PURE__ */ new Map();
12
5
  function ee() {
13
6
  return globalThis.Buffer ?? null;
14
7
  }
@@ -24,7 +17,7 @@ function re(e) {
24
17
  let t = `hs256:${e}`, n = d.get(t);
25
18
  if (n) return n;
26
19
  d.size >= u && d.clear();
27
- let r = _().importKey("raw", l.encode(e), {
20
+ let r = v().importKey("raw", l.encode(e), {
28
21
  name: "HMAC",
29
22
  hash: "SHA-256"
30
23
  }, !1, ["sign", "verify"]).catch((e) => {
@@ -36,7 +29,7 @@ function ie(e) {
36
29
  let t = `ed25519:pkcs8:${e}`, n = p.get(t);
37
30
  if (n) return n;
38
31
  p.size >= f && p.clear();
39
- let r = _().importKey("pkcs8", se(h(e)), { name: "Ed25519" }, !1, ["sign"]).catch((e) => {
32
+ let r = v().importKey("pkcs8", oe(g(e)), { name: "Ed25519" }, !1, ["sign"]).catch((e) => {
40
33
  throw p.delete(t), e;
41
34
  });
42
35
  return p.set(t, r), r;
@@ -45,33 +38,33 @@ function ae(e) {
45
38
  let t = `ed25519:spki:${e}`, n = m.get(t);
46
39
  if (n) return n;
47
40
  m.size >= f && m.clear();
48
- let r = _().importKey("spki", se(h(e)), { name: "Ed25519" }, !1, ["verify"]).catch((e) => {
41
+ let r = v().importKey("spki", oe(g(e)), { name: "Ed25519" }, !1, ["verify"]).catch((e) => {
49
42
  throw m.delete(t), e;
50
43
  });
51
44
  return m.set(t, r), r;
52
45
  }
53
- function oe(e) {
46
+ function h(e) {
54
47
  let t = ee();
55
48
  return (t ? t.from(e).toString("base64") : btoa(String.fromCharCode(...e))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
56
49
  }
57
- function h(e) {
50
+ function g(e) {
58
51
  let t = e.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(e.length / 4) * 4, "="), n = ee();
59
52
  if (n) return new Uint8Array(n.from(t, "base64"));
60
53
  let r = atob(t), i = new Uint8Array(r.length);
61
54
  for (let e = 0; e < r.length; e += 1) i[e] = r.charCodeAt(e);
62
55
  return i;
63
56
  }
64
- function se(e) {
57
+ function oe(e) {
65
58
  return e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength);
66
59
  }
67
- function g(e) {
60
+ function _(e) {
68
61
  return `{"body":${ne(e.body)},"header":${te(e.header)}}`;
69
62
  }
70
- function _() {
63
+ function v() {
71
64
  if (typeof crypto > "u" || !crypto.subtle) throw Error("Web Crypto API is not available in this runtime");
72
65
  return crypto.subtle;
73
66
  }
74
- function v(e = 12) {
67
+ function y(e = 12) {
75
68
  if (typeof crypto > "u" || !crypto.getRandomValues) throw Error("Web Crypto API is not available in this runtime");
76
69
  let t = new Uint8Array(e);
77
70
  crypto.getRandomValues(t);
@@ -79,43 +72,43 @@ function v(e = 12) {
79
72
  for (let e of t) n += e.toString(16).padStart(2, "0");
80
73
  return n;
81
74
  }
82
- async function ce(e, t) {
83
- let n = _(), r = await re(t), i = await n.sign("HMAC", r, l.encode(e));
84
- return oe(new Uint8Array(i));
75
+ async function se(e, t) {
76
+ let n = v(), r = await re(t), i = await n.sign("HMAC", r, l.encode(e));
77
+ return h(new Uint8Array(i));
85
78
  }
86
- async function le(e, t, n) {
87
- let r = _(), i = await re(n), a = h(t);
79
+ async function ce(e, t, n) {
80
+ let r = v(), i = await re(n), a = g(t);
88
81
  return r.verify("HMAC", i, a.buffer, l.encode(e));
89
82
  }
90
- async function ue(e, t) {
91
- let n = _(), r = await ie(t), i = await n.sign("Ed25519", r, l.encode(e));
92
- return oe(new Uint8Array(i));
83
+ async function le(e, t) {
84
+ let n = v(), r = await ie(t), i = await n.sign("Ed25519", r, l.encode(e));
85
+ return h(new Uint8Array(i));
93
86
  }
94
- async function de(e, t, n) {
95
- let r = _(), i = await ae(n), a = h(t);
87
+ async function ue(e, t, n) {
88
+ let r = v(), i = await ae(n), a = g(t);
96
89
  return r.verify("Ed25519", i, a.buffer, l.encode(e));
97
90
  }
98
- async function fe(e, t) {
99
- return ce(e, t);
91
+ async function de(e, t) {
92
+ return se(e, t);
100
93
  }
101
- async function pe(e, t, n) {
102
- return le(e, t, n);
94
+ async function fe(e, t, n) {
95
+ return ce(e, t, n);
103
96
  }
104
- async function me() {
105
- let e = _(), t = await e.generateKey({ name: "Ed25519" }, !0, ["sign", "verify"]), n = await e.exportKey("pkcs8", t.privateKey), r = await e.exportKey("spki", t.publicKey);
97
+ async function pe() {
98
+ let e = v(), t = await e.generateKey({ name: "Ed25519" }, !0, ["sign", "verify"]), n = await e.exportKey("pkcs8", t.privateKey), r = await e.exportKey("spki", t.publicKey);
106
99
  return {
107
- privateKey: oe(new Uint8Array(n)),
108
- publicKey: oe(new Uint8Array(r))
100
+ privateKey: h(new Uint8Array(n)),
101
+ publicKey: h(new Uint8Array(r))
109
102
  };
110
103
  }
111
- async function y(e, t) {
112
- return ue(e, t);
104
+ async function b(e, t) {
105
+ return le(e, t);
113
106
  }
114
- async function b(e, t, n) {
115
- return de(e, t, n);
107
+ async function x(e, t, n) {
108
+ return ue(e, t, n);
116
109
  }
117
- async function x(e, t, n = "local-dev-key") {
118
- let r = await ce(g(e), t);
110
+ async function S(e, t, n = "local-dev-key") {
111
+ let r = await se(_(e), t);
119
112
  return {
120
113
  ...e,
121
114
  signature: {
@@ -125,14 +118,14 @@ async function x(e, t, n = "local-dev-key") {
125
118
  }
126
119
  };
127
120
  }
128
- async function he(e, t) {
129
- return !e.signature || e.signature.alg !== "HS256" ? !1 : le(g({
121
+ async function C(e, t) {
122
+ return !e.signature || e.signature.alg !== "HS256" ? !1 : ce(_({
130
123
  header: e.header,
131
124
  body: e.body
132
125
  }), e.signature.value, t);
133
126
  }
134
- async function S(e, t, n = "local-ed25519-key") {
135
- let r = await ue(g(e), t);
127
+ async function w(e, t, n = "local-ed25519-key") {
128
+ let r = await le(_(e), t);
136
129
  return {
137
130
  ...e,
138
131
  signature: {
@@ -142,20 +135,21 @@ async function S(e, t, n = "local-ed25519-key") {
142
135
  }
143
136
  };
144
137
  }
145
- async function C(e, t) {
146
- return !e.signature || e.signature.alg !== "ED25519" ? !1 : de(g({
138
+ async function T(e, t) {
139
+ return !e.signature || e.signature.alg !== "ED25519" ? !1 : ue(_({
147
140
  header: e.header,
148
141
  body: e.body
149
142
  }), e.signature.value, t);
150
143
  }
151
- async function ge(e, t) {
152
- return !e.signature || e.signature.alg !== t.alg ? !1 : t.alg === "HS256" ? he(e, t.secret) : C(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);
153
146
  }
154
- async function _e(e, t, n) {
155
- return !t || t.alg !== n.alg ? !1 : n.alg === "HS256" ? pe(e, t.value, n.secret) : b(e, t.value, n.publicKey);
147
+ async function he(e, t, n) {
148
+ return !t || t.alg !== n.alg ? !1 : n.alg === "HS256" ? fe(e, t.value, n.secret) : x(e, t.value, n.publicKey);
156
149
  }
157
- function w(e, t = Date.now()) {
158
- 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;
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 : "";
159
153
  return a !== "7h3/0.1" && n.push({
160
154
  level: "error",
161
155
  message: `Unsupported protocol version '${a}'`
@@ -168,10 +162,19 @@ function w(e, t = Date.now()) {
168
162
  }), c.trim() || n.push({
169
163
  level: "error",
170
164
  message: "Missing nonce — replay protection requires a unique nonce per message"
171
- }), 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({
172
169
  level: "error",
173
170
  message: "ttlMs must be greater than zero"
174
- }), l + u < t && n.push({
171
+ }), u > 864e5 && n.push({
172
+ level: "error",
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) && Number.isFinite(u) && l + u < t && n.push({
175
178
  level: "error",
176
179
  message: "Message TTL expired"
177
180
  }), d.trim() || n.push({
@@ -179,17 +182,17 @@ function w(e, t = Date.now()) {
179
182
  message: "Empty content payload"
180
183
  }), n;
181
184
  }
182
- function T(e) {
185
+ function D(e) {
183
186
  let t = e.nowMs ?? Date.now();
184
187
  return {
185
188
  header: {
186
189
  version: "7h3/0.1",
187
- messageId: e.messageId ?? `msg-${t}-${v(6)}`,
190
+ messageId: e.messageId ?? `msg-${t}-${y(6)}`,
188
191
  timestampMs: t,
189
192
  ttlMs: e.ttlMs ?? 6e4,
190
193
  sender: e.sender,
191
194
  recipient: e.recipient,
192
- nonce: e.nonce ?? v(12)
195
+ nonce: e.nonce ?? y(12)
193
196
  },
194
197
  body: {
195
198
  intent: e.intent,
@@ -201,12 +204,12 @@ function T(e) {
201
204
  }
202
205
  //#endregion
203
206
  //#region src/protocolBinary.ts
204
- var ve = [
207
+ var _e = [
205
208
  65,
206
209
  73,
207
210
  80,
208
211
  66
209
- ], ye = Uint8Array.from(ve), be = 1, xe = 1024 * 1024, Se = 1, Ce = 2, we = 4, Te = 8, Ee = new TextEncoder(), De = new TextDecoder(), Oe = new Set([
212
+ ], ve = Uint8Array.from(_e), ye = 1, be = 1024 * 1024, xe = 1, Se = 2, Ce = 4, we = 8, Te = new TextEncoder(), Ee = new TextDecoder(), De = /* @__PURE__ */ new Set([
210
213
  "PING",
211
214
  "PONG",
212
215
  "CAPS",
@@ -214,25 +217,25 @@ var ve = [
214
217
  "RESULT",
215
218
  "ERROR"
216
219
  ]);
220
+ function Oe(e) {
221
+ return Te.encode(e);
222
+ }
217
223
  function ke(e) {
218
- return Ee.encode(e);
224
+ return Ee.decode(e);
219
225
  }
220
226
  function Ae(e) {
221
- return De.decode(e);
222
- }
223
- function je(e) {
224
227
  return e === "ED25519" ? 2 : 1;
225
228
  }
226
- function Me(e) {
229
+ function je(e) {
227
230
  return e === 1 ? "HS256" : e === 2 ? "ED25519" : null;
228
231
  }
229
- function E(e) {
230
- return { bytes: ke(e) };
232
+ function O(e) {
233
+ return { bytes: Oe(e) };
231
234
  }
232
- function D(e) {
235
+ function k(e) {
233
236
  return e ? 4 + e.bytes.byteLength : 0;
234
237
  }
235
- var Ne = class {
238
+ var Me = class {
236
239
  bytes;
237
240
  view;
238
241
  offset = 0;
@@ -257,7 +260,7 @@ var Ne = class {
257
260
  finish() {
258
261
  return this.bytes;
259
262
  }
260
- }, Pe = class {
263
+ }, Ne = class {
261
264
  bytes;
262
265
  offset = 0;
263
266
  constructor(e) {
@@ -288,14 +291,14 @@ var Ne = class {
288
291
  }
289
292
  readString() {
290
293
  let e = this.readU32();
291
- return Ae(this.readBytes(e));
294
+ return ke(this.readBytes(e));
292
295
  }
293
296
  };
294
- function Fe(e) {
295
- let t = (e.header.recipient ? Se : 0) | (e.body.capability ? Ce : 0) | (e.body.correlationId ? we : 0) | (e.signature ? Te : 0), n = E(e.header.version), r = E(e.header.messageId), i = E(e.header.sender), a = E(e.header.nonce), o = E(e.body.intent), s = E(e.body.content), c = e.header.recipient ? E(e.header.recipient) : null, l = e.body.capability ? E(e.body.capability) : null, u = e.body.correlationId ? E(e.body.correlationId) : null, d = e.signature ? E(e.signature.keyId) : null, f = e.signature ? E(e.signature.value) : null, p = new Ne(ye.byteLength + 1 + 1 + 8 + 4 + D(n) + D(r) + D(i) + D(a) + D(o) + D(s) + D(c) + D(l) + D(u) + +!!e.signature + D(d) + D(f));
296
- 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();
297
+ function Pe(e) {
298
+ let t = (e.header.recipient ? xe : 0) | (e.body.capability ? Se : 0) | (e.body.correlationId ? Ce : 0) | (e.signature ? we : 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 Me(ve.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));
299
+ return p.writeBytes(ve), p.writeU8(ye), 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(Ae(e.signature.alg)), p.writeString(d), p.writeString(f)), p.finish();
297
300
  }
298
- function Ie(e, t = {}) {
301
+ function Fe(e, t = {}) {
299
302
  try {
300
303
  let n = t.maxFrameBytes ?? 1048576;
301
304
  if (e.byteLength > n) return {
@@ -306,13 +309,13 @@ function Ie(e, t = {}) {
306
309
  }],
307
310
  envelope: null
308
311
  };
309
- let r = new Pe(e);
312
+ let r = new Ne(e);
310
313
  if ([
311
314
  r.readU8(),
312
315
  r.readU8(),
313
316
  r.readU8(),
314
317
  r.readU8()
315
- ].some((e, t) => e !== ve[t])) return {
318
+ ].some((e, t) => e !== _e[t])) return {
316
319
  ok: !1,
317
320
  diagnostics: [{
318
321
  level: "error",
@@ -321,7 +324,7 @@ function Ie(e, t = {}) {
321
324
  envelope: null
322
325
  };
323
326
  let i = r.readU8();
324
- if (i !== be) return {
327
+ if (i !== ye) return {
325
328
  ok: !1,
326
329
  diagnostics: [{
327
330
  level: "error",
@@ -351,7 +354,7 @@ function Ie(e, t = {}) {
351
354
  }],
352
355
  envelope: null
353
356
  };
354
- if (!Oe.has(c.body.intent)) return {
357
+ if (!De.has(c.body.intent)) return {
355
358
  ok: !1,
356
359
  diagnostics: [{
357
360
  level: "error",
@@ -359,8 +362,8 @@ function Ie(e, t = {}) {
359
362
  }],
360
363
  envelope: null
361
364
  };
362
- if (a & Se && (c.header.recipient = r.readString()), a & Ce && (c.body.capability = r.readString()), a & we && (c.body.correlationId = r.readString()), a & Te) {
363
- let e = r.readU8(), t = Me(e);
365
+ if (a & xe && (c.header.recipient = r.readString()), a & Se && (c.body.capability = r.readString()), a & Ce && (c.body.correlationId = r.readString()), a & we) {
366
+ let e = r.readU8(), t = je(e);
364
367
  if (!t) return {
365
368
  ok: !1,
366
369
  diagnostics: [{
@@ -400,7 +403,7 @@ function Ie(e, t = {}) {
400
403
  }
401
404
  //#endregion
402
405
  //#region src/protocolReplay.ts
403
- var Le = class {
406
+ var Ie = class {
404
407
  items = [];
405
408
  peek() {
406
409
  return this.items[0];
@@ -433,10 +436,10 @@ var Le = class {
433
436
  this.items[t] = l, this.items[r] = c, t = r;
434
437
  }
435
438
  }
436
- }, O = class {
439
+ }, A = class {
437
440
  entries = /* @__PURE__ */ new Map();
438
441
  maxEntries;
439
- expiries = new Le();
442
+ expiries = new Ie();
440
443
  constructor(e = 1e4) {
441
444
  this.maxEntries = e;
442
445
  }
@@ -470,21 +473,23 @@ var Le = class {
470
473
  consume(e, t = Date.now()) {
471
474
  this.prune(t);
472
475
  let n = this.makeKey(e), r = this.entries.get(n);
473
- if (r && r > t) return {
476
+ if (r !== void 0 && (!Number.isFinite(r) || r > t)) return {
474
477
  ok: !1,
475
478
  reason: "Replay detected for sender/messageId/nonce"
476
479
  };
477
- this.entries.size >= this.maxEntries && this.evictOne();
478
480
  let i = e.header.timestampMs + e.header.ttlMs;
479
- return this.entries.set(n, i), this.expiries.push({
481
+ return Number.isFinite(i) ? (this.entries.size >= this.maxEntries && this.evictOne(), this.entries.set(n, i), this.expiries.push({
480
482
  key: n,
481
483
  expiresAt: i
482
- }), { ok: !0 };
484
+ }), { ok: !0 }) : {
485
+ ok: !1,
486
+ reason: "Cannot track replay protection for a non-finite timestampMs/ttlMs"
487
+ };
483
488
  }
484
489
  consumeMany(e, t = Date.now()) {
485
490
  return e.map((e) => this.consume(e, t));
486
491
  }
487
- }, Re = class {
492
+ }, Le = class {
488
493
  store;
489
494
  constructor(e) {
490
495
  this.store = e;
@@ -494,9 +499,12 @@ var Le = class {
494
499
  }
495
500
  async consume(e, t = Date.now()) {
496
501
  let n = this.makeKey(e), r = e.header.timestampMs + e.header.ttlMs;
497
- return await this.store.reserve(n, r, t) ? { ok: !0 } : {
502
+ return Number.isFinite(r) ? await this.store.reserve(n, r, t) ? { ok: !0 } : {
498
503
  ok: !1,
499
504
  reason: "Replay detected for sender/messageId/nonce"
505
+ } : {
506
+ ok: !1,
507
+ reason: "Cannot track replay protection for a non-finite timestampMs/ttlMs"
500
508
  };
501
509
  }
502
510
  async consumeMany(e, t = Date.now()) {
@@ -512,7 +520,7 @@ var Le = class {
512
520
  }
513
521
  return Promise.all(e.map((e) => this.consume(e, t)));
514
522
  }
515
- }, ze = class {
523
+ }, Re = class {
516
524
  entries = /* @__PURE__ */ new Map();
517
525
  maxEntries;
518
526
  constructor(e = 512) {
@@ -542,20 +550,20 @@ var Le = class {
542
550
  this.entries.delete(e);
543
551
  }
544
552
  };
545
- function Be(e, t) {
553
+ function ze(e, t) {
546
554
  return `${t}|${e.alg}|${e.keyId}`;
547
555
  }
548
- function Ve(e) {
556
+ function Be(e) {
549
557
  if (!e || typeof e != "object") return !1;
550
558
  let t = e;
551
559
  return !!(t.header && t.body);
552
560
  }
553
- function He(e) {
561
+ function Ve(e) {
554
562
  if (!e || typeof e != "object") return !1;
555
563
  let t = e;
556
564
  return t.v === "7h3/0.1" && typeof t.mid == "string" && typeof t.i == "string";
557
565
  }
558
- function Ue(e) {
566
+ function He(e) {
559
567
  return {
560
568
  header: {
561
569
  version: e.v,
@@ -579,7 +587,7 @@ function Ue(e) {
579
587
  } : void 0
580
588
  };
581
589
  }
582
- function We(e) {
590
+ function Ue(e) {
583
591
  return {
584
592
  v: e.header.version,
585
593
  mid: e.header.messageId,
@@ -599,15 +607,15 @@ function We(e) {
599
607
  } : void 0
600
608
  };
601
609
  }
602
- function Ge(e) {
603
- if (e instanceof Uint8Array) return Ie(e);
610
+ function We(e) {
611
+ if (e instanceof Uint8Array) return Fe(e);
604
612
  try {
605
613
  let t = JSON.parse(e);
606
- return He(t) ? {
614
+ return Ve(t) ? {
607
615
  ok: !0,
608
616
  diagnostics: [],
609
- envelope: Ue(t)
610
- } : Ve(t) ? {
617
+ envelope: He(t)
618
+ } : Be(t) ? {
611
619
  ok: !0,
612
620
  diagnostics: [],
613
621
  envelope: t
@@ -630,20 +638,20 @@ function Ge(e) {
630
638
  };
631
639
  }
632
640
  }
633
- function Ke(e, t = "json") {
634
- return t === "binary" ? Fe(e) : JSON.stringify(t === "compact" ? We(e) : e);
641
+ function j(e, t = "json") {
642
+ return t === "binary" ? Pe(e) : JSON.stringify(t === "compact" ? Ue(e) : e);
635
643
  }
636
- function qe(e, t = "compact") {
637
- return JSON.stringify(t === "compact" ? e.map(We) : e);
644
+ function Ge(e, t = "compact") {
645
+ return JSON.stringify(t === "compact" ? e.map(Ue) : e);
638
646
  }
639
- function Je(e) {
647
+ function Ke(e) {
640
648
  try {
641
649
  let t = JSON.parse(e);
642
- return Array.isArray(t) ? t.map((e) => He(e) ? {
650
+ return Array.isArray(t) ? t.map((e) => Ve(e) ? {
643
651
  ok: !0,
644
652
  diagnostics: [],
645
- envelope: Ue(e)
646
- } : Ve(e) ? {
653
+ envelope: He(e)
654
+ } : Be(e) ? {
647
655
  ok: !0,
648
656
  diagnostics: [],
649
657
  envelope: e
@@ -673,7 +681,7 @@ function Je(e) {
673
681
  }];
674
682
  }
675
683
  }
676
- async function k(e, t = {}) {
684
+ async function M(e, t = {}) {
677
685
  let n = t.nowMs ?? Date.now(), r = t.requireSignature ?? !0, i = t.maxClockSkewMs ?? 3e4;
678
686
  async function a(e) {
679
687
  t.telemetry && await t.telemetry({
@@ -681,7 +689,7 @@ async function k(e, t = {}) {
681
689
  ...e
682
690
  });
683
691
  }
684
- let o = typeof e == "string" || e instanceof Uint8Array ? Ge(e) : {
692
+ let o = typeof e == "string" || e instanceof Uint8Array ? We(e) : {
685
693
  ok: !0,
686
694
  diagnostics: [],
687
695
  envelope: e
@@ -691,7 +699,7 @@ async function k(e, t = {}) {
691
699
  phase: "decoded",
692
700
  sender: o.envelope.header.sender,
693
701
  messageId: o.envelope.header.messageId
694
- }), o.envelope.header.timestampMs > n + i) {
702
+ }), !Number.isFinite(o.envelope.header.timestampMs) || o.envelope.header.timestampMs > n + i) {
695
703
  let e = "Message timestamp exceeds allowed clock skew", t = [{
696
704
  level: "error",
697
705
  message: e
@@ -707,7 +715,7 @@ async function k(e, t = {}) {
707
715
  envelope: o.envelope
708
716
  };
709
717
  }
710
- let s = [...w(o.envelope, n)];
718
+ let s = [...E(o.envelope, n)];
711
719
  if (s.some((e) => e.level === "error")) return await a({
712
720
  phase: "rejected_validation",
713
721
  sender: o.envelope.header.sender,
@@ -739,7 +747,7 @@ async function k(e, t = {}) {
739
747
  diagnostics: s,
740
748
  envelope: o.envelope
741
749
  });
742
- let c, l = o.envelope.signature, u = Be(l, o.envelope.header.sender);
750
+ let c, l = o.envelope.signature, u = ze(l, o.envelope.header.sender);
743
751
  if (t.verificationMaterialCache && (c = t.verificationMaterialCache.get(u, n)), t.signatureResolver && (c ??= await t.signatureResolver(l, o.envelope.header.sender)), !c && l.alg === "HS256" && t.secretResolver) {
744
752
  let e = await t.secretResolver(l.keyId, o.envelope.header.sender);
745
753
  e && (c = {
@@ -764,7 +772,7 @@ async function k(e, t = {}) {
764
772
  diagnostics: s,
765
773
  envelope: o.envelope
766
774
  };
767
- if (!await _e(g({
775
+ if (!await he(_({
768
776
  header: o.envelope.header,
769
777
  body: o.envelope.body
770
778
  }), o.envelope.signature, c)) return s.push({
@@ -806,7 +814,7 @@ async function k(e, t = {}) {
806
814
  envelope: o.envelope
807
815
  };
808
816
  }
809
- async function Ye(e, t = {}) {
817
+ async function qe(e, t = {}) {
810
818
  let n = Math.max(1, Math.floor(t.batchConcurrency ?? Infinity));
811
819
  return (async (e) => {
812
820
  let r = Array(e.length), i = 0, a = Number.isFinite(n) ? Math.min(n, e.length) : e.length;
@@ -815,48 +823,48 @@ async function Ye(e, t = {}) {
815
823
  let n = i;
816
824
  i += 1;
817
825
  let a = e[n];
818
- a && typeof a == "object" && "ok" in a && "diagnostics" in a && "envelope" in a ? r[n] = a : r[n] = await k(a, t);
826
+ a && typeof a == "object" && "ok" in a && "diagnostics" in a && "envelope" in a ? r[n] = a : r[n] = await M(a, t);
819
827
  }
820
828
  })), await t.telemetry?.({
821
829
  phase: "batch_summary",
822
830
  nowMs: t.nowMs ?? Date.now(),
823
831
  reason: `items=${e.length};accepted=${r.filter((e) => e?.ok).length}`
824
832
  }), r;
825
- })(typeof e == "string" ? Je(e).map((e) => e.ok && e.envelope ? e.envelope : e) : e);
833
+ })(typeof e == "string" ? Ke(e).map((e) => e.ok && e.envelope ? e.envelope : e) : e);
826
834
  }
827
- var Xe = class {
835
+ var Je = class {
828
836
  options;
829
837
  constructor(e = {}) {
830
838
  this.options = {
831
839
  ...e,
832
- replayCache: e.replayCache ?? new O(),
833
- verificationMaterialCache: e.verificationMaterialCache ?? new ze()
840
+ replayCache: e.replayCache ?? new A(),
841
+ verificationMaterialCache: e.verificationMaterialCache ?? new Re()
834
842
  };
835
843
  }
836
844
  receive(e, t = Date.now()) {
837
- return k(e, {
845
+ return M(e, {
838
846
  ...this.options,
839
847
  nowMs: t
840
848
  });
841
849
  }
842
850
  receiveBatch(e, t = Date.now()) {
843
- return Ye(e, {
851
+ return qe(e, {
844
852
  ...this.options,
845
853
  nowMs: t
846
854
  });
847
855
  }
848
856
  };
849
- async function Ze(e) {
850
- return x(T(e), e.secret, e.keyId);
857
+ async function Ye(e) {
858
+ return S(D(e), e.secret, e.keyId);
851
859
  }
852
860
  //#endregion
853
861
  //#region src/protocolCapabilities.ts
854
- var Qe = [
862
+ var Xe = [
855
863
  "binary",
856
864
  "compact",
857
865
  "json"
858
- ], $e = ["fast", "receipt"];
859
- function et(e) {
866
+ ], Ze = ["fast", "receipt"];
867
+ function Qe(e) {
860
868
  return {
861
869
  agent: e.agent,
862
870
  capabilities: e.capabilities ?? [],
@@ -865,10 +873,10 @@ function et(e) {
865
873
  ackModes: e.ackModes ?? ["receipt"]
866
874
  };
867
875
  }
868
- function tt(e) {
876
+ function $e(e) {
869
877
  return JSON.stringify(e);
870
878
  }
871
- function nt(e) {
879
+ function et(e) {
872
880
  try {
873
881
  let t = JSON.parse(e);
874
882
  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 : {
@@ -882,8 +890,8 @@ function nt(e) {
882
890
  return null;
883
891
  }
884
892
  }
885
- function rt(e, t) {
886
- 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";
893
+ function tt(e, t) {
894
+ let n = Xe.find((n) => e.wireFormats.includes(n) && t.wireFormats.includes(n)) ?? "compact", r = Ze.find((n) => e.ackModes.includes(n) && t.ackModes.includes(n)) ?? "receipt";
887
895
  return {
888
896
  wireFormat: n,
889
897
  batchMax: Math.max(1, Math.min(e.batchMax, t.batchMax)),
@@ -892,7 +900,7 @@ function rt(e, t) {
892
900
  }
893
901
  //#endregion
894
902
  //#region src/keyRotation.ts
895
- var it = class {
903
+ var nt = class {
896
904
  records;
897
905
  constructor(e = []) {
898
906
  this.records = [...e];
@@ -911,12 +919,12 @@ var it = class {
911
919
  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;
912
920
  }
913
921
  };
914
- function at(e, t = () => Date.now()) {
922
+ function rt(e, t = () => Date.now()) {
915
923
  return async (n, r) => e.resolveVerificationMaterial(n, r, t());
916
924
  }
917
925
  //#endregion
918
926
  //#region src/protocolAgent.ts
919
- var ot = class {
927
+ var it = class {
920
928
  agentId;
921
929
  outboundSecret;
922
930
  keyId;
@@ -930,13 +938,13 @@ var ot = class {
930
938
  resolveInboundSecret;
931
939
  onTask;
932
940
  constructor(e) {
933
- 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 O(), this.sharedSecrets = e.sharedSecrets ?? {}, this.resolveInboundSecret = e.resolveInboundSecret, this.onTask = e.onTask;
941
+ 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;
934
942
  }
935
943
  async inboundSecretResolver(e, t) {
936
944
  return this.resolveInboundSecret ? this.resolveInboundSecret(e, t) : this.sharedSecrets[t];
937
945
  }
938
946
  async createSignedIntent(e) {
939
- return x(T({
947
+ return S(D({
940
948
  sender: this.agentId,
941
949
  recipient: e.recipient,
942
950
  intent: e.intent,
@@ -950,7 +958,7 @@ var ot = class {
950
958
  }), this.outboundSecret, this.keyId);
951
959
  }
952
960
  async receiveAndRespond(e, t = Date.now()) {
953
- let n = await k(e, {
961
+ let n = await M(e, {
954
962
  nowMs: t,
955
963
  requireSignature: this.requireSignature,
956
964
  replayCache: this.replayCache,
@@ -981,7 +989,7 @@ var ot = class {
981
989
  if (e.body.intent === "CAPS") return this.createSignedIntent({
982
990
  recipient: e.header.sender,
983
991
  intent: "RESULT",
984
- content: tt(et({
992
+ content: $e(Qe({
985
993
  agent: this.agentId,
986
994
  capabilities: this.capabilities,
987
995
  wireFormats: this.supportedWireFormats,
@@ -1009,14 +1017,14 @@ var ot = class {
1009
1017
  }
1010
1018
  return null;
1011
1019
  }
1012
- }, st = class {
1020
+ }, at = class {
1013
1021
  session;
1014
1022
  wireFormat;
1015
1023
  constructor(e) {
1016
- this.session = new ot(e), this.wireFormat = e.wireFormat ?? "compact";
1024
+ this.session = new it(e), this.wireFormat = e.wireFormat ?? "compact";
1017
1025
  }
1018
1026
  toRaw(e) {
1019
- return Ke(e, this.wireFormat);
1027
+ return j(e, this.wireFormat);
1020
1028
  }
1021
1029
  async createRawIntent(e) {
1022
1030
  let t = await this.session.createSignedIntent(e);
@@ -1030,12 +1038,12 @@ var ot = class {
1030
1038
  return r.response && await t(this.toRaw(r.response), r.response), r;
1031
1039
  }
1032
1040
  };
1033
- function ct(e) {
1034
- return new st(e);
1041
+ function ot(e) {
1042
+ return new at(e);
1035
1043
  }
1036
1044
  //#endregion
1037
1045
  //#region src/frameworkAdapters.ts
1038
- async function lt(e, t, n = {}) {
1046
+ async function st(e, t, n = {}) {
1039
1047
  return e.createRawIntent({
1040
1048
  recipient: n.recipient,
1041
1049
  intent: "TASK",
@@ -1044,7 +1052,7 @@ async function lt(e, t, n = {}) {
1044
1052
  correlationId: n.correlationId
1045
1053
  });
1046
1054
  }
1047
- function ut(e) {
1055
+ function ct(e) {
1048
1056
  return {
1049
1057
  content: e.body.content,
1050
1058
  name: e.body.intent,
@@ -1058,7 +1066,7 @@ function ut(e) {
1058
1066
  }
1059
1067
  };
1060
1068
  }
1061
- async function dt(e, t, n = {}) {
1069
+ async function lt(e, t, n = {}) {
1062
1070
  return e.createRawIntent({
1063
1071
  recipient: n.recipient,
1064
1072
  intent: "TASK",
@@ -1067,7 +1075,7 @@ async function dt(e, t, n = {}) {
1067
1075
  correlationId: n.correlationId
1068
1076
  });
1069
1077
  }
1070
- function ft(e) {
1078
+ function ut(e) {
1071
1079
  return {
1072
1080
  role: e.body.intent === "TASK" ? "user" : "assistant",
1073
1081
  content: e.body.content,
@@ -1080,15 +1088,15 @@ function ft(e) {
1080
1088
  }
1081
1089
  };
1082
1090
  }
1083
- function pt(e) {
1091
+ function dt(e) {
1084
1092
  return `mcp.${e}`;
1085
1093
  }
1086
- async function mt(e, t, n = {}) {
1094
+ async function ft(e, t, n = {}) {
1087
1095
  async function r(e) {
1088
1096
  n.onPolicyEvent && await n.onPolicyEvent(e);
1089
1097
  }
1090
1098
  if (n.allowedMethods && !n.allowedMethods.includes(t.method)) {
1091
- let e = n.methodToCapability ? n.methodToCapability(t.method) : pt(t.method), i = {
1099
+ let e = n.methodToCapability ? n.methodToCapability(t.method) : dt(t.method), i = {
1092
1100
  intent: "TASK",
1093
1101
  recipient: n.recipient,
1094
1102
  capability: e,
@@ -1103,7 +1111,7 @@ async function mt(e, t, n = {}) {
1103
1111
  reason: "method_not_allowed"
1104
1112
  }), Error(`JSON-RPC method '${t.method}' is not allowed`);
1105
1113
  }
1106
- let i = n.methodToCapability ? n.methodToCapability(t.method) : pt(t.method), a = {
1114
+ let i = n.methodToCapability ? n.methodToCapability(t.method) : dt(t.method), a = {
1107
1115
  intent: "TASK",
1108
1116
  recipient: n.recipient,
1109
1117
  capability: i,
@@ -1157,7 +1165,7 @@ async function mt(e, t, n = {}) {
1157
1165
  })
1158
1166
  });
1159
1167
  }
1160
- function ht(e, t, n = {}) {
1168
+ function pt(e, t, n = {}) {
1161
1169
  if (e.body.intent === "ERROR") return {
1162
1170
  jsonrpc: "2.0",
1163
1171
  id: t,
@@ -1184,16 +1192,16 @@ function ht(e, t, n = {}) {
1184
1192
  }
1185
1193
  //#endregion
1186
1194
  //#region src/runtimePolicy.ts
1187
- function gt(e) {
1195
+ function mt(e) {
1188
1196
  return typeof e == "object" && !!e && !Array.isArray(e);
1189
1197
  }
1190
- function _t(e, t) {
1198
+ function ht(e, t) {
1191
1199
  if (typeof e != "string" || e.trim().length === 0) throw Error(`Invalid runtime policy: '${t}' must be a non-empty string`);
1192
1200
  return e;
1193
1201
  }
1194
- function vt(e) {
1195
- if (!gt(e)) throw Error("Invalid runtime policy: root must be an object");
1196
- let t = _t(e.version, "version"), n = _t(e.name, "name"), r = _t(e.status, "status");
1202
+ function gt(e) {
1203
+ if (!mt(e)) throw Error("Invalid runtime policy: root must be an object");
1204
+ let t = ht(e.version, "version"), n = ht(e.name, "name"), r = ht(e.status, "status");
1197
1205
  return {
1198
1206
  ...e,
1199
1207
  version: t,
@@ -1201,7 +1209,7 @@ function vt(e) {
1201
1209
  status: r
1202
1210
  };
1203
1211
  }
1204
- function yt(e) {
1212
+ function _t(e) {
1205
1213
  let t;
1206
1214
  try {
1207
1215
  t = JSON.parse(e);
@@ -1209,9 +1217,9 @@ function yt(e) {
1209
1217
  let t = e instanceof Error ? e.message : String(e);
1210
1218
  throw Error(`Invalid runtime policy JSON: ${t}`, { cause: e });
1211
1219
  }
1212
- return vt(t);
1220
+ return gt(t);
1213
1221
  }
1214
- async function bt(e) {
1222
+ async function vt(e) {
1215
1223
  if (typeof fetch == "function") {
1216
1224
  let t = await fetch(e);
1217
1225
  if (!t.ok) throw Error(`Failed to fetch runtime policy at '${e}': ${t.status} ${t.statusText}`);
@@ -1219,26 +1227,26 @@ async function bt(e) {
1219
1227
  }
1220
1228
  throw Error("No default runtime file reader available in this environment. Provide 'readTextFile' in loadRuntimePolicy(options).");
1221
1229
  }
1222
- async function xt(e = {}) {
1230
+ async function yt(e = {}) {
1223
1231
  let t = e.path ?? "AI_RUNTIME_POLICY.json";
1224
- return yt(await (e.readTextFile ?? bt)(t));
1232
+ return _t(await (e.readTextFile ?? vt)(t));
1225
1233
  }
1226
1234
  //#endregion
1227
1235
  //#region src/policyEnforcer.ts
1228
- function St(e, t) {
1236
+ function bt(e, t) {
1229
1237
  if (!Array.isArray(e) || e.length !== 2) throw Error(`Invalid policy tuning range '${t}': expected [min,max]`);
1230
1238
  let n = Number(e[0]), r = Number(e[1]);
1231
1239
  if (!Number.isFinite(n) || !Number.isFinite(r) || n <= 0 || r < n) throw Error(`Invalid policy tuning range '${t}': expected positive ascending numbers`);
1232
1240
  return [Math.floor(n), Math.floor(r)];
1233
1241
  }
1234
- function Ct(e) {
1242
+ function xt(e) {
1235
1243
  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";
1236
1244
  }
1237
- function wt(e) {
1245
+ function St(e) {
1238
1246
  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) => ({
1239
- batchSizeRange: St(o?.[`${e}_traffic`], `batch_size.${e}_traffic`),
1240
- inflightCapRange: St(s?.[`${e}_traffic`], `inflight_cap.${e}_traffic`),
1241
- retryBackoffMsRange: St(c?.[`${e}_traffic`], `retry_backoff_ms.${e}_traffic`)
1247
+ batchSizeRange: bt(o?.[`${e}_traffic`], `batch_size.${e}_traffic`),
1248
+ inflightCapRange: bt(s?.[`${e}_traffic`], `inflight_cap.${e}_traffic`),
1249
+ retryBackoffMsRange: bt(c?.[`${e}_traffic`], `retry_backoff_ms.${e}_traffic`)
1242
1250
  });
1243
1251
  function u(e) {
1244
1252
  return e.concurrency >= 100 ? "http-binary-batch" : e.latencySensitive ? "ws-batch" : e.compatibilityFirst ? "http" : "ws-batch";
@@ -1275,28 +1283,28 @@ function wt(e) {
1275
1283
  }
1276
1284
  };
1277
1285
  }
1278
- async function Tt(e = {}) {
1279
- let t = await xt(e);
1286
+ async function N(e = {}) {
1287
+ let t = await yt(e);
1280
1288
  return {
1281
1289
  policy: t,
1282
- enforcer: wt(t)
1290
+ enforcer: St(t)
1283
1291
  };
1284
1292
  }
1285
- function Et(e) {
1286
- return Ct(e);
1293
+ function Ct(e) {
1294
+ return xt(e);
1287
1295
  }
1288
1296
  //#endregion
1289
1297
  //#region src/mcpGateway.ts
1290
- var Dt = [
1298
+ var wt = [
1291
1299
  "tools/call",
1292
1300
  "resources/read",
1293
1301
  "prompts/get"
1294
1302
  ];
1295
- function Ot(e) {
1303
+ function Tt(e) {
1296
1304
  return JSON.stringify(e);
1297
1305
  }
1298
- function A(e, t, n) {
1299
- return Ot({
1306
+ function Et(e, t, n) {
1307
+ return Tt({
1300
1308
  jsonrpc: "2.0",
1301
1309
  id: e,
1302
1310
  error: {
@@ -1305,7 +1313,7 @@ function A(e, t, n) {
1305
1313
  }
1306
1314
  });
1307
1315
  }
1308
- function kt(e) {
1316
+ function Dt(e) {
1309
1317
  let t = JSON.parse(e);
1310
1318
  return t.jsonrpc !== "2.0" || typeof t.method != "string" || t.method.length === 0 || typeof t.id != "string" && typeof t.id != "number" ? null : {
1311
1319
  jsonrpc: "2.0",
@@ -1314,30 +1322,30 @@ function kt(e) {
1314
1322
  params: t.params
1315
1323
  };
1316
1324
  }
1317
- function At(e) {
1325
+ function Ot(e) {
1318
1326
  return e.includes("not allowed") ? -32601 : e.includes("not authorized") ? -32001 : e.includes("rate-limited") ? -32002 : -32603;
1319
1327
  }
1320
- function jt(e) {
1321
- let t = e.gatewayAgentId ?? "agent.gateway", n = e.workerAgentId ?? "agent.worker", r = e.allowedMethods ?? Dt, i = e.workerCapabilityPrefix ?? "mcp.", a = e.gatewayWireFormat ?? "compact", o = e.workerWireFormat ?? "compact";
1328
+ function kt(e) {
1329
+ let t = e.gatewayAgentId ?? "agent.gateway", n = e.workerAgentId ?? "agent.worker", r = e.allowedMethods ?? wt, i = e.workerCapabilityPrefix ?? "mcp.", a = e.gatewayWireFormat ?? "compact", o = e.workerWireFormat ?? "compact";
1322
1330
  async function s(t) {
1323
1331
  e.onAuditEvent && await e.onAuditEvent({
1324
1332
  ...t,
1325
1333
  timestampMs: Date.now()
1326
1334
  });
1327
1335
  }
1328
- let c = ct({
1336
+ let c = ot({
1329
1337
  agentId: t,
1330
1338
  outboundSecret: e.sharedSecret,
1331
1339
  sharedSecrets: { [n]: e.sharedSecret },
1332
1340
  wireFormat: a
1333
- }), l = ct({
1341
+ }), l = ot({
1334
1342
  agentId: n,
1335
1343
  outboundSecret: e.sharedSecret,
1336
1344
  sharedSecrets: { [t]: e.sharedSecret },
1337
1345
  wireFormat: o,
1338
1346
  onTask: async (e) => ({
1339
1347
  intent: "RESULT",
1340
- content: Ot({
1348
+ content: Tt({
1341
1349
  ok: !0,
1342
1350
  capability: e.body.capability,
1343
1351
  content: e.body.content
@@ -1350,18 +1358,18 @@ function jt(e) {
1350
1358
  if (!i) return null;
1351
1359
  let a = null;
1352
1360
  try {
1353
- let t = kt(i);
1361
+ let t = Dt(i);
1354
1362
  if (!t) return await s({
1355
1363
  phase: "request_error",
1356
1364
  code: -32600,
1357
1365
  message: "Invalid Request"
1358
- }), A(null, -32600, "Invalid Request");
1366
+ }), Et(null, -32600, "Invalid Request");
1359
1367
  a = t.id, await s({
1360
1368
  phase: "request_received",
1361
1369
  id: t.id,
1362
1370
  method: t.method
1363
1371
  });
1364
- let o = await mt(c, t, {
1372
+ let o = {
1365
1373
  recipient: n,
1366
1374
  allowedMethods: r,
1367
1375
  methodToCapability: e.methodToCapability,
@@ -1376,42 +1384,42 @@ function jt(e) {
1376
1384
  policy: e
1377
1385
  });
1378
1386
  }
1379
- }), u = null;
1380
- if (await l.handleRaw(o, async (e) => {
1381
- u = e;
1382
- }), !u) return await s({
1387
+ }, u = await ft(c, t, o), d = null;
1388
+ if (await l.handleRaw(u, async (e) => {
1389
+ d = e;
1390
+ }), !d) return await s({
1383
1391
  phase: "verification_failed",
1384
1392
  id: t.id,
1385
1393
  method: t.method,
1386
1394
  code: -32603,
1387
1395
  message: "AIP worker did not produce a response"
1388
- }), A(a, -32603, "AIP worker did not produce a response");
1389
- let d = await c.receiveRaw(u);
1390
- return !d.ok || !d.received ? (await s({
1396
+ }), Et(a, -32603, "AIP worker did not produce a response");
1397
+ let f = await c.receiveRaw(d);
1398
+ return !f.ok || !f.received ? (await s({
1391
1399
  phase: "verification_failed",
1392
1400
  id: t.id,
1393
1401
  method: t.method,
1394
1402
  code: -32603,
1395
1403
  message: "AIP verification failed"
1396
- }), A(a, -32603, "AIP verification failed")) : (await s({
1404
+ }), Et(a, -32603, "AIP verification failed")) : (await s({
1397
1405
  phase: "request_success",
1398
1406
  id: t.id,
1399
1407
  method: t.method
1400
- }), Ot(ht(d.received, t.id)));
1408
+ }), Tt(pt(f.received, t.id)));
1401
1409
  } catch (e) {
1402
- let t = e instanceof Error ? e.message : "Internal error", n = At(t);
1410
+ let t = e instanceof Error ? e.message : "Internal error", n = Ot(t);
1403
1411
  return await s({
1404
1412
  phase: "request_error",
1405
1413
  id: a,
1406
1414
  code: n,
1407
1415
  message: t
1408
- }), A(a, n, t);
1416
+ }), Et(a, n, t);
1409
1417
  }
1410
1418
  } };
1411
1419
  }
1412
- async function Mt(e) {
1413
- if (!e.runtimePolicy?.enabled) return jt(e);
1414
- let { enforcer: t } = await Tt(e.runtimePolicy.options);
1420
+ async function At(e) {
1421
+ if (!e.runtimePolicy?.enabled) return kt(e);
1422
+ let { enforcer: t } = await N(e.runtimePolicy.options);
1415
1423
  t.assertInvariant({
1416
1424
  signatureVerification: !0,
1417
1425
  canonicalization: !0,
@@ -1423,7 +1431,7 @@ async function Mt(e) {
1423
1431
  latencySensitive: e.runtimePolicy.latencySensitive,
1424
1432
  compatibilityFirst: e.runtimePolicy.compatibilityFirst
1425
1433
  }), r = n.includes("binary") ? "binary" : "compact";
1426
- return jt({
1434
+ return kt({
1427
1435
  ...e,
1428
1436
  gatewayWireFormat: r,
1429
1437
  workerWireFormat: r,
@@ -1439,14 +1447,14 @@ async function Mt(e) {
1439
1447
  }
1440
1448
  //#endregion
1441
1449
  //#region src/runtimePolicyManager.ts
1442
- var Nt = class {
1450
+ var jt = class {
1443
1451
  snapshot = null;
1444
1452
  options;
1445
1453
  constructor(e = {}) {
1446
1454
  this.options = e;
1447
1455
  }
1448
1456
  async loadInitial() {
1449
- let e = await Tt(this.options);
1457
+ let e = await N(this.options);
1450
1458
  return this.snapshot = {
1451
1459
  ...e,
1452
1460
  loadedAtMs: Date.now()
@@ -1459,7 +1467,7 @@ var Nt = class {
1459
1467
  async refresh() {
1460
1468
  let e = this.snapshot;
1461
1469
  try {
1462
- let e = await Tt(this.options);
1470
+ let e = await N(this.options);
1463
1471
  return this.snapshot = {
1464
1472
  ...e,
1465
1473
  loadedAtMs: Date.now()
@@ -1469,7 +1477,7 @@ var Nt = class {
1469
1477
  throw t;
1470
1478
  }
1471
1479
  }
1472
- }, Pt = {
1480
+ }, Mt = {
1473
1481
  dev: {
1474
1482
  environment: "dev",
1475
1483
  mode: "ws-batch",
@@ -1495,12 +1503,12 @@ var Nt = class {
1495
1503
  retryMaxAttempts: 3
1496
1504
  }
1497
1505
  };
1498
- function Ft(e) {
1499
- return Pt[e];
1506
+ function Nt(e) {
1507
+ return Mt[e];
1500
1508
  }
1501
1509
  //#endregion
1502
1510
  //#region src/policyTelemetryFeedback.ts
1503
- function It(e) {
1511
+ function Pt(e) {
1504
1512
  let t = [], n = "normal";
1505
1513
  return e.dropPct > .1 && (t.push("reduce inflight cap"), t.push("reduce batch size"), t.push("increase retry backoff"), e.mode === "http" && e.concurrency >= 100 && t.push("switch to http-binary-batch"), n = e.dropPct > 2 ? "critical" : "warn"), e.p99Ms > 20 && (t.push("reduce batch size"), t.push("run adaptive benchmark and re-baseline"), n === "normal" && (n = "warn"), e.p99Ms > 100 && (n = "critical")), {
1506
1514
  severity: n,
@@ -1509,7 +1517,7 @@ function It(e) {
1509
1517
  }
1510
1518
  //#endregion
1511
1519
  //#region src/redisClient.ts
1512
- var Lt = class {
1520
+ var Ft = class {
1513
1521
  entries = /* @__PURE__ */ new Map();
1514
1522
  now;
1515
1523
  constructor(e = {}) {
@@ -1555,13 +1563,13 @@ var Lt = class {
1555
1563
  };
1556
1564
  return t;
1557
1565
  }
1558
- }, Rt = class {
1566
+ }, It = class {
1559
1567
  keyPrefix;
1560
1568
  client;
1561
1569
  constructor(e = {}) {
1562
1570
  if (this.keyPrefix = e.keyPrefix ?? "7h3:nonce:", e.client) this.client = e.client;
1563
1571
  else {
1564
- let e = new Lt();
1572
+ let e = new Ft();
1565
1573
  this.client = {
1566
1574
  set: (t, n, r) => e.set(t, n, {
1567
1575
  nx: r?.nx,
@@ -1580,7 +1588,7 @@ var Lt = class {
1580
1588
  px: Math.max(1, t)
1581
1589
  }) === null;
1582
1590
  }
1583
- }, zt = class {
1591
+ }, Lt = class {
1584
1592
  nodes;
1585
1593
  constructor(e) {
1586
1594
  this.nodes = e;
@@ -1589,17 +1597,17 @@ var Lt = class {
1589
1597
  return (await Promise.all(this.nodes.map((n) => n.check(e, t)))).some((e) => e);
1590
1598
  }
1591
1599
  };
1592
- function Bt(e, t = {}) {
1593
- return Vt(e) ? Ut(e, t) : new Rt(e);
1600
+ function Rt(e, t = {}) {
1601
+ return zt(e) ? Vt(e, t) : new It(e);
1594
1602
  }
1595
- function Vt(e) {
1603
+ function zt(e) {
1596
1604
  return typeof e == "object" && !!e && typeof e.set == "function" && (typeof e.pipeline == "function" || !("quit" in e));
1597
1605
  }
1598
- function Ht(e) {
1599
- return new zt(e.map((e) => new Rt({ redisUrl: e })));
1606
+ function Bt(e) {
1607
+ return new Lt(e.map((e) => new It({ redisUrl: e })));
1600
1608
  }
1601
- function Ut(e, t = {}) {
1602
- let n = t.keyPrefix ?? "aip:replay:", r = t.errorBehavior ?? "fallback", i = t.onDegraded, a = t.fallback ?? (r === "fallback" ? Ut(new Lt(), {
1609
+ function Vt(e, t = {}) {
1610
+ let n = t.keyPrefix ?? "aip:replay:", r = t.errorBehavior ?? "fallback", i = t.onDegraded, a = t.fallback ?? (r === "fallback" ? Vt(new Ft(), {
1603
1611
  keyPrefix: n,
1604
1612
  errorBehavior: "reject"
1605
1613
  }) : void 0);
@@ -1639,7 +1647,7 @@ function Ut(e, t = {}) {
1639
1647
  }
1640
1648
  //#endregion
1641
1649
  //#region src/revocation.ts
1642
- var Wt = class {
1650
+ var Ht = class {
1643
1651
  revoked = /* @__PURE__ */ new Map();
1644
1652
  now;
1645
1653
  constructor(e = {}) {
@@ -1656,7 +1664,7 @@ var Wt = class {
1656
1664
  this.revoked.set(this.makeKey(e, t), n.untilMs ?? Infinity);
1657
1665
  }
1658
1666
  };
1659
- function Gt(e, t = {}) {
1667
+ function Ut(e, t = {}) {
1660
1668
  let n = t.keyPrefix ?? "aip:revoked:", r = t.errorBehavior ?? "reject", i = t.cacheTtlMs ?? 5e3, a = t.onDegraded, o = t.now ?? (() => Date.now()), s = /* @__PURE__ */ new Map();
1661
1669
  function c(e, t) {
1662
1670
  return `${n}${e}${t}`;
@@ -1688,7 +1696,7 @@ function Gt(e, t = {}) {
1688
1696
  }
1689
1697
  };
1690
1698
  }
1691
- function Kt(e, t, n = {}) {
1699
+ function Wt(e, t, n = {}) {
1692
1700
  let r = n.nowMsProvider ?? (() => Date.now());
1693
1701
  return async (n, i) => {
1694
1702
  if (!await t.isRevoked(i, n.keyId, r())) return e(n, i);
@@ -1696,7 +1704,7 @@ function Kt(e, t, n = {}) {
1696
1704
  }
1697
1705
  //#endregion
1698
1706
  //#region src/mcpWrapper.ts
1699
- function j(e, t, n) {
1707
+ function Gt(e, t, n) {
1700
1708
  return {
1701
1709
  jsonrpc: "2.0",
1702
1710
  id: e,
@@ -1706,20 +1714,20 @@ function j(e, t, n) {
1706
1714
  }
1707
1715
  };
1708
1716
  }
1709
- function qt(e, t) {
1717
+ function Kt(e, t) {
1710
1718
  return {
1711
- requireSignature: !0,
1712
1719
  ...e.receive,
1720
+ requireSignature: !0,
1713
1721
  replayCache: t
1714
1722
  };
1715
1723
  }
1716
- function Jt(e, t) {
1717
- let n = t.wireFormat ?? "compact", r = t.ttlMs ?? 6e4, i = qt(t, t.receive?.replayCache ?? new O());
1724
+ function qt(e, t) {
1725
+ let n = t.wireFormat ?? "compact", r = t.ttlMs ?? 6e4, i = Kt(t, t.receive?.replayCache ?? new A());
1718
1726
  async function a(e) {
1719
- return Ke(await t.sign(e), n);
1727
+ return j(await t.sign(e), n);
1720
1728
  }
1721
1729
  function o(e, n, i, o) {
1722
- return a(T({
1730
+ return a(D({
1723
1731
  sender: t.selfAgentId,
1724
1732
  recipient: e,
1725
1733
  intent: n,
@@ -1729,29 +1737,29 @@ function Jt(e, t) {
1729
1737
  }));
1730
1738
  }
1731
1739
  return async (n) => {
1732
- let r = await k(n, i), a = r.envelope?.header.sender, s = r.envelope?.header.messageId;
1733
- if (!r.ok || !r.envelope) return o(a, "ERROR", j(null, -32600, r.diagnostics.find((e) => e.level === "error")?.message ?? "AIP verification failed"), s);
1734
- if (r.envelope.header.recipient !== t.selfAgentId) return o(a, "ERROR", j(null, -32600, "Recipient mismatch: envelope not addressed to this agent"), s);
1740
+ let r = await M(n, i), a = r.envelope?.header.sender, s = r.envelope?.header.messageId;
1741
+ if (!r.ok || !r.envelope) return o(a, "ERROR", Gt(null, -32600, r.diagnostics.find((e) => e.level === "error")?.message ?? "AIP verification failed"), s);
1742
+ if (r.envelope.header.recipient !== t.selfAgentId) return o(a, "ERROR", Gt(null, -32600, "Recipient mismatch: envelope not addressed to this agent"), s);
1735
1743
  let c;
1736
1744
  try {
1737
1745
  c = JSON.parse(r.envelope.body.content);
1738
1746
  } catch {
1739
- return o(a, "ERROR", j(null, -32700, "Parse error: envelope body is not JSON-RPC"), s);
1747
+ return o(a, "ERROR", Gt(null, -32700, "Parse error: envelope body is not JSON-RPC"), s);
1740
1748
  }
1741
1749
  let l;
1742
1750
  try {
1743
1751
  l = await e(c);
1744
1752
  } catch (e) {
1745
- l = j(c.id ?? null, -32603, e instanceof Error ? e.message : "Internal error");
1753
+ l = Gt(c.id ?? null, -32603, e instanceof Error ? e.message : "Internal error");
1746
1754
  }
1747
1755
  return o(r.envelope.header.sender, "RESULT", l, s);
1748
1756
  };
1749
1757
  }
1750
- function Yt(e) {
1751
- let t = e.wireFormat ?? "compact", n = e.ttlMs ?? 6e4, r = qt(e, e.receive?.replayCache ?? new O());
1758
+ function Jt(e) {
1759
+ let t = e.wireFormat ?? "compact", n = e.ttlMs ?? 6e4, r = Kt(e, e.receive?.replayCache ?? new A());
1752
1760
  return {
1753
1761
  async encodeRequest(r) {
1754
- let i = T({
1762
+ let i = D({
1755
1763
  sender: e.selfAgentId,
1756
1764
  recipient: e.peerAgentId,
1757
1765
  intent: "TASK",
@@ -1759,12 +1767,12 @@ function Yt(e) {
1759
1767
  ttlMs: n
1760
1768
  });
1761
1769
  return {
1762
- raw: Ke(await e.sign(i), t),
1770
+ raw: j(await e.sign(i), t),
1763
1771
  messageId: i.header.messageId
1764
1772
  };
1765
1773
  },
1766
1774
  async decodeResponse(t, n = {}) {
1767
- let i = await k(t, r);
1775
+ let i = await M(t, r);
1768
1776
  if (!i.ok || !i.envelope) {
1769
1777
  let e = i.diagnostics.find((e) => e.level === "error")?.message ?? "unknown";
1770
1778
  throw Error(`AIP response verification failed: ${e}`);
@@ -1776,8 +1784,8 @@ function Yt(e) {
1776
1784
  }
1777
1785
  };
1778
1786
  }
1779
- function Xt(e, t) {
1780
- let n = Yt(t);
1787
+ function Yt(e, t) {
1788
+ let n = Jt(t);
1781
1789
  return async (t) => {
1782
1790
  let { raw: r, messageId: i } = await n.encodeRequest(t);
1783
1791
  return n.decodeResponse(await e(r), { expectCorrelationId: i });
@@ -1785,55 +1793,52 @@ function Xt(e, t) {
1785
1793
  }
1786
1794
  //#endregion
1787
1795
  //#region src/mcpTransports.ts
1788
- var M = /* @__PURE__ */ c((/* @__PURE__ */ o(((e, t) => {
1789
- t.exports = {};
1790
- })))(), 1);
1791
- function Zt(e) {
1796
+ function Xt(e) {
1792
1797
  if (typeof e != "string") throw Error("stdio adapter supports json/compact (string) wire formats; use the HTTP adapter for binary");
1793
1798
  return e;
1794
1799
  }
1795
- function Qt(e, t = {}) {
1796
- let n = t.input ?? process.stdin, r = t.output ?? process.stdout, i = M.default.createInterface({
1797
- input: n,
1800
+ function Zt(t, n = {}) {
1801
+ let r = n.input ?? process.stdin, i = n.output ?? process.stdout, a = e.createInterface({
1802
+ input: r,
1798
1803
  crlfDelay: Infinity
1799
- }), a = Promise.resolve(), o = (n) => {
1800
- let i = n.trim();
1801
- i && (a = a.then(async () => {
1804
+ }), o = Promise.resolve(), s = (e) => {
1805
+ let r = e.trim();
1806
+ r && (o = o.then(async () => {
1802
1807
  try {
1803
- let t = await e(i);
1804
- r.write(`${Zt(t)}\n`);
1808
+ let e = await t(r);
1809
+ i.write(`${Xt(e)}\n`);
1805
1810
  } catch (e) {
1806
- t.onError?.(e);
1811
+ n.onError?.(e);
1807
1812
  }
1808
1813
  }));
1809
1814
  };
1810
- return i.on("line", o), { close() {
1811
- i.off("line", o), i.close();
1815
+ return a.on("line", s), { close() {
1816
+ a.off("line", s), a.close();
1812
1817
  } };
1813
1818
  }
1814
- function $t(e) {
1815
- let t = M.default.createInterface({
1816
- input: e.input,
1819
+ function Qt(t) {
1820
+ let n = e.createInterface({
1821
+ input: t.input,
1817
1822
  crlfDelay: Infinity
1818
- }), n = [], r = (e) => {
1823
+ }), r = [], i = (e) => {
1819
1824
  let t = e.trim();
1820
1825
  if (!t) return;
1821
- let r = n.shift();
1822
- r && r(t);
1823
- };
1824
- return t.on("line", r), {
1825
- send(t) {
1826
- let r = Zt(t);
1827
- return new Promise((t) => {
1828
- n.push(t), e.output.write(`${r}\n`);
1826
+ let n = r.shift();
1827
+ n && n(t);
1828
+ };
1829
+ return n.on("line", i), {
1830
+ send(e) {
1831
+ let n = Xt(e);
1832
+ return new Promise((e) => {
1833
+ r.push(e), t.output.write(`${n}\n`);
1829
1834
  });
1830
1835
  },
1831
1836
  close() {
1832
- t.off("line", r), t.close();
1837
+ n.off("line", i), n.close();
1833
1838
  }
1834
1839
  };
1835
1840
  }
1836
- function en(e, t = {}) {
1841
+ function $t(e, t = {}) {
1837
1842
  return (n, r) => {
1838
1843
  let i = [];
1839
1844
  n.on("data", (e) => i.push(e)), n.on("error", () => {
@@ -1857,7 +1862,7 @@ function en(e, t = {}) {
1857
1862
  });
1858
1863
  };
1859
1864
  }
1860
- function tn(e) {
1865
+ function en(e) {
1861
1866
  let t = e.fetchImpl ?? fetch, n = e.binary ? "application/octet-stream" : "application/json";
1862
1867
  return { async send(r) {
1863
1868
  let i = await t(e.url, {
@@ -1873,12 +1878,12 @@ function tn(e) {
1873
1878
  }
1874
1879
  //#endregion
1875
1880
  //#region src/keyRegistry.ts
1876
- function nn(e) {
1881
+ function tn(e) {
1877
1882
  return { async getPublicKey(t) {
1878
1883
  return e[t] ?? null;
1879
1884
  } };
1880
1885
  }
1881
- function rn(...e) {
1886
+ function nn(...e) {
1882
1887
  return {
1883
1888
  async getPublicKey(t) {
1884
1889
  for (let n of e) {
@@ -1887,17 +1892,17 @@ function rn(...e) {
1887
1892
  }
1888
1893
  return null;
1889
1894
  },
1890
- async getSharedSecret(t) {
1891
- for (let n of e) {
1892
- if (!n.getSharedSecret) continue;
1893
- let e = await n.getSharedSecret(t);
1895
+ async getSharedSecret(t, n) {
1896
+ for (let r of e) {
1897
+ if (!r.getSharedSecret) continue;
1898
+ let e = await r.getSharedSecret(t, n);
1894
1899
  if (e !== null) return e;
1895
1900
  }
1896
1901
  return null;
1897
1902
  }
1898
1903
  };
1899
1904
  }
1900
- function an(e, t) {
1905
+ function rn(e, t) {
1901
1906
  let n = t?.ttlMs ?? 6e4, r = /* @__PURE__ */ new Map();
1902
1907
  async function i(e, t) {
1903
1908
  let i = Date.now(), a = r.get(e);
@@ -1912,25 +1917,25 @@ function an(e, t) {
1912
1917
  async getPublicKey(t) {
1913
1918
  return i(`pk:${t}`, () => e.getPublicKey(t));
1914
1919
  },
1915
- async getSharedSecret(t) {
1916
- return e.getSharedSecret ? i(`ss:${t}`, () => e.getSharedSecret(t)) : null;
1920
+ async getSharedSecret(t, n) {
1921
+ return e.getSharedSecret ? i(`ss:${n}:${t}`, () => e.getSharedSecret(t, n)) : null;
1917
1922
  }
1918
1923
  };
1919
1924
  }
1920
1925
  //#endregion
1921
1926
  //#region src/cborCodec.ts
1922
- var N = new TextEncoder(), on = new TextDecoder(), P = 0, sn = 1, cn = 2, F = 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 {
1927
+ 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 {
1923
1928
  chunks = [];
1924
1929
  encode(e) {
1925
1930
  return this.chunks = [], this._encode(e), this._concat();
1926
1931
  }
1927
1932
  _encode(e) {
1928
1933
  if (e == null) {
1929
- this.chunks.push(new Uint8Array([mn]));
1934
+ this.chunks.push(new Uint8Array([pn]));
1930
1935
  return;
1931
1936
  }
1932
1937
  if (typeof e == "boolean") {
1933
- this.chunks.push(new Uint8Array([e ? pn : fn]));
1938
+ this.chunks.push(new Uint8Array([e ? fn : dn]));
1934
1939
  return;
1935
1940
  }
1936
1941
  if (typeof e == "number") {
@@ -1968,28 +1973,28 @@ var N = new TextEncoder(), on = new TextDecoder(), P = 0, sn = 1, cn = 2, F = 3,
1968
1973
  new DataView(t).setFloat64(0, e, !1), this.chunks.push(new Uint8Array(t));
1969
1974
  return;
1970
1975
  }
1971
- e >= 0 ? this._encodeHead(P, e) : this._encodeHead(sn, -1 - e);
1976
+ e >= 0 ? this._encodeHead(F, e) : this._encodeHead(on, -1 - e);
1972
1977
  }
1973
1978
  _float64Header() {
1974
1979
  return new Uint8Array([251]);
1975
1980
  }
1976
1981
  _encodeString(e) {
1977
- let t = N.encode(e);
1978
- this._encodeHead(F, t.length), this.chunks.push(t);
1982
+ let t = P.encode(e);
1983
+ this._encodeHead(I, t.length), this.chunks.push(t);
1979
1984
  }
1980
1985
  _encodeByteString(e) {
1981
- this._encodeHead(cn, e.length), this.chunks.push(e);
1986
+ this._encodeHead(sn, e.length), this.chunks.push(e);
1982
1987
  }
1983
1988
  _encodeArray(e) {
1984
- this._encodeHead(ln, e.length);
1989
+ this._encodeHead(cn, e.length);
1985
1990
  for (let t of e) this._encode(t);
1986
1991
  }
1987
1992
  _encodeMapFromAnyEntries(e) {
1988
1993
  let t = e.map(([e, t]) => {
1989
1994
  let n;
1990
- if (typeof e == "number" && Number.isInteger(e)) n = this._encodeHeadBytes(P, e);
1995
+ if (typeof e == "number" && Number.isInteger(e)) n = this._encodeHeadBytes(F, e);
1991
1996
  else {
1992
- let t = N.encode(String(e)), r = this._encodeHeadBytes(F, t.length);
1997
+ let t = P.encode(String(e)), r = this._encodeHeadBytes(I, t.length);
1993
1998
  n = this._concatPair(r, t);
1994
1999
  }
1995
2000
  return {
@@ -1998,27 +2003,27 @@ var N = new TextEncoder(), on = new TextDecoder(), P = 0, sn = 1, cn = 2, F = 3,
1998
2003
  value: t
1999
2004
  };
2000
2005
  });
2001
- t.sort((e, t) => this._compareBytes(e.keyEncoded, t.keyEncoded)), this._encodeHead(un, t.length);
2006
+ t.sort((e, t) => this._compareBytes(e.keyEncoded, t.keyEncoded)), this._encodeHead(ln, t.length);
2002
2007
  for (let { key: e, value: n } of t) {
2003
- if (typeof e == "number" && Number.isInteger(e)) this._encodeHead(P, e);
2008
+ if (typeof e == "number" && Number.isInteger(e)) this._encodeHead(F, e);
2004
2009
  else {
2005
- let t = N.encode(String(e));
2006
- this._encodeHead(F, t.length), this.chunks.push(t);
2010
+ let t = P.encode(String(e));
2011
+ this._encodeHead(I, t.length), this.chunks.push(t);
2007
2012
  }
2008
2013
  this._encode(n);
2009
2014
  }
2010
2015
  }
2011
2016
  _encodeMapFromEntries(e) {
2012
2017
  let t = e.map(([e, t]) => {
2013
- let n = N.encode(e), r = this._encodeHeadBytes(F, n.length);
2018
+ let n = P.encode(e), r = this._encodeHeadBytes(I, n.length);
2014
2019
  return {
2015
2020
  keyBytes: n,
2016
2021
  keyEncoded: this._concatPair(r, n),
2017
2022
  value: t
2018
2023
  };
2019
2024
  });
2020
- t.sort((e, t) => this._compareBytes(e.keyEncoded, t.keyEncoded)), this._encodeHead(un, t.length);
2021
- for (let { keyBytes: e, value: n } of t) this._encodeHead(F, e.length), this.chunks.push(e), this._encode(n);
2025
+ t.sort((e, t) => this._compareBytes(e.keyEncoded, t.keyEncoded)), this._encodeHead(ln, t.length);
2026
+ for (let { keyBytes: e, value: n } of t) this._encodeHead(I, e.length), this.chunks.push(e), this._encode(n);
2022
2027
  }
2023
2028
  _compareBytes(e, t) {
2024
2029
  let n = Math.min(e.length, t.length);
@@ -2038,24 +2043,24 @@ var N = new TextEncoder(), on = new TextDecoder(), P = 0, sn = 1, cn = 2, F = 3,
2038
2043
  _encodeHeadBytes(e, t) {
2039
2044
  let n = e << 5;
2040
2045
  if (t <= 23) return new Uint8Array([n | t]);
2041
- if (t <= 255) return new Uint8Array([n | hn, t]);
2046
+ if (t <= 255) return new Uint8Array([n | mn, t]);
2042
2047
  if (t <= 65535) {
2043
2048
  let e = /* @__PURE__ */ new ArrayBuffer(3), r = new DataView(e);
2044
- return r.setUint8(0, n | gn), r.setUint16(1, t, !1), new Uint8Array(e);
2049
+ return r.setUint8(0, n | hn), r.setUint16(1, t, !1), new Uint8Array(e);
2045
2050
  }
2046
2051
  if (t <= 4294967295) {
2047
2052
  let e = /* @__PURE__ */ new ArrayBuffer(5), r = new DataView(e);
2048
- return r.setUint8(0, n | _n), r.setUint32(1, t, !1), new Uint8Array(e);
2053
+ return r.setUint8(0, n | gn), r.setUint32(1, t, !1), new Uint8Array(e);
2049
2054
  }
2050
2055
  let r = /* @__PURE__ */ new ArrayBuffer(9), i = new DataView(r);
2051
- return i.setUint8(0, n | vn), i.setBigUint64(1, BigInt(t), !1), new Uint8Array(r);
2056
+ return i.setUint8(0, n | _n), i.setBigUint64(1, BigInt(t), !1), new Uint8Array(r);
2052
2057
  }
2053
2058
  _concat() {
2054
2059
  let e = this.chunks.reduce((e, t) => e + t.length, 0), t = new Uint8Array(e), n = 0;
2055
2060
  for (let e of this.chunks) t.set(e, n), n += e.length;
2056
2061
  return t;
2057
2062
  }
2058
- }, xn = class {
2063
+ }, bn = class {
2059
2064
  data;
2060
2065
  offset = 0;
2061
2066
  decode(e) {
@@ -2064,34 +2069,34 @@ var N = new TextEncoder(), on = new TextDecoder(), P = 0, sn = 1, cn = 2, F = 3,
2064
2069
  _decode() {
2065
2070
  let e = this._readByte(), t = e >> 5 & 7, n = e & 31;
2066
2071
  switch (t) {
2067
- case P: return this._decodeUint(n);
2068
- case sn: return -1 - this._decodeUint(n);
2069
- case cn: {
2072
+ case F: return this._decodeUint(n);
2073
+ case on: return -1 - this._decodeUint(n);
2074
+ case sn: {
2070
2075
  let e = this._decodeUint(n);
2071
2076
  return this._readBytes(e);
2072
2077
  }
2073
- case F: {
2078
+ case I: {
2074
2079
  let e = this._decodeUint(n), t = this._readBytes(e);
2075
- return on.decode(t);
2080
+ return an.decode(t);
2076
2081
  }
2077
- case ln: {
2082
+ case cn: {
2078
2083
  let e = this._decodeUint(n), t = [];
2079
2084
  for (let n = 0; n < e; n++) t.push(this._decode());
2080
2085
  return t;
2081
2086
  }
2082
- case un: {
2083
- let e = this._decodeUint(n), t = {};
2087
+ case ln: {
2088
+ let e = this._decodeUint(n), t = Object.create(null);
2084
2089
  for (let n = 0; n < e; n++) {
2085
2090
  let e = this._decode();
2086
2091
  t[String(e)] = this._decode();
2087
2092
  }
2088
2093
  return t;
2089
2094
  }
2090
- case dn:
2095
+ case un:
2091
2096
  if (n === 20) return !1;
2092
2097
  if (n === 21) return !0;
2093
2098
  if (n === 22) return null;
2094
- if (n === yn) {
2099
+ if (n === vn) {
2095
2100
  let e = this._readBytes(8);
2096
2101
  return new DataView(e.buffer, e.byteOffset, 8).getFloat64(0, !1);
2097
2102
  }
@@ -2101,16 +2106,16 @@ var N = new TextEncoder(), on = new TextDecoder(), P = 0, sn = 1, cn = 2, F = 3,
2101
2106
  }
2102
2107
  _decodeUint(e) {
2103
2108
  if (e <= 23) return e;
2104
- if (e === hn) return this._readByte();
2105
- if (e === gn) {
2109
+ if (e === mn) return this._readByte();
2110
+ if (e === hn) {
2106
2111
  let e = this._readBytes(2);
2107
2112
  return new DataView(e.buffer, e.byteOffset, 2).getUint16(0, !1);
2108
2113
  }
2109
- if (e === _n) {
2114
+ if (e === gn) {
2110
2115
  let e = this._readBytes(4);
2111
2116
  return new DataView(e.buffer, e.byteOffset, 4).getUint32(0, !1);
2112
2117
  }
2113
- if (e === vn) {
2118
+ if (e === _n) {
2114
2119
  let e = this._readBytes(8);
2115
2120
  return Number(new DataView(e.buffer, e.byteOffset, 8).getBigUint64(0, !1));
2116
2121
  }
@@ -2126,16 +2131,16 @@ var N = new TextEncoder(), on = new TextDecoder(), P = 0, sn = 1, cn = 2, F = 3,
2126
2131
  return this.offset += e, t;
2127
2132
  }
2128
2133
  };
2129
- function Sn(e) {
2130
- return new bn().encode(e);
2134
+ function xn(e) {
2135
+ return new yn().encode(e);
2131
2136
  }
2132
- function Cn(e) {
2133
- return new xn().decode(e);
2137
+ function Sn(e) {
2138
+ return new bn().decode(e);
2134
2139
  }
2135
2140
  //#endregion
2136
2141
  //#region src/envelopeCbor.ts
2137
- var wn = "application/7h3-cbor";
2138
- function Tn(e) {
2142
+ var Cn = "application/7h3-cbor";
2143
+ function wn(e) {
2139
2144
  let t = /* @__PURE__ */ new Map();
2140
2145
  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);
2141
2146
  let n = /* @__PURE__ */ new Map();
@@ -2147,10 +2152,21 @@ function Tn(e) {
2147
2152
  let e = /* @__PURE__ */ new Map();
2148
2153
  e.set(1, i.alg), e.set(2, i.keyId), e.set(3, i.value), r.set(3, e);
2149
2154
  }
2150
- return Sn(r);
2155
+ return xn(r);
2156
+ }
2157
+ function L(e, t) {
2158
+ if (typeof e != "string") throw Error(`decodeEnvelopeCbor: ${t} must be a string`);
2159
+ return e;
2160
+ }
2161
+ function Tn(e, t) {
2162
+ if (e !== void 0) return L(e, t);
2163
+ }
2164
+ function En(e, t) {
2165
+ if (typeof e != "number" || !Number.isFinite(e)) throw Error(`decodeEnvelopeCbor: ${t} must be a finite number`);
2166
+ return e;
2151
2167
  }
2152
- function En(e) {
2153
- let t = Cn(e);
2168
+ function Dn(e) {
2169
+ let t = Sn(e);
2154
2170
  if (!t || typeof t != "object" || Array.isArray(t)) throw Error("decodeEnvelopeCbor: expected a map at top level");
2155
2171
  let n = t, r = n[1];
2156
2172
  if (!r || typeof r != "object" || Array.isArray(r)) throw Error("decodeEnvelopeCbor: missing header map (key 1)");
@@ -2158,38 +2174,42 @@ function En(e) {
2158
2174
  if (!a || typeof a != "object" || Array.isArray(a)) throw Error("decodeEnvelopeCbor: missing body map (key 2)");
2159
2175
  let o = a, s = {
2160
2176
  header: {
2161
- version: i[1],
2162
- messageId: i[2],
2163
- timestampMs: i[3],
2164
- ttlMs: i[4],
2165
- sender: i[5],
2166
- nonce: i[7]
2177
+ version: L(i[1], "header.version"),
2178
+ messageId: L(i[2], "header.messageId"),
2179
+ timestampMs: En(i[3], "header.timestampMs"),
2180
+ ttlMs: En(i[4], "header.ttlMs"),
2181
+ sender: L(i[5], "header.sender"),
2182
+ nonce: L(i[7], "header.nonce")
2167
2183
  },
2168
2184
  body: {
2169
- intent: o[1],
2170
- content: o[2]
2171
- }
2172
- };
2173
- 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]);
2174
- let c = n[3];
2175
- if (c != null) {
2176
- if (typeof c != "object" || Array.isArray(c)) throw Error("decodeEnvelopeCbor: expected signature map at key 3");
2177
- let e = c;
2185
+ intent: L(o[1], "body.intent"),
2186
+ content: L(o[2], "body.content")
2187
+ }
2188
+ }, c = Tn(i[6], "header.recipient");
2189
+ c !== void 0 && (s.header.recipient = c);
2190
+ let l = Tn(o[3], "body.capability");
2191
+ l !== void 0 && (s.body.capability = l);
2192
+ let u = Tn(o[4], "body.correlationId");
2193
+ u !== void 0 && (s.body.correlationId = u);
2194
+ let d = n[3];
2195
+ if (d != null) {
2196
+ if (typeof d != "object" || Array.isArray(d)) throw Error("decodeEnvelopeCbor: expected signature map at key 3");
2197
+ let e = d;
2178
2198
  s.signature = {
2179
- alg: e[1],
2180
- keyId: e[2],
2181
- value: e[3]
2199
+ alg: L(e[1], "signature.alg"),
2200
+ keyId: L(e[2], "signature.keyId"),
2201
+ value: L(e[3], "signature.value")
2182
2202
  };
2183
2203
  }
2184
2204
  return s;
2185
2205
  }
2186
2206
  //#endregion
2187
2207
  //#region src/httpBinding.ts
2188
- var Dn = "x-7h3-envelope";
2189
- async function On(e, t, n) {
2208
+ var On = "x-7h3-envelope";
2209
+ async function kn(e, t, n) {
2190
2210
  let r = t.headerName ?? "x-7h3-envelope", i = (Array.isArray(e["content-type"]) ? e["content-type"][0] : e["content-type"]) ?? "", a;
2191
2211
  if (i.includes("7h3-cbor") && n instanceof Uint8Array) try {
2192
- a = En(n);
2212
+ a = Dn(n);
2193
2213
  } catch (e) {
2194
2214
  return {
2195
2215
  ok: !1,
@@ -2219,7 +2239,7 @@ async function On(e, t, n) {
2219
2239
  detail: "missing required fields"
2220
2240
  };
2221
2241
  if (t.strictTtl ?? !0) {
2222
- let e = w(a).filter((e) => e.level === "error");
2242
+ let e = E(a).filter((e) => e.level === "error");
2223
2243
  if (e.length > 0) return {
2224
2244
  ok: !1,
2225
2245
  reason: "ttl-expired",
@@ -2234,18 +2254,18 @@ async function On(e, t, n) {
2234
2254
  reason: "unknown-sender",
2235
2255
  detail: o
2236
2256
  };
2237
- if (!await C(a, e)) return {
2257
+ if (!await T(a, e)) return {
2238
2258
  ok: !1,
2239
2259
  reason: "invalid-signature"
2240
2260
  };
2241
2261
  } else if (s === "HS256") {
2242
- let e = await t.keyRegistry.getSharedSecret?.(a.signature.keyId);
2262
+ let e = await t.keyRegistry.getSharedSecret?.(a.signature.keyId, o);
2243
2263
  if (!e) return {
2244
2264
  ok: !1,
2245
2265
  reason: "unknown-sender",
2246
2266
  detail: a.signature.keyId
2247
2267
  };
2248
- if (!await he(a, e)) return {
2268
+ if (!await C(a, e)) return {
2249
2269
  ok: !1,
2250
2270
  reason: "invalid-signature"
2251
2271
  };
@@ -2259,24 +2279,24 @@ async function On(e, t, n) {
2259
2279
  envelope: a
2260
2280
  };
2261
2281
  }
2262
- async function kn(e, t, n) {
2263
- let r = await S(e, t);
2282
+ async function An(e, t, n) {
2283
+ let r = await w(e, t);
2264
2284
  if (n?.format === "cbor") {
2265
- let e = Tn(r);
2285
+ let e = wn(r);
2266
2286
  return {
2267
- headers: { "content-type": wn },
2287
+ headers: { "content-type": Cn },
2268
2288
  body: e
2269
2289
  };
2270
2290
  }
2271
2291
  return { headers: { [n?.headerName ?? "x-7h3-envelope"]: JSON.stringify(r) } };
2272
2292
  }
2273
- async function An(e, t, n, r) {
2274
- let i = await x(e, t, n);
2293
+ async function jn(e, t, n, r) {
2294
+ let i = await S(e, t, n);
2275
2295
  return { headers: { [r?.headerName ?? "x-7h3-envelope"]: JSON.stringify(i) } };
2276
2296
  }
2277
- function jn(e) {
2297
+ function Mn(e) {
2278
2298
  return async function(t, n, r) {
2279
- let i = await On(t.headers, e);
2299
+ let i = await kn(t.headers, e);
2280
2300
  if (!i.ok) {
2281
2301
  n.status(401).json({
2282
2302
  error: "7h3: request verification failed",
@@ -2288,13 +2308,13 @@ function jn(e) {
2288
2308
  t["7h3Envelope"] = i.envelope, r();
2289
2309
  };
2290
2310
  }
2291
- async function Mn(e, t, n, r) {
2292
- let { headers: i } = await kn(t, n, r), a = new Headers(e.headers);
2311
+ async function Nn(e, t, n, r) {
2312
+ let { headers: i } = await An(t, n, r), a = new Headers(e.headers);
2293
2313
  for (let [e, t] of Object.entries(i)) a.set(e, t);
2294
2314
  return new Request(e, { headers: a });
2295
2315
  }
2296
- async function Nn(e, t) {
2297
- return Mn(e, T({
2316
+ async function Pn(e, t) {
2317
+ return Nn(e, D({
2298
2318
  sender: t.sender,
2299
2319
  recipient: t.recipient,
2300
2320
  ttlMs: t.ttlMs ?? 6e4,
@@ -2304,49 +2324,68 @@ async function Nn(e, t) {
2304
2324
  }
2305
2325
  //#endregion
2306
2326
  //#region src/webhookBinding.ts
2307
- var I = "x-7h3-sig", L = "x-7h3-ts", Pn = 3e5;
2308
- function R(e, t) {
2327
+ var R = "x-7h3-sig", z = "x-7h3-ts", Fn = 3e5, In = class {
2328
+ seen = /* @__PURE__ */ new Map();
2329
+ maxEntries;
2330
+ constructor(e = 1e4) {
2331
+ this.maxEntries = e;
2332
+ }
2333
+ prune(e) {
2334
+ for (let [t, n] of this.seen) n <= e && this.seen.delete(t);
2335
+ }
2336
+ consume(e, t, n) {
2337
+ this.prune(n);
2338
+ let r = this.seen.get(e);
2339
+ if (r !== void 0 && r > n) return !1;
2340
+ if (this.seen.size >= this.maxEntries) {
2341
+ let e = this.seen.keys().next().value;
2342
+ e !== void 0 && this.seen.delete(e);
2343
+ }
2344
+ return this.seen.set(e, t), !0;
2345
+ }
2346
+ };
2347
+ function B(e, t) {
2309
2348
  return `${e}.${t}`;
2310
2349
  }
2311
- async function Fn(e, t) {
2312
- let n = typeof e == "string" ? e : new TextDecoder().decode(e), r = Date.now(), i = await y(R(r, n), t.privateKey);
2350
+ async function Ln(e, t) {
2351
+ let n = typeof e == "string" ? e : new TextDecoder().decode(e), r = Date.now(), i = await b(B(r, n), t.privateKey);
2313
2352
  return {
2314
- [I]: i,
2315
- [L]: String(r)
2353
+ [R]: i,
2354
+ [z]: String(r)
2316
2355
  };
2317
2356
  }
2318
- async function In(e, t) {
2319
- let n = typeof e == "string" ? e : new TextDecoder().decode(e), r = Date.now(), i = await fe(R(r, n), t.secret);
2357
+ async function Rn(e, t) {
2358
+ let n = typeof e == "string" ? e : new TextDecoder().decode(e), r = Date.now(), i = await de(B(r, n), t.secret);
2320
2359
  return {
2321
- [I]: i,
2322
- [L]: String(r)
2360
+ [R]: i,
2361
+ [z]: String(r)
2323
2362
  };
2324
2363
  }
2325
- async function Ln(e, t, n) {
2326
- let r = typeof e == "string" ? e : new TextDecoder().decode(e), i = t[I], a = t[L];
2364
+ async function zn(e, t, n) {
2365
+ let r = typeof e == "string" ? e : new TextDecoder().decode(e), i = t[R], a = t[z];
2327
2366
  if (!i || !a) return !1;
2328
2367
  let o = Number(a);
2329
2368
  if (!Number.isFinite(o)) return !1;
2330
- let s = n.maxAgeMs ?? 3e5;
2331
- return Date.now() - o > s ? !1 : b(R(o, r), i, n.publicKey);
2369
+ let s = n.maxAgeMs ?? 3e5, c = Date.now();
2370
+ return !(c - o > s || !await x(B(o, r), i, n.publicKey) || n.replayCache && !await n.replayCache.consume(i, o + s, c));
2332
2371
  }
2333
- async function Rn(e, t, n) {
2334
- let r = typeof e == "string" ? e : new TextDecoder().decode(e), i = t[I], a = t[L];
2372
+ async function Bn(e, t, n) {
2373
+ let r = typeof e == "string" ? e : new TextDecoder().decode(e), i = t[R], a = t[z];
2335
2374
  if (!i || !a) return !1;
2336
2375
  let o = Number(a);
2337
2376
  if (!Number.isFinite(o)) return !1;
2338
- let s = n.maxAgeMs ?? 3e5;
2339
- return Date.now() - o > s ? !1 : pe(R(o, r), i, n.secret);
2377
+ let s = n.maxAgeMs ?? 3e5, c = Date.now();
2378
+ return !(c - o > s || !await fe(B(o, r), i, n.secret) || n.replayCache && !await n.replayCache.consume(i, o + s, c));
2340
2379
  }
2341
- async function zn(e, t, n) {
2342
- if (!await Ln(e, t, n)) throw Error("7h3: webhook signature verification failed");
2380
+ async function Vn(e, t, n) {
2381
+ if (!await zn(e, t, n)) throw Error("7h3: webhook signature verification failed");
2343
2382
  return JSON.parse(e);
2344
2383
  }
2345
2384
  //#endregion
2346
2385
  //#region src/queueBinding.ts
2347
- async function Bn(e, t) {
2386
+ async function Hn(e, t) {
2348
2387
  let n = t.ttlMs ?? 36e5, r = typeof e == "string" ? e : JSON.stringify(e), i = {
2349
- envelope: await S(T({
2388
+ envelope: await w(D({
2350
2389
  sender: t.sender,
2351
2390
  recipient: t.recipient,
2352
2391
  intent: "TASK",
@@ -2357,7 +2396,7 @@ async function Bn(e, t) {
2357
2396
  };
2358
2397
  return JSON.stringify(i);
2359
2398
  }
2360
- async function Vn(e, t) {
2399
+ async function Un(e, t) {
2361
2400
  let n;
2362
2401
  try {
2363
2402
  n = JSON.parse(e);
@@ -2365,16 +2404,25 @@ async function Vn(e, t) {
2365
2404
  throw Error("Queue message is not valid JSON");
2366
2405
  }
2367
2406
  if (!n.envelope || typeof n.envelope != "object") throw Error("Queue message missing envelope");
2368
- if (!await C(n.envelope, t.publicKey)) throw Error("Queue message signature verification failed");
2407
+ let r = t.nowMs ?? Date.now();
2408
+ if (t.strictTtl ?? !0) {
2409
+ let e = E(n.envelope, r).filter((e) => e.level === "error");
2410
+ if (e.length > 0) throw Error(`Queue message failed validation: ${e.map((e) => e.message).join("; ")}`);
2411
+ }
2412
+ if (!await T(n.envelope, t.publicKey)) throw Error("Queue message signature verification failed");
2413
+ if (t.replayCache) {
2414
+ let e = await t.replayCache.consume(n.envelope, r);
2415
+ if (!e.ok) throw Error(e.reason ?? "Queue message replay detected");
2416
+ }
2369
2417
  return {
2370
2418
  payload: n.payload,
2371
2419
  envelope: n.envelope
2372
2420
  };
2373
2421
  }
2374
- async function Hn(e, t) {
2422
+ async function Wn(e, t) {
2375
2423
  return Promise.all(e.map(async (e) => {
2376
2424
  try {
2377
- let { payload: n, envelope: r } = await Vn(e, t);
2425
+ let { payload: n, envelope: r } = await Un(e, t);
2378
2426
  return {
2379
2427
  ok: !0,
2380
2428
  payload: n,
@@ -2391,87 +2439,87 @@ async function Hn(e, t) {
2391
2439
  }
2392
2440
  //#endregion
2393
2441
  //#region src/stream.ts
2394
- var Un = "x-7h3-stream", z = new TextEncoder();
2395
- function B() {
2442
+ var Gn = "x-7h3-stream", V = new TextEncoder();
2443
+ function H() {
2396
2444
  if (typeof crypto > "u" || !crypto.subtle) throw Error("Web Crypto API is not available in this runtime");
2397
2445
  return crypto.subtle;
2398
2446
  }
2399
- function Wn() {
2447
+ function Kn() {
2400
2448
  return globalThis.Buffer;
2401
2449
  }
2402
- function V(e) {
2403
- let t = Wn();
2450
+ function U(e) {
2451
+ let t = Kn();
2404
2452
  return (t ? t.from(e).toString("base64") : btoa(String.fromCharCode(...e))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
2405
2453
  }
2406
- function H(e) {
2407
- let t = e.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(e.length / 4) * 4, "="), n = Wn();
2454
+ function W(e) {
2455
+ let t = e.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(e.length / 4) * 4, "="), n = Kn();
2408
2456
  if (n) return new Uint8Array(n.from(t, "base64"));
2409
2457
  let r = atob(t), i = new Uint8Array(r.length);
2410
2458
  for (let e = 0; e < r.length; e++) i[e] = r.charCodeAt(e);
2411
2459
  return i;
2412
2460
  }
2413
- function U(e) {
2461
+ function G(e) {
2414
2462
  return e.buffer.slice(e.byteOffset, e.byteOffset + e.byteLength);
2415
2463
  }
2416
- function Gn() {
2417
- let e = new Uint8Array(16);
2418
- return crypto.getRandomValues(e), V(e);
2464
+ function qn() {
2465
+ let e = /* @__PURE__ */ new Uint8Array(16);
2466
+ return crypto.getRandomValues(e), U(e);
2419
2467
  }
2420
- var W = /* @__PURE__ */ new Map(), Kn = 128;
2421
- function qn(e, t) {
2422
- let n = `${e}:${t}`, r = W.get(n);
2468
+ var K = /* @__PURE__ */ new Map(), Jn = 128;
2469
+ function Yn(e, t) {
2470
+ let n = `${e}:${t}`, r = K.get(n);
2423
2471
  if (r) return r;
2424
- W.size >= Kn && W.clear();
2425
- let i = B(), a = H(e), o = (async () => {
2426
- let e = await i.importKey("raw", U(a), "HKDF", !1, ["deriveBits"]), n = await i.deriveBits({
2472
+ K.size >= Jn && K.clear();
2473
+ let i = H(), a = W(e), o = (async () => {
2474
+ let e = await i.importKey("raw", G(a), "HKDF", !1, ["deriveBits"]), n = await i.deriveBits({
2427
2475
  name: "HKDF",
2428
2476
  hash: "SHA-256",
2429
- salt: z.encode(t),
2430
- info: z.encode("7h3-stream/1")
2477
+ salt: V.encode(t),
2478
+ info: V.encode("7h3-stream/1")
2431
2479
  }, e, 256);
2432
2480
  return i.importKey("raw", n, {
2433
2481
  name: "HMAC",
2434
2482
  hash: "SHA-256"
2435
2483
  }, !1, ["sign"]);
2436
2484
  })();
2437
- return o.catch(() => W.delete(n)), W.set(n, o), o;
2485
+ return o.catch(() => K.delete(n)), K.set(n, o), o;
2438
2486
  }
2439
- var G = /* @__PURE__ */ new Map(), Jn = 64;
2440
- function Yn(e) {
2441
- let t = G.get(e);
2487
+ var q = /* @__PURE__ */ new Map(), Xn = 64;
2488
+ function Zn(e) {
2489
+ let t = q.get(e);
2442
2490
  if (t) return t;
2443
- G.size >= Jn && G.clear();
2444
- let n = B().importKey("pkcs8", U(H(e)), { name: "Ed25519" }, !1, ["sign"]).catch((t) => {
2445
- throw G.delete(e), t;
2491
+ q.size >= Xn && q.clear();
2492
+ let n = H().importKey("pkcs8", G(W(e)), { name: "Ed25519" }, !1, ["sign"]).catch((t) => {
2493
+ throw q.delete(e), t;
2446
2494
  });
2447
- return G.set(e, n), n;
2495
+ return q.set(e, n), n;
2448
2496
  }
2449
- var K = /* @__PURE__ */ new Map(), Xn = 64;
2450
- function Zn(e) {
2451
- let t = K.get(e);
2497
+ var J = /* @__PURE__ */ new Map(), Qn = 64;
2498
+ function $n(e) {
2499
+ let t = J.get(e);
2452
2500
  if (t) return t;
2453
- K.size >= Xn && K.clear();
2454
- let n = B().importKey("spki", U(H(e)), { name: "Ed25519" }, !1, ["verify"]).catch((t) => {
2455
- throw K.delete(e), t;
2501
+ J.size >= Qn && J.clear();
2502
+ let n = H().importKey("spki", G(W(e)), { name: "Ed25519" }, !1, ["verify"]).catch((t) => {
2503
+ throw J.delete(e), t;
2456
2504
  });
2457
- return K.set(e, n), n;
2505
+ return J.set(e, n), n;
2458
2506
  }
2459
- function Qn(e) {
2507
+ function er(e) {
2460
2508
  let t = e.map((e) => `${e.i}:${e.d}`);
2461
- return z.encode(t.join("\n"));
2509
+ return V.encode(t.join("\n"));
2462
2510
  }
2463
- async function $n(e) {
2464
- let t = await B().digest("SHA-256", U(e));
2511
+ async function tr(e) {
2512
+ let t = await H().digest("SHA-256", G(e));
2465
2513
  return new Uint8Array(t);
2466
2514
  }
2467
- var q = class {
2515
+ var nr = class {
2468
2516
  opts;
2469
2517
  seq = 0;
2470
2518
  accum = [];
2471
2519
  hmacKeyPromise = null;
2472
2520
  constructor(e) {
2473
2521
  this.opts = {
2474
- nonce: e.nonce ?? Gn(),
2522
+ nonce: e.nonce ?? qn(),
2475
2523
  keyId: e.keyId ?? "stream-key",
2476
2524
  ...e
2477
2525
  };
@@ -2480,11 +2528,11 @@ var q = class {
2480
2528
  return this.opts.nonce;
2481
2529
  }
2482
2530
  getHmacKey() {
2483
- return this.hmacKeyPromise ||= qn(this.opts.privateKey, this.opts.nonce), this.hmacKeyPromise;
2531
+ return this.hmacKeyPromise ||= Yn(this.opts.privateKey, this.opts.nonce), this.hmacKeyPromise;
2484
2532
  }
2485
2533
  async computeChunkHmac(e, t) {
2486
- let n = B(), r = await this.getHmacKey(), i = `${this.opts.nonce}:${e}:${t}`, a = await n.sign("HMAC", r, z.encode(i));
2487
- return V(new Uint8Array(a));
2534
+ let n = H(), r = await this.getHmacKey(), i = `${this.opts.nonce}:${e}:${t}`, a = await n.sign("HMAC", r, V.encode(i));
2535
+ return U(new Uint8Array(a));
2488
2536
  }
2489
2537
  async writeChunk(e) {
2490
2538
  let t = this.seq++, n = await this.computeChunkHmac(t, e);
@@ -2499,17 +2547,17 @@ var q = class {
2499
2547
  };
2500
2548
  }
2501
2549
  async finalize() {
2502
- 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;
2550
+ let e = H(), t = await Zn(this.opts.privateKey), n = await tr(er(this.accum)), r = await e.sign("Ed25519", t, G(n)), i = U(new Uint8Array(r)), a = this.seq;
2503
2551
  return {
2504
2552
  i: a,
2505
2553
  d: "",
2506
- h: await this.computeChunkHmac(a, V(n)),
2554
+ h: await this.computeChunkHmac(a, U(n)),
2507
2555
  f: !0,
2508
2556
  sig: i,
2509
2557
  kid: this.opts.keyId
2510
2558
  };
2511
2559
  }
2512
- }, er = class {
2560
+ }, rr = class {
2513
2561
  opts;
2514
2562
  expectedSeq = 0;
2515
2563
  accum = [];
@@ -2530,7 +2578,7 @@ var q = class {
2530
2578
  } : e.i === this.expectedSeq ? (this.expectedSeq++, this.accum.push({
2531
2579
  i: e.i,
2532
2580
  d: e.d
2533
- }), this.totalBytes += z.encode(e.d).length, { ok: !0 }) : {
2581
+ }), this.totalBytes += V.encode(e.d).length, { ok: !0 }) : {
2534
2582
  ok: !1,
2535
2583
  reason: `sequence error: expected ${this.expectedSeq}, got ${e.i}`
2536
2584
  };
@@ -2544,17 +2592,17 @@ var q = class {
2544
2592
  ok: !1,
2545
2593
  reason: "missing signature on final chunk"
2546
2594
  };
2547
- let t = B(), n;
2595
+ let t = H(), n;
2548
2596
  try {
2549
- n = await Zn(this.opts.publicKey);
2597
+ n = await $n(this.opts.publicKey);
2550
2598
  } catch {
2551
2599
  return {
2552
2600
  ok: !1,
2553
2601
  reason: "invalid public key"
2554
2602
  };
2555
2603
  }
2556
- let r = await $n(Qn(this.accum)), i = H(e.sig);
2557
- return await t.verify("Ed25519", n, U(i), U(r)) ? {
2604
+ let r = await tr(er(this.accum)), i = W(e.sig);
2605
+ return await t.verify("Ed25519", n, G(i), G(r)) ? {
2558
2606
  ok: !0,
2559
2607
  totalBytes: this.totalBytes,
2560
2608
  chunkCount: this.accum.length
@@ -2564,20 +2612,20 @@ var q = class {
2564
2612
  };
2565
2613
  }
2566
2614
  };
2567
- function tr(e) {
2568
- return new q(e);
2615
+ function ir(e) {
2616
+ return new nr(e);
2569
2617
  }
2570
- function nr(e) {
2571
- return new er(e);
2618
+ function ar(e) {
2619
+ return new rr(e);
2572
2620
  }
2573
- async function rr(e, t) {
2574
- let n = new q(t), r = [];
2621
+ async function or(e, t) {
2622
+ let n = new nr(t), r = [];
2575
2623
  if (Array.isArray(e)) for (let t of e) r.push(await n.writeChunk(t));
2576
2624
  else for await (let t of e) r.push(await n.writeChunk(t));
2577
2625
  return r.push(await n.finalize()), r;
2578
2626
  }
2579
- async function ir(e, t) {
2580
- let n = new er(t), r = e.slice(0, -1), i = e[e.length - 1];
2627
+ async function sr(e, t) {
2628
+ let n = new rr(t), r = e.slice(0, -1), i = e[e.length - 1];
2581
2629
  if (e.length === 0) return {
2582
2630
  ok: !1,
2583
2631
  reason: "empty chunk array — missing final frame"
@@ -2603,10 +2651,10 @@ async function ir(e, t) {
2603
2651
  }
2604
2652
  return n.finalize(i);
2605
2653
  }
2606
- function ar(e) {
2654
+ function cr(e) {
2607
2655
  return JSON.stringify(e);
2608
2656
  }
2609
- function or(e) {
2657
+ function lr(e) {
2610
2658
  let t;
2611
2659
  try {
2612
2660
  t = JSON.parse(e);
@@ -2633,7 +2681,7 @@ function or(e) {
2633
2681
  }
2634
2682
  //#endregion
2635
2683
  //#region src/wsBinding.ts
2636
- function sr(e, t) {
2684
+ function ur(e, t) {
2637
2685
  let n = 0, r = [], i = [];
2638
2686
  function a(e, n) {
2639
2687
  t.onVerifyFail?.(e, n);
@@ -2657,15 +2705,22 @@ function sr(e, t) {
2657
2705
  a(/* @__PURE__ */ Error(`unknown sender: ${o}`), n);
2658
2706
  return;
2659
2707
  }
2660
- if (!await C(i, s).catch(() => !1)) {
2708
+ if (!await T(i, s).catch(() => !1)) {
2661
2709
  a(/* @__PURE__ */ Error("invalid signature"), n);
2662
2710
  return;
2663
2711
  }
2664
- let c = w(i);
2712
+ let c = E(i);
2665
2713
  if (c.some((e) => e.level === "error")) {
2666
2714
  a(/* @__PURE__ */ Error(`envelope invalid: ${c.map((e) => e.message).join("; ")}`), n);
2667
2715
  return;
2668
2716
  }
2717
+ if (t.replayCache) {
2718
+ let e = await t.replayCache.consume(i);
2719
+ if (!e.ok) {
2720
+ a(Error(e.reason ?? "replay detected"), n);
2721
+ return;
2722
+ }
2723
+ }
2669
2724
  let l = i.body.content;
2670
2725
  try {
2671
2726
  l = JSON.parse(i.body.content);
@@ -2679,7 +2734,7 @@ function sr(e, t) {
2679
2734
  return n;
2680
2735
  },
2681
2736
  async send(r) {
2682
- let i = typeof r == "string" ? r : JSON.stringify(r), a = await S(T({
2737
+ let i = typeof r == "string" ? r : JSON.stringify(r), a = await w(D({
2683
2738
  sender: t.sender,
2684
2739
  recipient: t.recipient,
2685
2740
  ttlMs: t.ttlMs ?? 3e4,
@@ -2697,28 +2752,28 @@ function sr(e, t) {
2697
2752
  }
2698
2753
  };
2699
2754
  }
2700
- function cr(e, t) {
2701
- let n = new q(t), r = async (t) => {
2755
+ function dr(e, t) {
2756
+ let n = new nr(t), r = async (t) => {
2702
2757
  let r = typeof t.data == "string" ? t.data : t.data.toString("utf8"), i = await n.writeChunk(r);
2703
- e.send(ar(i));
2758
+ e.send(cr(i));
2704
2759
  }, i = async () => {
2705
2760
  e.removeEventListener("message", r), e.removeEventListener("close", i);
2706
2761
  let t = await n.finalize();
2707
- e.send(ar(t));
2762
+ e.send(cr(t));
2708
2763
  };
2709
2764
  return e.addEventListener("message", r), e.addEventListener("close", i), n;
2710
2765
  }
2711
- function lr(e, t) {
2766
+ function fr(e, t) {
2712
2767
  return new Promise((n, r) => {
2713
2768
  let i = [], a = async (e) => {
2714
2769
  let a = typeof e.data == "string" ? e.data : e.data.toString("utf8"), o;
2715
2770
  try {
2716
- o = or(a);
2771
+ o = lr(a);
2717
2772
  } catch (e) {
2718
2773
  s(), r(e);
2719
2774
  return;
2720
2775
  }
2721
- i.push(o), o.f && (s(), n(await ir(i, t)));
2776
+ i.push(o), o.f && (s(), n(await sr(i, t)));
2722
2777
  }, o = () => {
2723
2778
  s(), n({
2724
2779
  ok: !1,
@@ -2733,9 +2788,9 @@ function lr(e, t) {
2733
2788
  }
2734
2789
  //#endregion
2735
2790
  //#region src/grpcBinding.ts
2736
- var ur = "7h3-envelope-bin";
2737
- async function dr(e) {
2738
- let t = await S(T({
2791
+ var pr = "7h3-envelope-bin";
2792
+ async function mr(e) {
2793
+ let t = await w(D({
2739
2794
  sender: e.sender,
2740
2795
  recipient: e.recipient,
2741
2796
  ttlMs: e.ttlMs ?? 6e4,
@@ -2744,7 +2799,7 @@ async function dr(e) {
2744
2799
  }), e.privateKey);
2745
2800
  return { [e.metadataKey ?? "7h3-envelope-bin"]: JSON.stringify(t) };
2746
2801
  }
2747
- async function fr(e, t) {
2802
+ async function hr(e, t) {
2748
2803
  let n = e[t.metadataKey ?? "7h3-envelope-bin"], r = Array.isArray(n) ? n[0] : n instanceof Uint8Array ? new TextDecoder().decode(n) : n;
2749
2804
  if (!r) return {
2750
2805
  ok: !1,
@@ -2761,7 +2816,7 @@ async function fr(e, t) {
2761
2816
  message: "7h3: malformed envelope metadata"
2762
2817
  };
2763
2818
  }
2764
- if (t.strictTtl !== !1 && w(i).some((e) => e.level === "error")) return {
2819
+ if (t.strictTtl !== !1 && E(i).some((e) => e.level === "error")) return {
2765
2820
  ok: !1,
2766
2821
  code: 4,
2767
2822
  message: "7h3: envelope expired or invalid"
@@ -2779,19 +2834,19 @@ async function fr(e, t) {
2779
2834
  code: 16,
2780
2835
  message: `7h3: unknown sender ${a}`
2781
2836
  };
2782
- if (!await C(i, e)) return {
2837
+ if (!await T(i, e)) return {
2783
2838
  ok: !1,
2784
2839
  code: 16,
2785
2840
  message: "7h3: invalid signature"
2786
2841
  };
2787
2842
  } else if (o === "HS256") {
2788
- let e = await t.keyRegistry.getSharedSecret?.(i.signature.keyId);
2843
+ let e = await t.keyRegistry.getSharedSecret?.(i.signature.keyId, a);
2789
2844
  if (!e) return {
2790
2845
  ok: !1,
2791
2846
  code: 16,
2792
2847
  message: "7h3: unknown key"
2793
2848
  };
2794
- if (!await he(i, e)) return {
2849
+ if (!await C(i, e)) return {
2795
2850
  ok: !1,
2796
2851
  code: 16,
2797
2852
  message: "7h3: invalid signature"
@@ -2806,39 +2861,39 @@ async function fr(e, t) {
2806
2861
  envelope: i
2807
2862
  };
2808
2863
  }
2809
- function pr(e, t) {
2864
+ function gr(e, t) {
2810
2865
  return async (n) => {
2811
- let r = await fr(n.metadata, t);
2866
+ let r = await hr(n.metadata, t);
2812
2867
  if (!r.ok) throw Object.assign(Error(r.message), { code: r.code });
2813
2868
  return n["7h3Envelope"] = r.envelope, e(n);
2814
2869
  };
2815
2870
  }
2816
2871
  //#endregion
2817
2872
  //#region src/keyInfra.ts
2818
- function mr(e) {
2873
+ function _r(e) {
2819
2874
  return JSON.stringify(e);
2820
2875
  }
2821
- function hr(e) {
2876
+ function vr(e) {
2822
2877
  let t = JSON.parse(e);
2823
2878
  if (t.version !== "7h3/0.1") throw Error(`unsupported version: ${t.version}`);
2824
2879
  return t;
2825
2880
  }
2826
- async function gr(e, t) {
2881
+ async function yr(e, t) {
2827
2882
  let n = e.replace(/\/$/, "") + "/.well-known/7h3-keys", r = new AbortController(), i = t?.timeout ? setTimeout(() => r.abort(), t.timeout) : void 0;
2828
2883
  try {
2829
2884
  let e = await fetch(n, { signal: r.signal });
2830
2885
  if (!e.ok) throw Error(`HTTP ${e.status} from ${n}`);
2831
- return hr(await e.text());
2886
+ return vr(await e.text());
2832
2887
  } finally {
2833
2888
  i !== void 0 && clearTimeout(i);
2834
2889
  }
2835
2890
  }
2836
- function _r(e) {
2891
+ function br(e) {
2837
2892
  let t = /* @__PURE__ */ new Map(), n = e?.cacheMs ?? 6e4, r = e?.timeout ?? 5e3;
2838
2893
  async function i(e) {
2839
2894
  let i = Date.now(), a = t.get(e);
2840
2895
  if (a && a.expiresAt > i) return a.doc;
2841
- let o = await gr(e, { timeout: r });
2896
+ let o = await yr(e, { timeout: r });
2842
2897
  return t.set(e, {
2843
2898
  doc: o,
2844
2899
  expiresAt: i + n
@@ -2855,7 +2910,7 @@ function _r(e) {
2855
2910
  }
2856
2911
  } };
2857
2912
  }
2858
- var vr = class {
2913
+ var xr = class {
2859
2914
  maxAgeMs;
2860
2915
  overlapMs;
2861
2916
  keys = [];
@@ -2873,8 +2928,8 @@ var vr = class {
2873
2928
  let e = Date.now(), t = this.getCurrentKey();
2874
2929
  if (t && e - t.createdAt < this.maxAgeMs - this.overlapMs) return null;
2875
2930
  t && !t.expiresAt && (t.expiresAt = e + this.overlapMs);
2876
- let { publicKey: n, privateKey: r } = await me(), i = {
2877
- id: `key-${e}-${v(4)}`,
2931
+ let { publicKey: n, privateKey: r } = await pe(), i = {
2932
+ id: `key-${e}-${y(4)}`,
2878
2933
  publicKey: n,
2879
2934
  privateKey: r,
2880
2935
  createdAt: e
@@ -2902,10 +2957,10 @@ var vr = class {
2902
2957
  toKeyRegistry() {
2903
2958
  return { getPublicKey: async (e) => {
2904
2959
  let t = Date.now();
2905
- return this.keys.find((n) => n.id === e && (!n.expiresAt || n.expiresAt > t))?.publicKey ?? this.getCurrentKey()?.publicKey ?? null;
2960
+ return this.keys.find((n) => n.id === e && (!n.expiresAt || n.expiresAt > t))?.publicKey ?? null;
2906
2961
  } };
2907
2962
  }
2908
- }, yr = class {
2963
+ }, Sr = class {
2909
2964
  revoked = /* @__PURE__ */ new Map();
2910
2965
  revoke(e, t) {
2911
2966
  this.revoked.set(e, {
@@ -2930,11 +2985,15 @@ var vr = class {
2930
2985
  wrapRegistry(e) {
2931
2986
  return {
2932
2987
  getPublicKey: async (t) => this.isRevoked(t) ? null : e.getPublicKey(t),
2933
- getSharedSecret: e.getSharedSecret?.bind(e)
2988
+ getSharedSecret: e.getSharedSecret ? async (t, n) => this.isRevoked(t) || this.isRevoked(n) ? null : e.getSharedSecret(t, n) : void 0
2934
2989
  };
2935
2990
  }
2936
- }, br = class {
2991
+ }, Cr = class {
2937
2992
  windows = /* @__PURE__ */ new Map();
2993
+ maxKeys;
2994
+ constructor(e = {}) {
2995
+ this.maxKeys = e.maxKeys ?? 5e4;
2996
+ }
2938
2997
  check(e, t, n = Date.now()) {
2939
2998
  let r = n - t.windowMs, i = (this.windows.get(e) ?? []).filter((e) => e > r), a = i.length, o = a < t.requests;
2940
2999
  return {
@@ -2945,7 +3004,13 @@ var vr = class {
2945
3004
  }
2946
3005
  consume(e, t, n = Date.now()) {
2947
3006
  let r = n - t.windowMs, i = (this.windows.get(e) ?? []).filter((e) => e > r), a = i.length < t.requests;
2948
- return a && (i.push(n), this.windows.set(e, i)), {
3007
+ if (a && i.push(n), i.length > 0) for (this.windows.delete(e), this.windows.set(e, i); this.windows.size > this.maxKeys;) {
3008
+ let e = this.windows.keys().next().value;
3009
+ if (e === void 0) break;
3010
+ this.windows.delete(e);
3011
+ }
3012
+ else this.windows.delete(e);
3013
+ return {
2949
3014
  allowed: a,
2950
3015
  remaining: Math.max(0, t.requests - i.length),
2951
3016
  resetMs: i.length > 0 ? Math.max(0, i[0] + t.windowMs - n) : 0
@@ -2957,10 +3022,10 @@ var vr = class {
2957
3022
  clear() {
2958
3023
  this.windows.clear();
2959
3024
  }
2960
- }, xr = new br();
3025
+ }, wr = new Cr();
2961
3026
  //#endregion
2962
3027
  //#region src/routePolicy.ts
2963
- function J(e, t) {
3028
+ function Tr(e, t) {
2964
3029
  let n = "^", r = 0;
2965
3030
  for (; r < e.length;) {
2966
3031
  let t = e[r];
@@ -2968,18 +3033,18 @@ function J(e, t) {
2968
3033
  }
2969
3034
  return n += "$", new RegExp(n).test(t);
2970
3035
  }
2971
- function Sr(e, t) {
2972
- for (let n of e) if (J(n.path, t)) return n;
3036
+ function Er(e, t) {
3037
+ for (let n of e) if (Tr(n.path, t)) return n;
2973
3038
  return null;
2974
3039
  }
2975
- function Cr(e, t) {
2976
- return !e.allowedSenders || e.allowedSenders.length === 0 ? !0 : e.allowedSenders.includes(t);
3040
+ function Dr(e, t) {
3041
+ return !e.allowedSenders || e.allowedSenders.length === 0 || e.allowedSenders.includes(t);
2977
3042
  }
2978
3043
  //#endregion
2979
3044
  //#region src/signedResponse.ts
2980
- var wr = "x-7h3-response";
2981
- async function Tr(e, t) {
2982
- let n = await S(T({
3045
+ var Or = "x-7h3-response";
3046
+ async function kr(e, t) {
3047
+ let n = await w(D({
2983
3048
  sender: t.sender,
2984
3049
  recipient: t.recipient,
2985
3050
  intent: "RESULT",
@@ -2987,10 +3052,10 @@ async function Tr(e, t) {
2987
3052
  correlationId: t.correlationId,
2988
3053
  ttlMs: t.ttlMs ?? 6e4
2989
3054
  }), t.privateKey);
2990
- return { headers: { [wr]: JSON.stringify(n) } };
3055
+ return { headers: { [Or]: JSON.stringify(n) } };
2991
3056
  }
2992
- async function Er(e, t, n) {
2993
- let r = t[wr], i = Array.isArray(r) ? r[0] : r;
3057
+ async function Ar(e, t, n) {
3058
+ let r = t[Or], i = Array.isArray(r) ? r[0] : r;
2994
3059
  if (!i) return {
2995
3060
  ok: !1,
2996
3061
  reason: "missing-header"
@@ -3009,7 +3074,7 @@ async function Er(e, t, n) {
3009
3074
  ok: !1,
3010
3075
  reason: "ttl-expired",
3011
3076
  envelope: a
3012
- } : await C(a, n.publicKey) ? a.body.content === e ? {
3077
+ } : await T(a, n.publicKey) ? a.body.content === e ? {
3013
3078
  ok: !0,
3014
3079
  envelope: a
3015
3080
  } : {
@@ -3024,21 +3089,21 @@ async function Er(e, t, n) {
3024
3089
  }
3025
3090
  //#endregion
3026
3091
  //#region src/telemetry.ts
3027
- function Y(e) {
3092
+ function jr(e) {
3028
3093
  return !e || Object.keys(e).length === 0 ? "__default__" : Object.entries(e).sort(([e], [t]) => e.localeCompare(t)).map(([e, t]) => `${e}=${t}`).join(",");
3029
3094
  }
3030
- function Dr(e) {
3095
+ function Mr(e) {
3031
3096
  return !e || Object.keys(e).length === 0 ? "" : `{${Object.entries(e).sort(([e], [t]) => e.localeCompare(t)).map(([e, t]) => `${e}="${t}"`).join(",")}}`;
3032
3097
  }
3033
- var X = class {
3098
+ var Y = class {
3034
3099
  counts = /* @__PURE__ */ new Map();
3035
3100
  labelSets = /* @__PURE__ */ new Map();
3036
3101
  increment(e) {
3037
- let t = Y(e);
3102
+ let t = jr(e);
3038
3103
  this.counts.set(t, (this.counts.get(t) ?? 0) + 1), this.labelSets.has(t) || this.labelSets.set(t, e);
3039
3104
  }
3040
3105
  value(e) {
3041
- return this.counts.get(Y(e)) ?? 0;
3106
+ return this.counts.get(jr(e)) ?? 0;
3042
3107
  }
3043
3108
  entries() {
3044
3109
  let e = [];
@@ -3048,7 +3113,7 @@ var X = class {
3048
3113
  });
3049
3114
  return e;
3050
3115
  }
3051
- }, Or = class {
3116
+ }, Nr = class {
3052
3117
  bucketBounds;
3053
3118
  states = /* @__PURE__ */ new Map();
3054
3119
  labelSets = /* @__PURE__ */ new Map();
@@ -3068,7 +3133,7 @@ var X = class {
3068
3133
  this.bucketBounds = [...e].sort((e, t) => e - t);
3069
3134
  }
3070
3135
  observe(e, t) {
3071
- let n = Y(t);
3136
+ let n = jr(t);
3072
3137
  this.states.has(n) || (this.states.set(n, {
3073
3138
  count: 0,
3074
3139
  sum: 0,
@@ -3078,7 +3143,7 @@ var X = class {
3078
3143
  r.count++, r.sum += e, r.observations.push(e);
3079
3144
  }
3080
3145
  snapshot(e) {
3081
- let t = Y(e), n = this.states.get(t) ?? {
3146
+ let t = jr(e), n = this.states.get(t) ?? {
3082
3147
  count: 0,
3083
3148
  sum: 0,
3084
3149
  observations: []
@@ -3104,9 +3169,9 @@ var X = class {
3104
3169
  getBounds() {
3105
3170
  return [...this.bucketBounds];
3106
3171
  }
3107
- }, kr = class {
3108
- verifications_total = new X();
3109
- verification_duration_ms = new Or([
3172
+ }, Pr = class {
3173
+ verifications_total = new Y();
3174
+ verification_duration_ms = new Nr([
3110
3175
  .1,
3111
3176
  .5,
3112
3177
  1,
@@ -3115,20 +3180,20 @@ var X = class {
3115
3180
  50,
3116
3181
  100
3117
3182
  ]);
3118
- rate_limit_hits_total = new X();
3119
- sender_denials_total = new X();
3120
- replay_detections_total = new X();
3121
- audit_entries_total = new X();
3122
- active_connections = new X();
3123
- }, Z = new kr();
3124
- function Ar(e, t = "7h3") {
3183
+ rate_limit_hits_total = new Y();
3184
+ sender_denials_total = new Y();
3185
+ replay_detections_total = new Y();
3186
+ audit_entries_total = new Y();
3187
+ active_connections = new Y();
3188
+ }, X = new Pr();
3189
+ function Fr(e, t = "7h3") {
3125
3190
  let n = [];
3126
3191
  function r(e, r, i) {
3127
3192
  let a = `${t}_${e}`;
3128
3193
  n.push(`# HELP ${a} ${r}`), n.push(`# TYPE ${a} counter`);
3129
3194
  let o = i.entries();
3130
3195
  if (o.length === 0) n.push(`${a} 0`);
3131
- 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}`);
3196
+ else for (let { labels: e, value: t } of o) e && Object.keys(e).length > 0 ? n.push(`${a}${Mr(e)} ${t}`) : n.push(`${a} ${t}`);
3132
3197
  }
3133
3198
  function i(e, r, i) {
3134
3199
  let a = `${t}_${e}`;
@@ -3138,7 +3203,7 @@ function Ar(e, t = "7h3") {
3138
3203
  for (let e of i.getBounds()) n.push(`${a}_bucket{le="${e}"} 0`);
3139
3204
  n.push(`${a}_bucket{le="+Inf"} 0`), n.push(`${a}_sum 0`), n.push(`${a}_count 0`);
3140
3205
  } else for (let { labels: e, snapshot: t } of o) {
3141
- let r = e && Object.keys(e).length > 0 ? Dr(e) : "";
3206
+ let r = e && Object.keys(e).length > 0 ? Mr(e) : "";
3142
3207
  for (let [e, i] of Object.entries(t.buckets)) {
3143
3208
  if (e === "+Inf") continue;
3144
3209
  let t = r ? r.slice(0, -1) + `,le="${e}"}` : `{le="${e}"}`;
@@ -3150,29 +3215,29 @@ function Ar(e, t = "7h3") {
3150
3215
  }
3151
3216
  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";
3152
3217
  }
3153
- function jr(e = "/metrics", t = Z, n = "7h3") {
3218
+ function Ir(e = "/metrics", t = X, n = "7h3") {
3154
3219
  return (r, i, a) => {
3155
3220
  if (r.url === e && (r.method === "GET" || r.method === void 0)) {
3156
- let e = Ar(t, n);
3221
+ let e = Fr(t, n);
3157
3222
  i.writeHead(200, { "content-type": "text/plain; version=0.0.4; charset=utf-8" }), i.end(e);
3158
3223
  } else a();
3159
3224
  };
3160
3225
  }
3161
3226
  //#endregion
3162
3227
  //#region src/capability.ts
3163
- var Mr = "x-7h3-capability";
3164
- function Nr(e) {
3228
+ var Lr = "x-7h3-capability";
3229
+ function Rr(e) {
3165
3230
  let t = [];
3166
3231
  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(",")}}`;
3167
3232
  }
3168
- function Q(e) {
3233
+ function Z(e) {
3169
3234
  let t = [];
3170
3235
  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)}`);
3171
- let n = `[${e.scopes.map(Nr).join(",")}]`;
3236
+ let n = `[${e.scopes.map(Rr).join(",")}]`;
3172
3237
  return t.push(`"scopes":${n}`), t.push(`"subject":${JSON.stringify(e.subject)}`), t.push(`"version":${JSON.stringify(e.version)}`), `{${t.join(",")}}`;
3173
3238
  }
3174
- async function Pr(e) {
3175
- let t = Date.now(), n = `cap-${t}-${v(6)}`, r = e.keyId ?? `${e.issuerId}-key`, i = e.maxDelegations ?? 0, a = {
3239
+ async function zr(e) {
3240
+ let t = Date.now(), n = `cap-${t}-${y(6)}`, r = e.keyId ?? `${e.issuerId}-key`, i = e.maxDelegations ?? 0, a = {
3176
3241
  id: n,
3177
3242
  version: "7h3-cap/1",
3178
3243
  issuer: e.issuerId,
@@ -3183,35 +3248,49 @@ async function Pr(e) {
3183
3248
  delegationDepth: 0,
3184
3249
  maxDelegations: i,
3185
3250
  keyId: r
3186
- }, o = await y(Q(a), e.issuerPrivateKey);
3251
+ }, o = await b(Z(a), e.issuerPrivateKey);
3187
3252
  return {
3188
3253
  ...a,
3189
3254
  signature: o
3190
3255
  };
3191
3256
  }
3192
- function Fr(e, t) {
3193
- if (!J(t.pathGlob, e.pathGlob)) return !1;
3257
+ function Br(e, t) {
3258
+ return e === t || t === "*" && e !== "**";
3259
+ }
3260
+ function Vr(e, t) {
3261
+ let n = e.split("/"), r = t.split("/"), i = 0;
3262
+ for (let e of r) {
3263
+ if (e === "**") return !0;
3264
+ if (i >= n.length) return !1;
3265
+ let t = n[i];
3266
+ if (t === "**" || !Br(t, e)) return !1;
3267
+ i += 1;
3268
+ }
3269
+ return i === n.length;
3270
+ }
3271
+ function Hr(e, t) {
3272
+ if (!Vr(e.pathGlob, t.pathGlob)) return !1;
3194
3273
  if (t.methods !== void 0) {
3195
3274
  if (e.methods === void 0) return !1;
3196
3275
  for (let n of e.methods) if (!t.methods.includes(n)) return !1;
3197
3276
  }
3198
3277
  return !0;
3199
3278
  }
3200
- function Ir(e, t) {
3201
- for (let n of e) if (!t.some((e) => Fr(n, e))) return !1;
3279
+ function Ur(e, t) {
3280
+ for (let n of e) if (!t.some((e) => Hr(n, e))) return !1;
3202
3281
  return !0;
3203
3282
  }
3204
- async function Lr(e) {
3283
+ async function Wr(e) {
3205
3284
  let { parentToken: t, delegatorId: n, newSubject: r } = e;
3206
3285
  if (n !== t.subject) throw Error(`delegatorId '${n}' does not match parentToken.subject '${t.subject}'`);
3207
3286
  let i = Date.now();
3208
3287
  if (i >= t.expiresAt) throw Error("Parent token is expired");
3209
3288
  if (t.maxDelegations !== void 0 && t.maxDelegations <= 0) throw Error("Parent token does not allow further delegation (maxDelegations=0)");
3210
3289
  let a = e.scopes ?? t.scopes;
3211
- if (!Ir(a, t.scopes)) throw Error("Delegated scopes exceed parent token scopes");
3290
+ if (!Ur(a, t.scopes)) throw Error("Delegated scopes exceed parent token scopes");
3212
3291
  let o = t.expiresAt - i;
3213
3292
  if (e.ttlMs > o) throw Error(`Delegated ttlMs (${e.ttlMs}) exceeds parent token remaining TTL (${o})`);
3214
- let s = `cap-${i}-${v(6)}`, c = e.keyId ?? `${n}-key`, l = t.maxDelegations === void 0 ? void 0 : t.maxDelegations - 1, u = {
3293
+ let s = `cap-${i}-${y(6)}`, c = e.keyId ?? `${n}-key`, l = t.maxDelegations === void 0 ? void 0 : t.maxDelegations - 1, u = {
3215
3294
  id: s,
3216
3295
  version: "7h3-cap/1",
3217
3296
  issuer: n,
@@ -3223,18 +3302,18 @@ async function Lr(e) {
3223
3302
  parentTokenId: t.id,
3224
3303
  maxDelegations: l,
3225
3304
  keyId: c
3226
- }, d = await y(Q(u), e.delegatorPrivateKey);
3305
+ }, d = await b(Z(u), e.delegatorPrivateKey);
3227
3306
  return {
3228
3307
  ...u,
3229
3308
  signature: d
3230
3309
  };
3231
3310
  }
3232
- async function Rr(e, t, n) {
3311
+ async function Gr(e, t, n) {
3233
3312
  if ((n?.now ?? Date.now()) >= e.expiresAt) return !1;
3234
3313
  let { signature: r, ...i } = e;
3235
- return b(Q(i), r, t);
3314
+ return x(Z(i), r, t);
3236
3315
  }
3237
- async function zr(e, t, n) {
3316
+ async function Kr(e, t, n) {
3238
3317
  if (e.length === 0) return {
3239
3318
  ok: !1,
3240
3319
  reason: "empty-chain"
@@ -3260,6 +3339,18 @@ async function zr(e, t, n) {
3260
3339
  ok: !1,
3261
3340
  reason: `chain-broken: token[${n}].delegationDepth ${i.delegationDepth} !== ${t.delegationDepth + 1}`
3262
3341
  };
3342
+ if (t.maxDelegations !== void 0 && t.maxDelegations <= 0) return {
3343
+ ok: !1,
3344
+ reason: `chain-broken: token[${n - 1}] does not permit further delegation (maxDelegations=0)`
3345
+ };
3346
+ if (i.expiresAt > t.expiresAt) return {
3347
+ ok: !1,
3348
+ reason: `chain-broken: token[${n}].expiresAt exceeds token[${n - 1}].expiresAt`
3349
+ };
3350
+ if (!Ur(i.scopes, t.scopes)) return {
3351
+ ok: !1,
3352
+ reason: `chain-broken: token[${n}].scopes exceed token[${n - 1}].scopes`
3353
+ };
3263
3354
  }
3264
3355
  if (r >= i.expiresAt) return {
3265
3356
  ok: !1,
@@ -3271,13 +3362,13 @@ async function zr(e, t, n) {
3271
3362
  reason: `no-public-key-for-issuer:${i.issuer}`
3272
3363
  };
3273
3364
  let { signature: o, ...s } = i;
3274
- if (!await b(Q(s), o, a)) return {
3365
+ if (!await x(Z(s), o, a)) return {
3275
3366
  ok: !1,
3276
3367
  reason: `invalid-signature-at-index:${n}`
3277
3368
  };
3278
3369
  }
3279
3370
  let i = e[e.length - 1];
3280
- return n?.requiredPathGlob !== void 0 && !Br(i, n.requiredPathGlob, n.requiredMethod) ? {
3371
+ return n?.requiredPathGlob !== void 0 && !qr(i, n.requiredPathGlob, n.requiredMethod) ? {
3281
3372
  ok: !1,
3282
3373
  reason: "leaf-token-does-not-cover-required-scope"
3283
3374
  } : {
@@ -3286,85 +3377,151 @@ async function zr(e, t, n) {
3286
3377
  chain: e
3287
3378
  };
3288
3379
  }
3289
- function Br(e, t, n) {
3290
- 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;
3380
+ function qr(e, t, n) {
3381
+ for (let r of e.scopes) if (Tr(r.pathGlob, t) && (r.methods === void 0 || n !== void 0 && r.methods.includes(n.toUpperCase()))) return !0;
3291
3382
  return !1;
3292
3383
  }
3293
- function Vr(e) {
3384
+ function Jr(e) {
3294
3385
  return JSON.stringify(e);
3295
3386
  }
3296
- function Hr(e) {
3387
+ function Yr(e) {
3297
3388
  return JSON.parse(e);
3298
3389
  }
3299
3390
  //#endregion
3300
3391
  //#region src/gateway.ts
3301
- var Ur = class {
3392
+ function Xr(e) {
3393
+ if (!e.startsWith("/")) return null;
3394
+ let t = e;
3395
+ for (let e = 0; e < 5; e++) {
3396
+ let e;
3397
+ try {
3398
+ e = decodeURIComponent(t);
3399
+ } catch {
3400
+ return null;
3401
+ }
3402
+ if (e === t) break;
3403
+ t = e;
3404
+ }
3405
+ if (/%[0-9a-fA-F]{2}/.test(t) || /[\x00-\x1f]/.test(t)) return null;
3406
+ let n = t.split("/"), r = [];
3407
+ for (let e of n) if (!(e === "" || e === ".")) {
3408
+ if (e === "..") {
3409
+ if (r.length === 0) return null;
3410
+ r.pop();
3411
+ continue;
3412
+ }
3413
+ r.push(e);
3414
+ }
3415
+ return "/" + r.join("/");
3416
+ }
3417
+ var Zr = class {
3302
3418
  config;
3303
3419
  rateLimiter;
3304
3420
  constructor(e) {
3305
- this.config = e, this.rateLimiter = new br();
3421
+ this.config = e, this.rateLimiter = new Cr(), !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.");
3422
+ }
3423
+ async checkSenderAndRateLimit(e, t, n, r, i) {
3424
+ if (e && !Dr(e, t)) {
3425
+ let e = performance.now() - i;
3426
+ return X.verifications_total.increment({
3427
+ result: "fail",
3428
+ alg: n,
3429
+ transport: "http"
3430
+ }), X.verification_duration_ms.observe(e), X.sender_denials_total.increment({
3431
+ sender: t,
3432
+ path: r.path
3433
+ }), {
3434
+ ok: !1,
3435
+ status: 403,
3436
+ reason: "sender-denied"
3437
+ };
3438
+ }
3439
+ if (e?.rateLimit && !(this.config.rateLimitStore ? await this.config.rateLimitStore.consume(t, e.rateLimit) : this.rateLimiter.consume(t, e.rateLimit)).allowed) {
3440
+ let e = performance.now() - i;
3441
+ return X.verifications_total.increment({
3442
+ result: "fail",
3443
+ alg: n,
3444
+ transport: "http"
3445
+ }), X.verification_duration_ms.observe(e), X.rate_limit_hits_total.increment({
3446
+ sender: t,
3447
+ path: r.path
3448
+ }), {
3449
+ ok: !1,
3450
+ status: 429,
3451
+ reason: "rate-limited"
3452
+ };
3453
+ }
3454
+ return null;
3306
3455
  }
3307
3456
  async verify(e) {
3308
- let t = performance.now(), n = Sr(this.config.policies ?? [], e.path);
3309
- if (n?.require === "none" || !n && (this.config.defaultPolicy ?? "allow") === "allow") {
3457
+ let t = performance.now(), n = Xr(e.path);
3458
+ if (n === null) return {
3459
+ ok: !1,
3460
+ status: 400,
3461
+ reason: "invalid-path"
3462
+ };
3463
+ let r = Er(this.config.policies ?? [], n);
3464
+ if (r?.require === "none" || !r && (this.config.defaultPolicy ?? "allow") === "allow") {
3310
3465
  let e = performance.now() - t;
3311
- return Z.verifications_total.increment({
3466
+ return X.verifications_total.increment({
3312
3467
  result: "ok",
3313
3468
  alg: "none",
3314
3469
  transport: "http"
3315
- }), Z.verification_duration_ms.observe(e), {
3470
+ }), X.verification_duration_ms.observe(e), {
3316
3471
  ok: !0,
3317
3472
  sender: ""
3318
3473
  };
3319
3474
  }
3320
3475
  if (this.config.capabilityRegistry) {
3321
- let n = e.headers[Mr], r = Array.isArray(n) ? n[0] : n;
3322
- if (r) try {
3323
- let n = await zr(Hr(r), this.config.capabilityRegistry, {
3476
+ let n = e.headers[Lr], i = Array.isArray(n) ? n[0] : n;
3477
+ if (i) try {
3478
+ let n = await Kr(Yr(i), this.config.capabilityRegistry, {
3324
3479
  requiredPathGlob: e.path,
3325
3480
  requiredMethod: e.method
3326
3481
  });
3327
- if (n.ok && Br(n.token, e.path, e.method)) {
3328
- let e = performance.now() - t;
3329
- return Z.verifications_total.increment({
3482
+ if (n.ok && qr(n.token, e.path, e.method)) {
3483
+ let i = n.token.subject, a = await this.checkSenderAndRateLimit(r, i, "ED25519", e, t);
3484
+ if (a) return a;
3485
+ let o = performance.now() - t;
3486
+ return X.verifications_total.increment({
3330
3487
  result: "ok",
3331
3488
  alg: "ED25519",
3332
3489
  transport: "http"
3333
- }), Z.verification_duration_ms.observe(e), {
3490
+ }), X.verification_duration_ms.observe(o), {
3334
3491
  ok: !0,
3335
- sender: n.token.subject
3492
+ sender: i
3336
3493
  };
3337
3494
  }
3338
- let i = performance.now() - t;
3339
- return Z.verifications_total.increment({
3495
+ let a = performance.now() - t;
3496
+ return X.verifications_total.increment({
3340
3497
  result: "fail",
3341
3498
  alg: "none",
3342
3499
  transport: "http"
3343
- }), Z.verification_duration_ms.observe(i), {
3500
+ }), X.verification_duration_ms.observe(a), {
3344
3501
  ok: !1,
3345
3502
  status: 401,
3346
3503
  reason: n.ok ? "capability-scope-mismatch" : n.reason
3347
3504
  };
3348
3505
  } catch {
3349
3506
  let e = performance.now() - t;
3350
- return Z.verifications_total.increment({
3507
+ return X.verifications_total.increment({
3351
3508
  result: "fail",
3352
3509
  alg: "none",
3353
3510
  transport: "http"
3354
- }), Z.verification_duration_ms.observe(e), {
3511
+ }), X.verification_duration_ms.observe(e), {
3355
3512
  ok: !1,
3356
3513
  status: 401,
3357
3514
  reason: "invalid-capability-chain"
3358
3515
  };
3359
3516
  }
3360
3517
  }
3361
- if (!n && (this.config.defaultPolicy ?? "allow") === "deny") {
3518
+ if (!r && (this.config.defaultPolicy ?? "allow") === "deny") {
3362
3519
  let n = performance.now() - t;
3363
- return Z.verifications_total.increment({
3520
+ return X.verifications_total.increment({
3364
3521
  result: "fail",
3365
3522
  alg: "none",
3366
3523
  transport: "http"
3367
- }), Z.verification_duration_ms.observe(n), Z.sender_denials_total.increment({
3524
+ }), X.verification_duration_ms.observe(n), X.sender_denials_total.increment({
3368
3525
  sender: "",
3369
3526
  path: e.path
3370
3527
  }), {
@@ -3373,82 +3530,54 @@ var Ur = class {
3373
3530
  reason: "no-matching-policy"
3374
3531
  };
3375
3532
  }
3376
- let r = await On(e.headers, {
3533
+ let i = await kn(e.headers, {
3377
3534
  keyRegistry: this.config.keyRegistry,
3378
3535
  headerName: this.config.headerName
3379
3536
  });
3380
- if (!r.ok) {
3537
+ if (!i.ok) {
3381
3538
  let e = performance.now() - t;
3382
- return Z.verifications_total.increment({
3539
+ return X.verifications_total.increment({
3383
3540
  result: "fail",
3384
3541
  alg: "none",
3385
3542
  transport: "http"
3386
- }), Z.verification_duration_ms.observe(e), {
3543
+ }), X.verification_duration_ms.observe(e), {
3387
3544
  ok: !1,
3388
3545
  status: 401,
3389
- reason: r.reason
3546
+ reason: i.reason
3390
3547
  };
3391
3548
  }
3392
- let i = r.envelope, a = i.header.sender, o = i.header.messageId, s = i.signature?.alg ?? "none";
3393
- if (this.config.replayStore && await this.config.replayStore.check(i.header.nonce, i.header.ttlMs)) return {
3549
+ let a = i.envelope, o = a.header.sender, s = a.header.messageId, c = a.signature?.alg ?? "none";
3550
+ if (this.config.replayStore && await this.config.replayStore.check(a.header.nonce, a.header.ttlMs)) return {
3394
3551
  ok: !1,
3395
3552
  status: 401,
3396
3553
  reason: "replay-detected"
3397
3554
  };
3398
- if (n && n.require !== "any") {
3399
- let e = i.signature?.alg, r = n.require === "ed25519" && e !== "ED25519", a = n.require === "hmac" && e !== "HS256";
3400
- if (r || a) {
3555
+ if (r && r.require !== "any") {
3556
+ let e = a.signature?.alg, n = r.require === "ed25519" && e !== "ED25519", i = r.require === "hmac" && e !== "HS256";
3557
+ if (n || i) {
3401
3558
  let e = performance.now() - t;
3402
- return Z.verifications_total.increment({
3559
+ return X.verifications_total.increment({
3403
3560
  result: "fail",
3404
- alg: s,
3561
+ alg: c,
3405
3562
  transport: "http"
3406
- }), Z.verification_duration_ms.observe(e), {
3563
+ }), X.verification_duration_ms.observe(e), {
3407
3564
  ok: !1,
3408
3565
  status: 401,
3409
3566
  reason: "invalid-signature"
3410
3567
  };
3411
3568
  }
3412
3569
  }
3413
- if (n && !Cr(n, a)) {
3414
- let n = performance.now() - t;
3415
- return Z.verifications_total.increment({
3416
- result: "fail",
3417
- alg: s,
3418
- transport: "http"
3419
- }), Z.verification_duration_ms.observe(n), Z.sender_denials_total.increment({
3420
- sender: a,
3421
- path: e.path
3422
- }), {
3423
- ok: !1,
3424
- status: 403,
3425
- reason: "sender-denied"
3426
- };
3427
- }
3428
- if (n?.rateLimit && !this.rateLimiter.consume(a, n.rateLimit).allowed) {
3429
- let n = performance.now() - t;
3430
- return Z.verifications_total.increment({
3431
- result: "fail",
3432
- alg: s,
3433
- transport: "http"
3434
- }), Z.verification_duration_ms.observe(n), Z.rate_limit_hits_total.increment({
3435
- sender: a,
3436
- path: e.path
3437
- }), {
3438
- ok: !1,
3439
- status: 429,
3440
- reason: "rate-limited"
3441
- };
3442
- }
3443
- let c = performance.now() - t;
3444
- return Z.verifications_total.increment({
3570
+ let l = await this.checkSenderAndRateLimit(r, o, c, e, t);
3571
+ if (l) return l;
3572
+ let u = performance.now() - t;
3573
+ return X.verifications_total.increment({
3445
3574
  result: "ok",
3446
- alg: s,
3575
+ alg: c,
3447
3576
  transport: "http"
3448
- }), Z.verification_duration_ms.observe(c), {
3577
+ }), X.verification_duration_ms.observe(u), {
3449
3578
  ok: !0,
3450
- sender: a,
3451
- envelopeId: o
3579
+ sender: o,
3580
+ envelopeId: s
3452
3581
  };
3453
3582
  }
3454
3583
  async handle(e) {
@@ -3458,38 +3587,43 @@ var Ur = class {
3458
3587
  headers: { "content-type": "application/json" },
3459
3588
  body: JSON.stringify({ error: t.reason })
3460
3589
  };
3461
- let n = this.config.upstream.replace(/\/$/, "") + e.path, r = {};
3462
- for (let [t, n] of Object.entries(e.headers)) r[t] = Array.isArray(n) ? n[0] : n;
3463
- t.sender && (r["x-7h3-sender"] = t.sender), r["x-7h3-verified"] = "true";
3464
- let i = await fetch(n, {
3590
+ let n = Xr(e.path), r = this.config.upstream.replace(/\/$/, "") + n, i = {};
3591
+ for (let [t, n] of Object.entries(e.headers)) i[t] = Array.isArray(n) ? n[0] : n;
3592
+ t.sender && (i["x-7h3-sender"] = t.sender, i["x-7h3-verified"] = "true");
3593
+ let a = await fetch(r, {
3465
3594
  method: e.method,
3466
- headers: r,
3595
+ headers: i,
3467
3596
  body: e.body
3468
- }), a = await i.text(), o = { "content-type": i.headers.get("content-type") ?? "application/json" };
3597
+ }), o = await a.text(), s = { "content-type": a.headers.get("content-type") ?? "application/json" };
3469
3598
  if (this.config.privateKey !== void 0 && (this.config.signResponses ?? !0) && this.config.sender !== void 0) {
3470
- let e = await Tr(a, {
3599
+ let e = await kr(o, {
3471
3600
  privateKey: this.config.privateKey,
3472
3601
  sender: this.config.sender,
3473
3602
  recipient: t.sender || void 0
3474
3603
  });
3475
- Object.assign(o, e.headers);
3604
+ Object.assign(s, e.headers);
3476
3605
  }
3477
3606
  return {
3478
- status: i.status,
3479
- headers: o,
3480
- body: a
3607
+ status: a.status,
3608
+ headers: s,
3609
+ body: o
3481
3610
  };
3482
3611
  }
3483
3612
  getRateLimiter() {
3484
3613
  return this.rateLimiter;
3485
3614
  }
3486
3615
  };
3487
- function Wr(e) {
3488
- return new Ur(e);
3616
+ function Qr(e) {
3617
+ return new Zr(e);
3618
+ }
3619
+ function $r(e) {
3620
+ if (e.defaultPolicy !== "deny") throw Error("createProductionGateway(): defaultPolicy must be explicitly 'deny'. Unmatched routes must never be forwarded unverified in production.");
3621
+ 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.");
3622
+ return new Zr(e);
3489
3623
  }
3490
3624
  //#endregion
3491
3625
  //#region src/auditLog.ts
3492
- function Gr(e) {
3626
+ function ei(e) {
3493
3627
  let t = [
3494
3628
  `"id":${JSON.stringify(e.id)}`,
3495
3629
  `"timestampMs":${e.timestampMs}`,
@@ -3497,7 +3631,7 @@ function Gr(e) {
3497
3631
  ];
3498
3632
  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(",")}}`;
3499
3633
  }
3500
- var Kr = class {
3634
+ var ti = class {
3501
3635
  entries = [];
3502
3636
  privateKey;
3503
3637
  maxEntries;
@@ -3506,10 +3640,10 @@ var Kr = class {
3506
3640
  }
3507
3641
  async log(e) {
3508
3642
  let t = {
3509
- id: `audit-${Date.now()}-${v(5)}`,
3643
+ id: `audit-${Date.now()}-${y(5)}`,
3510
3644
  timestampMs: Date.now(),
3511
3645
  ...e
3512
- }, n = await y(Gr(t), this.privateKey), r = {
3646
+ }, n = await b(ei(t), this.privateKey), r = {
3513
3647
  ...t,
3514
3648
  entrySignature: n
3515
3649
  };
@@ -3520,7 +3654,7 @@ var Kr = class {
3520
3654
  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;
3521
3655
  }
3522
3656
  async verify(e, t) {
3523
- return b(Gr({
3657
+ return x(ei({
3524
3658
  id: e.id,
3525
3659
  timestampMs: e.timestampMs,
3526
3660
  type: e.type,
@@ -3536,7 +3670,7 @@ var Kr = class {
3536
3670
  size() {
3537
3671
  return this.entries.length;
3538
3672
  }
3539
- }, qr = class {
3673
+ }, ni = class {
3540
3674
  async log(e) {}
3541
3675
  async query(e) {
3542
3676
  return [];
@@ -3548,25 +3682,25 @@ var Kr = class {
3548
3682
  return 0;
3549
3683
  }
3550
3684
  };
3551
- function Jr(e, t) {
3552
- return new Kr(e, t?.maxEntries);
3685
+ function ri(e, t) {
3686
+ return new ti(e, t?.maxEntries);
3553
3687
  }
3554
3688
  //#endregion
3555
3689
  //#region src/otel.ts
3556
- var Yr = null;
3557
- function Xr(e) {
3558
- Yr = e;
3690
+ var ii = null;
3691
+ function ai(e) {
3692
+ ii = e;
3559
3693
  }
3560
- function Zr() {
3561
- if (Yr === null) return null;
3694
+ function oi() {
3695
+ if (ii === null) return null;
3562
3696
  try {
3563
- return Yr.getTracer("7h3/protocol");
3697
+ return ii.getTracer("7h3/protocol");
3564
3698
  } catch {
3565
3699
  return null;
3566
3700
  }
3567
3701
  }
3568
- async function Qr(e, t) {
3569
- let n = Zr();
3702
+ async function si(e, t) {
3703
+ let n = oi();
3570
3704
  if (n === null) return e(null);
3571
3705
  let r = n.startSpan("7h3.verify", t);
3572
3706
  try {
@@ -3577,8 +3711,8 @@ async function Qr(e, t) {
3577
3711
  r.end();
3578
3712
  }
3579
3713
  }
3580
- async function $r(e) {
3581
- let t = Zr();
3714
+ async function ci(e) {
3715
+ let t = oi();
3582
3716
  if (t === null) return e(null);
3583
3717
  let n = t.startSpan("7h3.audit.write");
3584
3718
  try {
@@ -3591,64 +3725,64 @@ async function $r(e) {
3591
3725
  }
3592
3726
  //#endregion
3593
3727
  //#region src/encryption.ts
3594
- function ei(e) {
3728
+ function Q(e) {
3595
3729
  return Buffer.from(e).toString("base64url");
3596
3730
  }
3597
3731
  function $(e) {
3598
3732
  return Buffer.from(e, "base64url");
3599
3733
  }
3600
- var ti = Buffer.from("302e020100300506032b656e04220420", "hex"), ni = Buffer.from("302a300506032b656e032100", "hex");
3601
- function ri(e) {
3734
+ var li = Buffer.from("302e020100300506032b656e04220420", "hex"), ui = Buffer.from("302a300506032b656e032100", "hex");
3735
+ function di(e) {
3602
3736
  let t = $(e);
3603
- return (0, M.createPrivateKey)({
3604
- key: Buffer.concat([ti, t]),
3737
+ return r({
3738
+ key: Buffer.concat([li, t]),
3605
3739
  format: "der",
3606
3740
  type: "pkcs8"
3607
3741
  });
3608
3742
  }
3609
- function ii(e) {
3743
+ function fi(e) {
3610
3744
  let t = $(e);
3611
- return (0, M.createPublicKey)({
3612
- key: Buffer.concat([ni, t]),
3745
+ return i({
3746
+ key: Buffer.concat([ui, t]),
3613
3747
  format: "der",
3614
3748
  type: "spki"
3615
3749
  });
3616
3750
  }
3617
- function ai() {
3618
- let { privateKey: e, publicKey: t } = (0, M.generateKeyPairSync)("x25519"), n = e.export({ format: "jwk" });
3751
+ function pi() {
3752
+ let { privateKey: e, publicKey: t } = o("x25519"), n = e.export({ format: "jwk" });
3619
3753
  return {
3620
3754
  publicKey: t.export({ format: "jwk" }).x,
3621
3755
  privateKey: n.d
3622
3756
  };
3623
3757
  }
3624
- function oi(e, t, n) {
3625
- let r = (0, M.hkdfSync)("sha256", (0, M.diffieHellman)({
3626
- privateKey: ri(e),
3627
- publicKey: ii(t)
3758
+ function mi(e, t, n) {
3759
+ let r = s("sha256", a({
3760
+ privateKey: di(e),
3761
+ publicKey: fi(t)
3628
3762
  }), $(n), Buffer.from("7h3-enc/1", "utf8"), 32);
3629
3763
  return Buffer.from(r);
3630
3764
  }
3631
- function si(e, t) {
3632
- let n = ai(), r = (0, M.randomBytes)(12), i = ei(r), a = oi(n.privateKey, t, i), o = Buffer.from(JSON.stringify(e), "utf8"), s = (0, M.createCipheriv)("chacha20-poly1305", a, r, { authTagLength: 16 }), c = Buffer.concat([s.update(o), s.final()]), l = s.getAuthTag(), u = {
3633
- ephemeralPublic: n.publicKey,
3634
- nonce: i,
3635
- ciphertext: ei(c),
3636
- tag: ei(l)
3765
+ function hi(e, n) {
3766
+ let r = pi(), i = c(12), a = Q(i), o = mi(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 = {
3767
+ ephemeralPublic: r.publicKey,
3768
+ nonce: a,
3769
+ ciphertext: Q(u),
3770
+ tag: Q(d)
3637
3771
  };
3638
3772
  return {
3639
- encryptedContent: ei(Buffer.from(JSON.stringify(u), "utf8")),
3640
- ephemeralPublic: n.publicKey
3773
+ encryptedContent: Q(Buffer.from(JSON.stringify(f), "utf8")),
3774
+ ephemeralPublic: r.publicKey
3641
3775
  };
3642
3776
  }
3643
- function ci(e, t) {
3644
- let n = $(e).toString("utf8"), { ephemeralPublic: r, nonce: i, ciphertext: a, tag: o } = JSON.parse(n), s = oi(t, r, i), c = $(i), l = $(a), u = $(o), d = (0, M.createDecipheriv)("chacha20-poly1305", s, c, { authTagLength: 16 });
3645
- d.setAuthTag(u);
3646
- let f = Buffer.concat([d.update(l), d.final()]);
3647
- return JSON.parse(f.toString("utf8"));
3777
+ function gi(e, t) {
3778
+ let r = $(e).toString("utf8"), { ephemeralPublic: i, nonce: a, ciphertext: o, tag: s } = JSON.parse(r), c = mi(t, i, a), l = $(a), u = $(o), d = $(s), f = n("chacha20-poly1305", c, l, { authTagLength: 16 });
3779
+ f.setAuthTag(d);
3780
+ let p = Buffer.concat([f.update(u), f.final()]);
3781
+ return JSON.parse(p.toString("utf8"));
3648
3782
  }
3649
- async function li(e, t) {
3650
- let { encryptedContent: n } = si(e.body, t.recipientX25519PublicKey);
3651
- return S({
3783
+ async function _i(e, t) {
3784
+ let { encryptedContent: n } = hi(e.body, t.recipientX25519PublicKey);
3785
+ return w({
3652
3786
  header: e.header,
3653
3787
  body: {
3654
3788
  intent: "ENCRYPTED",
@@ -3658,12 +3792,12 @@ async function li(e, t) {
3658
3792
  }
3659
3793
  }, t.senderEd25519PrivateKey);
3660
3794
  }
3661
- async function ui(e, t) {
3662
- if (!await C(e, t.senderEd25519PublicKey)) throw Error("7h3/encryption: Ed25519 signature verification failed");
3795
+ async function vi(e, t) {
3796
+ if (!await T(e, t.senderEd25519PublicKey)) throw Error("7h3/encryption: Ed25519 signature verification failed");
3663
3797
  return {
3664
3798
  envelope: e,
3665
- body: ci(e.body.content, t.recipientX25519PrivateKey)
3799
+ body: gi(e.body.content, t.recipientX25519PrivateKey)
3666
3800
  };
3667
3801
  }
3668
3802
  //#endregion
3669
- export { ot as AgentSession, st as AipAgentAdapter, Mr as CAP_HEADER, wn as CBOR_CONTENT_TYPE, xn as CborDecoder, bn as CborEncoder, zt as ClusterRedisReplayStore, Dn as DEFAULT_HEADER, xe as DEFAULT_MAX_BINARY_ENVELOPE_BYTES, Re as DistributedReplayCache, ur as GRPC_METADATA_KEY, Kr as InMemoryAuditLog, Lt as InMemoryRedisLikeClient, O as InMemoryReplayCache, Wt as InMemoryRevocationStore, ze as InMemoryVerificationMaterialCache, vr as KeyRotationManager, qr as NoopAuditLog, Ur as Protocol7h3Gateway, kr as Protocol7h3Metrics, wr as RESPONSE_HEADER, Rt as RedisReplayStore, yr as RevocationRegistry, it as RollingKeyring, Nt as RuntimePolicyManager, Un as STREAM_HEADER, Xe as SessionTransport, er as SignedStreamReader, q as SignedStreamWriter, X as SimpleCounter, Or as SimpleHistogram, br as SlidingWindowRateLimiter, Pn as WEBHOOK_DEFAULT_TTL_MS, I as WEBHOOK_SIG_HEADER, L as WEBHOOK_TS_HEADER, Tt as bootstrapRuntimePolicyEnforcer, Q as canonicalizeCapabilityToken, g as canonicalizeEnvelope, zn as consumeWebhook, ct as createAipAgentAdapter, et as createAipCapabilities, jt as createAipMcpGatewayRuntime, Mt as createAipMcpGatewayRuntimeWithPolicy, Jr as createAuditLog, an as createCachingKeyRegistry, Ht as createClusterReplayStore, rn as createCompositeKeyRegistry, T as createEnvelope, Wr as createGateway, _r as createHttpKeyRegistry, tn as createHttpMcpClient, en as createHttpMcpHandler, jn as createHttpMiddleware, at as createKeyringSignatureResolver, Yt as createMcpClientCodec, jr as createMetricsMiddleware, wt as createPolicyEnforcer, mt as createRawTaskFromJsonRpc, lt as createRawTaskFromLangChain, dt as createRawTaskFromLlamaIndex, Bt as createRedisReplayStore, Gt as createRedisRevocationStore, Nn as createSignedFetchRequest, Ze as createSignedMessage, tr as createSignedStream, cr as createSignedWebSocketStream, nn as createStaticKeyRegistry, $t as createStdioMcpClient, nr as createStreamVerifier, Cn as decodeCbor, Ge as decodeEnvelope, Je as decodeEnvelopeBatch, Ie as decodeEnvelopeBinary, En as decodeEnvelopeCbor, or as decodeStreamChunk, ci as decryptBody, Lr as delegateCapabilityToken, oi as deriveEncryptionKey, tt as encodeAipCapabilities, Sn as encodeCbor, Ke as encodeEnvelope, qe as encodeEnvelopeBatch, Fe as encodeEnvelopeBinary, Tn as encodeEnvelopeCbor, ar as encodeStreamChunk, si as encryptBody, gr as fetchWellKnownKeys, me as generateEd25519KeypairBase64Url, ai as generateX25519KeyPair, Zr as getOtelTracer, Ft as getRuntimeTuningPreset, xr as globalRateLimiter, Cr as isAllowedSender, Et as isRuntimeMode, Pr as issueCapabilityToken, xt as loadRuntimePolicy, J as matchGlob, Sr as matchPolicy, Z as metrics, rt as negotiateAipCapabilities, ui as openEnvelope, nt as parseAipCapabilities, Hr as parseCapabilityChain, yt as parseRuntimePolicyJson, hr as parseWellKnownKeys, v as randomHex, k as receiveEnvelope, Ye as receiveEnvelopeBatch, lr as receiveSignedWebSocketStream, It as recommendPolicyAdjustments, Ar as renderPrometheusText, li as sealEnvelope, Vr as serializeCapabilityChain, Qt as serveMcpOverStdio, mr as serveWellKnownKeys, Xr as setOtelProvider, y as signCanonicalPayloadEd25519, fe as signCanonicalPayloadHmac, S as signEnvelopeEd25519, x as signEnvelopeHmac, Mn as signFetchRequest, dr as signGrpcCall, kn as signHttpRequest, An 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, w as validateEnvelope, vt as validateRuntimePolicy, b as verifyCanonicalPayloadEd25519, pe as verifyCanonicalPayloadHmac, _e as verifyCanonicalPayloadSignature, zr as verifyCapabilityChain, Rr as verifyCapabilityToken, C as verifyEnvelopeEd25519, he as verifyEnvelopeHmac, ge as verifyEnvelopeSignature, fr as verifyGrpcCall, On as verifyHttpEnvelope, Hn as verifyQueueBatch, Vn as verifyQueueMessage, Er as verifyResponse, ir as verifyStream, Ln as verifyWebhook, Rn as verifyWebhookHmac, $r as withAuditSpan, pr as withGrpcVerification, Kt as withRevocationCheck, Qr as withVerificationSpan, Xt as wrapMcpClient, Jt as wrapMcpServer, sr as wrapWebSocket };
3803
+ export { it as AgentSession, at as AipAgentAdapter, Lr as CAP_HEADER, Cn as CBOR_CONTENT_TYPE, bn as CborDecoder, yn as CborEncoder, Lt as ClusterRedisReplayStore, On as DEFAULT_HEADER, be as DEFAULT_MAX_BINARY_ENVELOPE_BYTES, Le as DistributedReplayCache, pr as GRPC_METADATA_KEY, ti as InMemoryAuditLog, Ft as InMemoryRedisLikeClient, A as InMemoryReplayCache, Ht as InMemoryRevocationStore, Re as InMemoryVerificationMaterialCache, In as InMemoryWebhookReplayCache, xr as KeyRotationManager, ge as MAX_TTL_MS, ni as NoopAuditLog, Zr as Protocol7h3Gateway, Pr as Protocol7h3Metrics, Or as RESPONSE_HEADER, It as RedisReplayStore, Sr as RevocationRegistry, nt as RollingKeyring, jt as RuntimePolicyManager, Gn as STREAM_HEADER, Je as SessionTransport, rr as SignedStreamReader, nr as SignedStreamWriter, Y as SimpleCounter, Nr as SimpleHistogram, Cr as SlidingWindowRateLimiter, Fn as WEBHOOK_DEFAULT_TTL_MS, R as WEBHOOK_SIG_HEADER, z as WEBHOOK_TS_HEADER, N as bootstrapRuntimePolicyEnforcer, Z as canonicalizeCapabilityToken, _ as canonicalizeEnvelope, Vn as consumeWebhook, ot as createAipAgentAdapter, Qe as createAipCapabilities, kt as createAipMcpGatewayRuntime, At as createAipMcpGatewayRuntimeWithPolicy, ri as createAuditLog, rn as createCachingKeyRegistry, Bt as createClusterReplayStore, nn as createCompositeKeyRegistry, D as createEnvelope, Qr as createGateway, br as createHttpKeyRegistry, en as createHttpMcpClient, $t as createHttpMcpHandler, Mn as createHttpMiddleware, rt as createKeyringSignatureResolver, Jt as createMcpClientCodec, Ir as createMetricsMiddleware, St as createPolicyEnforcer, $r as createProductionGateway, ft as createRawTaskFromJsonRpc, st as createRawTaskFromLangChain, lt as createRawTaskFromLlamaIndex, Rt as createRedisReplayStore, Ut as createRedisRevocationStore, Pn as createSignedFetchRequest, Ye as createSignedMessage, ir as createSignedStream, dr as createSignedWebSocketStream, tn as createStaticKeyRegistry, Qt as createStdioMcpClient, ar as createStreamVerifier, Sn as decodeCbor, We as decodeEnvelope, Ke as decodeEnvelopeBatch, Fe as decodeEnvelopeBinary, Dn as decodeEnvelopeCbor, lr as decodeStreamChunk, gi as decryptBody, Wr as delegateCapabilityToken, mi as deriveEncryptionKey, $e as encodeAipCapabilities, xn as encodeCbor, j as encodeEnvelope, Ge as encodeEnvelopeBatch, Pe as encodeEnvelopeBinary, wn as encodeEnvelopeCbor, cr as encodeStreamChunk, hi as encryptBody, yr as fetchWellKnownKeys, pe as generateEd25519KeypairBase64Url, pi as generateX25519KeyPair, oi as getOtelTracer, Nt as getRuntimeTuningPreset, wr as globalRateLimiter, Dr as isAllowedSender, Ct as isRuntimeMode, zr as issueCapabilityToken, yt as loadRuntimePolicy, Tr as matchGlob, Er as matchPolicy, X as metrics, tt as negotiateAipCapabilities, Xr as normalizeGatewayPath, vi as openEnvelope, et as parseAipCapabilities, Yr as parseCapabilityChain, _t as parseRuntimePolicyJson, vr as parseWellKnownKeys, y as randomHex, M as receiveEnvelope, qe as receiveEnvelopeBatch, fr as receiveSignedWebSocketStream, Pt as recommendPolicyAdjustments, Fr as renderPrometheusText, _i as sealEnvelope, Jr as serializeCapabilityChain, Zt as serveMcpOverStdio, _r as serveWellKnownKeys, ai as setOtelProvider, b as signCanonicalPayloadEd25519, de as signCanonicalPayloadHmac, w as signEnvelopeEd25519, S as signEnvelopeHmac, Nn as signFetchRequest, mr as signGrpcCall, An as signHttpRequest, jn as signHttpRequestHmac, Hn as signQueueMessage, kr as signResponse, or as signStream, Ln as signWebhook, Rn as signWebhookHmac, pt as toJsonRpcResponse, ct as toLangChainMessage, ut as toLlamaIndexMessage, qr as tokenMatchesScope, E as validateEnvelope, gt as validateRuntimePolicy, x as verifyCanonicalPayloadEd25519, fe as verifyCanonicalPayloadHmac, he as verifyCanonicalPayloadSignature, Kr as verifyCapabilityChain, Gr as verifyCapabilityToken, T as verifyEnvelopeEd25519, C as verifyEnvelopeHmac, me as verifyEnvelopeSignature, hr as verifyGrpcCall, kn as verifyHttpEnvelope, Wn as verifyQueueBatch, Un as verifyQueueMessage, Ar as verifyResponse, sr as verifyStream, zn as verifyWebhook, Bn as verifyWebhookHmac, ci as withAuditSpan, gr as withGrpcVerification, Wt as withRevocationCheck, si as withVerificationSpan, Yt as wrapMcpClient, qt as wrapMcpServer, ur as wrapWebSocket };