@btps/sdk 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/LICENSE +190 -0
  3. package/NOTICE +25 -0
  4. package/README.md +261 -2
  5. package/dist/client/btpsAgent.d.ts +20 -0
  6. package/dist/client/btpsAgent.js +172 -0
  7. package/dist/client/btpsClient.d.ts +202 -0
  8. package/dist/client/btpsClient.js +602 -0
  9. package/dist/client/btpsTransporter.d.ts +52 -0
  10. package/dist/client/btpsTransporter.js +249 -0
  11. package/dist/client/constants.ts/index.d.ts +11 -0
  12. package/dist/client/constants.ts/index.js +20 -0
  13. package/dist/client/index.d.ts +12 -0
  14. package/dist/client/index.js +27 -0
  15. package/dist/client/libs/schema.d.ts +27604 -0
  16. package/dist/client/libs/schema.js +56 -0
  17. package/dist/client/libs/timeouts.d.ts +22 -0
  18. package/dist/client/libs/timeouts.js +19 -0
  19. package/dist/client/types/index.d.ts +155 -0
  20. package/dist/client/types/index.js +7 -0
  21. package/dist/core/authentication/BtpsAuthentication.d.ts +128 -0
  22. package/dist/core/authentication/BtpsAuthentication.js +293 -0
  23. package/dist/core/authentication/index.d.ts +11 -0
  24. package/dist/core/authentication/index.js +12 -0
  25. package/dist/core/authentication/keyProof.d.ts +18 -0
  26. package/dist/core/authentication/keyProof.js +16 -0
  27. package/dist/core/authentication/storage/InMemoryAuthSessionStore.d.ts +55 -0
  28. package/dist/core/authentication/storage/InMemoryAuthSessionStore.js +62 -0
  29. package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +63 -0
  30. package/dist/core/authentication/storage/InMemoryTokenStore.js +63 -0
  31. package/dist/core/authentication/types.d.ts +135 -0
  32. package/dist/core/authentication/types.js +7 -0
  33. package/dist/core/crypto/decryptVerify.d.ts +9 -0
  34. package/dist/core/crypto/decryptVerify.js +45 -0
  35. package/dist/core/crypto/decrypter-interface.d.ts +25 -0
  36. package/dist/core/crypto/decrypter-interface.js +7 -0
  37. package/dist/core/crypto/index.d.ts +77 -0
  38. package/dist/core/crypto/index.js +210 -0
  39. package/dist/core/crypto/jcs.d.ts +28 -0
  40. package/dist/core/crypto/jcs.js +60 -0
  41. package/dist/core/crypto/keygen.d.ts +9 -0
  42. package/dist/core/crypto/keygen.js +35 -0
  43. package/dist/core/crypto/pem-decrypter.d.ts +26 -0
  44. package/dist/core/crypto/pem-decrypter.js +52 -0
  45. package/dist/core/crypto/pem-signer.d.ts +21 -0
  46. package/dist/core/crypto/pem-signer.js +34 -0
  47. package/dist/core/crypto/signEncrypt.d.ts +34 -0
  48. package/dist/core/crypto/signEncrypt.js +75 -0
  49. package/dist/core/crypto/signer-interface.d.ts +22 -0
  50. package/dist/core/crypto/signer-interface.js +7 -0
  51. package/dist/core/crypto/types.d.ts +79 -0
  52. package/dist/core/crypto/types.js +7 -0
  53. package/dist/core/delegation/BtpsDelegator.d.ts +102 -0
  54. package/dist/core/delegation/BtpsDelegator.js +118 -0
  55. package/dist/core/delegation/index.d.ts +7 -0
  56. package/dist/core/delegation/index.js +8 -0
  57. package/dist/core/error/constant.d.ts +66 -0
  58. package/dist/core/error/constant.js +194 -0
  59. package/dist/core/error/index.d.ts +35 -0
  60. package/dist/core/error/index.js +52 -0
  61. package/dist/core/error/types.d.ts +16 -0
  62. package/dist/core/error/types.js +7 -0
  63. package/dist/core/server/constants/btps-protocol.d.ts +17 -0
  64. package/dist/core/server/constants/btps-protocol.js +25 -0
  65. package/dist/core/server/constants/control.d.ts +7 -0
  66. package/dist/core/server/constants/control.js +11 -0
  67. package/dist/core/server/constants/currency.d.ts +7 -0
  68. package/dist/core/server/constants/currency.js +332 -0
  69. package/dist/core/server/constants/index.d.ts +26 -0
  70. package/dist/core/server/constants/index.js +61 -0
  71. package/dist/core/server/constants/limits.d.ts +50 -0
  72. package/dist/core/server/constants/limits.js +50 -0
  73. package/dist/core/server/helpers/BtpsMessageQueue.d.ts +13 -0
  74. package/dist/core/server/helpers/BtpsMessageQueue.js +12 -0
  75. package/dist/core/server/helpers/InMemoryQueue.d.ts +16 -0
  76. package/dist/core/server/helpers/InMemoryQueue.js +35 -0
  77. package/dist/core/server/helpers/index.d.ts +8 -0
  78. package/dist/core/server/helpers/index.js +9 -0
  79. package/dist/core/server/schemas/artifacts/agentSchema.d.ts +4565 -0
  80. package/dist/core/server/schemas/artifacts/agentSchema.js +51 -0
  81. package/dist/core/server/schemas/artifacts/artifacts.d.ts +4920 -0
  82. package/dist/core/server/schemas/artifacts/artifacts.js +21 -0
  83. package/dist/core/server/schemas/artifacts/controlSchema.d.ts +23 -0
  84. package/dist/core/server/schemas/artifacts/controlSchema.js +18 -0
  85. package/dist/core/server/schemas/artifacts/identityLookupSchema.d.ts +32 -0
  86. package/dist/core/server/schemas/artifacts/identityLookupSchema.js +21 -0
  87. package/dist/core/server/schemas/artifacts/transporterSchema.d.ts +553 -0
  88. package/dist/core/server/schemas/artifacts/transporterSchema.js +60 -0
  89. package/dist/core/server/schemas/btpsDocsSchema.d.ts +4519 -0
  90. package/dist/core/server/schemas/btpsDocsSchema.js +272 -0
  91. package/dist/core/server/schemas/helpers.d.ts +1612 -0
  92. package/dist/core/server/schemas/helpers.js +87 -0
  93. package/dist/core/server/schemas/responseSchema.d.ts +6918 -0
  94. package/dist/core/server/schemas/responseSchema.js +86 -0
  95. package/dist/core/server/schemas/schema.d.ts +4916 -0
  96. package/dist/core/server/schemas/schema.js +70 -0
  97. package/dist/core/server/schemas/shared.d.ts +21 -0
  98. package/dist/core/server/schemas/shared.js +18 -0
  99. package/dist/core/server/types.d.ts +172 -0
  100. package/dist/core/server/types.js +7 -0
  101. package/dist/core/storage/AbstractIdentityStore.d.ts +17 -0
  102. package/dist/core/storage/AbstractIdentityStore.js +13 -0
  103. package/dist/core/storage/AbstractStorageStore.d.ts +16 -0
  104. package/dist/core/storage/AbstractStorageStore.js +17 -0
  105. package/dist/core/storage/JsonIdentityStore.d.ts +29 -0
  106. package/dist/core/storage/JsonIdentityStore.js +39 -0
  107. package/dist/core/storage/JsonStorageStore.d.ts +59 -0
  108. package/dist/core/storage/JsonStorageStore.js +110 -0
  109. package/dist/core/storage/index.d.ts +11 -0
  110. package/dist/core/storage/index.js +18 -0
  111. package/dist/core/storage/types.d.ts +28 -0
  112. package/dist/core/storage/types.js +7 -0
  113. package/dist/core/trust/index.d.ts +10 -0
  114. package/dist/core/trust/index.js +15 -0
  115. package/dist/core/trust/storage/AbstractTrustStore.d.ts +23 -0
  116. package/dist/core/trust/storage/AbstractTrustStore.js +13 -0
  117. package/dist/core/trust/storage/JsonTrustStore.d.ts +33 -0
  118. package/dist/core/trust/storage/JsonTrustStore.js +42 -0
  119. package/dist/core/trust/trustUtils.d.ts +78 -0
  120. package/dist/core/trust/trustUtils.js +41 -0
  121. package/dist/core/trust/types.d.ts +53 -0
  122. package/dist/core/trust/types.js +7 -0
  123. package/dist/core/utils/identity.d.ts +20 -0
  124. package/dist/core/utils/identity.js +22 -0
  125. package/dist/core/utils/index.d.ts +70 -0
  126. package/dist/core/utils/index.js +124 -0
  127. package/dist/core/utils/types.d.ts +10 -0
  128. package/dist/core/utils/types.js +7 -0
  129. package/dist/core/utils/validation.d.ts +14 -0
  130. package/dist/core/utils/validation.js +13 -0
  131. package/dist/index.d.ts +7 -0
  132. package/dist/index.js +8 -0
  133. package/dist/server/btpsServer.d.ts +292 -0
  134. package/dist/server/btpsServer.js +827 -0
  135. package/dist/server/index.d.ts +11 -0
  136. package/dist/server/index.js +15 -0
  137. package/dist/server/libs/abstractRateLimiter.d.ts +10 -0
  138. package/dist/server/libs/abstractRateLimiter.js +15 -0
  139. package/dist/server/libs/artifactSizeGuard.d.ts +27 -0
  140. package/dist/server/libs/artifactSizeGuard.js +44 -0
  141. package/dist/server/libs/artifactTimeWindow.d.ts +24 -0
  142. package/dist/server/libs/artifactTimeWindow.js +30 -0
  143. package/dist/server/libs/btpsFactory.d.ts +29 -0
  144. package/dist/server/libs/btpsFactory.js +49 -0
  145. package/dist/server/libs/btpsLightweightFactory.d.ts +35 -0
  146. package/dist/server/libs/btpsLightweightFactory.js +37 -0
  147. package/dist/server/libs/btpsRegistry.d.ts +14 -0
  148. package/dist/server/libs/btpsRegistry.js +16 -0
  149. package/dist/server/libs/btpsSimpleMetricsTracker.d.ts +13 -0
  150. package/dist/server/libs/btpsSimpleMetricsTracker.js +21 -0
  151. package/dist/server/libs/btpsSimpleRateLimiter.d.ts +28 -0
  152. package/dist/server/libs/btpsSimpleRateLimiter.js +46 -0
  153. package/dist/server/libs/connectionTimeout.d.ts +16 -0
  154. package/dist/server/libs/connectionTimeout.js +14 -0
  155. package/dist/server/libs/defaultMiddleware.d.ts +8 -0
  156. package/dist/server/libs/defaultMiddleware.js +128 -0
  157. package/dist/server/libs/inFlightLimit.d.ts +18 -0
  158. package/dist/server/libs/inFlightLimit.js +17 -0
  159. package/dist/server/libs/index.d.ts +18 -0
  160. package/dist/server/libs/index.js +34 -0
  161. package/dist/server/libs/middlewareManager.d.ts +59 -0
  162. package/dist/server/libs/middlewareManager.js +126 -0
  163. package/dist/server/libs/type.d.ts +22 -0
  164. package/dist/server/libs/type.js +7 -0
  165. package/dist/server/types.d.ts +236 -0
  166. package/dist/server/types.js +7 -0
  167. package/package.json +126 -4
@@ -0,0 +1,602 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+
8
+ import tls from "tls";
9
+ import { EventEmitter } from "events";
10
+ import split2 from "split2";
11
+ import {
12
+ getBtpAddressParts,
13
+ getDnsIdentityParts,
14
+ getHostAndSelector,
15
+ isValidIdentity,
16
+ resolvePublicKey
17
+ } from "../core/utils/index.js";
18
+ import {
19
+ BTP_ERROR_CONNECTION_CLOSED,
20
+ BTP_ERROR_CONNECTION_ENDED,
21
+ BTP_ERROR_IDENTITY,
22
+ BTP_ERROR_IDENTITY_NOT_FOUND,
23
+ BTP_ERROR_RESOLVE_DNS,
24
+ BTP_ERROR_RESOLVE_PUBKEY,
25
+ BTP_ERROR_SIG_VERIFICATION,
26
+ BTP_ERROR_SOCKET_TIMEOUT,
27
+ BTP_ERROR_TIMEOUT,
28
+ BTP_ERROR_VALIDATION,
29
+ BTPErrorException,
30
+ transformToBTPErrorException
31
+ } from "../core/error/index.js";
32
+ import { BTP_PROTOCOL_VERSION } from "../core/server/constants/index.js";
33
+ import { randomUUID } from "crypto";
34
+ import isEmpty from "lodash/isEmpty.js";
35
+ import { decryptVerify } from "../core/crypto/decryptVerify.js";
36
+ import { assertStrictJson } from "../core/crypto/jcs.js";
37
+ import { validate } from "../core/utils/validation.js";
38
+ import { BtpArtifactServerSchema } from "../core/server/schemas/artifacts/artifacts.js";
39
+ import {
40
+ DEFAULT_CONNECT_TIMEOUT_MS,
41
+ DEFAULT_REPLY_TIMEOUT_MS,
42
+ MIN_CONNECT_TIMEOUT_MS,
43
+ MIN_REPLY_TIMEOUT_MS,
44
+ resolveTimeoutMs
45
+ } from "./libs/timeouts.js";
46
+ class BtpsClient {
47
+ constructor(options) {
48
+ this.options = options;
49
+ const { to } = this.options;
50
+ if (!to || !isValidIdentity(to))
51
+ throw new BTPErrorException(BTP_ERROR_IDENTITY, {
52
+ cause: "Invalid to identity"
53
+ });
54
+ this.connectTimeoutMs = resolveTimeoutMs(
55
+ "connectTimeoutMs",
56
+ options.connectTimeoutMs,
57
+ MIN_CONNECT_TIMEOUT_MS,
58
+ DEFAULT_CONNECT_TIMEOUT_MS
59
+ ), this.replyTimeoutMs = resolveTimeoutMs(
60
+ "replyTimeoutMs",
61
+ options.replyTimeoutMs,
62
+ MIN_REPLY_TIMEOUT_MS,
63
+ DEFAULT_REPLY_TIMEOUT_MS
64
+ );
65
+ }
66
+ socket;
67
+ emitter = new EventEmitter();
68
+ retries = 0;
69
+ backpressureQueue = [];
70
+ states = {
71
+ isConnecting: !1,
72
+ isConnected: !1,
73
+ isDraining: !1,
74
+ isDestroyed: !1,
75
+ shouldRetry: !0
76
+ };
77
+ queue = new Map();
78
+ connectTimeoutMs;
79
+ replyTimeoutMs;
80
+ async getSocket() {
81
+ if (this.socket && !this.socket.destroyed) return { socket: this.socket, error: void 0 };
82
+ if (this.states.isConnecting) {
83
+ const error = new BTPErrorException({ message: "already connecting" });
84
+ return this.emitError({
85
+ error,
86
+ ...this.getRetryInfo(error)
87
+ }), {
88
+ socket: void 0,
89
+ error
90
+ };
91
+ }
92
+ this.states.isConnecting = !0;
93
+ const btpHostDnsConfig = await this.resolveBtpsHostDnsTxt(this.options.to);
94
+ if (!btpHostDnsConfig)
95
+ return this.states.isConnecting = !1, { socket: void 0, error: new BTPErrorException({
96
+ message: `DNS resolution failed for ${this.options.to}`
97
+ }) };
98
+ const { hostname, port } = btpHostDnsConfig, tlsOptions = {
99
+ ...this.options.btpMtsOptions,
100
+ host: hostname,
101
+ port
102
+ };
103
+ return new Promise((resolve) => {
104
+ const connectTimer = setTimeout(() => {
105
+ sock.destroy(
106
+ new BTPErrorException(BTP_ERROR_SOCKET_TIMEOUT, {
107
+ cause: `could not connect within ${this.connectTimeoutMs} ms`
108
+ })
109
+ );
110
+ }, this.connectTimeoutMs), sock = tls.connect(tlsOptions, () => {
111
+ clearTimeout(connectTimer), this.states.isConnected = !0, this.states.isConnecting = !1, sock.ref(), this.socket = sock, this.emitter.emit("connected", {
112
+ identity: this.options.to,
113
+ retries: this.retries,
114
+ states: this.states,
115
+ socket: sock
116
+ }), resolve({ socket: sock, error: void 0 });
117
+ });
118
+ sock.once("close", () => clearTimeout(connectTimer)), this.attachListeners(sock, this.options.to);
119
+ const idleMs = this.options.connectionTimeoutMs;
120
+ idleMs && sock.setTimeout(idleMs, () => {
121
+ if (this.queue.size > 0) {
122
+ sock.setTimeout(idleMs);
123
+ return;
124
+ }
125
+ this.end();
126
+ });
127
+ });
128
+ }
129
+ attachListeners(socket, receiverId) {
130
+ socket.pipe(split2()).on("data", (line) => this.onData(line)), socket.on("drain", () => {
131
+ this.flushBackpressure();
132
+ });
133
+ const onSocketError = (err) => {
134
+ const error = transformToBTPErrorException(err), info = this.getRetryInfo(error), errorInfo = { ...info, error };
135
+ this.states.isConnecting = !1, this.states.isConnected = !1, this.emitError(errorInfo), info.willRetry ? this.retryConnect(receiverId) : this.resolveError(error);
136
+ };
137
+ socket.on("error", onSocketError), socket.on("end", () => {
138
+ this.states.isConnected = !1, this.states.isConnecting = !1;
139
+ const info = this.getRetryInfo(), error = new BTPErrorException(BTP_ERROR_CONNECTION_ENDED);
140
+ this.emitter.emit("end", {
141
+ ...info,
142
+ error
143
+ }), info.willRetry ? this.resolveError(error) : this.retryConnect(receiverId);
144
+ }), socket.on("close", () => {
145
+ const err = new BTPErrorException(BTP_ERROR_CONNECTION_CLOSED, {
146
+ cause: "connection closed"
147
+ }), info = this.getRetryInfo(err);
148
+ this.emitter.emit("end", { ...info, error: err }), this.resolveError(err);
149
+ });
150
+ }
151
+ async onData(line) {
152
+ if (line.trim())
153
+ try {
154
+ assertStrictJson(line);
155
+ const msg = JSON.parse(line);
156
+ this.states.shouldRetry = !1;
157
+ const { isValid: validSignature, error } = await this.verifyServerMessage(msg), reqId = msg?.reqId ?? (msg?.type === "btps_error" && this.queue.size === 1 ? this.queue.keys().next().value : void 0);
158
+ if (reqId && this.queue.has(reqId)) {
159
+ const pendingMsg = { ...this.queue.get(reqId) }, { resolve, timeout } = pendingMsg;
160
+ this.queue.delete(reqId), clearTimeout(timeout), resolve({
161
+ response: validSignature ? msg : void 0,
162
+ error: validSignature ? void 0 : error
163
+ }), this.pumpNextQueue();
164
+ } else
165
+ this.emitter.emit("message", { response: msg, validSignature, error });
166
+ } catch (e) {
167
+ const err = new SyntaxError(`Invalid JSON: ${e}`);
168
+ this.states.shouldRetry = !1, this.emitError({ error: err, ...this.getRetryInfo(err) });
169
+ }
170
+ }
171
+ pumpNextQueue() {
172
+ if (this.queue.size && this.states.isConnected) {
173
+ const firstJob = this.queue.values().next().value;
174
+ firstJob && this.sendArtifact(firstJob.artifact, {
175
+ resolve: firstJob.resolve,
176
+ timeout: firstJob.timeout
177
+ });
178
+ } else
179
+ this.unrefSocketIfNoQueue();
180
+ }
181
+ unrefSocketIfNoQueue() {
182
+ this.queue.size === 0 && this.socket && !this.socket.destroyed && this.socket.unref();
183
+ }
184
+ async flushBackpressure() {
185
+ if (!this.states.isDraining) {
186
+ this.states.isDraining = !0;
187
+ try {
188
+ for (; this.backpressureQueue.length && this.socket?.writable; ) {
189
+ const chunk = this.backpressureQueue.shift();
190
+ if (!chunk) break;
191
+ this.socket.write(chunk) || await new Promise((resolve) => this.socket.once("drain", resolve));
192
+ }
193
+ } finally {
194
+ this.states.isDraining = !1;
195
+ }
196
+ }
197
+ }
198
+ retryConnect(receiverId) {
199
+ const maxRetries = this.options.maxRetries ?? 5, delay = this.options.retryDelayMs ?? 1e3;
200
+ this.retries >= maxRetries || (this.retries++, setTimeout(() => {
201
+ this.getSocket().catch((err) => {
202
+ });
203
+ }, delay));
204
+ }
205
+ resolveError(error) {
206
+ this.states.isConnected = !1, this.states.isConnecting = !1, this.socket = void 0, this.cleanupQueue(error);
207
+ }
208
+ cleanupQueue(resolveError) {
209
+ if (this.queue.size !== 0) {
210
+ for (const [_id, qItem] of this.queue)
211
+ clearTimeout(qItem.timeout), resolveError && qItem.resolve({
212
+ response: void 0,
213
+ error: resolveError
214
+ });
215
+ this.queue.clear();
216
+ }
217
+ }
218
+ emitError(errorInfo) {
219
+ this.emitter.listenerCount("error") === 0 ? console.error("[BtpsClient]::Unhandled error:", errorInfo) : this.emitter.emit("error", errorInfo);
220
+ }
221
+ getRetryInfo(forError) {
222
+ const maxRetries = this.options.maxRetries ?? 5;
223
+ let willRetry = this.retries < maxRetries;
224
+ return (this.states.isDestroyed || forError instanceof SyntaxError || this.isNonRetryableError(forError) || !this.states.shouldRetry) && (willRetry = !1), {
225
+ willRetry,
226
+ retriesLeft: willRetry ? maxRetries - this.retries - 1 : 0,
227
+ attempt: this.retries
228
+ };
229
+ }
230
+ buildClientErrorResponse(error, responseProp = "response") {
231
+ return Promise.resolve({ [responseProp]: void 0, error });
232
+ }
233
+ update(options) {
234
+ const {
235
+ maxRetries,
236
+ retryDelayMs,
237
+ connectTimeoutMs,
238
+ replyTimeoutMs,
239
+ connectionTimeoutMs,
240
+ maxQueue
241
+ } = options;
242
+ this.options.maxRetries = maxRetries ?? this.options.maxRetries, this.options.retryDelayMs = retryDelayMs ?? this.options.retryDelayMs, connectTimeoutMs !== void 0 && (this.connectTimeoutMs = resolveTimeoutMs(
243
+ "connectTimeoutMs",
244
+ connectTimeoutMs,
245
+ MIN_CONNECT_TIMEOUT_MS,
246
+ DEFAULT_CONNECT_TIMEOUT_MS
247
+ )), replyTimeoutMs !== void 0 && (this.replyTimeoutMs = resolveTimeoutMs(
248
+ "replyTimeoutMs",
249
+ replyTimeoutMs,
250
+ MIN_REPLY_TIMEOUT_MS,
251
+ DEFAULT_REPLY_TIMEOUT_MS
252
+ )), this.options.connectionTimeoutMs = connectionTimeoutMs ?? this.options.connectionTimeoutMs, this.options.maxQueue = maxQueue ?? this.options.maxQueue;
253
+ }
254
+ getConnectionStates() {
255
+ return this.states;
256
+ }
257
+ resolveBtpsHostDnsTxt(receiverId) {
258
+ return new Promise((resolve) => {
259
+ if (this.options?.host) {
260
+ const addressParts = getBtpAddressParts(this.options.host), hostname = addressParts?.hostname ?? this.options.host, port = addressParts?.port ? parseInt(addressParts.port, 10) : this.options?.port ?? 3443;
261
+ resolve({
262
+ hostname,
263
+ selector: this.options?.hostSelector ?? "btps1",
264
+ version: this.options?.version ?? BTP_PROTOCOL_VERSION,
265
+ port,
266
+ ...this.options?.hostOperator ? { operator: this.options.hostOperator } : {}
267
+ });
268
+ return;
269
+ }
270
+ getHostAndSelector(receiverId).then((btpConfig) => {
271
+ if (!btpConfig) {
272
+ resolve(void 0);
273
+ return;
274
+ }
275
+ const addressParts = getBtpAddressParts(btpConfig.host);
276
+ if (!addressParts) {
277
+ resolve(void 0);
278
+ return;
279
+ }
280
+ const hostname = addressParts.hostname, port = addressParts?.port ? parseInt(addressParts.port, 10) : 3443;
281
+ resolve({
282
+ hostname,
283
+ port,
284
+ selector: btpConfig.selector,
285
+ version: btpConfig.version,
286
+ ...btpConfig.operator ? { operator: btpConfig.operator } : {}
287
+ });
288
+ }).catch(() => {
289
+ resolve(void 0);
290
+ });
291
+ });
292
+ }
293
+ processResolveOnError(artifactId, error, resolveOnError) {
294
+ const { resolve, timeout } = resolveOnError ?? {};
295
+ resolve ? resolve({ response: void 0, error }) : this.emitError({ error, ...this.getRetryInfo(error) }), timeout && clearTimeout(timeout), this.queue.has(artifactId) && this.queue.delete(artifactId), this.unrefSocketIfNoQueue();
296
+ }
297
+ sendArtifact(artifact, resolveOnError) {
298
+ const { isValid, error } = this.validateArtifact(artifact);
299
+ if (!isValid) {
300
+ this.processResolveOnError(artifact.id, error, resolveOnError);
301
+ return;
302
+ }
303
+ if (this.socket?.destroyed || this.socket?.writableEnded || !this.states.isConnected || this.states.isDestroyed || this.states.isConnecting) {
304
+ this.processResolveOnError(
305
+ artifact.id,
306
+ new BTPErrorException(BTP_ERROR_CONNECTION_CLOSED, {
307
+ cause: "connection closed"
308
+ }),
309
+ resolveOnError
310
+ );
311
+ return;
312
+ }
313
+ const serialized = JSON.stringify(artifact) + `
314
+ `;
315
+ this.socket?.write(serialized) || (this.backpressureQueue.push(serialized), this.states.isDraining = !0);
316
+ }
317
+ async dispatch(job) {
318
+ const { artifact, resolve, timeoutMs } = job, id = artifact.id, timeout = setTimeout(() => {
319
+ this.queue.has(id) && this.queue.delete(id), resolve({
320
+ response: void 0,
321
+ error: new BTPErrorException(BTP_ERROR_TIMEOUT, {
322
+ cause: `timeout waiting for response reqId=${id}`
323
+ })
324
+ }), this.unrefSocketIfNoQueue();
325
+ }, timeoutMs);
326
+ if (this.queue.set(id, { artifact, resolve, timeout }), this.states.isConnecting)
327
+ return;
328
+ const { socket, error } = await this.getSocket();
329
+ if (error && !this.states.isConnecting) {
330
+ this.queue.delete(id), clearTimeout(timeout), resolve({
331
+ response: void 0,
332
+ error
333
+ }), this.queue.size && this.cleanupQueue(
334
+ new BTPErrorException({ message: "socket could not be established." }, { cause: error })
335
+ ), this.unrefSocketIfNoQueue();
336
+ return;
337
+ }
338
+ socket?.ref(), socket && this.sendArtifact(artifact, { resolve, timeout });
339
+ }
340
+ isNonRetryableError(err) {
341
+ const message = (err?.message ?? "").toLowerCase();
342
+ return [
343
+ "client disconnected after inactivity",
344
+ "already connecting",
345
+ "dns resolution failed",
346
+ "invalid identity",
347
+ "invalid btpaddress",
348
+ "invalid hostname",
349
+ "invalid artifact",
350
+ "unsupported protocol",
351
+ "signature verification failed",
352
+ "destroyed"
353
+ ].some((m) => message.includes(m));
354
+ }
355
+ async verifyServerMessage(msg) {
356
+ const { signature, signedBy, selector } = msg;
357
+ if (!msg.signature)
358
+ return {
359
+ isValid: !0,
360
+ error: void 0
361
+ };
362
+ if (signature && signedBy && selector) {
363
+ let senderPubPem, error;
364
+ try {
365
+ senderPubPem = await resolvePublicKey(signedBy, selector), senderPubPem || (error = new BTPErrorException(BTP_ERROR_SIG_VERIFICATION, {
366
+ cause: `Failed to resolve public key for identity: ${signedBy} and selector: ${selector}`,
367
+ meta: msg
368
+ }));
369
+ } catch (err) {
370
+ error = transformToBTPErrorException(err, {
371
+ cause: `Failed to resolve public key for identity: ${signedBy} and selector: ${selector}`,
372
+ meta: { msg }
373
+ });
374
+ }
375
+ if (error)
376
+ return {
377
+ isValid: !1,
378
+ error
379
+ };
380
+ const { error: decryptError } = await this.decryptVerifyArtifact(
381
+ msg,
382
+ senderPubPem
383
+ );
384
+ return decryptError ? {
385
+ isValid: !1,
386
+ error: decryptError
387
+ } : {
388
+ isValid: !0,
389
+ error: void 0
390
+ };
391
+ }
392
+ return {
393
+ isValid: !1,
394
+ error: new BTPErrorException(BTP_ERROR_VALIDATION, {
395
+ cause: "Message is either not signed or does not have signedBy",
396
+ meta: msg
397
+ })
398
+ };
399
+ }
400
+ validateArtifact(artifact) {
401
+ const validationResult = validate(BtpArtifactServerSchema, artifact);
402
+ return validationResult.success ? { isValid: !0, error: void 0 } : {
403
+ isValid: !1,
404
+ error: new BTPErrorException(BTP_ERROR_VALIDATION, {
405
+ cause: "Invalid artifact",
406
+ meta: validationResult.error.issues.reduce(
407
+ (acc, issue) => (acc[issue.path.join(".")] = issue.message, acc),
408
+ {}
409
+ )
410
+ })
411
+ };
412
+ }
413
+ async send(artifact, timeoutMs) {
414
+ if (timeoutMs = timeoutMs === void 0 ? this.replyTimeoutMs : resolveTimeoutMs("replyTimeoutMs", timeoutMs, MIN_REPLY_TIMEOUT_MS, this.replyTimeoutMs), this.states.isDestroyed)
415
+ return this.buildClientErrorResponse(
416
+ new BTPErrorException({ message: "BtpsClient instance is destroyed" }),
417
+ "response"
418
+ );
419
+ const { isValid, error } = this.validateArtifact(artifact);
420
+ if (!isValid)
421
+ return this.buildClientErrorResponse(error, "response");
422
+ const id = artifact.id ?? randomUUID();
423
+ return artifact.id = id, artifact.issuedAt = artifact.issuedAt ?? ( new Date()).toISOString(), await new Promise((resolve) => {
424
+ const job = { artifact, resolve, timeoutMs };
425
+ this.queue.size < (this.options.maxQueue ?? 100) ? this.dispatch(job) : resolve({
426
+ response: void 0,
427
+ error: new BTPErrorException(
428
+ {
429
+ message: "request queue full. Please try again later or increase maxQueue"
430
+ },
431
+ { meta: { maxQueue: this.options.maxQueue ?? 100 } }
432
+ )
433
+ });
434
+ });
435
+ }
436
+ decryptVerifyArtifact = async (artifact, senderPubPem, receiverKey) => await decryptVerify(senderPubPem, artifact, receiverKey);
437
+ async resolveIdentity(identity, from, receiverKey) {
438
+ if (!isValidIdentity(identity) || !isValidIdentity(from))
439
+ return await this.buildClientErrorResponse(
440
+ new BTPErrorException(BTP_ERROR_IDENTITY, {
441
+ cause: `invalid identity: ${identity} or ${from}`
442
+ })
443
+ );
444
+ const btpHostDnsConfig = await this.resolveBtpsHostDnsTxt(identity);
445
+ if (!btpHostDnsConfig)
446
+ return await this.buildClientErrorResponse(
447
+ new BTPErrorException(BTP_ERROR_RESOLVE_DNS, {
448
+ cause: `DNS resolution failed for ${identity}`
449
+ })
450
+ );
451
+ const { selector, hostname, port, version } = btpHostDnsConfig;
452
+ if (isEmpty(hostname) || !hostname)
453
+ return await this.buildClientErrorResponse(
454
+ new BTPErrorException({ message: `invalid hostname: ${hostname}` })
455
+ );
456
+ try {
457
+ const dnsIdentityParts = await getDnsIdentityParts(identity, selector);
458
+ if (dnsIdentityParts && typeof dnsIdentityParts == "object") {
459
+ const { key, version: version2, pem } = dnsIdentityParts;
460
+ return {
461
+ response: {
462
+ keyType: key,
463
+ publicKey: pem,
464
+ selector,
465
+ version: version2,
466
+ hostname,
467
+ port
468
+ },
469
+ error: void 0
470
+ };
471
+ }
472
+ const { operator } = btpHostDnsConfig;
473
+ return operator ? await new Promise((resolve) => {
474
+ const socket = tls.connect({ ...this.options.btpMtsOptions, host: hostname, port });
475
+ let settled = !1;
476
+ const settle = (value) => {
477
+ settled = !0, socket.destroy(), resolve(value);
478
+ }, fail = (error) => {
479
+ settled || settle(this.buildClientErrorResponse(error));
480
+ }, identityLookupRequest = {
481
+ identity,
482
+ from,
483
+ hostSelector: selector,
484
+ version: BTP_PROTOCOL_VERSION,
485
+ id: randomUUID(),
486
+ issuedAt: ( new Date()).toISOString()
487
+ };
488
+ socket.write(JSON.stringify(identityLookupRequest) + `
489
+ `);
490
+ let received = "";
491
+ socket.on("data", async (chunk) => {
492
+ received += chunk.toString();
493
+ const end = received.indexOf(`
494
+ `);
495
+ if (end === -1) return;
496
+ socket.removeAllListeners("data");
497
+ let msg;
498
+ try {
499
+ const line = received.slice(0, end);
500
+ assertStrictJson(line), msg = JSON.parse(line);
501
+ } catch (error) {
502
+ fail(new BTPErrorException(BTP_ERROR_VALIDATION, { cause: error }));
503
+ return;
504
+ }
505
+ const { signature, signedBy, selector: signedWith, type, status } = msg;
506
+ if (type === "btps_error" || !status.ok) {
507
+ fail(
508
+ new BTPErrorException(BTP_ERROR_IDENTITY_NOT_FOUND, {
509
+ cause: `Server returned error for identity: ${identity}`,
510
+ meta: msg
511
+ })
512
+ );
513
+ return;
514
+ }
515
+ if (!signature || !signedBy || !signedWith) {
516
+ fail(
517
+ new BTPErrorException(BTP_ERROR_VALIDATION, {
518
+ cause: "Message is not signed or does not have signedBy",
519
+ meta: msg
520
+ })
521
+ );
522
+ return;
523
+ }
524
+ if (signedBy !== operator) {
525
+ fail(
526
+ new BTPErrorException(BTP_ERROR_SIG_VERIFICATION, {
527
+ cause: `The answer is signed by ${signedBy}, not by ${operator}, the operator of ${identity}'s domain`
528
+ })
529
+ );
530
+ return;
531
+ }
532
+ const hostPubPem = await resolvePublicKey(signedBy, signedWith);
533
+ if (!hostPubPem) {
534
+ fail(
535
+ new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY, {
536
+ cause: `SignedBy is present but public key is not found for identity: ${signedBy} and selector: ${signedWith}`,
537
+ meta: msg
538
+ })
539
+ );
540
+ return;
541
+ }
542
+ const { payload: decryptedPayload, error: decryptError } = await this.decryptVerifyArtifact(
543
+ msg,
544
+ hostPubPem,
545
+ receiverKey
546
+ );
547
+ if (decryptError) {
548
+ fail(decryptError);
549
+ return;
550
+ }
551
+ const { document } = decryptedPayload || {};
552
+ if (!document) {
553
+ fail(
554
+ new BTPErrorException(BTP_ERROR_VALIDATION, {
555
+ cause: "document is not present in the message",
556
+ meta: msg
557
+ })
558
+ );
559
+ return;
560
+ }
561
+ settle({
562
+ response: {
563
+ ...document,
564
+ hostname,
565
+ port,
566
+ version
567
+ },
568
+ error: void 0
569
+ });
570
+ }), socket.on("error", (err) => fail(transformToBTPErrorException(err))), socket.on(
571
+ "close",
572
+ () => fail(new BTPErrorException(BTP_ERROR_CONNECTION_CLOSED, { cause: "connection closed" }))
573
+ );
574
+ }) : await this.buildClientErrorResponse(
575
+ new BTPErrorException(BTP_ERROR_IDENTITY_NOT_FOUND, {
576
+ cause: `${identity} has no key in DNS, and its domain declares no operator to answer for it`
577
+ })
578
+ );
579
+ } catch (error) {
580
+ return await this.buildClientErrorResponse(transformToBTPErrorException(error));
581
+ }
582
+ }
583
+ on = (event, listener) => (this.emitter.on(event, listener), this);
584
+ off = (event, listener) => (this.emitter.off(event, listener), this);
585
+ removeAllListeners() {
586
+ this.emitter.removeAllListeners();
587
+ }
588
+ getProtocolVersion() {
589
+ return BTP_PROTOCOL_VERSION;
590
+ }
591
+ end() {
592
+ this.states.isConnecting = !1, this.states.isConnected = !1, this.socket?.end(), this.socket = void 0;
593
+ }
594
+ destroy() {
595
+ this.states.isConnecting = !1, this.states.isConnected = !1, this.states.isDestroyed = !0, this.states.shouldRetry = !1, this.states.isDraining = !1, this.backpressureQueue = [], this.removeAllListeners(), this.socket?.destroy(), this.cleanupQueue(
596
+ new BTPErrorException(BTP_ERROR_CONNECTION_CLOSED, { cause: "client destroyed" })
597
+ );
598
+ }
599
+ }
600
+ export {
601
+ BtpsClient
602
+ };
@@ -0,0 +1,52 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+ import { BTPErrorException } from '../core/error/index.js';
8
+ import type { BTPClientOptions, BTPTransporterOptions, BTPConnection, BTPClientResponse, UpdateBTPClientOptions, TypedEventEmitter, BtpsTransporterEvents, BTPConnectionInternal, BTPTransporterMetrics } from './types/index.js';
9
+ import type { BTPTransporterArtifact } from '../core/server/types.js';
10
+ export declare class BtpsTransporter {
11
+ private connections;
12
+ private readonly connectionLock;
13
+ private readonly clientOptions;
14
+ private maxConnections;
15
+ private connectionTTLSeconds;
16
+ private readonly emitter;
17
+ constructor(options: BTPTransporterOptions);
18
+ private createClient;
19
+ protected attachListeners(connection: BTPConnectionInternal): void;
20
+ protected detachListeners(connection: BTPConnectionInternal): void;
21
+ protected performConnectionRegistration(to: string, clientOptions?: BTPClientOptions, override?: boolean): Promise<{
22
+ connection: BTPConnection;
23
+ error: undefined;
24
+ } | {
25
+ connection: undefined;
26
+ error: BTPErrorException;
27
+ }>;
28
+ protected buildClientErrorResponse(error: BTPErrorException): Promise<BTPClientResponse>;
29
+ protected createConnectionTimeout(connectionId: string, ttlSeconds?: number): NodeJS.Timeout;
30
+ /** Marks a connection used now, so its TTL counts from this moment. */
31
+ private touch;
32
+ registerConnection(to: string, clientOptions?: BTPClientOptions, override?: boolean): Promise<BTPConnection>;
33
+ deregisterConnection(to: string): void;
34
+ transport(to: string, artifact: BTPTransporterArtifact, clientOptions?: BTPClientOptions): Promise<BTPClientResponse>;
35
+ transportBatch(to: string, artifacts: BTPTransporterArtifact[], clientOptions?: BTPClientOptions): Promise<BTPClientResponse[]>;
36
+ getMaxConnections(): number;
37
+ setMaxConnections(maxConnections: number): void;
38
+ getConnectionTTLSeconds(): number;
39
+ updateConnectionTTLSeconds(connectionTTLSeconds: number, updateExistingConnections?: boolean): void;
40
+ getClientOptions(): Omit<BTPClientOptions, 'to'>;
41
+ getProtocolVersion(): string;
42
+ getConnections(): BTPConnection[];
43
+ getConnection(id: string): BTPConnection | undefined;
44
+ updateConnection(id: string, clientOptions?: UpdateBTPClientOptions, ttlSeconds?: number): BTPConnection | undefined;
45
+ getActiveConnections(): BTPConnection[];
46
+ getTotalConnections(): number;
47
+ getTotalActiveConnections(): number;
48
+ getMetrics(): BTPTransporterMetrics;
49
+ on: TypedEventEmitter<BtpsTransporterEvents>['on'];
50
+ off: TypedEventEmitter<BtpsTransporterEvents>['off'];
51
+ destroy(): void;
52
+ }