@btps/sdk 1.1.3 → 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.
Files changed (111) hide show
  1. package/CHANGELOG.md +422 -0
  2. package/bin/verify-evidence-bundle.mjs +96 -0
  3. package/dist/client/btpsAgent.d.ts +10 -1
  4. package/dist/client/btpsAgent.js +116 -18
  5. package/dist/client/btpsClient.d.ts +53 -7
  6. package/dist/client/btpsClient.js +265 -147
  7. package/dist/client/index.d.ts +1 -1
  8. package/dist/client/index.js +3 -1
  9. package/dist/client/libs/schema.js +78 -13
  10. package/dist/client/libs/timeouts.d.ts +6 -0
  11. package/dist/client/libs/timeouts.js +2 -1
  12. package/dist/client/types/index.d.ts +54 -2
  13. package/dist/core/authentication/BtpsAuthentication.d.ts +43 -1
  14. package/dist/core/authentication/BtpsAuthentication.js +152 -36
  15. package/dist/core/authentication/refreshSuccessor.js +47 -0
  16. package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +17 -1
  17. package/dist/core/authentication/storage/InMemoryTokenStore.js +16 -4
  18. package/dist/core/authentication/types.d.ts +82 -0
  19. package/dist/core/crypto/contentKey.d.ts +34 -0
  20. package/dist/core/crypto/contentKey.js +64 -0
  21. package/dist/core/crypto/decryptVerify.d.ts +7 -1
  22. package/dist/core/crypto/decryptVerify.js +23 -5
  23. package/dist/core/crypto/decrypter-interface.d.ts +6 -0
  24. package/dist/core/crypto/index.d.ts +12 -0
  25. package/dist/core/crypto/index.js +7 -1
  26. package/dist/core/crypto/keyResolver.d.ts +48 -0
  27. package/dist/core/crypto/keyResolver.js +46 -0
  28. package/dist/core/crypto/pem-decrypter.d.ts +2 -0
  29. package/dist/core/crypto/pem-decrypter.js +13 -8
  30. package/dist/core/crypto/signEncrypt.d.ts +4 -1
  31. package/dist/core/crypto/signEncrypt.js +20 -5
  32. package/dist/core/crypto/types.d.ts +8 -1
  33. package/dist/core/delegation/BtpsDelegator.d.ts +4 -0
  34. package/dist/core/delegation/BtpsDelegator.js +3 -2
  35. package/dist/core/delegation/verifyTransporterSignature.d.ts +104 -0
  36. package/dist/core/delegation/verifyTransporterSignature.js +224 -0
  37. package/dist/core/error/constant.d.ts +39 -0
  38. package/dist/core/error/constant.js +55 -0
  39. package/dist/core/server/constants/btps-protocol.d.ts +21 -5
  40. package/dist/core/server/constants/btps-protocol.js +46 -8
  41. package/dist/core/server/constants/index.d.ts +7 -3
  42. package/dist/core/server/constants/index.js +19 -4
  43. package/dist/core/server/constants/limits.d.ts +18 -0
  44. package/dist/core/server/constants/limits.js +19 -1
  45. package/dist/core/server/constants/permissions.d.ts +38 -0
  46. package/dist/core/server/constants/permissions.js +38 -0
  47. package/dist/core/server/schemas/artifacts/agentSchema.js +2 -1
  48. package/dist/core/server/schemas/artifacts/artifacts.js +7 -1
  49. package/dist/core/server/schemas/artifacts/controlSchema.js +1 -1
  50. package/dist/core/server/schemas/artifacts/identityLookupSchema.js +10 -1
  51. package/dist/core/server/schemas/artifacts/transporterSchema.js +92 -12
  52. package/dist/core/server/schemas/bounded.js +2 -2
  53. package/dist/core/server/schemas/btpsDocsSchema.d.ts +34185 -1084
  54. package/dist/core/server/schemas/btpsDocsSchema.js +300 -42
  55. package/dist/core/server/schemas/helpers.d.ts +9580 -0
  56. package/dist/core/server/schemas/helpers.js +76 -12
  57. package/dist/core/server/schemas/keyChainSchema.js +53 -0
  58. package/dist/core/server/schemas/responseSchema.js +52 -9
  59. package/dist/core/server/schemas/schema.js +3 -1
  60. package/dist/core/server/schemas/trustValues.d.ts +105 -0
  61. package/dist/core/server/schemas/trustValues.js +117 -0
  62. package/dist/core/server/types.d.ts +104 -6
  63. package/dist/core/storage/AbstractIdentityStore.d.ts +9 -0
  64. package/dist/core/storage/JsonIdentityStore.d.ts +3 -0
  65. package/dist/core/storage/JsonIdentityStore.js +3 -0
  66. package/dist/core/storage/types.d.ts +2 -0
  67. package/dist/core/trust/agreements.d.ts +107 -0
  68. package/dist/core/trust/agreements.js +116 -0
  69. package/dist/core/trust/evidence.d.ts +220 -0
  70. package/dist/core/trust/evidence.js +334 -0
  71. package/dist/core/trust/index.d.ts +10 -0
  72. package/dist/core/trust/index.js +14 -1
  73. package/dist/core/trust/keyRotation.d.ts +148 -0
  74. package/dist/core/trust/keyRotation.js +267 -0
  75. package/dist/core/trust/permissions.d.ts +114 -0
  76. package/dist/core/trust/permissions.js +115 -0
  77. package/dist/core/trust/shaping.d.ts +42 -0
  78. package/dist/core/trust/shaping.js +47 -0
  79. package/dist/core/trust/storage/AbstractTrustStore.d.ts +2 -1
  80. package/dist/core/trust/storage/JsonTrustStore.d.ts +3 -2
  81. package/dist/core/trust/timestamps.d.ts +49 -0
  82. package/dist/core/trust/timestamps.js +78 -0
  83. package/dist/core/trust/trustUtils.d.ts +13 -2
  84. package/dist/core/trust/trustUtils.js +28 -3
  85. package/dist/core/trust/types.d.ts +302 -2
  86. package/dist/core/trust/verification.d.ts +52 -0
  87. package/dist/core/trust/verification.js +55 -0
  88. package/dist/server/btpsServer.d.ts +70 -5
  89. package/dist/server/btpsServer.js +263 -143
  90. package/dist/server/index.d.ts +3 -0
  91. package/dist/server/index.js +17 -1
  92. package/dist/server/libs/agreementOrderCheck.d.ts +29 -0
  93. package/dist/server/libs/agreementOrderCheck.js +29 -0
  94. package/dist/server/libs/artifactTimeWindow.d.ts +2 -2
  95. package/dist/server/libs/artifactTimeWindow.js +2 -1
  96. package/dist/server/libs/detailsRequestLimit.d.ts +27 -0
  97. package/dist/server/libs/detailsRequestLimit.js +28 -0
  98. package/dist/server/libs/detailsResponseCheck.d.ts +27 -0
  99. package/dist/server/libs/detailsResponseCheck.js +27 -0
  100. package/dist/server/libs/eventChainCheck.d.ts +31 -0
  101. package/dist/server/libs/eventChainCheck.js +39 -0
  102. package/dist/server/libs/inFlightLimit.d.ts +10 -0
  103. package/dist/server/libs/inFlightLimit.js +7 -1
  104. package/dist/server/libs/index.d.ts +5 -0
  105. package/dist/server/libs/index.js +10 -0
  106. package/dist/server/libs/keyChains.d.ts +14 -0
  107. package/dist/server/libs/keyChains.js +17 -0
  108. package/dist/server/libs/wrapForAgent.d.ts +20 -0
  109. package/dist/server/libs/wrapForAgent.js +36 -0
  110. package/dist/server/types.d.ts +95 -9
  111. 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 { resolveMaxInFlightPerConnection } from "./libs/inFlightLimit.js";
80
- import { BtpArtifactServerSchema } from "../core/server/schemas/artifacts/artifacts.js";
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.maxArtifactAgeSeconds = resolveMaxArtifactAgeSeconds(options.maxArtifactAgeSeconds), this.middlewareManager = new MiddlewareManager(options.middlewarePath), this.dependencies = {
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(
@@ -186,7 +232,7 @@ class BtpsServer {
186
232
  sendError: (error, action) => {
187
233
  responseSent || (responseSent = !0);
188
234
  const reqId = resCtx?.reqId;
189
- this.sendBtpsError(socket, error, reqId, action);
235
+ this.sendBtpsError(socket, error, reqId, action, !0);
190
236
  },
191
237
  get responseSent() {
192
238
  return responseSent;
@@ -194,7 +240,7 @@ class BtpsServer {
194
240
  };
195
241
  return { reqCtx, resCtx };
196
242
  };
197
- let inFlight = 0;
243
+ let inFlight = 0, invalidInARow = 0;
198
244
  stream.on("data", async (line) => {
199
245
  if (!line.trim()) return;
200
246
  const lineIdentity = createIdentityRef(), { reqCtx: parseReq, resCtx: parseRes } = createContexts(lineIdentity);
@@ -218,9 +264,13 @@ class BtpsServer {
218
264
  return;
219
265
  if (parseError || !data) {
220
266
  const errorToSend = parseError ?? BTP_ERROR_INVALID_JSON;
221
- return this.sendBtpsError(socket, errorToSend);
267
+ return invalidInARow++, invalidInARow >= this.maxConsecutiveInvalidLines ? this.handleOnSocketError(
268
+ new BTPErrorException(errorToSend),
269
+ { req: parseReq, res: parseRes },
270
+ "end"
271
+ ) : this.sendBtpsError(socket, errorToSend);
222
272
  }
223
- if (!isSupportedVersion(data.artifact.version))
273
+ if (invalidInARow = 0, !isSupportedVersion(data.artifact.version))
224
274
  return this.sendBtpsError(
225
275
  socket,
226
276
  {
@@ -229,6 +279,8 @@ class BtpsServer {
229
279
  },
230
280
  parseRes.reqId
231
281
  );
282
+ if (data.type === "transporter" && data.artifact.syncOf !== void 0)
283
+ return this.sendBtpsError(socket, BTP_ERROR_SYNC_NOT_ALLOWED, parseRes.reqId);
232
284
  if (data.type === "control")
233
285
  return await this.handleControl(data.artifact, {
234
286
  req: parseReq,
@@ -243,7 +295,7 @@ class BtpsServer {
243
295
  await this.executeRequestPipeline(reqCtx, resCtx);
244
296
  } catch (err) {
245
297
  const error = transformToBTPErrorException(err), errorReq = parseReq;
246
- 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(
247
299
  error,
248
300
  {
249
301
  req: errorReq,
@@ -252,7 +304,7 @@ class BtpsServer {
252
304
  "answer"
253
305
  );
254
306
  } finally {
255
- inFlight--, stream.isPaused() && !stream.destroyed && stream.resume();
307
+ await this.answersOnSocket.get(socket), inFlight--, stream.isPaused() && !stream.destroyed && stream.resume();
256
308
  }
257
309
  }), socket.setTimeout(this.connectionTimeoutMs, () => {
258
310
  if (inFlight > 0) {
@@ -309,17 +361,18 @@ class BtpsServer {
309
361
  }
310
362
  }
311
363
  async handleIdentityLookup(artifact, context) {
312
- const { res } = context, { identity, hostSelector, identitySelector } = artifact, identityRecord = await this.identityStore?.getPublicKeyRecord(
313
- computeId(identity),
314
- identitySelector
315
- );
316
- if (!identityRecord)
317
- return this.sendBtpsError(res.socket, BTP_ERROR_IDENTITY_NOT_FOUND, res.reqId);
318
- const { createdAt, ...restRecord } = identityRecord, data = {
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 = {
319
372
  ...this.prepareBtpsResponse({ ok: !0, message: "success", code: 200 }, res.reqId),
320
373
  type: "btps_response",
321
374
  selector: hostSelector,
322
- document: restRecord,
375
+ document,
323
376
  signedBy: this.serverIdentity.identity
324
377
  };
325
378
  try {
@@ -387,7 +440,7 @@ class BtpsServer {
387
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;
388
441
  return this.sendBtpsError(resCtx.socket, wireError, resCtx.reqId);
389
442
  }
390
- await this.executeMiddleware(
443
+ this.tellDetails(data), !(await this.executeMiddleware(
391
444
  this.middlewareManager.getMiddleware("before", "onArtifact"),
392
445
  reqCtx,
393
446
  resCtx
@@ -395,7 +448,7 @@ class BtpsServer {
395
448
  this.middlewareManager.getMiddleware("after", "onArtifact"),
396
449
  reqCtx,
397
450
  resCtx
398
- ) || this.sendBtpsResponse(resCtx.socket, {
451
+ )) && this.sendBtpsResponse(resCtx.socket, {
399
452
  ...this.prepareBtpsResponse({ ok: !0, message: "success", code: 200 }, resCtx.reqId),
400
453
  type: "btps_response"
401
454
  });
@@ -494,111 +547,64 @@ class BtpsServer {
494
547
  if (artifact.action === "auth.request")
495
548
  return { isTrusted: !0, error: void 0 };
496
549
  const { agentId, to } = artifact, computedTrustId = computeAgentTrustId(agentId, this.deviceOwner(artifact)), trustRecord = await this.trustStore.getById(computedTrustId);
497
- return trustRecord ? { isTrusted: isTrustActive(trustRecord), error: void 0 } : {
498
- isTrusted: !1,
499
- error: new BTPErrorException(BTP_ERROR_TRUST_NOT_ALLOWED, {
500
- cause: `Agent ${agentId} not trusted`,
501
- meta: { agentId, to, computedTrustId }
502
- })
503
- };
504
- }
505
- async verifyAttestation(delegation) {
506
- const { attestation, ...restDelegation } = delegation, { signature, ...restAttestation } = attestation, attestorPubKey = await resolvePublicKey(attestation.signedBy, attestation.selector);
507
- if (!attestorPubKey)
550
+ if (!trustRecord)
508
551
  return {
509
- isValid: !1,
510
- error: new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY, {
511
- cause: `Attestor ${attestation.signedBy} public key not found`,
512
- meta: { attestation }
552
+ isTrusted: !1,
553
+ error: new BTPErrorException(BTP_ERROR_TRUST_NOT_ALLOWED, {
554
+ cause: `Agent ${agentId} not trusted`,
555
+ meta: { agentId, to, computedTrustId }
513
556
  })
514
557
  };
515
- const signedMsg = { ...restDelegation, attestation: restAttestation }, { isValid, error } = verifySignature(signedMsg, signature, attestorPubKey);
516
- return {
517
- isValid,
518
- error: error ? new BTPErrorException(BTP_ERROR_ATTESTATION_VERIFICATION, {
519
- cause: `Attestation signature verification failed of attestor ${attestation.signedBy}`,
520
- meta: { attestation }
521
- }) : void 0
522
- };
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);
523
595
  }
524
596
  async verifyDelegation(artifactWithDelegation) {
525
- const operator = (await getHostAndSelector(artifactWithDelegation.from))?.operator;
526
- if (!isDelegationAllowed(artifactWithDelegation, operator))
527
- return {
528
- isValid: !1,
529
- error: new BTPErrorException(BTP_ERROR_DELEGATION_INVALID, {
530
- 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`
531
- })
532
- };
533
- const { delegation, ...restArtifact } = artifactWithDelegation;
534
- if (delegation.signedBy === artifactWithDelegation.from && !delegation.attestation)
535
- return {
536
- isValid: !1,
537
- error: new BTPErrorException(BTP_ERROR_DELEGATION_INVALID, {
538
- cause: "Custom managed domain delegation requires attestation. Either provide attestation or directly send without delegation via transporter",
539
- meta: {
540
- delegation,
541
- from: artifactWithDelegation.from
542
- }
543
- })
544
- };
545
- if (delegation.attestation) {
546
- if (delegation.attestation.signedBy !== operator)
547
- return {
548
- isValid: !1,
549
- error: new BTPErrorException(BTP_ERROR_ATTESTATION_VERIFICATION, {
550
- cause: `${delegation.attestation.signedBy} is not the operator of ${artifactWithDelegation.from}'s domain`
551
- })
552
- };
553
- const { isValid: isValid2, error: error2 } = await this.verifyAttestation(
554
- delegation
555
- );
556
- if (!isValid2) return { isValid: isValid2, error: error2 };
557
- }
558
- const delegatorPubKey = await resolvePublicKey(delegation.signedBy, delegation.selector);
559
- if (!delegatorPubKey)
560
- return {
561
- isValid: !1,
562
- error: new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY, {
563
- cause: `Delegator ${delegation.signedBy} public key not found`,
564
- meta: { delegation }
565
- })
566
- };
567
- const { signature, attestation, ...restDelegation } = delegation, signedMsg = { ...artifactWithDelegation, delegation: restDelegation }, { isValid: isValidDelegation } = verifySignature(signedMsg, signature, delegatorPubKey);
568
- if (!isValidDelegation)
569
- return {
570
- isValid: isValidDelegation,
571
- error: new BTPErrorException(BTP_ERROR_DELEGATION_SIG_VERIFICATION, {
572
- cause: `Delegation signature verification failed of delegator ${delegation.signedBy}`,
573
- meta: {
574
- delegation
575
- }
576
- })
577
- };
578
- const { signature: origSignature, ...origSignedMsg } = restArtifact, { isValid, error } = verifySignature(
579
- origSignedMsg,
580
- origSignature,
581
- delegation.agentPubKey
582
- );
583
- return {
584
- isValid,
585
- error: error ? new BTPErrorException(BTP_ERROR_DELEGATION_SIG_VERIFICATION, {
586
- cause: `Delegated artifact's original artifact signature verification failed of agent ${delegation.agentId}`,
587
- meta: {
588
- delegation
589
- }
590
- }) : void 0
591
- };
597
+ return verifyDelegation(artifactWithDelegation, this.keyResolver, this.keyChains);
592
598
  }
593
599
  async verifySignature(data) {
594
600
  const { artifact, type } = data;
595
601
  if (type === "agent") return this.verifyAgentSignature(artifact);
596
- if (artifact.delegation)
597
- return this.verifyDelegation(
598
- artifact
599
- );
600
- const { signature, ...signedMsg } = artifact, publicKey = await resolvePublicKey(artifact.from, artifact.selector);
601
- return publicKey ? verifySignature(signedMsg, signature, publicKey) : { isValid: !1, error: new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY) };
602
+ const { isValid, error } = await verifyTransporterSignature(
603
+ artifact,
604
+ this.keyResolver,
605
+ this.keyChains
606
+ );
607
+ return { isValid, error };
602
608
  }
603
609
  async verifyEventRelation(data) {
604
610
  if (data.type !== "transporter" || data.artifact.type !== "BTPS_EVENT")
@@ -611,15 +617,65 @@ class BtpsServer {
611
617
  meta: { relatesTo, from, to }
612
618
  })
613
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);
614
667
  }
615
668
  async verifyTrust(data) {
616
669
  const { artifact, type } = data;
617
670
  if (type === "agent") return this.verifyAgentTrust(artifact);
671
+ if (DETAILS_ARTIFACT_TYPES.includes(artifact.type))
672
+ return this.verifyDetailsTrust(artifact);
618
673
  if (artifact.type === "TRUST_RES") {
619
674
  const { isValid, error } = await validateTrustResponse(
620
675
  artifact.from,
621
676
  artifact.to,
622
- this.trustStore
677
+ this.trustStore,
678
+ artifact
623
679
  );
624
680
  return { isTrusted: isValid, error };
625
681
  }
@@ -629,10 +685,17 @@ class BtpsServer {
629
685
  if (isTrustActive(ownTrust)) return this.verifyPrivacyType(artifact, ownTrust);
630
686
  }
631
687
  if (artifact.type === "TRUST_REQ") {
632
- const { isValid, error } = validateTrustRequest(trustRecord);
688
+ const { isValid, error } = validateTrustRequest(trustRecord, artifact);
633
689
  return { isTrusted: isValid, error };
634
- } else
635
- return isTrustActive(trustRecord) ? this.verifyPrivacyType(artifact, trustRecord) : { isTrusted: !1, error: this.getTrustRefusalError(trustRecord) };
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
+ }
636
699
  }
637
700
  verifyPrivacyType(artifact, trustRecord) {
638
701
  const required = trustRecord?.privacyType, sent = artifact.encryption ? "encrypted" : "unencrypted";
@@ -674,6 +737,9 @@ class BtpsServer {
674
737
  }
675
738
  acceptsArtifacts(type) {
676
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;
677
743
  }
678
744
  noHandlerWarning(type) {
679
745
  const name = type === "agent" ? "Agent" : "Transporter";
@@ -702,7 +768,7 @@ class BtpsServer {
702
768
  let type;
703
769
  if (isBtpsControlArtifact(data) ? type = "control" : isBtpsTransportArtifact(data) ? type = "transporter" : isBtpsIdentityRequest(data) ? type = "identityLookup" : isBtpsAgentArtifact(data) && (type = "agent"), !type)
704
770
  return { error: "VALIDATION", data };
705
- if (!validate(BtpArtifactServerSchema, data).success)
771
+ if (!validate(BtpArtifactSchemaByType[type], data).success)
706
772
  return {
707
773
  error: "VALIDATION",
708
774
  data: type === "agent" ? { artifact: data, type, respondNow: !1 } : { artifact: data, type }
@@ -747,16 +813,36 @@ class BtpsServer {
747
813
  res
748
814
  );
749
815
  }
750
- wireStatus(error) {
751
- 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 } : {
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 {
752
838
  ok: !1,
753
839
  code: BTP_ERROR_UNKNOWN.status ?? 500,
754
840
  message: BTP_ERROR_UNKNOWN.message,
755
841
  error: String(BTP_ERROR_UNKNOWN.code)
756
842
  };
757
843
  }
758
- async sendBtpsError(socket, error, reqId, action) {
759
- 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);
760
846
  this.sendBtpsResponse(
761
847
  socket,
762
848
  {
@@ -766,25 +852,59 @@ class BtpsServer {
766
852
  action
767
853
  );
768
854
  }
769
- sendBtpsResponse(socket, artifact, action) {
855
+ sendBtpsResponse(socket, response, action) {
770
856
  if (socket.destroyed || socket.writableEnded || !socket.writable) return;
771
- 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);
772
858
  if (!validationResult.success) {
773
859
  const error = new BTPErrorException(BTP_ERROR_VALIDATION, {
774
860
  cause: "Invalid server response format",
775
861
  meta: { validationErrors: validationResult.error.errors, response: artifact }
776
862
  });
777
- this.onError?.(error), socket.destroyed || socket.destroy();
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);
778
869
  return;
779
870
  }
871
+ if (!this.signAnswers) {
872
+ this.writeAnswer(socket, artifact, action);
873
+ return;
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
+ };
780
888
  try {
781
- socket.write(JSON.stringify(artifact) + `
782
- `), this.middlewareManager.onResponseSent(artifact), action && (action === "destroy" ? socket.destroy() : (socket.end(), setTimeout(() => {
783
- socket.destroyed || socket.destroy();
784
- }, this.connectionTimeoutMs)));
785
- } catch (err) {
786
- this.onError?.(transformToBTPErrorException(err)), socket.destroyed || socket.destroy();
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;
787
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
+ }
788
908
  }
789
909
  getProtocolVersion() {
790
910
  return BTP_PROTOCOL_VERSION;
@@ -8,4 +8,7 @@ export * from '../core/server/types.js';
8
8
  export * from '../core/server/constants/index.js';
9
9
  export * from '../core/server/helpers/index.js';
10
10
  export { BtpsServer } from './btpsServer.js';
11
+ export { lifecycleEventChainProblem, lifecycleEventChainReference, lifecycleEventSenderProblem, trustRequestProblem, trustResponseProblem, } from '../core/server/schemas/helpers.js';
12
+ export { wrapForAgent } from './libs/wrapForAgent.js';
13
+ export { verifyTransporterSignature } from '../core/delegation/verifyTransporterSignature.js';
11
14
  export * from './types.js';
@@ -9,7 +9,23 @@ export * from "../core/server/types.js";
9
9
  export * from "../core/server/constants/index.js";
10
10
  export * from "../core/server/helpers/index.js";
11
11
  import { BtpsServer } from "./btpsServer.js";
12
+ import {
13
+ lifecycleEventChainProblem,
14
+ lifecycleEventChainReference,
15
+ lifecycleEventSenderProblem,
16
+ trustRequestProblem,
17
+ trustResponseProblem
18
+ } from "../core/server/schemas/helpers.js";
19
+ import { wrapForAgent } from "./libs/wrapForAgent.js";
20
+ import { verifyTransporterSignature } from "../core/delegation/verifyTransporterSignature.js";
12
21
  export * from "./types.js";
13
22
  export {
14
- BtpsServer
23
+ BtpsServer,
24
+ lifecycleEventChainProblem,
25
+ lifecycleEventChainReference,
26
+ lifecycleEventSenderProblem,
27
+ trustRequestProblem,
28
+ trustResponseProblem,
29
+ verifyTransporterSignature,
30
+ wrapForAgent
15
31
  };