@btps/sdk 0.0.0-stage → 1.1.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 +171 -0
- package/LICENSE +190 -0
- package/NOTICE +25 -0
- package/README.md +261 -2
- package/dist/client/btpsAgent.d.ts +20 -0
- package/dist/client/btpsAgent.js +172 -0
- package/dist/client/btpsClient.d.ts +202 -0
- package/dist/client/btpsClient.js +602 -0
- package/dist/client/btpsTransporter.d.ts +52 -0
- package/dist/client/btpsTransporter.js +249 -0
- package/dist/client/constants/index.d.ts +11 -0
- package/dist/client/constants/index.js +20 -0
- package/dist/client/index.d.ts +12 -0
- package/dist/client/index.js +27 -0
- package/dist/client/libs/schema.js +56 -0
- package/dist/client/libs/timeouts.d.ts +22 -0
- package/dist/client/libs/timeouts.js +19 -0
- package/dist/client/types/index.d.ts +155 -0
- package/dist/client/types/index.js +7 -0
- package/dist/core/authentication/BtpsAuthentication.d.ts +128 -0
- package/dist/core/authentication/BtpsAuthentication.js +293 -0
- package/dist/core/authentication/index.d.ts +11 -0
- package/dist/core/authentication/index.js +12 -0
- package/dist/core/authentication/keyProof.d.ts +18 -0
- package/dist/core/authentication/keyProof.js +16 -0
- package/dist/core/authentication/storage/InMemoryAuthSessionStore.d.ts +55 -0
- package/dist/core/authentication/storage/InMemoryAuthSessionStore.js +62 -0
- package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +63 -0
- package/dist/core/authentication/storage/InMemoryTokenStore.js +63 -0
- package/dist/core/authentication/types.d.ts +135 -0
- package/dist/core/authentication/types.js +7 -0
- package/dist/core/crypto/decryptVerify.d.ts +9 -0
- package/dist/core/crypto/decryptVerify.js +45 -0
- package/dist/core/crypto/decrypter-interface.d.ts +25 -0
- package/dist/core/crypto/decrypter-interface.js +7 -0
- package/dist/core/crypto/index.d.ts +77 -0
- package/dist/core/crypto/index.js +210 -0
- package/dist/core/crypto/jcs.d.ts +28 -0
- package/dist/core/crypto/jcs.js +60 -0
- package/dist/core/crypto/keygen.d.ts +9 -0
- package/dist/core/crypto/keygen.js +35 -0
- package/dist/core/crypto/pem-decrypter.d.ts +26 -0
- package/dist/core/crypto/pem-decrypter.js +52 -0
- package/dist/core/crypto/pem-signer.d.ts +21 -0
- package/dist/core/crypto/pem-signer.js +34 -0
- package/dist/core/crypto/signEncrypt.d.ts +34 -0
- package/dist/core/crypto/signEncrypt.js +75 -0
- package/dist/core/crypto/signer-interface.d.ts +22 -0
- package/dist/core/crypto/signer-interface.js +7 -0
- package/dist/core/crypto/types.d.ts +79 -0
- package/dist/core/crypto/types.js +7 -0
- package/dist/core/delegation/BtpsDelegator.d.ts +102 -0
- package/dist/core/delegation/BtpsDelegator.js +118 -0
- package/dist/core/delegation/index.d.ts +7 -0
- package/dist/core/delegation/index.js +8 -0
- package/dist/core/error/constant.d.ts +66 -0
- package/dist/core/error/constant.js +194 -0
- package/dist/core/error/index.d.ts +35 -0
- package/dist/core/error/index.js +52 -0
- package/dist/core/error/types.d.ts +16 -0
- package/dist/core/error/types.js +7 -0
- package/dist/core/server/constants/btps-protocol.d.ts +17 -0
- package/dist/core/server/constants/btps-protocol.js +25 -0
- package/dist/core/server/constants/control.d.ts +7 -0
- package/dist/core/server/constants/control.js +11 -0
- package/dist/core/server/constants/currency.d.ts +7 -0
- package/dist/core/server/constants/currency.js +332 -0
- package/dist/core/server/constants/index.d.ts +26 -0
- package/dist/core/server/constants/index.js +61 -0
- package/dist/core/server/constants/limits.d.ts +50 -0
- package/dist/core/server/constants/limits.js +50 -0
- package/dist/core/server/helpers/BtpsMessageQueue.d.ts +13 -0
- package/dist/core/server/helpers/BtpsMessageQueue.js +12 -0
- package/dist/core/server/helpers/InMemoryQueue.d.ts +16 -0
- package/dist/core/server/helpers/InMemoryQueue.js +35 -0
- package/dist/core/server/helpers/index.d.ts +8 -0
- package/dist/core/server/helpers/index.js +9 -0
- package/dist/core/server/schemas/artifacts/agentSchema.js +51 -0
- package/dist/core/server/schemas/artifacts/artifacts.js +21 -0
- package/dist/core/server/schemas/artifacts/controlSchema.js +18 -0
- package/dist/core/server/schemas/artifacts/identityLookupSchema.js +21 -0
- package/dist/core/server/schemas/artifacts/transporterSchema.js +60 -0
- package/dist/core/server/schemas/btpsDocsSchema.d.ts +4519 -0
- package/dist/core/server/schemas/btpsDocsSchema.js +272 -0
- package/dist/core/server/schemas/helpers.js +87 -0
- package/dist/core/server/schemas/responseSchema.js +86 -0
- package/dist/core/server/schemas/schema.js +70 -0
- package/dist/core/server/schemas/shared.js +18 -0
- package/dist/core/server/types.d.ts +172 -0
- package/dist/core/server/types.js +7 -0
- package/dist/core/storage/AbstractIdentityStore.d.ts +17 -0
- package/dist/core/storage/AbstractIdentityStore.js +13 -0
- package/dist/core/storage/AbstractStorageStore.d.ts +16 -0
- package/dist/core/storage/AbstractStorageStore.js +17 -0
- package/dist/core/storage/JsonIdentityStore.d.ts +29 -0
- package/dist/core/storage/JsonIdentityStore.js +39 -0
- package/dist/core/storage/JsonStorageStore.d.ts +59 -0
- package/dist/core/storage/JsonStorageStore.js +110 -0
- package/dist/core/storage/index.d.ts +11 -0
- package/dist/core/storage/index.js +18 -0
- package/dist/core/storage/types.d.ts +28 -0
- package/dist/core/storage/types.js +7 -0
- package/dist/core/trust/index.d.ts +10 -0
- package/dist/core/trust/index.js +15 -0
- package/dist/core/trust/storage/AbstractTrustStore.d.ts +23 -0
- package/dist/core/trust/storage/AbstractTrustStore.js +13 -0
- package/dist/core/trust/storage/JsonTrustStore.d.ts +33 -0
- package/dist/core/trust/storage/JsonTrustStore.js +42 -0
- package/dist/core/trust/trustUtils.d.ts +78 -0
- package/dist/core/trust/trustUtils.js +41 -0
- package/dist/core/trust/types.d.ts +53 -0
- package/dist/core/trust/types.js +7 -0
- package/dist/core/utils/identity.d.ts +20 -0
- package/dist/core/utils/identity.js +22 -0
- package/dist/core/utils/index.d.ts +70 -0
- package/dist/core/utils/index.js +124 -0
- package/dist/core/utils/types.d.ts +10 -0
- package/dist/core/utils/types.js +7 -0
- package/dist/core/utils/validation.js +13 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +8 -0
- package/dist/server/btpsServer.d.ts +292 -0
- package/dist/server/btpsServer.js +827 -0
- package/dist/server/index.d.ts +11 -0
- package/dist/server/index.js +15 -0
- package/dist/server/libs/abstractRateLimiter.d.ts +10 -0
- package/dist/server/libs/abstractRateLimiter.js +15 -0
- package/dist/server/libs/artifactSizeGuard.d.ts +27 -0
- package/dist/server/libs/artifactSizeGuard.js +44 -0
- package/dist/server/libs/artifactTimeWindow.d.ts +24 -0
- package/dist/server/libs/artifactTimeWindow.js +30 -0
- package/dist/server/libs/btpsFactory.d.ts +29 -0
- package/dist/server/libs/btpsFactory.js +49 -0
- package/dist/server/libs/btpsLightweightFactory.d.ts +35 -0
- package/dist/server/libs/btpsLightweightFactory.js +37 -0
- package/dist/server/libs/btpsRegistry.d.ts +14 -0
- package/dist/server/libs/btpsRegistry.js +16 -0
- package/dist/server/libs/btpsSimpleMetricsTracker.d.ts +13 -0
- package/dist/server/libs/btpsSimpleMetricsTracker.js +21 -0
- package/dist/server/libs/btpsSimpleRateLimiter.d.ts +28 -0
- package/dist/server/libs/btpsSimpleRateLimiter.js +46 -0
- package/dist/server/libs/connectionTimeout.d.ts +16 -0
- package/dist/server/libs/connectionTimeout.js +14 -0
- package/dist/server/libs/defaultMiddleware.d.ts +8 -0
- package/dist/server/libs/defaultMiddleware.js +128 -0
- package/dist/server/libs/inFlightLimit.d.ts +18 -0
- package/dist/server/libs/inFlightLimit.js +17 -0
- package/dist/server/libs/index.d.ts +18 -0
- package/dist/server/libs/index.js +34 -0
- package/dist/server/libs/middlewareManager.js +126 -0
- package/dist/server/libs/type.d.ts +22 -0
- package/dist/server/libs/type.js +7 -0
- package/dist/server/types.d.ts +236 -0
- package/dist/server/types.js +7 -0
- package/package.json +126 -4
|
@@ -0,0 +1,827 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright (c) 2025 Bhupendra Tamang
|
|
4
|
+
* Licensed under the Apache License, Version 2.0
|
|
5
|
+
* https://www.apache.org/licenses/LICENSE-2.0
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {
|
|
9
|
+
isTrustActive,
|
|
10
|
+
validateTrustRequest,
|
|
11
|
+
computeTrustId,
|
|
12
|
+
computeAgentTrustId,
|
|
13
|
+
validateTrustResponse
|
|
14
|
+
} from "../core/trust/index.js";
|
|
15
|
+
import tls from "tls";
|
|
16
|
+
import { EventEmitter } from "events";
|
|
17
|
+
import split2 from "split2";
|
|
18
|
+
import { randomUUID } from "crypto";
|
|
19
|
+
import {
|
|
20
|
+
BTP_ERROR_SIG_VERIFICATION,
|
|
21
|
+
BTP_ERROR_INVALID_JSON,
|
|
22
|
+
BTP_ERROR_VALIDATION,
|
|
23
|
+
BTP_ERROR_RESOLVE_PUBKEY,
|
|
24
|
+
BTP_ERROR_TRUST_NOT_ALLOWED,
|
|
25
|
+
BTP_ERROR_TRUST_NON_EXISTENT,
|
|
26
|
+
BTP_ERROR_TRUST_EXPIRED,
|
|
27
|
+
BTP_ERROR_TRUST_REVOKED,
|
|
28
|
+
BTP_ERROR_TRUST_BLOCKED,
|
|
29
|
+
BTP_ERROR_DELEGATION_SIG_VERIFICATION,
|
|
30
|
+
BTP_ERROR_DELEGATION_INVALID,
|
|
31
|
+
BTP_ERROR_ATTESTATION_VERIFICATION,
|
|
32
|
+
BTP_ERROR_SOCKET_TIMEOUT,
|
|
33
|
+
BTP_ERROR_IDENTITY_NOT_FOUND,
|
|
34
|
+
BTP_ERROR_UNKNOWN,
|
|
35
|
+
BTP_ERROR_INVALID_ACTION,
|
|
36
|
+
BTP_ERROR_EVENT_UNRELATED,
|
|
37
|
+
BTP_ERROR_KEY_ROTATION_PROOF,
|
|
38
|
+
BTP_ERROR_AGENT_ID,
|
|
39
|
+
BTP_ERROR_ARTIFACT_NOT_ACCEPTED,
|
|
40
|
+
BTP_ERROR_PRIVACY_TYPE,
|
|
41
|
+
BTP_ERROR_VERSION_UNSUPPORTED
|
|
42
|
+
} from "../core/error/constant.js";
|
|
43
|
+
import {
|
|
44
|
+
assertStrictJson,
|
|
45
|
+
getFingerprintFromPem,
|
|
46
|
+
signBtpPayload,
|
|
47
|
+
signBtpPayloadWithSigner,
|
|
48
|
+
verifySignature
|
|
49
|
+
} from "../core/crypto/index.js";
|
|
50
|
+
import {
|
|
51
|
+
base64ToPem,
|
|
52
|
+
isDelegationAllowed,
|
|
53
|
+
computeId,
|
|
54
|
+
getHostAndSelector,
|
|
55
|
+
isBtpsIdentityRequest,
|
|
56
|
+
isBtpsTransportArtifact,
|
|
57
|
+
resolvePublicKey,
|
|
58
|
+
isBtpsControlArtifact,
|
|
59
|
+
isBtpsAgentArtifact,
|
|
60
|
+
isValidIdentity
|
|
61
|
+
} from "../core/utils/index.js";
|
|
62
|
+
import { BTPErrorException, transformToBTPErrorException } from "../core/error/index.js";
|
|
63
|
+
import {
|
|
64
|
+
AGENT_TRANSPORTER_ACTIONS,
|
|
65
|
+
BTP_PROTOCOL_VERSION,
|
|
66
|
+
IMMEDIATE_ACTIONS,
|
|
67
|
+
MAX_SUPPORTED_VERSION,
|
|
68
|
+
MIN_SUPPORTED_VERSION,
|
|
69
|
+
isSupportedVersion
|
|
70
|
+
} from "../core/server/constants/index.js";
|
|
71
|
+
import { validate } from "../core/utils/validation.js";
|
|
72
|
+
import { MiddlewareManager } from "./libs/middlewareManager.js";
|
|
73
|
+
import { artifactSizeGuard, resolveMaxArtifactSizeKb } from "./libs/artifactSizeGuard.js";
|
|
74
|
+
import {
|
|
75
|
+
artifactTimeWindowError,
|
|
76
|
+
resolveMaxArtifactAgeSeconds
|
|
77
|
+
} from "./libs/artifactTimeWindow.js";
|
|
78
|
+
import { resolveConnectionTimeoutMs } from "./libs/connectionTimeout.js";
|
|
79
|
+
import { resolveMaxInFlightPerConnection } from "./libs/inFlightLimit.js";
|
|
80
|
+
import { BtpArtifactServerSchema } from "../core/server/schemas/artifacts/artifacts.js";
|
|
81
|
+
import { BtpServerResponseSchema } from "../core/server/schemas/responseSchema.js";
|
|
82
|
+
import { BtpAuthReqDocSchema } from "../core/server/schemas/btpsDocsSchema.js";
|
|
83
|
+
import { keyProofPayload } from "../core/authentication/keyProof.js";
|
|
84
|
+
class BtpsServer {
|
|
85
|
+
tlsOptions;
|
|
86
|
+
serverIdentity;
|
|
87
|
+
onError;
|
|
88
|
+
identityStore;
|
|
89
|
+
trustStore;
|
|
90
|
+
middlewareManager;
|
|
91
|
+
connectionTimeoutMs;
|
|
92
|
+
maxArtifactSizeKb;
|
|
93
|
+
maxInFlightPerConnection;
|
|
94
|
+
maxArtifactAgeSeconds;
|
|
95
|
+
dependencies;
|
|
96
|
+
port;
|
|
97
|
+
server;
|
|
98
|
+
emitter = new EventEmitter();
|
|
99
|
+
handlerFn = null;
|
|
100
|
+
constructor(options) {
|
|
101
|
+
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
|
+
options.maxInFlightPerConnection
|
|
103
|
+
), this.maxArtifactAgeSeconds = resolveMaxArtifactAgeSeconds(options.maxArtifactAgeSeconds), this.middlewareManager = new MiddlewareManager(options.middlewarePath), this.dependencies = {
|
|
104
|
+
trustStore: this.trustStore,
|
|
105
|
+
identityStore: this.identityStore
|
|
106
|
+
}, this.server = tls.createServer(
|
|
107
|
+
{
|
|
108
|
+
...this.tlsOptions
|
|
109
|
+
},
|
|
110
|
+
this.handleConnection.bind(this)
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
async initialize() {
|
|
114
|
+
await this.middlewareManager.loadMiddleware(this.dependencies), await this.middlewareManager.onServerStart();
|
|
115
|
+
}
|
|
116
|
+
async updateIdentityInfo(data, identityRef, remoteAddress) {
|
|
117
|
+
const { update, get } = identityRef, { to: currentTo, from: currentFrom } = get();
|
|
118
|
+
if (isValidIdentity(currentTo) && isValidIdentity(currentFrom))
|
|
119
|
+
return {
|
|
120
|
+
to: currentTo,
|
|
121
|
+
from: currentFrom
|
|
122
|
+
};
|
|
123
|
+
const { type, artifact } = data || {}, updatedTo = currentTo ?? "unknown", updatedFrom = currentFrom ?? remoteAddress;
|
|
124
|
+
if (!artifact)
|
|
125
|
+
return update(updatedTo, updatedFrom), {
|
|
126
|
+
to: updatedTo,
|
|
127
|
+
from: updatedFrom
|
|
128
|
+
};
|
|
129
|
+
if (!type) {
|
|
130
|
+
const fromMaybe = artifact?.from ?? updatedFrom, toMaybe = artifact?.to ?? updatedTo;
|
|
131
|
+
return update(toMaybe, fromMaybe), {
|
|
132
|
+
to: toMaybe,
|
|
133
|
+
from: fromMaybe
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
let to, from;
|
|
137
|
+
switch (type) {
|
|
138
|
+
case "agent":
|
|
139
|
+
to = artifact.to, from = artifact.agentId;
|
|
140
|
+
break;
|
|
141
|
+
case "transporter":
|
|
142
|
+
to = artifact.to, from = artifact.from;
|
|
143
|
+
break;
|
|
144
|
+
case "identityLookup":
|
|
145
|
+
to = artifact.identity, from = artifact.from;
|
|
146
|
+
break;
|
|
147
|
+
case "control":
|
|
148
|
+
to = updatedTo, from = updatedFrom;
|
|
149
|
+
break;
|
|
150
|
+
}
|
|
151
|
+
return update(to, from), {
|
|
152
|
+
to,
|
|
153
|
+
from
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
handleConnection(socket) {
|
|
157
|
+
const ipAddress = socket.remoteAddress ?? "unknown", sizeGuard = artifactSizeGuard(this.maxArtifactSizeKb, (error) => {
|
|
158
|
+
sizeGuard.unpipe(stream), stream.destroy();
|
|
159
|
+
const { reqCtx, resCtx } = createContexts(), errorReq = reqCtx;
|
|
160
|
+
errorReq.error = error, this.handleOnSocketError(error, { req: errorReq, res: resCtx }, "end");
|
|
161
|
+
});
|
|
162
|
+
socket.pipe(sizeGuard);
|
|
163
|
+
const stream = sizeGuard.pipe(split2());
|
|
164
|
+
let fromIdentity, toIdentity;
|
|
165
|
+
const identityRef = {
|
|
166
|
+
update: (to, from) => {
|
|
167
|
+
toIdentity = to, fromIdentity = from;
|
|
168
|
+
},
|
|
169
|
+
get: () => ({ to: toIdentity, from: fromIdentity })
|
|
170
|
+
}, createContexts = () => {
|
|
171
|
+
const context = {
|
|
172
|
+
socket,
|
|
173
|
+
remoteAddress: ipAddress,
|
|
174
|
+
startTime: ( new Date()).toISOString()
|
|
175
|
+
};
|
|
176
|
+
let responseSent = !1;
|
|
177
|
+
const reqCtx = {
|
|
178
|
+
...context,
|
|
179
|
+
getIdentity: identityRef.get
|
|
180
|
+
}, resCtx = {
|
|
181
|
+
...context,
|
|
182
|
+
sendRes: (response) => {
|
|
183
|
+
responseSent || (responseSent = !0), response.reqId = resCtx?.reqId, this.sendBtpsResponse(socket, response);
|
|
184
|
+
},
|
|
185
|
+
sendError: (error, action) => {
|
|
186
|
+
responseSent || (responseSent = !0);
|
|
187
|
+
const reqId = resCtx?.reqId;
|
|
188
|
+
this.sendBtpsError(socket, error, reqId, action);
|
|
189
|
+
},
|
|
190
|
+
get responseSent() {
|
|
191
|
+
return responseSent;
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
return { reqCtx, resCtx };
|
|
195
|
+
};
|
|
196
|
+
let inFlight = 0;
|
|
197
|
+
stream.on("data", async (line) => {
|
|
198
|
+
if (!line.trim()) return;
|
|
199
|
+
const { reqCtx: parseReq, resCtx: parseRes } = createContexts();
|
|
200
|
+
parseReq.rawPacket = line, inFlight++, inFlight >= this.maxInFlightPerConnection && stream.pause();
|
|
201
|
+
try {
|
|
202
|
+
const beforeParseMiddleware = this.middlewareManager.getMiddleware("before", "parsing");
|
|
203
|
+
if (await this.executeMiddleware(
|
|
204
|
+
beforeParseMiddleware,
|
|
205
|
+
parseReq,
|
|
206
|
+
parseRes
|
|
207
|
+
))
|
|
208
|
+
return;
|
|
209
|
+
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
|
+
if (parseRes.reqId = data?.artifact?.id, parseRes.data = data, parseRes.error = parseErrException, parseReq.data = data, parseReq.error = parseErrException, parseReq.getIdentity = identityRef.get, await this.updateIdentityInfo(data, identityRef, ipAddress), await this.executeMiddleware(
|
|
211
|
+
this.middlewareManager.getMiddleware("after", "parsing"),
|
|
212
|
+
parseReq,
|
|
213
|
+
parseRes
|
|
214
|
+
))
|
|
215
|
+
return;
|
|
216
|
+
if (parseError || !data) {
|
|
217
|
+
const errorToSend = parseError ?? BTP_ERROR_INVALID_JSON;
|
|
218
|
+
return this.sendBtpsError(socket, errorToSend);
|
|
219
|
+
}
|
|
220
|
+
if (!isSupportedVersion(data.artifact.version))
|
|
221
|
+
return this.sendBtpsError(
|
|
222
|
+
socket,
|
|
223
|
+
{
|
|
224
|
+
...BTP_ERROR_VERSION_UNSUPPORTED,
|
|
225
|
+
message: `${BTP_ERROR_VERSION_UNSUPPORTED.message}: supports ${MIN_SUPPORTED_VERSION} to ${MAX_SUPPORTED_VERSION}`
|
|
226
|
+
},
|
|
227
|
+
parseRes.reqId
|
|
228
|
+
);
|
|
229
|
+
if (data.type === "control")
|
|
230
|
+
return this.handleControl(data.artifact, {
|
|
231
|
+
req: parseReq,
|
|
232
|
+
res: parseRes
|
|
233
|
+
});
|
|
234
|
+
if (data.type === "identityLookup")
|
|
235
|
+
return this.handleIdentityLookup(data.artifact, {
|
|
236
|
+
req: parseReq,
|
|
237
|
+
res: parseRes
|
|
238
|
+
});
|
|
239
|
+
const reqCtx = parseReq, resCtx = parseRes;
|
|
240
|
+
await this.executeRequestPipeline(reqCtx, resCtx);
|
|
241
|
+
} catch (err) {
|
|
242
|
+
const error = transformToBTPErrorException(err), errorReq = parseReq;
|
|
243
|
+
return errorReq.error = error, console.error("[BtpsServer] Error", error.toJSON()), await this.handleOnSocketError(
|
|
244
|
+
error,
|
|
245
|
+
{
|
|
246
|
+
req: errorReq,
|
|
247
|
+
res: parseRes
|
|
248
|
+
},
|
|
249
|
+
"end"
|
|
250
|
+
);
|
|
251
|
+
} finally {
|
|
252
|
+
inFlight--, stream.isPaused() && !stream.destroyed && stream.resume();
|
|
253
|
+
}
|
|
254
|
+
}), socket.setTimeout(this.connectionTimeoutMs, () => {
|
|
255
|
+
if (inFlight > 0) {
|
|
256
|
+
socket.setTimeout(this.connectionTimeoutMs);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
const timeoutError = new BTPErrorException(BTP_ERROR_SOCKET_TIMEOUT, {
|
|
260
|
+
cause: `Connection timeout after ${this.connectionTimeoutMs}ms`,
|
|
261
|
+
meta: { remoteAddress: socket.remoteAddress, timeoutMs: this.connectionTimeoutMs }
|
|
262
|
+
}), { reqCtx, resCtx } = createContexts(), errorReq = reqCtx;
|
|
263
|
+
errorReq.error = timeoutError, this.handleOnSocketError(
|
|
264
|
+
timeoutError,
|
|
265
|
+
{
|
|
266
|
+
req: errorReq,
|
|
267
|
+
res: resCtx
|
|
268
|
+
},
|
|
269
|
+
"end"
|
|
270
|
+
);
|
|
271
|
+
});
|
|
272
|
+
const handleError = (err) => {
|
|
273
|
+
const error = transformToBTPErrorException(err), { reqCtx, resCtx } = createContexts(), errorReq = reqCtx;
|
|
274
|
+
errorReq.error = error, this.handleOnSocketError(error, {
|
|
275
|
+
req: errorReq,
|
|
276
|
+
res: resCtx
|
|
277
|
+
});
|
|
278
|
+
};
|
|
279
|
+
socket.on("error", handleError), sizeGuard.on("error", handleError), stream.on("error", handleError), socket.on("close", () => {
|
|
280
|
+
socket.off("error", handleError), sizeGuard.off("error", handleError), typeof stream.off == "function" && stream.off("error", handleError);
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
async handleControl(artifact, context) {
|
|
284
|
+
const { res } = context, { action } = artifact;
|
|
285
|
+
switch (action) {
|
|
286
|
+
case "QUIT":
|
|
287
|
+
return this.sendBtpsResponse(
|
|
288
|
+
res.socket,
|
|
289
|
+
{
|
|
290
|
+
...this.prepareBtpsResponse({ ok: !0, message: "bye", code: 200 }, res.reqId),
|
|
291
|
+
type: "btps_response"
|
|
292
|
+
},
|
|
293
|
+
"end"
|
|
294
|
+
);
|
|
295
|
+
|
|
296
|
+
case "PING":
|
|
297
|
+
return this.sendBtpsResponse(res.socket, {
|
|
298
|
+
...this.prepareBtpsResponse(
|
|
299
|
+
{ ok: !0, message: "Server is operational", code: 200 },
|
|
300
|
+
res.reqId
|
|
301
|
+
),
|
|
302
|
+
type: "btps_response"
|
|
303
|
+
});
|
|
304
|
+
default:
|
|
305
|
+
return this.sendBtpsError(res.socket, BTP_ERROR_INVALID_ACTION, res.reqId, "end");
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
async handleIdentityLookup(artifact, context) {
|
|
309
|
+
const { res } = context, { identity, hostSelector, identitySelector } = artifact, identityRecord = await this.identityStore?.getPublicKeyRecord(
|
|
310
|
+
computeId(identity),
|
|
311
|
+
identitySelector
|
|
312
|
+
);
|
|
313
|
+
if (!identityRecord)
|
|
314
|
+
return this.sendBtpsError(res.socket, BTP_ERROR_IDENTITY_NOT_FOUND, res.reqId);
|
|
315
|
+
const { createdAt, ...restRecord } = identityRecord, data = {
|
|
316
|
+
...this.prepareBtpsResponse({ ok: !0, message: "success", code: 200 }, res.reqId),
|
|
317
|
+
type: "btps_response",
|
|
318
|
+
selector: hostSelector,
|
|
319
|
+
document: restRecord,
|
|
320
|
+
signedBy: this.serverIdentity.identity
|
|
321
|
+
};
|
|
322
|
+
try {
|
|
323
|
+
const signature = "signer" in this.serverIdentity ? await signBtpPayloadWithSigner(data, this.serverIdentity.signer) : signBtpPayload(data, {
|
|
324
|
+
publicKey: this.serverIdentity.publicKey,
|
|
325
|
+
privateKey: this.serverIdentity.privateKey
|
|
326
|
+
});
|
|
327
|
+
this.sendBtpsResponse(
|
|
328
|
+
res.socket,
|
|
329
|
+
{
|
|
330
|
+
...data,
|
|
331
|
+
signature
|
|
332
|
+
},
|
|
333
|
+
"end"
|
|
334
|
+
);
|
|
335
|
+
} catch (error) {
|
|
336
|
+
const err = transformToBTPErrorException(error), newErr = new BTPErrorException(BTP_ERROR_UNKNOWN, {
|
|
337
|
+
cause: err,
|
|
338
|
+
meta: data
|
|
339
|
+
}), errorReq = context.req;
|
|
340
|
+
return errorReq.error = newErr, this.handleOnSocketError(
|
|
341
|
+
newErr,
|
|
342
|
+
{
|
|
343
|
+
req: errorReq,
|
|
344
|
+
res: context.res
|
|
345
|
+
},
|
|
346
|
+
"end"
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
async executeRequestPipeline(reqCtx, resCtx) {
|
|
351
|
+
if (await this.executeMiddleware(
|
|
352
|
+
this.middlewareManager.getMiddleware("before", "signatureVerification"),
|
|
353
|
+
reqCtx,
|
|
354
|
+
resCtx
|
|
355
|
+
)) return;
|
|
356
|
+
const { data } = reqCtx, { isValid, error: verificationError } = await this.verifySignature(data);
|
|
357
|
+
if (reqCtx.isValid = isValid, verificationError && (reqCtx.error = verificationError), await this.executeMiddleware(
|
|
358
|
+
this.middlewareManager.getMiddleware("after", "signatureVerification"),
|
|
359
|
+
reqCtx,
|
|
360
|
+
resCtx
|
|
361
|
+
)) return;
|
|
362
|
+
if (!isValid) {
|
|
363
|
+
const wireError = verificationError?.status ? verificationError : BTP_ERROR_SIG_VERIFICATION;
|
|
364
|
+
return this.sendBtpsError(resCtx.socket, wireError, resCtx.reqId);
|
|
365
|
+
}
|
|
366
|
+
const timeWindowError = artifactTimeWindowError(
|
|
367
|
+
data.artifact.issuedAt,
|
|
368
|
+
this.maxArtifactAgeSeconds
|
|
369
|
+
);
|
|
370
|
+
if (timeWindowError)
|
|
371
|
+
return reqCtx.error = timeWindowError, this.sendBtpsError(resCtx.socket, timeWindowError, resCtx.reqId);
|
|
372
|
+
if (await this.executeMiddleware(
|
|
373
|
+
this.middlewareManager.getMiddleware("before", "trustVerification"),
|
|
374
|
+
reqCtx,
|
|
375
|
+
resCtx
|
|
376
|
+
)) return;
|
|
377
|
+
const trust = await this.verifyTrust(data), { isTrusted, error: trustError } = trust.isTrusted ? await this.verifyEventRelation(data) : trust;
|
|
378
|
+
if (reqCtx.isTrusted = isTrusted, trustError && (reqCtx.error = trustError), await this.executeMiddleware(
|
|
379
|
+
this.middlewareManager.getMiddleware("after", "trustVerification"),
|
|
380
|
+
reqCtx,
|
|
381
|
+
resCtx
|
|
382
|
+
)) return;
|
|
383
|
+
if (!isTrusted) {
|
|
384
|
+
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
|
+
return this.sendBtpsError(resCtx.socket, wireError, resCtx.reqId);
|
|
386
|
+
}
|
|
387
|
+
await this.executeMiddleware(
|
|
388
|
+
this.middlewareManager.getMiddleware("before", "onArtifact"),
|
|
389
|
+
reqCtx,
|
|
390
|
+
resCtx
|
|
391
|
+
) || await this.processMessage(data, resCtx, reqCtx) || await this.executeMiddleware(
|
|
392
|
+
this.middlewareManager.getMiddleware("after", "onArtifact"),
|
|
393
|
+
reqCtx,
|
|
394
|
+
resCtx
|
|
395
|
+
) || this.sendBtpsResponse(resCtx.socket, {
|
|
396
|
+
...this.prepareBtpsResponse({ ok: !0, message: "success", code: 200 }, resCtx.reqId),
|
|
397
|
+
type: "btps_response"
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
isResponseSent(resCtx) {
|
|
401
|
+
const { socket, responseSent } = resCtx;
|
|
402
|
+
return socket.destroyed || socket.writableEnded || responseSent;
|
|
403
|
+
}
|
|
404
|
+
async executeMiddleware(middleware, req, res) {
|
|
405
|
+
for (const mw of middleware) {
|
|
406
|
+
if (this.isResponseSent(res)) return !0;
|
|
407
|
+
const context = {
|
|
408
|
+
dependencies: this.dependencies,
|
|
409
|
+
config: mw.config?.options ?? {},
|
|
410
|
+
serverInstance: this,
|
|
411
|
+
currentTime: ( new Date()).toISOString()
|
|
412
|
+
}, typedHandler = mw.handler;
|
|
413
|
+
if (await typedHandler(req, res, () => Promise.resolve(), context), this.isResponseSent(res)) return !0;
|
|
414
|
+
}
|
|
415
|
+
return !1;
|
|
416
|
+
}
|
|
417
|
+
async verifyAgentSignature(artifact) {
|
|
418
|
+
const { signature, ...signedMsg } = artifact;
|
|
419
|
+
if (artifact.action !== "auth.request" && isValidIdentity(artifact.agentId))
|
|
420
|
+
return {
|
|
421
|
+
isValid: !1,
|
|
422
|
+
error: new BTPErrorException(BTP_ERROR_AGENT_ID, {
|
|
423
|
+
cause: `${artifact.agentId} is an identity, not an agent id`,
|
|
424
|
+
meta: { agentId: artifact.agentId, action: artifact.action }
|
|
425
|
+
})
|
|
426
|
+
};
|
|
427
|
+
const agentPublicPem = await this.getAgentPublicKey(artifact);
|
|
428
|
+
if (!agentPublicPem) {
|
|
429
|
+
const isOnboardingAgent = artifact.action === "auth.request", errorMessage = isOnboardingAgent ? `Agent ${signedMsg.agentId} public key not found in auth request document` : `Agent ${signedMsg.agentId} not trusted or not found in trust store`;
|
|
430
|
+
return {
|
|
431
|
+
isValid: !1,
|
|
432
|
+
error: new BTPErrorException(BTP_ERROR_SIG_VERIFICATION, {
|
|
433
|
+
cause: errorMessage,
|
|
434
|
+
meta: {
|
|
435
|
+
agentId: signedMsg.agentId,
|
|
436
|
+
action: artifact.action,
|
|
437
|
+
isOnboardingAgent
|
|
438
|
+
}
|
|
439
|
+
})
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
const { isValid, error } = verifySignature(signedMsg, signature, agentPublicPem);
|
|
443
|
+
return isValid ? artifact.action !== "auth.refresh" ? { isValid, error } : this.verifyKeyProof(artifact, agentPublicPem) : {
|
|
444
|
+
isValid,
|
|
445
|
+
error: new BTPErrorException(BTP_ERROR_SIG_VERIFICATION, {
|
|
446
|
+
cause: error,
|
|
447
|
+
meta: { agentId: signedMsg.agentId, action: artifact.action }
|
|
448
|
+
})
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
verifyKeyProof(artifact, currentPublicPem) {
|
|
452
|
+
const refuse = (cause) => ({
|
|
453
|
+
isValid: !1,
|
|
454
|
+
error: new BTPErrorException(BTP_ERROR_KEY_ROTATION_PROOF, {
|
|
455
|
+
cause,
|
|
456
|
+
meta: { agentId: artifact.agentId }
|
|
457
|
+
})
|
|
458
|
+
}), parsed = BtpAuthReqDocSchema.safeParse(artifact.document);
|
|
459
|
+
if (!parsed.success) return refuse("auth.refresh has no valid document");
|
|
460
|
+
const { identity, publicKey, keyProof } = parsed.data;
|
|
461
|
+
try {
|
|
462
|
+
if (getFingerprintFromPem(publicKey) === getFingerprintFromPem(currentPublicPem))
|
|
463
|
+
return { isValid: !0, error: void 0 };
|
|
464
|
+
} catch {
|
|
465
|
+
return refuse("the new key is not a public key");
|
|
466
|
+
}
|
|
467
|
+
return keyProof ? verifySignature(
|
|
468
|
+
keyProofPayload(artifact.agentId, identity, publicKey),
|
|
469
|
+
keyProof,
|
|
470
|
+
publicKey
|
|
471
|
+
).isValid ? { isValid: !0, error: void 0 } : refuse("the keyProof does not verify") : refuse("a new key without a keyProof");
|
|
472
|
+
}
|
|
473
|
+
deviceOwner(artifact) {
|
|
474
|
+
return artifact.action in AGENT_TRANSPORTER_ACTIONS ? artifact.document.from : artifact.to;
|
|
475
|
+
}
|
|
476
|
+
async getAgentPublicKey(artifact) {
|
|
477
|
+
if (artifact.action === "auth.request")
|
|
478
|
+
return artifact.document?.publicKey || null;
|
|
479
|
+
const computedTrustId = computeAgentTrustId(artifact.agentId, this.deviceOwner(artifact)), trustRecord = await this.trustStore.getById(computedTrustId);
|
|
480
|
+
if (!trustRecord || trustRecord.senderId !== artifact.agentId)
|
|
481
|
+
return null;
|
|
482
|
+
const { document } = artifact;
|
|
483
|
+
if (document)
|
|
484
|
+
if (artifact.action === "auth.refresh") {
|
|
485
|
+
if (!document?.publicKey) return null;
|
|
486
|
+
} else
|
|
487
|
+
return base64ToPem(trustRecord.publicKeyBase64);
|
|
488
|
+
return base64ToPem(trustRecord.publicKeyBase64);
|
|
489
|
+
}
|
|
490
|
+
async verifyAgentTrust(artifact) {
|
|
491
|
+
if (artifact.action === "auth.request")
|
|
492
|
+
return { isTrusted: !0, error: void 0 };
|
|
493
|
+
const { agentId, to } = artifact, computedTrustId = computeAgentTrustId(agentId, this.deviceOwner(artifact)), trustRecord = await this.trustStore.getById(computedTrustId);
|
|
494
|
+
return trustRecord ? { isTrusted: isTrustActive(trustRecord), error: void 0 } : {
|
|
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)
|
|
505
|
+
return {
|
|
506
|
+
isValid: !1,
|
|
507
|
+
error: new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY, {
|
|
508
|
+
cause: `Attestor ${attestation.signedBy} public key not found`,
|
|
509
|
+
meta: { attestation }
|
|
510
|
+
})
|
|
511
|
+
};
|
|
512
|
+
const signedMsg = { ...restDelegation, attestation: restAttestation }, { isValid, error } = verifySignature(signedMsg, signature, attestorPubKey);
|
|
513
|
+
return {
|
|
514
|
+
isValid,
|
|
515
|
+
error: error ? new BTPErrorException(BTP_ERROR_ATTESTATION_VERIFICATION, {
|
|
516
|
+
cause: `Attestation signature verification failed of attestor ${attestation.signedBy}`,
|
|
517
|
+
meta: { attestation }
|
|
518
|
+
}) : void 0
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
async verifyDelegation(artifactWithDelegation) {
|
|
522
|
+
const operator = (await getHostAndSelector(artifactWithDelegation.from))?.operator;
|
|
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
|
+
};
|
|
589
|
+
}
|
|
590
|
+
async verifySignature(data) {
|
|
591
|
+
const { artifact, type } = data;
|
|
592
|
+
if (type === "agent") return this.verifyAgentSignature(artifact);
|
|
593
|
+
if (artifact.delegation)
|
|
594
|
+
return this.verifyDelegation(
|
|
595
|
+
artifact
|
|
596
|
+
);
|
|
597
|
+
const { signature, ...signedMsg } = artifact, publicKey = await resolvePublicKey(artifact.from, artifact.selector);
|
|
598
|
+
return publicKey ? verifySignature(signedMsg, signature, publicKey) : { isValid: !1, error: new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY) };
|
|
599
|
+
}
|
|
600
|
+
async verifyEventRelation(data) {
|
|
601
|
+
if (data.type !== "transporter" || data.artifact.type !== "BTPS_EVENT")
|
|
602
|
+
return { isTrusted: !0, error: void 0 };
|
|
603
|
+
const { relatesTo, from, to } = data.artifact;
|
|
604
|
+
return relatesTo !== void 0 && await this.trustStore.isKnownArtifact({ artifactId: relatesTo, from, to }) ? { isTrusted: !0, error: void 0 } : {
|
|
605
|
+
isTrusted: !1,
|
|
606
|
+
error: new BTPErrorException(BTP_ERROR_EVENT_UNRELATED, {
|
|
607
|
+
cause: `no artifact ${relatesTo} between ${from} and ${to}`,
|
|
608
|
+
meta: { relatesTo, from, to }
|
|
609
|
+
})
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
async verifyTrust(data) {
|
|
613
|
+
const { artifact, type } = data;
|
|
614
|
+
if (type === "agent") return this.verifyAgentTrust(artifact);
|
|
615
|
+
if (artifact.type === "TRUST_RES") {
|
|
616
|
+
const { isValid, error } = await validateTrustResponse(
|
|
617
|
+
artifact.from,
|
|
618
|
+
artifact.to,
|
|
619
|
+
this.trustStore
|
|
620
|
+
);
|
|
621
|
+
return { isTrusted: isValid, error };
|
|
622
|
+
}
|
|
623
|
+
const computedTrustId = computeTrustId(artifact.from, artifact.to), trustRecord = await this.trustStore.getById(computedTrustId);
|
|
624
|
+
if (artifact.type === "BTPS_EVENT" && !isTrustActive(trustRecord)) {
|
|
625
|
+
const ownTrust = await this.trustStore.getById(computeTrustId(artifact.to, artifact.from));
|
|
626
|
+
if (isTrustActive(ownTrust)) return this.verifyPrivacyType(artifact, ownTrust);
|
|
627
|
+
}
|
|
628
|
+
if (artifact.type === "TRUST_REQ") {
|
|
629
|
+
const { isValid, error } = validateTrustRequest(trustRecord);
|
|
630
|
+
return { isTrusted: isValid, error };
|
|
631
|
+
} else
|
|
632
|
+
return isTrustActive(trustRecord) ? this.verifyPrivacyType(artifact, trustRecord) : { isTrusted: !1, error: this.getTrustRefusalError(trustRecord) };
|
|
633
|
+
}
|
|
634
|
+
verifyPrivacyType(artifact, trustRecord) {
|
|
635
|
+
const required = trustRecord?.privacyType, sent = artifact.encryption ? "encrypted" : "unencrypted";
|
|
636
|
+
return !required || required === "mixed" || required === sent ? { isTrusted: !0, error: void 0 } : {
|
|
637
|
+
isTrusted: !1,
|
|
638
|
+
error: new BTPErrorException(
|
|
639
|
+
{ ...BTP_ERROR_PRIVACY_TYPE, message: `${BTP_ERROR_PRIVACY_TYPE.message}: ${required}` },
|
|
640
|
+
{ meta: { required, sent } }
|
|
641
|
+
)
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
getTrustRefusalError(trustRecord) {
|
|
645
|
+
return trustRecord ? trustRecord.status === "revoked" ? new BTPErrorException(BTP_ERROR_TRUST_REVOKED) : trustRecord.status === "blocked" ? new BTPErrorException(BTP_ERROR_TRUST_BLOCKED) : trustRecord.status === "accepted" && trustRecord.expiresAt && new Date(trustRecord.expiresAt).getTime() < Date.now() ? new BTPErrorException(BTP_ERROR_TRUST_EXPIRED) : new BTPErrorException(BTP_ERROR_TRUST_NOT_ALLOWED) : new BTPErrorException(BTP_ERROR_TRUST_NON_EXISTENT);
|
|
646
|
+
}
|
|
647
|
+
async awaitableEmitIfNeeded(event, shouldAwait, reqCtx, resCtx, artifact) {
|
|
648
|
+
if (!shouldAwait) {
|
|
649
|
+
this.emitter.emit(event, artifact, resCtx);
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
const listeners = this.emitter.listeners(event);
|
|
653
|
+
await Promise.all(
|
|
654
|
+
listeners.map(async (listener) => {
|
|
655
|
+
try {
|
|
656
|
+
const result = listener(artifact, resCtx);
|
|
657
|
+
await Promise.resolve(result);
|
|
658
|
+
} catch (err) {
|
|
659
|
+
const error = transformToBTPErrorException(err);
|
|
660
|
+
this.handleOnSocketError(
|
|
661
|
+
error,
|
|
662
|
+
{
|
|
663
|
+
req: { ...reqCtx, error },
|
|
664
|
+
res: resCtx
|
|
665
|
+
},
|
|
666
|
+
"end"
|
|
667
|
+
);
|
|
668
|
+
}
|
|
669
|
+
})
|
|
670
|
+
);
|
|
671
|
+
}
|
|
672
|
+
acceptsArtifacts(type) {
|
|
673
|
+
return this.emitter.listenerCount(type === "agent" ? "agentArtifact" : "transporterArtifact") > 0 || this.handlerFn !== null || this.middlewareManager.getMiddleware("before", "onArtifact").length > 0;
|
|
674
|
+
}
|
|
675
|
+
noHandlerWarning(type) {
|
|
676
|
+
const name = type === "agent" ? "Agent" : "Transporter";
|
|
677
|
+
return `no ${name} handler, forwardTo or 'before onArtifact' middleware is registered, so ${type} artifacts are refused. Register one with onIncomingArtifact('${name}', handler).`;
|
|
678
|
+
}
|
|
679
|
+
async processMessage(data, resCtx, reqCtx) {
|
|
680
|
+
const { artifact, type } = data;
|
|
681
|
+
if (!this.acceptsArtifacts(type))
|
|
682
|
+
return console.warn(`[BtpsServer] Refused a ${type} artifact: ${this.noHandlerWarning(type)}`), this.sendBtpsError(resCtx.socket, BTP_ERROR_ARTIFACT_NOT_ACCEPTED, resCtx.reqId), !0;
|
|
683
|
+
if (type === "agent") {
|
|
684
|
+
const { respondNow } = data;
|
|
685
|
+
if (await this.awaitableEmitIfNeeded("agentArtifact", respondNow === !0, reqCtx, resCtx, {
|
|
686
|
+
...artifact,
|
|
687
|
+
respondNow
|
|
688
|
+
}), this.isResponseSent(resCtx)) return !0;
|
|
689
|
+
} else {
|
|
690
|
+
const listeners = this.emitter.listeners("transporterArtifact");
|
|
691
|
+
await Promise.all(listeners.map(async (listener) => listener(artifact)));
|
|
692
|
+
}
|
|
693
|
+
return await this._forwardArtifact(data), !1;
|
|
694
|
+
}
|
|
695
|
+
_parseAndValidateArtifact(line) {
|
|
696
|
+
try {
|
|
697
|
+
assertStrictJson(line);
|
|
698
|
+
const data = JSON.parse(line);
|
|
699
|
+
let type;
|
|
700
|
+
if (isBtpsControlArtifact(data) ? type = "control" : isBtpsTransportArtifact(data) ? type = "transporter" : isBtpsIdentityRequest(data) ? type = "identityLookup" : isBtpsAgentArtifact(data) && (type = "agent"), !type)
|
|
701
|
+
return { error: "VALIDATION", data };
|
|
702
|
+
if (!validate(BtpArtifactServerSchema, data).success)
|
|
703
|
+
return {
|
|
704
|
+
error: "VALIDATION",
|
|
705
|
+
data: type === "agent" ? { artifact: data, type, respondNow: !1 } : { artifact: data, type }
|
|
706
|
+
};
|
|
707
|
+
switch (type) {
|
|
708
|
+
case "transporter":
|
|
709
|
+
return { data: { artifact: data, type } };
|
|
710
|
+
case "identityLookup":
|
|
711
|
+
return { data: { artifact: data, type } };
|
|
712
|
+
case "agent":
|
|
713
|
+
return {
|
|
714
|
+
data: {
|
|
715
|
+
artifact: data,
|
|
716
|
+
type,
|
|
717
|
+
respondNow: this.isImmediateAction(data.action)
|
|
718
|
+
}
|
|
719
|
+
};
|
|
720
|
+
case "control":
|
|
721
|
+
return { data: { artifact: data, type } };
|
|
722
|
+
default:
|
|
723
|
+
return { error: "VALIDATION", data: void 0 };
|
|
724
|
+
}
|
|
725
|
+
} catch {
|
|
726
|
+
return { error: "JSON" };
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
isImmediateAction(action) {
|
|
730
|
+
return IMMEDIATE_ACTIONS.includes(action);
|
|
731
|
+
}
|
|
732
|
+
async _forwardArtifact(data) {
|
|
733
|
+
this.handlerFn && await this.handlerFn(data);
|
|
734
|
+
}
|
|
735
|
+
async handleOnSocketError(error, context, action = "destroy") {
|
|
736
|
+
const { req, res } = context;
|
|
737
|
+
action === "end" && (req.socket.unpipe(), req.socket.resume()), req.error = error, await this.executeMiddleware(
|
|
738
|
+
this.middlewareManager.getMiddleware("before", "onError"),
|
|
739
|
+
req,
|
|
740
|
+
res
|
|
741
|
+
), this.onError?.(error), this.sendBtpsError(req.socket, error, res.reqId, action), action === "destroy" && !req.socket.destroyed && req.socket.destroy(), await this.executeMiddleware(
|
|
742
|
+
this.middlewareManager.getMiddleware("after", "onError"),
|
|
743
|
+
req,
|
|
744
|
+
res
|
|
745
|
+
);
|
|
746
|
+
}
|
|
747
|
+
wireStatus(error) {
|
|
748
|
+
return typeof error.code == "number" ? { ok: !1, code: error.code, message: error.message } : error.status && error.code ? { ok: !1, code: error.status, message: error.message, error: error.code } : {
|
|
749
|
+
ok: !1,
|
|
750
|
+
code: BTP_ERROR_UNKNOWN.status ?? 500,
|
|
751
|
+
message: BTP_ERROR_UNKNOWN.message,
|
|
752
|
+
error: String(BTP_ERROR_UNKNOWN.code)
|
|
753
|
+
};
|
|
754
|
+
}
|
|
755
|
+
async sendBtpsError(socket, error, reqId, action) {
|
|
756
|
+
const response = this.prepareBtpsResponse(this.wireStatus(error), reqId);
|
|
757
|
+
this.sendBtpsResponse(
|
|
758
|
+
socket,
|
|
759
|
+
{
|
|
760
|
+
...response,
|
|
761
|
+
type: "btps_error"
|
|
762
|
+
},
|
|
763
|
+
action
|
|
764
|
+
);
|
|
765
|
+
}
|
|
766
|
+
sendBtpsResponse(socket, artifact, action) {
|
|
767
|
+
if (socket.destroyed || socket.writableEnded || !socket.writable) return;
|
|
768
|
+
const validationResult = validate(BtpServerResponseSchema, artifact);
|
|
769
|
+
if (!validationResult.success) {
|
|
770
|
+
const error = new BTPErrorException(BTP_ERROR_VALIDATION, {
|
|
771
|
+
cause: "Invalid server response format",
|
|
772
|
+
meta: { validationErrors: validationResult.error.errors, response: artifact }
|
|
773
|
+
});
|
|
774
|
+
this.onError?.(error), socket.destroyed || socket.destroy();
|
|
775
|
+
return;
|
|
776
|
+
}
|
|
777
|
+
try {
|
|
778
|
+
socket.write(JSON.stringify(artifact) + `
|
|
779
|
+
`), this.middlewareManager.onResponseSent(artifact), action && (action === "destroy" ? socket.destroy() : (socket.end(), setTimeout(() => {
|
|
780
|
+
socket.destroyed || socket.destroy();
|
|
781
|
+
}, this.connectionTimeoutMs)));
|
|
782
|
+
} catch (err) {
|
|
783
|
+
this.onError?.(transformToBTPErrorException(err)), socket.destroyed || socket.destroy();
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
getProtocolVersion() {
|
|
787
|
+
return BTP_PROTOCOL_VERSION;
|
|
788
|
+
}
|
|
789
|
+
prepareBtpsResponse(status, reqId) {
|
|
790
|
+
const response = {
|
|
791
|
+
version: this.getProtocolVersion(),
|
|
792
|
+
status,
|
|
793
|
+
id: randomUUID(),
|
|
794
|
+
issuedAt: ( new Date()).toISOString()
|
|
795
|
+
};
|
|
796
|
+
return reqId && (response.reqId = reqId), response;
|
|
797
|
+
}
|
|
798
|
+
async start() {
|
|
799
|
+
await this.initialize(), this.server.listen(this.port, () => {
|
|
800
|
+
console.log(`\u2705 BtpsServer started on port ${this.port}`);
|
|
801
|
+
for (const type of ["transporter", "agent"])
|
|
802
|
+
this.acceptsArtifacts(type) || console.warn(`[BtpsServer] Warning: ${this.noHandlerWarning(type)}`);
|
|
803
|
+
});
|
|
804
|
+
}
|
|
805
|
+
stop() {
|
|
806
|
+
this.server.close(), this.middlewareManager.onServerStop(), this.emitter.removeAllListeners(), console.log("\u2705 BtpsServer stopped");
|
|
807
|
+
}
|
|
808
|
+
forwardTo(handler) {
|
|
809
|
+
this.handlerFn = handler;
|
|
810
|
+
}
|
|
811
|
+
onIncomingArtifact(type, handler) {
|
|
812
|
+
type === "Agent" ? this.emitter.on(
|
|
813
|
+
"agentArtifact",
|
|
814
|
+
handler
|
|
815
|
+
) : this.emitter.on("transporterArtifact", handler);
|
|
816
|
+
}
|
|
817
|
+
getServerIdentity() {
|
|
818
|
+
const { identity } = this.serverIdentity;
|
|
819
|
+
return "signer" in this.serverIdentity ? { identity } : { identity, publicKey: this.serverIdentity.publicKey };
|
|
820
|
+
}
|
|
821
|
+
getDependencies() {
|
|
822
|
+
return this.dependencies;
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
export {
|
|
826
|
+
BtpsServer
|
|
827
|
+
};
|