@kehto/paja 0.35.2 → 0.35.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kehto contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -25596,7 +25596,6 @@ var DIGEST_PREFIX = "sha256:";
25596
25596
  var MAX_TRANSFER_CHUNKS = 1e4;
25597
25597
  var MAX_TRANSFER_BYTES = 100 * 1024 * 1024;
25598
25598
  var MAX_ACTIVE_TRANSFERS = 8;
25599
- var MAX_TRANSFER_LIFETIME_MS = 12e4;
25600
25599
  var COMPLETION_MODE_RENDER = "render";
25601
25600
  var DEFAULT_STREAM_IDLE_TIMEOUT_MS = 3e4;
25602
25601
  var DEFAULT_STREAM_PROBE_TIMEOUT_MS = 1e4;
@@ -25623,11 +25622,10 @@ function createCvmProgressController(options) {
25623
25622
  const correlationId = options.issuedTokens.get(`${serverPubkey}:${tokenKey}`);
25624
25623
  if (!correlationId) return null;
25625
25624
  const entry = options.pending.get(correlationId);
25626
- return entry && entry.serverPubkey === serverPubkey ? entry : null;
25625
+ return entry && entry.serverPubkey === serverPubkey && options.admit(entry) ? entry : null;
25627
25626
  }
25628
25627
  function releaseTransfer(entry) {
25629
25628
  if (!entry.oversized) return;
25630
- clearTimeout(entry.oversized.expiryTimer);
25631
25629
  entry.oversized = void 0;
25632
25630
  }
25633
25631
  function releaseStream(entry) {
@@ -25709,10 +25707,9 @@ function createCvmProgressController(options) {
25709
25707
  startProgress: progress,
25710
25708
  acceptProgress: null,
25711
25709
  chunks: /* @__PURE__ */ new Map(),
25712
- codeUnitsReceived: 0,
25713
- expiryTimer: setTimeout(() => releaseTransfer(entry), MAX_TRANSFER_LIFETIME_MS)
25710
+ codeUnitsReceived: 0
25711
+ // The admitted request deadline bounds buffer lifetime to at most 300 seconds.
25714
25712
  };
25715
- options.refreshPendingTimeout(entry);
25716
25713
  return;
25717
25714
  }
25718
25715
  const transfer = entry.oversized;
@@ -25723,7 +25720,6 @@ function createCvmProgressController(options) {
25723
25720
  return;
25724
25721
  }
25725
25722
  transfer.acceptProgress = progress;
25726
- options.refreshPendingTimeout(entry);
25727
25723
  return;
25728
25724
  }
25729
25725
  if (cvm.frameType === "chunk") {
@@ -25738,7 +25734,6 @@ function createCvmProgressController(options) {
25738
25734
  return;
25739
25735
  }
25740
25736
  transfer.chunks.set(progress, cvm.data);
25741
- options.refreshPendingTimeout(entry);
25742
25737
  return;
25743
25738
  }
25744
25739
  if (cvm.frameType === "abort") {
@@ -25768,7 +25763,6 @@ function createCvmProgressController(options) {
25768
25763
  idleTimer: setTimeout(() => onStreamIdle(entry), options.streamIdleTimeoutMs),
25769
25764
  probeTimer: null
25770
25765
  };
25771
- options.refreshPendingTimeout(entry);
25772
25766
  options.routeEvent(serverPubkey, message3);
25773
25767
  return;
25774
25768
  }
@@ -25779,7 +25773,6 @@ function createCvmProgressController(options) {
25779
25773
  }
25780
25774
  stream.lastProgress = progress;
25781
25775
  resetStreamIdleTimer(entry, stream);
25782
- options.refreshPendingTimeout(entry);
25783
25776
  return true;
25784
25777
  };
25785
25778
  switch (cvm.frameType) {
@@ -25809,7 +25802,6 @@ function createCvmProgressController(options) {
25809
25802
  stream.outOfOrder.set(index, { message: message3, progress, codeUnits: cvm.data.length });
25810
25803
  stream.outOfOrderCodeUnits += cvm.data.length;
25811
25804
  resetStreamIdleTimer(entry, stream);
25812
- options.refreshPendingTimeout(entry);
25813
25805
  return;
25814
25806
  }
25815
25807
  const ready = [{ message: message3, progress, codeUnits: 0 }];
@@ -25837,7 +25829,6 @@ function createCvmProgressController(options) {
25837
25829
  }
25838
25830
  stream.lastProgress = previousProgress;
25839
25831
  resetStreamIdleTimer(entry, stream);
25840
- options.refreshPendingTimeout(entry);
25841
25832
  return;
25842
25833
  }
25843
25834
  case "ping":
@@ -25851,6 +25842,10 @@ function createCvmProgressController(options) {
25851
25842
  stream.probeTimer = null;
25852
25843
  return;
25853
25844
  case "close": {
25845
+ if (stream.outOfOrder.size > 0) {
25846
+ failStream(entry, "close with unresolved chunk gaps");
25847
+ return;
25848
+ }
25854
25849
  if (cvm.lastChunkIndex !== void 0) {
25855
25850
  const bound = cvm.lastChunkIndex;
25856
25851
  if (!isBoundedInteger(bound, 0, Number.MAX_SAFE_INTEGER) || stream.nextChunkIndex !== bound + 1 || stream.outOfOrder.size !== 0) {
@@ -25909,18 +25904,25 @@ var SUPPORT_ENCRYPTION_EPHEMERAL = "support_encryption_ephemeral";
25909
25904
  var SUPPORT_OVERSIZED_TRANSFER = "support_oversized_transfer";
25910
25905
  var SUPPORT_OPEN_STREAM = "support_open_stream";
25911
25906
  var DEFAULT_TIMEOUT_MS = 3e4;
25907
+ var MAX_REQUEST_TIMEOUT_MS = 3e5;
25912
25908
  var DEFAULT_DISCOVER_TIMEOUT_MS = 6e3;
25913
25909
  var MCP_PROTOCOL_VERSION = "2025-11-25";
25914
25910
  var SEEN_WRAP_LIMIT = 512;
25911
+ function randomIdSuffix() {
25912
+ return Array.from(
25913
+ crypto.getRandomValues(new Uint8Array(4)),
25914
+ (byte) => byte.toString(16).padStart(2, "0")
25915
+ ).join("");
25916
+ }
25915
25917
  var correlationCounter = 0;
25916
25918
  function nextCorrelationId() {
25917
25919
  correlationCounter += 1;
25918
- return `cvm-${correlationCounter}-${getPublicKey(generateSecretKey()).slice(0, 8)}`;
25920
+ return `cvm-${correlationCounter}-${randomIdSuffix()}`;
25919
25921
  }
25920
25922
  var streamNonceCounter = 0;
25921
25923
  function nextStreamNonce() {
25922
25924
  streamNonceCounter += 1;
25923
- return `cvm-ping-${streamNonceCounter}-${getPublicKey(generateSecretKey()).slice(0, 8)}`;
25925
+ return `cvm-ping-${streamNonceCounter}-${randomIdSuffix()}`;
25924
25926
  }
25925
25927
  function randomizedPastTimestamp() {
25926
25928
  const jitter = Math.floor(Math.random() * 172800);
@@ -25996,7 +25998,11 @@ function createNostrCvmTransport(options = {}) {
25996
25998
  },
25997
25999
  routeMessage,
25998
26000
  routeEvent,
25999
- refreshPendingTimeout
26001
+ admit(entry) {
26002
+ if (performance.now() < entry.deadline) return true;
26003
+ settlePending(entry.correlationId)?.reject(new Error("relay timeout"));
26004
+ return false;
26005
+ }
26000
26006
  });
26001
26007
  let inbound = null;
26002
26008
  let subscribedRelays = "";
@@ -26070,20 +26076,14 @@ function createNostrCvmTransport(options = {}) {
26070
26076
  progressController.release(entry);
26071
26077
  return entry;
26072
26078
  }
26073
- function refreshPendingTimeout(entry) {
26074
- clearTimeout(entry.timer);
26075
- entry.timer = setTimeout(() => {
26076
- const settled = settlePending(entry.correlationId);
26077
- settled?.reject(new Error("relay timeout"));
26078
- }, entry.timeoutMs);
26079
- }
26080
26079
  function routeMessage(serverPubkey, mcp) {
26081
26080
  const id = mcp.id;
26082
26081
  if (id != null && pending.has(String(id))) {
26083
26082
  const entry = pending.get(String(id));
26084
26083
  if (entry.serverPubkey !== serverPubkey) return;
26085
26084
  const settled = settlePending(String(id));
26086
- settled?.resolve({ ...mcp, id: entry.originalId });
26085
+ if (performance.now() >= entry.deadline) settled?.reject(new Error("relay timeout"));
26086
+ else settled?.resolve({ ...mcp, id: entry.originalId });
26087
26087
  return;
26088
26088
  }
26089
26089
  routeEvent(serverPubkey, mcp);
@@ -26094,7 +26094,7 @@ function createNostrCvmTransport(options = {}) {
26094
26094
  for (const handler of eventHandlers) handler(server, mcp);
26095
26095
  }
26096
26096
  }
26097
- async function publishMcp(server, relays, message3, signal) {
26097
+ async function publishMcp(server, relays, message3, deadline, signal) {
26098
26098
  if (signal?.aborted) throw new Error("policy denied");
26099
26099
  const capabilityTags = [
26100
26100
  ...encrypt22 ? [[SUPPORT_ENCRYPTION]] : [],
@@ -26112,6 +26112,7 @@ function createNostrCvmTransport(options = {}) {
26112
26112
  clientSecretKey
26113
26113
  );
26114
26114
  if (!encrypt22) {
26115
+ if (deadline !== void 0) remainingTime(deadline);
26115
26116
  await pool.publish(relays, inner, { signal });
26116
26117
  return;
26117
26118
  }
@@ -26127,10 +26128,12 @@ function createNostrCvmTransport(options = {}) {
26127
26128
  },
26128
26129
  wrapSecretKey
26129
26130
  );
26131
+ if (deadline !== void 0) remainingTime(deadline);
26130
26132
  await pool.publish(relays, wrap, { signal });
26131
26133
  }
26132
- function sendCorrelated(server, relays, message3, timeout, signal) {
26134
+ function sendCorrelated(server, relays, message3, deadline, signal) {
26133
26135
  if (signal?.aborted) return Promise.reject(new Error("policy denied"));
26136
+ remainingTime(deadline);
26134
26137
  const correlationId = nextCorrelationId();
26135
26138
  const originalId = message3.id;
26136
26139
  let outgoing = { ...message3, id: correlationId };
@@ -26165,8 +26168,8 @@ function createNostrCvmTransport(options = {}) {
26165
26168
  timer: setTimeout(() => {
26166
26169
  const settled = settlePending(correlationId);
26167
26170
  settled?.reject(new Error("relay timeout"));
26168
- }, timeout),
26169
- timeoutMs: timeout,
26171
+ }, remainingTime(deadline)),
26172
+ deadline,
26170
26173
  originalId,
26171
26174
  serverPubkey: server.pubkey,
26172
26175
  correlationId
@@ -26180,7 +26183,7 @@ function createNostrCvmTransport(options = {}) {
26180
26183
  const settled = settlePending(correlationId);
26181
26184
  settled?.reject(new Error("policy denied"));
26182
26185
  }, { once: true });
26183
- void publishMcp(server, relays, outgoing, signal).catch((err2) => {
26186
+ void publishMcp(server, relays, outgoing, deadline, signal).catch((err2) => {
26184
26187
  const settled = settlePending(correlationId);
26185
26188
  settled?.reject(err2 instanceof Error ? err2 : new Error("publish failed"));
26186
26189
  });
@@ -26196,11 +26199,34 @@ function createNostrCvmTransport(options = {}) {
26196
26199
  }
26197
26200
  return session;
26198
26201
  }
26199
- async function ensureInitialized(server, session, timeout, signal) {
26202
+ function remainingTime(deadline) {
26203
+ const remaining = deadline - performance.now();
26204
+ if (remaining <= 0) throw new Error("relay timeout");
26205
+ return remaining;
26206
+ }
26207
+ async function beforeDeadline(deadline, operation) {
26208
+ const timeout = remainingTime(deadline);
26209
+ let timer;
26210
+ try {
26211
+ return await Promise.race([
26212
+ new Promise((_resolve, reject2) => {
26213
+ timer = setTimeout(() => reject2(new Error("relay timeout")), timeout);
26214
+ }),
26215
+ operation()
26216
+ ]);
26217
+ } finally {
26218
+ clearTimeout(timer);
26219
+ }
26220
+ }
26221
+ async function ensureInitialized(server, session, deadline, signal) {
26200
26222
  if (session.initialized) return;
26201
- if (session.initializing) return session.initializing;
26202
- session.initializing = (async () => {
26223
+ if (session.initializing) {
26224
+ await beforeDeadline(deadline, () => session.initializing);
26225
+ return;
26226
+ }
26227
+ session.initializing = Promise.resolve().then(async () => {
26203
26228
  try {
26229
+ if (sessions.get(server.pubkey) !== session) throw new Error("server closed");
26204
26230
  await sendCorrelated(
26205
26231
  server,
26206
26232
  session.relays,
@@ -26210,17 +26236,28 @@ function createNostrCvmTransport(options = {}) {
26210
26236
  method: "initialize",
26211
26237
  params: { protocolVersion: MCP_PROTOCOL_VERSION, capabilities: {}, clientInfo }
26212
26238
  },
26213
- timeout,
26239
+ deadline,
26214
26240
  signal
26215
26241
  );
26216
- await publishMcp(server, session.relays, { jsonrpc: "2.0", method: "notifications/initialized" }, signal);
26242
+ remainingTime(deadline);
26243
+ if (sessions.get(server.pubkey) !== session) throw new Error("server closed");
26244
+ await beforeDeadline(deadline, () => publishMcp(
26245
+ server,
26246
+ session.relays,
26247
+ { jsonrpc: "2.0", method: "notifications/initialized" },
26248
+ deadline,
26249
+ signal
26250
+ ));
26251
+ remainingTime(deadline);
26252
+ if (sessions.get(server.pubkey) !== session) throw new Error("server closed");
26217
26253
  session.initialized = true;
26218
- } catch {
26254
+ } catch (error) {
26255
+ if (error instanceof Error && (error.message === "relay timeout" || error.message === "server closed")) throw error;
26219
26256
  throw new Error("initialization failed");
26220
26257
  } finally {
26221
26258
  session.initializing = null;
26222
26259
  }
26223
- })();
26260
+ });
26224
26261
  return session.initializing;
26225
26262
  }
26226
26263
  return {
@@ -26286,10 +26323,15 @@ function createNostrCvmTransport(options = {}) {
26286
26323
  },
26287
26324
  async request(server, message3, requestOptions, execution) {
26288
26325
  if (execution?.signal.aborted) throw new Error("policy denied");
26326
+ const timeout = requestOptions?.timeoutMs === void 0 ? timeoutMs : requestOptions.timeoutMs;
26327
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > MAX_REQUEST_TIMEOUT_MS) {
26328
+ throw new Error("invalid timeout");
26329
+ }
26330
+ const deadline = performance.now() + timeout;
26289
26331
  const session = getSession(server);
26290
- const timeout = requestOptions?.timeoutMs ?? timeoutMs;
26291
- if (requestOptions?.initialize) await ensureInitialized(server, session, timeout, execution?.signal);
26292
- return sendCorrelated(server, session.relays, message3, timeout, execution?.signal);
26332
+ if (requestOptions?.initialize) await ensureInitialized(server, session, deadline, execution?.signal);
26333
+ if (sessions.get(server.pubkey) !== session) throw new Error("server closed");
26334
+ return sendCorrelated(server, session.relays, message3, deadline, execution?.signal);
26293
26335
  },
26294
26336
  async close(server) {
26295
26337
  const session = sessions.get(server.pubkey);