@btps/sdk 1.1.1 → 1.1.3
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 +77 -0
- package/dist/client/btpsAgent.js +1 -1
- package/dist/client/btpsClient.d.ts +33 -20
- package/dist/client/btpsClient.js +97 -72
- package/dist/client/btpsTransporter.js +2 -1
- package/dist/client/libs/schema.js +17 -5
- package/dist/client/types/index.d.ts +6 -0
- package/dist/core/crypto/index.d.ts +16 -3
- package/dist/core/crypto/index.js +27 -19
- package/dist/core/error/constant.d.ts +2 -0
- package/dist/core/error/constant.js +5 -0
- package/dist/core/server/constants/limits.d.ts +23 -1
- package/dist/core/server/constants/limits.js +26 -1
- package/dist/core/server/schemas/bounded.js +41 -0
- package/dist/core/server/schemas/btpsDocsSchema.d.ts +545 -545
- package/dist/core/server/schemas/btpsDocsSchema.js +56 -27
- package/dist/core/server/schemas/responseSchema.js +37 -4
- package/dist/core/server/schemas/schema.js +3 -1
- package/dist/server/btpsServer.d.ts +2 -1
- package/dist/server/btpsServer.js +17 -14
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,81 @@ 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.3] — 2026-10-30 (alpha)
|
|
8
|
+
|
|
9
|
+
A patch release. Every document a compliant sender sent before is still
|
|
10
|
+
valid; what is new only adds.
|
|
11
|
+
|
|
12
|
+
### Security
|
|
13
|
+
|
|
14
|
+
- **A crafted document can no longer exhaust a receiver's memory**
|
|
15
|
+
(GHSA-mrhx-c7xc-m3w5, in zod 3). zod makes one issue for every invalid
|
|
16
|
+
entry of a list, with no cap, and keeps reading after a `.max()` fails: one
|
|
17
|
+
5 MB document cost 2 GB to check. Every list and record in a document now
|
|
18
|
+
has a protocol limit, far above any real document, and is checked before
|
|
19
|
+
zod reads inside it. Over its limit, a list is refused with one issue; a
|
|
20
|
+
list of more than 100 entries stops at its first invalid entry. Both crafted
|
|
21
|
+
documents now cost one issue and under a megabyte. The limits are on the
|
|
22
|
+
[Limits](https://www.openbtps.org/docs/protocol/specifications/limits) page and
|
|
23
|
+
in `BTPS_FIELD_LIMITS`.
|
|
24
|
+
- **`generateUserToken` draws every character from a secure random source**,
|
|
25
|
+
about 60 bits for a 12-character token, where it had about 32.
|
|
26
|
+
|
|
27
|
+
### Added
|
|
28
|
+
|
|
29
|
+
- `encryptBtpPayload`, `decryptBtpPayload` and
|
|
30
|
+
`decryptBtpPayloadWithDecrypter` take an optional document type. Given one,
|
|
31
|
+
they check the document against it, limits included. Without one they
|
|
32
|
+
behave as before.
|
|
33
|
+
- `BtpsAgent.command` takes `options.id`, a UUID: the artifact is sent under
|
|
34
|
+
it, so a document sent again after a lost answer keeps its id. On
|
|
35
|
+
`event.send` it may only be the event's own id.
|
|
36
|
+
- `trust.fetch` may answer with trust records (`BTPTrustRecord`), which now
|
|
37
|
+
have a schema, as well as with the requests' `TRUST_REQ` artifacts.
|
|
38
|
+
- `BTP_ERROR_TEMPORARILY_UNAVAILABLE` (503), for a trust or identity store to
|
|
39
|
+
throw when it is briefly unreachable, so a sender sends again later.
|
|
40
|
+
|
|
41
|
+
### Fixed
|
|
42
|
+
|
|
43
|
+
- **An error on one artifact no longer ends its connection**, and every other
|
|
44
|
+
artifact in flight on it. The server answers that artifact's error and
|
|
45
|
+
keeps the connection; only framing, socket, size and timeout failures end
|
|
46
|
+
it.
|
|
47
|
+
- **Each artifact on a connection is attributed to its own sender.**
|
|
48
|
+
`getIdentity()` returned the first artifact's sender for every later one,
|
|
49
|
+
in middleware, rate limits and logs.
|
|
50
|
+
- **An identity lookup whose store throws is answered with an error**, where
|
|
51
|
+
it was left unanswered as an unhandled rejection.
|
|
52
|
+
- **A client keeps an identity lookup's answer when the host closes the
|
|
53
|
+
connection first**, as it does right after answering. The lookup failed
|
|
54
|
+
with `BTP_ERROR_CONNECTION_CLOSED` whenever the close arrived while the
|
|
55
|
+
answer was being verified.
|
|
56
|
+
- **A `BtpsTransporter`'s idle connections no longer keep a process alive**
|
|
57
|
+
for up to five minutes after its work is done.
|
|
58
|
+
|
|
59
|
+
## [1.1.2] — 2026-10-19 (alpha)
|
|
60
|
+
|
|
61
|
+
A patch release: the protocol and the API are unchanged.
|
|
62
|
+
|
|
63
|
+
### Fixed
|
|
64
|
+
|
|
65
|
+
- **A client or transporter can keep sending after a server ends the
|
|
66
|
+
connection.** The next send used the ended connection and failed with
|
|
67
|
+
`BTP_ERROR_CONNECTION_CLOSED`. It now makes a new one. A `BtpsTransporter`
|
|
68
|
+
keeping one connection per receiver depends on this.
|
|
69
|
+
- **An answer is not lost when the server ends the connection right after
|
|
70
|
+
writing it**, as a rate limit does. Sends waiting on a connection are failed
|
|
71
|
+
only once the lines already received have been read.
|
|
72
|
+
- **A connection's end fails only the sends written to it.** An older
|
|
73
|
+
connection closing late used to fail the sends waiting on the newer one.
|
|
74
|
+
- **Sends made while the client is connecting each go out once**, on the
|
|
75
|
+
connection being made. Before, they waited for an earlier answer, and one
|
|
76
|
+
could be written twice.
|
|
77
|
+
- **`maxRetries` retries the connection, as documented.** A retry used to
|
|
78
|
+
reconnect without sending what was waiting, which then timed out. Each new
|
|
79
|
+
connection has its own tries, and an error event's `willRetry` says whether
|
|
80
|
+
another follows.
|
|
81
|
+
|
|
7
82
|
## [1.1.1] — 2026-10-19 (alpha)
|
|
8
83
|
|
|
9
84
|
A patch release: the protocol and the API are unchanged.
|
|
@@ -167,5 +242,7 @@ of an exchange must upgrade together.
|
|
|
167
242
|
- The default middleware counts an identity's rate limit after signature
|
|
168
243
|
verification. Rate limiting is off unless a provider enables it.
|
|
169
244
|
|
|
245
|
+
[1.1.3]: https://github.com/openbtps/btps-node/releases/tag/v1.1.3
|
|
246
|
+
[1.1.2]: https://github.com/openbtps/btps-node/releases/tag/v1.1.2
|
|
170
247
|
[1.1.1]: https://github.com/openbtps/btps-node/releases/tag/v1.1.1
|
|
171
248
|
[1.1.0]: https://github.com/openbtps/btps-node/releases/tag/v1.1.0
|
package/dist/client/btpsAgent.js
CHANGED
|
@@ -120,7 +120,7 @@ class BtpsAgent extends BtpsClient {
|
|
|
120
120
|
})
|
|
121
121
|
);
|
|
122
122
|
const transporterArtifact = {
|
|
123
|
-
id: event?.success ? event.data.id : randomUUID(),
|
|
123
|
+
id: event?.success ? event.data.id : options?.id ?? randomUUID(),
|
|
124
124
|
issuedAt: ( new Date()).toISOString(),
|
|
125
125
|
version: this.getProtocolVersion(),
|
|
126
126
|
type: artifactType,
|
|
@@ -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
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
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
|
|
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
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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
|
-
|
|
106
|
+
}
|
|
107
|
+
async connectOnce() {
|
|
93
108
|
const btpHostDnsConfig = await this.resolveBtpsHostDnsTxt(this.options.to);
|
|
94
109
|
if (!btpHostDnsConfig)
|
|
95
|
-
return
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
134
|
-
|
|
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",
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
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
|
|
166
|
+
const error = new BTPErrorException(BTP_ERROR_CONNECTION_CLOSED, {
|
|
146
167
|
cause: "connection closed"
|
|
147
|
-
})
|
|
148
|
-
this.emitter.emit("end", { ...
|
|
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.
|
|
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
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
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();
|
|
@@ -487,16 +501,23 @@ class BtpsClient {
|
|
|
487
501
|
};
|
|
488
502
|
socket.write(JSON.stringify(identityLookupRequest) + `
|
|
489
503
|
`);
|
|
490
|
-
let received = "";
|
|
504
|
+
let received = "", answerRead = !1;
|
|
491
505
|
socket.on("data", async (chunk) => {
|
|
492
506
|
received += chunk.toString();
|
|
493
507
|
const end = received.indexOf(`
|
|
494
508
|
`);
|
|
495
|
-
if (end
|
|
496
|
-
|
|
509
|
+
if (end !== -1) {
|
|
510
|
+
socket.removeAllListeners("data"), answerRead = !0;
|
|
511
|
+
try {
|
|
512
|
+
await verifyAnswer(received.slice(0, end));
|
|
513
|
+
} catch (error) {
|
|
514
|
+
fail(transformToBTPErrorException(error));
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
});
|
|
518
|
+
const verifyAnswer = async (line) => {
|
|
497
519
|
let msg;
|
|
498
520
|
try {
|
|
499
|
-
const line = received.slice(0, end);
|
|
500
521
|
assertStrictJson(line), msg = JSON.parse(line);
|
|
501
522
|
} catch (error) {
|
|
502
523
|
fail(new BTPErrorException(BTP_ERROR_VALIDATION, { cause: error }));
|
|
@@ -567,10 +588,14 @@ class BtpsClient {
|
|
|
567
588
|
},
|
|
568
589
|
error: void 0
|
|
569
590
|
});
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
)
|
|
591
|
+
};
|
|
592
|
+
socket.on("error", (err) => {
|
|
593
|
+
answerRead || fail(transformToBTPErrorException(err));
|
|
594
|
+
}), socket.on("close", () => {
|
|
595
|
+
answerRead || fail(
|
|
596
|
+
new BTPErrorException(BTP_ERROR_CONNECTION_CLOSED, { cause: "connection closed" })
|
|
597
|
+
);
|
|
598
|
+
});
|
|
574
599
|
}) : await this.buildClientErrorResponse(
|
|
575
600
|
new BTPErrorException(BTP_ERROR_IDENTITY_NOT_FOUND, {
|
|
576
601
|
cause: `${identity} has no key in DNS, and its domain declares no operator to answer for it`
|
|
@@ -125,7 +125,7 @@ class BtpsTransporter {
|
|
|
125
125
|
});
|
|
126
126
|
}
|
|
127
127
|
createConnectionTimeout(connectionId, ttlSeconds) {
|
|
128
|
-
|
|
128
|
+
const timeout = setTimeout(
|
|
129
129
|
() => {
|
|
130
130
|
const connection = this.connections.get(connectionId);
|
|
131
131
|
if (connection && connection.inFlight > 0) {
|
|
@@ -136,6 +136,7 @@ class BtpsTransporter {
|
|
|
136
136
|
},
|
|
137
137
|
(ttlSeconds ?? this.connectionTTLSeconds) * 1e3
|
|
138
138
|
);
|
|
139
|
+
return timeout.unref(), timeout;
|
|
139
140
|
}
|
|
140
141
|
touch(connection) {
|
|
141
142
|
clearTimeout(connection.timeout), connection.timeout = this.createConnectionTimeout(connection.id, connection.ttlSeconds), connection.lastUsedAt = ( new Date()).toISOString();
|
|
@@ -37,17 +37,29 @@ const BtpsAgentOptionsSchema = BtpCryptoOptionsSchema.optional(), BtpsAgentComma
|
|
|
37
37
|
actionType: BtpsAgentActionTypeSchema,
|
|
38
38
|
to: identitySchema,
|
|
39
39
|
document: BtpsAgentCommandDocumentSchema.optional(),
|
|
40
|
-
options: BtpCryptoOptionsSchema.extend({
|
|
40
|
+
options: BtpCryptoOptionsSchema.extend({
|
|
41
|
+
relatesTo: z.string().min(1).optional(),
|
|
42
|
+
id: z.string().uuid().optional()
|
|
43
|
+
}).optional()
|
|
41
44
|
}), BtpsAgentCommandCallSchema = BtpsAgentCommandSchema.refine(
|
|
42
45
|
(data) => validateAgentDocument(data.actionType, null, data.document),
|
|
43
46
|
{
|
|
44
47
|
message: "Document is required for this action type or document format is invalid",
|
|
45
48
|
path: ["document"]
|
|
46
49
|
}
|
|
47
|
-
).refine(
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
50
|
+
).refine(
|
|
51
|
+
(data) => data.actionType === "event.send" == (data.options?.relatesTo !== void 0),
|
|
52
|
+
{
|
|
53
|
+
message: "options.relatesTo is required on event.send and only there",
|
|
54
|
+
path: ["options", "relatesTo"]
|
|
55
|
+
}
|
|
56
|
+
).refine(
|
|
57
|
+
(data) => data.actionType !== "event.send" || data.options?.id === void 0 || data.options.id === data.document?.id,
|
|
58
|
+
{
|
|
59
|
+
message: "an event travels under its own id: options.id may only be that id",
|
|
60
|
+
path: ["options", "id"]
|
|
61
|
+
}
|
|
62
|
+
);
|
|
51
63
|
export {
|
|
52
64
|
BtpsAgentCommandCallSchema,
|
|
53
65
|
BtpsAgentCommandDocumentSchema,
|
|
@@ -56,6 +56,12 @@ export type BtpsAgentDoc = BTPDocType | BTPAuthReqDoc | BTPAgentMutation | BTPId
|
|
|
56
56
|
export type BtpsAgentCommandOptions = BTPCryptoOptions & {
|
|
57
57
|
/** Required on `event.send`, refused elsewhere: the id of the `BTPS_DOC` artifact that delivered the invoice. */
|
|
58
58
|
relatesTo?: string;
|
|
59
|
+
/**
|
|
60
|
+
* The id of the artifact the command sends, a UUID. Sending the same document again after a lost answer under
|
|
61
|
+
* the same id lets the receiver keep it once. Without it, a new id. An event always travels under its own id, so
|
|
62
|
+
* on `event.send` it may only be that id.
|
|
63
|
+
*/
|
|
64
|
+
id?: string;
|
|
59
65
|
};
|
|
60
66
|
export type BtpsAgentCommandParams = {
|
|
61
67
|
actionType: AgentAction;
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { BTPCryptoOptions, BTPEncryption, BTPSignature, PemKeys } from './types.js';
|
|
8
8
|
import { BTPErrorException } from '../error/index.js';
|
|
9
|
+
import type { BTPArtifactType } from '../server/types.js';
|
|
9
10
|
import type { Signer } from './signer-interface.js';
|
|
10
11
|
import type { Decrypter } from './decrypter-interface.js';
|
|
11
12
|
export * from './decryptVerify.js';
|
|
@@ -17,7 +18,13 @@ export * from './signer-interface.js';
|
|
|
17
18
|
export * from './decrypter-interface.js';
|
|
18
19
|
export * from './pem-signer.js';
|
|
19
20
|
export * from './pem-decrypter.js';
|
|
20
|
-
|
|
21
|
+
/**
|
|
22
|
+
* Encrypts a document to the receiver's key. Given `documentType`, the
|
|
23
|
+
* document is checked against that type first, and an invalid one throws
|
|
24
|
+
* `BTP_ERROR_VALIDATION`. Without it, nothing is checked: a direct caller
|
|
25
|
+
* validates the document itself. `signEncrypt` and the clients always do.
|
|
26
|
+
*/
|
|
27
|
+
export declare const encryptBtpPayload: (payload: unknown | undefined, receiverPubPem: string, options?: BTPCryptoOptions["encryption"], documentType?: BTPArtifactType) => {
|
|
21
28
|
data: string;
|
|
22
29
|
encryption: {
|
|
23
30
|
algorithm: "aes-256-gcm";
|
|
@@ -27,7 +34,13 @@ export declare const encryptBtpPayload: (payload: unknown | undefined, receiverP
|
|
|
27
34
|
type: import("./types.js").EncryptionMode;
|
|
28
35
|
};
|
|
29
36
|
};
|
|
30
|
-
|
|
37
|
+
/**
|
|
38
|
+
* Decrypts a document with the receiver's key. Given `documentType`, the
|
|
39
|
+
* decrypted document is checked against that type, and an invalid one is
|
|
40
|
+
* returned as a `BTP_ERROR_VALIDATION` error. Without it, nothing is checked:
|
|
41
|
+
* a direct caller validates the document itself. `decryptVerify` always does.
|
|
42
|
+
*/
|
|
43
|
+
export declare const decryptBtpPayload: <T = unknown>(payload: unknown | undefined, encryption: BTPEncryption, receiverPrivPem: string, documentType?: BTPArtifactType) => {
|
|
31
44
|
data?: T;
|
|
32
45
|
error?: BTPErrorException;
|
|
33
46
|
};
|
|
@@ -35,7 +48,7 @@ export declare const decryptBtpPayload: <T = unknown>(payload: unknown | undefin
|
|
|
35
48
|
* Decrypts like `decryptBtpPayload`, through a Decrypter that holds the
|
|
36
49
|
* receiver's private key elsewhere (a KMS, a device) instead of a PEM key.
|
|
37
50
|
*/
|
|
38
|
-
export declare const decryptBtpPayloadWithDecrypter: <T = unknown>(payload: unknown | undefined, encryption: BTPEncryption, decrypter: Decrypter) => Promise<{
|
|
51
|
+
export declare const decryptBtpPayloadWithDecrypter: <T = unknown>(payload: unknown | undefined, encryption: BTPEncryption, decrypter: Decrypter, documentType?: BTPArtifactType) => Promise<{
|
|
39
52
|
data?: T;
|
|
40
53
|
error?: BTPErrorException;
|
|
41
54
|
}>;
|
|
@@ -5,16 +5,17 @@
|
|
|
5
5
|
* https://www.apache.org/licenses/LICENSE-2.0
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import crypto, { constants
|
|
9
|
-
import { performance } from "perf_hooks";
|
|
8
|
+
import crypto, { constants } from "crypto";
|
|
10
9
|
import {
|
|
11
10
|
BTP_ERROR_UNSUPPORTED_ENCRYPT,
|
|
12
11
|
BTP_ERROR_DECRYPTION_UNINTENDED,
|
|
13
12
|
BTP_ERROR_SIG_MISMATCH,
|
|
14
13
|
BTP_ERROR_SIG_VERIFICATION,
|
|
15
|
-
BTP_ERROR_UNKNOWN
|
|
14
|
+
BTP_ERROR_UNKNOWN,
|
|
15
|
+
BTP_ERROR_VALIDATION
|
|
16
16
|
} from "../error/constant.js";
|
|
17
17
|
import { BTPErrorException } from "../error/index.js";
|
|
18
|
+
import { processBtpDocSchema } from "../server/schemas/helpers.js";
|
|
18
19
|
import { assertStrictJson, canonicalize, canonicalizeValue } from "./jcs.js";
|
|
19
20
|
import { assertFullLengthAuthTag } from "./pem-decrypter.js";
|
|
20
21
|
export * from "./decryptVerify.js";
|
|
@@ -26,10 +27,20 @@ export * from "./signer-interface.js";
|
|
|
26
27
|
export * from "./decrypter-interface.js";
|
|
27
28
|
export * from "./pem-signer.js";
|
|
28
29
|
export * from "./pem-decrypter.js";
|
|
29
|
-
const
|
|
30
|
+
const documentTypeError = (document, documentType) => {
|
|
31
|
+
if (!documentType) return;
|
|
32
|
+
const parsed = processBtpDocSchema(documentType)?.safeParse(document);
|
|
33
|
+
if (!(!parsed || parsed.success))
|
|
34
|
+
return new BTPErrorException(BTP_ERROR_VALIDATION, {
|
|
35
|
+
cause: `Document is not a valid ${documentType} document`,
|
|
36
|
+
meta: { issues: parsed.error.issues }
|
|
37
|
+
});
|
|
38
|
+
}, encryptBtpPayload = (payload = "", receiverPubPem, options = {
|
|
30
39
|
algorithm: "aes-256-gcm",
|
|
31
40
|
mode: "standardEncrypt"
|
|
32
|
-
}) => {
|
|
41
|
+
}, documentType) => {
|
|
42
|
+
const invalid = documentTypeError(payload, documentType);
|
|
43
|
+
if (invalid) throw invalid;
|
|
33
44
|
const aesKey = crypto.randomBytes(32), iv = crypto.randomBytes(12), algorithm = options.algorithm, stringifiedPayload = typeof payload != "string" ? JSON.stringify(payload) : payload, cipher = crypto.createCipheriv(algorithm, aesKey, iv);
|
|
34
45
|
let encryptedPayload = cipher.update(stringifiedPayload, "utf8", "base64");
|
|
35
46
|
encryptedPayload += cipher.final("base64");
|
|
@@ -44,7 +55,7 @@ const encryptBtpPayload = (payload = "", receiverPubPem, options = {
|
|
|
44
55
|
type: options.mode
|
|
45
56
|
}
|
|
46
57
|
};
|
|
47
|
-
}, decryptBtpPayload = (payload = "", encryption, receiverPrivPem) => {
|
|
58
|
+
}, decryptBtpPayload = (payload = "", encryption, receiverPrivPem, documentType) => {
|
|
48
59
|
if (encryption.algorithm !== "aes-256-gcm")
|
|
49
60
|
return {
|
|
50
61
|
data: void 0,
|
|
@@ -65,14 +76,13 @@ const encryptBtpPayload = (payload = "", receiverPubPem, options = {
|
|
|
65
76
|
decipher.setAuthTag(authTag);
|
|
66
77
|
const stringifiedPayload = typeof payload != "string" ? JSON.stringify(payload) : payload;
|
|
67
78
|
let decryptedPayload = decipher.update(stringifiedPayload, "base64", "utf8");
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
};
|
|
79
|
+
decryptedPayload += decipher.final("utf8"), assertStrictJson(decryptedPayload);
|
|
80
|
+
const data = JSON.parse(decryptedPayload), invalid = documentTypeError(data, documentType);
|
|
81
|
+
return invalid ? { data: void 0, error: invalid } : { data, error: void 0 };
|
|
72
82
|
} catch (err) {
|
|
73
83
|
return { data: void 0, error: decryptionError(err) };
|
|
74
84
|
}
|
|
75
|
-
}, decryptBtpPayloadWithDecrypter = async (payload = "", encryption, decrypter) => {
|
|
85
|
+
}, decryptBtpPayloadWithDecrypter = async (payload = "", encryption, decrypter, documentType) => {
|
|
76
86
|
if (encryption.algorithm !== "aes-256-gcm")
|
|
77
87
|
return {
|
|
78
88
|
data: void 0,
|
|
@@ -85,10 +95,9 @@ const encryptBtpPayload = (payload = "", receiverPubPem, options = {
|
|
|
85
95
|
ciphertext: Buffer.from(stringifiedPayload, "base64"),
|
|
86
96
|
authTag: Buffer.from(encryption.authTag, "base64")
|
|
87
97
|
}), decryptedPayload = Buffer.from(plaintext).toString("utf8");
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
};
|
|
98
|
+
assertStrictJson(decryptedPayload);
|
|
99
|
+
const data = JSON.parse(decryptedPayload), invalid = documentTypeError(data, documentType);
|
|
100
|
+
return invalid ? { data: void 0, error: invalid } : { data, error: void 0 };
|
|
92
101
|
} catch (err) {
|
|
93
102
|
return { data: void 0, error: decryptionError(err) };
|
|
94
103
|
}
|
|
@@ -189,10 +198,9 @@ const encryptBtpPayload = (payload = "", receiverPubPem, options = {
|
|
|
189
198
|
function generateUserToken(userIdentity, length = 12, charactersFrom = DEFAULT_ALPHABET) {
|
|
190
199
|
if (length < 8 || length > 24)
|
|
191
200
|
throw new BTPErrorException({ message: "Token length must be between 8 and 24 characters." });
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
return Array.from(sliced).map((byte) => charactersFrom[byte % charactersFrom.length]).join("").toUpperCase();
|
|
201
|
+
let token = "";
|
|
202
|
+
for (let i = 0; i < length; i++) token += charactersFrom[crypto.randomInt(charactersFrom.length)];
|
|
203
|
+
return token.toUpperCase();
|
|
196
204
|
}
|
|
197
205
|
export {
|
|
198
206
|
DEFAULT_ALPHABET,
|