@btps/sdk 1.1.2 → 1.2.0-rc.1
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 +475 -0
- package/bin/verify-evidence-bundle.mjs +96 -0
- package/dist/client/btpsAgent.d.ts +10 -1
- package/dist/client/btpsAgent.js +117 -19
- package/dist/client/btpsClient.d.ts +53 -7
- package/dist/client/btpsClient.js +266 -137
- package/dist/client/btpsTransporter.js +2 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.js +3 -1
- package/dist/client/libs/schema.js +92 -15
- package/dist/client/libs/timeouts.d.ts +6 -0
- package/dist/client/libs/timeouts.js +2 -1
- package/dist/client/types/index.d.ts +60 -2
- package/dist/core/authentication/BtpsAuthentication.d.ts +43 -1
- package/dist/core/authentication/BtpsAuthentication.js +152 -36
- package/dist/core/authentication/refreshSuccessor.js +47 -0
- package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +17 -1
- package/dist/core/authentication/storage/InMemoryTokenStore.js +16 -4
- package/dist/core/authentication/types.d.ts +82 -0
- package/dist/core/crypto/contentKey.d.ts +34 -0
- package/dist/core/crypto/contentKey.js +64 -0
- package/dist/core/crypto/decryptVerify.d.ts +7 -1
- package/dist/core/crypto/decryptVerify.js +23 -5
- package/dist/core/crypto/decrypter-interface.d.ts +6 -0
- package/dist/core/crypto/index.d.ts +28 -3
- package/dist/core/crypto/index.js +34 -20
- package/dist/core/crypto/keyResolver.d.ts +48 -0
- package/dist/core/crypto/keyResolver.js +46 -0
- package/dist/core/crypto/pem-decrypter.d.ts +2 -0
- package/dist/core/crypto/pem-decrypter.js +13 -8
- package/dist/core/crypto/signEncrypt.d.ts +4 -1
- package/dist/core/crypto/signEncrypt.js +20 -5
- package/dist/core/crypto/types.d.ts +8 -1
- package/dist/core/delegation/BtpsDelegator.d.ts +4 -0
- package/dist/core/delegation/BtpsDelegator.js +3 -2
- package/dist/core/delegation/verifyTransporterSignature.d.ts +104 -0
- package/dist/core/delegation/verifyTransporterSignature.js +224 -0
- package/dist/core/error/constant.d.ts +41 -0
- package/dist/core/error/constant.js +60 -0
- package/dist/core/server/constants/btps-protocol.d.ts +21 -5
- package/dist/core/server/constants/btps-protocol.js +46 -8
- package/dist/core/server/constants/index.d.ts +7 -3
- package/dist/core/server/constants/index.js +19 -4
- package/dist/core/server/constants/limits.d.ts +41 -1
- package/dist/core/server/constants/limits.js +45 -2
- package/dist/core/server/constants/permissions.d.ts +38 -0
- package/dist/core/server/constants/permissions.js +38 -0
- package/dist/core/server/schemas/artifacts/agentSchema.js +2 -1
- package/dist/core/server/schemas/artifacts/artifacts.js +7 -1
- package/dist/core/server/schemas/artifacts/controlSchema.js +1 -1
- package/dist/core/server/schemas/artifacts/identityLookupSchema.js +10 -1
- package/dist/core/server/schemas/artifacts/transporterSchema.js +92 -12
- package/dist/core/server/schemas/bounded.js +41 -0
- package/dist/core/server/schemas/btpsDocsSchema.d.ts +34522 -1421
- package/dist/core/server/schemas/btpsDocsSchema.js +355 -68
- package/dist/core/server/schemas/helpers.d.ts +9580 -0
- package/dist/core/server/schemas/helpers.js +76 -12
- package/dist/core/server/schemas/keyChainSchema.js +53 -0
- package/dist/core/server/schemas/responseSchema.js +88 -12
- package/dist/core/server/schemas/schema.js +6 -2
- package/dist/core/server/schemas/trustValues.d.ts +105 -0
- package/dist/core/server/schemas/trustValues.js +117 -0
- package/dist/core/server/types.d.ts +104 -6
- package/dist/core/storage/AbstractIdentityStore.d.ts +9 -0
- package/dist/core/storage/JsonIdentityStore.d.ts +3 -0
- package/dist/core/storage/JsonIdentityStore.js +3 -0
- package/dist/core/storage/types.d.ts +2 -0
- package/dist/core/trust/agreements.d.ts +107 -0
- package/dist/core/trust/agreements.js +116 -0
- package/dist/core/trust/evidence.d.ts +220 -0
- package/dist/core/trust/evidence.js +334 -0
- package/dist/core/trust/index.d.ts +10 -0
- package/dist/core/trust/index.js +14 -1
- package/dist/core/trust/keyRotation.d.ts +148 -0
- package/dist/core/trust/keyRotation.js +267 -0
- package/dist/core/trust/permissions.d.ts +114 -0
- package/dist/core/trust/permissions.js +115 -0
- package/dist/core/trust/shaping.d.ts +42 -0
- package/dist/core/trust/shaping.js +47 -0
- package/dist/core/trust/storage/AbstractTrustStore.d.ts +2 -1
- package/dist/core/trust/storage/JsonTrustStore.d.ts +3 -2
- package/dist/core/trust/timestamps.d.ts +49 -0
- package/dist/core/trust/timestamps.js +78 -0
- package/dist/core/trust/trustUtils.d.ts +13 -2
- package/dist/core/trust/trustUtils.js +28 -3
- package/dist/core/trust/types.d.ts +302 -2
- package/dist/core/trust/verification.d.ts +52 -0
- package/dist/core/trust/verification.js +55 -0
- package/dist/server/btpsServer.d.ts +72 -6
- package/dist/server/btpsServer.js +280 -157
- package/dist/server/index.d.ts +3 -0
- package/dist/server/index.js +17 -1
- package/dist/server/libs/agreementOrderCheck.d.ts +29 -0
- package/dist/server/libs/agreementOrderCheck.js +29 -0
- package/dist/server/libs/artifactTimeWindow.d.ts +2 -2
- package/dist/server/libs/artifactTimeWindow.js +2 -1
- package/dist/server/libs/detailsRequestLimit.d.ts +27 -0
- package/dist/server/libs/detailsRequestLimit.js +28 -0
- package/dist/server/libs/detailsResponseCheck.d.ts +27 -0
- package/dist/server/libs/detailsResponseCheck.js +27 -0
- package/dist/server/libs/eventChainCheck.d.ts +31 -0
- package/dist/server/libs/eventChainCheck.js +39 -0
- package/dist/server/libs/inFlightLimit.d.ts +10 -0
- package/dist/server/libs/inFlightLimit.js +7 -1
- package/dist/server/libs/index.d.ts +5 -0
- package/dist/server/libs/index.js +10 -0
- package/dist/server/libs/keyChains.d.ts +14 -0
- package/dist/server/libs/keyChains.js +17 -0
- package/dist/server/libs/wrapForAgent.d.ts +20 -0
- package/dist/server/libs/wrapForAgent.js +36 -0
- package/dist/server/types.d.ts +95 -9
- package/package.json +12 -3
|
@@ -10,7 +10,10 @@ import {
|
|
|
10
10
|
validateTrustRequest,
|
|
11
11
|
computeTrustId,
|
|
12
12
|
computeAgentTrustId,
|
|
13
|
-
validateTrustResponse
|
|
13
|
+
validateTrustResponse,
|
|
14
|
+
documentTypeRefusal,
|
|
15
|
+
detailsNamesRefusal,
|
|
16
|
+
verifyKeyChain
|
|
14
17
|
} from "../core/trust/index.js";
|
|
15
18
|
import tls from "tls";
|
|
16
19
|
import { EventEmitter } from "events";
|
|
@@ -20,15 +23,11 @@ import {
|
|
|
20
23
|
BTP_ERROR_SIG_VERIFICATION,
|
|
21
24
|
BTP_ERROR_INVALID_JSON,
|
|
22
25
|
BTP_ERROR_VALIDATION,
|
|
23
|
-
BTP_ERROR_RESOLVE_PUBKEY,
|
|
24
26
|
BTP_ERROR_TRUST_NOT_ALLOWED,
|
|
25
27
|
BTP_ERROR_TRUST_NON_EXISTENT,
|
|
26
28
|
BTP_ERROR_TRUST_EXPIRED,
|
|
27
29
|
BTP_ERROR_TRUST_REVOKED,
|
|
28
30
|
BTP_ERROR_TRUST_BLOCKED,
|
|
29
|
-
BTP_ERROR_DELEGATION_SIG_VERIFICATION,
|
|
30
|
-
BTP_ERROR_DELEGATION_INVALID,
|
|
31
|
-
BTP_ERROR_ATTESTATION_VERIFICATION,
|
|
32
31
|
BTP_ERROR_SOCKET_TIMEOUT,
|
|
33
32
|
BTP_ERROR_IDENTITY_NOT_FOUND,
|
|
34
33
|
BTP_ERROR_UNKNOWN,
|
|
@@ -38,7 +37,9 @@ import {
|
|
|
38
37
|
BTP_ERROR_AGENT_ID,
|
|
39
38
|
BTP_ERROR_ARTIFACT_NOT_ACCEPTED,
|
|
40
39
|
BTP_ERROR_PRIVACY_TYPE,
|
|
41
|
-
BTP_ERROR_VERSION_UNSUPPORTED
|
|
40
|
+
BTP_ERROR_VERSION_UNSUPPORTED,
|
|
41
|
+
BTP_ERROR_SYNC_NOT_ALLOWED,
|
|
42
|
+
BTP_ERROR_PERMISSION
|
|
42
43
|
} from "../core/error/constant.js";
|
|
43
44
|
import {
|
|
44
45
|
assertStrictJson,
|
|
@@ -49,12 +50,9 @@ import {
|
|
|
49
50
|
} from "../core/crypto/index.js";
|
|
50
51
|
import {
|
|
51
52
|
base64ToPem,
|
|
52
|
-
isDelegationAllowed,
|
|
53
53
|
computeId,
|
|
54
|
-
getHostAndSelector,
|
|
55
54
|
isBtpsIdentityRequest,
|
|
56
55
|
isBtpsTransportArtifact,
|
|
57
|
-
resolvePublicKey,
|
|
58
56
|
isBtpsControlArtifact,
|
|
59
57
|
isBtpsAgentArtifact,
|
|
60
58
|
isValidIdentity
|
|
@@ -66,21 +64,44 @@ import {
|
|
|
66
64
|
IMMEDIATE_ACTIONS,
|
|
67
65
|
MAX_SUPPORTED_VERSION,
|
|
68
66
|
MIN_SUPPORTED_VERSION,
|
|
69
|
-
isSupportedVersion
|
|
67
|
+
isSupportedVersion,
|
|
68
|
+
isVersionBelow,
|
|
69
|
+
DETAILS_ARTIFACT_TYPES
|
|
70
70
|
} from "../core/server/constants/index.js";
|
|
71
71
|
import { validate } from "../core/utils/validation.js";
|
|
72
72
|
import { MiddlewareManager } from "./libs/middlewareManager.js";
|
|
73
|
+
import {
|
|
74
|
+
verifyAttestation,
|
|
75
|
+
verifyDelegation,
|
|
76
|
+
verifyTransporterSignature
|
|
77
|
+
} from "../core/delegation/verifyTransporterSignature.js";
|
|
78
|
+
import { createDefaultKeyResolver } from "../core/crypto/keyResolver.js";
|
|
79
|
+
import { resolveKeyChainMaxCacheSeconds, resolveRetiredKeyGraceSeconds } from "./libs/keyChains.js";
|
|
73
80
|
import { artifactSizeGuard, resolveMaxArtifactSizeKb } from "./libs/artifactSizeGuard.js";
|
|
74
81
|
import {
|
|
75
82
|
artifactTimeWindowError,
|
|
76
83
|
resolveMaxArtifactAgeSeconds
|
|
77
84
|
} from "./libs/artifactTimeWindow.js";
|
|
78
85
|
import { resolveConnectionTimeoutMs } from "./libs/connectionTimeout.js";
|
|
79
|
-
import {
|
|
80
|
-
|
|
86
|
+
import {
|
|
87
|
+
resolveMaxConsecutiveInvalidLines,
|
|
88
|
+
resolveMaxInFlightPerConnection
|
|
89
|
+
} from "./libs/inFlightLimit.js";
|
|
90
|
+
import { BtpArtifactSchemaByType } from "../core/server/schemas/artifacts/artifacts.js";
|
|
81
91
|
import { BtpServerResponseSchema } from "../core/server/schemas/responseSchema.js";
|
|
82
92
|
import { BtpAuthReqDocSchema } from "../core/server/schemas/btpsDocsSchema.js";
|
|
83
93
|
import { keyProofPayload } from "../core/authentication/keyProof.js";
|
|
94
|
+
import * as BTPS_ERROR_CONSTANTS from "../core/error/constant.js";
|
|
95
|
+
const lastRotationTo = (chain) => {
|
|
96
|
+
const to = [...chain].reverse().find(
|
|
97
|
+
(record) => "rotation" in record
|
|
98
|
+
)?.rotation.to;
|
|
99
|
+
return to && { selector: to.selector, publicKey: base64ToPem(to.publicKey) };
|
|
100
|
+
}, BTPS_ERRORS_BY_CODE = new Map(
|
|
101
|
+
Object.values(BTPS_ERROR_CONSTANTS).filter(
|
|
102
|
+
(value) => typeof value == "object" && value !== null && typeof value.code == "string" && typeof value.status == "number"
|
|
103
|
+
).map((constant) => [String(constant.code), constant])
|
|
104
|
+
);
|
|
84
105
|
class BtpsServer {
|
|
85
106
|
tlsOptions;
|
|
86
107
|
serverIdentity;
|
|
@@ -91,7 +112,13 @@ class BtpsServer {
|
|
|
91
112
|
connectionTimeoutMs;
|
|
92
113
|
maxArtifactSizeKb;
|
|
93
114
|
maxInFlightPerConnection;
|
|
115
|
+
maxConsecutiveInvalidLines;
|
|
94
116
|
maxArtifactAgeSeconds;
|
|
117
|
+
signAnswers;
|
|
118
|
+
keyResolver;
|
|
119
|
+
keyChains;
|
|
120
|
+
events = new EventEmitter();
|
|
121
|
+
answersOnSocket = new WeakMap();
|
|
95
122
|
dependencies;
|
|
96
123
|
port;
|
|
97
124
|
server;
|
|
@@ -100,7 +127,26 @@ class BtpsServer {
|
|
|
100
127
|
constructor(options) {
|
|
101
128
|
this.serverIdentity = options.serverIdentity, this.port = options.port ?? 3443, this.onError = options.onError, this.tlsOptions = options.tlsOptions, this.trustStore = options.trustStore, this.identityStore = options.identityStore, this.connectionTimeoutMs = resolveConnectionTimeoutMs(options.connectionTimeoutMs), this.maxArtifactSizeKb = resolveMaxArtifactSizeKb(options.maxArtifactSizeKb), this.maxInFlightPerConnection = resolveMaxInFlightPerConnection(
|
|
102
129
|
options.maxInFlightPerConnection
|
|
103
|
-
), this.
|
|
130
|
+
), this.maxConsecutiveInvalidLines = resolveMaxConsecutiveInvalidLines(
|
|
131
|
+
options.maxConsecutiveInvalidLines
|
|
132
|
+
), this.maxArtifactAgeSeconds = resolveMaxArtifactAgeSeconds(options.maxArtifactAgeSeconds), this.signAnswers = options.signAnswers === !0, this.keyResolver = options.keyResolver;
|
|
133
|
+
const keyChainMaxCacheSeconds = resolveKeyChainMaxCacheSeconds(options.keyChainMaxCacheSeconds), chains = options.keyResolver?.resolveKeyChain ? options.keyResolver : createDefaultKeyResolver({
|
|
134
|
+
from: options.serverIdentity.identity,
|
|
135
|
+
keyChainMaxCacheSeconds
|
|
136
|
+
});
|
|
137
|
+
if (this.keyChains = {
|
|
138
|
+
resolveKeyChain: (identity) => chains.resolveKeyChain?.(identity) ?? Promise.resolve({ status: "unavailable", reason: "no key chain lookup" }),
|
|
139
|
+
retiredKeyGraceSeconds: resolveRetiredKeyGraceSeconds(options.retiredKeyGraceSeconds),
|
|
140
|
+
maxSkewSeconds: this.maxArtifactAgeSeconds,
|
|
141
|
+
|
|
142
|
+
checked: new Map(),
|
|
143
|
+
checkedForSeconds: keyChainMaxCacheSeconds
|
|
144
|
+
}, this.signAnswers && !options.serverIdentity.selector)
|
|
145
|
+
throw new BTPErrorException({
|
|
146
|
+
code: "INVALID_CONFIG",
|
|
147
|
+
message: "signAnswers needs serverIdentity.selector: the selector the key is published under"
|
|
148
|
+
});
|
|
149
|
+
this.middlewareManager = new MiddlewareManager(options.middlewarePath), this.dependencies = {
|
|
104
150
|
trustStore: this.trustStore,
|
|
105
151
|
identityStore: this.identityStore
|
|
106
152
|
}, this.server = tls.createServer(
|
|
@@ -160,14 +206,15 @@ class BtpsServer {
|
|
|
160
206
|
errorReq.error = error, this.handleOnSocketError(error, { req: errorReq, res: resCtx }, "end");
|
|
161
207
|
});
|
|
162
208
|
socket.pipe(sizeGuard);
|
|
163
|
-
const stream = sizeGuard.pipe(split2())
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
209
|
+
const stream = sizeGuard.pipe(split2()), createIdentityRef = () => {
|
|
210
|
+
let toIdentity, fromIdentity;
|
|
211
|
+
return {
|
|
212
|
+
update: (to, from) => {
|
|
213
|
+
toIdentity = to, fromIdentity = from;
|
|
214
|
+
},
|
|
215
|
+
get: () => ({ to: toIdentity, from: fromIdentity })
|
|
216
|
+
};
|
|
217
|
+
}, connectionIdentity = createIdentityRef(), createContexts = (identityRef = connectionIdentity) => {
|
|
171
218
|
const context = {
|
|
172
219
|
socket,
|
|
173
220
|
remoteAddress: ipAddress,
|
|
@@ -185,7 +232,7 @@ class BtpsServer {
|
|
|
185
232
|
sendError: (error, action) => {
|
|
186
233
|
responseSent || (responseSent = !0);
|
|
187
234
|
const reqId = resCtx?.reqId;
|
|
188
|
-
this.sendBtpsError(socket, error, reqId, action);
|
|
235
|
+
this.sendBtpsError(socket, error, reqId, action, !0);
|
|
189
236
|
},
|
|
190
237
|
get responseSent() {
|
|
191
238
|
return responseSent;
|
|
@@ -193,10 +240,10 @@ class BtpsServer {
|
|
|
193
240
|
};
|
|
194
241
|
return { reqCtx, resCtx };
|
|
195
242
|
};
|
|
196
|
-
let inFlight = 0;
|
|
243
|
+
let inFlight = 0, invalidInARow = 0;
|
|
197
244
|
stream.on("data", async (line) => {
|
|
198
245
|
if (!line.trim()) return;
|
|
199
|
-
const { reqCtx: parseReq, resCtx: parseRes } = createContexts();
|
|
246
|
+
const lineIdentity = createIdentityRef(), { reqCtx: parseReq, resCtx: parseRes } = createContexts(lineIdentity);
|
|
200
247
|
parseReq.rawPacket = line, inFlight++, inFlight >= this.maxInFlightPerConnection && stream.pause();
|
|
201
248
|
try {
|
|
202
249
|
const beforeParseMiddleware = this.middlewareManager.getMiddleware("before", "parsing");
|
|
@@ -207,7 +254,9 @@ class BtpsServer {
|
|
|
207
254
|
))
|
|
208
255
|
return;
|
|
209
256
|
const { data, error } = this._parseAndValidateArtifact(line), parseError = error ? error === "VALIDATION" ? BTP_ERROR_VALIDATION : BTP_ERROR_INVALID_JSON : void 0, parseErrException = parseError ? new BTPErrorException(parseError) : void 0;
|
|
210
|
-
|
|
257
|
+
parseRes.reqId = data?.artifact?.id, parseRes.data = data, parseRes.error = parseErrException, parseReq.data = data, parseReq.error = parseErrException;
|
|
258
|
+
const { to, from } = await this.updateIdentityInfo(data, lineIdentity, ipAddress);
|
|
259
|
+
if (connectionIdentity.update(to, from), await this.executeMiddleware(
|
|
211
260
|
this.middlewareManager.getMiddleware("after", "parsing"),
|
|
212
261
|
parseReq,
|
|
213
262
|
parseRes
|
|
@@ -215,9 +264,13 @@ class BtpsServer {
|
|
|
215
264
|
return;
|
|
216
265
|
if (parseError || !data) {
|
|
217
266
|
const errorToSend = parseError ?? BTP_ERROR_INVALID_JSON;
|
|
218
|
-
return this.
|
|
267
|
+
return invalidInARow++, invalidInARow >= this.maxConsecutiveInvalidLines ? this.handleOnSocketError(
|
|
268
|
+
new BTPErrorException(errorToSend),
|
|
269
|
+
{ req: parseReq, res: parseRes },
|
|
270
|
+
"end"
|
|
271
|
+
) : this.sendBtpsError(socket, errorToSend);
|
|
219
272
|
}
|
|
220
|
-
if (!isSupportedVersion(data.artifact.version))
|
|
273
|
+
if (invalidInARow = 0, !isSupportedVersion(data.artifact.version))
|
|
221
274
|
return this.sendBtpsError(
|
|
222
275
|
socket,
|
|
223
276
|
{
|
|
@@ -226,13 +279,15 @@ class BtpsServer {
|
|
|
226
279
|
},
|
|
227
280
|
parseRes.reqId
|
|
228
281
|
);
|
|
282
|
+
if (data.type === "transporter" && data.artifact.syncOf !== void 0)
|
|
283
|
+
return this.sendBtpsError(socket, BTP_ERROR_SYNC_NOT_ALLOWED, parseRes.reqId);
|
|
229
284
|
if (data.type === "control")
|
|
230
|
-
return this.handleControl(data.artifact, {
|
|
285
|
+
return await this.handleControl(data.artifact, {
|
|
231
286
|
req: parseReq,
|
|
232
287
|
res: parseRes
|
|
233
288
|
});
|
|
234
289
|
if (data.type === "identityLookup")
|
|
235
|
-
return this.handleIdentityLookup(data.artifact, {
|
|
290
|
+
return await this.handleIdentityLookup(data.artifact, {
|
|
236
291
|
req: parseReq,
|
|
237
292
|
res: parseRes
|
|
238
293
|
});
|
|
@@ -240,16 +295,16 @@ class BtpsServer {
|
|
|
240
295
|
await this.executeRequestPipeline(reqCtx, resCtx);
|
|
241
296
|
} catch (err) {
|
|
242
297
|
const error = transformToBTPErrorException(err), errorReq = parseReq;
|
|
243
|
-
return errorReq.error = error, console.error("[BtpsServer] Error", error.toJSON()), await this.handleOnSocketError(
|
|
298
|
+
return errorReq.error = error, this.takesErrors() || console.error("[BtpsServer] Error", error.toJSON()), await this.handleOnSocketError(
|
|
244
299
|
error,
|
|
245
300
|
{
|
|
246
301
|
req: errorReq,
|
|
247
302
|
res: parseRes
|
|
248
303
|
},
|
|
249
|
-
"
|
|
304
|
+
"answer"
|
|
250
305
|
);
|
|
251
306
|
} finally {
|
|
252
|
-
inFlight--, stream.isPaused() && !stream.destroyed && stream.resume();
|
|
307
|
+
await this.answersOnSocket.get(socket), inFlight--, stream.isPaused() && !stream.destroyed && stream.resume();
|
|
253
308
|
}
|
|
254
309
|
}), socket.setTimeout(this.connectionTimeoutMs, () => {
|
|
255
310
|
if (inFlight > 0) {
|
|
@@ -306,17 +361,18 @@ class BtpsServer {
|
|
|
306
361
|
}
|
|
307
362
|
}
|
|
308
363
|
async handleIdentityLookup(artifact, context) {
|
|
309
|
-
const { res } = context, { identity, hostSelector, identitySelector } = artifact, identityRecord = await this.identityStore?.getPublicKeyRecord(
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
364
|
+
const { res } = context, { identity, hostSelector, identitySelector } = artifact, id = computeId(identity), keyChain = artifact.keyChain ? await this.identityStore?.getKeyChain?.(id) ?? [] : void 0, identityRecord = await this.identityStore?.getPublicKeyRecord(id, identitySelector), current = keyChain?.length ? verifyKeyChain(keyChain, { identity }).keys.at(-1) ?? lastRotationTo(keyChain) : void 0, restRecord = identityRecord ? (({ createdAt, ...rest }) => rest)(identityRecord) : current && {
|
|
365
|
+
selector: current.selector,
|
|
366
|
+
publicKey: current.publicKey,
|
|
367
|
+
keyType: "rsa",
|
|
368
|
+
version: BTP_PROTOCOL_VERSION
|
|
369
|
+
};
|
|
370
|
+
if (!restRecord) return this.sendBtpsError(res.socket, BTP_ERROR_IDENTITY_NOT_FOUND, res.reqId);
|
|
371
|
+
const document = isVersionBelow(artifact.version, "1.2.0") ? restRecord : { ...restRecord, identity, ...keyChain && { keyChain } }, data = {
|
|
316
372
|
...this.prepareBtpsResponse({ ok: !0, message: "success", code: 200 }, res.reqId),
|
|
317
373
|
type: "btps_response",
|
|
318
374
|
selector: hostSelector,
|
|
319
|
-
document
|
|
375
|
+
document,
|
|
320
376
|
signedBy: this.serverIdentity.identity
|
|
321
377
|
};
|
|
322
378
|
try {
|
|
@@ -384,7 +440,7 @@ class BtpsServer {
|
|
|
384
440
|
const refusal = reqCtx.error, wireError = refusal?.code === BTP_ERROR_TRUST_EXPIRED.code ? BTP_ERROR_TRUST_EXPIRED : refusal && refusal.code === BTP_ERROR_PRIVACY_TYPE.code ? refusal : BTP_ERROR_TRUST_NOT_ALLOWED;
|
|
385
441
|
return this.sendBtpsError(resCtx.socket, wireError, resCtx.reqId);
|
|
386
442
|
}
|
|
387
|
-
await this.executeMiddleware(
|
|
443
|
+
this.tellDetails(data), !(await this.executeMiddleware(
|
|
388
444
|
this.middlewareManager.getMiddleware("before", "onArtifact"),
|
|
389
445
|
reqCtx,
|
|
390
446
|
resCtx
|
|
@@ -392,7 +448,7 @@ class BtpsServer {
|
|
|
392
448
|
this.middlewareManager.getMiddleware("after", "onArtifact"),
|
|
393
449
|
reqCtx,
|
|
394
450
|
resCtx
|
|
395
|
-
)
|
|
451
|
+
)) && this.sendBtpsResponse(resCtx.socket, {
|
|
396
452
|
...this.prepareBtpsResponse({ ok: !0, message: "success", code: 200 }, resCtx.reqId),
|
|
397
453
|
type: "btps_response"
|
|
398
454
|
});
|
|
@@ -491,111 +547,64 @@ class BtpsServer {
|
|
|
491
547
|
if (artifact.action === "auth.request")
|
|
492
548
|
return { isTrusted: !0, error: void 0 };
|
|
493
549
|
const { agentId, to } = artifact, computedTrustId = computeAgentTrustId(agentId, this.deviceOwner(artifact)), trustRecord = await this.trustStore.getById(computedTrustId);
|
|
494
|
-
|
|
495
|
-
isTrusted: !1,
|
|
496
|
-
error: new BTPErrorException(BTP_ERROR_TRUST_NOT_ALLOWED, {
|
|
497
|
-
cause: `Agent ${agentId} not trusted`,
|
|
498
|
-
meta: { agentId, to, computedTrustId }
|
|
499
|
-
})
|
|
500
|
-
};
|
|
501
|
-
}
|
|
502
|
-
async verifyAttestation(delegation) {
|
|
503
|
-
const { attestation, ...restDelegation } = delegation, { signature, ...restAttestation } = attestation, attestorPubKey = await resolvePublicKey(attestation.signedBy, attestation.selector);
|
|
504
|
-
if (!attestorPubKey)
|
|
550
|
+
if (!trustRecord)
|
|
505
551
|
return {
|
|
506
|
-
|
|
507
|
-
error: new BTPErrorException(
|
|
508
|
-
cause: `
|
|
509
|
-
meta: {
|
|
552
|
+
isTrusted: !1,
|
|
553
|
+
error: new BTPErrorException(BTP_ERROR_TRUST_NOT_ALLOWED, {
|
|
554
|
+
cause: `Agent ${agentId} not trusted`,
|
|
555
|
+
meta: { agentId, to, computedTrustId }
|
|
510
556
|
})
|
|
511
557
|
};
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
558
|
+
if (!isTrustActive(trustRecord)) return { isTrusted: !1, error: void 0 };
|
|
559
|
+
const carried = artifact.document;
|
|
560
|
+
return artifact.action === "artifact.send" && carried?.type === "BTPS_DOC" ? this.verifyDocumentSend(carried) : DETAILS_ARTIFACT_TYPES.includes(carried?.type) ? this.verifyDetailsSend(carried) : { isTrusted: !0, error: void 0 };
|
|
561
|
+
}
|
|
562
|
+
async verifyDocumentSend(carried) {
|
|
563
|
+
const record = await this.trustStore.getById(computeTrustId(carried.from, carried.to)), refusal = isTrustActive(record) && record && documentTypeRefusal(carried, record);
|
|
564
|
+
return refusal ? {
|
|
565
|
+
isTrusted: !1,
|
|
566
|
+
error: new BTPErrorException(refusal.error, { cause: refusal.problem })
|
|
567
|
+
} : { isTrusted: !0, error: void 0 };
|
|
568
|
+
}
|
|
569
|
+
async verifyDetailsSend(carried) {
|
|
570
|
+
const { from, to } = carried, records = await Promise.all([
|
|
571
|
+
this.trustStore.getById(computeTrustId(from, to)),
|
|
572
|
+
this.trustStore.getById(computeTrustId(to, from))
|
|
573
|
+
]), active = records.filter(isTrustActive), record = active.find((r) => r?.permissions) ?? active[0];
|
|
574
|
+
if (!record) return { isTrusted: !1, error: this.getTrustRefusalError(records[0]) };
|
|
575
|
+
const refuse = (refusal) => ({
|
|
576
|
+
isTrusted: !1,
|
|
577
|
+
error: new BTPErrorException(refusal.error, { cause: refusal.problem })
|
|
578
|
+
}), { permissions } = record, asReceiver = permissions && {
|
|
579
|
+
permissions: {
|
|
580
|
+
...permissions,
|
|
581
|
+
detailsHeld: permissions.detailsShared,
|
|
582
|
+
detailsShared: permissions.detailsHeld
|
|
583
|
+
}
|
|
584
|
+
}, namesRefusal = detailsNamesRefusal(carried, asReceiver ?? {});
|
|
585
|
+
if (namesRefusal) return refuse(namesRefusal);
|
|
586
|
+
if (carried.type !== "DETAILS_RES") return { isTrusted: !0, error: void 0 };
|
|
587
|
+
const query = { artifactId: carried.relatesTo ?? "", from: to, to: from };
|
|
588
|
+
return await this.trustStore.isKnownArtifact(query) ? { isTrusted: !0, error: void 0 } : refuse({
|
|
589
|
+
error: BTP_ERROR_PERMISSION,
|
|
590
|
+
problem: "a details response answers a request its sender received"
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
async verifyAttestation(delegation) {
|
|
594
|
+
return verifyAttestation(delegation, this.keyResolver, this.keyChains);
|
|
520
595
|
}
|
|
521
596
|
async verifyDelegation(artifactWithDelegation) {
|
|
522
|
-
|
|
523
|
-
if (!isDelegationAllowed(artifactWithDelegation, operator))
|
|
524
|
-
return {
|
|
525
|
-
isValid: !1,
|
|
526
|
-
error: new BTPErrorException(BTP_ERROR_DELEGATION_INVALID, {
|
|
527
|
-
cause: operator ? `Delegation is not allowed: ${artifactWithDelegation.delegation.signedBy} is not the operator of ${artifactWithDelegation.from}'s domain` : `Delegation is not allowed: ${artifactWithDelegation.from}'s domain declares no operator`
|
|
528
|
-
})
|
|
529
|
-
};
|
|
530
|
-
const { delegation, ...restArtifact } = artifactWithDelegation;
|
|
531
|
-
if (delegation.signedBy === artifactWithDelegation.from && !delegation.attestation)
|
|
532
|
-
return {
|
|
533
|
-
isValid: !1,
|
|
534
|
-
error: new BTPErrorException(BTP_ERROR_DELEGATION_INVALID, {
|
|
535
|
-
cause: "Custom managed domain delegation requires attestation. Either provide attestation or directly send without delegation via transporter",
|
|
536
|
-
meta: {
|
|
537
|
-
delegation,
|
|
538
|
-
from: artifactWithDelegation.from
|
|
539
|
-
}
|
|
540
|
-
})
|
|
541
|
-
};
|
|
542
|
-
if (delegation.attestation) {
|
|
543
|
-
if (delegation.attestation.signedBy !== operator)
|
|
544
|
-
return {
|
|
545
|
-
isValid: !1,
|
|
546
|
-
error: new BTPErrorException(BTP_ERROR_ATTESTATION_VERIFICATION, {
|
|
547
|
-
cause: `${delegation.attestation.signedBy} is not the operator of ${artifactWithDelegation.from}'s domain`
|
|
548
|
-
})
|
|
549
|
-
};
|
|
550
|
-
const { isValid: isValid2, error: error2 } = await this.verifyAttestation(
|
|
551
|
-
delegation
|
|
552
|
-
);
|
|
553
|
-
if (!isValid2) return { isValid: isValid2, error: error2 };
|
|
554
|
-
}
|
|
555
|
-
const delegatorPubKey = await resolvePublicKey(delegation.signedBy, delegation.selector);
|
|
556
|
-
if (!delegatorPubKey)
|
|
557
|
-
return {
|
|
558
|
-
isValid: !1,
|
|
559
|
-
error: new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY, {
|
|
560
|
-
cause: `Delegator ${delegation.signedBy} public key not found`,
|
|
561
|
-
meta: { delegation }
|
|
562
|
-
})
|
|
563
|
-
};
|
|
564
|
-
const { signature, attestation, ...restDelegation } = delegation, signedMsg = { ...artifactWithDelegation, delegation: restDelegation }, { isValid: isValidDelegation } = verifySignature(signedMsg, signature, delegatorPubKey);
|
|
565
|
-
if (!isValidDelegation)
|
|
566
|
-
return {
|
|
567
|
-
isValid: isValidDelegation,
|
|
568
|
-
error: new BTPErrorException(BTP_ERROR_DELEGATION_SIG_VERIFICATION, {
|
|
569
|
-
cause: `Delegation signature verification failed of delegator ${delegation.signedBy}`,
|
|
570
|
-
meta: {
|
|
571
|
-
delegation
|
|
572
|
-
}
|
|
573
|
-
})
|
|
574
|
-
};
|
|
575
|
-
const { signature: origSignature, ...origSignedMsg } = restArtifact, { isValid, error } = verifySignature(
|
|
576
|
-
origSignedMsg,
|
|
577
|
-
origSignature,
|
|
578
|
-
delegation.agentPubKey
|
|
579
|
-
);
|
|
580
|
-
return {
|
|
581
|
-
isValid,
|
|
582
|
-
error: error ? new BTPErrorException(BTP_ERROR_DELEGATION_SIG_VERIFICATION, {
|
|
583
|
-
cause: `Delegated artifact's original artifact signature verification failed of agent ${delegation.agentId}`,
|
|
584
|
-
meta: {
|
|
585
|
-
delegation
|
|
586
|
-
}
|
|
587
|
-
}) : void 0
|
|
588
|
-
};
|
|
597
|
+
return verifyDelegation(artifactWithDelegation, this.keyResolver, this.keyChains);
|
|
589
598
|
}
|
|
590
599
|
async verifySignature(data) {
|
|
591
600
|
const { artifact, type } = data;
|
|
592
601
|
if (type === "agent") return this.verifyAgentSignature(artifact);
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
return
|
|
602
|
+
const { isValid, error } = await verifyTransporterSignature(
|
|
603
|
+
artifact,
|
|
604
|
+
this.keyResolver,
|
|
605
|
+
this.keyChains
|
|
606
|
+
);
|
|
607
|
+
return { isValid, error };
|
|
599
608
|
}
|
|
600
609
|
async verifyEventRelation(data) {
|
|
601
610
|
if (data.type !== "transporter" || data.artifact.type !== "BTPS_EVENT")
|
|
@@ -608,15 +617,65 @@ class BtpsServer {
|
|
|
608
617
|
meta: { relatesTo, from, to }
|
|
609
618
|
})
|
|
610
619
|
};
|
|
620
|
+
}
|
|
621
|
+
async verifyDetailsTrust(artifact) {
|
|
622
|
+
const { from, to } = artifact, records = await Promise.all([
|
|
623
|
+
this.trustStore.getById(computeTrustId(from, to)),
|
|
624
|
+
this.trustStore.getById(computeTrustId(to, from))
|
|
625
|
+
]), active = records.filter(isTrustActive), record = active.find((r) => r?.permissions) ?? active[0];
|
|
626
|
+
if (!record) return { isTrusted: !1, error: this.getTrustRefusalError(records[0]) };
|
|
627
|
+
const refuse = (refusal) => ({
|
|
628
|
+
isTrusted: !1,
|
|
629
|
+
error: new BTPErrorException(refusal.error, { cause: refusal.problem })
|
|
630
|
+
}), namesRefusal = detailsNamesRefusal(artifact, record);
|
|
631
|
+
if (namesRefusal) return refuse(namesRefusal);
|
|
632
|
+
if (artifact.type === "DETAILS_RES") {
|
|
633
|
+
const query = { artifactId: artifact.relatesTo ?? "", from: to, to: from };
|
|
634
|
+
if (!await this.trustStore.isKnownArtifact(query))
|
|
635
|
+
return refuse({
|
|
636
|
+
error: BTP_ERROR_PERMISSION,
|
|
637
|
+
problem: "a details response answers a request its receiver sent"
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
return this.verifyPrivacyType(artifact, record);
|
|
641
|
+
}
|
|
642
|
+
tellDetails({ type, artifact }) {
|
|
643
|
+
const at = ( new Date()).toISOString();
|
|
644
|
+
if (type === "transporter" && artifact.type === "DETAILS_REQ") {
|
|
645
|
+
const { from, to, details = [] } = artifact;
|
|
646
|
+
this.tell("detailsRequested", { from, to, names: [...details], at });
|
|
647
|
+
}
|
|
648
|
+
const carried = type === "agent" ? artifact.document : void 0;
|
|
649
|
+
if (carried?.type === "DETAILS_RES") {
|
|
650
|
+
const { from, to, details = [] } = carried;
|
|
651
|
+
this.tell("detailsShared", { from, to, names: [...details], at });
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
tell(event, info) {
|
|
655
|
+
for (const listener of this.events.listeners(event))
|
|
656
|
+
try {
|
|
657
|
+
listener(info);
|
|
658
|
+
} catch (error) {
|
|
659
|
+
console.warn(`[BtpsServer] Warning: a ${event} listener threw:`, error);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
on(event, listener) {
|
|
663
|
+
this.events.on(event, listener);
|
|
664
|
+
}
|
|
665
|
+
off(event, listener) {
|
|
666
|
+
this.events.off(event, listener);
|
|
611
667
|
}
|
|
612
668
|
async verifyTrust(data) {
|
|
613
669
|
const { artifact, type } = data;
|
|
614
670
|
if (type === "agent") return this.verifyAgentTrust(artifact);
|
|
671
|
+
if (DETAILS_ARTIFACT_TYPES.includes(artifact.type))
|
|
672
|
+
return this.verifyDetailsTrust(artifact);
|
|
615
673
|
if (artifact.type === "TRUST_RES") {
|
|
616
674
|
const { isValid, error } = await validateTrustResponse(
|
|
617
675
|
artifact.from,
|
|
618
676
|
artifact.to,
|
|
619
|
-
this.trustStore
|
|
677
|
+
this.trustStore,
|
|
678
|
+
artifact
|
|
620
679
|
);
|
|
621
680
|
return { isTrusted: isValid, error };
|
|
622
681
|
}
|
|
@@ -626,10 +685,17 @@ class BtpsServer {
|
|
|
626
685
|
if (isTrustActive(ownTrust)) return this.verifyPrivacyType(artifact, ownTrust);
|
|
627
686
|
}
|
|
628
687
|
if (artifact.type === "TRUST_REQ") {
|
|
629
|
-
const { isValid, error } = validateTrustRequest(trustRecord);
|
|
688
|
+
const { isValid, error } = validateTrustRequest(trustRecord, artifact);
|
|
630
689
|
return { isTrusted: isValid, error };
|
|
631
|
-
} else
|
|
632
|
-
|
|
690
|
+
} else {
|
|
691
|
+
if (!isTrustActive(trustRecord))
|
|
692
|
+
return { isTrusted: !1, error: this.getTrustRefusalError(trustRecord) };
|
|
693
|
+
const refusal = trustRecord && documentTypeRefusal(artifact, trustRecord);
|
|
694
|
+
return refusal ? {
|
|
695
|
+
isTrusted: !1,
|
|
696
|
+
error: new BTPErrorException(refusal.error, { cause: refusal.problem })
|
|
697
|
+
} : this.verifyPrivacyType(artifact, trustRecord);
|
|
698
|
+
}
|
|
633
699
|
}
|
|
634
700
|
verifyPrivacyType(artifact, trustRecord) {
|
|
635
701
|
const required = trustRecord?.privacyType, sent = artifact.encryption ? "encrypted" : "unencrypted";
|
|
@@ -671,6 +737,9 @@ class BtpsServer {
|
|
|
671
737
|
}
|
|
672
738
|
acceptsArtifacts(type) {
|
|
673
739
|
return this.emitter.listenerCount(type === "agent" ? "agentArtifact" : "transporterArtifact") > 0 || this.handlerFn !== null || this.middlewareManager.getMiddleware("before", "onArtifact").length > 0;
|
|
740
|
+
}
|
|
741
|
+
takesErrors() {
|
|
742
|
+
return this.onError !== void 0 || this.middlewareManager.getMiddleware("before", "onError").length > 0 || this.middlewareManager.getMiddleware("after", "onError").length > 0;
|
|
674
743
|
}
|
|
675
744
|
noHandlerWarning(type) {
|
|
676
745
|
const name = type === "agent" ? "Agent" : "Transporter";
|
|
@@ -699,7 +768,7 @@ class BtpsServer {
|
|
|
699
768
|
let type;
|
|
700
769
|
if (isBtpsControlArtifact(data) ? type = "control" : isBtpsTransportArtifact(data) ? type = "transporter" : isBtpsIdentityRequest(data) ? type = "identityLookup" : isBtpsAgentArtifact(data) && (type = "agent"), !type)
|
|
701
770
|
return { error: "VALIDATION", data };
|
|
702
|
-
if (!validate(
|
|
771
|
+
if (!validate(BtpArtifactSchemaByType[type], data).success)
|
|
703
772
|
return {
|
|
704
773
|
error: "VALIDATION",
|
|
705
774
|
data: type === "agent" ? { artifact: data, type, respondNow: !1 } : { artifact: data, type }
|
|
@@ -738,22 +807,42 @@ class BtpsServer {
|
|
|
738
807
|
this.middlewareManager.getMiddleware("before", "onError"),
|
|
739
808
|
req,
|
|
740
809
|
res
|
|
741
|
-
), this.onError?.(error), this.sendBtpsError(req.socket, error, res.reqId, action), action === "destroy" && !req.socket.destroyed && req.socket.destroy(), await this.executeMiddleware(
|
|
810
|
+
), this.onError?.(error), this.sendBtpsError(req.socket, error, res.reqId, action === "answer" ? void 0 : action), action === "destroy" && !req.socket.destroyed && req.socket.destroy(), await this.executeMiddleware(
|
|
742
811
|
this.middlewareManager.getMiddleware("after", "onError"),
|
|
743
812
|
req,
|
|
744
813
|
res
|
|
745
814
|
);
|
|
746
815
|
}
|
|
747
|
-
wireStatus(error) {
|
|
748
|
-
|
|
816
|
+
wireStatus(error, fromMiddleware = !1) {
|
|
817
|
+
const status = this.errorStatus(error, fromMiddleware), retryAfter = error instanceof BTPErrorException ? error.meta?.retryAfter : void 0;
|
|
818
|
+
return status.code === 429 && typeof retryAfter == "number" && Number.isSafeInteger(retryAfter) && retryAfter >= 0 ? { ...status, retryAfter } : status;
|
|
819
|
+
}
|
|
820
|
+
errorStatus(error, fromMiddleware) {
|
|
821
|
+
if (fromMiddleware && !(error instanceof Error)) {
|
|
822
|
+
if (error.status && typeof error.code == "string")
|
|
823
|
+
return { ok: !1, code: error.status, message: error.message, error: error.code };
|
|
824
|
+
if (typeof error.code == "number")
|
|
825
|
+
return { ok: !1, code: error.code, message: error.message };
|
|
826
|
+
}
|
|
827
|
+
const constant = typeof error.code == "string" ? BTPS_ERRORS_BY_CODE.get(error.code) : void 0;
|
|
828
|
+
if (constant?.status !== void 0) {
|
|
829
|
+
const ownMessage = error.message === constant.message || error.message.startsWith(`${constant.message}: `);
|
|
830
|
+
return {
|
|
831
|
+
ok: !1,
|
|
832
|
+
code: constant.status,
|
|
833
|
+
message: ownMessage ? error.message : constant.message,
|
|
834
|
+
error: String(constant.code)
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
return {
|
|
749
838
|
ok: !1,
|
|
750
839
|
code: BTP_ERROR_UNKNOWN.status ?? 500,
|
|
751
840
|
message: BTP_ERROR_UNKNOWN.message,
|
|
752
841
|
error: String(BTP_ERROR_UNKNOWN.code)
|
|
753
842
|
};
|
|
754
843
|
}
|
|
755
|
-
async sendBtpsError(socket, error, reqId, action) {
|
|
756
|
-
const response = this.prepareBtpsResponse(this.wireStatus(error), reqId);
|
|
844
|
+
async sendBtpsError(socket, error, reqId, action, fromMiddleware = !1) {
|
|
845
|
+
const response = this.prepareBtpsResponse(this.wireStatus(error, fromMiddleware), reqId);
|
|
757
846
|
this.sendBtpsResponse(
|
|
758
847
|
socket,
|
|
759
848
|
{
|
|
@@ -763,25 +852,59 @@ class BtpsServer {
|
|
|
763
852
|
action
|
|
764
853
|
);
|
|
765
854
|
}
|
|
766
|
-
sendBtpsResponse(socket,
|
|
855
|
+
sendBtpsResponse(socket, response, action) {
|
|
767
856
|
if (socket.destroyed || socket.writableEnded || !socket.writable) return;
|
|
768
|
-
const validationResult = validate(BtpServerResponseSchema, artifact);
|
|
857
|
+
const artifact = action && !response.signature && !isVersionBelow(response.version, "1.2.0") ? { ...response, status: { ...response.status, closing: !0 } } : response, validationResult = validate(BtpServerResponseSchema, artifact);
|
|
769
858
|
if (!validationResult.success) {
|
|
770
859
|
const error = new BTPErrorException(BTP_ERROR_VALIDATION, {
|
|
771
860
|
cause: "Invalid server response format",
|
|
772
861
|
meta: { validationErrors: validationResult.error.errors, response: artifact }
|
|
773
862
|
});
|
|
774
|
-
this.onError?.(error),
|
|
863
|
+
if (this.onError?.(error), artifact.type === "btps_error" && artifact.status?.error === BTP_ERROR_UNKNOWN.code) {
|
|
864
|
+
socket.destroyed || socket.destroy();
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
const reqId = typeof artifact.reqId == "string" ? artifact.reqId : void 0;
|
|
868
|
+
this.sendBtpsError(socket, BTP_ERROR_UNKNOWN, reqId, action);
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
if (!this.signAnswers) {
|
|
872
|
+
this.writeAnswer(socket, artifact, action);
|
|
775
873
|
return;
|
|
776
874
|
}
|
|
875
|
+
const answer = (this.answersOnSocket.get(socket) ?? Promise.resolve()).then(async () => {
|
|
876
|
+
if (socket.destroyed || socket.writableEnded) return;
|
|
877
|
+
const signed = artifact.signature ? artifact : await this.signAnswer(artifact);
|
|
878
|
+
this.writeAnswer(socket, signed, action);
|
|
879
|
+
}).catch((err) => this.onError?.(transformToBTPErrorException(err)));
|
|
880
|
+
this.answersOnSocket.set(socket, answer);
|
|
881
|
+
}
|
|
882
|
+
async signAnswer(artifact) {
|
|
883
|
+
const unsigned = {
|
|
884
|
+
...artifact,
|
|
885
|
+
signedBy: this.serverIdentity.identity,
|
|
886
|
+
selector: this.serverIdentity.selector
|
|
887
|
+
};
|
|
777
888
|
try {
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
}
|
|
782
|
-
|
|
783
|
-
|
|
889
|
+
const signature = "signer" in this.serverIdentity ? await signBtpPayloadWithSigner(unsigned, this.serverIdentity.signer) : signBtpPayload(unsigned, {
|
|
890
|
+
publicKey: this.serverIdentity.publicKey,
|
|
891
|
+
privateKey: this.serverIdentity.privateKey
|
|
892
|
+
});
|
|
893
|
+
return { ...unsigned, signature };
|
|
894
|
+
} catch (error) {
|
|
895
|
+
return this.onError?.(transformToBTPErrorException(error)), artifact;
|
|
784
896
|
}
|
|
897
|
+
}
|
|
898
|
+
writeAnswer(socket, artifact, action) {
|
|
899
|
+
if (!(socket.destroyed || socket.writableEnded || !socket.writable))
|
|
900
|
+
try {
|
|
901
|
+
socket.write(JSON.stringify(artifact) + `
|
|
902
|
+
`), this.middlewareManager.onResponseSent(artifact), action && (action === "destroy" ? socket.destroy() : (socket.end(), setTimeout(() => {
|
|
903
|
+
socket.destroyed || socket.destroy();
|
|
904
|
+
}, this.connectionTimeoutMs)));
|
|
905
|
+
} catch (err) {
|
|
906
|
+
this.onError?.(transformToBTPErrorException(err)), socket.destroyed || socket.destroy();
|
|
907
|
+
}
|
|
785
908
|
}
|
|
786
909
|
getProtocolVersion() {
|
|
787
910
|
return BTP_PROTOCOL_VERSION;
|