@toon-protocol/client 0.21.3 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1009 -228
- package/dist/index.js +1206 -241
- package/dist/index.js.map +1 -1
- package/package.json +5 -2
package/dist/index.js
CHANGED
|
@@ -32,7 +32,11 @@ import {
|
|
|
32
32
|
} from "./chunk-7TDAU43L.js";
|
|
33
33
|
|
|
34
34
|
// src/ToonClient.ts
|
|
35
|
-
import {
|
|
35
|
+
import {
|
|
36
|
+
generateSecretKey as generateSecretKey3,
|
|
37
|
+
getPublicKey as getPublicKey2,
|
|
38
|
+
finalizeEvent
|
|
39
|
+
} from "nostr-tools/pure";
|
|
36
40
|
|
|
37
41
|
// src/config.ts
|
|
38
42
|
import { generateSecretKey as generateSecretKey2 } from "nostr-tools/pure";
|
|
@@ -540,51 +544,837 @@ function isBase64(str) {
|
|
|
540
544
|
return /^[A-Za-z0-9+/]*={0,2}$/.test(str);
|
|
541
545
|
}
|
|
542
546
|
|
|
543
|
-
// src/
|
|
544
|
-
var
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
547
|
+
// src/adapters/ConnectorEdgeClient.ts
|
|
548
|
+
var ConnectorEdgeError = class extends ToonClientError {
|
|
549
|
+
constructor(message, code, cause) {
|
|
550
|
+
super(message, code, cause);
|
|
551
|
+
this.name = "ConnectorEdgeError";
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
function connectorEdgeBaseUrl(endpoint) {
|
|
555
|
+
let url;
|
|
556
|
+
try {
|
|
557
|
+
url = new URL(endpoint);
|
|
558
|
+
} catch (error) {
|
|
559
|
+
throw new ConnectorEdgeError(
|
|
560
|
+
`not a valid connector endpoint URL: ${endpoint}`,
|
|
561
|
+
"IDENTITY_MALFORMED",
|
|
562
|
+
error instanceof Error ? error : void 0
|
|
563
|
+
);
|
|
564
|
+
}
|
|
565
|
+
let path = url.pathname.replace(/\/+$/, "");
|
|
566
|
+
if (path.endsWith("/ilp")) path = path.slice(0, -"/ilp".length);
|
|
567
|
+
url.pathname = path;
|
|
568
|
+
url.search = "";
|
|
569
|
+
url.hash = "";
|
|
570
|
+
return url.toString().replace(/\/+$/, "");
|
|
571
|
+
}
|
|
572
|
+
var UNCOMPRESSED_KEY_BYTES = 65;
|
|
573
|
+
var SEC1_UNCOMPRESSED_TAG = 4;
|
|
574
|
+
function decodeConnectorPublicKey(publicKeyHex) {
|
|
575
|
+
const trimmed = publicKeyHex.trim();
|
|
576
|
+
if (!/^0x[0-9a-fA-F]*$/.test(trimmed) || trimmed.length % 2 !== 0) {
|
|
577
|
+
throw new ConnectorEdgeError(
|
|
578
|
+
`connector publicKey is not 0x-prefixed hex: ${publicKeyHex}`,
|
|
579
|
+
"IDENTITY_KEY_NOT_HEX"
|
|
580
|
+
);
|
|
581
|
+
}
|
|
582
|
+
const hex = trimmed.slice(2);
|
|
583
|
+
const bytes = new Uint8Array(hex.length / 2);
|
|
584
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
585
|
+
bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
586
|
+
}
|
|
587
|
+
if (bytes.length !== UNCOMPRESSED_KEY_BYTES) {
|
|
588
|
+
throw new ConnectorEdgeError(
|
|
589
|
+
`connector publicKey must be ${UNCOMPRESSED_KEY_BYTES} bytes, got ${bytes.length}`,
|
|
590
|
+
"IDENTITY_KEY_LENGTH"
|
|
591
|
+
);
|
|
592
|
+
}
|
|
593
|
+
const tag = bytes[0] ?? 0;
|
|
594
|
+
if (tag !== SEC1_UNCOMPRESSED_TAG) {
|
|
595
|
+
throw new ConnectorEdgeError(
|
|
596
|
+
`connector publicKey must be SEC1-uncompressed (0x04 prefix), got 0x${tag.toString(16).padStart(2, "0")}`,
|
|
597
|
+
"IDENTITY_KEY_NOT_UNCOMPRESSED"
|
|
598
|
+
);
|
|
599
|
+
}
|
|
600
|
+
return bytes;
|
|
550
601
|
}
|
|
602
|
+
function parseConnectorIdentity(body, endpoint) {
|
|
603
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
604
|
+
throw new ConnectorEdgeError(
|
|
605
|
+
"GET /ilp/identity did not answer a JSON object",
|
|
606
|
+
"IDENTITY_MALFORMED"
|
|
607
|
+
);
|
|
608
|
+
}
|
|
609
|
+
const record = body;
|
|
610
|
+
const keyId = record["keyId"];
|
|
611
|
+
const publicKeyHex = record["publicKey"];
|
|
612
|
+
if (typeof keyId !== "string" || keyId.length === 0) {
|
|
613
|
+
throw new ConnectorEdgeError(
|
|
614
|
+
"GET /ilp/identity answered without a keyId",
|
|
615
|
+
"IDENTITY_MALFORMED"
|
|
616
|
+
);
|
|
617
|
+
}
|
|
618
|
+
if (typeof publicKeyHex !== "string" || publicKeyHex.length === 0) {
|
|
619
|
+
throw new ConnectorEdgeError(
|
|
620
|
+
"GET /ilp/identity answered without a publicKey",
|
|
621
|
+
"IDENTITY_MALFORMED"
|
|
622
|
+
);
|
|
623
|
+
}
|
|
624
|
+
return {
|
|
625
|
+
keyId,
|
|
626
|
+
publicKey: decodeConnectorPublicKey(publicKeyHex),
|
|
627
|
+
publicKeyHex: publicKeyHex.trim().toLowerCase(),
|
|
628
|
+
endpoint
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
function parseConnectorRoutePrice(body) {
|
|
632
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
633
|
+
throw new ConnectorEdgeError(
|
|
634
|
+
"GET /ilp/routes/price did not answer a JSON object",
|
|
635
|
+
"ROUTE_PRICE_MALFORMED"
|
|
636
|
+
);
|
|
637
|
+
}
|
|
638
|
+
const record = body;
|
|
639
|
+
const destination = record["destination"];
|
|
640
|
+
const price = record["price"];
|
|
641
|
+
if (typeof destination !== "string" || destination.length === 0) {
|
|
642
|
+
throw new ConnectorEdgeError(
|
|
643
|
+
"GET /ilp/routes/price answered without a destination",
|
|
644
|
+
"ROUTE_PRICE_MALFORMED"
|
|
645
|
+
);
|
|
646
|
+
}
|
|
647
|
+
if (typeof price !== "number" || !Number.isFinite(price) || !Number.isInteger(price) || price < 0) {
|
|
648
|
+
throw new ConnectorEdgeError(
|
|
649
|
+
`GET /ilp/routes/price answered a non-integer price: ${String(price)}`,
|
|
650
|
+
"ROUTE_PRICE_MALFORMED"
|
|
651
|
+
);
|
|
652
|
+
}
|
|
653
|
+
return { destination, price: BigInt(price) };
|
|
654
|
+
}
|
|
655
|
+
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
656
|
+
var PRICE_KEY_SEPARATOR = "\0";
|
|
657
|
+
function priceCacheKey(base, destination) {
|
|
658
|
+
return `${base}${PRICE_KEY_SEPARATOR}${destination}`;
|
|
659
|
+
}
|
|
660
|
+
function priceCacheKeyPrefix(base) {
|
|
661
|
+
return priceCacheKey(base, "");
|
|
662
|
+
}
|
|
663
|
+
var ConnectorEdgeClient = class {
|
|
664
|
+
fetchImpl;
|
|
665
|
+
timeout;
|
|
666
|
+
identities = /* @__PURE__ */ new Map();
|
|
667
|
+
prices = /* @__PURE__ */ new Map();
|
|
668
|
+
constructor(config = {}) {
|
|
669
|
+
this.fetchImpl = config.fetch ?? globalThis.fetch.bind(globalThis);
|
|
670
|
+
this.timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* The terminating connector's public key, fetched once per endpoint.
|
|
674
|
+
*
|
|
675
|
+
* @param endpoint any client-edge URL (`https://apex`, `https://apex/ilp`).
|
|
676
|
+
* @param options `forceRefresh` bypasses (and replaces) the cache entry.
|
|
677
|
+
*/
|
|
678
|
+
async getIdentity(endpoint, options = {}) {
|
|
679
|
+
const base = connectorEdgeBaseUrl(endpoint);
|
|
680
|
+
if (options.forceRefresh) this.identities.delete(base);
|
|
681
|
+
const cached = this.identities.get(base);
|
|
682
|
+
if (cached) return cached;
|
|
683
|
+
const inFlight = this.fetchIdentity(base).catch((error) => {
|
|
684
|
+
this.identities.delete(base);
|
|
685
|
+
throw error;
|
|
686
|
+
});
|
|
687
|
+
this.identities.set(base, inFlight);
|
|
688
|
+
return inFlight;
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Drop a cached identity — one endpoint's, or every endpoint's when
|
|
692
|
+
* `endpoint` is omitted. The way to react to a key rotation.
|
|
693
|
+
*/
|
|
694
|
+
invalidateIdentity(endpoint) {
|
|
695
|
+
if (endpoint === void 0) {
|
|
696
|
+
this.identities.clear();
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
this.identities.delete(connectorEdgeBaseUrl(endpoint));
|
|
700
|
+
}
|
|
701
|
+
/** Whether an identity for `endpoint` is already held (no request is made). */
|
|
702
|
+
hasCachedIdentity(endpoint) {
|
|
703
|
+
return this.identities.has(connectorEdgeBaseUrl(endpoint));
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* What `destination` costs at this connector, or `null` when the connector
|
|
707
|
+
* answers `404` — no locally-terminated route matches it.
|
|
708
|
+
*
|
|
709
|
+
* `null` is the answer to "you do not terminate this", which is information;
|
|
710
|
+
* a transport failure throws {@link NetworkError} instead, so a caller can
|
|
711
|
+
* always tell "not mine" from "could not ask".
|
|
712
|
+
*
|
|
713
|
+
* Fetched once per (endpoint, destination) and reused. ADR 0020 makes a
|
|
714
|
+
* price flat per handler, so it does not vary with the packet — a route
|
|
715
|
+
* being repriced is an operator event, and {@link invalidateRoutePrice} is
|
|
716
|
+
* how a caller reacts to one.
|
|
717
|
+
*
|
|
718
|
+
* @param options `forceRefresh` bypasses (and replaces) the cache entry.
|
|
719
|
+
*/
|
|
720
|
+
async getRoutePrice(endpoint, destination, options = {}) {
|
|
721
|
+
if (typeof destination !== "string" || destination.trim().length === 0) {
|
|
722
|
+
throw new ConnectorEdgeError(
|
|
723
|
+
"a route price needs a non-empty ILP destination",
|
|
724
|
+
"INVALID_DESTINATION"
|
|
725
|
+
);
|
|
726
|
+
}
|
|
727
|
+
const base = connectorEdgeBaseUrl(endpoint);
|
|
728
|
+
const key2 = priceCacheKey(base, destination);
|
|
729
|
+
if (options.forceRefresh) this.prices.delete(key2);
|
|
730
|
+
const cached = this.prices.get(key2);
|
|
731
|
+
if (cached) return cached;
|
|
732
|
+
const inFlight = this.fetchRoutePrice(base, destination).catch(
|
|
733
|
+
(error) => {
|
|
734
|
+
this.prices.delete(key2);
|
|
735
|
+
throw error;
|
|
736
|
+
}
|
|
737
|
+
);
|
|
738
|
+
this.prices.set(key2, inFlight);
|
|
739
|
+
return inFlight;
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* Drop a cached route price — one (endpoint, destination)'s, every
|
|
743
|
+
* destination's at one endpoint when `destination` is omitted, or all of
|
|
744
|
+
* them when both are. The way to react to a route being repriced.
|
|
745
|
+
*/
|
|
746
|
+
invalidateRoutePrice(endpoint, destination) {
|
|
747
|
+
if (endpoint === void 0) {
|
|
748
|
+
this.prices.clear();
|
|
749
|
+
return;
|
|
750
|
+
}
|
|
751
|
+
const base = connectorEdgeBaseUrl(endpoint);
|
|
752
|
+
if (destination !== void 0) {
|
|
753
|
+
this.prices.delete(priceCacheKey(base, destination));
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
const prefix = priceCacheKeyPrefix(base);
|
|
757
|
+
for (const key2 of this.prices.keys()) {
|
|
758
|
+
if (key2.startsWith(prefix)) this.prices.delete(key2);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* Whether a price for `(endpoint, destination)` is already held (no request
|
|
763
|
+
* is made).
|
|
764
|
+
*/
|
|
765
|
+
hasCachedRoutePrice(endpoint, destination) {
|
|
766
|
+
return this.prices.has(
|
|
767
|
+
priceCacheKey(connectorEdgeBaseUrl(endpoint), destination)
|
|
768
|
+
);
|
|
769
|
+
}
|
|
770
|
+
async fetchRoutePrice(base, destination) {
|
|
771
|
+
const url = `${base}/ilp/routes/price?destination=${encodeURIComponent(destination)}`;
|
|
772
|
+
const response = await this.get(url);
|
|
773
|
+
if (response.status === 404) return null;
|
|
774
|
+
if (!response.ok) {
|
|
775
|
+
throw new ConnectorEdgeError(
|
|
776
|
+
`GET /ilp/routes/price answered ${response.status}`,
|
|
777
|
+
"ROUTE_PRICE_HTTP_STATUS"
|
|
778
|
+
);
|
|
779
|
+
}
|
|
780
|
+
return parseConnectorRoutePrice(
|
|
781
|
+
await this.readJson(response, "ROUTE_PRICE_MALFORMED")
|
|
782
|
+
);
|
|
783
|
+
}
|
|
784
|
+
async fetchIdentity(base) {
|
|
785
|
+
const response = await this.get(`${base}/ilp/identity`);
|
|
786
|
+
if (!response.ok) {
|
|
787
|
+
throw new ConnectorEdgeError(
|
|
788
|
+
`GET /ilp/identity answered ${response.status}`,
|
|
789
|
+
"IDENTITY_HTTP_STATUS"
|
|
790
|
+
);
|
|
791
|
+
}
|
|
792
|
+
return parseConnectorIdentity(
|
|
793
|
+
await this.readJson(response, "IDENTITY_MALFORMED"),
|
|
794
|
+
base
|
|
795
|
+
);
|
|
796
|
+
}
|
|
797
|
+
async readJson(response, code) {
|
|
798
|
+
try {
|
|
799
|
+
return await response.json();
|
|
800
|
+
} catch (error) {
|
|
801
|
+
throw new ConnectorEdgeError(
|
|
802
|
+
"connector answered a body that is not JSON",
|
|
803
|
+
code,
|
|
804
|
+
error instanceof Error ? error : void 0
|
|
805
|
+
);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
/** GET with a timeout, mapping any transport failure onto {@link NetworkError}. */
|
|
809
|
+
async get(url) {
|
|
810
|
+
const controller = new AbortController();
|
|
811
|
+
const timer = setTimeout(() => controller.abort(), this.timeout);
|
|
812
|
+
try {
|
|
813
|
+
return await this.fetchImpl(url, {
|
|
814
|
+
method: "GET",
|
|
815
|
+
headers: { accept: "application/json" },
|
|
816
|
+
signal: controller.signal
|
|
817
|
+
});
|
|
818
|
+
} catch (error) {
|
|
819
|
+
throw new NetworkError(
|
|
820
|
+
`could not reach the connector client edge at ${url}`,
|
|
821
|
+
error instanceof Error ? error : void 0
|
|
822
|
+
);
|
|
823
|
+
} finally {
|
|
824
|
+
clearTimeout(timer);
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
};
|
|
551
828
|
|
|
552
|
-
// src/
|
|
553
|
-
var
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
829
|
+
// src/wire/oer.ts
|
|
830
|
+
var OerErrorKind = /* @__PURE__ */ ((OerErrorKind2) => {
|
|
831
|
+
OerErrorKind2["BufferUnderflow"] = "buffer_underflow";
|
|
832
|
+
OerErrorKind2["NonCanonicalLength"] = "non_canonical_length";
|
|
833
|
+
OerErrorKind2["LengthDeterminantOverflow"] = "length_determinant_overflow";
|
|
834
|
+
return OerErrorKind2;
|
|
835
|
+
})(OerErrorKind || {});
|
|
836
|
+
var OerError = class extends Error {
|
|
837
|
+
constructor(kind) {
|
|
838
|
+
super(OER_ERROR_MESSAGES[kind]);
|
|
839
|
+
this.kind = kind;
|
|
840
|
+
this.name = "OerError";
|
|
841
|
+
}
|
|
842
|
+
kind;
|
|
843
|
+
};
|
|
844
|
+
var OER_ERROR_MESSAGES = {
|
|
845
|
+
["buffer_underflow" /* BufferUnderflow */]: "buffer underflow: the value is truncated",
|
|
846
|
+
["non_canonical_length" /* NonCanonicalLength */]: "non-canonical OER length determinant: not the minimal encoding of its value",
|
|
847
|
+
["length_determinant_overflow" /* LengthDeterminantOverflow */]: "OER length determinant wider than 8 bytes"
|
|
848
|
+
};
|
|
849
|
+
var MAX_DETERMINANT_BYTES = 8;
|
|
850
|
+
function encodeVarUint(value) {
|
|
851
|
+
if (value < 0n)
|
|
852
|
+
throw new RangeError("VarUInt cannot encode a negative value");
|
|
853
|
+
if (value <= 127n) return Uint8Array.of(Number(value));
|
|
854
|
+
const body = [];
|
|
855
|
+
let remaining = value;
|
|
856
|
+
while (remaining > 0n) {
|
|
857
|
+
body.unshift(Number(remaining & 0xffn));
|
|
858
|
+
remaining >>= 8n;
|
|
859
|
+
}
|
|
860
|
+
if (body.length > MAX_DETERMINANT_BYTES) {
|
|
861
|
+
throw new RangeError("VarUInt cannot encode a value wider than 8 bytes");
|
|
862
|
+
}
|
|
863
|
+
return Uint8Array.from([128 | body.length, ...body]);
|
|
864
|
+
}
|
|
865
|
+
function decodeVarUint(buf, offset) {
|
|
866
|
+
const first = buf[offset];
|
|
867
|
+
if (first === void 0) throw new OerError("buffer_underflow" /* BufferUnderflow */);
|
|
868
|
+
if (first <= 127) return { value: BigInt(first), consumed: 1 };
|
|
869
|
+
const length = first & 127;
|
|
870
|
+
if (length > MAX_DETERMINANT_BYTES) {
|
|
871
|
+
throw new OerError("length_determinant_overflow" /* LengthDeterminantOverflow */);
|
|
872
|
+
}
|
|
873
|
+
const start = offset + 1;
|
|
874
|
+
const end = start + length;
|
|
875
|
+
if (end > buf.length) throw new OerError("buffer_underflow" /* BufferUnderflow */);
|
|
876
|
+
let value = 0n;
|
|
877
|
+
for (let i = start; i < end; i++) {
|
|
878
|
+
value = value << 8n | BigInt(buf[i]);
|
|
879
|
+
}
|
|
880
|
+
const consumed = 1 + length;
|
|
881
|
+
const canonical = encodeVarUint(value);
|
|
882
|
+
if (canonical.length !== consumed || !canonical.every((byte, i) => byte === buf[offset + i])) {
|
|
883
|
+
throw new OerError("non_canonical_length" /* NonCanonicalLength */);
|
|
884
|
+
}
|
|
885
|
+
return { value, consumed };
|
|
886
|
+
}
|
|
887
|
+
function encodeVarOctetString(data) {
|
|
888
|
+
const prefix = encodeVarUint(BigInt(data.length));
|
|
889
|
+
const out = new Uint8Array(prefix.length + data.length);
|
|
890
|
+
out.set(prefix, 0);
|
|
891
|
+
out.set(data, prefix.length);
|
|
892
|
+
return out;
|
|
893
|
+
}
|
|
894
|
+
function decodeVarOctetString(buf, offset) {
|
|
895
|
+
const { value: length, consumed: lengthBytes } = decodeVarUint(buf, offset);
|
|
896
|
+
if (length > BigInt(buf.length)) {
|
|
897
|
+
throw new OerError("buffer_underflow" /* BufferUnderflow */);
|
|
898
|
+
}
|
|
899
|
+
const start = offset + lengthBytes;
|
|
900
|
+
const end = start + Number(length);
|
|
901
|
+
if (end > buf.length) throw new OerError("buffer_underflow" /* BufferUnderflow */);
|
|
902
|
+
return {
|
|
903
|
+
value: buf.slice(start, end),
|
|
904
|
+
consumed: lengthBytes + Number(length)
|
|
568
905
|
};
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
// src/wire/envelope.ts
|
|
909
|
+
var TYPE_ENVELOPE_REQUEST = 1;
|
|
910
|
+
var TYPE_ENVELOPE_RESPONSE = 2;
|
|
911
|
+
var EnvelopeErrorKind = /* @__PURE__ */ ((EnvelopeErrorKind2) => {
|
|
912
|
+
EnvelopeErrorKind2["BufferUnderflow"] = "buffer_underflow";
|
|
913
|
+
EnvelopeErrorKind2["NonCanonicalLength"] = "non_canonical_length";
|
|
914
|
+
EnvelopeErrorKind2["LengthDeterminantOverflow"] = "length_determinant_overflow";
|
|
915
|
+
EnvelopeErrorKind2["InvalidType"] = "invalid_type";
|
|
916
|
+
EnvelopeErrorKind2["InvalidUtf8"] = "invalid_utf8";
|
|
917
|
+
EnvelopeErrorKind2["TrailingBytes"] = "trailing_bytes";
|
|
918
|
+
return EnvelopeErrorKind2;
|
|
919
|
+
})(EnvelopeErrorKind || {});
|
|
920
|
+
var EnvelopeError = class extends Error {
|
|
921
|
+
constructor(kind, field) {
|
|
922
|
+
super(
|
|
923
|
+
field === void 0 ? ENVELOPE_ERROR_MESSAGES[kind] : `${ENVELOPE_ERROR_MESSAGES[kind]} (field '${field}')`
|
|
924
|
+
);
|
|
925
|
+
this.kind = kind;
|
|
926
|
+
this.field = field;
|
|
927
|
+
this.name = "EnvelopeError";
|
|
928
|
+
}
|
|
929
|
+
kind;
|
|
930
|
+
field;
|
|
931
|
+
};
|
|
932
|
+
var ENVELOPE_ERROR_MESSAGES = {
|
|
933
|
+
["buffer_underflow" /* BufferUnderflow */]: "buffer underflow: envelope is truncated",
|
|
934
|
+
["non_canonical_length" /* NonCanonicalLength */]: "non-canonical OER length determinant: not the minimal encoding of its value",
|
|
935
|
+
["length_determinant_overflow" /* LengthDeterminantOverflow */]: "OER length determinant wider than 8 bytes",
|
|
936
|
+
["invalid_type" /* InvalidType */]: "invalid envelope type byte: expected 1 (REQUEST) or 2 (RESPONSE)",
|
|
937
|
+
["invalid_utf8" /* InvalidUtf8 */]: "invalid UTF-8 in envelope field",
|
|
938
|
+
["trailing_bytes" /* TrailingBytes */]: "trailing bytes after a fully decoded envelope"
|
|
939
|
+
};
|
|
940
|
+
var UTF8_ENCODER = new TextEncoder();
|
|
941
|
+
var UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
|
|
942
|
+
function fromOerError(error) {
|
|
943
|
+
if (error instanceof OerError) {
|
|
944
|
+
switch (error.kind) {
|
|
945
|
+
case "buffer_underflow" /* BufferUnderflow */:
|
|
946
|
+
return new EnvelopeError("buffer_underflow" /* BufferUnderflow */);
|
|
947
|
+
case "non_canonical_length" /* NonCanonicalLength */:
|
|
948
|
+
return new EnvelopeError("non_canonical_length" /* NonCanonicalLength */);
|
|
949
|
+
case "length_determinant_overflow" /* LengthDeterminantOverflow */:
|
|
950
|
+
return new EnvelopeError("length_determinant_overflow" /* LengthDeterminantOverflow */);
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
throw error;
|
|
954
|
+
}
|
|
955
|
+
function decodeOctets(buf, offset) {
|
|
956
|
+
try {
|
|
957
|
+
return decodeVarOctetString(buf, offset);
|
|
958
|
+
} catch (error) {
|
|
959
|
+
throw fromOerError(error);
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
function decodeCount(buf, offset) {
|
|
963
|
+
try {
|
|
964
|
+
return decodeVarUint(buf, offset);
|
|
965
|
+
} catch (error) {
|
|
966
|
+
throw fromOerError(error);
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
function decodeStringField(buf, offset, field) {
|
|
970
|
+
const { value: bytes, consumed } = decodeOctets(buf, offset);
|
|
971
|
+
try {
|
|
972
|
+
return { value: UTF8_DECODER.decode(bytes), consumed };
|
|
973
|
+
} catch {
|
|
974
|
+
throw new EnvelopeError("invalid_utf8" /* InvalidUtf8 */, field);
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
function checkTypeByte(buf, expected) {
|
|
978
|
+
const typeByte = buf[0];
|
|
979
|
+
if (typeByte === void 0) {
|
|
980
|
+
throw new EnvelopeError("buffer_underflow" /* BufferUnderflow */);
|
|
981
|
+
}
|
|
982
|
+
if (typeByte !== expected) {
|
|
983
|
+
throw new EnvelopeError("invalid_type" /* InvalidType */);
|
|
984
|
+
}
|
|
985
|
+
return 1;
|
|
986
|
+
}
|
|
987
|
+
function concat(parts) {
|
|
988
|
+
const total = parts.reduce((sum, part) => sum + part.length, 0);
|
|
989
|
+
const out = new Uint8Array(total);
|
|
990
|
+
let offset = 0;
|
|
991
|
+
for (const part of parts) {
|
|
992
|
+
out.set(part, offset);
|
|
993
|
+
offset += part.length;
|
|
994
|
+
}
|
|
995
|
+
return out;
|
|
996
|
+
}
|
|
997
|
+
function encodeHeaders(headers) {
|
|
998
|
+
const parts = [encodeVarUint(BigInt(headers.length))];
|
|
999
|
+
for (const [name, value] of headers) {
|
|
1000
|
+
parts.push(encodeVarOctetString(UTF8_ENCODER.encode(name)));
|
|
1001
|
+
parts.push(encodeVarOctetString(UTF8_ENCODER.encode(value)));
|
|
1002
|
+
}
|
|
1003
|
+
return concat(parts);
|
|
1004
|
+
}
|
|
1005
|
+
function decodeHeaders(buf, offset) {
|
|
1006
|
+
const { value: count, consumed: countBytes } = decodeCount(buf, offset);
|
|
1007
|
+
if (count * 2n > BigInt(buf.length - offset - countBytes)) {
|
|
1008
|
+
throw new EnvelopeError("buffer_underflow" /* BufferUnderflow */);
|
|
1009
|
+
}
|
|
1010
|
+
let consumed = countBytes;
|
|
1011
|
+
const headers = [];
|
|
1012
|
+
for (let i = 0n; i < count; i++) {
|
|
1013
|
+
const name = decodeStringField(buf, offset + consumed, "header name");
|
|
1014
|
+
consumed += name.consumed;
|
|
1015
|
+
const value = decodeStringField(buf, offset + consumed, "header value");
|
|
1016
|
+
consumed += value.consumed;
|
|
1017
|
+
headers.push([name.value, value.value]);
|
|
1018
|
+
}
|
|
1019
|
+
return { value: headers, consumed };
|
|
1020
|
+
}
|
|
1021
|
+
function encodeEnvelopeRequest(request) {
|
|
1022
|
+
return concat([
|
|
1023
|
+
Uint8Array.of(TYPE_ENVELOPE_REQUEST),
|
|
1024
|
+
encodeVarOctetString(UTF8_ENCODER.encode(request.method)),
|
|
1025
|
+
encodeVarOctetString(UTF8_ENCODER.encode(request.target)),
|
|
1026
|
+
encodeHeaders(request.headers),
|
|
1027
|
+
encodeVarOctetString(request.body)
|
|
1028
|
+
]);
|
|
1029
|
+
}
|
|
1030
|
+
function decodeEnvelopeRequest(buf) {
|
|
1031
|
+
let offset = checkTypeByte(buf, TYPE_ENVELOPE_REQUEST);
|
|
1032
|
+
const method = decodeStringField(buf, offset, "method");
|
|
1033
|
+
offset += method.consumed;
|
|
1034
|
+
const target = decodeStringField(buf, offset, "target");
|
|
1035
|
+
offset += target.consumed;
|
|
1036
|
+
const headers = decodeHeaders(buf, offset);
|
|
1037
|
+
offset += headers.consumed;
|
|
1038
|
+
const body = decodeOctets(buf, offset);
|
|
1039
|
+
offset += body.consumed;
|
|
1040
|
+
if (offset !== buf.length) {
|
|
1041
|
+
throw new EnvelopeError("trailing_bytes" /* TrailingBytes */);
|
|
1042
|
+
}
|
|
579
1043
|
return {
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
body:
|
|
1044
|
+
method: method.value,
|
|
1045
|
+
target: target.value,
|
|
1046
|
+
headers: headers.value,
|
|
1047
|
+
body: body.value
|
|
584
1048
|
};
|
|
585
1049
|
}
|
|
586
|
-
function
|
|
587
|
-
|
|
1050
|
+
function encodeEnvelopeResponse(response) {
|
|
1051
|
+
if (!Number.isInteger(response.status) || response.status < 0 || response.status > 65535) {
|
|
1052
|
+
throw new RangeError(
|
|
1053
|
+
`envelope status must fit two bytes, got ${response.status}`
|
|
1054
|
+
);
|
|
1055
|
+
}
|
|
1056
|
+
return concat([
|
|
1057
|
+
Uint8Array.of(
|
|
1058
|
+
TYPE_ENVELOPE_RESPONSE,
|
|
1059
|
+
response.status >> 8 & 255,
|
|
1060
|
+
response.status & 255
|
|
1061
|
+
),
|
|
1062
|
+
encodeHeaders(response.headers),
|
|
1063
|
+
encodeVarOctetString(response.body)
|
|
1064
|
+
]);
|
|
1065
|
+
}
|
|
1066
|
+
function decodeEnvelopeResponse(buf) {
|
|
1067
|
+
let offset = checkTypeByte(buf, TYPE_ENVELOPE_RESPONSE);
|
|
1068
|
+
const high = buf[offset];
|
|
1069
|
+
const low = buf[offset + 1];
|
|
1070
|
+
if (high === void 0 || low === void 0) {
|
|
1071
|
+
throw new EnvelopeError("buffer_underflow" /* BufferUnderflow */);
|
|
1072
|
+
}
|
|
1073
|
+
const status = high << 8 | low;
|
|
1074
|
+
offset += 2;
|
|
1075
|
+
const headers = decodeHeaders(buf, offset);
|
|
1076
|
+
offset += headers.consumed;
|
|
1077
|
+
const body = decodeOctets(buf, offset);
|
|
1078
|
+
offset += body.consumed;
|
|
1079
|
+
if (offset !== buf.length) {
|
|
1080
|
+
throw new EnvelopeError("trailing_bytes" /* TrailingBytes */);
|
|
1081
|
+
}
|
|
1082
|
+
return { status, headers: headers.value, body: body.value };
|
|
1083
|
+
}
|
|
1084
|
+
function encodeEnvelope(envelope) {
|
|
1085
|
+
return envelope.direction === "request" ? encodeEnvelopeRequest(envelope) : encodeEnvelopeResponse(envelope);
|
|
1086
|
+
}
|
|
1087
|
+
function decodeEnvelope(buf, direction) {
|
|
1088
|
+
return direction === "request" ? { direction, ...decodeEnvelopeRequest(buf) } : { direction, ...decodeEnvelopeResponse(buf) };
|
|
1089
|
+
}
|
|
1090
|
+
|
|
1091
|
+
// src/wire/giftwrap.ts
|
|
1092
|
+
import { secp256k1 } from "@noble/curves/secp256k1.js";
|
|
1093
|
+
import { chacha20poly1305 } from "@noble/ciphers/chacha.js";
|
|
1094
|
+
import { hkdf } from "@noble/hashes/hkdf.js";
|
|
1095
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
1096
|
+
import { randomBytes } from "@noble/hashes/utils.js";
|
|
1097
|
+
var GIFTWRAP_NONCE_LENGTH = 12;
|
|
1098
|
+
var GIFTWRAP_SECRET_LENGTH = 32;
|
|
1099
|
+
var GIFTWRAP_PUBLIC_KEY_LENGTH = 65;
|
|
1100
|
+
var REQUEST_INFO = "toon-giftwrap-request";
|
|
1101
|
+
var RESPONSE_INFO = "toon-giftwrap-response";
|
|
1102
|
+
var FULFILLMENT_INFO = "toon-giftwrap-fulfillment";
|
|
1103
|
+
var GIFTWRAP_TYPE_REQUEST = 1;
|
|
1104
|
+
var GIFTWRAP_TYPE_RESPONSE = 2;
|
|
1105
|
+
var TAG_LENGTH = 16;
|
|
1106
|
+
var GiftWrapErrorKind = /* @__PURE__ */ ((GiftWrapErrorKind2) => {
|
|
1107
|
+
GiftWrapErrorKind2["InvalidType"] = "invalid_type";
|
|
1108
|
+
GiftWrapErrorKind2["Truncated"] = "truncated";
|
|
1109
|
+
GiftWrapErrorKind2["InvalidKey"] = "invalid_key";
|
|
1110
|
+
GiftWrapErrorKind2["OpenFailed"] = "open_failed";
|
|
1111
|
+
return GiftWrapErrorKind2;
|
|
1112
|
+
})(GiftWrapErrorKind || {});
|
|
1113
|
+
var GIFTWRAP_ERROR_MESSAGES = {
|
|
1114
|
+
["invalid_type" /* InvalidType */]: "invalid gift wrap type byte",
|
|
1115
|
+
["truncated" /* Truncated */]: "gift wrap is truncated",
|
|
1116
|
+
["invalid_key" /* InvalidKey */]: "invalid ephemeral or peer public key",
|
|
1117
|
+
["open_failed" /* OpenFailed */]: "gift wrap failed to decrypt"
|
|
1118
|
+
};
|
|
1119
|
+
var GiftWrapError = class extends Error {
|
|
1120
|
+
constructor(kind, expectedType) {
|
|
1121
|
+
super(
|
|
1122
|
+
expectedType === void 0 ? GIFTWRAP_ERROR_MESSAGES[kind] : `${GIFTWRAP_ERROR_MESSAGES[kind]}: expected ${expectedType}`
|
|
1123
|
+
);
|
|
1124
|
+
this.kind = kind;
|
|
1125
|
+
this.expectedType = expectedType;
|
|
1126
|
+
this.name = "GiftWrapError";
|
|
1127
|
+
}
|
|
1128
|
+
kind;
|
|
1129
|
+
expectedType;
|
|
1130
|
+
};
|
|
1131
|
+
function concat2(parts) {
|
|
1132
|
+
const total = parts.reduce((sum, part) => sum + part.length, 0);
|
|
1133
|
+
const out = new Uint8Array(total);
|
|
1134
|
+
let offset = 0;
|
|
1135
|
+
for (const part of parts) {
|
|
1136
|
+
out.set(part, offset);
|
|
1137
|
+
offset += part.length;
|
|
1138
|
+
}
|
|
1139
|
+
return out;
|
|
1140
|
+
}
|
|
1141
|
+
function hkdfKey(ikm, info) {
|
|
1142
|
+
return hkdf(sha256, ikm, void 0, info, 32);
|
|
1143
|
+
}
|
|
1144
|
+
function encryptWithNonce(key2, plaintext, nonce) {
|
|
1145
|
+
return concat2([nonce, chacha20poly1305(key2, nonce).encrypt(plaintext)]);
|
|
1146
|
+
}
|
|
1147
|
+
function decrypt(key2, nonceAndCiphertext) {
|
|
1148
|
+
if (nonceAndCiphertext.length < GIFTWRAP_NONCE_LENGTH) {
|
|
1149
|
+
throw new GiftWrapError("truncated" /* Truncated */);
|
|
1150
|
+
}
|
|
1151
|
+
const nonce = nonceAndCiphertext.subarray(0, GIFTWRAP_NONCE_LENGTH);
|
|
1152
|
+
const ciphertext = nonceAndCiphertext.subarray(GIFTWRAP_NONCE_LENGTH);
|
|
1153
|
+
if (ciphertext.length < TAG_LENGTH) {
|
|
1154
|
+
throw new GiftWrapError("truncated" /* Truncated */);
|
|
1155
|
+
}
|
|
1156
|
+
try {
|
|
1157
|
+
return chacha20poly1305(key2, nonce).decrypt(ciphertext);
|
|
1158
|
+
} catch {
|
|
1159
|
+
throw new GiftWrapError("open_failed" /* OpenFailed */);
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
function ecdhXCoordinate(secretKey, publicKey) {
|
|
1163
|
+
let compressed;
|
|
1164
|
+
try {
|
|
1165
|
+
compressed = secp256k1.getSharedSecret(secretKey, publicKey, true);
|
|
1166
|
+
} catch {
|
|
1167
|
+
throw new GiftWrapError("invalid_key" /* InvalidKey */);
|
|
1168
|
+
}
|
|
1169
|
+
return compressed.slice(1);
|
|
1170
|
+
}
|
|
1171
|
+
function localGiftWrapEcdh(secretKey) {
|
|
1172
|
+
return {
|
|
1173
|
+
ecdh: (ephemeralPublicKey) => ecdhXCoordinate(secretKey, ephemeralPublicKey)
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
function sealRequestWithRandomness(plaintext, receiverPublicKey, ephemeralSecretKey, sharedSecret, nonce) {
|
|
1177
|
+
if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {
|
|
1178
|
+
throw new GiftWrapError("truncated" /* Truncated */);
|
|
1179
|
+
}
|
|
1180
|
+
if (nonce.length !== GIFTWRAP_NONCE_LENGTH) {
|
|
1181
|
+
throw new GiftWrapError("truncated" /* Truncated */);
|
|
1182
|
+
}
|
|
1183
|
+
let ephemeralPublicKey;
|
|
1184
|
+
try {
|
|
1185
|
+
ephemeralPublicKey = secp256k1.getPublicKey(ephemeralSecretKey, false);
|
|
1186
|
+
} catch {
|
|
1187
|
+
throw new GiftWrapError("invalid_key" /* InvalidKey */);
|
|
1188
|
+
}
|
|
1189
|
+
const aeadKey = hkdfKey(
|
|
1190
|
+
ecdhXCoordinate(ephemeralSecretKey, receiverPublicKey),
|
|
1191
|
+
REQUEST_INFO
|
|
1192
|
+
);
|
|
1193
|
+
const inner = concat2([sharedSecret, plaintext]);
|
|
1194
|
+
return concat2([
|
|
1195
|
+
Uint8Array.of(GIFTWRAP_TYPE_REQUEST),
|
|
1196
|
+
ephemeralPublicKey,
|
|
1197
|
+
encryptWithNonce(aeadKey, inner, nonce)
|
|
1198
|
+
]);
|
|
1199
|
+
}
|
|
1200
|
+
function sealRequest(plaintext, receiverPublicKey) {
|
|
1201
|
+
const ephemeralSecretKey = secp256k1.utils.randomSecretKey();
|
|
1202
|
+
const sharedSecret = randomBytes(GIFTWRAP_SECRET_LENGTH);
|
|
1203
|
+
const nonce = randomBytes(GIFTWRAP_NONCE_LENGTH);
|
|
1204
|
+
return {
|
|
1205
|
+
wrapped: sealRequestWithRandomness(
|
|
1206
|
+
plaintext,
|
|
1207
|
+
receiverPublicKey,
|
|
1208
|
+
ephemeralSecretKey,
|
|
1209
|
+
sharedSecret,
|
|
1210
|
+
nonce
|
|
1211
|
+
),
|
|
1212
|
+
sharedSecret
|
|
1213
|
+
};
|
|
1214
|
+
}
|
|
1215
|
+
function openRequest(bytes, identity) {
|
|
1216
|
+
if (bytes.length === 0) {
|
|
1217
|
+
throw new GiftWrapError("truncated" /* Truncated */);
|
|
1218
|
+
}
|
|
1219
|
+
if (bytes[0] !== GIFTWRAP_TYPE_REQUEST) {
|
|
1220
|
+
throw new GiftWrapError(
|
|
1221
|
+
"invalid_type" /* InvalidType */,
|
|
1222
|
+
GIFTWRAP_TYPE_REQUEST
|
|
1223
|
+
);
|
|
1224
|
+
}
|
|
1225
|
+
if (bytes.length < 1 + GIFTWRAP_PUBLIC_KEY_LENGTH) {
|
|
1226
|
+
throw new GiftWrapError("truncated" /* Truncated */);
|
|
1227
|
+
}
|
|
1228
|
+
const ephemeralPublicKey = bytes.slice(1, 1 + GIFTWRAP_PUBLIC_KEY_LENGTH);
|
|
1229
|
+
const ciphertext = bytes.subarray(1 + GIFTWRAP_PUBLIC_KEY_LENGTH);
|
|
1230
|
+
const agreement = identity instanceof Uint8Array ? localGiftWrapEcdh(identity) : identity;
|
|
1231
|
+
let ecdhSecret;
|
|
1232
|
+
try {
|
|
1233
|
+
ecdhSecret = agreement.ecdh(ephemeralPublicKey);
|
|
1234
|
+
} catch (error) {
|
|
1235
|
+
throw error instanceof GiftWrapError ? error : new GiftWrapError("invalid_key" /* InvalidKey */);
|
|
1236
|
+
}
|
|
1237
|
+
const plaintext = decrypt(hkdfKey(ecdhSecret, REQUEST_INFO), ciphertext);
|
|
1238
|
+
if (plaintext.length < GIFTWRAP_SECRET_LENGTH) {
|
|
1239
|
+
throw new GiftWrapError("truncated" /* Truncated */);
|
|
1240
|
+
}
|
|
1241
|
+
return {
|
|
1242
|
+
envelopeBytes: plaintext.slice(GIFTWRAP_SECRET_LENGTH),
|
|
1243
|
+
sharedSecret: plaintext.slice(0, GIFTWRAP_SECRET_LENGTH)
|
|
1244
|
+
};
|
|
1245
|
+
}
|
|
1246
|
+
function sealResponseWithRandomness(sharedSecret, plaintext, nonce) {
|
|
1247
|
+
if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {
|
|
1248
|
+
throw new GiftWrapError("truncated" /* Truncated */);
|
|
1249
|
+
}
|
|
1250
|
+
if (nonce.length !== GIFTWRAP_NONCE_LENGTH) {
|
|
1251
|
+
throw new GiftWrapError("truncated" /* Truncated */);
|
|
1252
|
+
}
|
|
1253
|
+
return concat2([
|
|
1254
|
+
Uint8Array.of(GIFTWRAP_TYPE_RESPONSE),
|
|
1255
|
+
encryptWithNonce(hkdfKey(sharedSecret, RESPONSE_INFO), plaintext, nonce)
|
|
1256
|
+
]);
|
|
1257
|
+
}
|
|
1258
|
+
function sealResponse(sharedSecret, plaintext) {
|
|
1259
|
+
return sealResponseWithRandomness(
|
|
1260
|
+
sharedSecret,
|
|
1261
|
+
plaintext,
|
|
1262
|
+
randomBytes(GIFTWRAP_NONCE_LENGTH)
|
|
1263
|
+
);
|
|
1264
|
+
}
|
|
1265
|
+
function openResponse(sharedSecret, bytes) {
|
|
1266
|
+
if (bytes.length === 0) {
|
|
1267
|
+
throw new GiftWrapError("truncated" /* Truncated */);
|
|
1268
|
+
}
|
|
1269
|
+
if (bytes[0] !== GIFTWRAP_TYPE_RESPONSE) {
|
|
1270
|
+
throw new GiftWrapError(
|
|
1271
|
+
"invalid_type" /* InvalidType */,
|
|
1272
|
+
GIFTWRAP_TYPE_RESPONSE
|
|
1273
|
+
);
|
|
1274
|
+
}
|
|
1275
|
+
if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {
|
|
1276
|
+
throw new GiftWrapError("truncated" /* Truncated */);
|
|
1277
|
+
}
|
|
1278
|
+
return decrypt(hkdfKey(sharedSecret, RESPONSE_INFO), bytes.subarray(1));
|
|
1279
|
+
}
|
|
1280
|
+
function looksLikeSealedResponse(bytes) {
|
|
1281
|
+
return bytes.length > 0 && bytes[0] === GIFTWRAP_TYPE_RESPONSE;
|
|
1282
|
+
}
|
|
1283
|
+
function deriveFulfillment(sharedSecret) {
|
|
1284
|
+
if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {
|
|
1285
|
+
throw new GiftWrapError("truncated" /* Truncated */);
|
|
1286
|
+
}
|
|
1287
|
+
return hkdfKey(sharedSecret, FULFILLMENT_INFO);
|
|
1288
|
+
}
|
|
1289
|
+
function deriveCondition(fulfillment) {
|
|
1290
|
+
return sha256(fulfillment);
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
// src/wire/sealed-exchange.ts
|
|
1294
|
+
var SealedResponseError = class extends Error {
|
|
1295
|
+
constructor(kind, message, cause) {
|
|
1296
|
+
super(message);
|
|
1297
|
+
this.kind = kind;
|
|
1298
|
+
this.cause = cause;
|
|
1299
|
+
this.name = "SealedResponseError";
|
|
1300
|
+
}
|
|
1301
|
+
kind;
|
|
1302
|
+
cause;
|
|
1303
|
+
};
|
|
1304
|
+
function sealExchange(request, connectorPublicKey) {
|
|
1305
|
+
const { wrapped, sharedSecret } = sealRequest(
|
|
1306
|
+
encodeEnvelopeRequest(request),
|
|
1307
|
+
connectorPublicKey
|
|
1308
|
+
);
|
|
1309
|
+
const fulfillment = deriveFulfillment(sharedSecret);
|
|
1310
|
+
return {
|
|
1311
|
+
data: wrapped,
|
|
1312
|
+
condition: deriveCondition(fulfillment),
|
|
1313
|
+
sharedSecret,
|
|
1314
|
+
fulfillment
|
|
1315
|
+
};
|
|
1316
|
+
}
|
|
1317
|
+
function readExchangeOutcome(result, data, sharedSecret) {
|
|
1318
|
+
if (result.accepted) {
|
|
1319
|
+
return { kind: "answered", response: openAnswer(data, sharedSecret) };
|
|
1320
|
+
}
|
|
1321
|
+
const code = result.code ?? "F00";
|
|
1322
|
+
const message = result.message ?? "";
|
|
1323
|
+
if (data !== void 0 && looksLikeSealedResponse(data)) {
|
|
1324
|
+
try {
|
|
1325
|
+
return {
|
|
1326
|
+
kind: "destination-refused",
|
|
1327
|
+
code,
|
|
1328
|
+
message,
|
|
1329
|
+
detail: openResponse(sharedSecret, data)
|
|
1330
|
+
};
|
|
1331
|
+
} catch (error) {
|
|
1332
|
+
if (!(error instanceof GiftWrapError)) throw error;
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
return { kind: "path-refused", code, message };
|
|
1336
|
+
}
|
|
1337
|
+
function openAnswer(data, sharedSecret) {
|
|
1338
|
+
if (data === void 0 || data.length === 0) {
|
|
1339
|
+
throw new SealedResponseError(
|
|
1340
|
+
"not-sealed",
|
|
1341
|
+
"FULFILL carried no data; a terminated route always seals a response envelope"
|
|
1342
|
+
);
|
|
1343
|
+
}
|
|
1344
|
+
if (!looksLikeSealedResponse(data)) {
|
|
1345
|
+
throw new SealedResponseError(
|
|
1346
|
+
"not-sealed",
|
|
1347
|
+
`FULFILL data is not a sealed response (leading byte 0x${(data[0] ?? 0).toString(16).padStart(2, "0")}, expected 0x02)`
|
|
1348
|
+
);
|
|
1349
|
+
}
|
|
1350
|
+
let opened;
|
|
1351
|
+
try {
|
|
1352
|
+
opened = openResponse(sharedSecret, data);
|
|
1353
|
+
} catch (error) {
|
|
1354
|
+
if (!(error instanceof GiftWrapError)) throw error;
|
|
1355
|
+
throw new SealedResponseError(
|
|
1356
|
+
"unopenable",
|
|
1357
|
+
"FULFILL data did not open under this packet's shared secret",
|
|
1358
|
+
error
|
|
1359
|
+
);
|
|
1360
|
+
}
|
|
1361
|
+
try {
|
|
1362
|
+
return decodeEnvelopeResponse(opened);
|
|
1363
|
+
} catch (error) {
|
|
1364
|
+
if (!(error instanceof EnvelopeError)) throw error;
|
|
1365
|
+
throw new SealedResponseError(
|
|
1366
|
+
"malformed-envelope",
|
|
1367
|
+
`sealed answer opened but did not decode as a response envelope: ${error.message}`,
|
|
1368
|
+
error
|
|
1369
|
+
);
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
function envelopeHeader(response, name) {
|
|
1373
|
+
const wanted = name.toLowerCase();
|
|
1374
|
+
for (const [header, value] of response.headers) {
|
|
1375
|
+
if (header.toLowerCase() === wanted) return value;
|
|
1376
|
+
}
|
|
1377
|
+
return void 0;
|
|
588
1378
|
}
|
|
589
1379
|
|
|
590
1380
|
// src/modes/http.ts
|
|
@@ -791,7 +1581,7 @@ var ILPPacketType = {
|
|
|
791
1581
|
FULFILL: 13,
|
|
792
1582
|
REJECT: 14
|
|
793
1583
|
};
|
|
794
|
-
function
|
|
1584
|
+
function concat3(...arrays) {
|
|
795
1585
|
const totalLength = arrays.reduce((sum, a) => sum + a.length, 0);
|
|
796
1586
|
const result = new Uint8Array(totalLength);
|
|
797
1587
|
let offset = 0;
|
|
@@ -858,10 +1648,10 @@ function decodeVarUInt(buf, offset) {
|
|
|
858
1648
|
}
|
|
859
1649
|
return { value, bytesRead: 1 + length };
|
|
860
1650
|
}
|
|
861
|
-
function
|
|
862
|
-
return
|
|
1651
|
+
function encodeVarOctetString2(data) {
|
|
1652
|
+
return concat3(encodeVarUInt(BigInt(data.length)), data);
|
|
863
1653
|
}
|
|
864
|
-
function
|
|
1654
|
+
function decodeVarOctetString2(buf, offset) {
|
|
865
1655
|
const { value: length, bytesRead: lenBytes } = decodeVarUInt(buf, offset);
|
|
866
1656
|
const dataLen = Number(length);
|
|
867
1657
|
const start = offset + lenBytes;
|
|
@@ -884,13 +1674,13 @@ function encodeGeneralizedTime(date) {
|
|
|
884
1674
|
}
|
|
885
1675
|
function serializeIlpPrepare(packet) {
|
|
886
1676
|
const condition = packet.executionCondition.length === 32 ? packet.executionCondition : new Uint8Array(32);
|
|
887
|
-
return
|
|
1677
|
+
return concat3(
|
|
888
1678
|
writeUint8(ILPPacketType.PREPARE),
|
|
889
1679
|
encodeVarUInt(packet.amount),
|
|
890
1680
|
encodeGeneralizedTime(packet.expiresAt),
|
|
891
1681
|
condition,
|
|
892
|
-
|
|
893
|
-
|
|
1682
|
+
encodeVarOctetString2(textEncoder.encode(packet.destination)),
|
|
1683
|
+
encodeVarOctetString2(packet.data)
|
|
894
1684
|
);
|
|
895
1685
|
}
|
|
896
1686
|
function deserializeIlpPacket(buf) {
|
|
@@ -907,22 +1697,22 @@ function deserializeIlpFulfill(buf) {
|
|
|
907
1697
|
}
|
|
908
1698
|
const fulfillment = buf.slice(offset, offset + 32);
|
|
909
1699
|
offset += 32;
|
|
910
|
-
const { value: data } =
|
|
1700
|
+
const { value: data } = decodeVarOctetString2(buf, offset);
|
|
911
1701
|
return { type: ILPPacketType.FULFILL, fulfillment, data };
|
|
912
1702
|
}
|
|
913
1703
|
function deserializeIlpReject(buf) {
|
|
914
1704
|
let offset = 1;
|
|
915
1705
|
const code = sliceUtf8(buf, offset, 3);
|
|
916
1706
|
offset += 3;
|
|
917
|
-
const { bytesRead: tbBytes } =
|
|
1707
|
+
const { bytesRead: tbBytes } = decodeVarOctetString2(buf, offset);
|
|
918
1708
|
offset += tbBytes;
|
|
919
|
-
const { value: msgBuf, bytesRead: msgBytes } =
|
|
1709
|
+
const { value: msgBuf, bytesRead: msgBytes } = decodeVarOctetString2(
|
|
920
1710
|
buf,
|
|
921
1711
|
offset
|
|
922
1712
|
);
|
|
923
1713
|
offset += msgBytes;
|
|
924
1714
|
const message = textDecoder.decode(msgBuf);
|
|
925
|
-
const { value: data } =
|
|
1715
|
+
const { value: data } = decodeVarOctetString2(buf, offset);
|
|
926
1716
|
return { type: ILPPacketType.REJECT, code, message, data };
|
|
927
1717
|
}
|
|
928
1718
|
function serializeBtpMessage(message) {
|
|
@@ -944,7 +1734,7 @@ function serializeBtpMessage(message) {
|
|
|
944
1734
|
const ilpPacket = data.ilpPacket ?? new Uint8Array(0);
|
|
945
1735
|
parts.push(writeUint32BE(ilpPacket.length));
|
|
946
1736
|
if (ilpPacket.length > 0) parts.push(ilpPacket);
|
|
947
|
-
return
|
|
1737
|
+
return concat3(...parts);
|
|
948
1738
|
}
|
|
949
1739
|
function parseBtpMessage(buf) {
|
|
950
1740
|
if (buf.length < 5) throw new Error("BTP message too short");
|
|
@@ -1289,12 +2079,12 @@ var IsomorphicBtpClient = class {
|
|
|
1289
2079
|
};
|
|
1290
2080
|
|
|
1291
2081
|
// src/utils/condition.ts
|
|
1292
|
-
import { sha256 } from "@noble/hashes/sha2.js";
|
|
1293
|
-
import { randomBytes } from "@noble/hashes/utils.js";
|
|
2082
|
+
import { sha256 as sha2562 } from "@noble/hashes/sha2.js";
|
|
2083
|
+
import { randomBytes as randomBytes2 } from "@noble/hashes/utils.js";
|
|
1294
2084
|
var CONDITION_LENGTH = 32;
|
|
1295
2085
|
function mintExecutionCondition() {
|
|
1296
|
-
const preimage =
|
|
1297
|
-
return { preimage, condition:
|
|
2086
|
+
const preimage = randomBytes2(CONDITION_LENGTH);
|
|
2087
|
+
return { preimage, condition: sha2562(preimage) };
|
|
1298
2088
|
}
|
|
1299
2089
|
function isZeroCondition(condition) {
|
|
1300
2090
|
if (condition === void 0) return true;
|
|
@@ -1314,7 +2104,7 @@ function fulfillmentMatchesCondition(fulfillment, condition) {
|
|
|
1314
2104
|
if (fulfillment === void 0 || fulfillment.length !== CONDITION_LENGTH) {
|
|
1315
2105
|
return false;
|
|
1316
2106
|
}
|
|
1317
|
-
const digest =
|
|
2107
|
+
const digest = sha2562(fulfillment);
|
|
1318
2108
|
for (let i = 0; i < CONDITION_LENGTH; i++) {
|
|
1319
2109
|
if (digest[i] !== condition[i]) return false;
|
|
1320
2110
|
}
|
|
@@ -1537,7 +2327,6 @@ var BtpRuntimeClient = class {
|
|
|
1537
2327
|
|
|
1538
2328
|
// src/adapters/HttpIlpClient.ts
|
|
1539
2329
|
var ILP_CLAIM_HEADER = "ILP-Payment-Channel-Claim";
|
|
1540
|
-
var ILP_CLAIM_WRAPPED_HEADER = "ILP-Payment-Channel-Claim-Wrapped";
|
|
1541
2330
|
var ILP_PEER_ID_HEADER = "ILP-Peer-Id";
|
|
1542
2331
|
var HttpIlpClient = class {
|
|
1543
2332
|
httpEndpoint;
|
|
@@ -1559,6 +2348,15 @@ var HttpIlpClient = class {
|
|
|
1559
2348
|
this.httpClient = config.httpClient ?? fetch;
|
|
1560
2349
|
this.createWebSocket = config.createWebSocket;
|
|
1561
2350
|
}
|
|
2351
|
+
/**
|
|
2352
|
+
* The client edge this transport pays — the origin `GET /ilp/identity` and
|
|
2353
|
+
* `GET /ilp/routes/price` hang off (`ConnectorEdgeClient` normalizes the
|
|
2354
|
+
* trailing `/ilp` away). Exposed because a sealed write must ask the
|
|
2355
|
+
* connector it is ACTUALLY paying for its key, not a configured guess.
|
|
2356
|
+
*/
|
|
2357
|
+
get clientEdgeEndpoint() {
|
|
2358
|
+
return this.httpEndpoint;
|
|
2359
|
+
}
|
|
1562
2360
|
/**
|
|
1563
2361
|
* Send an ILP PREPARE via `POST /ilp` WITHOUT a claim. The connector accepts
|
|
1564
2362
|
* this only on free/zero-amount routes; paid writes must use
|
|
@@ -1780,7 +2578,7 @@ import { base58Encode as base58Encode2 } from "@toon-protocol/core";
|
|
|
1780
2578
|
|
|
1781
2579
|
// src/channel/solana-payment-channel.ts
|
|
1782
2580
|
import { ed25519 } from "@noble/curves/ed25519.js";
|
|
1783
|
-
import { sha256 as
|
|
2581
|
+
import { sha256 as sha2563 } from "@noble/hashes/sha2.js";
|
|
1784
2582
|
import { base58Encode, base58Decode } from "@toon-protocol/core";
|
|
1785
2583
|
var TOKEN_PROGRAM_ID = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
|
|
1786
2584
|
var SYSTEM_PROGRAM_ID = "11111111111111111111111111111111";
|
|
@@ -1869,7 +2667,7 @@ function findProgramAddress(seeds, programId) {
|
|
|
1869
2667
|
input.set(programId, offset);
|
|
1870
2668
|
offset += programId.length;
|
|
1871
2669
|
input.set(PDA_MARKER, offset);
|
|
1872
|
-
const hash =
|
|
2670
|
+
const hash = sha2563(input);
|
|
1873
2671
|
if (!isOnCurve(hash)) return { pda: hash, bump };
|
|
1874
2672
|
}
|
|
1875
2673
|
throw new Error("Could not find a viable PDA bump seed");
|
|
@@ -3091,9 +3889,10 @@ async function initializeHttpMode(config) {
|
|
|
3091
3889
|
settlementInfo,
|
|
3092
3890
|
ownIlpAddress: config.ilpInfo.ilpAddress,
|
|
3093
3891
|
toonEncoder: config.toonEncoder,
|
|
3094
|
-
toonDecoder: config.toonDecoder
|
|
3095
|
-
basePricePerByte
|
|
3096
|
-
//
|
|
3892
|
+
toonDecoder: config.toonDecoder
|
|
3893
|
+
// No `basePricePerByte`: ADR 0020 removed per-byte pricing, and a packet's
|
|
3894
|
+
// amount now comes from `GET /ilp/routes/price` at the terminating
|
|
3895
|
+
// connector (toon-client#452). Nothing here may state a local rate.
|
|
3097
3896
|
};
|
|
3098
3897
|
const bootstrapService = new BootstrapService(
|
|
3099
3898
|
bootstrapConfig,
|
|
@@ -3202,7 +4001,7 @@ var SolanaSigner = class {
|
|
|
3202
4001
|
|
|
3203
4002
|
// src/signing/mina-signer.ts
|
|
3204
4003
|
import { hexToMinaBase58PrivateKey as hexToMinaBase58PrivateKey2 } from "@toon-protocol/core";
|
|
3205
|
-
import { sha256 as
|
|
4004
|
+
import { sha256 as sha2564 } from "@noble/hashes/sha2.js";
|
|
3206
4005
|
import { bytesToHex } from "@noble/hashes/utils.js";
|
|
3207
4006
|
|
|
3208
4007
|
// src/channel/mina-payment-channel.ts
|
|
@@ -3376,7 +4175,7 @@ var DEFAULT_MINA_TOKEN_ID = "MINA";
|
|
|
3376
4175
|
var MINA_CLAIM_NETWORK = "devnet";
|
|
3377
4176
|
function deriveMinaSalt(zkAppAddress, nonce) {
|
|
3378
4177
|
const digestHex = bytesToHex(
|
|
3379
|
-
|
|
4178
|
+
sha2564(new TextEncoder().encode(`mina-pc-salt:${zkAppAddress}:${nonce}`))
|
|
3380
4179
|
);
|
|
3381
4180
|
const salt = BigInt("0x" + digestHex.slice(0, 60));
|
|
3382
4181
|
return salt === 0n ? 1n : salt;
|
|
@@ -3933,7 +4732,7 @@ var JsonFileChannelStore = class {
|
|
|
3933
4732
|
|
|
3934
4733
|
// src/balance/WalletBalanceReader.ts
|
|
3935
4734
|
import { createPublicClient as createPublicClient2, http as http2, defineChain as defineChain2 } from "viem";
|
|
3936
|
-
import { sha256 as
|
|
4735
|
+
import { sha256 as sha2565 } from "@noble/hashes/sha2.js";
|
|
3937
4736
|
var ERC20_READ_ABI = [
|
|
3938
4737
|
{ name: "balanceOf", type: "function", stateMutability: "view", inputs: [{ name: "account", type: "address" }], outputs: [{ type: "uint256" }] },
|
|
3939
4738
|
{ name: "decimals", type: "function", stateMutability: "view", inputs: [], outputs: [{ type: "uint8" }] },
|
|
@@ -4076,7 +4875,7 @@ function minaTokenIdToBase58(tokenId) {
|
|
|
4076
4875
|
const body = new Uint8Array(1 + 32);
|
|
4077
4876
|
body[0] = 28;
|
|
4078
4877
|
body.set(le, 1);
|
|
4079
|
-
const checksum =
|
|
4878
|
+
const checksum = sha2565(sha2565(body)).slice(0, 4);
|
|
4080
4879
|
const raw = new Uint8Array(body.length + 4);
|
|
4081
4880
|
raw.set(body, 0);
|
|
4082
4881
|
raw.set(checksum, body.length);
|
|
@@ -4244,16 +5043,16 @@ async function requestBlobStorage(client, secretKey, params) {
|
|
|
4244
5043
|
error: result.error ?? "Blob storage request rejected"
|
|
4245
5044
|
};
|
|
4246
5045
|
}
|
|
4247
|
-
if (!result.
|
|
5046
|
+
if (!result.response) {
|
|
4248
5047
|
return {
|
|
4249
5048
|
success: false,
|
|
4250
5049
|
eventId: event.id,
|
|
4251
|
-
error: "FULFILL
|
|
5050
|
+
error: "FULFILL carried no sealed response envelope; expected the store's answer with the Arweave tx ID"
|
|
4252
5051
|
};
|
|
4253
5052
|
}
|
|
4254
5053
|
let txId;
|
|
4255
5054
|
try {
|
|
4256
|
-
txId = extractArweaveTxId(result.
|
|
5055
|
+
txId = extractArweaveTxId(result.response);
|
|
4257
5056
|
} catch (error) {
|
|
4258
5057
|
return {
|
|
4259
5058
|
success: false,
|
|
@@ -4267,30 +5066,19 @@ async function requestBlobStorage(client, secretKey, params) {
|
|
|
4267
5066
|
eventId: event.id
|
|
4268
5067
|
};
|
|
4269
5068
|
}
|
|
4270
|
-
function extractArweaveTxId(
|
|
4271
|
-
|
|
4272
|
-
|
|
4273
|
-
const legacy = decodeUtf8(fromBase64(base64Data));
|
|
4274
|
-
if (!ARWEAVE_TX_ID_REGEX.test(legacy)) {
|
|
4275
|
-
throw new Error(
|
|
4276
|
-
`Decoded FULFILL data is not a valid Arweave tx ID: "${legacy}"`
|
|
4277
|
-
);
|
|
4278
|
-
}
|
|
4279
|
-
return legacy;
|
|
4280
|
-
}
|
|
4281
|
-
if (http4.status < 200 || http4.status >= 300) {
|
|
4282
|
-
const detail = http4.body ? ` - ${http4.body}` : "";
|
|
5069
|
+
function extractArweaveTxId(response) {
|
|
5070
|
+
if (response.status < 200 || response.status >= 300) {
|
|
5071
|
+
const detail = response.body.length > 0 ? ` - ${decodeUtf8(response.body)}` : "";
|
|
4283
5072
|
throw new Error(
|
|
4284
|
-
`Blob upload failed:
|
|
5073
|
+
`Blob upload failed: the store answered HTTP ${response.status}${detail}`
|
|
4285
5074
|
);
|
|
4286
5075
|
}
|
|
5076
|
+
const text = decodeUtf8(response.body);
|
|
4287
5077
|
let parsed;
|
|
4288
5078
|
try {
|
|
4289
|
-
parsed = JSON.parse(
|
|
5079
|
+
parsed = JSON.parse(text);
|
|
4290
5080
|
} catch {
|
|
4291
|
-
throw new Error(
|
|
4292
|
-
`Blob upload response body was not valid JSON: "${http4.body}"`
|
|
4293
|
-
);
|
|
5081
|
+
throw new Error(`Blob upload response body was not valid JSON: "${text}"`);
|
|
4294
5082
|
}
|
|
4295
5083
|
const body = parsed;
|
|
4296
5084
|
if (body.accept === false) {
|
|
@@ -4307,7 +5095,7 @@ function extractArweaveTxId(base64Data) {
|
|
|
4307
5095
|
}
|
|
4308
5096
|
}
|
|
4309
5097
|
throw new Error(
|
|
4310
|
-
`Blob upload response did not contain a valid Arweave tx ID: "${
|
|
5098
|
+
`Blob upload response did not contain a valid Arweave tx ID: "${text}"`
|
|
4311
5099
|
);
|
|
4312
5100
|
}
|
|
4313
5101
|
|
|
@@ -4317,11 +5105,17 @@ var Http402Client = class {
|
|
|
4317
5105
|
resolveClaim;
|
|
4318
5106
|
createIlpClient;
|
|
4319
5107
|
needsDuplex;
|
|
5108
|
+
connectorEdge;
|
|
4320
5109
|
constructor(config = {}) {
|
|
4321
5110
|
this.fetchImpl = config.fetch ?? fetch;
|
|
4322
5111
|
this.resolveClaim = config.resolveClaim;
|
|
4323
5112
|
this.createIlpClient = config.createIlpClient ?? ((httpEndpoint) => new HttpIlpClient({ httpEndpoint }));
|
|
4324
5113
|
this.needsDuplex = config.needsDuplex ?? false;
|
|
5114
|
+
this.connectorEdge = config.connectorEdge ?? new ConnectorEdgeClient({
|
|
5115
|
+
// Same `fetch` the probe uses: a host that installs its own (and a
|
|
5116
|
+
// test that swaps one in) must be the one the identity comes from.
|
|
5117
|
+
fetch: (input, init) => this.fetchImpl(input, init)
|
|
5118
|
+
});
|
|
4325
5119
|
}
|
|
4326
5120
|
/**
|
|
4327
5121
|
* `fetch()`-like entry point. Issues the request; on `402` parses the x402
|
|
@@ -4344,19 +5138,22 @@ var Http402Client = class {
|
|
|
4344
5138
|
return this.payOverToon(url, method, opts, accept, this.resolveClaim);
|
|
4345
5139
|
}
|
|
4346
5140
|
/**
|
|
4347
|
-
* Open/reuse a channel (via the injected claim resolver),
|
|
4348
|
-
*
|
|
4349
|
-
* and
|
|
5141
|
+
* Open/reuse a channel (via the injected claim resolver), seal the request
|
|
5142
|
+
* envelope to the terminating connector, send it to `POST /ilp` with the
|
|
5143
|
+
* claim and the matching condition, and open the answer.
|
|
5144
|
+
*
|
|
5145
|
+
* The identity is fetched BEFORE a packet is formed, and there is no default
|
|
5146
|
+
* to fall back to: sealing to the wrong key is a confidentiality failure
|
|
5147
|
+
* that merely presents as an undeliverable packet (ADR 0018).
|
|
4350
5148
|
*/
|
|
4351
5149
|
async payOverToon(url, method, opts, accept, resolveClaim) {
|
|
4352
5150
|
const destination = opts.destination ?? accept.destination;
|
|
4353
5151
|
const claim = await resolveClaim(destination, accept.amount);
|
|
4354
|
-
const
|
|
4355
|
-
|
|
4356
|
-
url,
|
|
4357
|
-
|
|
4358
|
-
|
|
4359
|
-
});
|
|
5152
|
+
const identity = await this.connectorEdge.getIdentity(accept.httpEndpoint);
|
|
5153
|
+
const exchange = sealExchange(
|
|
5154
|
+
toEnvelopeRequest(url, method, opts),
|
|
5155
|
+
identity.publicKey
|
|
5156
|
+
);
|
|
4360
5157
|
const peer = {
|
|
4361
5158
|
httpEndpoint: accept.httpEndpoint,
|
|
4362
5159
|
supportsUpgrade: accept.supportsUpgrade
|
|
@@ -4371,25 +5168,31 @@ var Http402Client = class {
|
|
|
4371
5168
|
{
|
|
4372
5169
|
destination,
|
|
4373
5170
|
amount: String(accept.amount),
|
|
4374
|
-
data: toBase64(
|
|
5171
|
+
data: toBase64(exchange.data),
|
|
5172
|
+
executionCondition: exchange.condition,
|
|
4375
5173
|
...opts.timeout !== void 0 ? { timeout: opts.timeout } : {}
|
|
4376
5174
|
},
|
|
4377
5175
|
claim
|
|
4378
5176
|
);
|
|
4379
|
-
|
|
5177
|
+
const outcome = readExchangeOutcome(
|
|
5178
|
+
result,
|
|
5179
|
+
result.data === void 0 ? void 0 : fromBase64(result.data),
|
|
5180
|
+
exchange.sharedSecret
|
|
5181
|
+
);
|
|
5182
|
+
if (outcome.kind === "destination-refused") {
|
|
4380
5183
|
throw new ConnectorError(
|
|
4381
|
-
`h402
|
|
5184
|
+
`h402 request refused by the destination: ${outcome.code} ${outcome.message}`.trim()
|
|
4382
5185
|
);
|
|
4383
5186
|
}
|
|
4384
|
-
if (
|
|
5187
|
+
if (outcome.kind === "path-refused") {
|
|
4385
5188
|
throw new ConnectorError(
|
|
4386
|
-
|
|
5189
|
+
`h402 request refused by a connector on the path: ${outcome.code} ${outcome.message}`.trim()
|
|
4387
5190
|
);
|
|
4388
5191
|
}
|
|
4389
|
-
return
|
|
5192
|
+
return toWebResponse(outcome.response);
|
|
4390
5193
|
}
|
|
4391
5194
|
/**
|
|
4392
|
-
* Send the
|
|
5195
|
+
* Send the sealed PREPARE over the selected transport.
|
|
4393
5196
|
*
|
|
4394
5197
|
* - `http` / `http-upgradable`: stateless one-shot `POST /ilp` with the claim.
|
|
4395
5198
|
* - `http-upgradable` additionally exercises {@link HttpIlpClient.upgradeToBtp}
|
|
@@ -4431,11 +5234,22 @@ function readAmount(obj, keys) {
|
|
|
4431
5234
|
for (const k of keys) {
|
|
4432
5235
|
const v = obj[k];
|
|
4433
5236
|
if (typeof v === "bigint") return v;
|
|
4434
|
-
if (typeof v === "number" && Number.isFinite(v))
|
|
4435
|
-
|
|
5237
|
+
if (typeof v === "number" && Number.isFinite(v))
|
|
5238
|
+
return BigInt(Math.trunc(v));
|
|
5239
|
+
if (typeof v === "string" && /^\d+$/.test(v.trim()))
|
|
5240
|
+
return BigInt(v.trim());
|
|
4436
5241
|
}
|
|
4437
5242
|
return void 0;
|
|
4438
5243
|
}
|
|
5244
|
+
function resolveEndpoint(endpoint, baseUrl) {
|
|
5245
|
+
if (!endpoint || !baseUrl) return endpoint;
|
|
5246
|
+
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(endpoint)) return endpoint;
|
|
5247
|
+
try {
|
|
5248
|
+
return new URL(endpoint, baseUrl).toString();
|
|
5249
|
+
} catch {
|
|
5250
|
+
return endpoint;
|
|
5251
|
+
}
|
|
5252
|
+
}
|
|
4439
5253
|
async function parseX402Challenge(response) {
|
|
4440
5254
|
let body;
|
|
4441
5255
|
try {
|
|
@@ -4443,9 +5257,9 @@ async function parseX402Challenge(response) {
|
|
|
4443
5257
|
} catch {
|
|
4444
5258
|
return {};
|
|
4445
5259
|
}
|
|
4446
|
-
return parseX402Body(body);
|
|
5260
|
+
return parseX402Body(body, response.url || void 0);
|
|
4447
5261
|
}
|
|
4448
|
-
function parseX402Body(body) {
|
|
5262
|
+
function parseX402Body(body, baseUrl) {
|
|
4449
5263
|
if (typeof body !== "object" || body === null) return {};
|
|
4450
5264
|
const b = body;
|
|
4451
5265
|
const version = typeof b["x402Version"] === "number" ? b["x402Version"] : void 0;
|
|
@@ -4455,17 +5269,11 @@ function parseX402Body(body) {
|
|
|
4455
5269
|
const entry = raw;
|
|
4456
5270
|
const scheme = readString(entry, ["scheme"]);
|
|
4457
5271
|
if (scheme !== "toon-channel") continue;
|
|
4458
|
-
const
|
|
4459
|
-
|
|
4460
|
-
|
|
4461
|
-
|
|
4462
|
-
]);
|
|
4463
|
-
const httpEndpoint = readString(entry, [
|
|
4464
|
-
"httpEndpoint",
|
|
4465
|
-
"ilpEndpoint",
|
|
4466
|
-
"endpoint"
|
|
4467
|
-
]);
|
|
4468
|
-
const amount = readAmount(entry, ["amount", "price", "maxAmountRequired"]);
|
|
5272
|
+
const extra = typeof entry["extra"] === "object" && entry["extra"] !== null ? entry["extra"] : {};
|
|
5273
|
+
const destination = readString(extra, ["ilpAddress", "destination"]) ?? readString(entry, ["destination", "ilpAddress", "payTo"]);
|
|
5274
|
+
const rawEndpoint = readString(entry, ["httpEndpoint", "ilpEndpoint"]) ?? readString(extra, ["httpEndpoint", "endpoint"]) ?? readString(entry, ["endpoint"]);
|
|
5275
|
+
const httpEndpoint = resolveEndpoint(rawEndpoint, baseUrl);
|
|
5276
|
+
const amount = readAmount(extra, ["price", "amount"]) ?? readAmount(entry, ["amount", "price", "maxAmountRequired"]);
|
|
4469
5277
|
if (!destination || !httpEndpoint || amount === void 0) continue;
|
|
4470
5278
|
const network = readString(entry, ["network", "chain"]);
|
|
4471
5279
|
const supportsUpgrade = entry["supportsUpgrade"] === true || entry["upgradable"] === true;
|
|
@@ -4483,82 +5291,33 @@ function parseX402Body(body) {
|
|
|
4483
5291
|
}
|
|
4484
5292
|
return version !== void 0 ? { x402Version: version } : {};
|
|
4485
5293
|
}
|
|
4486
|
-
var CRLF2 = "\r\n";
|
|
4487
|
-
function concatHeadAndBody(head, body) {
|
|
4488
|
-
const headBytes = encodeUtf8(head);
|
|
4489
|
-
const out = new Uint8Array(headBytes.length + body.length);
|
|
4490
|
-
out.set(headBytes, 0);
|
|
4491
|
-
out.set(body, headBytes.length);
|
|
4492
|
-
return out;
|
|
4493
|
-
}
|
|
4494
5294
|
function bodyToBytes(body) {
|
|
4495
5295
|
if (body === void 0) return new Uint8Array(0);
|
|
4496
5296
|
return typeof body === "string" ? encodeUtf8(body) : body;
|
|
4497
5297
|
}
|
|
4498
|
-
function
|
|
4499
|
-
const u = new URL(
|
|
4500
|
-
const
|
|
4501
|
-
|
|
4502
|
-
|
|
4503
|
-
|
|
4504
|
-
|
|
4505
|
-
|
|
4506
|
-
|
|
4507
|
-
|
|
4508
|
-
|
|
4509
|
-
if (bodyBytes.length > 0 && !has("content-length")) {
|
|
4510
|
-
put("Content-Length", String(bodyBytes.length));
|
|
4511
|
-
}
|
|
4512
|
-
const lines = [
|
|
4513
|
-
`${req.method.toUpperCase()} ${target} HTTP/1.1`,
|
|
4514
|
-
...headers.values()
|
|
4515
|
-
];
|
|
4516
|
-
const head = lines.join(CRLF2) + CRLF2 + CRLF2;
|
|
4517
|
-
return concatHeadAndBody(head, bodyBytes);
|
|
4518
|
-
}
|
|
4519
|
-
function findHeaderEnd2(bytes) {
|
|
4520
|
-
for (let i = 0; i + 3 < bytes.length; i++) {
|
|
4521
|
-
if (bytes[i] === 13 && bytes[i + 1] === 10 && bytes[i + 2] === 13 && bytes[i + 3] === 10) {
|
|
4522
|
-
return i + 4;
|
|
4523
|
-
}
|
|
4524
|
-
}
|
|
4525
|
-
return -1;
|
|
5298
|
+
function toEnvelopeRequest(url, method, opts) {
|
|
5299
|
+
const u = new URL(url);
|
|
5300
|
+
const headers = Object.entries(opts.headers ?? {}).map(
|
|
5301
|
+
([name, value]) => [name, value]
|
|
5302
|
+
);
|
|
5303
|
+
return {
|
|
5304
|
+
method: method.toUpperCase(),
|
|
5305
|
+
target: `${u.pathname}${u.search}` || "/",
|
|
5306
|
+
headers,
|
|
5307
|
+
body: bodyToBytes(opts.body)
|
|
5308
|
+
};
|
|
4526
5309
|
}
|
|
4527
|
-
function
|
|
4528
|
-
const headerEnd = findHeaderEnd2(bytes);
|
|
4529
|
-
const headBytes = headerEnd === -1 ? bytes : bytes.subarray(0, headerEnd - 2);
|
|
4530
|
-
const body = headerEnd === -1 ? new Uint8Array(0) : bytes.subarray(headerEnd);
|
|
4531
|
-
const headText = decodeUtf8(headBytes);
|
|
4532
|
-
const lines = headText.split(CRLF2).filter((l) => l.length > 0);
|
|
4533
|
-
const statusLine = lines.shift();
|
|
4534
|
-
if (!statusLine) {
|
|
4535
|
-
throw new ConnectorError(
|
|
4536
|
-
"h402 response payload had no HTTP status line"
|
|
4537
|
-
);
|
|
4538
|
-
}
|
|
4539
|
-
const match = /^HTTP\/\d\.\d\s+(\d{3})(?:\s+(.*))?$/.exec(statusLine.trim());
|
|
4540
|
-
if (!match) {
|
|
4541
|
-
throw new ConnectorError(
|
|
4542
|
-
`h402 response payload had a malformed status line: "${statusLine}"`
|
|
4543
|
-
);
|
|
4544
|
-
}
|
|
4545
|
-
const status = parseInt(match[1], 10);
|
|
4546
|
-
const statusText = match[2] ?? "";
|
|
5310
|
+
function toWebResponse(envelope) {
|
|
4547
5311
|
const headers = new Headers();
|
|
4548
|
-
for (const
|
|
4549
|
-
|
|
4550
|
-
if (idx === -1) continue;
|
|
4551
|
-
const name = line.slice(0, idx).trim();
|
|
4552
|
-
const value = line.slice(idx + 1).trim();
|
|
4553
|
-
if (name.length === 0) continue;
|
|
5312
|
+
for (const [name, value] of envelope.headers) {
|
|
5313
|
+
if (name.toLowerCase() === "content-length") continue;
|
|
4554
5314
|
headers.append(name, value);
|
|
4555
5315
|
}
|
|
5316
|
+
const status = envelope.status;
|
|
4556
5317
|
const nullBodyStatus = status === 101 || status === 204 || status === 205 || status === 304;
|
|
4557
|
-
const init = { status, headers };
|
|
4558
|
-
if (statusText) init.statusText = statusText;
|
|
4559
5318
|
return new Response(
|
|
4560
|
-
nullBodyStatus || body.length === 0 ? null : body.slice(),
|
|
4561
|
-
|
|
5319
|
+
nullBodyStatus || envelope.body.length === 0 ? null : envelope.body.slice(),
|
|
5320
|
+
{ status, headers }
|
|
4562
5321
|
);
|
|
4563
5322
|
}
|
|
4564
5323
|
|
|
@@ -5015,6 +5774,17 @@ var ToonClient = class {
|
|
|
5015
5774
|
/** Concrete on-chain client, kept so deposit/withdraw can reach chain methods. */
|
|
5016
5775
|
onChainChannelClient;
|
|
5017
5776
|
peerNegotiations = /* @__PURE__ */ new Map();
|
|
5777
|
+
/**
|
|
5778
|
+
* Asks terminating connectors for their identity key, caching one per
|
|
5779
|
+
* client edge. A packet cannot be formed without the key of the connector
|
|
5780
|
+
* that terminates it (ADR 0018), so this is reached on every paid write.
|
|
5781
|
+
*/
|
|
5782
|
+
connectorEdge = new ConnectorEdgeClient({
|
|
5783
|
+
// Resolve `fetch` per call rather than binding it once: a host that
|
|
5784
|
+
// installs its own global (and a test that swaps one in) must be the one
|
|
5785
|
+
// this reaches, whenever it is reached.
|
|
5786
|
+
fetch: (input, init) => globalThis.fetch(input, init)
|
|
5787
|
+
});
|
|
5018
5788
|
/**
|
|
5019
5789
|
* Creates a new ToonClient instance.
|
|
5020
5790
|
*
|
|
@@ -5254,15 +6024,42 @@ var ToonClient = class {
|
|
|
5254
6024
|
}
|
|
5255
6025
|
}
|
|
5256
6026
|
/**
|
|
5257
|
-
* Publishes a Nostr event
|
|
6027
|
+
* Publishes a Nostr event through the connector that terminates
|
|
6028
|
+
* `destination`, as a sealed, condition-bearing paid write (ADR 0018/0019).
|
|
6029
|
+
*
|
|
6030
|
+
* What crosses the wire, in order:
|
|
6031
|
+
*
|
|
6032
|
+
* 1. **The terminating connector's identity is fetched first.** `data` is
|
|
6033
|
+
* sealed to that key, so a packet cannot be formed without it — and
|
|
6034
|
+
* there is no default to fall back to, because sealing to the wrong key
|
|
6035
|
+
* is a confidentiality failure that merely presents as undeliverable.
|
|
6036
|
+
* 2. **The price is ASKED for, not computed.** ADR 0020 makes a price flat
|
|
6037
|
+
* per handler, so `GET /ilp/routes/price` — the same longest-prefix
|
|
6038
|
+
* lookup the claim gate charges against — is the only thing that can
|
|
6039
|
+
* state what this write costs. `options.ilpAmount` still overrides.
|
|
6040
|
+
* 3. **The event becomes an OER `EnvelopeRequest`** — `POST <proxyPath>`
|
|
6041
|
+
* carrying `{"event": …}` — never HTTP text.
|
|
6042
|
+
* 4. **The PREPARE carries a real execution condition**, minted as
|
|
6043
|
+
* `sha256` of the fulfilment derived from the secret sealed inside the
|
|
6044
|
+
* wrap. The transport verifies the returned preimage against it, so a
|
|
6045
|
+
* FULFILL nobody could have earned is counted failed rather than
|
|
6046
|
+
* accepted.
|
|
6047
|
+
* 5. **The answer is opened with that same secret.** A FULFILL carries a
|
|
6048
|
+
* sealed response envelope; a REJECT sealed at the termination means the
|
|
6049
|
+
* destination refused, and a plaintext one means somebody on the path
|
|
6050
|
+
* did. `refusedBy` keeps those apart.
|
|
5258
6051
|
*
|
|
5259
|
-
*
|
|
6052
|
+
* An HTTP status inside the response envelope is envelope CONTENT, not a
|
|
6053
|
+
* packet outcome (ADR 0020): a 404 rides home on a FULFILL and value moved.
|
|
6054
|
+
* This method still reports a non-2xx as `success: false` — the event did
|
|
6055
|
+
* not persist — but `response` is populated either way, so a caller can see
|
|
6056
|
+
* exactly what it paid for.
|
|
5260
6057
|
*
|
|
5261
6058
|
* @param event - Signed Nostr event to publish
|
|
5262
|
-
* @param options - Optional
|
|
5263
|
-
* @
|
|
5264
|
-
*
|
|
5265
|
-
*
|
|
6059
|
+
* @param options - Optional destination, claim, amount and request target
|
|
6060
|
+
* @throws {ToonClientError} If the client is not started, the terminating
|
|
6061
|
+
* connector's identity or route price cannot be obtained, or the send
|
|
6062
|
+
* fails outright.
|
|
5266
6063
|
*/
|
|
5267
6064
|
async publishEvent(event, options) {
|
|
5268
6065
|
if (!this.state) {
|
|
@@ -5272,11 +6069,19 @@ var ToonClient = class {
|
|
|
5272
6069
|
);
|
|
5273
6070
|
}
|
|
5274
6071
|
try {
|
|
5275
|
-
const toonData = this.config.toonEncoder(event);
|
|
5276
|
-
const basePricePerByte = 10n;
|
|
5277
|
-
const amount = options?.ilpAmount !== void 0 ? String(options.ilpAmount) : String(BigInt(toonData.length) * basePricePerByte);
|
|
5278
|
-
const writeData = buildStoreWriteEnvelope(event, options?.proxyPath);
|
|
5279
6072
|
const destination = options?.destination ?? this.config.destinationAddress;
|
|
6073
|
+
const edge = this.resolveClientEdgeEndpoint();
|
|
6074
|
+
const identity = await this.connectorEdge.getIdentity(edge);
|
|
6075
|
+
const amount = options?.ilpAmount !== void 0 ? String(options.ilpAmount) : String(await this.routePriceFor(edge, destination));
|
|
6076
|
+
const exchange = sealExchange(
|
|
6077
|
+
{
|
|
6078
|
+
method: "POST",
|
|
6079
|
+
target: options?.proxyPath ?? "/write",
|
|
6080
|
+
headers: [["content-type", "application/json"]],
|
|
6081
|
+
body: encodeUtf8(JSON.stringify({ event }))
|
|
6082
|
+
},
|
|
6083
|
+
identity.publicKey
|
|
6084
|
+
);
|
|
5280
6085
|
const transport = this.getClaimTransport();
|
|
5281
6086
|
const claimMessage = await this.resolveClaimForDestination(
|
|
5282
6087
|
destination,
|
|
@@ -5287,37 +6092,51 @@ var ToonClient = class {
|
|
|
5287
6092
|
{
|
|
5288
6093
|
destination,
|
|
5289
6094
|
amount,
|
|
5290
|
-
data: toBase64(
|
|
6095
|
+
data: toBase64(exchange.data),
|
|
6096
|
+
executionCondition: exchange.condition
|
|
5291
6097
|
},
|
|
5292
6098
|
claimMessage
|
|
5293
6099
|
);
|
|
5294
|
-
|
|
6100
|
+
const outcome = readExchangeOutcome(
|
|
6101
|
+
response,
|
|
6102
|
+
response.data === void 0 ? void 0 : fromBase64(response.data),
|
|
6103
|
+
exchange.sharedSecret
|
|
6104
|
+
);
|
|
6105
|
+
if (outcome.kind === "destination-refused") {
|
|
5295
6106
|
return {
|
|
5296
6107
|
success: false,
|
|
5297
|
-
|
|
6108
|
+
refusedBy: "destination",
|
|
6109
|
+
code: outcome.code,
|
|
6110
|
+
error: `Destination refused the write: ${outcome.code} - ${outcome.message}`
|
|
5298
6111
|
};
|
|
5299
6112
|
}
|
|
5300
|
-
if (
|
|
5301
|
-
|
|
5302
|
-
|
|
5303
|
-
|
|
5304
|
-
|
|
5305
|
-
|
|
5306
|
-
|
|
5307
|
-
};
|
|
5308
|
-
}
|
|
6113
|
+
if (outcome.kind === "path-refused") {
|
|
6114
|
+
return {
|
|
6115
|
+
success: false,
|
|
6116
|
+
refusedBy: "path",
|
|
6117
|
+
code: outcome.code,
|
|
6118
|
+
error: `A connector on the path refused the write: ${outcome.code} - ${outcome.message}`
|
|
6119
|
+
};
|
|
5309
6120
|
}
|
|
5310
|
-
|
|
5311
|
-
|
|
5312
|
-
|
|
5313
|
-
|
|
5314
|
-
|
|
6121
|
+
const { response: answer } = outcome;
|
|
6122
|
+
if (answer.status < 200 || answer.status >= 300) {
|
|
6123
|
+
const detail = answer.body.length > 0 ? ` - ${decodeUtf8(answer.body)}` : "";
|
|
6124
|
+
return {
|
|
6125
|
+
success: false,
|
|
6126
|
+
response: answer,
|
|
6127
|
+
error: `Write failed: the destination answered HTTP ${answer.status}${detail}`
|
|
6128
|
+
};
|
|
6129
|
+
}
|
|
6130
|
+
return { success: true, eventId: event.id, response: answer };
|
|
5315
6131
|
} catch (error) {
|
|
5316
6132
|
console.error(
|
|
5317
6133
|
"[ToonClient.publishEvent] ROOT CAUSE:",
|
|
5318
6134
|
String(error),
|
|
5319
6135
|
error instanceof Error ? error.stack : ""
|
|
5320
6136
|
);
|
|
6137
|
+
if (error instanceof ToonClientError && (error.code === "NO_TERMINATED_ROUTE" || error.code === "NO_CONNECTOR_EDGE")) {
|
|
6138
|
+
throw error;
|
|
6139
|
+
}
|
|
5321
6140
|
throw new ToonClientError(
|
|
5322
6141
|
"Failed to publish event",
|
|
5323
6142
|
"PUBLISH_ERROR",
|
|
@@ -5325,6 +6144,78 @@ var ToonClient = class {
|
|
|
5325
6144
|
);
|
|
5326
6145
|
}
|
|
5327
6146
|
}
|
|
6147
|
+
/**
|
|
6148
|
+
* What a destination costs, asked of the connector that terminates it —
|
|
6149
|
+
* `null` when it terminates no route matching it.
|
|
6150
|
+
*
|
|
6151
|
+
* The public form of the lookup `publishEvent` makes, for callers that need
|
|
6152
|
+
* a price BEFORE they build a packet: a pre-push estimate that must equal
|
|
6153
|
+
* what the push will actually pay, a fee quote shown to a user for consent.
|
|
6154
|
+
* Since ADR 0020 a price is flat per handler, so the figure is the whole
|
|
6155
|
+
* fee for one packet to that destination — there is nothing to multiply it
|
|
6156
|
+
* by. Cached per destination, so this is cheap to call repeatedly.
|
|
6157
|
+
*
|
|
6158
|
+
* @throws {ToonClientError} NO_CONNECTOR_EDGE when no client edge is known.
|
|
6159
|
+
* @throws {ConnectorEdgeError} when the connector cannot be asked.
|
|
6160
|
+
*/
|
|
6161
|
+
async getRoutePrice(destination) {
|
|
6162
|
+
const price = await this.connectorEdge.getRoutePrice(
|
|
6163
|
+
this.resolveClientEdgeEndpoint(),
|
|
6164
|
+
destination
|
|
6165
|
+
);
|
|
6166
|
+
return price === null ? null : price.price;
|
|
6167
|
+
}
|
|
6168
|
+
/**
|
|
6169
|
+
* What this destination costs, from the connector that terminates it.
|
|
6170
|
+
*
|
|
6171
|
+
* ADR 0020 makes a price flat per handler: one handler, one price, and an
|
|
6172
|
+
* app that wants to charge differently exposes more handlers. There is
|
|
6173
|
+
* therefore nothing to compute — the route table IS the price list, and
|
|
6174
|
+
* `GET /ilp/routes/price` is the same longest-prefix lookup the claim gate
|
|
6175
|
+
* charges against, so it can never state a price a real request would not
|
|
6176
|
+
* be charged.
|
|
6177
|
+
*
|
|
6178
|
+
* Cached per (edge, destination) by {@link ConnectorEdgeClient}, so this is
|
|
6179
|
+
* one round trip per destination rather than one per packet.
|
|
6180
|
+
*
|
|
6181
|
+
* @throws {ToonClientError} NO_TERMINATED_ROUTE when the connector answers
|
|
6182
|
+
* `404` — it does not terminate this destination. That is a refusal to
|
|
6183
|
+
* guess, not a zero: pricing an unroutable write at 0 (or at some local
|
|
6184
|
+
* fallback rate) would send a packet certain to be rejected, and report
|
|
6185
|
+
* the wrong reason for it.
|
|
6186
|
+
*/
|
|
6187
|
+
async routePriceFor(edge, destination) {
|
|
6188
|
+
const price = await this.connectorEdge.getRoutePrice(edge, destination);
|
|
6189
|
+
if (price === null) {
|
|
6190
|
+
throw new ToonClientError(
|
|
6191
|
+
`The connector at ${edge} terminates no route for "${destination}", so it cannot say what a write there costs. Check the destination, or pass an explicit \`ilpAmount\` to price it yourself.`,
|
|
6192
|
+
"NO_TERMINATED_ROUTE"
|
|
6193
|
+
);
|
|
6194
|
+
}
|
|
6195
|
+
return price.price;
|
|
6196
|
+
}
|
|
6197
|
+
/**
|
|
6198
|
+
* The client edge `/ilp/identity` and `/ilp/routes/price` hang off — the
|
|
6199
|
+
* same origin paid writes already POST `/ilp` to.
|
|
6200
|
+
*
|
|
6201
|
+
* Preferring the live transport's own endpoint over config is deliberate:
|
|
6202
|
+
* transport selection may have followed a discovered `httpEndpoint`, and
|
|
6203
|
+
* the identity must come from the connector actually being paid, not from
|
|
6204
|
+
* whatever URL was configured before discovery ran.
|
|
6205
|
+
*
|
|
6206
|
+
* @throws {ToonClientError} NO_CONNECTOR_EDGE when no origin is known.
|
|
6207
|
+
*/
|
|
6208
|
+
resolveClientEdgeEndpoint() {
|
|
6209
|
+
const runtime = this.state?.runtimeClient;
|
|
6210
|
+
const endpoint = runtime?.clientEdgeEndpoint ?? this.config.proxyUrl ?? this.config.connectorUrl;
|
|
6211
|
+
if (!endpoint) {
|
|
6212
|
+
throw new ToonClientError(
|
|
6213
|
+
"No connector client edge to ask for an identity. Configure `proxyUrl` or `connectorUrl`; a payload cannot be sealed without the terminating connector's key (ADR 0018).",
|
|
6214
|
+
"NO_CONNECTOR_EDGE"
|
|
6215
|
+
);
|
|
6216
|
+
}
|
|
6217
|
+
return connectorEdgeBaseUrl(endpoint);
|
|
6218
|
+
}
|
|
5328
6219
|
/**
|
|
5329
6220
|
* Payment-aware HTTP fetch over TOON (issue #50). A `fetch()`-like method that
|
|
5330
6221
|
* makes paying for an HTTP resource transparent:
|
|
@@ -5359,6 +6250,11 @@ var ToonClient = class {
|
|
|
5359
6250
|
);
|
|
5360
6251
|
}
|
|
5361
6252
|
const client = new Http402Client({
|
|
6253
|
+
// Share this client's identity cache rather than letting each per-call
|
|
6254
|
+
// engine fetch the same connector's key again: `h402Fetch` builds a
|
|
6255
|
+
// fresh Http402Client per call (below), and a paid request now needs a
|
|
6256
|
+
// terminating key.
|
|
6257
|
+
connectorEdge: this.connectorEdge,
|
|
5362
6258
|
...this.channelManager ? {
|
|
5363
6259
|
resolveClaim: (destination, amount) => this.resolveClaimForDestination(destination, amount)
|
|
5364
6260
|
} : {}
|
|
@@ -5620,14 +6516,20 @@ var ToonClient = class {
|
|
|
5620
6516
|
async depositToChannel(channelId, amount) {
|
|
5621
6517
|
if (!this.channelManager) throw new Error("ChannelManager not initialized");
|
|
5622
6518
|
if (!this.onChainChannelClient) {
|
|
5623
|
-
throw new Error(
|
|
6519
|
+
throw new Error(
|
|
6520
|
+
"On-chain channel client not configured (no chainRpcUrls)."
|
|
6521
|
+
);
|
|
5624
6522
|
}
|
|
5625
6523
|
const delta = BigInt(amount);
|
|
5626
6524
|
if (delta <= 0n) throw new Error("Deposit amount must be positive.");
|
|
5627
6525
|
const currentDeposit = this.channelManager.getDepositTotal(channelId);
|
|
5628
|
-
const result = await this.onChainChannelClient.depositToChannel(
|
|
5629
|
-
|
|
5630
|
-
|
|
6526
|
+
const result = await this.onChainChannelClient.depositToChannel(
|
|
6527
|
+
channelId,
|
|
6528
|
+
delta,
|
|
6529
|
+
{
|
|
6530
|
+
currentDeposit
|
|
6531
|
+
}
|
|
6532
|
+
);
|
|
5631
6533
|
this.channelManager.setDepositTotal(channelId, result.depositTotal);
|
|
5632
6534
|
return {
|
|
5633
6535
|
channelId,
|
|
@@ -5644,7 +6546,9 @@ var ToonClient = class {
|
|
|
5644
6546
|
async closeChannel(channelId) {
|
|
5645
6547
|
if (!this.channelManager) throw new Error("ChannelManager not initialized");
|
|
5646
6548
|
if (!this.onChainChannelClient) {
|
|
5647
|
-
throw new Error(
|
|
6549
|
+
throw new Error(
|
|
6550
|
+
"On-chain channel client not configured (no chainRpcUrls)."
|
|
6551
|
+
);
|
|
5648
6552
|
}
|
|
5649
6553
|
const r = await this.onChainChannelClient.closeChannel(channelId);
|
|
5650
6554
|
this.channelManager.setChannelClosed(channelId, r.closedAt, r.settleableAt);
|
|
@@ -5664,11 +6568,15 @@ var ToonClient = class {
|
|
|
5664
6568
|
async settleChannel(channelId) {
|
|
5665
6569
|
if (!this.channelManager) throw new Error("ChannelManager not initialized");
|
|
5666
6570
|
if (!this.onChainChannelClient) {
|
|
5667
|
-
throw new Error(
|
|
6571
|
+
throw new Error(
|
|
6572
|
+
"On-chain channel client not configured (no chainRpcUrls)."
|
|
6573
|
+
);
|
|
5668
6574
|
}
|
|
5669
6575
|
const settleableAt = this.channelManager.getSettleableAt(channelId);
|
|
5670
6576
|
if (settleableAt === void 0) {
|
|
5671
|
-
throw new Error(
|
|
6577
|
+
throw new Error(
|
|
6578
|
+
`Channel "${channelId}" is not closed; call closeChannel first.`
|
|
6579
|
+
);
|
|
5672
6580
|
}
|
|
5673
6581
|
const nowSec = BigInt(Math.floor(Date.now() / 1e3));
|
|
5674
6582
|
if (nowSec < settleableAt) {
|
|
@@ -5677,7 +6585,11 @@ var ToonClient = class {
|
|
|
5677
6585
|
new Error(
|
|
5678
6586
|
`Channel "${channelId}" is not settleable yet \u2014 ${remaining}s remain (settleable at ${settleableAt}).`
|
|
5679
6587
|
),
|
|
5680
|
-
{
|
|
6588
|
+
{
|
|
6589
|
+
name: "SettleTooEarlyError",
|
|
6590
|
+
retryable: true,
|
|
6591
|
+
settleableAt: settleableAt.toString()
|
|
6592
|
+
}
|
|
5681
6593
|
);
|
|
5682
6594
|
}
|
|
5683
6595
|
const r = await this.onChainChannelClient.settleChannel(channelId);
|
|
@@ -5755,12 +6667,14 @@ var ToonClient = class {
|
|
|
5755
6667
|
if (!this.channelManager || !this.onChainChannelClient) return void 0;
|
|
5756
6668
|
const participant = this.getEvmAddress();
|
|
5757
6669
|
if (!participant) return void 0;
|
|
5758
|
-
const { deposit } = await this.onChainChannelClient.readEvmParticipantState(
|
|
5759
|
-
|
|
5760
|
-
|
|
5761
|
-
|
|
5762
|
-
|
|
5763
|
-
|
|
6670
|
+
const { deposit } = await this.onChainChannelClient.readEvmParticipantState(
|
|
6671
|
+
{
|
|
6672
|
+
chain: opts.chain,
|
|
6673
|
+
tokenNetworkAddress: opts.tokenNetworkAddress,
|
|
6674
|
+
channelId,
|
|
6675
|
+
participant
|
|
6676
|
+
}
|
|
6677
|
+
);
|
|
5764
6678
|
this.channelManager.setDepositTotal(channelId, deposit);
|
|
5765
6679
|
return deposit;
|
|
5766
6680
|
}
|
|
@@ -5786,7 +6700,14 @@ var ToonClient = class {
|
|
|
5786
6700
|
const tokenAddress = chainKey ? tokens[chainKey] : void 0;
|
|
5787
6701
|
if (chainKey && rpcUrl && tokenAddress) {
|
|
5788
6702
|
try {
|
|
5789
|
-
out.push(
|
|
6703
|
+
out.push(
|
|
6704
|
+
await readEvmTokenBalance({
|
|
6705
|
+
rpcUrl,
|
|
6706
|
+
chainKey,
|
|
6707
|
+
tokenAddress,
|
|
6708
|
+
owner: evmAddress
|
|
6709
|
+
})
|
|
6710
|
+
);
|
|
5790
6711
|
} catch {
|
|
5791
6712
|
}
|
|
5792
6713
|
}
|
|
@@ -5796,7 +6717,11 @@ var ToonClient = class {
|
|
|
5796
6717
|
if (solAddress && sol?.rpcUrl && sol.tokenMint) {
|
|
5797
6718
|
try {
|
|
5798
6719
|
out.push(
|
|
5799
|
-
await readSolanaTokenBalance({
|
|
6720
|
+
await readSolanaTokenBalance({
|
|
6721
|
+
rpcUrl: sol.rpcUrl,
|
|
6722
|
+
mint: sol.tokenMint,
|
|
6723
|
+
owner: solAddress
|
|
6724
|
+
})
|
|
5800
6725
|
);
|
|
5801
6726
|
} catch {
|
|
5802
6727
|
}
|
|
@@ -5805,7 +6730,12 @@ var ToonClient = class {
|
|
|
5805
6730
|
const mina = this.config.minaChannel;
|
|
5806
6731
|
if (minaAddress && mina?.graphqlUrl) {
|
|
5807
6732
|
try {
|
|
5808
|
-
out.push(
|
|
6733
|
+
out.push(
|
|
6734
|
+
await readMinaBalance({
|
|
6735
|
+
graphqlUrl: mina.graphqlUrl,
|
|
6736
|
+
owner: minaAddress
|
|
6737
|
+
})
|
|
6738
|
+
);
|
|
5809
6739
|
} catch {
|
|
5810
6740
|
}
|
|
5811
6741
|
}
|
|
@@ -6441,7 +7371,7 @@ import {
|
|
|
6441
7371
|
import {
|
|
6442
7372
|
hashTypedData
|
|
6443
7373
|
} from "viem";
|
|
6444
|
-
import { secp256k1 } from "@noble/curves/secp256k1.js";
|
|
7374
|
+
import { secp256k1 as secp256k12 } from "@noble/curves/secp256k1.js";
|
|
6445
7375
|
import { keccak_256 } from "@noble/hashes/sha3.js";
|
|
6446
7376
|
import { hexToBytes, bytesToHex as bytesToHex2 } from "@noble/hashes/utils.js";
|
|
6447
7377
|
var ROLLING_SWAP_DOMAIN_NAME = "RollingSwapChannel";
|
|
@@ -6517,7 +7447,7 @@ function recoverEvmClaimSigner(ctx, message, signature) {
|
|
|
6517
7447
|
throw new Error(`EVM signature v must be 27 or 28, got ${v}`);
|
|
6518
7448
|
}
|
|
6519
7449
|
const digest = evmClaimDigest(ctx, message).slice(2);
|
|
6520
|
-
const recovered =
|
|
7450
|
+
const recovered = secp256k12.Signature.fromBytes(bytes.slice(0, 64), "compact").addRecoveryBit(v - 27).recoverPublicKey(hexToBytes(digest));
|
|
6521
7451
|
const uncompressed = recovered.toBytes(false);
|
|
6522
7452
|
const addrHash = keccak_256(uncompressed.slice(1));
|
|
6523
7453
|
return `0x${bytesToHex2(addrHash.slice(-20))}`;
|
|
@@ -7789,7 +8719,7 @@ import {
|
|
|
7789
8719
|
scryptSync,
|
|
7790
8720
|
createCipheriv,
|
|
7791
8721
|
createDecipheriv,
|
|
7792
|
-
randomBytes as
|
|
8722
|
+
randomBytes as randomBytes3
|
|
7793
8723
|
} from "crypto";
|
|
7794
8724
|
import { writeFileSync as writeFileSync3, readFileSync as readFileSync3 } from "fs";
|
|
7795
8725
|
var SCRYPT_N = 2 ** 17;
|
|
@@ -7816,8 +8746,8 @@ function encryptMnemonic2(mnemonic, password) {
|
|
|
7816
8746
|
if (typeof password !== "string" || password.length === 0) {
|
|
7817
8747
|
throw new Error("encryptMnemonic: password must be a non-empty string");
|
|
7818
8748
|
}
|
|
7819
|
-
const salt =
|
|
7820
|
-
const iv =
|
|
8749
|
+
const salt = randomBytes3(SALT_LEN);
|
|
8750
|
+
const iv = randomBytes3(IV_LEN);
|
|
7821
8751
|
const key2 = scryptSync(password, salt, SCRYPT_KEY_LEN, {
|
|
7822
8752
|
N: SCRYPT_N,
|
|
7823
8753
|
r: SCRYPT_R,
|
|
@@ -7925,17 +8855,27 @@ export {
|
|
|
7925
8855
|
COOP_CLOSE_TYPEHASH,
|
|
7926
8856
|
ChannelFundingError,
|
|
7927
8857
|
ChannelManager,
|
|
8858
|
+
ConnectorEdgeClient,
|
|
8859
|
+
ConnectorEdgeError,
|
|
7928
8860
|
ConnectorError,
|
|
8861
|
+
EnvelopeError,
|
|
8862
|
+
EnvelopeErrorKind,
|
|
7929
8863
|
EvmSigner,
|
|
7930
8864
|
FULFILLMENT_MISMATCH_CODE,
|
|
7931
8865
|
FULFILLMENT_MISMATCH_MESSAGE,
|
|
8866
|
+
GIFTWRAP_NONCE_LENGTH,
|
|
8867
|
+
GIFTWRAP_PUBLIC_KEY_LENGTH,
|
|
8868
|
+
GIFTWRAP_SECRET_LENGTH,
|
|
8869
|
+
GIFTWRAP_TYPE_REQUEST,
|
|
8870
|
+
GIFTWRAP_TYPE_RESPONSE,
|
|
7932
8871
|
GenerativeFallbackRenderer,
|
|
8872
|
+
GiftWrapError,
|
|
8873
|
+
GiftWrapErrorKind,
|
|
7933
8874
|
Http402Client,
|
|
7934
8875
|
HttpConnectorAdmin,
|
|
7935
8876
|
HttpIlpClient,
|
|
7936
8877
|
HttpRuntimeClient,
|
|
7937
8878
|
ILP_CLAIM_HEADER,
|
|
7938
|
-
ILP_CLAIM_WRAPPED_HEADER,
|
|
7939
8879
|
ILP_PEER_ID_HEADER,
|
|
7940
8880
|
InMemoryPreimageRetentionStore,
|
|
7941
8881
|
InMemoryReceivedClaimStore,
|
|
@@ -7948,10 +8888,13 @@ export {
|
|
|
7948
8888
|
MinaSettlementError,
|
|
7949
8889
|
MinaSigner,
|
|
7950
8890
|
NetworkError,
|
|
8891
|
+
OerError,
|
|
8892
|
+
OerErrorKind,
|
|
7951
8893
|
OnChainChannelClient,
|
|
7952
8894
|
ROLLING_SWAP_DOMAIN_NAME,
|
|
7953
8895
|
ROLLING_SWAP_DOMAIN_VERSION,
|
|
7954
8896
|
RendererPinStore,
|
|
8897
|
+
SealedResponseError,
|
|
7955
8898
|
SolanaSigner,
|
|
7956
8899
|
ToonClient,
|
|
7957
8900
|
ToonClientError,
|
|
@@ -7967,22 +8910,36 @@ export {
|
|
|
7967
8910
|
buildMinaCoSignedClaim,
|
|
7968
8911
|
buildRendererEventTemplate,
|
|
7969
8912
|
buildSettlementInfo,
|
|
7970
|
-
buildStoreWriteEnvelope,
|
|
7971
8913
|
buildSwapSettlements,
|
|
7972
8914
|
buildUiCoordinate,
|
|
7973
8915
|
classifyIntent,
|
|
8916
|
+
connectorEdgeBaseUrl,
|
|
7974
8917
|
createO1jsMinaClaimSubmitter,
|
|
8918
|
+
decodeConnectorPublicKey,
|
|
8919
|
+
decodeEnvelope,
|
|
8920
|
+
decodeEnvelopeRequest,
|
|
8921
|
+
decodeEnvelopeResponse,
|
|
7975
8922
|
decodeEvmSettlementTx,
|
|
8923
|
+
decodeVarOctetString,
|
|
8924
|
+
decodeVarUint,
|
|
7976
8925
|
decryptMnemonic2 as decryptMnemonic,
|
|
7977
8926
|
defaultFaucetTimeout,
|
|
7978
8927
|
deployMinaChannelZkApp,
|
|
8928
|
+
deriveCondition,
|
|
7979
8929
|
deriveFromNsec,
|
|
8930
|
+
deriveFulfillment,
|
|
7980
8931
|
deriveFullIdentity,
|
|
7981
8932
|
deriveNostrKeyFromMnemonic,
|
|
7982
8933
|
deterministicGenerator,
|
|
8934
|
+
encodeEnvelope,
|
|
8935
|
+
encodeEnvelopeRequest,
|
|
8936
|
+
encodeEnvelopeResponse,
|
|
8937
|
+
encodeVarOctetString,
|
|
8938
|
+
encodeVarUint,
|
|
7983
8939
|
encryptMnemonic2 as encryptMnemonic,
|
|
7984
8940
|
ensureOwnedMinaZkApp,
|
|
7985
8941
|
entryToAccumulatedClaim,
|
|
8942
|
+
envelopeHeader,
|
|
7986
8943
|
evmClaimDigest,
|
|
7987
8944
|
evmCooperativeCloseDigest,
|
|
7988
8945
|
extractArweaveTxId,
|
|
@@ -8005,12 +8962,15 @@ export {
|
|
|
8005
8962
|
isTrustDowngrade,
|
|
8006
8963
|
isZeroCondition,
|
|
8007
8964
|
loadKeystore,
|
|
8965
|
+
localGiftWrapEcdh,
|
|
8966
|
+
looksLikeSealedResponse,
|
|
8008
8967
|
mintExecutionCondition,
|
|
8968
|
+
openRequest,
|
|
8969
|
+
openResponse,
|
|
8009
8970
|
parseBackupPayload,
|
|
8971
|
+
parseConnectorIdentity,
|
|
8972
|
+
parseConnectorRoutePrice,
|
|
8010
8973
|
parseEvmChainId2 as parseEvmChainId,
|
|
8011
|
-
parseFulfillHttp,
|
|
8012
|
-
parseFulfillHttpBytes,
|
|
8013
|
-
parseHttpResponse,
|
|
8014
8974
|
parseUiCoordinate,
|
|
8015
8975
|
parseX402Body,
|
|
8016
8976
|
parseX402Challenge,
|
|
@@ -8019,6 +8979,7 @@ export {
|
|
|
8019
8979
|
readDiscoveredIlpPeer,
|
|
8020
8980
|
readEvmNativeBalance,
|
|
8021
8981
|
readEvmTokenBalance,
|
|
8982
|
+
readExchangeOutcome,
|
|
8022
8983
|
readMinaBalance,
|
|
8023
8984
|
readMinaChannelState,
|
|
8024
8985
|
readMinaDepositTotal,
|
|
@@ -8032,9 +8993,13 @@ export {
|
|
|
8032
8993
|
resolveRendererMime,
|
|
8033
8994
|
resolveUiCoordinate,
|
|
8034
8995
|
resolveUiRenderer,
|
|
8996
|
+
sealExchange,
|
|
8997
|
+
sealRequest,
|
|
8998
|
+
sealRequestWithRandomness,
|
|
8999
|
+
sealResponse,
|
|
9000
|
+
sealResponseWithRandomness,
|
|
8035
9001
|
selectIlpTransport,
|
|
8036
9002
|
selectLatestAddressable,
|
|
8037
|
-
serializeHttpRequest,
|
|
8038
9003
|
submitEvmSettlement,
|
|
8039
9004
|
submitMinaSettlement,
|
|
8040
9005
|
validateConfig,
|