@btps/sdk 1.1.0 → 1.1.2

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/CHANGELOG.md CHANGED
@@ -4,6 +4,50 @@ All notable changes to `@btps/sdk` and the BTPS protocol it implements. The
4
4
  format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
5
5
  versions follow [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [1.1.2] — 2026-10-19 (alpha)
8
+
9
+ A patch release: the protocol and the API are unchanged.
10
+
11
+ ### Fixed
12
+
13
+ - **A client or transporter can keep sending after a server ends the
14
+ connection.** The next send used the ended connection and failed with
15
+ `BTP_ERROR_CONNECTION_CLOSED`. It now makes a new one. A `BtpsTransporter`
16
+ keeping one connection per receiver depends on this.
17
+ - **An answer is not lost when the server ends the connection right after
18
+ writing it**, as a rate limit does. Sends waiting on a connection are failed
19
+ only once the lines already received have been read.
20
+ - **A connection's end fails only the sends written to it.** An older
21
+ connection closing late used to fail the sends waiting on the newer one.
22
+ - **Sends made while the client is connecting each go out once**, on the
23
+ connection being made. Before, they waited for an earlier answer, and one
24
+ could be written twice.
25
+ - **`maxRetries` retries the connection, as documented.** A retry used to
26
+ reconnect without sending what was waiting, which then timed out. Each new
27
+ connection has its own tries, and an error event's `willRetry` says whether
28
+ another follows.
29
+
30
+ ## [1.1.1] — 2026-10-19 (alpha)
31
+
32
+ A patch release: the protocol and the API are unchanged.
33
+
34
+ ### Fixed
35
+
36
+ - **The package is about 3.8 MB smaller.** It no longer ships type
37
+ declarations that no entry point can reach: the exports map lets a project
38
+ import only the entry points, so those files were never read. The
39
+ declarations every entry point needs are all still included, and CI now
40
+ type-checks each entry point against the packed package.
41
+
42
+ ### Corrected
43
+
44
+ - The 1.1.0 notes said every trust refusal reads `BTP_ERROR_TRUST_NOT_ALLOWED`.
45
+ Two stay distinct on the wire: an expired trust reads
46
+ `BTP_ERROR_TRUST_EXPIRED`, and an artifact sent without the encryption the
47
+ trust requires reads `BTP_ERROR_PRIVACY_TYPE`. Every other refusal, including
48
+ a trust that was never made, is pending, rejected, revoked or blocked, reads
49
+ `BTP_ERROR_TRUST_NOT_ALLOWED`.
50
+
7
51
  ## [1.1.0] — 2026-10-18 (alpha)
8
52
 
9
53
  BTPS 1.1 is the alpha release of the protocol: 1.2 is planned as the beta and
@@ -146,4 +190,6 @@ of an exchange must upgrade together.
146
190
  - The default middleware counts an identity's rate limit after signature
147
191
  verification. Rate limiting is off unless a provider enables it.
148
192
 
193
+ [1.1.2]: https://github.com/openbtps/btps-node/releases/tag/v1.1.2
194
+ [1.1.1]: https://github.com/openbtps/btps-node/releases/tag/v1.1.1
149
195
  [1.1.0]: https://github.com/openbtps/btps-node/releases/tag/v1.1.0
@@ -10,6 +10,13 @@ import { BTPClientOptions, BTPClientResponse, BtpsClientEvents, BtpsHostDnsTxt,
10
10
  import { BTPErrorException } from '../core/error/index.js';
11
11
  import type { BTPArtifact, BTPIdentityResDoc, BTPServerResponse } from '../core/server/types.js';
12
12
  import { BTPCryptoResponse, BTPDecryptionKey, VerifyEncryptedPayload } from '../core/crypto/types.js';
13
+ type SocketResult = {
14
+ socket: TLSSocket;
15
+ error: undefined;
16
+ } | {
17
+ socket: undefined;
18
+ error: BTPErrorException;
19
+ };
13
20
  export declare class BtpsClient {
14
21
  protected options: BTPClientOptions;
15
22
  protected socket?: TLSSocket;
@@ -21,20 +28,36 @@ export declare class BtpsClient {
21
28
  artifact: BTPArtifact;
22
29
  resolve: (v: BTPClientResponse) => void;
23
30
  timeout: NodeJS.Timeout;
31
+ /** The connection it was written to: only that connection's end can answer it. */
32
+ socket?: TLSSocket;
24
33
  }>;
34
+ /** The connection being made, which every send waiting for one shares. */
35
+ protected connecting?: Promise<SocketResult>;
36
+ /** Lines being read: a connection that ends waits for them, so an answer that came first is not lost. */
37
+ protected reading: Set<Promise<void>>;
25
38
  protected connectTimeoutMs: number;
26
39
  protected replyTimeoutMs: number;
27
40
  constructor(options: BTPClientOptions);
28
- protected getSocket(): Promise<{
29
- socket: TLSSocket;
30
- error: undefined;
31
- } | {
32
- socket: undefined;
33
- error: BTPErrorException;
34
- }>;
35
- protected attachListeners(socket: TLSSocket, receiverId: string): void;
41
+ /**
42
+ * The open connection, or a new one. A connection the server has ended, or
43
+ * that failed, is never written to again: the next send makes a new one.
44
+ * Sends that arrive while one is being made wait for that one.
45
+ */
46
+ protected getSocket(): Promise<SocketResult>;
47
+ protected isOpen(socket: TLSSocket): boolean;
48
+ /** Connects, trying again `maxRetries` times, `retryDelayMs` apart, when a try fails in a way worth retrying. */
49
+ protected connect(): Promise<SocketResult>;
50
+ protected connectOnce(): Promise<SocketResult>;
51
+ /**
52
+ * A connection's events concern that connection: the sends written to it,
53
+ * and the client's state only while it is the current one. An older
54
+ * connection closing late leaves a newer one alone.
55
+ */
56
+ protected attachListeners(socket: TLSSocket): void;
57
+ /** Answers every send written to `socket` that is still waiting, with `error`. */
58
+ protected failSendsOn(socket: TLSSocket, error: BTPErrorException): void;
36
59
  protected onData(line: string): Promise<void>;
37
- protected pumpNextQueue(): void;
60
+ protected readLine(line: string): Promise<void>;
38
61
  /**
39
62
  * Unref the socket when there are no pending requests to allow process termination
40
63
  */
@@ -43,17 +66,6 @@ export declare class BtpsClient {
43
66
  * Flush the backpressure queue
44
67
  */
45
68
  protected flushBackpressure(): Promise<void>;
46
- /**
47
- * Retry the connection to the server
48
- * @param receiverId - The identity of the receiver
49
- */
50
- protected retryConnect(receiverId: string): void;
51
- /**
52
- * Resolve the error
53
- * @param error - The error to resolve
54
- * @returns The error info
55
- */
56
- protected resolveError(error?: BTPErrorException): void;
57
69
  /**
58
70
  * Cleanup the queue
59
71
  * @param resolveError - The error to resolve
@@ -200,3 +212,4 @@ export declare class BtpsClient {
200
212
  */
201
213
  destroy(): void;
202
214
  }
215
+ export {};
@@ -75,24 +75,39 @@ class BtpsClient {
75
75
  shouldRetry: !0
76
76
  };
77
77
  queue = new Map();
78
+ connecting;
79
+ reading = new Set();
78
80
  connectTimeoutMs;
79
81
  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
- };
82
+ async getSocket() {
83
+ this.socket && this.isOpen(this.socket) && await new Promise((resolve) => setImmediate(resolve));
84
+ const current = this.socket;
85
+ return current && this.isOpen(current) ? { socket: current, error: void 0 } : (current && (this.socket = void 0, current.destroy()), this.connecting ??= this.connect().finally(() => {
86
+ this.connecting = void 0;
87
+ }), this.connecting);
88
+ }
89
+ isOpen(socket) {
90
+ return this.states.isConnected && !socket.destroyed && !socket.writableEnded;
91
+ }
92
+ async connect() {
93
+ for (this.states.isConnecting = !0, this.retries = 0, this.states.shouldRetry = !0; ; ) {
94
+ const result = await this.connectOnce();
95
+ if (result.socket && this.states.isDestroyed)
96
+ return result.socket.destroy(), this.socket = void 0, {
97
+ socket: void 0,
98
+ error: new BTPErrorException({ message: "BtpsClient instance is destroyed" })
99
+ };
100
+ if (result.socket) return result;
101
+ const info = this.getRetryInfo(result.error);
102
+ if (this.emitError({ ...info, error: result.error }), !info.willRetry)
103
+ return this.states.isConnecting = !1, result;
104
+ this.retries++, await new Promise((resolve) => setTimeout(resolve, this.options.retryDelayMs ?? 1e3));
91
105
  }
92
- this.states.isConnecting = !0;
106
+ }
107
+ async connectOnce() {
93
108
  const btpHostDnsConfig = await this.resolveBtpsHostDnsTxt(this.options.to);
94
109
  if (!btpHostDnsConfig)
95
- return this.states.isConnecting = !1, { socket: void 0, error: new BTPErrorException({
110
+ return { socket: void 0, error: new BTPErrorException({
96
111
  message: `DNS resolution failed for ${this.options.to}`
97
112
  }) };
98
113
  const { hostname, port } = btpHostDnsConfig, tlsOptions = {
@@ -101,6 +116,7 @@ class BtpsClient {
101
116
  port
102
117
  };
103
118
  return new Promise((resolve) => {
119
+ let settled = !1;
104
120
  const connectTimer = setTimeout(() => {
105
121
  sock.destroy(
106
122
  new BTPErrorException(BTP_ERROR_SOCKET_TIMEOUT, {
@@ -108,14 +124,21 @@ class BtpsClient {
108
124
  })
109
125
  );
110
126
  }, 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", {
127
+ clearTimeout(connectTimer), settled = !0, this.states.isConnected = !0, this.states.isConnecting = !1, sock.ref(), this.socket = sock, this.emitter.emit("connected", {
112
128
  identity: this.options.to,
113
129
  retries: this.retries,
114
130
  states: this.states,
115
131
  socket: sock
116
132
  }), resolve({ socket: sock, error: void 0 });
117
- });
118
- sock.once("close", () => clearTimeout(connectTimer)), this.attachListeners(sock, this.options.to);
133
+ }), failed = (err) => {
134
+ clearTimeout(connectTimer), !settled && (settled = !0, resolve({ socket: void 0, error: transformToBTPErrorException(err) }));
135
+ };
136
+ sock.once("error", failed), sock.once(
137
+ "close",
138
+ () => failed(
139
+ new BTPErrorException(BTP_ERROR_CONNECTION_CLOSED, { cause: "closed while connecting" })
140
+ )
141
+ ), this.attachListeners(sock);
119
142
  const idleMs = this.options.connectionTimeoutMs;
120
143
  idleMs && sock.setTimeout(idleMs, () => {
121
144
  if (this.queue.size > 0) {
@@ -126,29 +149,41 @@ class BtpsClient {
126
149
  });
127
150
  });
128
151
  }
129
- attachListeners(socket, receiverId) {
130
- socket.pipe(split2()).on("data", (line) => this.onData(line)), socket.on("drain", () => {
152
+ attachListeners(socket) {
153
+ socket.pipe(split2()).on("data", (line) => void this.onData(line)), socket.on("drain", () => {
131
154
  this.flushBackpressure();
132
155
  });
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);
156
+ const over = (error) => {
157
+ this.socket === socket && (this.states.isConnected = !1, this.states.isConnecting = !1, this.backpressureQueue = []), Promise.allSettled([...this.reading]).then(() => this.failSendsOn(socket, error));
136
158
  };
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);
159
+ socket.on("error", (err) => {
160
+ const error = transformToBTPErrorException(err);
161
+ this.socket === socket && this.emitError({ ...this.getRetryInfo(error), error }), over(error);
162
+ }), socket.on("end", () => {
163
+ const error = new BTPErrorException(BTP_ERROR_CONNECTION_ENDED);
164
+ this.socket === socket && this.emitter.emit("end", { ...this.getRetryInfo(), error }), over(error);
144
165
  }), socket.on("close", () => {
145
- const err = new BTPErrorException(BTP_ERROR_CONNECTION_CLOSED, {
166
+ const error = new BTPErrorException(BTP_ERROR_CONNECTION_CLOSED, {
146
167
  cause: "connection closed"
147
- }), info = this.getRetryInfo(err);
148
- this.emitter.emit("end", { ...info, error: err }), this.resolveError(err);
168
+ });
169
+ this.socket === socket && (this.emitter.emit("end", { ...this.getRetryInfo(error), error }), this.socket = void 0), over(error);
149
170
  });
171
+ }
172
+ failSendsOn(socket, error) {
173
+ for (const [id, pending] of this.queue)
174
+ pending.socket === socket && (clearTimeout(pending.timeout), this.queue.delete(id), pending.resolve({ response: void 0, error }));
175
+ this.unrefSocketIfNoQueue();
150
176
  }
151
177
  async onData(line) {
178
+ const read = this.readLine(line);
179
+ this.reading.add(read);
180
+ try {
181
+ await read;
182
+ } finally {
183
+ this.reading.delete(read);
184
+ }
185
+ }
186
+ async readLine(line) {
152
187
  if (line.trim())
153
188
  try {
154
189
  assertStrictJson(line);
@@ -160,23 +195,13 @@ class BtpsClient {
160
195
  this.queue.delete(reqId), clearTimeout(timeout), resolve({
161
196
  response: validSignature ? msg : void 0,
162
197
  error: validSignature ? void 0 : error
163
- }), this.pumpNextQueue();
198
+ }), this.unrefSocketIfNoQueue();
164
199
  } else
165
200
  this.emitter.emit("message", { response: msg, validSignature, error });
166
201
  } catch (e) {
167
202
  const err = new SyntaxError(`Invalid JSON: ${e}`);
168
203
  this.states.shouldRetry = !1, this.emitError({ error: err, ...this.getRetryInfo(err) });
169
204
  }
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
205
  }
181
206
  unrefSocketIfNoQueue() {
182
207
  this.queue.size === 0 && this.socket && !this.socket.destroyed && this.socket.unref();
@@ -194,16 +219,6 @@ class BtpsClient {
194
219
  this.states.isDraining = !1;
195
220
  }
196
221
  }
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
222
  }
208
223
  cleanupQueue(resolveError) {
209
224
  if (this.queue.size !== 0) {
@@ -323,19 +338,18 @@ class BtpsClient {
323
338
  })
324
339
  }), this.unrefSocketIfNoQueue();
325
340
  }, 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;
341
+ this.queue.set(id, { artifact, resolve, timeout });
342
+ const { socket, error } = await this.getSocket(), pending = this.queue.get(id);
343
+ if (pending) {
344
+ if (error) {
345
+ this.queue.delete(id), clearTimeout(timeout), resolve({
346
+ response: void 0,
347
+ error
348
+ }), this.unrefSocketIfNoQueue();
349
+ return;
350
+ }
351
+ socket.ref(), pending.socket = socket, this.sendArtifact(artifact, { resolve, timeout });
337
352
  }
338
- socket?.ref(), socket && this.sendArtifact(artifact, { resolve, timeout });
339
353
  }
340
354
  isNonRetryableError(err) {
341
355
  const message = (err?.message ?? "").toLowerCase();
@@ -14,7 +14,7 @@ import {
14
14
  BTP_TRANSPORTER_DEFAULT_MAX_CONNECTIONS,
15
15
  BTP_TRANSPORTER_ERROR_CONNECTION_ALREADY_EXISTS,
16
16
  BTP_TRANSPORTER_ERROR_MAX_CONNECTIONS_REACHED
17
- } from "./constants.ts/index.js";
17
+ } from "./constants/index.js";
18
18
  import { BtpTransporterArtifactSchema } from "../core/server/schemas/artifacts/transporterSchema.js";
19
19
  import { validate } from "../core/utils/validation.js";
20
20
  import { EventEmitter } from "events";
@@ -8,5 +8,5 @@ export * from './types/index.js';
8
8
  export { BtpsAgent } from './btpsAgent.js';
9
9
  export { BtpsClient } from './btpsClient.js';
10
10
  export { BtpsTransporter } from './btpsTransporter.js';
11
- export * from './constants.ts/index.js';
11
+ export * from './constants/index.js';
12
12
  export { MIN_CONNECT_TIMEOUT_MS, DEFAULT_CONNECT_TIMEOUT_MS, MIN_REPLY_TIMEOUT_MS, DEFAULT_REPLY_TIMEOUT_MS, } from './libs/timeouts.js';
@@ -9,7 +9,7 @@ export * from "./types/index.js";
9
9
  import { BtpsAgent } from "./btpsAgent.js";
10
10
  import { BtpsClient } from "./btpsClient.js";
11
11
  import { BtpsTransporter } from "./btpsTransporter.js";
12
- export * from "./constants.ts/index.js";
12
+ export * from "./constants/index.js";
13
13
  import {
14
14
  MIN_CONNECT_TIMEOUT_MS,
15
15
  DEFAULT_CONNECT_TIMEOUT_MS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@btps/sdk",
3
- "version": "1.1.0",
3
+ "version": "1.1.2",
4
4
  "description": "The reference implementation of BTPS, the Billing Trust Protocol Secure: signed, encrypted, trust-first delivery of invoices and documents between organisations.",
5
5
  "keywords": [
6
6
  "btps",
@@ -74,7 +74,7 @@
74
74
  "clean": "rimraf dist",
75
75
  "build:mjs": "node build/index.mjs",
76
76
  "build:add-license": "bash scripts/add-license-header.sh",
77
- "build:types": "tsc -p tsconfig.build.json && tsc-alias",
77
+ "build:types": "tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json && node build/pruneTypes.mjs",
78
78
  "build": "yarn build:add-license && yarn clean && yarn build:mjs && yarn build:types && yarn build:add-license -dir ./dist",
79
79
  "dev": "nodemon --config nodemon.json",
80
80
  "start": "node ./dist/server/index.js",