@toon-protocol/client 0.29.2 → 0.29.4

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
@@ -1190,7 +1198,16 @@ var ConnectorEdgeClient = class {
1190
1198
  /**
1191
1199
  * The terminating connector's public key, fetched once per endpoint.
1192
1200
  *
1193
- * @param endpoint any client-edge URL (`https://apex`, `https://apex/ilp`).
1201
+ * `endpoint` MUST already be the TERMINATING connector's client edge, not
1202
+ * merely whatever origin a caller is about to POST an ILP packet to —
1203
+ * those are the same machine for most routes today, but never for a
1204
+ * forwarded prefix (ADR 0022, toon-client#526). This method trusts
1205
+ * `endpoint` and fetches exactly that origin's `/ilp/identity`; resolving
1206
+ * a destination address to its terminator first is the caller's job.
1207
+ *
1208
+ * @param endpoint the TERMINATING connector's client-edge URL
1209
+ * (`https://apex`, `https://apex/ilp`) — already resolved from the
1210
+ * destination, never assumed to be the posting edge.
1194
1211
  * @param options `forceRefresh` bypasses (and replaces) the cache entry.
1195
1212
  */
1196
1213
  async getIdentity(endpoint, options = {}) {
@@ -1919,6 +1936,13 @@ function localGiftWrapEcdh(secretKey) {
1919
1936
  ecdh: (ephemeralPublicKey) => ecdhXCoordinate(secretKey, ephemeralPublicKey)
1920
1937
  };
1921
1938
  }
1939
+ function giftWrapPublicKey(secretKey) {
1940
+ try {
1941
+ return secp256k1.getPublicKey(secretKey, false);
1942
+ } catch {
1943
+ throw new GiftWrapError("invalid_key" /* InvalidKey */);
1944
+ }
1945
+ }
1922
1946
  function sealRequestWithRandomness(plaintext, receiverPublicKey, ephemeralSecretKey, sharedSecret, nonce) {
1923
1947
  if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {
1924
1948
  throw new GiftWrapError("truncated" /* Truncated */);
@@ -3396,24 +3420,40 @@ function rejectResponse(code, message2, triggeredBy) {
3396
3420
  })
3397
3421
  };
3398
3422
  }
3399
- function createJobMessageHandler(handler) {
3423
+ function createJobMessageHandler(handler, identity) {
3400
3424
  return async (message2) => {
3401
3425
  if (!message2.ilpPacket || message2.ilpPacket.length === 0) {
3402
3426
  return {};
3403
3427
  }
3404
- let job;
3428
+ let prepared;
3405
3429
  try {
3406
- job = deserializeIlpPrepare(message2.ilpPacket);
3430
+ prepared = deserializeIlpPrepare(message2.ilpPacket);
3407
3431
  } catch (error) {
3408
3432
  return rejectResponse("F00", `undecodable PREPARE: ${errText(error)}`);
3409
3433
  }
3410
- if (job.expiresAt.getTime() <= Date.now()) {
3434
+ if (prepared.expiresAt.getTime() <= Date.now()) {
3411
3435
  return rejectResponse(
3412
3436
  "R00",
3413
3437
  "PREPARE already expired; the handler was never invoked",
3414
- job.destination
3438
+ prepared.destination
3415
3439
  );
3416
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
+ }
3417
3457
  let answer;
3418
3458
  try {
3419
3459
  answer = await handler(job);
@@ -3427,10 +3467,14 @@ function createJobMessageHandler(handler) {
3427
3467
  job.destination
3428
3468
  );
3429
3469
  }
3470
+ const answerData = answer.data ?? new Uint8Array(0);
3430
3471
  return {
3431
3472
  ilpPacket: serializeIlpFulfill({
3432
3473
  fulfillment: answer.fulfillment,
3433
- 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
3434
3478
  })
3435
3479
  };
3436
3480
  };
@@ -5072,7 +5116,15 @@ async function initializeHttpMode(config, hooks = {}) {
5072
5116
  // MESSAGE carrying a PREPARE is answered by the configured handler.
5073
5117
  // Unset `jobHandler` leaves `onMessage` unset too, so an inbound job
5074
5118
  // MESSAGE is dropped unanswered — unchanged from the pre-#494 default.
5075
- ...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
+ } : {},
5076
5128
  ...hooks.getChannelDeclaration ? { getChannelDeclaration: hooks.getChannelDeclaration } : {}
5077
5129
  });
5078
5130
  await btpClient.connect();
@@ -7758,6 +7810,35 @@ function parseMakerMinaSignature(raw) {
7758
7810
  }
7759
7811
  return void 0;
7760
7812
  }
7813
+ function ilpAddressTerminates(address, destination) {
7814
+ return destination === address || destination.startsWith(`${address}.`);
7815
+ }
7816
+ function claimsTermination(peerInfo, address, destination) {
7817
+ if (destination === address) return true;
7818
+ return peerInfo.ilpAddresses === void 0 && ilpAddressTerminates(address, destination);
7819
+ }
7820
+ function outranks(claim, best) {
7821
+ if (claim.segments !== best.segments) return claim.segments > best.segments;
7822
+ return claim.isPrimary && !best.isPrimary;
7823
+ }
7824
+ function resolveTerminatorHttpEndpoint(destination, peers) {
7825
+ let best;
7826
+ for (const { peerInfo } of peers) {
7827
+ const httpEndpoint = peerInfo.httpEndpoint;
7828
+ if (!httpEndpoint) continue;
7829
+ const addresses = peerInfo.ilpAddresses ?? [peerInfo.ilpAddress];
7830
+ for (const [index, address] of addresses.entries()) {
7831
+ if (!claimsTermination(peerInfo, address, destination)) continue;
7832
+ const claim = {
7833
+ endpoint: httpEndpoint,
7834
+ segments: address.split(".").length,
7835
+ isPrimary: index === 0
7836
+ };
7837
+ if (!best || outranks(claim, best)) best = claim;
7838
+ }
7839
+ }
7840
+ return best?.endpoint;
7841
+ }
7761
7842
  function canonicalChainId(chain) {
7762
7843
  const parts = chain.split(":");
7763
7844
  return parts[0] === "evm" && parts.length >= 3 ? `evm:${parts[2]}` : chain;
@@ -7870,6 +7951,28 @@ var ToonClient = class {
7870
7951
  getPublicKey() {
7871
7952
  return getPublicKey2(this.config.secretKey);
7872
7953
  }
7954
+ /**
7955
+ * This client's own ADR 0018 sealing public key — the 65-byte uncompressed
7956
+ * secp256k1 identity a buyer seals a job PREPARE's `data` to when this
7957
+ * client IS the destination (toon-client#537, toon-meta#266 §3.1/§7), in
7958
+ * the same format a real connector reports from `GET /ilp/identity`
7959
+ * (`ConnectorIdentity.publicKey`). Publish it as a `kind:31990`
7960
+ * advertisement's `seal_pubkey` tag ({@link getSealingPublicKeyHex}) so a
7961
+ * buyer can address this client without a `GET /identity` it cannot serve
7962
+ * behind NAT (ADR 0022).
7963
+ *
7964
+ * Derived from the same `secretKey` as {@link getPublicKey}'s Nostr
7965
+ * identity — stable across daemon restarts and reconnects, never a fresh
7966
+ * key per call, so a durable advertisement stays valid. Works before
7967
+ * `start()` is called.
7968
+ */
7969
+ getSealingPublicKey() {
7970
+ return giftWrapPublicKey(this.config.secretKey);
7971
+ }
7972
+ /** {@link getSealingPublicKey}, hex-encoded — the exact `seal_pubkey` tag value. */
7973
+ getSealingPublicKeyHex() {
7974
+ return toHex2(this.getSealingPublicKey());
7975
+ }
7873
7976
  /**
7874
7977
  * Sign an unsigned Nostr event template with the client's Nostr secret key,
7875
7978
  * returning a fully-signed event (id + pubkey + sig).
@@ -8170,7 +8273,9 @@ var ToonClient = class {
8170
8273
  try {
8171
8274
  const destination = options?.destination ?? this.config.destinationAddress;
8172
8275
  const edge = this.resolveClientEdgeEndpoint();
8173
- const identity = await this.connectorEdge.getIdentity(edge);
8276
+ const identity = await this.connectorEdge.getIdentity(
8277
+ this.resolveTerminatorEndpoint(destination)
8278
+ );
8174
8279
  const amount = options?.ilpAmount !== void 0 ? String(options.ilpAmount) : String(await this.routePriceFor(edge, destination));
8175
8280
  const exchange = sealExchange(
8176
8281
  {
@@ -8241,7 +8346,7 @@ var ToonClient = class {
8241
8346
  String(error),
8242
8347
  error instanceof Error ? error.stack : ""
8243
8348
  );
8244
- if (error instanceof ToonClientError && (error.code === "NO_TERMINATED_ROUTE" || error.code === "NO_CONNECTOR_EDGE" || error.code === "PEER_NOT_NEGOTIATED" || error.code === "CHANNEL_FUNDING")) {
8349
+ if (error instanceof ToonClientError && (error.code === "NO_TERMINATED_ROUTE" || error.code === "NO_CONNECTOR_EDGE" || error.code === "PEER_NOT_NEGOTIATED" || error.code === "CHANNEL_FUNDING" || error.code === "TERMINATOR_UNRESOLVED")) {
8245
8350
  throw error;
8246
8351
  }
8247
8352
  throw new ToonClientError(
@@ -8323,6 +8428,58 @@ var ToonClient = class {
8323
8428
  }
8324
8429
  return connectorEdgeBaseUrl(endpoint);
8325
8430
  }
8431
+ /**
8432
+ * The client edge to fetch `destination`'s identity from — the connector
8433
+ * that TERMINATES it, not the one this client happens to be posting to
8434
+ * (issue #526). ADR 0022 makes identity answered-not-announced, so it is
8435
+ * fetched from the terminator's own `/ilp/identity`; discovery is only
8436
+ * used to find WHICH origin that is.
8437
+ *
8438
+ * Matches `destination` against every peer this client has discovered
8439
+ * announcing itself via kind:10032 — including ones never peered with,
8440
+ * since a forwarded prefix's terminator need not be a direct peer at all
8441
+ * (that is precisely the shape a forwarded prefix has). Falls back to the
8442
+ * posting edge only when there is no discovery tracker wired up AT ALL —
8443
+ * preserving the (still-common) same-node case where the posting node
8444
+ * terminates its own destination, and the only case that worked before
8445
+ * #526.
8446
+ *
8447
+ * Once a tracker exists, silence — whether zero peers discovered at all,
8448
+ * or peers discovered but none of them claiming `destination` — is treated
8449
+ * as a refusal, not a green light (toon-client#533): zero peers is not
8450
+ * evidence the posting edge terminates the destination, only the absence
8451
+ * of evidence that anything does, and that absence is exactly what
8452
+ * fail-closed exists for. It is also a live production window, not a
8453
+ * theoretical one: `discoveryTracker` is always constructed for a started
8454
+ * client, so a tracker reporting zero peers is what the startup race looks
8455
+ * like before the first announce lands. Likewise, an ancestor-only claim
8456
+ * (a router legitimately owning `g.toon`, which is not the same as owning
8457
+ * everything under it) used to slip through here and get treated as
8458
+ * coverage once a competing announce expired. `resolveTerminatorHttpEndpoint`'s
8459
+ * own claim-gating fixes that; the caller-visible half of the fix is this —
8460
+ * refusing to publish beats sealing to a key that cannot open the wrap,
8461
+ * for a defect whose symptom is "money spent, write lost".
8462
+ *
8463
+ * @throws {ToonClientError} NO_CONNECTOR_EDGE when no origin is known at
8464
+ * all (propagated from {@link resolveClientEdgeEndpoint}).
8465
+ * @throws {ToonClientError} TERMINATOR_UNRESOLVED when a discovery tracker
8466
+ * is present but no discovered announce claims `destination` — including
8467
+ * when it has discovered no peers at all yet.
8468
+ */
8469
+ resolveTerminatorEndpoint(destination) {
8470
+ const edge = this.resolveClientEdgeEndpoint();
8471
+ const tracker = this.state?.discoveryTracker;
8472
+ if (typeof tracker?.getAllDiscoveredPeers !== "function") return edge;
8473
+ const peers = tracker.getAllDiscoveredPeers();
8474
+ const httpEndpoint = resolveTerminatorHttpEndpoint(destination, peers);
8475
+ if (!httpEndpoint) {
8476
+ throw new ToonClientError(
8477
+ `No discovered announce terminates "${destination}" (${peers.length} peer(s) discovered, none claims it), so this client cannot confirm the posting edge is who it would be paying. Refusing to publish rather than seal to a key that may not be able to open the wrap.`,
8478
+ "TERMINATOR_UNRESOLVED"
8479
+ );
8480
+ }
8481
+ return connectorEdgeBaseUrl(httpEndpoint);
8482
+ }
8326
8483
  /**
8327
8484
  * Payment-aware HTTP fetch over TOON (issue #50). A `fetch()`-like method that
8328
8485
  * makes paying for an HTTP resource transparent:
@@ -11645,6 +11802,7 @@ export {
11645
11802
  generateRandomIdentity,
11646
11803
  getNetworkStatus,
11647
11804
  getUiCoordinate,
11805
+ giftWrapPublicKey,
11648
11806
  guardedRenderDispatch,
11649
11807
  hasSettlementMetadata,
11650
11808
  httpEndpointToBtpUrl,