@toon-protocol/client 0.29.3 → 0.29.5

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/dist/index.js CHANGED
@@ -359,6 +359,12 @@ function getNetworkStatus(config) {
359
359
  if (!network || network === "custom") return void 0;
360
360
  return resolveClientNetwork(network).status;
361
361
  }
362
+ function deriveConnectorEdgeFromBtpUrl(btpUrl) {
363
+ const url = new URL(btpUrl);
364
+ const httpProtocol = url.protocol === "wss:" ? "https:" : "http:";
365
+ const connectorUrl = `${httpProtocol}//${url.host}`;
366
+ return { connectorUrl, connectorHttpEndpoint: `${connectorUrl}/ilp` };
367
+ }
362
368
  function proxyIlpEndpoint(proxyUrl) {
363
369
  if (!proxyUrl) return void 0;
364
370
  const trimmed = proxyUrl.replace(/\/+$/, "");
@@ -370,9 +376,9 @@ function validateConfig(config) {
370
376
  "Embedded mode not yet implemented in ToonClient. Use connectorUrl for HTTP mode."
371
377
  );
372
378
  }
373
- if (!config.connectorUrl && !config.proxyUrl) {
379
+ if (!config.connectorUrl && !config.proxyUrl && !config.btpUrl) {
374
380
  throw new ValidationError(
375
- 'connectorUrl (or proxyUrl) is required for HTTP mode. Example: "http://localhost:8080"'
381
+ 'connectorUrl (or proxyUrl, or btpUrl) is required for HTTP mode. Example: "http://localhost:8080"'
376
382
  );
377
383
  }
378
384
  if (config.connectorUrl) {
@@ -481,8 +487,9 @@ function applyDefaults(rawConfig) {
481
487
  config.mnemonic,
482
488
  config.mnemonicAccountIndex ?? 0
483
489
  ).secretKey : generateSecretKey2());
484
- const connectorHttpEndpoint = config.connectorHttpEndpoint ?? proxyIlpEndpoint(config.proxyUrl);
485
- const connectorUrl = config.connectorUrl ?? config.proxyUrl?.replace(/\/+$/, "");
490
+ const btpDerivedEdge = !config.connectorUrl && !config.proxyUrl && config.btpUrl ? deriveConnectorEdgeFromBtpUrl(config.btpUrl) : void 0;
491
+ const connectorHttpEndpoint = config.connectorHttpEndpoint ?? proxyIlpEndpoint(config.proxyUrl) ?? btpDerivedEdge?.connectorHttpEndpoint;
492
+ const connectorUrl = config.connectorUrl ?? config.proxyUrl?.replace(/\/+$/, "") ?? btpDerivedEdge?.connectorUrl;
486
493
  let btpUrl = config.btpUrl;
487
494
  if (!btpUrl && connectorUrl && !connectorHttpEndpoint) {
488
495
  try {
@@ -530,6 +537,7 @@ function applyDefaults(rawConfig) {
530
537
  maxRetries: config.maxRetries ?? 3,
531
538
  retryDelay: config.retryDelay ?? 1e3,
532
539
  preferBtpForPaidWrites: config.preferBtpForPaidWrites ?? false,
540
+ jobHandlerSealed: config.jobHandlerSealed ?? false,
533
541
  btpUrl,
534
542
  destinationAddress
535
543
  // Always set by logic above
@@ -1928,6 +1936,13 @@ function localGiftWrapEcdh(secretKey) {
1928
1936
  ecdh: (ephemeralPublicKey) => ecdhXCoordinate(secretKey, ephemeralPublicKey)
1929
1937
  };
1930
1938
  }
1939
+ function giftWrapPublicKey(secretKey) {
1940
+ try {
1941
+ return secp256k1.getPublicKey(secretKey, false);
1942
+ } catch {
1943
+ throw new GiftWrapError("invalid_key" /* InvalidKey */);
1944
+ }
1945
+ }
1931
1946
  function sealRequestWithRandomness(plaintext, receiverPublicKey, ephemeralSecretKey, sharedSecret, nonce) {
1932
1947
  if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {
1933
1948
  throw new GiftWrapError("truncated" /* Truncated */);
@@ -3405,24 +3420,40 @@ function rejectResponse(code, message2, triggeredBy) {
3405
3420
  })
3406
3421
  };
3407
3422
  }
3408
- function createJobMessageHandler(handler) {
3423
+ function createJobMessageHandler(handler, identity) {
3409
3424
  return async (message2) => {
3410
3425
  if (!message2.ilpPacket || message2.ilpPacket.length === 0) {
3411
3426
  return {};
3412
3427
  }
3413
- let job;
3428
+ let prepared;
3414
3429
  try {
3415
- job = deserializeIlpPrepare(message2.ilpPacket);
3430
+ prepared = deserializeIlpPrepare(message2.ilpPacket);
3416
3431
  } catch (error) {
3417
3432
  return rejectResponse("F00", `undecodable PREPARE: ${errText(error)}`);
3418
3433
  }
3419
- if (job.expiresAt.getTime() <= Date.now()) {
3434
+ if (prepared.expiresAt.getTime() <= Date.now()) {
3420
3435
  return rejectResponse(
3421
3436
  "R00",
3422
3437
  "PREPARE already expired; the handler was never invoked",
3423
- job.destination
3438
+ prepared.destination
3424
3439
  );
3425
3440
  }
3441
+ let job = prepared;
3442
+ let sharedSecret;
3443
+ if (identity !== void 0) {
3444
+ try {
3445
+ const opened = openRequest(prepared.data, identity);
3446
+ job = { ...prepared, data: opened.envelopeBytes };
3447
+ sharedSecret = opened.sharedSecret;
3448
+ } catch (error) {
3449
+ if (!(error instanceof GiftWrapError)) throw error;
3450
+ return rejectResponse(
3451
+ "F00",
3452
+ `sealed PREPARE data did not open under this client's identity: ${error.message}`,
3453
+ prepared.destination
3454
+ );
3455
+ }
3456
+ }
3426
3457
  let answer;
3427
3458
  try {
3428
3459
  answer = await handler(job);
@@ -3436,10 +3467,14 @@ function createJobMessageHandler(handler) {
3436
3467
  job.destination
3437
3468
  );
3438
3469
  }
3470
+ const answerData = answer.data ?? new Uint8Array(0);
3439
3471
  return {
3440
3472
  ilpPacket: serializeIlpFulfill({
3441
3473
  fulfillment: answer.fulfillment,
3442
- data: answer.data ?? new Uint8Array(0)
3474
+ // Seal the answer back with the request's own secret (ADR 0018's
3475
+ // bidirectional rule) whenever the request itself was sealed;
3476
+ // unsealed in, unsealed out otherwise (additive).
3477
+ data: sharedSecret !== void 0 ? sealResponse(sharedSecret, answerData) : answerData
3443
3478
  })
3444
3479
  };
3445
3480
  };
@@ -5081,7 +5116,15 @@ async function initializeHttpMode(config, hooks = {}) {
5081
5116
  // MESSAGE carrying a PREPARE is answered by the configured handler.
5082
5117
  // Unset `jobHandler` leaves `onMessage` unset too, so an inbound job
5083
5118
  // MESSAGE is dropped unanswered — unchanged from the pre-#494 default.
5084
- ...config.jobHandler ? { onMessage: createJobMessageHandler(config.jobHandler) } : {},
5119
+ // `jobHandlerSealed` (toon-client#537) additionally unseals/reseals at
5120
+ // this client's own identity (toon-meta#266 §7); default `false` keeps
5121
+ // every existing `jobHandler` on the unsealed pre-#537 wire.
5122
+ ...config.jobHandler ? {
5123
+ onMessage: createJobMessageHandler(
5124
+ config.jobHandler,
5125
+ config.jobHandlerSealed ? config.secretKey : void 0
5126
+ )
5127
+ } : {},
5085
5128
  ...hooks.getChannelDeclaration ? { getChannelDeclaration: hooks.getChannelDeclaration } : {}
5086
5129
  });
5087
5130
  await btpClient.connect();
@@ -5156,6 +5199,30 @@ async function initializeHttpMode(config, hooks = {}) {
5156
5199
  };
5157
5200
  }
5158
5201
 
5202
+ // src/discovery-subscription.ts
5203
+ import { ILP_PEER_INFO_KIND } from "@toon-protocol/core";
5204
+ async function subscribeToDiscovery(relayUrls, tracker) {
5205
+ const urls = Array.from(new Set(relayUrls.filter((url) => url !== "")));
5206
+ if (urls.length === 0) {
5207
+ return { close: () => void 0 };
5208
+ }
5209
+ const { SimplePool } = await import("nostr-tools/pool");
5210
+ const pool = new SimplePool();
5211
+ const sub = pool.subscribeMany(
5212
+ urls,
5213
+ { kinds: [ILP_PEER_INFO_KIND] },
5214
+ {
5215
+ onevent: (event) => tracker.processEvent(event)
5216
+ }
5217
+ );
5218
+ return {
5219
+ close: () => {
5220
+ sub.close();
5221
+ pool.close(urls);
5222
+ }
5223
+ };
5224
+ }
5225
+
5159
5226
  // src/signing/solana-signer.ts
5160
5227
  import { ed25519 as ed255193 } from "@noble/curves/ed25519.js";
5161
5228
  import { base58Encode as base58Encode3, base58Decode as base58Decode2 } from "@toon-protocol/core";
@@ -7908,6 +7975,28 @@ var ToonClient = class {
7908
7975
  getPublicKey() {
7909
7976
  return getPublicKey2(this.config.secretKey);
7910
7977
  }
7978
+ /**
7979
+ * This client's own ADR 0018 sealing public key — the 65-byte uncompressed
7980
+ * secp256k1 identity a buyer seals a job PREPARE's `data` to when this
7981
+ * client IS the destination (toon-client#537, toon-meta#266 §3.1/§7), in
7982
+ * the same format a real connector reports from `GET /ilp/identity`
7983
+ * (`ConnectorIdentity.publicKey`). Publish it as a `kind:31990`
7984
+ * advertisement's `seal_pubkey` tag ({@link getSealingPublicKeyHex}) so a
7985
+ * buyer can address this client without a `GET /identity` it cannot serve
7986
+ * behind NAT (ADR 0022).
7987
+ *
7988
+ * Derived from the same `secretKey` as {@link getPublicKey}'s Nostr
7989
+ * identity — stable across daemon restarts and reconnects, never a fresh
7990
+ * key per call, so a durable advertisement stays valid. Works before
7991
+ * `start()` is called.
7992
+ */
7993
+ getSealingPublicKey() {
7994
+ return giftWrapPublicKey(this.config.secretKey);
7995
+ }
7996
+ /** {@link getSealingPublicKey}, hex-encoded — the exact `seal_pubkey` tag value. */
7997
+ getSealingPublicKeyHex() {
7998
+ return toHex2(this.getSealingPublicKey());
7999
+ }
7911
8000
  /**
7912
8001
  * Sign an unsigned Nostr event template with the client's Nostr secret key,
7913
8002
  * returning a fully-signed event (id + pubkey + sig).
@@ -8048,6 +8137,13 @@ var ToonClient = class {
8048
8137
  btpClient,
8049
8138
  btpSession
8050
8139
  } = initialization;
8140
+ const discoverySubscription = await subscribeToDiscovery(
8141
+ [
8142
+ this.config.relayUrl,
8143
+ ...(this.config.knownPeers ?? []).map((peer) => peer.relayUrl)
8144
+ ],
8145
+ discoveryTracker
8146
+ );
8051
8147
  if (this.channelManager) {
8052
8148
  const cm = this.channelManager;
8053
8149
  const nostrPubkey = this.getPublicKey();
@@ -8143,6 +8239,7 @@ var ToonClient = class {
8143
8239
  this.state = {
8144
8240
  bootstrapService,
8145
8241
  discoveryTracker,
8242
+ discoverySubscription,
8146
8243
  runtimeClient,
8147
8244
  peersDiscovered: bootstrapResults.length,
8148
8245
  btpClient: btpClient ?? void 0,
@@ -9607,6 +9704,7 @@ var ToonClient = class {
9607
9704
  throw new ToonClientError("Client not started", "INVALID_STATE");
9608
9705
  }
9609
9706
  try {
9707
+ this.state.discoverySubscription.close();
9610
9708
  if (this.state.btpClient) {
9611
9709
  await this.state.btpClient.disconnect();
9612
9710
  }
@@ -11737,6 +11835,7 @@ export {
11737
11835
  generateRandomIdentity,
11738
11836
  getNetworkStatus,
11739
11837
  getUiCoordinate,
11838
+ giftWrapPublicKey,
11740
11839
  guardedRenderDispatch,
11741
11840
  hasSettlementMetadata,
11742
11841
  httpEndpointToBtpUrl,