@hashgraphonline/standards-sdk 0.1.141 → 0.1.143
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/README.md +24 -1
- package/dist/cjs/hcs-11/client.d.ts.map +1 -1
- package/dist/cjs/hcs-11/types.d.ts +1 -0
- package/dist/cjs/hcs-11/types.d.ts.map +1 -1
- package/dist/cjs/hcs-16/base-client.d.ts.map +1 -1
- package/dist/cjs/hcs-17/types.d.ts.map +1 -1
- package/dist/cjs/hcs-20/sdk.d.ts.map +1 -1
- package/dist/cjs/hcs-20/types.d.ts +9 -8
- package/dist/cjs/hcs-20/types.d.ts.map +1 -1
- package/dist/cjs/hcs-21/base-client.d.ts +14 -12
- package/dist/cjs/hcs-21/base-client.d.ts.map +1 -1
- package/dist/cjs/hcs-21/browser.d.ts +17 -7
- package/dist/cjs/hcs-21/browser.d.ts.map +1 -1
- package/dist/cjs/hcs-21/index.d.ts +1 -0
- package/dist/cjs/hcs-21/index.d.ts.map +1 -1
- package/dist/cjs/hcs-21/sdk.d.ts +70 -6
- package/dist/cjs/hcs-21/sdk.d.ts.map +1 -1
- package/dist/cjs/hcs-21/tx.d.ts +6 -2
- package/dist/cjs/hcs-21/tx.d.ts.map +1 -1
- package/dist/cjs/hcs-21/types.d.ts +751 -66
- package/dist/cjs/hcs-21/types.d.ts.map +1 -1
- package/dist/cjs/hcs-21/verify.d.ts +6 -0
- package/dist/cjs/hcs-21/verify.d.ts.map +1 -0
- package/dist/cjs/inscribe/inscriber.d.ts +3 -1
- package/dist/cjs/inscribe/inscriber.d.ts.map +1 -1
- package/dist/cjs/inscribe/quote-cache.d.ts.map +1 -1
- package/dist/cjs/inscribe/types.d.ts +7 -0
- package/dist/cjs/inscribe/types.d.ts.map +1 -1
- package/dist/cjs/services/registry-broker/client.d.ts +4 -3
- package/dist/cjs/services/registry-broker/client.d.ts.map +1 -1
- package/dist/cjs/services/registry-broker/private-key-signer.d.ts.map +1 -1
- package/dist/cjs/services/registry-broker/schemas.d.ts +49 -25
- package/dist/cjs/services/registry-broker/schemas.d.ts.map +1 -1
- package/dist/cjs/services/registry-broker/types.d.ts +1 -2
- package/dist/cjs/services/registry-broker/types.d.ts.map +1 -1
- package/dist/cjs/services/types.d.ts +1 -0
- package/dist/cjs/services/types.d.ts.map +1 -1
- package/dist/cjs/standards-sdk.cjs +2 -2
- package/dist/cjs/standards-sdk.cjs.map +1 -1
- package/dist/cjs/utils/dynamic-import.d.ts +1 -0
- package/dist/cjs/utils/dynamic-import.d.ts.map +1 -1
- package/dist/es/hcs-11/client.d.ts.map +1 -1
- package/dist/es/hcs-11/types.d.ts +1 -0
- package/dist/es/hcs-11/types.d.ts.map +1 -1
- package/dist/es/hcs-16/base-client.d.ts.map +1 -1
- package/dist/es/hcs-17/types.d.ts.map +1 -1
- package/dist/es/hcs-20/sdk.d.ts.map +1 -1
- package/dist/es/hcs-20/types.d.ts +9 -8
- package/dist/es/hcs-20/types.d.ts.map +1 -1
- package/dist/es/hcs-21/base-client.d.ts +14 -12
- package/dist/es/hcs-21/base-client.d.ts.map +1 -1
- package/dist/es/hcs-21/browser.d.ts +17 -7
- package/dist/es/hcs-21/browser.d.ts.map +1 -1
- package/dist/es/hcs-21/index.d.ts +1 -0
- package/dist/es/hcs-21/index.d.ts.map +1 -1
- package/dist/es/hcs-21/sdk.d.ts +70 -6
- package/dist/es/hcs-21/sdk.d.ts.map +1 -1
- package/dist/es/hcs-21/tx.d.ts +6 -2
- package/dist/es/hcs-21/tx.d.ts.map +1 -1
- package/dist/es/hcs-21/types.d.ts +751 -66
- package/dist/es/hcs-21/types.d.ts.map +1 -1
- package/dist/es/hcs-21/verify.d.ts +6 -0
- package/dist/es/hcs-21/verify.d.ts.map +1 -0
- package/dist/es/inscribe/inscriber.d.ts +3 -1
- package/dist/es/inscribe/inscriber.d.ts.map +1 -1
- package/dist/es/inscribe/quote-cache.d.ts.map +1 -1
- package/dist/es/inscribe/types.d.ts +7 -0
- package/dist/es/inscribe/types.d.ts.map +1 -1
- package/dist/es/services/registry-broker/client.d.ts +4 -3
- package/dist/es/services/registry-broker/client.d.ts.map +1 -1
- package/dist/es/services/registry-broker/private-key-signer.d.ts.map +1 -1
- package/dist/es/services/registry-broker/schemas.d.ts +49 -25
- package/dist/es/services/registry-broker/schemas.d.ts.map +1 -1
- package/dist/es/services/registry-broker/types.d.ts +1 -2
- package/dist/es/services/registry-broker/types.d.ts.map +1 -1
- package/dist/es/services/types.d.ts +1 -0
- package/dist/es/services/types.d.ts.map +1 -1
- package/dist/es/standards-sdk.es.js +64 -51
- package/dist/es/standards-sdk.es.js.map +1 -1
- package/dist/es/standards-sdk.es10.js +2 -2
- package/dist/es/standards-sdk.es100.js +26 -229
- package/dist/es/standards-sdk.es100.js.map +1 -1
- package/dist/es/standards-sdk.es101.js +228 -109
- package/dist/es/standards-sdk.es101.js.map +1 -1
- package/dist/es/standards-sdk.es102.js +94 -15
- package/dist/es/standards-sdk.es102.js.map +1 -1
- package/dist/es/standards-sdk.es103.js +30 -80
- package/dist/es/standards-sdk.es103.js.map +1 -1
- package/dist/es/standards-sdk.es104.js +80 -27
- package/dist/es/standards-sdk.es104.js.map +1 -1
- package/dist/es/standards-sdk.es105.js +25 -136
- package/dist/es/standards-sdk.es105.js.map +1 -1
- package/dist/es/standards-sdk.es106.js +140 -27
- package/dist/es/standards-sdk.es106.js.map +1 -1
- package/dist/es/standards-sdk.es107.js +27 -20
- package/dist/es/standards-sdk.es107.js.map +1 -1
- package/dist/es/standards-sdk.es108.js +18 -156
- package/dist/es/standards-sdk.es108.js.map +1 -1
- package/dist/es/standards-sdk.es109.js +148 -196
- package/dist/es/standards-sdk.es109.js.map +1 -1
- package/dist/es/standards-sdk.es110.js +160 -747
- package/dist/es/standards-sdk.es110.js.map +1 -1
- package/dist/es/standards-sdk.es111.js +786 -9
- package/dist/es/standards-sdk.es111.js.map +1 -1
- package/dist/es/standards-sdk.es112.js +13 -567
- package/dist/es/standards-sdk.es112.js.map +1 -1
- package/dist/es/standards-sdk.es113.js +541 -576
- package/dist/es/standards-sdk.es113.js.map +1 -1
- package/dist/es/standards-sdk.es114.js +601 -12
- package/dist/es/standards-sdk.es114.js.map +1 -1
- package/dist/es/standards-sdk.es115.js +13 -2
- package/dist/es/standards-sdk.es115.js.map +1 -1
- package/dist/es/standards-sdk.es116.js +2 -83
- package/dist/es/standards-sdk.es116.js.map +1 -1
- package/dist/es/standards-sdk.es117.js +80 -36
- package/dist/es/standards-sdk.es117.js.map +1 -1
- package/dist/es/standards-sdk.es118.js +39 -2
- package/dist/es/standards-sdk.es118.js.map +1 -1
- package/dist/es/standards-sdk.es119.js +2 -223
- package/dist/es/standards-sdk.es119.js.map +1 -1
- package/dist/es/standards-sdk.es12.js +1 -1
- package/dist/es/standards-sdk.es120.js +193 -1110
- package/dist/es/standards-sdk.es120.js.map +1 -1
- package/dist/es/standards-sdk.es121.js +1059 -225
- package/dist/es/standards-sdk.es121.js.map +1 -1
- package/dist/es/standards-sdk.es122.js +303 -419
- package/dist/es/standards-sdk.es122.js.map +1 -1
- package/dist/es/standards-sdk.es123.js +418 -351
- package/dist/es/standards-sdk.es123.js.map +1 -1
- package/dist/es/standards-sdk.es124.js +348 -754
- package/dist/es/standards-sdk.es124.js.map +1 -1
- package/dist/es/standards-sdk.es125.js +854 -178
- package/dist/es/standards-sdk.es125.js.map +1 -1
- package/dist/es/standards-sdk.es126.js +153 -1512
- package/dist/es/standards-sdk.es126.js.map +1 -1
- package/dist/es/standards-sdk.es127.js +1373 -1977
- package/dist/es/standards-sdk.es127.js.map +1 -1
- package/dist/es/standards-sdk.es128.js +2211 -50
- package/dist/es/standards-sdk.es128.js.map +1 -1
- package/dist/es/standards-sdk.es129.js +59 -79
- package/dist/es/standards-sdk.es129.js.map +1 -1
- package/dist/es/standards-sdk.es13.js +1 -1
- package/dist/es/standards-sdk.es130.js +80 -152
- package/dist/es/standards-sdk.es130.js.map +1 -1
- package/dist/es/standards-sdk.es131.js +159 -7
- package/dist/es/standards-sdk.es131.js.map +1 -1
- package/dist/es/standards-sdk.es132.js +7 -86
- package/dist/es/standards-sdk.es132.js.map +1 -1
- package/dist/es/standards-sdk.es133.js +65 -44
- package/dist/es/standards-sdk.es133.js.map +1 -1
- package/dist/es/standards-sdk.es134.js +65 -28
- package/dist/es/standards-sdk.es134.js.map +1 -1
- package/dist/es/standards-sdk.es135.js +28 -138
- package/dist/es/standards-sdk.es135.js.map +1 -1
- package/dist/es/standards-sdk.es136.js +133 -37
- package/dist/es/standards-sdk.es136.js.map +1 -1
- package/dist/es/standards-sdk.es137.js +42 -732
- package/dist/es/standards-sdk.es137.js.map +1 -1
- package/dist/es/standards-sdk.es138.js +746 -12254
- package/dist/es/standards-sdk.es138.js.map +1 -1
- package/dist/es/standards-sdk.es139.js +12269 -12
- package/dist/es/standards-sdk.es139.js.map +1 -1
- package/dist/es/standards-sdk.es14.js +1 -1
- package/dist/es/standards-sdk.es141.js +20 -2
- package/dist/es/standards-sdk.es141.js.map +1 -1
- package/dist/es/standards-sdk.es142.js +13 -168
- package/dist/es/standards-sdk.es142.js.map +1 -1
- package/dist/es/standards-sdk.es143.js +139 -289
- package/dist/es/standards-sdk.es143.js.map +1 -1
- package/dist/es/standards-sdk.es144.js +274 -298
- package/dist/es/standards-sdk.es144.js.map +1 -1
- package/dist/es/standards-sdk.es145.js +262 -369
- package/dist/es/standards-sdk.es145.js.map +1 -1
- package/dist/es/standards-sdk.es146.js +316 -194
- package/dist/es/standards-sdk.es146.js.map +1 -1
- package/dist/es/standards-sdk.es147.js +319 -64
- package/dist/es/standards-sdk.es147.js.map +1 -1
- package/dist/es/standards-sdk.es148.js +79 -0
- package/dist/es/standards-sdk.es148.js.map +1 -0
- package/dist/es/standards-sdk.es15.js +1 -1
- package/dist/es/standards-sdk.es16.js +1 -1
- package/dist/es/standards-sdk.es17.js +5 -10
- package/dist/es/standards-sdk.es17.js.map +1 -1
- package/dist/es/standards-sdk.es19.js +12 -16
- package/dist/es/standards-sdk.es19.js.map +1 -1
- package/dist/es/standards-sdk.es20.js +9 -13
- package/dist/es/standards-sdk.es20.js.map +1 -1
- package/dist/es/standards-sdk.es21.js +1 -1
- package/dist/es/standards-sdk.es22.js +1 -1
- package/dist/es/standards-sdk.es23.js +1 -1
- package/dist/es/standards-sdk.es24.js +1 -1
- package/dist/es/standards-sdk.es25.js +1 -1
- package/dist/es/standards-sdk.es26.js +1 -1
- package/dist/es/standards-sdk.es27.js +1 -1
- package/dist/es/standards-sdk.es28.js +16 -18
- package/dist/es/standards-sdk.es28.js.map +1 -1
- package/dist/es/standards-sdk.es29.js.map +1 -1
- package/dist/es/standards-sdk.es3.js +2 -2
- package/dist/es/standards-sdk.es31.js +2 -2
- package/dist/es/standards-sdk.es32.js +4 -4
- package/dist/es/standards-sdk.es33.js +1 -1
- package/dist/es/standards-sdk.es36.js +8 -12
- package/dist/es/standards-sdk.es36.js.map +1 -1
- package/dist/es/standards-sdk.es37.js +4 -4
- package/dist/es/standards-sdk.es38.js +2 -2
- package/dist/es/standards-sdk.es39.js +2 -2
- package/dist/es/standards-sdk.es40.js +1 -1
- package/dist/es/standards-sdk.es41.js +1 -1
- package/dist/es/standards-sdk.es42.js +2 -2
- package/dist/es/standards-sdk.es47.js +1 -1
- package/dist/es/standards-sdk.es5.js +2 -2
- package/dist/es/standards-sdk.es52.js +1 -1
- package/dist/es/standards-sdk.es54.js +1 -1
- package/dist/es/standards-sdk.es57.js +1 -1
- package/dist/es/standards-sdk.es6.js +2 -2
- package/dist/es/standards-sdk.es61.js +7 -11
- package/dist/es/standards-sdk.es61.js.map +1 -1
- package/dist/es/standards-sdk.es65.js +2 -2
- package/dist/es/standards-sdk.es66.js +3 -3
- package/dist/es/standards-sdk.es69.js +2 -2
- package/dist/es/standards-sdk.es7.js +2 -2
- package/dist/es/standards-sdk.es70.js +3 -3
- package/dist/es/standards-sdk.es71.js +2 -2
- package/dist/es/standards-sdk.es72.js +1 -1
- package/dist/es/standards-sdk.es73.js.map +1 -1
- package/dist/es/standards-sdk.es75.js +2 -2
- package/dist/es/standards-sdk.es77.js +5 -3
- package/dist/es/standards-sdk.es77.js.map +1 -1
- package/dist/es/standards-sdk.es78.js +4 -10
- package/dist/es/standards-sdk.es78.js.map +1 -1
- package/dist/es/standards-sdk.es79.js +1 -1
- package/dist/es/standards-sdk.es8.js +1 -1
- package/dist/es/standards-sdk.es80.js +113 -29
- package/dist/es/standards-sdk.es80.js.map +1 -1
- package/dist/es/standards-sdk.es82.js +23 -4
- package/dist/es/standards-sdk.es82.js.map +1 -1
- package/dist/es/standards-sdk.es83.js +39 -14
- package/dist/es/standards-sdk.es83.js.map +1 -1
- package/dist/es/standards-sdk.es84.js +198 -17
- package/dist/es/standards-sdk.es84.js.map +1 -1
- package/dist/es/standards-sdk.es85.js +256 -9
- package/dist/es/standards-sdk.es85.js.map +1 -1
- package/dist/es/standards-sdk.es86.js +55 -21
- package/dist/es/standards-sdk.es86.js.map +1 -1
- package/dist/es/standards-sdk.es87.js +22 -75
- package/dist/es/standards-sdk.es87.js.map +1 -1
- package/dist/es/standards-sdk.es88.js +45 -30
- package/dist/es/standards-sdk.es88.js.map +1 -1
- package/dist/es/standards-sdk.es89.js +57 -22
- package/dist/es/standards-sdk.es89.js.map +1 -1
- package/dist/es/standards-sdk.es90.js +28 -23
- package/dist/es/standards-sdk.es90.js.map +1 -1
- package/dist/es/standards-sdk.es91.js +23 -167
- package/dist/es/standards-sdk.es91.js.map +1 -1
- package/dist/es/standards-sdk.es92.js +158 -119
- package/dist/es/standards-sdk.es92.js.map +1 -1
- package/dist/es/standards-sdk.es93.js +68 -95
- package/dist/es/standards-sdk.es93.js.map +1 -1
- package/dist/es/standards-sdk.es94.js +136 -119
- package/dist/es/standards-sdk.es94.js.map +1 -1
- package/dist/es/standards-sdk.es95.js +139 -39
- package/dist/es/standards-sdk.es95.js.map +1 -1
- package/dist/es/standards-sdk.es96.js +42 -257
- package/dist/es/standards-sdk.es96.js.map +1 -1
- package/dist/es/standards-sdk.es97.js +243 -80
- package/dist/es/standards-sdk.es97.js.map +1 -1
- package/dist/es/standards-sdk.es98.js +47 -48
- package/dist/es/standards-sdk.es98.js.map +1 -1
- package/dist/es/standards-sdk.es99.js +100 -28
- package/dist/es/standards-sdk.es99.js.map +1 -1
- package/dist/es/utils/dynamic-import.d.ts +1 -0
- package/dist/es/utils/dynamic-import.d.ts.map +1 -1
- package/package.json +3 -3
|
@@ -1,55 +1,2216 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
1
|
+
import * as path from "node:path";
|
|
2
|
+
import { Buffer } from "node:buffer";
|
|
3
|
+
import { randomBytes, createHash, createCipheriv, createDecipheriv } from "node:crypto";
|
|
4
|
+
import { secp256k1 } from "@noble/curves/secp256k1.js";
|
|
5
|
+
import { canonicalizeLedgerNetwork } from "./standards-sdk.es130.js";
|
|
6
|
+
import { searchResponseSchema, statsResponseSchema, registriesResponseSchema, additionalRegistryCatalogResponseSchema, popularResponseSchema, resolveResponseSchema, registerAgentResponseSchema, registrationQuoteResponseSchema, registrationProgressResponseSchema, creditPurchaseResponseSchema, x402MinimumsResponseSchema, x402CreditPurchaseResponseSchema, ledgerChallengeResponseSchema, ledgerVerifyResponseSchema, protocolsResponseSchema, detectProtocolResponseSchema, registrySearchByNamespaceSchema, vectorSearchResponseSchema, searchStatusResponseSchema, adapterDetailsResponseSchema, websocketStatsResponseSchema, metricsSummaryResponseSchema, uaidValidationResponseSchema, uaidConnectionStatusSchema, dashboardStatsResponseSchema, adaptersResponseSchema, searchFacetsResponseSchema, createSessionResponseSchema, chatHistorySnapshotResponseSchema, chatHistoryCompactionResponseSchema, sessionEncryptionStatusResponseSchema, encryptionHandshakeResponseSchema, registerEncryptionKeyResponseSchema, sendMessageResponseSchema } from "./standards-sdk.es138.js";
|
|
7
|
+
import { ZodError } from "zod";
|
|
8
|
+
import { createPrivateKeySigner } from "./standards-sdk.es129.js";
|
|
9
|
+
import { optionalImport } from "./standards-sdk.es141.js";
|
|
10
|
+
const getFs = async () => {
|
|
11
|
+
const fsModule = await optionalImport("node:fs");
|
|
12
|
+
if (fsModule && typeof fsModule.existsSync === "function" && typeof fsModule.readFileSync === "function" && typeof fsModule.writeFileSync === "function" && typeof fsModule.appendFileSync === "function") {
|
|
13
|
+
return fsModule;
|
|
14
|
+
}
|
|
15
|
+
return null;
|
|
16
|
+
};
|
|
17
|
+
const DEFAULT_USER_AGENT = "@hol-org/rb-client";
|
|
18
|
+
const DEFAULT_PROGRESS_INTERVAL_MS = 1500;
|
|
19
|
+
const DEFAULT_PROGRESS_TIMEOUT_MS = 5 * 60 * 1e3;
|
|
20
|
+
const createAbortError = () => typeof DOMException === "function" ? new DOMException("Aborted", "AbortError") : new Error("The operation was aborted");
|
|
21
|
+
const normaliseHeaderName = (name) => name.trim().toLowerCase();
|
|
22
|
+
const isBrowserRuntime = () => typeof window !== "undefined" && typeof window.fetch === "function";
|
|
23
|
+
const DEFAULT_BASE_URL = "https://hol.org/registry/api/v1";
|
|
24
|
+
const JSON_CONTENT_TYPE = /application\/json/i;
|
|
25
|
+
const DEFAULT_HISTORY_TOP_UP_HBAR = 0.25;
|
|
26
|
+
const MINIMUM_REGISTRATION_AUTO_TOP_UP_CREDITS = 1;
|
|
27
|
+
const toJsonValue = (value) => {
|
|
28
|
+
if (value === null) {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
if (value instanceof Date) {
|
|
32
|
+
return value.toISOString();
|
|
33
|
+
}
|
|
34
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
35
|
+
return value;
|
|
36
|
+
}
|
|
37
|
+
if (Array.isArray(value)) {
|
|
38
|
+
return value.map((item) => item === void 0 ? null : toJsonValue(item));
|
|
39
|
+
}
|
|
40
|
+
if (typeof value === "object") {
|
|
41
|
+
const result = {};
|
|
42
|
+
Object.entries(value).forEach(
|
|
43
|
+
([key, entryValue]) => {
|
|
44
|
+
if (entryValue !== void 0) {
|
|
45
|
+
result[key] = toJsonValue(entryValue);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
);
|
|
49
|
+
return result;
|
|
50
|
+
}
|
|
51
|
+
throw new TypeError("Only JSON-compatible values are supported");
|
|
52
|
+
};
|
|
53
|
+
const isJsonObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
54
|
+
const toJsonObject = (value) => {
|
|
55
|
+
const normalised = toJsonValue(value);
|
|
56
|
+
if (isJsonObject(normalised)) {
|
|
57
|
+
return normalised;
|
|
58
|
+
}
|
|
59
|
+
throw new TypeError("Expected JSON object value");
|
|
60
|
+
};
|
|
61
|
+
const serialiseAuthConfig = (auth) => {
|
|
62
|
+
const authPayload = {};
|
|
63
|
+
if (auth.type) {
|
|
64
|
+
authPayload.type = auth.type;
|
|
65
|
+
}
|
|
66
|
+
if (auth.token) {
|
|
67
|
+
authPayload.token = auth.token;
|
|
68
|
+
}
|
|
69
|
+
if (auth.username) {
|
|
70
|
+
authPayload.username = auth.username;
|
|
71
|
+
}
|
|
72
|
+
if (auth.password) {
|
|
73
|
+
authPayload.password = auth.password;
|
|
74
|
+
}
|
|
75
|
+
if (auth.headerName) {
|
|
76
|
+
authPayload.headerName = auth.headerName;
|
|
77
|
+
}
|
|
78
|
+
if (auth.headerValue) {
|
|
79
|
+
authPayload.headerValue = auth.headerValue;
|
|
80
|
+
}
|
|
81
|
+
if (auth.headers) {
|
|
82
|
+
authPayload.headers = { ...auth.headers };
|
|
83
|
+
}
|
|
84
|
+
return authPayload;
|
|
85
|
+
};
|
|
86
|
+
const serialiseAgentRegistrationRequest = (payload) => {
|
|
87
|
+
const body = {
|
|
88
|
+
profile: toJsonObject(payload.profile)
|
|
50
89
|
};
|
|
90
|
+
if (payload.endpoint !== void 0) {
|
|
91
|
+
body.endpoint = payload.endpoint;
|
|
92
|
+
}
|
|
93
|
+
if (payload.protocol !== void 0) {
|
|
94
|
+
body.protocol = payload.protocol;
|
|
95
|
+
}
|
|
96
|
+
if (payload.communicationProtocol !== void 0) {
|
|
97
|
+
body.communicationProtocol = payload.communicationProtocol;
|
|
98
|
+
}
|
|
99
|
+
if (payload.registry !== void 0) {
|
|
100
|
+
body.registry = payload.registry;
|
|
101
|
+
}
|
|
102
|
+
if (payload.additionalRegistries !== void 0) {
|
|
103
|
+
body.additionalRegistries = payload.additionalRegistries;
|
|
104
|
+
}
|
|
105
|
+
if (payload.metadata !== void 0) {
|
|
106
|
+
body.metadata = toJsonObject(payload.metadata);
|
|
107
|
+
}
|
|
108
|
+
return body;
|
|
109
|
+
};
|
|
110
|
+
const normalizeHexPrivateKey = (value) => {
|
|
111
|
+
const trimmed = value.trim();
|
|
112
|
+
if (!trimmed) {
|
|
113
|
+
throw new Error("evmPrivateKey is required");
|
|
114
|
+
}
|
|
115
|
+
return trimmed.startsWith("0x") ? trimmed : `0x${trimmed}`;
|
|
51
116
|
};
|
|
117
|
+
class RegistryBrokerError extends Error {
|
|
118
|
+
constructor(message, details) {
|
|
119
|
+
super(message);
|
|
120
|
+
this.status = details.status;
|
|
121
|
+
this.statusText = details.statusText;
|
|
122
|
+
this.body = details.body;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
class RegistryBrokerParseError extends Error {
|
|
126
|
+
constructor(message, cause, rawValue) {
|
|
127
|
+
super(message);
|
|
128
|
+
this.cause = cause;
|
|
129
|
+
this.rawValue = rawValue;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function normaliseBaseUrl(input) {
|
|
133
|
+
const trimmed = input?.trim();
|
|
134
|
+
let baseCandidate = trimmed && trimmed.length > 0 ? trimmed : DEFAULT_BASE_URL;
|
|
135
|
+
try {
|
|
136
|
+
const url = new URL(baseCandidate.replace(/\/+$/, ""));
|
|
137
|
+
const hostname = url.hostname.toLowerCase();
|
|
138
|
+
const ensureRegistryPrefix = () => {
|
|
139
|
+
if (!url.pathname.startsWith("/registry")) {
|
|
140
|
+
url.pathname = url.pathname === "/" ? "/registry" : `/registry${url.pathname}`;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
if (hostname === "hol.org") {
|
|
144
|
+
ensureRegistryPrefix();
|
|
145
|
+
baseCandidate = url.toString();
|
|
146
|
+
} else if (hostname === "registry.hashgraphonline.com" || hostname === "hashgraphonline.com") {
|
|
147
|
+
ensureRegistryPrefix();
|
|
148
|
+
url.hostname = "hol.org";
|
|
149
|
+
baseCandidate = url.toString();
|
|
150
|
+
}
|
|
151
|
+
} catch {
|
|
152
|
+
}
|
|
153
|
+
const withoutTrailing = baseCandidate.replace(/\/+$/, "");
|
|
154
|
+
if (/\/api\/v\d+$/i.test(withoutTrailing)) {
|
|
155
|
+
return withoutTrailing;
|
|
156
|
+
}
|
|
157
|
+
if (/\/api$/i.test(withoutTrailing)) {
|
|
158
|
+
return `${withoutTrailing}/v1`;
|
|
159
|
+
}
|
|
160
|
+
return `${withoutTrailing}/api/v1`;
|
|
161
|
+
}
|
|
162
|
+
function buildSearchQuery(params) {
|
|
163
|
+
const query = new URLSearchParams();
|
|
164
|
+
const appendList = (key, values) => {
|
|
165
|
+
if (!values) {
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
values.forEach((value) => {
|
|
169
|
+
if (typeof value === "string") {
|
|
170
|
+
const trimmed = value.trim();
|
|
171
|
+
if (trimmed.length > 0) {
|
|
172
|
+
query.append(key, trimmed);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
};
|
|
177
|
+
if (params.q) {
|
|
178
|
+
const trimmed = params.q.trim();
|
|
179
|
+
if (trimmed.length > 0) {
|
|
180
|
+
query.set("q", trimmed);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
if (typeof params.page === "number") {
|
|
184
|
+
query.set("page", params.page.toString());
|
|
185
|
+
}
|
|
186
|
+
if (typeof params.limit === "number") {
|
|
187
|
+
query.set("limit", params.limit.toString());
|
|
188
|
+
}
|
|
189
|
+
if (params.registry) {
|
|
190
|
+
const trimmed = params.registry.trim();
|
|
191
|
+
if (trimmed.length > 0) {
|
|
192
|
+
query.set("registry", trimmed);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
appendList("registries", params.registries);
|
|
196
|
+
if (typeof params.minTrust === "number") {
|
|
197
|
+
query.set("minTrust", params.minTrust.toString());
|
|
198
|
+
}
|
|
199
|
+
appendList("capabilities", params.capabilities);
|
|
200
|
+
appendList("protocols", params.protocols);
|
|
201
|
+
appendList("adapters", params.adapters);
|
|
202
|
+
if (params.metadata) {
|
|
203
|
+
Object.entries(params.metadata).forEach(([key, values]) => {
|
|
204
|
+
if (!key || !Array.isArray(values) || values.length === 0) {
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
const trimmedKey = key.trim();
|
|
208
|
+
if (trimmedKey.length === 0) {
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
values.forEach((value) => {
|
|
212
|
+
if (value === void 0 || value === null) {
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
query.append(`metadata.${trimmedKey}`, String(value));
|
|
216
|
+
});
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
if (params.type) {
|
|
220
|
+
const trimmedType = params.type.trim();
|
|
221
|
+
if (trimmedType.length > 0 && trimmedType.toLowerCase() !== "all") {
|
|
222
|
+
query.set("type", trimmedType);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (params.verified === true) {
|
|
226
|
+
query.set("verified", "true");
|
|
227
|
+
}
|
|
228
|
+
if (params.online === true) {
|
|
229
|
+
query.set("online", "true");
|
|
230
|
+
}
|
|
231
|
+
if (params.sortBy) {
|
|
232
|
+
const trimmedSort = params.sortBy.trim();
|
|
233
|
+
if (trimmedSort.length > 0) {
|
|
234
|
+
query.set("sortBy", trimmedSort);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
if (params.sortOrder) {
|
|
238
|
+
const lowered = params.sortOrder.toLowerCase();
|
|
239
|
+
if (lowered === "asc" || lowered === "desc") {
|
|
240
|
+
query.set("sortOrder", lowered);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
const queryString = query.toString();
|
|
244
|
+
return queryString.length > 0 ? `?${queryString}` : "";
|
|
245
|
+
}
|
|
246
|
+
class RegistryBrokerClient {
|
|
247
|
+
constructor(options = {}) {
|
|
248
|
+
this.conversationContexts = /* @__PURE__ */ new Map();
|
|
249
|
+
this.request = async (path2, config) => {
|
|
250
|
+
const headers = new Headers();
|
|
251
|
+
Object.entries(this.defaultHeaders).forEach(([key, value]) => {
|
|
252
|
+
headers.set(key, value);
|
|
253
|
+
});
|
|
254
|
+
if (config.headers) {
|
|
255
|
+
Object.entries(config.headers).forEach(([key, value]) => {
|
|
256
|
+
headers.set(key, value);
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
if (!headers.has("accept")) {
|
|
260
|
+
headers.set("accept", "application/json");
|
|
261
|
+
}
|
|
262
|
+
if (!headers.has("user-agent") && !isBrowserRuntime()) {
|
|
263
|
+
headers.set("user-agent", DEFAULT_USER_AGENT);
|
|
264
|
+
}
|
|
265
|
+
const init = {
|
|
266
|
+
method: config.method ?? "GET",
|
|
267
|
+
headers
|
|
268
|
+
};
|
|
269
|
+
if (config.body !== void 0) {
|
|
270
|
+
init.body = JSON.stringify(config.body);
|
|
271
|
+
if (!headers.has("content-type")) {
|
|
272
|
+
headers.set("content-type", "application/json");
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
const response = await this.fetchImpl(this.buildUrl(path2), init);
|
|
276
|
+
if (response.ok) {
|
|
277
|
+
return response;
|
|
278
|
+
}
|
|
279
|
+
const errorBody = await this.extractErrorBody(response);
|
|
280
|
+
throw new RegistryBrokerError("Registry broker request failed", {
|
|
281
|
+
status: response.status,
|
|
282
|
+
statusText: response.statusText,
|
|
283
|
+
body: errorBody
|
|
284
|
+
});
|
|
285
|
+
};
|
|
286
|
+
this.baseUrl = normaliseBaseUrl(options.baseUrl);
|
|
287
|
+
const fetchCandidate = options.fetchImplementation ?? globalThis.fetch;
|
|
288
|
+
if (!fetchCandidate) {
|
|
289
|
+
throw new Error(
|
|
290
|
+
"A fetch implementation is required for RegistryBrokerClient"
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
this.fetchImpl = fetchCandidate;
|
|
294
|
+
this.defaultHeaders = {};
|
|
295
|
+
if (options.defaultHeaders) {
|
|
296
|
+
Object.entries(options.defaultHeaders).forEach(([name, value]) => {
|
|
297
|
+
if (typeof value === "string") {
|
|
298
|
+
this.setDefaultHeader(name, value);
|
|
299
|
+
}
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
if (options.apiKey && options.apiKey.trim().length > 0) {
|
|
303
|
+
this.setApiKey(options.apiKey);
|
|
304
|
+
}
|
|
305
|
+
if (options.ledgerApiKey && options.ledgerApiKey.trim().length > 0) {
|
|
306
|
+
this.setLedgerApiKey(options.ledgerApiKey);
|
|
307
|
+
}
|
|
308
|
+
this.registrationAutoTopUp = options.registrationAutoTopUp;
|
|
309
|
+
this.historyAutoTopUp = options.historyAutoTopUp;
|
|
310
|
+
this.encryptedChatManager = new EncryptedChatManager(this);
|
|
311
|
+
this.encryptionOptions = options.encryption;
|
|
312
|
+
this.encryptionBootstrapPromise = this.bootstrapEncryptionOptions(
|
|
313
|
+
options.encryption
|
|
314
|
+
);
|
|
315
|
+
this.chat = {
|
|
316
|
+
start: (options2) => this.startChat(options2),
|
|
317
|
+
createSession: (payload) => this.createSession(payload),
|
|
318
|
+
sendMessage: (payload) => this.sendMessage(payload),
|
|
319
|
+
endSession: (sessionId) => this.endSession(sessionId),
|
|
320
|
+
getHistory: (sessionId, options2) => this.fetchHistorySnapshot(sessionId, options2),
|
|
321
|
+
compactHistory: (payload) => this.compactHistory(payload),
|
|
322
|
+
getEncryptionStatus: (sessionId) => this.fetchEncryptionStatus(sessionId),
|
|
323
|
+
submitEncryptionHandshake: (sessionId, payload) => this.postEncryptionHandshake(sessionId, payload),
|
|
324
|
+
startConversation: (opts) => this.startConversation(opts),
|
|
325
|
+
acceptConversation: (opts) => this.acceptConversation(opts)
|
|
326
|
+
};
|
|
327
|
+
this.encryption = {
|
|
328
|
+
registerKey: (payload) => this.registerEncryptionKey(payload),
|
|
329
|
+
generateEphemeralKeyPair: () => this.createEphemeralKeyPair(),
|
|
330
|
+
deriveSharedSecret: (options2) => this.deriveSharedSecret(options2),
|
|
331
|
+
encryptCipherEnvelope: (options2) => this.buildCipherEnvelope(options2),
|
|
332
|
+
decryptCipherEnvelope: (options2) => this.openCipherEnvelope(options2),
|
|
333
|
+
ensureAgentKey: (options2) => this.ensureAgentEncryptionKey(options2)
|
|
334
|
+
};
|
|
335
|
+
this.chat.createEncryptedSession = (options2) => this.encryptedChatManager.startSession(options2);
|
|
336
|
+
this.chat.acceptEncryptedSession = (options2) => this.encryptedChatManager.acceptSession(options2);
|
|
337
|
+
}
|
|
338
|
+
static async initializeAgent(options) {
|
|
339
|
+
const { uaid, ensureEncryptionKey = true, ...clientOptions } = options;
|
|
340
|
+
const client = new RegistryBrokerClient(clientOptions);
|
|
341
|
+
let encryption = null;
|
|
342
|
+
if (ensureEncryptionKey) {
|
|
343
|
+
const ensureOptions = typeof ensureEncryptionKey === "object" ? ensureEncryptionKey : { generateIfMissing: true };
|
|
344
|
+
encryption = await client.encryption.ensureAgentKey({
|
|
345
|
+
uaid,
|
|
346
|
+
...ensureOptions
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
return { client, encryption };
|
|
350
|
+
}
|
|
351
|
+
async loadViemAccount(privateKey) {
|
|
352
|
+
try {
|
|
353
|
+
const viem = await import("viem/accounts");
|
|
354
|
+
return viem.privateKeyToAccount(privateKey);
|
|
355
|
+
} catch (error) {
|
|
356
|
+
const err = new Error(
|
|
357
|
+
'EVM ledger authentication requires the optional dependency "viem". Install it to use evmPrivateKey flows.'
|
|
358
|
+
);
|
|
359
|
+
err.cause = error;
|
|
360
|
+
throw err;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
async loadX402Dependencies() {
|
|
364
|
+
try {
|
|
365
|
+
const [{ default: axios }, x402Axios, x402Types] = await Promise.all([
|
|
366
|
+
import("axios"),
|
|
367
|
+
optionalImport("x402-axios"),
|
|
368
|
+
optionalImport("x402/types")
|
|
369
|
+
]);
|
|
370
|
+
if (!x402Axios || !x402Types) {
|
|
371
|
+
throw new Error(
|
|
372
|
+
"x402-axios and x402/types are required for X402 flows. Install them to enable ledger payments."
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
const withPaymentInterceptor = x402Axios.withPaymentInterceptor;
|
|
376
|
+
const decodePaymentResponse = x402Axios.decodeXPaymentResponse;
|
|
377
|
+
const createX402Signer = x402Types.createSigner;
|
|
378
|
+
const createPaymentClient = (walletClient) => {
|
|
379
|
+
const axiosClient = axios.create({
|
|
380
|
+
baseURL: this.baseUrl,
|
|
381
|
+
headers: {
|
|
382
|
+
...this.getDefaultHeaders(),
|
|
383
|
+
"content-type": "application/json"
|
|
384
|
+
}
|
|
385
|
+
});
|
|
386
|
+
const client = withPaymentInterceptor(axiosClient, walletClient);
|
|
387
|
+
return {
|
|
388
|
+
post: async (url, body) => {
|
|
389
|
+
const response = await client.post(url, body);
|
|
390
|
+
return {
|
|
391
|
+
data: response.data,
|
|
392
|
+
headers: response.headers
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
};
|
|
397
|
+
return {
|
|
398
|
+
createPaymentClient,
|
|
399
|
+
decodePaymentResponse,
|
|
400
|
+
createX402Signer
|
|
401
|
+
};
|
|
402
|
+
} catch (error) {
|
|
403
|
+
const err = new Error(
|
|
404
|
+
'X402 credit purchases require optional dependencies "axios", "x402-axios", and "x402/types". Install them to enable this feature.'
|
|
405
|
+
);
|
|
406
|
+
err.cause = error;
|
|
407
|
+
throw err;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
setApiKey(apiKey) {
|
|
411
|
+
this.setDefaultHeader("x-api-key", apiKey);
|
|
412
|
+
}
|
|
413
|
+
setLedgerApiKey(apiKey) {
|
|
414
|
+
this.setDefaultHeader("x-ledger-api-key", apiKey);
|
|
415
|
+
}
|
|
416
|
+
setDefaultHeader(name, value) {
|
|
417
|
+
if (!name || name.trim().length === 0) {
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
const headerName = normaliseHeaderName(name);
|
|
421
|
+
if (!value || value.trim().length === 0) {
|
|
422
|
+
delete this.defaultHeaders[headerName];
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
this.defaultHeaders[headerName] = value.trim();
|
|
426
|
+
}
|
|
427
|
+
getDefaultHeaders() {
|
|
428
|
+
return { ...this.defaultHeaders };
|
|
429
|
+
}
|
|
430
|
+
async encryptionReady() {
|
|
431
|
+
if (!this.encryptionBootstrapPromise) {
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
await this.encryptionBootstrapPromise;
|
|
435
|
+
}
|
|
436
|
+
async search(params = {}) {
|
|
437
|
+
const query = buildSearchQuery(params);
|
|
438
|
+
const raw = await this.requestJson(`/search${query}`, {
|
|
439
|
+
method: "GET"
|
|
440
|
+
});
|
|
441
|
+
return this.parseWithSchema(raw, searchResponseSchema, "search response");
|
|
442
|
+
}
|
|
443
|
+
async stats() {
|
|
444
|
+
const raw = await this.requestJson("/stats", { method: "GET" });
|
|
445
|
+
return this.parseWithSchema(raw, statsResponseSchema, "stats response");
|
|
446
|
+
}
|
|
447
|
+
async registries() {
|
|
448
|
+
const raw = await this.requestJson("/registries", {
|
|
449
|
+
method: "GET"
|
|
450
|
+
});
|
|
451
|
+
return this.parseWithSchema(
|
|
452
|
+
raw,
|
|
453
|
+
registriesResponseSchema,
|
|
454
|
+
"registries response"
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
async getAdditionalRegistries() {
|
|
458
|
+
const raw = await this.requestJson(
|
|
459
|
+
"/register/additional-registries",
|
|
460
|
+
{
|
|
461
|
+
method: "GET"
|
|
462
|
+
}
|
|
463
|
+
);
|
|
464
|
+
return this.parseWithSchema(
|
|
465
|
+
raw,
|
|
466
|
+
additionalRegistryCatalogResponseSchema,
|
|
467
|
+
"additional registry catalog response"
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
bootstrapEncryptionOptions(options) {
|
|
471
|
+
if (!options?.autoRegister || options.autoRegister.enabled === false) {
|
|
472
|
+
return null;
|
|
473
|
+
}
|
|
474
|
+
return this.autoRegisterEncryptionKey(options.autoRegister).then(
|
|
475
|
+
() => void 0
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
async autoRegisterEncryptionKey(config) {
|
|
479
|
+
const identity = this.normalizeAutoRegisterIdentity(config);
|
|
480
|
+
if (!identity) {
|
|
481
|
+
throw new Error(
|
|
482
|
+
"Auto-registration requires uaid, ledgerAccountId, or email"
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
const material = await this.resolveAutoRegisterKeyMaterial(config);
|
|
486
|
+
if (!material) {
|
|
487
|
+
throw new Error(
|
|
488
|
+
"Unable to resolve encryption public key for auto-registration"
|
|
489
|
+
);
|
|
490
|
+
}
|
|
491
|
+
await this.registerEncryptionKey({
|
|
492
|
+
keyType: config.keyType ?? "secp256k1",
|
|
493
|
+
publicKey: material.publicKey,
|
|
494
|
+
...identity
|
|
495
|
+
});
|
|
496
|
+
return material;
|
|
497
|
+
}
|
|
498
|
+
normalizeAutoRegisterIdentity(config) {
|
|
499
|
+
const identity = {};
|
|
500
|
+
if (config.uaid) {
|
|
501
|
+
identity.uaid = config.uaid;
|
|
502
|
+
}
|
|
503
|
+
if (config.ledgerAccountId) {
|
|
504
|
+
identity.ledgerAccountId = config.ledgerAccountId;
|
|
505
|
+
if (config.ledgerNetwork) {
|
|
506
|
+
identity.ledgerNetwork = config.ledgerNetwork;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
if (config.email) {
|
|
510
|
+
identity.email = config.email;
|
|
511
|
+
}
|
|
512
|
+
if (identity.uaid || identity.ledgerAccountId || identity.email) {
|
|
513
|
+
return identity;
|
|
514
|
+
}
|
|
515
|
+
return null;
|
|
516
|
+
}
|
|
517
|
+
async resolveAutoRegisterKeyMaterial(config) {
|
|
518
|
+
if (config.publicKey?.trim()) {
|
|
519
|
+
return { publicKey: config.publicKey.trim() };
|
|
520
|
+
}
|
|
521
|
+
let privateKey = config.privateKey?.trim();
|
|
522
|
+
const envVar = config.envVar ?? "RB_ENCRYPTION_PRIVATE_KEY";
|
|
523
|
+
if (!privateKey && envVar && process?.env?.[envVar]?.trim()) {
|
|
524
|
+
privateKey = process.env[envVar]?.trim();
|
|
525
|
+
}
|
|
526
|
+
if (!privateKey && config.generateIfMissing) {
|
|
527
|
+
const pair = await this.generateEncryptionKeyPair({
|
|
528
|
+
keyType: config.keyType ?? "secp256k1",
|
|
529
|
+
envVar,
|
|
530
|
+
envPath: config.envPath,
|
|
531
|
+
overwrite: config.overwriteEnv
|
|
532
|
+
});
|
|
533
|
+
if (envVar) {
|
|
534
|
+
process.env[envVar] = pair.privateKey;
|
|
535
|
+
}
|
|
536
|
+
return { publicKey: pair.publicKey, privateKey: pair.privateKey };
|
|
537
|
+
}
|
|
538
|
+
if (privateKey) {
|
|
539
|
+
const publicKey = this.derivePublicKeyFromPrivateKey(privateKey);
|
|
540
|
+
return { publicKey, privateKey };
|
|
541
|
+
}
|
|
542
|
+
return null;
|
|
543
|
+
}
|
|
544
|
+
derivePublicKeyFromPrivateKey(privateKey) {
|
|
545
|
+
const normalized = this.hexToBuffer(privateKey);
|
|
546
|
+
const publicKey = secp256k1.getPublicKey(normalized, true);
|
|
547
|
+
return Buffer.from(publicKey).toString("hex");
|
|
548
|
+
}
|
|
549
|
+
ensureAgentEncryptionKey(options) {
|
|
550
|
+
return this.autoRegisterEncryptionKey({
|
|
551
|
+
...options,
|
|
552
|
+
uaid: options.uaid,
|
|
553
|
+
enabled: true
|
|
554
|
+
});
|
|
555
|
+
}
|
|
556
|
+
async popularSearches() {
|
|
557
|
+
const raw = await this.requestJson("/popular", {
|
|
558
|
+
method: "GET"
|
|
559
|
+
});
|
|
560
|
+
return this.parseWithSchema(
|
|
561
|
+
raw,
|
|
562
|
+
popularResponseSchema,
|
|
563
|
+
"popular searches response"
|
|
564
|
+
);
|
|
565
|
+
}
|
|
566
|
+
async resolveUaid(uaid) {
|
|
567
|
+
const raw = await this.requestJson(
|
|
568
|
+
`/resolve/${encodeURIComponent(uaid)}`,
|
|
569
|
+
{
|
|
570
|
+
method: "GET"
|
|
571
|
+
}
|
|
572
|
+
);
|
|
573
|
+
return this.parseWithSchema(
|
|
574
|
+
raw,
|
|
575
|
+
resolveResponseSchema,
|
|
576
|
+
"resolve UAID response"
|
|
577
|
+
);
|
|
578
|
+
}
|
|
579
|
+
async performRegisterAgent(payload) {
|
|
580
|
+
const raw = await this.requestJson("/register", {
|
|
581
|
+
method: "POST",
|
|
582
|
+
body: serialiseAgentRegistrationRequest(payload),
|
|
583
|
+
headers: { "content-type": "application/json" }
|
|
584
|
+
});
|
|
585
|
+
return this.parseWithSchema(
|
|
586
|
+
raw,
|
|
587
|
+
registerAgentResponseSchema,
|
|
588
|
+
"register agent response"
|
|
589
|
+
);
|
|
590
|
+
}
|
|
591
|
+
async registerAgent(payload, options) {
|
|
592
|
+
const autoTopUp = options?.autoTopUp ?? this.registrationAutoTopUp;
|
|
593
|
+
if (!autoTopUp) {
|
|
594
|
+
return this.performRegisterAgent(payload);
|
|
595
|
+
}
|
|
596
|
+
await this.ensureCreditsForRegistration(payload, autoTopUp);
|
|
597
|
+
let retried = false;
|
|
598
|
+
while (true) {
|
|
599
|
+
try {
|
|
600
|
+
return await this.performRegisterAgent(payload);
|
|
601
|
+
} catch (error) {
|
|
602
|
+
const shortfall = this.extractInsufficientCreditsDetails(error);
|
|
603
|
+
if (shortfall && !retried) {
|
|
604
|
+
await this.ensureCreditsForRegistration(payload, autoTopUp);
|
|
605
|
+
retried = true;
|
|
606
|
+
continue;
|
|
607
|
+
}
|
|
608
|
+
throw error;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
async getRegistrationQuote(payload) {
|
|
613
|
+
const raw = await this.requestJson("/register/quote", {
|
|
614
|
+
method: "POST",
|
|
615
|
+
body: serialiseAgentRegistrationRequest(payload),
|
|
616
|
+
headers: { "content-type": "application/json" }
|
|
617
|
+
});
|
|
618
|
+
return this.parseWithSchema(
|
|
619
|
+
raw,
|
|
620
|
+
registrationQuoteResponseSchema,
|
|
621
|
+
"registration quote response"
|
|
622
|
+
);
|
|
623
|
+
}
|
|
624
|
+
async updateAgent(uaid, payload) {
|
|
625
|
+
const raw = await this.requestJson(
|
|
626
|
+
`/register/${encodeURIComponent(uaid)}`,
|
|
627
|
+
{
|
|
628
|
+
method: "PUT",
|
|
629
|
+
body: serialiseAgentRegistrationRequest(payload),
|
|
630
|
+
headers: { "content-type": "application/json" }
|
|
631
|
+
}
|
|
632
|
+
);
|
|
633
|
+
return this.parseWithSchema(
|
|
634
|
+
raw,
|
|
635
|
+
registerAgentResponseSchema,
|
|
636
|
+
"update agent response"
|
|
637
|
+
);
|
|
638
|
+
}
|
|
639
|
+
async getRegistrationProgress(attemptId) {
|
|
640
|
+
const normalisedAttemptId = attemptId.trim();
|
|
641
|
+
if (!normalisedAttemptId) {
|
|
642
|
+
throw new Error("attemptId is required");
|
|
643
|
+
}
|
|
644
|
+
try {
|
|
645
|
+
const raw = await this.requestJson(
|
|
646
|
+
`/register/progress/${encodeURIComponent(normalisedAttemptId)}`,
|
|
647
|
+
{ method: "GET" }
|
|
648
|
+
);
|
|
649
|
+
const parsed = this.parseWithSchema(
|
|
650
|
+
raw,
|
|
651
|
+
registrationProgressResponseSchema,
|
|
652
|
+
"registration progress response"
|
|
653
|
+
);
|
|
654
|
+
return parsed.progress;
|
|
655
|
+
} catch (error) {
|
|
656
|
+
if (error instanceof RegistryBrokerError && error.status === 404) {
|
|
657
|
+
return null;
|
|
658
|
+
}
|
|
659
|
+
throw error;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
async waitForRegistrationCompletion(attemptId, options = {}) {
|
|
663
|
+
const normalisedAttemptId = attemptId.trim();
|
|
664
|
+
if (!normalisedAttemptId) {
|
|
665
|
+
throw new Error("attemptId is required");
|
|
666
|
+
}
|
|
667
|
+
const interval = Math.max(
|
|
668
|
+
250,
|
|
669
|
+
options.intervalMs ?? DEFAULT_PROGRESS_INTERVAL_MS
|
|
670
|
+
);
|
|
671
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_PROGRESS_TIMEOUT_MS;
|
|
672
|
+
const throwOnFailure = options.throwOnFailure ?? true;
|
|
673
|
+
const signal = options.signal;
|
|
674
|
+
const startedAt = Date.now();
|
|
675
|
+
while (true) {
|
|
676
|
+
if (signal?.aborted) {
|
|
677
|
+
throw createAbortError();
|
|
678
|
+
}
|
|
679
|
+
const progress = await this.getRegistrationProgress(normalisedAttemptId);
|
|
680
|
+
if (progress) {
|
|
681
|
+
options.onProgress?.(progress);
|
|
682
|
+
if (progress.status === "completed") {
|
|
683
|
+
return progress;
|
|
684
|
+
}
|
|
685
|
+
if (progress.status === "partial" || progress.status === "failed") {
|
|
686
|
+
if (throwOnFailure) {
|
|
687
|
+
throw new RegistryBrokerError(
|
|
688
|
+
"Registration did not complete successfully",
|
|
689
|
+
{
|
|
690
|
+
status: 409,
|
|
691
|
+
statusText: progress.status,
|
|
692
|
+
body: progress
|
|
693
|
+
}
|
|
694
|
+
);
|
|
695
|
+
}
|
|
696
|
+
return progress;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
if (Date.now() - startedAt >= timeoutMs) {
|
|
700
|
+
throw new Error(
|
|
701
|
+
`Registration progress polling timed out after ${timeoutMs}ms`
|
|
702
|
+
);
|
|
703
|
+
}
|
|
704
|
+
await this.delay(interval, signal);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
async purchaseCreditsWithHbar(params) {
|
|
708
|
+
const body = {
|
|
709
|
+
accountId: params.accountId,
|
|
710
|
+
payerKey: params.privateKey,
|
|
711
|
+
hbarAmount: this.calculateHbarAmountParam(params.hbarAmount)
|
|
712
|
+
};
|
|
713
|
+
if (params.memo) {
|
|
714
|
+
body.memo = params.memo;
|
|
715
|
+
}
|
|
716
|
+
if (params.metadata) {
|
|
717
|
+
body.metadata = params.metadata;
|
|
718
|
+
}
|
|
719
|
+
const raw = await this.requestJson("/credits/purchase", {
|
|
720
|
+
method: "POST",
|
|
721
|
+
headers: { "content-type": "application/json" },
|
|
722
|
+
body
|
|
723
|
+
});
|
|
724
|
+
return this.parseWithSchema(
|
|
725
|
+
raw,
|
|
726
|
+
creditPurchaseResponseSchema,
|
|
727
|
+
"credit purchase response"
|
|
728
|
+
);
|
|
729
|
+
}
|
|
730
|
+
async getX402Minimums() {
|
|
731
|
+
const raw = await this.requestJson(
|
|
732
|
+
"/credits/purchase/x402/minimums",
|
|
733
|
+
{ method: "GET" }
|
|
734
|
+
);
|
|
735
|
+
return this.parseWithSchema(
|
|
736
|
+
raw,
|
|
737
|
+
x402MinimumsResponseSchema,
|
|
738
|
+
"x402 minimums response"
|
|
739
|
+
);
|
|
740
|
+
}
|
|
741
|
+
async purchaseCreditsWithX402(params) {
|
|
742
|
+
const { createPaymentClient, decodePaymentResponse } = await this.loadX402Dependencies();
|
|
743
|
+
if (!Number.isFinite(params.credits) || params.credits <= 0) {
|
|
744
|
+
throw new Error("credits must be a positive number");
|
|
745
|
+
}
|
|
746
|
+
if (params.usdAmount !== void 0 && (!Number.isFinite(params.usdAmount) || params.usdAmount <= 0)) {
|
|
747
|
+
throw new Error("usdAmount must be a positive number when provided");
|
|
748
|
+
}
|
|
749
|
+
const body = {
|
|
750
|
+
accountId: params.accountId,
|
|
751
|
+
credits: params.credits
|
|
752
|
+
};
|
|
753
|
+
if (params.usdAmount !== void 0) {
|
|
754
|
+
body.usdAmount = params.usdAmount;
|
|
755
|
+
}
|
|
756
|
+
if (params.description) {
|
|
757
|
+
body.description = params.description;
|
|
758
|
+
}
|
|
759
|
+
if (params.metadata) {
|
|
760
|
+
body.metadata = params.metadata;
|
|
761
|
+
}
|
|
762
|
+
const paymentClient = createPaymentClient(params.walletClient);
|
|
763
|
+
const response = await paymentClient.post("/credits/purchase/x402", body);
|
|
764
|
+
const parsed = this.parseWithSchema(
|
|
765
|
+
response.data,
|
|
766
|
+
x402CreditPurchaseResponseSchema,
|
|
767
|
+
"x402 credit purchase response"
|
|
768
|
+
);
|
|
769
|
+
const responseHeaders = response.headers ?? {};
|
|
770
|
+
const paymentHeader = typeof responseHeaders["x-payment-response"] === "string" ? responseHeaders["x-payment-response"] : void 0;
|
|
771
|
+
const decodedPayment = paymentHeader !== void 0 ? decodePaymentResponse(paymentHeader) : void 0;
|
|
772
|
+
return {
|
|
773
|
+
...parsed,
|
|
774
|
+
paymentResponseHeader: paymentHeader,
|
|
775
|
+
paymentResponse: decodedPayment
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
async buyCreditsWithX402(params) {
|
|
779
|
+
const network = params.network ?? "base";
|
|
780
|
+
const { createX402Signer } = await this.loadX402Dependencies();
|
|
781
|
+
const normalizedKey = normalizeHexPrivateKey(params.evmPrivateKey);
|
|
782
|
+
const walletClient = await createX402Signer(network, normalizedKey);
|
|
783
|
+
return this.purchaseCreditsWithX402({
|
|
784
|
+
accountId: params.accountId,
|
|
785
|
+
credits: params.credits,
|
|
786
|
+
usdAmount: params.usdAmount,
|
|
787
|
+
description: params.description,
|
|
788
|
+
metadata: params.metadata,
|
|
789
|
+
walletClient
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
calculateHbarAmount(creditsToPurchase, creditsPerHbar) {
|
|
793
|
+
if (creditsPerHbar <= 0) {
|
|
794
|
+
throw new Error("creditsPerHbar must be positive");
|
|
795
|
+
}
|
|
796
|
+
if (creditsToPurchase <= 0) {
|
|
797
|
+
throw new Error("creditsToPurchase must be positive");
|
|
798
|
+
}
|
|
799
|
+
const rawHbar = creditsToPurchase / creditsPerHbar;
|
|
800
|
+
const tinybars = Math.ceil(rawHbar * 1e8);
|
|
801
|
+
return tinybars / 1e8;
|
|
802
|
+
}
|
|
803
|
+
resolveCreditsToPurchase(shortfallCredits) {
|
|
804
|
+
if (!Number.isFinite(shortfallCredits) || shortfallCredits <= 0) {
|
|
805
|
+
return 0;
|
|
806
|
+
}
|
|
807
|
+
return Math.max(
|
|
808
|
+
Math.ceil(shortfallCredits),
|
|
809
|
+
MINIMUM_REGISTRATION_AUTO_TOP_UP_CREDITS
|
|
810
|
+
);
|
|
811
|
+
}
|
|
812
|
+
calculateHbarAmountParam(hbarAmount) {
|
|
813
|
+
const tinybars = Math.ceil(hbarAmount * 1e8);
|
|
814
|
+
if (tinybars <= 0) {
|
|
815
|
+
throw new Error("Calculated purchase amount must be positive");
|
|
816
|
+
}
|
|
817
|
+
return tinybars / 1e8;
|
|
818
|
+
}
|
|
819
|
+
shouldAutoTopUpHistory(payload, error) {
|
|
820
|
+
if (!this.historyAutoTopUp || payload.historyTtlSeconds === void 0) {
|
|
821
|
+
return false;
|
|
822
|
+
}
|
|
823
|
+
if (!(error instanceof RegistryBrokerError)) {
|
|
824
|
+
return false;
|
|
825
|
+
}
|
|
826
|
+
if (error.status !== 402) {
|
|
827
|
+
return false;
|
|
828
|
+
}
|
|
829
|
+
const message = this.extractErrorMessage(error.body);
|
|
830
|
+
if (!message) {
|
|
831
|
+
return true;
|
|
832
|
+
}
|
|
833
|
+
const normalised = message.toLowerCase();
|
|
834
|
+
return normalised.includes("history") || normalised.includes("chat history");
|
|
835
|
+
}
|
|
836
|
+
extractErrorMessage(body) {
|
|
837
|
+
if (typeof body === "string") {
|
|
838
|
+
return body;
|
|
839
|
+
}
|
|
840
|
+
if (isJsonObject(body) && typeof body.error === "string") {
|
|
841
|
+
return body.error;
|
|
842
|
+
}
|
|
843
|
+
if (isJsonObject(body) && typeof body.message === "string") {
|
|
844
|
+
return body.message;
|
|
845
|
+
}
|
|
846
|
+
return void 0;
|
|
847
|
+
}
|
|
848
|
+
async executeHistoryAutoTopUp(reason) {
|
|
849
|
+
if (!this.historyAutoTopUp) {
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
const hbarAmount = this.historyAutoTopUp.hbarAmount && this.historyAutoTopUp.hbarAmount > 0 ? this.historyAutoTopUp.hbarAmount : DEFAULT_HISTORY_TOP_UP_HBAR;
|
|
853
|
+
await this.purchaseCreditsWithHbar({
|
|
854
|
+
accountId: this.historyAutoTopUp.accountId,
|
|
855
|
+
privateKey: this.historyAutoTopUp.privateKey,
|
|
856
|
+
hbarAmount,
|
|
857
|
+
memo: this.historyAutoTopUp.memo ?? "registry-broker-client:chat-history-topup",
|
|
858
|
+
metadata: {
|
|
859
|
+
purpose: "chat-history",
|
|
860
|
+
reason
|
|
861
|
+
}
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
async ensureCreditsForRegistration(payload, autoTopUp) {
|
|
865
|
+
const details = autoTopUp ?? null;
|
|
866
|
+
if (!details) {
|
|
867
|
+
return;
|
|
868
|
+
}
|
|
869
|
+
if (!details.accountId || !details.accountId.trim()) {
|
|
870
|
+
throw new Error("autoTopUp.accountId is required");
|
|
871
|
+
}
|
|
872
|
+
if (!details.privateKey || !details.privateKey.trim()) {
|
|
873
|
+
throw new Error("autoTopUp.privateKey is required");
|
|
874
|
+
}
|
|
875
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
876
|
+
const quote = await this.getRegistrationQuote(payload);
|
|
877
|
+
const shortfall = quote.shortfallCredits ?? 0;
|
|
878
|
+
if (shortfall <= 0) {
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
const creditsToPurchase = this.resolveCreditsToPurchase(shortfall);
|
|
882
|
+
if (creditsToPurchase <= 0) {
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
const creditsPerHbar = quote.creditsPerHbar ?? null;
|
|
886
|
+
if (!creditsPerHbar || creditsPerHbar <= 0) {
|
|
887
|
+
throw new Error("Unable to determine credits per HBAR for auto top-up");
|
|
888
|
+
}
|
|
889
|
+
const hbarAmount = this.calculateHbarAmount(
|
|
890
|
+
creditsToPurchase,
|
|
891
|
+
creditsPerHbar
|
|
892
|
+
);
|
|
893
|
+
await this.purchaseCreditsWithHbar({
|
|
894
|
+
accountId: details.accountId.trim(),
|
|
895
|
+
privateKey: details.privateKey.trim(),
|
|
896
|
+
hbarAmount,
|
|
897
|
+
memo: details.memo ?? "Registry Broker auto top-up",
|
|
898
|
+
metadata: {
|
|
899
|
+
shortfallCredits: shortfall,
|
|
900
|
+
requiredCredits: quote.requiredCredits,
|
|
901
|
+
purchasedCredits: creditsToPurchase
|
|
902
|
+
}
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
const finalQuote = await this.getRegistrationQuote(payload);
|
|
906
|
+
if ((finalQuote.shortfallCredits ?? 0) > 0) {
|
|
907
|
+
throw new Error("Unable to purchase sufficient credits for registration");
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
extractInsufficientCreditsDetails(error) {
|
|
911
|
+
if (!(error instanceof RegistryBrokerError) || error.status !== 402) {
|
|
912
|
+
return null;
|
|
913
|
+
}
|
|
914
|
+
const body = error.body;
|
|
915
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
916
|
+
return null;
|
|
917
|
+
}
|
|
918
|
+
const maybeShortfall = body["shortfallCredits"];
|
|
919
|
+
if (typeof maybeShortfall !== "number" || maybeShortfall <= 0) {
|
|
920
|
+
return null;
|
|
921
|
+
}
|
|
922
|
+
return { shortfallCredits: maybeShortfall };
|
|
923
|
+
}
|
|
924
|
+
async createLedgerChallenge(payload) {
|
|
925
|
+
const resolvedNetwork = canonicalizeLedgerNetwork(payload.network);
|
|
926
|
+
const network = resolvedNetwork.kind === "hedera" ? resolvedNetwork.hederaNetwork ?? resolvedNetwork.canonical : resolvedNetwork.canonical;
|
|
927
|
+
const raw = await this.requestJson("/auth/ledger/challenge", {
|
|
928
|
+
method: "POST",
|
|
929
|
+
headers: { "content-type": "application/json" },
|
|
930
|
+
body: {
|
|
931
|
+
accountId: payload.accountId,
|
|
932
|
+
network
|
|
933
|
+
}
|
|
934
|
+
});
|
|
935
|
+
return this.parseWithSchema(
|
|
936
|
+
raw,
|
|
937
|
+
ledgerChallengeResponseSchema,
|
|
938
|
+
"ledger challenge response"
|
|
939
|
+
);
|
|
940
|
+
}
|
|
941
|
+
async verifyLedgerChallenge(payload) {
|
|
942
|
+
const resolvedNetwork = canonicalizeLedgerNetwork(payload.network);
|
|
943
|
+
const network = resolvedNetwork.kind === "hedera" ? resolvedNetwork.hederaNetwork ?? resolvedNetwork.canonical : resolvedNetwork.canonical;
|
|
944
|
+
const body = {
|
|
945
|
+
challengeId: payload.challengeId,
|
|
946
|
+
accountId: payload.accountId,
|
|
947
|
+
network,
|
|
948
|
+
signature: payload.signature
|
|
949
|
+
};
|
|
950
|
+
if (payload.signatureKind) {
|
|
951
|
+
body.signatureKind = payload.signatureKind;
|
|
952
|
+
}
|
|
953
|
+
if (payload.publicKey) {
|
|
954
|
+
body.publicKey = payload.publicKey;
|
|
955
|
+
}
|
|
956
|
+
if (typeof payload.expiresInMinutes === "number") {
|
|
957
|
+
body.expiresInMinutes = payload.expiresInMinutes;
|
|
958
|
+
}
|
|
959
|
+
const raw = await this.requestJson("/auth/ledger/verify", {
|
|
960
|
+
method: "POST",
|
|
961
|
+
headers: { "content-type": "application/json" },
|
|
962
|
+
body
|
|
963
|
+
});
|
|
964
|
+
const result = this.parseWithSchema(
|
|
965
|
+
raw,
|
|
966
|
+
ledgerVerifyResponseSchema,
|
|
967
|
+
"ledger verification response"
|
|
968
|
+
);
|
|
969
|
+
this.setLedgerApiKey(result.key);
|
|
970
|
+
return result;
|
|
971
|
+
}
|
|
972
|
+
async authenticateWithLedger(options) {
|
|
973
|
+
const challenge = await this.createLedgerChallenge({
|
|
974
|
+
accountId: options.accountId,
|
|
975
|
+
network: options.network
|
|
976
|
+
});
|
|
977
|
+
const signed = await this.resolveLedgerAuthSignature(
|
|
978
|
+
challenge.message,
|
|
979
|
+
options
|
|
980
|
+
);
|
|
981
|
+
const verification = await this.verifyLedgerChallenge({
|
|
982
|
+
challengeId: challenge.challengeId,
|
|
983
|
+
accountId: options.accountId,
|
|
984
|
+
network: options.network,
|
|
985
|
+
signature: signed.signature,
|
|
986
|
+
signatureKind: signed.signatureKind,
|
|
987
|
+
publicKey: signed.publicKey,
|
|
988
|
+
expiresInMinutes: options.expiresInMinutes
|
|
989
|
+
});
|
|
990
|
+
return verification;
|
|
991
|
+
}
|
|
992
|
+
async resolveLedgerAuthSignature(message, options) {
|
|
993
|
+
if (typeof options.sign === "function") {
|
|
994
|
+
const result = await options.sign(message);
|
|
995
|
+
if (!result || typeof result.signature !== "string" || result.signature.length === 0) {
|
|
996
|
+
throw new Error("Custom ledger signer failed to produce a signature.");
|
|
997
|
+
}
|
|
998
|
+
return result;
|
|
999
|
+
}
|
|
1000
|
+
if (!options.signer || typeof options.signer.sign !== "function") {
|
|
1001
|
+
throw new Error(
|
|
1002
|
+
"Ledger authentication requires a Hedera Signer or custom sign function."
|
|
1003
|
+
);
|
|
1004
|
+
}
|
|
1005
|
+
const payload = Buffer.from(message, "utf8");
|
|
1006
|
+
const signatures = await options.signer.sign([payload]);
|
|
1007
|
+
const signatureEntry = signatures?.[0];
|
|
1008
|
+
if (!signatureEntry) {
|
|
1009
|
+
throw new Error("Signer did not return any signatures.");
|
|
1010
|
+
}
|
|
1011
|
+
let derivedPublicKey;
|
|
1012
|
+
if (signatureEntry.publicKey) {
|
|
1013
|
+
derivedPublicKey = signatureEntry.publicKey.toString();
|
|
1014
|
+
} else if (typeof options.signer.getAccountKey === "function") {
|
|
1015
|
+
const accountKey = await options.signer.getAccountKey();
|
|
1016
|
+
if (accountKey && typeof accountKey.toString === "function") {
|
|
1017
|
+
derivedPublicKey = accountKey.toString();
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
return {
|
|
1021
|
+
signature: Buffer.from(signatureEntry.signature).toString("base64"),
|
|
1022
|
+
signatureKind: "raw",
|
|
1023
|
+
publicKey: derivedPublicKey
|
|
1024
|
+
};
|
|
1025
|
+
}
|
|
1026
|
+
async authenticateWithLedgerCredentials(options) {
|
|
1027
|
+
const {
|
|
1028
|
+
accountId,
|
|
1029
|
+
network,
|
|
1030
|
+
signer,
|
|
1031
|
+
sign,
|
|
1032
|
+
hederaPrivateKey,
|
|
1033
|
+
evmPrivateKey,
|
|
1034
|
+
expiresInMinutes,
|
|
1035
|
+
setAccountHeader = true,
|
|
1036
|
+
label,
|
|
1037
|
+
logger
|
|
1038
|
+
} = options;
|
|
1039
|
+
const resolvedNetwork = canonicalizeLedgerNetwork(network);
|
|
1040
|
+
const labelSuffix = label ? ` for ${label}` : "";
|
|
1041
|
+
const networkPayload = resolvedNetwork.canonical;
|
|
1042
|
+
const authOptions = {
|
|
1043
|
+
accountId,
|
|
1044
|
+
network: networkPayload,
|
|
1045
|
+
expiresInMinutes
|
|
1046
|
+
};
|
|
1047
|
+
if (sign) {
|
|
1048
|
+
authOptions.sign = sign;
|
|
1049
|
+
} else if (signer) {
|
|
1050
|
+
authOptions.signer = signer;
|
|
1051
|
+
} else if (hederaPrivateKey) {
|
|
1052
|
+
if (resolvedNetwork.kind !== "hedera" || !resolvedNetwork.hederaNetwork) {
|
|
1053
|
+
throw new Error(
|
|
1054
|
+
"hederaPrivateKey can only be used with hedera:mainnet or hedera:testnet networks."
|
|
1055
|
+
);
|
|
1056
|
+
}
|
|
1057
|
+
authOptions.signer = createPrivateKeySigner({
|
|
1058
|
+
accountId,
|
|
1059
|
+
privateKey: hederaPrivateKey,
|
|
1060
|
+
network: resolvedNetwork.hederaNetwork
|
|
1061
|
+
});
|
|
1062
|
+
} else if (evmPrivateKey) {
|
|
1063
|
+
if (resolvedNetwork.kind !== "evm") {
|
|
1064
|
+
throw new Error(
|
|
1065
|
+
"evmPrivateKey can only be used with CAIP-2 EVM networks (eip155:<chainId>)."
|
|
1066
|
+
);
|
|
1067
|
+
}
|
|
1068
|
+
const formattedKey = evmPrivateKey.startsWith("0x") ? evmPrivateKey : `0x${evmPrivateKey}`;
|
|
1069
|
+
const account = await this.loadViemAccount(formattedKey);
|
|
1070
|
+
authOptions.sign = async (message) => ({
|
|
1071
|
+
signature: await account.signMessage({ message }),
|
|
1072
|
+
signatureKind: "evm",
|
|
1073
|
+
publicKey: account.publicKey
|
|
1074
|
+
});
|
|
1075
|
+
} else {
|
|
1076
|
+
throw new Error(
|
|
1077
|
+
"Provide a signer, sign function, hederaPrivateKey, or evmPrivateKey to authenticate with the ledger."
|
|
1078
|
+
);
|
|
1079
|
+
}
|
|
1080
|
+
logger?.info?.(
|
|
1081
|
+
`Authenticating ledger account ${accountId} (${resolvedNetwork.canonical})${labelSuffix}...`
|
|
1082
|
+
);
|
|
1083
|
+
const verification = await this.authenticateWithLedger(authOptions);
|
|
1084
|
+
if (setAccountHeader) {
|
|
1085
|
+
this.setDefaultHeader("x-account-id", verification.accountId);
|
|
1086
|
+
}
|
|
1087
|
+
logger?.info?.(
|
|
1088
|
+
`Ledger authentication complete${labelSuffix}. Issued key prefix: ${verification.apiKey.prefix}…${verification.apiKey.lastFour}`
|
|
1089
|
+
);
|
|
1090
|
+
return verification;
|
|
1091
|
+
}
|
|
1092
|
+
async listProtocols() {
|
|
1093
|
+
const raw = await this.requestJson("/protocols", {
|
|
1094
|
+
method: "GET"
|
|
1095
|
+
});
|
|
1096
|
+
return this.parseWithSchema(
|
|
1097
|
+
raw,
|
|
1098
|
+
protocolsResponseSchema,
|
|
1099
|
+
"protocols response"
|
|
1100
|
+
);
|
|
1101
|
+
}
|
|
1102
|
+
async detectProtocol(message) {
|
|
1103
|
+
const raw = await this.requestJson("/detect-protocol", {
|
|
1104
|
+
method: "POST",
|
|
1105
|
+
body: { message },
|
|
1106
|
+
headers: { "content-type": "application/json" }
|
|
1107
|
+
});
|
|
1108
|
+
return this.parseWithSchema(
|
|
1109
|
+
raw,
|
|
1110
|
+
detectProtocolResponseSchema,
|
|
1111
|
+
"detect protocol response"
|
|
1112
|
+
);
|
|
1113
|
+
}
|
|
1114
|
+
async registrySearchByNamespace(registry, query) {
|
|
1115
|
+
const params = new URLSearchParams();
|
|
1116
|
+
if (query) {
|
|
1117
|
+
params.set("q", query);
|
|
1118
|
+
}
|
|
1119
|
+
const suffix = params.size > 0 ? `?${params.toString()}` : "";
|
|
1120
|
+
const raw = await this.requestJson(
|
|
1121
|
+
`/registries/${encodeURIComponent(registry)}/search${suffix}`,
|
|
1122
|
+
{
|
|
1123
|
+
method: "GET"
|
|
1124
|
+
}
|
|
1125
|
+
);
|
|
1126
|
+
return this.parseWithSchema(
|
|
1127
|
+
raw,
|
|
1128
|
+
registrySearchByNamespaceSchema,
|
|
1129
|
+
"registry search response"
|
|
1130
|
+
);
|
|
1131
|
+
}
|
|
1132
|
+
async vectorSearch(request) {
|
|
1133
|
+
try {
|
|
1134
|
+
const raw = await this.requestJson("/search", {
|
|
1135
|
+
method: "POST",
|
|
1136
|
+
body: request,
|
|
1137
|
+
headers: { "content-type": "application/json" }
|
|
1138
|
+
});
|
|
1139
|
+
return this.parseWithSchema(
|
|
1140
|
+
raw,
|
|
1141
|
+
vectorSearchResponseSchema,
|
|
1142
|
+
"vector search response"
|
|
1143
|
+
);
|
|
1144
|
+
} catch (error) {
|
|
1145
|
+
if (error instanceof RegistryBrokerError && error.status === 501) {
|
|
1146
|
+
const fallback = await this.search(
|
|
1147
|
+
this.buildVectorFallbackSearchParams(request)
|
|
1148
|
+
);
|
|
1149
|
+
return this.convertSearchResultToVectorResponse(fallback);
|
|
1150
|
+
}
|
|
1151
|
+
throw error;
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
async searchStatus() {
|
|
1155
|
+
const raw = await this.requestJson("/search/status", {
|
|
1156
|
+
method: "GET"
|
|
1157
|
+
});
|
|
1158
|
+
return this.parseWithSchema(
|
|
1159
|
+
raw,
|
|
1160
|
+
searchStatusResponseSchema,
|
|
1161
|
+
"search status response"
|
|
1162
|
+
);
|
|
1163
|
+
}
|
|
1164
|
+
async adaptersDetailed() {
|
|
1165
|
+
const raw = await this.requestJson("/adapters/details", {
|
|
1166
|
+
method: "GET"
|
|
1167
|
+
});
|
|
1168
|
+
return this.parseWithSchema(
|
|
1169
|
+
raw,
|
|
1170
|
+
adapterDetailsResponseSchema,
|
|
1171
|
+
"adapter details response"
|
|
1172
|
+
);
|
|
1173
|
+
}
|
|
1174
|
+
async websocketStats() {
|
|
1175
|
+
const raw = await this.requestJson("/websocket/stats", {
|
|
1176
|
+
method: "GET"
|
|
1177
|
+
});
|
|
1178
|
+
return this.parseWithSchema(
|
|
1179
|
+
raw,
|
|
1180
|
+
websocketStatsResponseSchema,
|
|
1181
|
+
"websocket stats response"
|
|
1182
|
+
);
|
|
1183
|
+
}
|
|
1184
|
+
async metricsSummary() {
|
|
1185
|
+
const raw = await this.requestJson("/metrics", {
|
|
1186
|
+
method: "GET"
|
|
1187
|
+
});
|
|
1188
|
+
return this.parseWithSchema(
|
|
1189
|
+
raw,
|
|
1190
|
+
metricsSummaryResponseSchema,
|
|
1191
|
+
"metrics summary response"
|
|
1192
|
+
);
|
|
1193
|
+
}
|
|
1194
|
+
async validateUaid(uaid) {
|
|
1195
|
+
const raw = await this.requestJson(
|
|
1196
|
+
`/uaids/validate/${encodeURIComponent(uaid)}`,
|
|
1197
|
+
{
|
|
1198
|
+
method: "GET"
|
|
1199
|
+
}
|
|
1200
|
+
);
|
|
1201
|
+
return this.parseWithSchema(
|
|
1202
|
+
raw,
|
|
1203
|
+
uaidValidationResponseSchema,
|
|
1204
|
+
"UAID validation response"
|
|
1205
|
+
);
|
|
1206
|
+
}
|
|
1207
|
+
async getUaidConnectionStatus(uaid) {
|
|
1208
|
+
const raw = await this.requestJson(
|
|
1209
|
+
`/uaids/connections/${encodeURIComponent(uaid)}/status`,
|
|
1210
|
+
{
|
|
1211
|
+
method: "GET"
|
|
1212
|
+
}
|
|
1213
|
+
);
|
|
1214
|
+
return this.parseWithSchema(
|
|
1215
|
+
raw,
|
|
1216
|
+
uaidConnectionStatusSchema,
|
|
1217
|
+
"UAID connection status"
|
|
1218
|
+
);
|
|
1219
|
+
}
|
|
1220
|
+
async closeUaidConnection(uaid) {
|
|
1221
|
+
await this.request(`/uaids/connections/${encodeURIComponent(uaid)}`, {
|
|
1222
|
+
method: "DELETE"
|
|
1223
|
+
});
|
|
1224
|
+
}
|
|
1225
|
+
async dashboardStats() {
|
|
1226
|
+
const raw = await this.requestJson("/dashboard/stats", {
|
|
1227
|
+
method: "GET"
|
|
1228
|
+
});
|
|
1229
|
+
return this.parseWithSchema(
|
|
1230
|
+
raw,
|
|
1231
|
+
dashboardStatsResponseSchema,
|
|
1232
|
+
"dashboard stats response"
|
|
1233
|
+
);
|
|
1234
|
+
}
|
|
1235
|
+
async adapters() {
|
|
1236
|
+
const raw = await this.requestJson("/adapters", {
|
|
1237
|
+
method: "GET"
|
|
1238
|
+
});
|
|
1239
|
+
return this.parseWithSchema(
|
|
1240
|
+
raw,
|
|
1241
|
+
adaptersResponseSchema,
|
|
1242
|
+
"adapters response"
|
|
1243
|
+
);
|
|
1244
|
+
}
|
|
1245
|
+
async facets(adapter) {
|
|
1246
|
+
const params = new URLSearchParams();
|
|
1247
|
+
if (adapter) {
|
|
1248
|
+
params.set("adapter", adapter);
|
|
1249
|
+
}
|
|
1250
|
+
const suffix = params.size > 0 ? `?${params.toString()}` : "";
|
|
1251
|
+
const raw = await this.requestJson(`/search/facets${suffix}`, {
|
|
1252
|
+
method: "GET"
|
|
1253
|
+
});
|
|
1254
|
+
return this.parseWithSchema(
|
|
1255
|
+
raw,
|
|
1256
|
+
searchFacetsResponseSchema,
|
|
1257
|
+
"search facets response"
|
|
1258
|
+
);
|
|
1259
|
+
}
|
|
1260
|
+
async createSession(payload, allowHistoryAutoTopUp = true) {
|
|
1261
|
+
const body = {};
|
|
1262
|
+
if ("uaid" in payload && payload.uaid) {
|
|
1263
|
+
body.uaid = payload.uaid;
|
|
1264
|
+
}
|
|
1265
|
+
if ("agentUrl" in payload && payload.agentUrl) {
|
|
1266
|
+
body.agentUrl = payload.agentUrl;
|
|
1267
|
+
}
|
|
1268
|
+
if (payload.auth) {
|
|
1269
|
+
body.auth = serialiseAuthConfig(payload.auth);
|
|
1270
|
+
}
|
|
1271
|
+
if (payload.historyTtlSeconds !== void 0) {
|
|
1272
|
+
body.historyTtlSeconds = payload.historyTtlSeconds;
|
|
1273
|
+
}
|
|
1274
|
+
if (payload.encryptionRequested !== void 0) {
|
|
1275
|
+
body.encryptionRequested = payload.encryptionRequested;
|
|
1276
|
+
}
|
|
1277
|
+
if (payload.senderUaid) {
|
|
1278
|
+
body.senderUaid = payload.senderUaid;
|
|
1279
|
+
}
|
|
1280
|
+
try {
|
|
1281
|
+
const raw = await this.requestJson("/chat/session", {
|
|
1282
|
+
method: "POST",
|
|
1283
|
+
body,
|
|
1284
|
+
headers: { "content-type": "application/json" }
|
|
1285
|
+
});
|
|
1286
|
+
return this.parseWithSchema(
|
|
1287
|
+
raw,
|
|
1288
|
+
createSessionResponseSchema,
|
|
1289
|
+
"chat session response"
|
|
1290
|
+
);
|
|
1291
|
+
} catch (error) {
|
|
1292
|
+
if (allowHistoryAutoTopUp && this.shouldAutoTopUpHistory(payload, error)) {
|
|
1293
|
+
await this.executeHistoryAutoTopUp("chat.session");
|
|
1294
|
+
return this.createSession(payload, false);
|
|
1295
|
+
}
|
|
1296
|
+
throw error;
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
async startChat(options) {
|
|
1300
|
+
if ("uaid" in options && options.uaid) {
|
|
1301
|
+
return this.startConversation({
|
|
1302
|
+
uaid: options.uaid,
|
|
1303
|
+
senderUaid: options.senderUaid,
|
|
1304
|
+
historyTtlSeconds: options.historyTtlSeconds,
|
|
1305
|
+
auth: options.auth,
|
|
1306
|
+
encryption: options.encryption,
|
|
1307
|
+
onSessionCreated: options.onSessionCreated
|
|
1308
|
+
});
|
|
1309
|
+
}
|
|
1310
|
+
if ("agentUrl" in options && options.agentUrl) {
|
|
1311
|
+
const session = await this.createSession({
|
|
1312
|
+
agentUrl: options.agentUrl,
|
|
1313
|
+
auth: options.auth,
|
|
1314
|
+
historyTtlSeconds: options.historyTtlSeconds,
|
|
1315
|
+
senderUaid: options.senderUaid
|
|
1316
|
+
});
|
|
1317
|
+
options.onSessionCreated?.(session.sessionId);
|
|
1318
|
+
return this.createPlaintextConversationHandle(
|
|
1319
|
+
session.sessionId,
|
|
1320
|
+
session.encryption ?? null,
|
|
1321
|
+
options.auth,
|
|
1322
|
+
{ agentUrl: options.agentUrl, uaid: options.uaid }
|
|
1323
|
+
);
|
|
1324
|
+
}
|
|
1325
|
+
throw new Error("startChat requires either uaid or agentUrl");
|
|
1326
|
+
}
|
|
1327
|
+
async startConversation(options) {
|
|
1328
|
+
const preference = options.encryption?.preference ?? "preferred";
|
|
1329
|
+
const requestEncryption = preference !== "disabled";
|
|
1330
|
+
if (!requestEncryption) {
|
|
1331
|
+
const session = await this.createSession({
|
|
1332
|
+
uaid: options.uaid,
|
|
1333
|
+
auth: options.auth,
|
|
1334
|
+
historyTtlSeconds: options.historyTtlSeconds,
|
|
1335
|
+
senderUaid: options.senderUaid,
|
|
1336
|
+
encryptionRequested: false
|
|
1337
|
+
});
|
|
1338
|
+
options.onSessionCreated?.(session.sessionId);
|
|
1339
|
+
return this.createPlaintextConversationHandle(
|
|
1340
|
+
session.sessionId,
|
|
1341
|
+
session.encryption ?? null,
|
|
1342
|
+
options.auth,
|
|
1343
|
+
{ uaid: options.uaid }
|
|
1344
|
+
);
|
|
1345
|
+
}
|
|
1346
|
+
try {
|
|
1347
|
+
const handle = await this.encryptedChatManager.startSession({
|
|
1348
|
+
uaid: options.uaid,
|
|
1349
|
+
senderUaid: options.senderUaid,
|
|
1350
|
+
historyTtlSeconds: options.historyTtlSeconds,
|
|
1351
|
+
handshakeTimeoutMs: options.encryption?.handshakeTimeoutMs,
|
|
1352
|
+
pollIntervalMs: options.encryption?.pollIntervalMs,
|
|
1353
|
+
onSessionCreated: (sessionId) => {
|
|
1354
|
+
options.onSessionCreated?.(sessionId);
|
|
1355
|
+
},
|
|
1356
|
+
auth: options.auth
|
|
1357
|
+
});
|
|
1358
|
+
return handle;
|
|
1359
|
+
} catch (error) {
|
|
1360
|
+
if (error instanceof EncryptionUnavailableError) {
|
|
1361
|
+
if (preference === "required") {
|
|
1362
|
+
throw error;
|
|
1363
|
+
}
|
|
1364
|
+
return this.createPlaintextConversationHandle(
|
|
1365
|
+
error.sessionId,
|
|
1366
|
+
error.summary ?? null,
|
|
1367
|
+
options.auth,
|
|
1368
|
+
{ uaid: options.uaid }
|
|
1369
|
+
);
|
|
1370
|
+
}
|
|
1371
|
+
throw error;
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
async acceptConversation(options) {
|
|
1375
|
+
const preference = options.encryption?.preference ?? "preferred";
|
|
1376
|
+
if (preference === "disabled") {
|
|
1377
|
+
return this.createPlaintextConversationHandle(options.sessionId, null);
|
|
1378
|
+
}
|
|
1379
|
+
try {
|
|
1380
|
+
const handle = await this.encryptedChatManager.acceptSession({
|
|
1381
|
+
sessionId: options.sessionId,
|
|
1382
|
+
responderUaid: options.responderUaid,
|
|
1383
|
+
handshakeTimeoutMs: options.encryption?.handshakeTimeoutMs,
|
|
1384
|
+
pollIntervalMs: options.encryption?.pollIntervalMs
|
|
1385
|
+
});
|
|
1386
|
+
return handle;
|
|
1387
|
+
} catch (error) {
|
|
1388
|
+
if (error instanceof EncryptionUnavailableError && preference !== "required") {
|
|
1389
|
+
return this.createPlaintextConversationHandle(
|
|
1390
|
+
options.sessionId,
|
|
1391
|
+
null,
|
|
1392
|
+
void 0,
|
|
1393
|
+
{ uaid: options.responderUaid }
|
|
1394
|
+
);
|
|
1395
|
+
}
|
|
1396
|
+
throw error;
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
async fetchHistorySnapshot(sessionId, options) {
|
|
1400
|
+
if (!sessionId || sessionId.trim().length === 0) {
|
|
1401
|
+
throw new Error("sessionId is required to fetch chat history");
|
|
1402
|
+
}
|
|
1403
|
+
const raw = await this.requestJson(
|
|
1404
|
+
`/chat/session/${encodeURIComponent(sessionId)}/history`,
|
|
1405
|
+
{
|
|
1406
|
+
method: "GET"
|
|
1407
|
+
}
|
|
1408
|
+
);
|
|
1409
|
+
const snapshot = this.parseWithSchema(
|
|
1410
|
+
raw,
|
|
1411
|
+
chatHistorySnapshotResponseSchema,
|
|
1412
|
+
"chat history snapshot response"
|
|
1413
|
+
);
|
|
1414
|
+
return this.attachDecryptedHistory(sessionId, snapshot, options);
|
|
1415
|
+
}
|
|
1416
|
+
attachDecryptedHistory(sessionId, snapshot, options) {
|
|
1417
|
+
const shouldDecrypt = options?.decrypt !== void 0 ? options.decrypt : this.encryptionOptions?.autoDecryptHistory === true;
|
|
1418
|
+
if (!shouldDecrypt) {
|
|
1419
|
+
return snapshot;
|
|
1420
|
+
}
|
|
1421
|
+
const context = this.resolveDecryptionContext(sessionId, options);
|
|
1422
|
+
if (!context) {
|
|
1423
|
+
throw new Error(
|
|
1424
|
+
"Unable to decrypt chat history: encryption context unavailable"
|
|
1425
|
+
);
|
|
1426
|
+
}
|
|
1427
|
+
const decryptedHistory = snapshot.history.map((entry) => ({
|
|
1428
|
+
entry,
|
|
1429
|
+
plaintext: this.decryptHistoryEntryFromContext(sessionId, entry, context)
|
|
1430
|
+
}));
|
|
1431
|
+
return { ...snapshot, decryptedHistory };
|
|
1432
|
+
}
|
|
1433
|
+
registerConversationContext(context) {
|
|
1434
|
+
const normalized = {
|
|
1435
|
+
sessionId: context.sessionId,
|
|
1436
|
+
sharedSecret: Buffer.from(context.sharedSecret),
|
|
1437
|
+
identity: context.identity ? { ...context.identity } : void 0
|
|
1438
|
+
};
|
|
1439
|
+
const entries = this.conversationContexts.get(context.sessionId) ?? [];
|
|
1440
|
+
const existingIndex = entries.findIndex(
|
|
1441
|
+
(existing) => this.identitiesMatch(existing.identity, normalized.identity)
|
|
1442
|
+
);
|
|
1443
|
+
if (existingIndex >= 0) {
|
|
1444
|
+
entries[existingIndex] = normalized;
|
|
1445
|
+
} else {
|
|
1446
|
+
entries.push(normalized);
|
|
1447
|
+
}
|
|
1448
|
+
this.conversationContexts.set(context.sessionId, entries);
|
|
1449
|
+
}
|
|
1450
|
+
// Exposed for EncryptedChatManager to persist decryption context
|
|
1451
|
+
registerConversationContextForEncryption(context) {
|
|
1452
|
+
this.registerConversationContext(context);
|
|
1453
|
+
}
|
|
1454
|
+
resolveDecryptionContext(sessionId, options) {
|
|
1455
|
+
if (options?.sharedSecret) {
|
|
1456
|
+
return {
|
|
1457
|
+
sessionId,
|
|
1458
|
+
sharedSecret: this.normalizeSharedSecret(options.sharedSecret),
|
|
1459
|
+
identity: options.identity
|
|
1460
|
+
};
|
|
1461
|
+
}
|
|
1462
|
+
const contexts = this.conversationContexts.get(sessionId);
|
|
1463
|
+
if (!contexts || contexts.length === 0) {
|
|
1464
|
+
return null;
|
|
1465
|
+
}
|
|
1466
|
+
if (options?.identity) {
|
|
1467
|
+
const match = contexts.find(
|
|
1468
|
+
(context) => this.identitiesMatch(context.identity, options.identity)
|
|
1469
|
+
);
|
|
1470
|
+
if (match) {
|
|
1471
|
+
return match;
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
return contexts[0];
|
|
1475
|
+
}
|
|
1476
|
+
decryptHistoryEntryFromContext(sessionId, entry, context) {
|
|
1477
|
+
const envelope = entry.cipherEnvelope;
|
|
1478
|
+
if (!envelope) {
|
|
1479
|
+
return entry.content;
|
|
1480
|
+
}
|
|
1481
|
+
const secret = Buffer.from(context.sharedSecret);
|
|
1482
|
+
try {
|
|
1483
|
+
return this.encryption.decryptCipherEnvelope({
|
|
1484
|
+
envelope,
|
|
1485
|
+
sharedSecret: secret
|
|
1486
|
+
});
|
|
1487
|
+
} catch (_error) {
|
|
1488
|
+
return null;
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
identitiesMatch(a, b) {
|
|
1492
|
+
if (!a && !b) {
|
|
1493
|
+
return true;
|
|
1494
|
+
}
|
|
1495
|
+
if (!a || !b) {
|
|
1496
|
+
return false;
|
|
1497
|
+
}
|
|
1498
|
+
if (a.uaid && b.uaid && a.uaid.toLowerCase() === b.uaid.toLowerCase()) {
|
|
1499
|
+
return true;
|
|
1500
|
+
}
|
|
1501
|
+
if (a.ledgerAccountId && b.ledgerAccountId && a.ledgerAccountId.toLowerCase() === b.ledgerAccountId.toLowerCase()) {
|
|
1502
|
+
return true;
|
|
1503
|
+
}
|
|
1504
|
+
if (a.userId && b.userId && a.userId === b.userId) {
|
|
1505
|
+
return true;
|
|
1506
|
+
}
|
|
1507
|
+
if (a.email && b.email && a.email.toLowerCase() === b.email.toLowerCase()) {
|
|
1508
|
+
return true;
|
|
1509
|
+
}
|
|
1510
|
+
return false;
|
|
1511
|
+
}
|
|
1512
|
+
identityMatchesRecipient(recipient, identity) {
|
|
1513
|
+
if (identity.uaid && recipient.uaid?.toLowerCase() === identity.uaid.toLowerCase()) {
|
|
1514
|
+
return true;
|
|
1515
|
+
}
|
|
1516
|
+
if (identity.ledgerAccountId && recipient.ledgerAccountId?.toLowerCase() === identity.ledgerAccountId.toLowerCase()) {
|
|
1517
|
+
return true;
|
|
1518
|
+
}
|
|
1519
|
+
if (identity.userId && recipient.userId === identity.userId) {
|
|
1520
|
+
return true;
|
|
1521
|
+
}
|
|
1522
|
+
if (identity.email && recipient.email?.toLowerCase() === identity.email.toLowerCase()) {
|
|
1523
|
+
return true;
|
|
1524
|
+
}
|
|
1525
|
+
return false;
|
|
1526
|
+
}
|
|
1527
|
+
createPlaintextConversationHandle(sessionId, summary, defaultAuth, context) {
|
|
1528
|
+
const uaid = context?.uaid?.trim();
|
|
1529
|
+
const agentUrl = context?.agentUrl?.trim();
|
|
1530
|
+
return {
|
|
1531
|
+
sessionId,
|
|
1532
|
+
mode: "plaintext",
|
|
1533
|
+
summary: summary ?? null,
|
|
1534
|
+
send: async (options) => {
|
|
1535
|
+
const plaintext = options.plaintext;
|
|
1536
|
+
if (!plaintext || plaintext.trim().length === 0) {
|
|
1537
|
+
throw new Error("plaintext is required for chat messages");
|
|
1538
|
+
}
|
|
1539
|
+
const message = options.message ?? plaintext;
|
|
1540
|
+
return this.sendMessage({
|
|
1541
|
+
sessionId,
|
|
1542
|
+
message,
|
|
1543
|
+
streaming: options.streaming,
|
|
1544
|
+
auth: options.auth ?? defaultAuth,
|
|
1545
|
+
uaid,
|
|
1546
|
+
agentUrl
|
|
1547
|
+
});
|
|
1548
|
+
},
|
|
1549
|
+
decryptHistoryEntry: (entry) => entry.content
|
|
1550
|
+
};
|
|
1551
|
+
}
|
|
1552
|
+
async compactHistory(payload) {
|
|
1553
|
+
if (!payload.sessionId || payload.sessionId.trim().length === 0) {
|
|
1554
|
+
throw new Error("sessionId is required to compact chat history");
|
|
1555
|
+
}
|
|
1556
|
+
const body = {};
|
|
1557
|
+
if (typeof payload.preserveEntries === "number" && Number.isFinite(payload.preserveEntries) && payload.preserveEntries >= 0) {
|
|
1558
|
+
body.preserveEntries = Math.floor(payload.preserveEntries);
|
|
1559
|
+
}
|
|
1560
|
+
const raw = await this.requestJson(
|
|
1561
|
+
`/chat/session/${encodeURIComponent(payload.sessionId)}/compact`,
|
|
1562
|
+
{
|
|
1563
|
+
method: "POST",
|
|
1564
|
+
headers: { "content-type": "application/json" },
|
|
1565
|
+
body
|
|
1566
|
+
}
|
|
1567
|
+
);
|
|
1568
|
+
return this.parseWithSchema(
|
|
1569
|
+
raw,
|
|
1570
|
+
chatHistoryCompactionResponseSchema,
|
|
1571
|
+
"chat history compaction response"
|
|
1572
|
+
);
|
|
1573
|
+
}
|
|
1574
|
+
async fetchEncryptionStatus(sessionId) {
|
|
1575
|
+
if (!sessionId || sessionId.trim().length === 0) {
|
|
1576
|
+
throw new Error("sessionId is required for encryption status");
|
|
1577
|
+
}
|
|
1578
|
+
const raw = await this.requestJson(
|
|
1579
|
+
`/chat/session/${encodeURIComponent(sessionId)}/encryption`,
|
|
1580
|
+
{
|
|
1581
|
+
method: "GET"
|
|
1582
|
+
}
|
|
1583
|
+
);
|
|
1584
|
+
return this.parseWithSchema(
|
|
1585
|
+
raw,
|
|
1586
|
+
sessionEncryptionStatusResponseSchema,
|
|
1587
|
+
"session encryption status response"
|
|
1588
|
+
);
|
|
1589
|
+
}
|
|
1590
|
+
async postEncryptionHandshake(sessionId, payload) {
|
|
1591
|
+
if (!sessionId || sessionId.trim().length === 0) {
|
|
1592
|
+
throw new Error("sessionId is required for encryption handshake");
|
|
1593
|
+
}
|
|
1594
|
+
const raw = await this.requestJson(
|
|
1595
|
+
`/chat/session/${encodeURIComponent(sessionId)}/encryption-handshake`,
|
|
1596
|
+
{
|
|
1597
|
+
method: "POST",
|
|
1598
|
+
headers: { "content-type": "application/json" },
|
|
1599
|
+
body: {
|
|
1600
|
+
role: payload.role,
|
|
1601
|
+
keyType: payload.keyType,
|
|
1602
|
+
ephemeralPublicKey: payload.ephemeralPublicKey,
|
|
1603
|
+
longTermPublicKey: payload.longTermPublicKey,
|
|
1604
|
+
signature: payload.signature,
|
|
1605
|
+
uaid: payload.uaid,
|
|
1606
|
+
userId: payload.userId,
|
|
1607
|
+
ledgerAccountId: payload.ledgerAccountId,
|
|
1608
|
+
metadata: payload.metadata
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
);
|
|
1612
|
+
const response = this.parseWithSchema(
|
|
1613
|
+
raw,
|
|
1614
|
+
encryptionHandshakeResponseSchema,
|
|
1615
|
+
"encryption handshake response"
|
|
1616
|
+
);
|
|
1617
|
+
return response.handshake;
|
|
1618
|
+
}
|
|
1619
|
+
async registerEncryptionKey(payload) {
|
|
1620
|
+
const raw = await this.requestJson("/encryption/keys", {
|
|
1621
|
+
method: "POST",
|
|
1622
|
+
headers: { "content-type": "application/json" },
|
|
1623
|
+
body: payload
|
|
1624
|
+
});
|
|
1625
|
+
return this.parseWithSchema(
|
|
1626
|
+
raw,
|
|
1627
|
+
registerEncryptionKeyResponseSchema,
|
|
1628
|
+
"register encryption key response"
|
|
1629
|
+
);
|
|
1630
|
+
}
|
|
1631
|
+
async sendMessage(payload) {
|
|
1632
|
+
const body = {
|
|
1633
|
+
message: payload.message
|
|
1634
|
+
};
|
|
1635
|
+
if (payload.streaming !== void 0) {
|
|
1636
|
+
body.streaming = payload.streaming;
|
|
1637
|
+
}
|
|
1638
|
+
if (payload.auth) {
|
|
1639
|
+
body.auth = serialiseAuthConfig(payload.auth);
|
|
1640
|
+
}
|
|
1641
|
+
if ("uaid" in payload) {
|
|
1642
|
+
body.uaid = payload.uaid;
|
|
1643
|
+
}
|
|
1644
|
+
if ("sessionId" in payload && payload.sessionId) {
|
|
1645
|
+
body.sessionId = payload.sessionId;
|
|
1646
|
+
}
|
|
1647
|
+
if ("agentUrl" in payload && payload.agentUrl) {
|
|
1648
|
+
body.agentUrl = payload.agentUrl;
|
|
1649
|
+
}
|
|
1650
|
+
let cipherEnvelope = payload.cipherEnvelope ?? null;
|
|
1651
|
+
if (payload.encryption) {
|
|
1652
|
+
const sessionIdForEncryption = payload.encryption.sessionId ?? (typeof body.sessionId === "string" ? body.sessionId : void 0);
|
|
1653
|
+
if (!sessionIdForEncryption) {
|
|
1654
|
+
throw new Error(
|
|
1655
|
+
"sessionId is required when using encrypted chat payloads"
|
|
1656
|
+
);
|
|
1657
|
+
}
|
|
1658
|
+
if (!payload.encryption.recipients?.length) {
|
|
1659
|
+
throw new Error("recipients are required for encrypted chat payloads");
|
|
1660
|
+
}
|
|
1661
|
+
cipherEnvelope = this.encryption.encryptCipherEnvelope({
|
|
1662
|
+
...payload.encryption,
|
|
1663
|
+
sessionId: sessionIdForEncryption
|
|
1664
|
+
});
|
|
1665
|
+
}
|
|
1666
|
+
if (cipherEnvelope) {
|
|
1667
|
+
body.cipherEnvelope = cipherEnvelope;
|
|
1668
|
+
}
|
|
1669
|
+
delete body.encryption;
|
|
1670
|
+
const raw = await this.requestJson("/chat/message", {
|
|
1671
|
+
method: "POST",
|
|
1672
|
+
body,
|
|
1673
|
+
headers: { "content-type": "application/json" }
|
|
1674
|
+
});
|
|
1675
|
+
return this.parseWithSchema(
|
|
1676
|
+
raw,
|
|
1677
|
+
sendMessageResponseSchema,
|
|
1678
|
+
"chat message response"
|
|
1679
|
+
);
|
|
1680
|
+
}
|
|
1681
|
+
async endSession(sessionId) {
|
|
1682
|
+
await this.request(`/chat/session/${encodeURIComponent(sessionId)}`, {
|
|
1683
|
+
method: "DELETE"
|
|
1684
|
+
});
|
|
1685
|
+
}
|
|
1686
|
+
async generateEncryptionKeyPair(options = {}) {
|
|
1687
|
+
this.assertNodeRuntime("generateEncryptionKeyPair");
|
|
1688
|
+
const keyType = options.keyType ?? "secp256k1";
|
|
1689
|
+
if (keyType !== "secp256k1") {
|
|
1690
|
+
throw new Error("Only secp256k1 key generation is supported currently");
|
|
1691
|
+
}
|
|
1692
|
+
const privateKeyBytes = randomBytes(32);
|
|
1693
|
+
const privateKey = Buffer.from(privateKeyBytes).toString("hex");
|
|
1694
|
+
const publicKeyBytes = secp256k1.getPublicKey(privateKeyBytes, true);
|
|
1695
|
+
const publicKey = Buffer.from(publicKeyBytes).toString("hex");
|
|
1696
|
+
const envVar = options.envVar ?? "RB_ENCRYPTION_PRIVATE_KEY";
|
|
1697
|
+
const resolvedPath = options.envPath ? path.resolve(options.envPath) : void 0;
|
|
1698
|
+
if (resolvedPath) {
|
|
1699
|
+
const fsModule = await getFs();
|
|
1700
|
+
if (!fsModule) {
|
|
1701
|
+
throw new Error(
|
|
1702
|
+
"File system module is not available; cannot write encryption key env file"
|
|
1703
|
+
);
|
|
1704
|
+
}
|
|
1705
|
+
const envLine = `${envVar}=${privateKey}`;
|
|
1706
|
+
if (fsModule.existsSync(resolvedPath)) {
|
|
1707
|
+
const content = fsModule.readFileSync(resolvedPath, "utf-8");
|
|
1708
|
+
const lineRegex = new RegExp(`^${envVar}=.*$`, "m");
|
|
1709
|
+
if (lineRegex.test(content)) {
|
|
1710
|
+
if (!options.overwrite) {
|
|
1711
|
+
throw new Error(
|
|
1712
|
+
`${envVar} already exists in ${resolvedPath}; set overwrite=true to replace it`
|
|
1713
|
+
);
|
|
1714
|
+
}
|
|
1715
|
+
const updated = content.replace(lineRegex, envLine);
|
|
1716
|
+
fsModule.writeFileSync(resolvedPath, updated);
|
|
1717
|
+
} else {
|
|
1718
|
+
const needsNewline = !content.endsWith("\n");
|
|
1719
|
+
fsModule.appendFileSync(
|
|
1720
|
+
resolvedPath,
|
|
1721
|
+
`${needsNewline ? "\n" : ""}${envLine}
|
|
1722
|
+
`
|
|
1723
|
+
);
|
|
1724
|
+
}
|
|
1725
|
+
} else {
|
|
1726
|
+
fsModule.writeFileSync(resolvedPath, `${envLine}
|
|
1727
|
+
`);
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
return {
|
|
1731
|
+
privateKey,
|
|
1732
|
+
publicKey,
|
|
1733
|
+
envPath: resolvedPath,
|
|
1734
|
+
envVar
|
|
1735
|
+
};
|
|
1736
|
+
}
|
|
1737
|
+
buildUrl(path2) {
|
|
1738
|
+
const normalisedPath = path2.startsWith("/") ? path2 : `/${path2}`;
|
|
1739
|
+
return `${this.baseUrl}${normalisedPath}`;
|
|
1740
|
+
}
|
|
1741
|
+
buildVectorFallbackSearchParams(request) {
|
|
1742
|
+
const params = {
|
|
1743
|
+
q: request.query
|
|
1744
|
+
};
|
|
1745
|
+
let effectiveLimit;
|
|
1746
|
+
if (typeof request.limit === "number" && Number.isFinite(request.limit)) {
|
|
1747
|
+
effectiveLimit = request.limit;
|
|
1748
|
+
params.limit = request.limit;
|
|
1749
|
+
}
|
|
1750
|
+
if (typeof request.offset === "number" && Number.isFinite(request.offset) && request.offset > 0) {
|
|
1751
|
+
const limit = effectiveLimit && effectiveLimit > 0 ? effectiveLimit : 20;
|
|
1752
|
+
params.limit = limit;
|
|
1753
|
+
params.page = Math.floor(request.offset / limit) + 1;
|
|
1754
|
+
}
|
|
1755
|
+
if (request.filter?.registry) {
|
|
1756
|
+
params.registry = request.filter.registry;
|
|
1757
|
+
}
|
|
1758
|
+
if (request.filter?.protocols?.length) {
|
|
1759
|
+
params.protocols = [...request.filter.protocols];
|
|
1760
|
+
}
|
|
1761
|
+
if (request.filter?.adapter?.length) {
|
|
1762
|
+
params.adapters = [...request.filter.adapter];
|
|
1763
|
+
}
|
|
1764
|
+
if (request.filter?.capabilities?.length) {
|
|
1765
|
+
params.capabilities = request.filter.capabilities.map(
|
|
1766
|
+
(value) => typeof value === "number" ? value.toString(10) : value
|
|
1767
|
+
);
|
|
1768
|
+
}
|
|
1769
|
+
if (request.filter?.type) {
|
|
1770
|
+
params.type = request.filter.type;
|
|
1771
|
+
}
|
|
1772
|
+
return params;
|
|
1773
|
+
}
|
|
1774
|
+
convertSearchResultToVectorResponse(result) {
|
|
1775
|
+
const hits = result.hits.map((agent) => ({
|
|
1776
|
+
agent,
|
|
1777
|
+
score: 0,
|
|
1778
|
+
highlights: {}
|
|
1779
|
+
}));
|
|
1780
|
+
const total = result.total;
|
|
1781
|
+
const limit = result.limit;
|
|
1782
|
+
const page = result.page;
|
|
1783
|
+
const totalVisible = page * limit;
|
|
1784
|
+
const limited = total > totalVisible || page > 1;
|
|
1785
|
+
return {
|
|
1786
|
+
hits,
|
|
1787
|
+
total,
|
|
1788
|
+
took: 0,
|
|
1789
|
+
totalAvailable: total,
|
|
1790
|
+
visible: hits.length,
|
|
1791
|
+
limited,
|
|
1792
|
+
credits_used: 0
|
|
1793
|
+
};
|
|
1794
|
+
}
|
|
1795
|
+
async delay(ms, signal) {
|
|
1796
|
+
if (ms <= 0) {
|
|
1797
|
+
if (signal?.aborted) {
|
|
1798
|
+
throw createAbortError();
|
|
1799
|
+
}
|
|
1800
|
+
return;
|
|
1801
|
+
}
|
|
1802
|
+
await new Promise((resolve, reject) => {
|
|
1803
|
+
const timer = setTimeout(() => {
|
|
1804
|
+
if (signal) {
|
|
1805
|
+
signal.removeEventListener("abort", onAbort);
|
|
1806
|
+
}
|
|
1807
|
+
resolve();
|
|
1808
|
+
}, ms);
|
|
1809
|
+
const onAbort = () => {
|
|
1810
|
+
clearTimeout(timer);
|
|
1811
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1812
|
+
reject(createAbortError());
|
|
1813
|
+
};
|
|
1814
|
+
if (signal) {
|
|
1815
|
+
if (signal.aborted) {
|
|
1816
|
+
clearTimeout(timer);
|
|
1817
|
+
reject(createAbortError());
|
|
1818
|
+
return;
|
|
1819
|
+
}
|
|
1820
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1821
|
+
}
|
|
1822
|
+
});
|
|
1823
|
+
}
|
|
1824
|
+
async requestJson(path2, config) {
|
|
1825
|
+
const response = await this.request(path2, config);
|
|
1826
|
+
const contentType = response.headers?.get("content-type") ?? "";
|
|
1827
|
+
if (!JSON_CONTENT_TYPE.test(contentType)) {
|
|
1828
|
+
const body = await response.text();
|
|
1829
|
+
throw new RegistryBrokerParseError(
|
|
1830
|
+
"Expected JSON response from registry broker",
|
|
1831
|
+
body
|
|
1832
|
+
);
|
|
1833
|
+
}
|
|
1834
|
+
return await response.json();
|
|
1835
|
+
}
|
|
1836
|
+
async extractErrorBody(response) {
|
|
1837
|
+
const contentType = response.headers?.get("content-type") ?? "";
|
|
1838
|
+
if (JSON_CONTENT_TYPE.test(contentType)) {
|
|
1839
|
+
try {
|
|
1840
|
+
return await response.json();
|
|
1841
|
+
} catch (error) {
|
|
1842
|
+
return { parseError: String(error) };
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
try {
|
|
1846
|
+
return await response.text();
|
|
1847
|
+
} catch (error) {
|
|
1848
|
+
return { parseError: String(error) };
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
parseWithSchema(value, schema, context) {
|
|
1852
|
+
try {
|
|
1853
|
+
return schema.parse(value);
|
|
1854
|
+
} catch (error) {
|
|
1855
|
+
throw new RegistryBrokerParseError(
|
|
1856
|
+
`Failed to parse ${context}`,
|
|
1857
|
+
error instanceof ZodError || error instanceof Error ? error : String(error),
|
|
1858
|
+
value
|
|
1859
|
+
);
|
|
1860
|
+
}
|
|
1861
|
+
}
|
|
1862
|
+
assertNodeRuntime(feature) {
|
|
1863
|
+
if (typeof process === "undefined" || !process.versions?.node) {
|
|
1864
|
+
throw new Error(`${feature} is only available in Node.js environments`);
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
createEphemeralKeyPair() {
|
|
1868
|
+
this.assertNodeRuntime("generateEphemeralKeyPair");
|
|
1869
|
+
const privateKeyBytes = randomBytes(32);
|
|
1870
|
+
const publicKey = secp256k1.getPublicKey(privateKeyBytes, true);
|
|
1871
|
+
return {
|
|
1872
|
+
privateKey: Buffer.from(privateKeyBytes).toString("hex"),
|
|
1873
|
+
publicKey: Buffer.from(publicKey).toString("hex")
|
|
1874
|
+
};
|
|
1875
|
+
}
|
|
1876
|
+
deriveSharedSecret(options) {
|
|
1877
|
+
this.assertNodeRuntime("deriveSharedSecret");
|
|
1878
|
+
const privateKey = this.hexToBuffer(options.privateKey);
|
|
1879
|
+
const peerPublicKey = this.hexToBuffer(options.peerPublicKey);
|
|
1880
|
+
const shared = secp256k1.getSharedSecret(privateKey, peerPublicKey, true);
|
|
1881
|
+
return createHash("sha256").update(Buffer.from(shared)).digest();
|
|
1882
|
+
}
|
|
1883
|
+
buildCipherEnvelope(options) {
|
|
1884
|
+
this.assertNodeRuntime("encryptCipherEnvelope");
|
|
1885
|
+
const sharedSecret = this.normalizeSharedSecret(options.sharedSecret);
|
|
1886
|
+
const iv = randomBytes(12);
|
|
1887
|
+
const cipher = createCipheriv("aes-256-gcm", sharedSecret, iv);
|
|
1888
|
+
const aadSource = options.associatedData ?? options.sessionId;
|
|
1889
|
+
const associatedDataEncoded = aadSource ? Buffer.from(aadSource, "utf8").toString("base64") : void 0;
|
|
1890
|
+
if (aadSource) {
|
|
1891
|
+
cipher.setAAD(Buffer.from(aadSource, "utf8"));
|
|
1892
|
+
}
|
|
1893
|
+
const ciphertext = Buffer.concat([
|
|
1894
|
+
cipher.update(Buffer.from(options.plaintext, "utf8")),
|
|
1895
|
+
cipher.final()
|
|
1896
|
+
]);
|
|
1897
|
+
const tag = cipher.getAuthTag();
|
|
1898
|
+
const payload = Buffer.concat([ciphertext, tag]);
|
|
1899
|
+
return {
|
|
1900
|
+
algorithm: "aes-256-gcm",
|
|
1901
|
+
ciphertext: payload.toString("base64"),
|
|
1902
|
+
nonce: iv.toString("base64"),
|
|
1903
|
+
associatedData: associatedDataEncoded,
|
|
1904
|
+
keyLocator: {
|
|
1905
|
+
sessionId: options.sessionId,
|
|
1906
|
+
revision: options.revision ?? 1
|
|
1907
|
+
},
|
|
1908
|
+
recipients: options.recipients.map((recipient) => ({
|
|
1909
|
+
...recipient,
|
|
1910
|
+
encryptedShare: ""
|
|
1911
|
+
}))
|
|
1912
|
+
};
|
|
1913
|
+
}
|
|
1914
|
+
openCipherEnvelope(options) {
|
|
1915
|
+
this.assertNodeRuntime("decryptCipherEnvelope");
|
|
1916
|
+
const sharedSecret = this.normalizeSharedSecret(options.sharedSecret);
|
|
1917
|
+
const payload = Buffer.from(options.envelope.ciphertext, "base64");
|
|
1918
|
+
const nonce = Buffer.from(options.envelope.nonce, "base64");
|
|
1919
|
+
const ciphertext = payload.slice(0, payload.length - 16);
|
|
1920
|
+
const tag = payload.slice(payload.length - 16);
|
|
1921
|
+
const decipher = createDecipheriv("aes-256-gcm", sharedSecret, nonce);
|
|
1922
|
+
if (options.envelope.associatedData) {
|
|
1923
|
+
decipher.setAAD(Buffer.from(options.envelope.associatedData, "base64"));
|
|
1924
|
+
}
|
|
1925
|
+
decipher.setAuthTag(tag);
|
|
1926
|
+
const plaintext = Buffer.concat([
|
|
1927
|
+
decipher.update(ciphertext),
|
|
1928
|
+
decipher.final()
|
|
1929
|
+
]);
|
|
1930
|
+
return plaintext.toString(options.encoding ?? "utf8");
|
|
1931
|
+
}
|
|
1932
|
+
normalizeSharedSecret(input) {
|
|
1933
|
+
if (Buffer.isBuffer(input)) {
|
|
1934
|
+
return Buffer.from(input);
|
|
1935
|
+
}
|
|
1936
|
+
if (input instanceof Uint8Array) {
|
|
1937
|
+
return Buffer.from(input);
|
|
1938
|
+
}
|
|
1939
|
+
if (typeof input === "string") {
|
|
1940
|
+
return this.bufferFromString(input);
|
|
1941
|
+
}
|
|
1942
|
+
throw new Error("Unsupported shared secret input");
|
|
1943
|
+
}
|
|
1944
|
+
bufferFromString(value) {
|
|
1945
|
+
const trimmed = value.trim();
|
|
1946
|
+
if (!trimmed) {
|
|
1947
|
+
throw new Error("sharedSecret string cannot be empty");
|
|
1948
|
+
}
|
|
1949
|
+
const normalized = trimmed.startsWith("0x") ? trimmed.slice(2) : trimmed;
|
|
1950
|
+
if (/^[0-9a-fA-F]+$/.test(normalized) && normalized.length % 2 === 0) {
|
|
1951
|
+
return Buffer.from(normalized, "hex");
|
|
1952
|
+
}
|
|
1953
|
+
return Buffer.from(trimmed, "base64");
|
|
1954
|
+
}
|
|
1955
|
+
hexToBuffer(value) {
|
|
1956
|
+
const normalized = value.startsWith("0x") ? value.slice(2) : value;
|
|
1957
|
+
if (!/^[0-9a-fA-F]+$/.test(normalized) || normalized.length % 2 !== 0) {
|
|
1958
|
+
throw new Error("Expected hex-encoded value");
|
|
1959
|
+
}
|
|
1960
|
+
return Buffer.from(normalized, "hex");
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
const isPendingRegisterAgentResponse = (response) => response.status === "pending";
|
|
1964
|
+
const isPartialRegisterAgentResponse = (response) => response.status === "partial" && response.success === false;
|
|
1965
|
+
const isSuccessRegisterAgentResponse = (response) => response.success === true && response.status !== "pending";
|
|
1966
|
+
class EncryptedChatManager {
|
|
1967
|
+
constructor(client) {
|
|
1968
|
+
this.client = client;
|
|
1969
|
+
}
|
|
1970
|
+
registerConversationContext(context) {
|
|
1971
|
+
this.client.registerConversationContextForEncryption(context);
|
|
1972
|
+
}
|
|
1973
|
+
async startSession(options) {
|
|
1974
|
+
await this.client.encryptionReady();
|
|
1975
|
+
const session = await this.client.chat.createSession({
|
|
1976
|
+
uaid: options.uaid,
|
|
1977
|
+
senderUaid: options.senderUaid,
|
|
1978
|
+
encryptionRequested: true,
|
|
1979
|
+
historyTtlSeconds: options.historyTtlSeconds,
|
|
1980
|
+
auth: options.auth
|
|
1981
|
+
});
|
|
1982
|
+
options.onSessionCreated?.(session.sessionId);
|
|
1983
|
+
const summary = session.encryption;
|
|
1984
|
+
if (!summary?.enabled) {
|
|
1985
|
+
throw new EncryptionUnavailableError(
|
|
1986
|
+
session.sessionId,
|
|
1987
|
+
session.encryption ?? null
|
|
1988
|
+
);
|
|
1989
|
+
}
|
|
1990
|
+
const handle = await this.establishRequesterContext({
|
|
1991
|
+
sessionId: session.sessionId,
|
|
1992
|
+
summary,
|
|
1993
|
+
senderUaid: options.senderUaid,
|
|
1994
|
+
handshakeTimeoutMs: options.handshakeTimeoutMs,
|
|
1995
|
+
pollIntervalMs: options.pollIntervalMs
|
|
1996
|
+
});
|
|
1997
|
+
return handle;
|
|
1998
|
+
}
|
|
1999
|
+
async acceptSession(options) {
|
|
2000
|
+
await this.client.encryptionReady();
|
|
2001
|
+
const summary = await this.waitForEncryptionSummary(
|
|
2002
|
+
options.sessionId,
|
|
2003
|
+
options.handshakeTimeoutMs,
|
|
2004
|
+
options.pollIntervalMs
|
|
2005
|
+
);
|
|
2006
|
+
const handle = await this.establishResponderContext({
|
|
2007
|
+
sessionId: options.sessionId,
|
|
2008
|
+
summary,
|
|
2009
|
+
responderUaid: options.responderUaid,
|
|
2010
|
+
handshakeTimeoutMs: options.handshakeTimeoutMs,
|
|
2011
|
+
pollIntervalMs: options.pollIntervalMs
|
|
2012
|
+
});
|
|
2013
|
+
return handle;
|
|
2014
|
+
}
|
|
2015
|
+
async establishRequesterContext(params) {
|
|
2016
|
+
const keyPair = this.client.encryption.generateEphemeralKeyPair();
|
|
2017
|
+
await this.client.chat.submitEncryptionHandshake(params.sessionId, {
|
|
2018
|
+
role: "requester",
|
|
2019
|
+
keyType: "secp256k1",
|
|
2020
|
+
ephemeralPublicKey: keyPair.publicKey,
|
|
2021
|
+
uaid: params.senderUaid ?? params.summary.requester?.uaid ?? void 0
|
|
2022
|
+
});
|
|
2023
|
+
const { summary, record } = await this.waitForHandshakeCompletion(
|
|
2024
|
+
params.sessionId,
|
|
2025
|
+
params.handshakeTimeoutMs,
|
|
2026
|
+
params.pollIntervalMs
|
|
2027
|
+
);
|
|
2028
|
+
const responderKey = record.responder?.ephemeralPublicKey;
|
|
2029
|
+
if (!responderKey) {
|
|
2030
|
+
throw new Error("Responder handshake was not completed in time");
|
|
2031
|
+
}
|
|
2032
|
+
const sharedSecret = this.client.encryption.deriveSharedSecret({
|
|
2033
|
+
privateKey: keyPair.privateKey,
|
|
2034
|
+
peerPublicKey: responderKey
|
|
2035
|
+
}).subarray();
|
|
2036
|
+
const recipients = this.buildRecipients(summary);
|
|
2037
|
+
return this.createHandle({
|
|
2038
|
+
sessionId: params.sessionId,
|
|
2039
|
+
sharedSecret,
|
|
2040
|
+
summary,
|
|
2041
|
+
recipients,
|
|
2042
|
+
identity: summary.requester ?? void 0
|
|
2043
|
+
});
|
|
2044
|
+
}
|
|
2045
|
+
async establishResponderContext(params) {
|
|
2046
|
+
const keyPair = this.client.encryption.generateEphemeralKeyPair();
|
|
2047
|
+
await this.client.chat.submitEncryptionHandshake(params.sessionId, {
|
|
2048
|
+
role: "responder",
|
|
2049
|
+
keyType: "secp256k1",
|
|
2050
|
+
ephemeralPublicKey: keyPair.publicKey,
|
|
2051
|
+
uaid: params.responderUaid ?? params.summary.responder?.uaid ?? void 0
|
|
2052
|
+
});
|
|
2053
|
+
const { summary, record } = await this.waitForHandshakeCompletion(
|
|
2054
|
+
params.sessionId,
|
|
2055
|
+
params.handshakeTimeoutMs,
|
|
2056
|
+
params.pollIntervalMs
|
|
2057
|
+
);
|
|
2058
|
+
const requesterKey = record.requester?.ephemeralPublicKey;
|
|
2059
|
+
if (!requesterKey) {
|
|
2060
|
+
throw new Error("Requester handshake was not detected in time");
|
|
2061
|
+
}
|
|
2062
|
+
const sharedSecret = this.client.encryption.deriveSharedSecret({
|
|
2063
|
+
privateKey: keyPair.privateKey,
|
|
2064
|
+
peerPublicKey: requesterKey
|
|
2065
|
+
}).subarray();
|
|
2066
|
+
const recipients = this.buildRecipients(summary);
|
|
2067
|
+
return this.createHandle({
|
|
2068
|
+
sessionId: params.sessionId,
|
|
2069
|
+
sharedSecret,
|
|
2070
|
+
summary,
|
|
2071
|
+
recipients,
|
|
2072
|
+
identity: summary.responder ?? void 0
|
|
2073
|
+
});
|
|
2074
|
+
}
|
|
2075
|
+
async waitForHandshakeCompletion(sessionId, timeoutMs = 3e4, pollIntervalMs = 1e3) {
|
|
2076
|
+
const deadline = Date.now() + timeoutMs;
|
|
2077
|
+
while (true) {
|
|
2078
|
+
const status = await this.client.chat.getEncryptionStatus(sessionId);
|
|
2079
|
+
const summary = status.encryption;
|
|
2080
|
+
const record = summary?.handshake;
|
|
2081
|
+
if (summary && record && record.status === "complete") {
|
|
2082
|
+
return { summary, record };
|
|
2083
|
+
}
|
|
2084
|
+
if (Date.now() >= deadline) {
|
|
2085
|
+
throw new Error("Timed out waiting for encrypted handshake completion");
|
|
2086
|
+
}
|
|
2087
|
+
await this.delay(pollIntervalMs);
|
|
2088
|
+
}
|
|
2089
|
+
}
|
|
2090
|
+
async waitForEncryptionSummary(sessionId, _timeoutMs = 3e4, _pollIntervalMs = 1e3) {
|
|
2091
|
+
const status = await this.client.chat.getEncryptionStatus(sessionId);
|
|
2092
|
+
if (!status.encryption?.enabled) {
|
|
2093
|
+
throw new EncryptionUnavailableError(
|
|
2094
|
+
sessionId,
|
|
2095
|
+
status.encryption ?? null
|
|
2096
|
+
);
|
|
2097
|
+
}
|
|
2098
|
+
return status.encryption;
|
|
2099
|
+
}
|
|
2100
|
+
buildRecipients(summary) {
|
|
2101
|
+
const candidates = [summary.requester, summary.responder].filter(Boolean);
|
|
2102
|
+
const normalized = candidates.map((candidate) => {
|
|
2103
|
+
if (!candidate) {
|
|
2104
|
+
return null;
|
|
2105
|
+
}
|
|
2106
|
+
const recipient = {};
|
|
2107
|
+
if (candidate.uaid) {
|
|
2108
|
+
recipient.uaid = candidate.uaid;
|
|
2109
|
+
}
|
|
2110
|
+
if (candidate.ledgerAccountId) {
|
|
2111
|
+
recipient.ledgerAccountId = candidate.ledgerAccountId;
|
|
2112
|
+
}
|
|
2113
|
+
if (candidate.userId) {
|
|
2114
|
+
recipient.userId = candidate.userId;
|
|
2115
|
+
}
|
|
2116
|
+
if (candidate.email) {
|
|
2117
|
+
recipient.email = candidate.email;
|
|
2118
|
+
}
|
|
2119
|
+
return recipient;
|
|
2120
|
+
}).filter(
|
|
2121
|
+
(entry) => Boolean(
|
|
2122
|
+
entry?.uaid || entry?.ledgerAccountId || entry?.userId || entry?.email
|
|
2123
|
+
)
|
|
2124
|
+
);
|
|
2125
|
+
if (normalized.length > 0) {
|
|
2126
|
+
return normalized;
|
|
2127
|
+
}
|
|
2128
|
+
if (summary.responder?.uaid) {
|
|
2129
|
+
return [{ uaid: summary.responder.uaid }];
|
|
2130
|
+
}
|
|
2131
|
+
return [];
|
|
2132
|
+
}
|
|
2133
|
+
createHandle(context) {
|
|
2134
|
+
const sharedSecret = context.sharedSecret;
|
|
2135
|
+
const uaid = context.summary.requester?.uaid ?? context.summary.responder?.uaid ?? context.identity?.uaid;
|
|
2136
|
+
const handle = {
|
|
2137
|
+
sessionId: context.sessionId,
|
|
2138
|
+
mode: "encrypted",
|
|
2139
|
+
summary: context.summary,
|
|
2140
|
+
send: async (options) => {
|
|
2141
|
+
const recipients = options.recipients ?? context.recipients;
|
|
2142
|
+
return this.client.chat.sendMessage({
|
|
2143
|
+
sessionId: context.sessionId,
|
|
2144
|
+
message: options.message ?? "[ciphertext omitted]",
|
|
2145
|
+
streaming: options.streaming,
|
|
2146
|
+
auth: options.auth,
|
|
2147
|
+
uaid,
|
|
2148
|
+
encryption: {
|
|
2149
|
+
plaintext: options.plaintext,
|
|
2150
|
+
sharedSecret: Buffer.from(sharedSecret),
|
|
2151
|
+
recipients
|
|
2152
|
+
}
|
|
2153
|
+
});
|
|
2154
|
+
},
|
|
2155
|
+
decryptHistoryEntry: (entry) => this.decryptEntry(entry, context.identity, sharedSecret)
|
|
2156
|
+
};
|
|
2157
|
+
this.registerConversationContext({
|
|
2158
|
+
sessionId: context.sessionId,
|
|
2159
|
+
sharedSecret,
|
|
2160
|
+
identity: context.identity
|
|
2161
|
+
});
|
|
2162
|
+
return handle;
|
|
2163
|
+
}
|
|
2164
|
+
decryptEntry(entry, identity, fallbackSecret) {
|
|
2165
|
+
const envelope = entry.cipherEnvelope;
|
|
2166
|
+
if (!envelope) {
|
|
2167
|
+
return null;
|
|
2168
|
+
}
|
|
2169
|
+
const secret = Buffer.from(fallbackSecret);
|
|
2170
|
+
try {
|
|
2171
|
+
return this.client.encryption.decryptCipherEnvelope({
|
|
2172
|
+
envelope,
|
|
2173
|
+
sharedSecret: secret
|
|
2174
|
+
});
|
|
2175
|
+
} catch (_error) {
|
|
2176
|
+
return null;
|
|
2177
|
+
}
|
|
2178
|
+
}
|
|
2179
|
+
recipientMatches(candidate, target) {
|
|
2180
|
+
if (target.uaid && candidate.uaid?.toLowerCase() === target.uaid.toLowerCase()) {
|
|
2181
|
+
return true;
|
|
2182
|
+
}
|
|
2183
|
+
if (target.ledgerAccountId && candidate.ledgerAccountId?.toLowerCase() === target.ledgerAccountId.toLowerCase()) {
|
|
2184
|
+
return true;
|
|
2185
|
+
}
|
|
2186
|
+
if (target.userId && candidate.userId === target.userId) {
|
|
2187
|
+
return true;
|
|
2188
|
+
}
|
|
2189
|
+
if (target.email && candidate.email?.toLowerCase() === target.email.toLowerCase()) {
|
|
2190
|
+
return true;
|
|
2191
|
+
}
|
|
2192
|
+
return false;
|
|
2193
|
+
}
|
|
2194
|
+
async delay(ms) {
|
|
2195
|
+
if (ms <= 0) {
|
|
2196
|
+
return;
|
|
2197
|
+
}
|
|
2198
|
+
await new Promise((resolve) => setTimeout(resolve, ms));
|
|
2199
|
+
}
|
|
2200
|
+
}
|
|
2201
|
+
class EncryptionUnavailableError extends Error {
|
|
2202
|
+
constructor(sessionId, summary) {
|
|
2203
|
+
super("Encryption is not enabled for this session");
|
|
2204
|
+
this.sessionId = sessionId;
|
|
2205
|
+
this.summary = summary;
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
52
2208
|
export {
|
|
53
|
-
|
|
2209
|
+
RegistryBrokerClient,
|
|
2210
|
+
RegistryBrokerError,
|
|
2211
|
+
RegistryBrokerParseError,
|
|
2212
|
+
isPartialRegisterAgentResponse,
|
|
2213
|
+
isPendingRegisterAgentResponse,
|
|
2214
|
+
isSuccessRegisterAgentResponse
|
|
54
2215
|
};
|
|
55
2216
|
//# sourceMappingURL=standards-sdk.es128.js.map
|