@btps/sdk 1.1.3 → 1.2.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/CHANGELOG.md +461 -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 +99 -12
  52. package/dist/core/server/schemas/bounded.js +2 -2
  53. package/dist/core/server/schemas/btpsDocsSchema.d.ts +36009 -1083
  54. package/dist/core/server/schemas/btpsDocsSchema.js +305 -42
  55. package/dist/core/server/schemas/helpers.d.ts +10090 -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 +312 -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 +79 -5
  89. package/dist/server/btpsServer.js +297 -145
  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 +103 -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,12 @@ 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,
43
+ BTP_ERROR_PERMISSION_REQUIRED,
44
+ BTP_ERROR_DOCUMENT_TYPE_MISMATCH,
45
+ BTP_ERROR_DETAILS_NOT_HELD
42
46
  } from "../core/error/constant.js";
43
47
  import {
44
48
  assertStrictJson,
@@ -49,16 +53,14 @@ import {
49
53
  } from "../core/crypto/index.js";
50
54
  import {
51
55
  base64ToPem,
52
- isDelegationAllowed,
53
56
  computeId,
54
- getHostAndSelector,
55
57
  isBtpsIdentityRequest,
56
58
  isBtpsTransportArtifact,
57
- resolvePublicKey,
58
59
  isBtpsControlArtifact,
59
60
  isBtpsAgentArtifact,
60
61
  isValidIdentity
61
62
  } from "../core/utils/index.js";
63
+ import { detailsOwed } from "../core/server/schemas/artifacts/transporterSchema.js";
62
64
  import { BTPErrorException, transformToBTPErrorException } from "../core/error/index.js";
63
65
  import {
64
66
  AGENT_TRANSPORTER_ACTIONS,
@@ -66,21 +68,53 @@ import {
66
68
  IMMEDIATE_ACTIONS,
67
69
  MAX_SUPPORTED_VERSION,
68
70
  MIN_SUPPORTED_VERSION,
69
- isSupportedVersion
71
+ isSupportedVersion,
72
+ isVersionBelow,
73
+ DETAILS_ARTIFACT_TYPES
70
74
  } from "../core/server/constants/index.js";
71
75
  import { validate } from "../core/utils/validation.js";
72
76
  import { MiddlewareManager } from "./libs/middlewareManager.js";
77
+ import {
78
+ verifyAttestation,
79
+ verifyDelegation,
80
+ verifyTransporterSignature
81
+ } from "../core/delegation/verifyTransporterSignature.js";
82
+ import { createDefaultKeyResolver } from "../core/crypto/keyResolver.js";
83
+ import { resolveKeyChainMaxCacheSeconds, resolveRetiredKeyGraceSeconds } from "./libs/keyChains.js";
73
84
  import { artifactSizeGuard, resolveMaxArtifactSizeKb } from "./libs/artifactSizeGuard.js";
74
85
  import {
75
86
  artifactTimeWindowError,
76
87
  resolveMaxArtifactAgeSeconds
77
88
  } from "./libs/artifactTimeWindow.js";
78
89
  import { resolveConnectionTimeoutMs } from "./libs/connectionTimeout.js";
79
- import { resolveMaxInFlightPerConnection } from "./libs/inFlightLimit.js";
80
- import { BtpArtifactServerSchema } from "../core/server/schemas/artifacts/artifacts.js";
90
+ import {
91
+ resolveMaxConsecutiveInvalidLines,
92
+ resolveMaxInFlightPerConnection
93
+ } from "./libs/inFlightLimit.js";
94
+ import { BtpArtifactSchemaByType } from "../core/server/schemas/artifacts/artifacts.js";
81
95
  import { BtpServerResponseSchema } from "../core/server/schemas/responseSchema.js";
82
96
  import { BtpAuthReqDocSchema } from "../core/server/schemas/btpsDocsSchema.js";
83
97
  import { keyProofPayload } from "../core/authentication/keyProof.js";
98
+ import * as BTPS_ERROR_CONSTANTS from "../core/error/constant.js";
99
+ const lastRotationTo = (chain) => {
100
+ const to = [...chain].reverse().find(
101
+ (record) => "rotation" in record
102
+ )?.rotation.to;
103
+ return to && { selector: to.selector, publicKey: base64ToPem(to.publicKey) };
104
+ }, BTPS_ERRORS_BY_CODE = new Map(
105
+ Object.values(BTPS_ERROR_CONSTANTS).filter(
106
+ (value) => typeof value == "object" && value !== null && typeof value.code == "string" && typeof value.status == "number"
107
+ ).map((constant) => [String(constant.code), constant])
108
+ ), TOLD_AS_ITSELF = new Set(
109
+ [
110
+ BTP_ERROR_VALIDATION.code,
111
+ BTP_ERROR_PRIVACY_TYPE.code,
112
+ BTP_ERROR_PERMISSION.code,
113
+ BTP_ERROR_PERMISSION_REQUIRED.code,
114
+ BTP_ERROR_DOCUMENT_TYPE_MISMATCH.code,
115
+ BTP_ERROR_DETAILS_NOT_HELD.code
116
+ ].map(String)
117
+ );
84
118
  class BtpsServer {
85
119
  tlsOptions;
86
120
  serverIdentity;
@@ -91,16 +125,42 @@ class BtpsServer {
91
125
  connectionTimeoutMs;
92
126
  maxArtifactSizeKb;
93
127
  maxInFlightPerConnection;
128
+ maxConsecutiveInvalidLines;
94
129
  maxArtifactAgeSeconds;
130
+ signAnswers;
131
+ keyResolver;
132
+ entityTypeOf;
133
+ keyChains;
134
+ events = new EventEmitter();
135
+ answersOnSocket = new WeakMap();
95
136
  dependencies;
96
137
  port;
97
138
  server;
98
139
  emitter = new EventEmitter();
99
140
  handlerFn = null;
100
141
  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(
142
+ 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.entityTypeOf = options.entityTypeOf, this.connectionTimeoutMs = resolveConnectionTimeoutMs(options.connectionTimeoutMs), this.maxArtifactSizeKb = resolveMaxArtifactSizeKb(options.maxArtifactSizeKb), this.maxInFlightPerConnection = resolveMaxInFlightPerConnection(
102
143
  options.maxInFlightPerConnection
103
- ), this.maxArtifactAgeSeconds = resolveMaxArtifactAgeSeconds(options.maxArtifactAgeSeconds), this.middlewareManager = new MiddlewareManager(options.middlewarePath), this.dependencies = {
144
+ ), this.maxConsecutiveInvalidLines = resolveMaxConsecutiveInvalidLines(
145
+ options.maxConsecutiveInvalidLines
146
+ ), this.maxArtifactAgeSeconds = resolveMaxArtifactAgeSeconds(options.maxArtifactAgeSeconds), this.signAnswers = options.signAnswers === !0, this.keyResolver = options.keyResolver;
147
+ const keyChainMaxCacheSeconds = resolveKeyChainMaxCacheSeconds(options.keyChainMaxCacheSeconds), chains = options.keyResolver?.resolveKeyChain ? options.keyResolver : createDefaultKeyResolver({
148
+ from: options.serverIdentity.identity,
149
+ keyChainMaxCacheSeconds
150
+ });
151
+ if (this.keyChains = {
152
+ resolveKeyChain: (identity) => chains.resolveKeyChain?.(identity) ?? Promise.resolve({ status: "unavailable", reason: "no key chain lookup" }),
153
+ retiredKeyGraceSeconds: resolveRetiredKeyGraceSeconds(options.retiredKeyGraceSeconds),
154
+ maxSkewSeconds: this.maxArtifactAgeSeconds,
155
+
156
+ checked: new Map(),
157
+ checkedForSeconds: keyChainMaxCacheSeconds
158
+ }, this.signAnswers && !options.serverIdentity.selector)
159
+ throw new BTPErrorException({
160
+ code: "INVALID_CONFIG",
161
+ message: "signAnswers needs serverIdentity.selector: the selector the key is published under"
162
+ });
163
+ this.middlewareManager = new MiddlewareManager(options.middlewarePath), this.dependencies = {
104
164
  trustStore: this.trustStore,
105
165
  identityStore: this.identityStore
106
166
  }, this.server = tls.createServer(
@@ -186,7 +246,7 @@ class BtpsServer {
186
246
  sendError: (error, action) => {
187
247
  responseSent || (responseSent = !0);
188
248
  const reqId = resCtx?.reqId;
189
- this.sendBtpsError(socket, error, reqId, action);
249
+ this.sendBtpsError(socket, error, reqId, action, !0);
190
250
  },
191
251
  get responseSent() {
192
252
  return responseSent;
@@ -194,7 +254,7 @@ class BtpsServer {
194
254
  };
195
255
  return { reqCtx, resCtx };
196
256
  };
197
- let inFlight = 0;
257
+ let inFlight = 0, invalidInARow = 0;
198
258
  stream.on("data", async (line) => {
199
259
  if (!line.trim()) return;
200
260
  const lineIdentity = createIdentityRef(), { reqCtx: parseReq, resCtx: parseRes } = createContexts(lineIdentity);
@@ -218,9 +278,13 @@ class BtpsServer {
218
278
  return;
219
279
  if (parseError || !data) {
220
280
  const errorToSend = parseError ?? BTP_ERROR_INVALID_JSON;
221
- return this.sendBtpsError(socket, errorToSend);
281
+ return invalidInARow++, invalidInARow >= this.maxConsecutiveInvalidLines ? this.handleOnSocketError(
282
+ new BTPErrorException(errorToSend),
283
+ { req: parseReq, res: parseRes },
284
+ "end"
285
+ ) : this.sendBtpsError(socket, errorToSend);
222
286
  }
223
- if (!isSupportedVersion(data.artifact.version))
287
+ if (invalidInARow = 0, !isSupportedVersion(data.artifact.version))
224
288
  return this.sendBtpsError(
225
289
  socket,
226
290
  {
@@ -229,6 +293,8 @@ class BtpsServer {
229
293
  },
230
294
  parseRes.reqId
231
295
  );
296
+ if (data.type === "transporter" && data.artifact.syncOf !== void 0)
297
+ return this.sendBtpsError(socket, BTP_ERROR_SYNC_NOT_ALLOWED, parseRes.reqId);
232
298
  if (data.type === "control")
233
299
  return await this.handleControl(data.artifact, {
234
300
  req: parseReq,
@@ -243,7 +309,7 @@ class BtpsServer {
243
309
  await this.executeRequestPipeline(reqCtx, resCtx);
244
310
  } catch (err) {
245
311
  const error = transformToBTPErrorException(err), errorReq = parseReq;
246
- return errorReq.error = error, console.error("[BtpsServer] Error", error.toJSON()), await this.handleOnSocketError(
312
+ return errorReq.error = error, this.takesErrors() || console.error("[BtpsServer] Error", error.toJSON()), await this.handleOnSocketError(
247
313
  error,
248
314
  {
249
315
  req: errorReq,
@@ -252,7 +318,7 @@ class BtpsServer {
252
318
  "answer"
253
319
  );
254
320
  } finally {
255
- inFlight--, stream.isPaused() && !stream.destroyed && stream.resume();
321
+ await this.answersOnSocket.get(socket), inFlight--, stream.isPaused() && !stream.destroyed && stream.resume();
256
322
  }
257
323
  }), socket.setTimeout(this.connectionTimeoutMs, () => {
258
324
  if (inFlight > 0) {
@@ -309,17 +375,18 @@ class BtpsServer {
309
375
  }
310
376
  }
311
377
  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 = {
378
+ 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 && {
379
+ selector: current.selector,
380
+ publicKey: current.publicKey,
381
+ keyType: "rsa",
382
+ version: BTP_PROTOCOL_VERSION
383
+ };
384
+ if (!restRecord) return this.sendBtpsError(res.socket, BTP_ERROR_IDENTITY_NOT_FOUND, res.reqId);
385
+ const document = isVersionBelow(artifact.version, "1.2.0") ? restRecord : { ...restRecord, identity, ...keyChain && { keyChain } }, data = {
319
386
  ...this.prepareBtpsResponse({ ok: !0, message: "success", code: 200 }, res.reqId),
320
387
  type: "btps_response",
321
388
  selector: hostSelector,
322
- document: restRecord,
389
+ document,
323
390
  signedBy: this.serverIdentity.identity
324
391
  };
325
392
  try {
@@ -384,10 +451,10 @@ class BtpsServer {
384
451
  resCtx
385
452
  )) return;
386
453
  if (!isTrusted) {
387
- 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;
454
+ const refusal = reqCtx.error, wireError = refusal?.code === BTP_ERROR_TRUST_EXPIRED.code ? BTP_ERROR_TRUST_EXPIRED : refusal && TOLD_AS_ITSELF.has(String(refusal.code)) ? refusal : BTP_ERROR_TRUST_NOT_ALLOWED;
388
455
  return this.sendBtpsError(resCtx.socket, wireError, resCtx.reqId);
389
456
  }
390
- await this.executeMiddleware(
457
+ this.tellDetails(data), !(await this.executeMiddleware(
391
458
  this.middlewareManager.getMiddleware("before", "onArtifact"),
392
459
  reqCtx,
393
460
  resCtx
@@ -395,7 +462,7 @@ class BtpsServer {
395
462
  this.middlewareManager.getMiddleware("after", "onArtifact"),
396
463
  reqCtx,
397
464
  resCtx
398
- ) || this.sendBtpsResponse(resCtx.socket, {
465
+ )) && this.sendBtpsResponse(resCtx.socket, {
399
466
  ...this.prepareBtpsResponse({ ok: !0, message: "success", code: 200 }, resCtx.reqId),
400
467
  type: "btps_response"
401
468
  });
@@ -494,111 +561,64 @@ class BtpsServer {
494
561
  if (artifact.action === "auth.request")
495
562
  return { isTrusted: !0, error: void 0 };
496
563
  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)
564
+ if (!trustRecord)
508
565
  return {
509
- isValid: !1,
510
- error: new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY, {
511
- cause: `Attestor ${attestation.signedBy} public key not found`,
512
- meta: { attestation }
566
+ isTrusted: !1,
567
+ error: new BTPErrorException(BTP_ERROR_TRUST_NOT_ALLOWED, {
568
+ cause: `Agent ${agentId} not trusted`,
569
+ meta: { agentId, to, computedTrustId }
513
570
  })
514
571
  };
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
- };
572
+ if (!isTrustActive(trustRecord)) return { isTrusted: !1, error: void 0 };
573
+ const carried = artifact.document;
574
+ 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 };
575
+ }
576
+ async verifyDocumentSend(carried) {
577
+ const record = await this.trustStore.getById(computeTrustId(carried.from, carried.to)), refusal = isTrustActive(record) && record && documentTypeRefusal(carried, record);
578
+ return refusal ? {
579
+ isTrusted: !1,
580
+ error: new BTPErrorException(refusal.error, { cause: refusal.problem })
581
+ } : { isTrusted: !0, error: void 0 };
582
+ }
583
+ async verifyDetailsSend(carried) {
584
+ const { from, to } = carried, records = await Promise.all([
585
+ this.trustStore.getById(computeTrustId(from, to)),
586
+ this.trustStore.getById(computeTrustId(to, from))
587
+ ]), active = records.filter(isTrustActive), record = active.find((r) => r?.permissions) ?? active[0];
588
+ if (!record) return { isTrusted: !1, error: this.getTrustRefusalError(records[0]) };
589
+ const refuse = (refusal) => ({
590
+ isTrusted: !1,
591
+ error: new BTPErrorException(refusal.error, { cause: refusal.problem })
592
+ }), { permissions } = record, asReceiver = permissions && {
593
+ permissions: {
594
+ ...permissions,
595
+ detailsHeld: permissions.detailsShared,
596
+ detailsShared: permissions.detailsHeld
597
+ }
598
+ }, namesRefusal = detailsNamesRefusal(carried, asReceiver ?? {});
599
+ if (namesRefusal) return refuse(namesRefusal);
600
+ if (carried.type !== "DETAILS_RES") return { isTrusted: !0, error: void 0 };
601
+ const query = { artifactId: carried.relatesTo ?? "", from: to, to: from };
602
+ return await this.trustStore.isKnownArtifact(query) ? { isTrusted: !0, error: void 0 } : refuse({
603
+ error: BTP_ERROR_PERMISSION,
604
+ problem: "a details response answers a request its sender received"
605
+ });
606
+ }
607
+ async verifyAttestation(delegation) {
608
+ return verifyAttestation(delegation, this.keyResolver, this.keyChains);
523
609
  }
524
610
  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
- };
611
+ return verifyDelegation(artifactWithDelegation, this.keyResolver, this.keyChains);
592
612
  }
593
613
  async verifySignature(data) {
594
614
  const { artifact, type } = data;
595
615
  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) };
616
+ const { isValid, error } = await verifyTransporterSignature(
617
+ artifact,
618
+ this.keyResolver,
619
+ this.keyChains
620
+ );
621
+ return { isValid, error };
602
622
  }
603
623
  async verifyEventRelation(data) {
604
624
  if (data.type !== "transporter" || data.artifact.type !== "BTPS_EVENT")
@@ -611,15 +631,65 @@ class BtpsServer {
611
631
  meta: { relatesTo, from, to }
612
632
  })
613
633
  };
634
+ }
635
+ async verifyDetailsTrust(artifact) {
636
+ const { from, to } = artifact, records = await Promise.all([
637
+ this.trustStore.getById(computeTrustId(from, to)),
638
+ this.trustStore.getById(computeTrustId(to, from))
639
+ ]), active = records.filter(isTrustActive), record = active.find((r) => r?.permissions) ?? active[0];
640
+ if (!record) return { isTrusted: !1, error: this.getTrustRefusalError(records[0]) };
641
+ const refuse = (refusal) => ({
642
+ isTrusted: !1,
643
+ error: new BTPErrorException(refusal.error, { cause: refusal.problem })
644
+ }), namesRefusal = detailsNamesRefusal(artifact, record);
645
+ if (namesRefusal) return refuse(namesRefusal);
646
+ if (artifact.type === "DETAILS_RES") {
647
+ const query = { artifactId: artifact.relatesTo ?? "", from: to, to: from };
648
+ if (!await this.trustStore.isKnownArtifact(query))
649
+ return refuse({
650
+ error: BTP_ERROR_PERMISSION,
651
+ problem: "a details response answers a request its receiver sent"
652
+ });
653
+ }
654
+ return this.verifyPrivacyType(artifact, record);
655
+ }
656
+ tellDetails({ type, artifact }) {
657
+ const at = ( new Date()).toISOString();
658
+ if (type === "transporter" && artifact.type === "DETAILS_REQ") {
659
+ const { from, to, details = [] } = artifact;
660
+ this.tell("detailsRequested", { from, to, names: [...details], at });
661
+ }
662
+ const carried = type === "agent" ? artifact.document : void 0;
663
+ if (carried?.type === "DETAILS_RES") {
664
+ const { from, to, details = [] } = carried;
665
+ this.tell("detailsShared", { from, to, names: [...details], at });
666
+ }
667
+ }
668
+ tell(event, info) {
669
+ for (const listener of this.events.listeners(event))
670
+ try {
671
+ listener(info);
672
+ } catch (error) {
673
+ console.warn(`[BtpsServer] Warning: a ${event} listener threw:`, error);
674
+ }
675
+ }
676
+ on(event, listener) {
677
+ this.events.on(event, listener);
678
+ }
679
+ off(event, listener) {
680
+ this.events.off(event, listener);
614
681
  }
615
682
  async verifyTrust(data) {
616
683
  const { artifact, type } = data;
617
684
  if (type === "agent") return this.verifyAgentTrust(artifact);
685
+ if (DETAILS_ARTIFACT_TYPES.includes(artifact.type))
686
+ return this.verifyDetailsTrust(artifact);
618
687
  if (artifact.type === "TRUST_RES") {
619
688
  const { isValid, error } = await validateTrustResponse(
620
689
  artifact.from,
621
690
  artifact.to,
622
- this.trustStore
691
+ this.trustStore,
692
+ artifact
623
693
  );
624
694
  return { isTrusted: isValid, error };
625
695
  }
@@ -629,10 +699,35 @@ class BtpsServer {
629
699
  if (isTrustActive(ownTrust)) return this.verifyPrivacyType(artifact, ownTrust);
630
700
  }
631
701
  if (artifact.type === "TRUST_REQ") {
632
- const { isValid, error } = validateTrustRequest(trustRecord);
702
+ const owes = await this.detailsOwedByPerson(artifact);
703
+ if (owes) return { isTrusted: !1, error: owes };
704
+ const { isValid, error } = validateTrustRequest(trustRecord, artifact);
633
705
  return { isTrusted: isValid, error };
634
- } else
635
- return isTrustActive(trustRecord) ? this.verifyPrivacyType(artifact, trustRecord) : { isTrusted: !1, error: this.getTrustRefusalError(trustRecord) };
706
+ } else {
707
+ if (!isTrustActive(trustRecord))
708
+ return { isTrusted: !1, error: this.getTrustRefusalError(trustRecord) };
709
+ const refusal = trustRecord && documentTypeRefusal(artifact, trustRecord);
710
+ return refusal ? {
711
+ isTrusted: !1,
712
+ error: new BTPErrorException(refusal.error, { cause: refusal.problem })
713
+ } : this.verifyPrivacyType(artifact, trustRecord);
714
+ }
715
+ }
716
+ async detailsOwedByPerson(artifact) {
717
+ const { permissions, entityType, given } = artifact;
718
+ if (!permissions || entityType !== "person") return;
719
+ const [first] = detailsOwed(permissions, entityType, given);
720
+ if (!first) return;
721
+ let receiver;
722
+ try {
723
+ receiver = await this.entityTypeOf?.(artifact.to);
724
+ } catch {
725
+ receiver = void 0;
726
+ }
727
+ if (receiver !== "organisation")
728
+ return new BTPErrorException(BTP_ERROR_VALIDATION, {
729
+ cause: `asks for ${first.asked} without giving ${first.owed}`
730
+ });
636
731
  }
637
732
  verifyPrivacyType(artifact, trustRecord) {
638
733
  const required = trustRecord?.privacyType, sent = artifact.encryption ? "encrypted" : "unencrypted";
@@ -674,6 +769,9 @@ class BtpsServer {
674
769
  }
675
770
  acceptsArtifacts(type) {
676
771
  return this.emitter.listenerCount(type === "agent" ? "agentArtifact" : "transporterArtifact") > 0 || this.handlerFn !== null || this.middlewareManager.getMiddleware("before", "onArtifact").length > 0;
772
+ }
773
+ takesErrors() {
774
+ return this.onError !== void 0 || this.middlewareManager.getMiddleware("before", "onError").length > 0 || this.middlewareManager.getMiddleware("after", "onError").length > 0;
677
775
  }
678
776
  noHandlerWarning(type) {
679
777
  const name = type === "agent" ? "Agent" : "Transporter";
@@ -702,7 +800,7 @@ class BtpsServer {
702
800
  let type;
703
801
  if (isBtpsControlArtifact(data) ? type = "control" : isBtpsTransportArtifact(data) ? type = "transporter" : isBtpsIdentityRequest(data) ? type = "identityLookup" : isBtpsAgentArtifact(data) && (type = "agent"), !type)
704
802
  return { error: "VALIDATION", data };
705
- if (!validate(BtpArtifactServerSchema, data).success)
803
+ if (!validate(BtpArtifactSchemaByType[type], data).success)
706
804
  return {
707
805
  error: "VALIDATION",
708
806
  data: type === "agent" ? { artifact: data, type, respondNow: !1 } : { artifact: data, type }
@@ -747,16 +845,36 @@ class BtpsServer {
747
845
  res
748
846
  );
749
847
  }
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 } : {
848
+ wireStatus(error, fromMiddleware = !1) {
849
+ const status = this.errorStatus(error, fromMiddleware), retryAfter = error instanceof BTPErrorException ? error.meta?.retryAfter : void 0;
850
+ return status.code === 429 && typeof retryAfter == "number" && Number.isSafeInteger(retryAfter) && retryAfter >= 0 ? { ...status, retryAfter } : status;
851
+ }
852
+ errorStatus(error, fromMiddleware) {
853
+ if (fromMiddleware && !(error instanceof Error)) {
854
+ if (error.status && typeof error.code == "string")
855
+ return { ok: !1, code: error.status, message: error.message, error: error.code };
856
+ if (typeof error.code == "number")
857
+ return { ok: !1, code: error.code, message: error.message };
858
+ }
859
+ const constant = typeof error.code == "string" ? BTPS_ERRORS_BY_CODE.get(error.code) : void 0;
860
+ if (constant?.status !== void 0) {
861
+ const ownMessage = error.message === constant.message || error.message.startsWith(`${constant.message}: `);
862
+ return {
863
+ ok: !1,
864
+ code: constant.status,
865
+ message: ownMessage ? error.message : constant.message,
866
+ error: String(constant.code)
867
+ };
868
+ }
869
+ return {
752
870
  ok: !1,
753
871
  code: BTP_ERROR_UNKNOWN.status ?? 500,
754
872
  message: BTP_ERROR_UNKNOWN.message,
755
873
  error: String(BTP_ERROR_UNKNOWN.code)
756
874
  };
757
875
  }
758
- async sendBtpsError(socket, error, reqId, action) {
759
- const response = this.prepareBtpsResponse(this.wireStatus(error), reqId);
876
+ async sendBtpsError(socket, error, reqId, action, fromMiddleware = !1) {
877
+ const response = this.prepareBtpsResponse(this.wireStatus(error, fromMiddleware), reqId);
760
878
  this.sendBtpsResponse(
761
879
  socket,
762
880
  {
@@ -766,25 +884,59 @@ class BtpsServer {
766
884
  action
767
885
  );
768
886
  }
769
- sendBtpsResponse(socket, artifact, action) {
887
+ sendBtpsResponse(socket, response, action) {
770
888
  if (socket.destroyed || socket.writableEnded || !socket.writable) return;
771
- const validationResult = validate(BtpServerResponseSchema, artifact);
889
+ const artifact = action && !response.signature && !isVersionBelow(response.version, "1.2.0") ? { ...response, status: { ...response.status, closing: !0 } } : response, validationResult = validate(BtpServerResponseSchema, artifact);
772
890
  if (!validationResult.success) {
773
891
  const error = new BTPErrorException(BTP_ERROR_VALIDATION, {
774
892
  cause: "Invalid server response format",
775
893
  meta: { validationErrors: validationResult.error.errors, response: artifact }
776
894
  });
777
- this.onError?.(error), socket.destroyed || socket.destroy();
895
+ if (this.onError?.(error), artifact.type === "btps_error" && artifact.status?.error === BTP_ERROR_UNKNOWN.code) {
896
+ socket.destroyed || socket.destroy();
897
+ return;
898
+ }
899
+ const reqId = typeof artifact.reqId == "string" ? artifact.reqId : void 0;
900
+ this.sendBtpsError(socket, BTP_ERROR_UNKNOWN, reqId, action);
901
+ return;
902
+ }
903
+ if (!this.signAnswers) {
904
+ this.writeAnswer(socket, artifact, action);
778
905
  return;
779
906
  }
907
+ const answer = (this.answersOnSocket.get(socket) ?? Promise.resolve()).then(async () => {
908
+ if (socket.destroyed || socket.writableEnded) return;
909
+ const signed = artifact.signature ? artifact : await this.signAnswer(artifact);
910
+ this.writeAnswer(socket, signed, action);
911
+ }).catch((err) => this.onError?.(transformToBTPErrorException(err)));
912
+ this.answersOnSocket.set(socket, answer);
913
+ }
914
+ async signAnswer(artifact) {
915
+ const unsigned = {
916
+ ...artifact,
917
+ signedBy: this.serverIdentity.identity,
918
+ selector: this.serverIdentity.selector
919
+ };
780
920
  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();
921
+ const signature = "signer" in this.serverIdentity ? await signBtpPayloadWithSigner(unsigned, this.serverIdentity.signer) : signBtpPayload(unsigned, {
922
+ publicKey: this.serverIdentity.publicKey,
923
+ privateKey: this.serverIdentity.privateKey
924
+ });
925
+ return { ...unsigned, signature };
926
+ } catch (error) {
927
+ return this.onError?.(transformToBTPErrorException(error)), artifact;
787
928
  }
929
+ }
930
+ writeAnswer(socket, artifact, action) {
931
+ if (!(socket.destroyed || socket.writableEnded || !socket.writable))
932
+ try {
933
+ socket.write(JSON.stringify(artifact) + `
934
+ `), this.middlewareManager.onResponseSent(artifact), action && (action === "destroy" ? socket.destroy() : (socket.end(), setTimeout(() => {
935
+ socket.destroyed || socket.destroy();
936
+ }, this.connectionTimeoutMs)));
937
+ } catch (err) {
938
+ this.onError?.(transformToBTPErrorException(err)), socket.destroyed || socket.destroy();
939
+ }
788
940
  }
789
941
  getProtocolVersion() {
790
942
  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';