@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
@@ -12,6 +12,8 @@ import {
12
12
  getBtpAddressParts,
13
13
  getDnsIdentityParts,
14
14
  getHostAndSelector,
15
+ isBtpsAgentArtifact,
16
+ isBtpsTransportArtifact,
15
17
  isValidIdentity,
16
18
  resolvePublicKey
17
19
  } from "../core/utils/index.js";
@@ -26,19 +28,28 @@ import {
26
28
  BTP_ERROR_SOCKET_TIMEOUT,
27
29
  BTP_ERROR_TIMEOUT,
28
30
  BTP_ERROR_VALIDATION,
31
+ BTP_ERROR_VERSION_UNSUPPORTED,
29
32
  BTPErrorException,
30
33
  transformToBTPErrorException
31
34
  } from "../core/error/index.js";
32
- import { BTP_PROTOCOL_VERSION } from "../core/server/constants/index.js";
35
+ import {
36
+ BTP_PROTOCOL_VERSION,
37
+ DEFAULT_MAX_ARTIFACT_AGE_SECONDS,
38
+ MIN_SUPPORTED_VERSION,
39
+ artifactVersion,
40
+ isVersionBelow
41
+ } from "../core/server/constants/index.js";
33
42
  import { randomUUID } from "crypto";
34
43
  import isEmpty from "lodash/isEmpty.js";
35
44
  import { decryptVerify } from "../core/crypto/decryptVerify.js";
36
45
  import { assertStrictJson } from "../core/crypto/jcs.js";
37
46
  import { validate } from "../core/utils/validation.js";
38
47
  import { BtpArtifactServerSchema } from "../core/server/schemas/artifacts/artifacts.js";
48
+ import { sameIdentity } from "../core/server/schemas/helpers.js";
39
49
  import {
40
50
  DEFAULT_CONNECT_TIMEOUT_MS,
41
51
  DEFAULT_REPLY_TIMEOUT_MS,
52
+ KEY_CHAIN_REPLY_TIMEOUT_MS,
42
53
  MIN_CONNECT_TIMEOUT_MS,
43
54
  MIN_REPLY_TIMEOUT_MS,
44
55
  resolveTimeoutMs
@@ -66,7 +77,6 @@ class BtpsClient {
66
77
  socket;
67
78
  emitter = new EventEmitter();
68
79
  retries = 0;
69
- backpressureQueue = [];
70
80
  states = {
71
81
  isConnecting: !1,
72
82
  isConnected: !1,
@@ -150,11 +160,9 @@ class BtpsClient {
150
160
  });
151
161
  }
152
162
  attachListeners(socket) {
153
- socket.pipe(split2()).on("data", (line) => void this.onData(line)), socket.on("drain", () => {
154
- this.flushBackpressure();
155
- });
163
+ socket.pipe(split2()).on("data", (line) => void this.onData(line, socket));
156
164
  const over = (error) => {
157
- this.socket === socket && (this.states.isConnected = !1, this.states.isConnecting = !1, this.backpressureQueue = []), Promise.allSettled([...this.reading]).then(() => this.failSendsOn(socket, error));
165
+ this.socket === socket && (this.states.isConnected = !1, this.states.isConnecting = !1), Promise.allSettled([...this.reading]).then(() => this.failSendsOn(socket, error));
158
166
  };
159
167
  socket.on("error", (err) => {
160
168
  const error = transformToBTPErrorException(err);
@@ -174,8 +182,8 @@ class BtpsClient {
174
182
  pending.socket === socket && (clearTimeout(pending.timeout), this.queue.delete(id), pending.resolve({ response: void 0, error }));
175
183
  this.unrefSocketIfNoQueue();
176
184
  }
177
- async onData(line) {
178
- const read = this.readLine(line);
185
+ async onData(line, socket) {
186
+ const read = this.readLine(line, socket);
179
187
  this.reading.add(read);
180
188
  try {
181
189
  await read;
@@ -183,18 +191,20 @@ class BtpsClient {
183
191
  this.reading.delete(read);
184
192
  }
185
193
  }
186
- async readLine(line) {
194
+ async readLine(line, socket) {
187
195
  if (line.trim())
188
196
  try {
189
197
  assertStrictJson(line);
190
198
  const msg = JSON.parse(line);
191
199
  this.states.shouldRetry = !1;
192
- const { isValid: validSignature, error } = await this.verifyServerMessage(msg), reqId = msg?.reqId ?? (msg?.type === "btps_error" && this.queue.size === 1 ? this.queue.keys().next().value : void 0);
200
+ const { isValid: validSignature, error } = await this.verifyServerMessage(msg);
201
+ validSignature && msg?.status?.closing === !0 && socket && this.socket === socket && (this.states.isConnected = !1);
202
+ const reqId = msg?.reqId ?? (msg?.type === "btps_error" && this.queue.size === 1 ? this.queue.keys().next().value : void 0);
193
203
  if (reqId && this.queue.has(reqId)) {
194
204
  const pendingMsg = { ...this.queue.get(reqId) }, { resolve, timeout } = pendingMsg;
195
205
  this.queue.delete(reqId), clearTimeout(timeout), resolve({
196
206
  response: validSignature ? msg : void 0,
197
- error: validSignature ? void 0 : error
207
+ error: validSignature ? this.versionRefusal(msg) : error
198
208
  }), this.unrefSocketIfNoQueue();
199
209
  } else
200
210
  this.emitter.emit("message", { response: msg, validSignature, error });
@@ -205,20 +215,6 @@ class BtpsClient {
205
215
  }
206
216
  unrefSocketIfNoQueue() {
207
217
  this.queue.size === 0 && this.socket && !this.socket.destroyed && this.socket.unref();
208
- }
209
- async flushBackpressure() {
210
- if (!this.states.isDraining) {
211
- this.states.isDraining = !0;
212
- try {
213
- for (; this.backpressureQueue.length && this.socket?.writable; ) {
214
- const chunk = this.backpressureQueue.shift();
215
- if (!chunk) break;
216
- this.socket.write(chunk) || await new Promise((resolve) => this.socket.once("drain", resolve));
217
- }
218
- } finally {
219
- this.states.isDraining = !1;
220
- }
221
- }
222
218
  }
223
219
  cleanupQueue(resolveError) {
224
220
  if (this.queue.size !== 0) {
@@ -325,9 +321,8 @@ class BtpsClient {
325
321
  );
326
322
  return;
327
323
  }
328
- const serialized = JSON.stringify(artifact) + `
329
- `;
330
- this.socket?.write(serialized) || (this.backpressureQueue.push(serialized), this.states.isDraining = !0);
324
+ this.socket?.write(JSON.stringify(artifact) + `
325
+ `);
331
326
  }
332
327
  async dispatch(job) {
333
328
  const { artifact, resolve, timeoutMs } = job, id = artifact.id, timeout = setTimeout(() => {
@@ -365,9 +360,19 @@ class BtpsClient {
365
360
  "signature verification failed",
366
361
  "destroyed"
367
362
  ].some((m) => message.includes(m));
363
+ }
364
+ signatureKey(identity, selector) {
365
+ return this.options.keyResolver ? this.options.keyResolver.resolvePublicKey(identity, selector, "verify") : resolvePublicKey(identity, selector);
368
366
  }
369
367
  async verifyServerMessage(msg) {
370
- const { signature, signedBy, selector } = msg;
368
+ const { signature, signedBy, selector } = msg, required = this.options.requireSignedBy, isRequiredSigner = signedBy?.toLowerCase() === required?.identity.toLowerCase() && selector === required?.selector;
369
+ if (required && (!signature || !isRequiredSigner))
370
+ return {
371
+ isValid: !1,
372
+ error: new BTPErrorException(BTP_ERROR_SIG_VERIFICATION, {
373
+ cause: signature ? `the answer is signed by ${signedBy} under ${selector}, not by ${required.identity} under ${required.selector}` : `the answer is not signed, and ${required.identity} must sign every answer`
374
+ })
375
+ };
371
376
  if (!msg.signature)
372
377
  return {
373
378
  isValid: !0,
@@ -376,7 +381,7 @@ class BtpsClient {
376
381
  if (signature && signedBy && selector) {
377
382
  let senderPubPem, error;
378
383
  try {
379
- senderPubPem = await resolvePublicKey(signedBy, selector), senderPubPem || (error = new BTPErrorException(BTP_ERROR_SIG_VERIFICATION, {
384
+ senderPubPem = await this.signatureKey(signedBy, selector), senderPubPem || (error = new BTPErrorException(BTP_ERROR_SIG_VERIFICATION, {
380
385
  cause: `Failed to resolve public key for identity: ${signedBy} and selector: ${selector}`,
381
386
  meta: msg
382
387
  }));
@@ -413,15 +418,49 @@ class BtpsClient {
413
418
  }
414
419
  validateArtifact(artifact) {
415
420
  const validationResult = validate(BtpArtifactServerSchema, artifact);
416
- return validationResult.success ? { isValid: !0, error: void 0 } : {
421
+ if (!validationResult.success)
422
+ return {
423
+ isValid: !1,
424
+ error: new BTPErrorException(BTP_ERROR_VALIDATION, {
425
+ cause: "Invalid artifact",
426
+ meta: validationResult.error.issues.reduce(
427
+ (acc, issue) => (acc[issue.path.join(".")] = issue.message, acc),
428
+ {}
429
+ )
430
+ })
431
+ };
432
+ const understamped = this.understamped(artifact);
433
+ return understamped ? {
417
434
  isValid: !1,
418
- error: new BTPErrorException(BTP_ERROR_VALIDATION, {
419
- cause: "Invalid artifact",
420
- meta: validationResult.error.issues.reduce(
421
- (acc, issue) => (acc[issue.path.join(".")] = issue.message, acc),
422
- {}
423
- )
424
- })
435
+ error: new BTPErrorException(BTP_ERROR_VALIDATION, { cause: understamped })
436
+ } : { isValid: !0, error: void 0 };
437
+ }
438
+ understamped(artifact) {
439
+ const carried = isBtpsAgentArtifact(artifact) ? artifact.document : void 0, transporter = isBtpsTransportArtifact(carried) ? carried : artifact;
440
+ if (!isBtpsTransportArtifact(transporter)) return;
441
+ const needed = artifactVersion({ ...transporter });
442
+ if (isVersionBelow(transporter.version, needed))
443
+ return `stamped ${transporter.version}, but it uses what ${needed} adds`;
444
+ if (transporter !== artifact && isVersionBelow(artifact.version, transporter.version))
445
+ return `an agent artifact stamped ${artifact.version} carries one stamped ${transporter.version}`;
446
+ }
447
+ versionRefusal(msg) {
448
+ if (!(msg.type !== "btps_error" || msg.status?.error !== BTP_ERROR_VERSION_UNSUPPORTED.code))
449
+ return new BTPErrorException(BTP_ERROR_VERSION_UNSUPPORTED, {
450
+ cause: msg.status.message,
451
+ meta: { receiverVersion: msg.version }
452
+ });
453
+ }
454
+ async getServerVersion() {
455
+ const ping = {
456
+ version: MIN_SUPPORTED_VERSION,
457
+ id: randomUUID(),
458
+ issuedAt: ( new Date()).toISOString(),
459
+ action: "PING"
460
+ }, { response, error } = await this.send(ping);
461
+ return response?.version ? { version: response.version, error: void 0 } : {
462
+ version: void 0,
463
+ error: error ?? new BTPErrorException(BTP_ERROR_VALIDATION, { cause: "no answer to PING" })
425
464
  };
426
465
  }
427
466
  async send(artifact, timeoutMs) {
@@ -468,7 +507,17 @@ class BtpsClient {
468
507
  new BTPErrorException({ message: `invalid hostname: ${hostname}` })
469
508
  );
470
509
  try {
471
- const dnsIdentityParts = await getDnsIdentityParts(identity, selector);
510
+ const resolved = await this.options.keyResolver?.resolvePublicKey(
511
+ identity,
512
+ selector,
513
+ "encrypt"
514
+ );
515
+ if (resolved)
516
+ return {
517
+ response: { keyType: "rsa", publicKey: resolved, selector, version, hostname, port },
518
+ error: void 0
519
+ };
520
+ const dnsIdentityParts = this.options.keyResolver ? void 0 : await getDnsIdentityParts(identity, selector);
472
521
  if (dnsIdentityParts && typeof dnsIdentityParts == "object") {
473
522
  const { key, version: version2, pem } = dnsIdentityParts;
474
523
  return {
@@ -484,126 +533,195 @@ class BtpsClient {
484
533
  };
485
534
  }
486
535
  const { operator } = btpHostDnsConfig;
487
- return operator ? await new Promise((resolve) => {
488
- const socket = tls.connect({ ...this.options.btpMtsOptions, host: hostname, port });
489
- let settled = !1;
490
- const settle = (value) => {
491
- settled = !0, socket.destroy(), resolve(value);
492
- }, fail = (error) => {
493
- settled || settle(this.buildClientErrorResponse(error));
494
- }, identityLookupRequest = {
495
- identity,
496
- from,
497
- hostSelector: selector,
498
- version: BTP_PROTOCOL_VERSION,
499
- id: randomUUID(),
500
- issuedAt: ( new Date()).toISOString()
501
- };
502
- socket.write(JSON.stringify(identityLookupRequest) + `
536
+ if (!operator)
537
+ return await this.buildClientErrorResponse(
538
+ new BTPErrorException(BTP_ERROR_IDENTITY_NOT_FOUND, {
539
+ cause: `${identity} has no key in DNS, and its domain declares no operator to answer for it`
540
+ })
541
+ );
542
+ const host = { hostname, port, selector, operator };
543
+ let asked = await this.askHost(identity, from, host, BTP_PROTOCOL_VERSION, receiverKey);
544
+ return asked.kind === "refused" && asked.code === BTP_ERROR_VERSION_UNSUPPORTED.code && (asked = await this.askHost(identity, from, host, MIN_SUPPORTED_VERSION, receiverKey)), asked.kind !== "answer" ? await this.buildClientErrorResponse(asked.error) : {
545
+ response: {
546
+ ...asked.document,
547
+ hostname,
548
+ port,
549
+ version,
550
+ serverVersion: asked.serverVersion
551
+ },
552
+ error: void 0
553
+ };
554
+ } catch (error) {
555
+ return await this.buildClientErrorResponse(transformToBTPErrorException(error));
556
+ }
557
+ }
558
+ async lookupKeyChain(identity, from, options = {}) {
559
+ if (!isValidIdentity(identity))
560
+ return { status: "invalid", reason: `invalid identity: ${identity}` };
561
+ if (!isValidIdentity(from))
562
+ return { status: "unavailable", reason: `cannot ask as ${from}: not an address` };
563
+ let dns;
564
+ try {
565
+ dns = await this.resolveBtpsHostDnsTxt(identity);
566
+ } catch (error) {
567
+ return { status: "unavailable", reason: transformToBTPErrorException(error).message };
568
+ }
569
+ if (!dns?.hostname || !dns.operator)
570
+ return { status: "unavailable", reason: `${identity}'s domain names no host or operator` };
571
+ const { hostname, port, selector, operator } = dns, asked = await this.askHost(
572
+ identity,
573
+ from,
574
+ { hostname, port, selector, operator },
575
+ BTP_PROTOCOL_VERSION,
576
+ void 0,
577
+ !0,
578
+ {
579
+ connectMs: this.connectTimeoutMs,
580
+ replyMs: options.replyTimeoutMs ?? KEY_CHAIN_REPLY_TIMEOUT_MS
581
+ }
582
+ );
583
+ if (asked.kind === "answer")
584
+ return { status: "chain", records: asked.document.keyChain ?? [], answer: asked.response };
585
+ const { message, cause } = asked.error, reason = typeof cause == "string" ? `${message}: ${cause}` : message;
586
+ return asked.kind === "failed" ? { status: "invalid", reason } : { status: "unavailable", reason };
587
+ }
588
+ askHost(identity, from, host, lookupVersion, receiverKey, keyChain, timeouts = { connectMs: this.connectTimeoutMs, replyMs: this.replyTimeoutMs }) {
589
+ const { hostname, port, selector, operator } = host;
590
+ return new Promise((resolve) => {
591
+ const socket = tls.connect({ ...this.options.btpMtsOptions, host: hostname, port });
592
+ let settled = !1;
593
+ const settle = (value) => {
594
+ settled || (settled = !0, clearTimeout(timer), socket.destroy(), resolve(value));
595
+ }, fail = (error) => settle({ kind: "failed", error }), giveUp = (what, ms) => setTimeout(
596
+ () => settle({
597
+ kind: "unreachable",
598
+ error: new BTPErrorException(BTP_ERROR_TIMEOUT, {
599
+ cause: `${hostname} did not ${what} within ${ms} ms`
600
+ })
601
+ }),
602
+ ms
603
+ );
604
+ let timer = giveUp("take the connection", timeouts.connectMs), connected = !1;
605
+ const replying = () => {
606
+ connected || (connected = !0, clearTimeout(timer), timer = giveUp("answer the lookup", timeouts.replyMs));
607
+ };
608
+ socket.once("connect", replying), socket.once("secureConnect", replying);
609
+ const identityLookupRequest = {
610
+ identity,
611
+ from,
612
+ hostSelector: selector,
613
+ version: lookupVersion,
614
+ id: randomUUID(),
615
+ issuedAt: ( new Date()).toISOString(),
616
+ ...keyChain && { keyChain }
617
+ };
618
+ socket.write(JSON.stringify(identityLookupRequest) + `
503
619
  `);
504
- let received = "", answerRead = !1;
505
- socket.on("data", async (chunk) => {
506
- received += chunk.toString();
507
- const end = received.indexOf(`
620
+ let received = "", answerRead = !1;
621
+ socket.on("data", async (chunk) => {
622
+ received += chunk.toString();
623
+ const end = received.indexOf(`
508
624
  `);
509
- if (end !== -1) {
510
- socket.removeAllListeners("data"), answerRead = !0;
511
- try {
512
- await verifyAnswer(received.slice(0, end));
513
- } catch (error) {
514
- fail(transformToBTPErrorException(error));
515
- }
516
- }
517
- });
518
- const verifyAnswer = async (line) => {
519
- let msg;
625
+ if (end !== -1) {
626
+ socket.removeAllListeners("data"), answerRead = !0;
520
627
  try {
521
- assertStrictJson(line), msg = JSON.parse(line);
628
+ await verifyAnswer(received.slice(0, end));
522
629
  } catch (error) {
523
- fail(new BTPErrorException(BTP_ERROR_VALIDATION, { cause: error }));
524
- return;
525
- }
526
- const { signature, signedBy, selector: signedWith, type, status } = msg;
527
- if (type === "btps_error" || !status.ok) {
528
- fail(
529
- new BTPErrorException(BTP_ERROR_IDENTITY_NOT_FOUND, {
530
- cause: `Server returned error for identity: ${identity}`,
531
- meta: msg
532
- })
533
- );
534
- return;
630
+ fail(transformToBTPErrorException(error));
535
631
  }
536
- if (!signature || !signedBy || !signedWith) {
537
- fail(
538
- new BTPErrorException(BTP_ERROR_VALIDATION, {
539
- cause: "Message is not signed or does not have signedBy",
540
- meta: msg
541
- })
542
- );
543
- return;
544
- }
545
- if (signedBy !== operator) {
546
- fail(
547
- new BTPErrorException(BTP_ERROR_SIG_VERIFICATION, {
548
- cause: `The answer is signed by ${signedBy}, not by ${operator}, the operator of ${identity}'s domain`
549
- })
550
- );
551
- return;
552
- }
553
- const hostPubPem = await resolvePublicKey(signedBy, signedWith);
554
- if (!hostPubPem) {
555
- fail(
556
- new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY, {
557
- cause: `SignedBy is present but public key is not found for identity: ${signedBy} and selector: ${signedWith}`,
558
- meta: msg
559
- })
560
- );
561
- return;
562
- }
563
- const { payload: decryptedPayload, error: decryptError } = await this.decryptVerifyArtifact(
564
- msg,
565
- hostPubPem,
566
- receiverKey
632
+ }
633
+ });
634
+ const verifyAnswer = async (line) => {
635
+ let msg;
636
+ try {
637
+ assertStrictJson(line), msg = JSON.parse(line);
638
+ } catch (error) {
639
+ fail(new BTPErrorException(BTP_ERROR_VALIDATION, { cause: error }));
640
+ return;
641
+ }
642
+ const { signature, signedBy, selector: signedWith, type, status } = msg;
643
+ if (type === "btps_error" || !status.ok) {
644
+ settle({
645
+ kind: "refused",
646
+ code: status?.error,
647
+ error: new BTPErrorException(BTP_ERROR_IDENTITY_NOT_FOUND, {
648
+ cause: `Server returned error for identity: ${identity}`,
649
+ meta: msg
650
+ })
651
+ });
652
+ return;
653
+ }
654
+ if (!signature || !signedBy || !signedWith) {
655
+ fail(
656
+ new BTPErrorException(BTP_ERROR_VALIDATION, {
657
+ cause: "Message is not signed or does not have signedBy",
658
+ meta: msg
659
+ })
567
660
  );
568
- if (decryptError) {
569
- fail(decryptError);
570
- return;
571
- }
572
- const { document } = decryptedPayload || {};
573
- if (!document) {
661
+ return;
662
+ }
663
+ if (signedBy !== operator) {
664
+ fail(
665
+ new BTPErrorException(BTP_ERROR_SIG_VERIFICATION, {
666
+ cause: `The answer is signed by ${signedBy}, not by ${operator}, the operator of ${identity}'s domain`
667
+ })
668
+ );
669
+ return;
670
+ }
671
+ const hostPubPem = await this.signatureKey(signedBy, signedWith);
672
+ if (!hostPubPem) {
673
+ fail(
674
+ new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY, {
675
+ cause: `SignedBy is present but public key is not found for identity: ${signedBy} and selector: ${signedWith}`,
676
+ meta: msg
677
+ })
678
+ );
679
+ return;
680
+ }
681
+ const { payload: decryptedPayload, error: decryptError } = await this.decryptVerifyArtifact(
682
+ msg,
683
+ hostPubPem,
684
+ receiverKey
685
+ );
686
+ if (decryptError) {
687
+ fail(decryptError);
688
+ return;
689
+ }
690
+ const { document } = decryptedPayload || {};
691
+ if (!document) {
692
+ fail(
693
+ new BTPErrorException(BTP_ERROR_VALIDATION, {
694
+ cause: "document is not present in the message",
695
+ meta: msg
696
+ })
697
+ );
698
+ return;
699
+ }
700
+ const answered = document;
701
+ if (!isVersionBelow(lookupVersion, "1.2.0")) {
702
+ const age = Math.abs(Date.now() - Date.parse(msg.issuedAt)), problem = msg.reqId !== identityLookupRequest.id ? "it answers another lookup" : age <= DEFAULT_MAX_ARTIFACT_AGE_SECONDS * 1e3 ? answered.identity === void 0 || !sameIdentity(answered.identity, identity) ? `it does not name ${identity}` : keyChain && !Array.isArray(answered.keyChain) ? "it carries no key chain" : void 0 : "it is not fresh";
703
+ if (problem) {
574
704
  fail(
575
705
  new BTPErrorException(BTP_ERROR_VALIDATION, {
576
- cause: "document is not present in the message",
577
- meta: msg
706
+ cause: `The answer to the lookup of ${identity} is refused: ${problem}`
578
707
  })
579
708
  );
580
709
  return;
581
710
  }
582
- settle({
583
- response: {
584
- ...document,
585
- hostname,
586
- port,
587
- version
588
- },
589
- error: void 0
590
- });
591
- };
592
- socket.on("error", (err) => {
593
- answerRead || fail(transformToBTPErrorException(err));
594
- }), socket.on("close", () => {
595
- answerRead || fail(
596
- new BTPErrorException(BTP_ERROR_CONNECTION_CLOSED, { cause: "connection closed" })
597
- );
711
+ }
712
+ settle({ kind: "answer", document: answered, serverVersion: msg.version, response: msg });
713
+ };
714
+ socket.on("error", (err) => {
715
+ answerRead || settle({ kind: "unreachable", error: transformToBTPErrorException(err) });
716
+ }), socket.on("close", () => {
717
+ answerRead || settle({
718
+ kind: "unreachable",
719
+ error: new BTPErrorException(BTP_ERROR_CONNECTION_CLOSED, {
720
+ cause: "connection closed"
721
+ })
598
722
  });
599
- }) : await this.buildClientErrorResponse(
600
- new BTPErrorException(BTP_ERROR_IDENTITY_NOT_FOUND, {
601
- cause: `${identity} has no key in DNS, and its domain declares no operator to answer for it`
602
- })
603
- );
604
- } catch (error) {
605
- return await this.buildClientErrorResponse(transformToBTPErrorException(error));
606
- }
723
+ });
724
+ });
607
725
  }
608
726
  on = (event, listener) => (this.emitter.on(event, listener), this);
609
727
  off = (event, listener) => (this.emitter.off(event, listener), this);
@@ -617,7 +735,7 @@ class BtpsClient {
617
735
  this.states.isConnecting = !1, this.states.isConnected = !1, this.socket?.end(), this.socket = void 0;
618
736
  }
619
737
  destroy() {
620
- this.states.isConnecting = !1, this.states.isConnected = !1, this.states.isDestroyed = !0, this.states.shouldRetry = !1, this.states.isDraining = !1, this.backpressureQueue = [], this.removeAllListeners(), this.socket?.destroy(), this.cleanupQueue(
738
+ this.states.isConnecting = !1, this.states.isConnected = !1, this.states.isDestroyed = !0, this.states.shouldRetry = !1, this.removeAllListeners(), this.socket?.destroy(), this.cleanupQueue(
621
739
  new BTPErrorException(BTP_ERROR_CONNECTION_CLOSED, { cause: "client destroyed" })
622
740
  );
623
741
  }
@@ -9,4 +9,4 @@ export { BtpsAgent } from './btpsAgent.js';
9
9
  export { BtpsClient } from './btpsClient.js';
10
10
  export { BtpsTransporter } from './btpsTransporter.js';
11
11
  export * from './constants/index.js';
12
- export { MIN_CONNECT_TIMEOUT_MS, DEFAULT_CONNECT_TIMEOUT_MS, MIN_REPLY_TIMEOUT_MS, DEFAULT_REPLY_TIMEOUT_MS, } from './libs/timeouts.js';
12
+ export { MIN_CONNECT_TIMEOUT_MS, DEFAULT_CONNECT_TIMEOUT_MS, MIN_REPLY_TIMEOUT_MS, DEFAULT_REPLY_TIMEOUT_MS, KEY_CHAIN_REPLY_TIMEOUT_MS, } from './libs/timeouts.js';
@@ -14,7 +14,8 @@ import {
14
14
  MIN_CONNECT_TIMEOUT_MS,
15
15
  DEFAULT_CONNECT_TIMEOUT_MS,
16
16
  MIN_REPLY_TIMEOUT_MS,
17
- DEFAULT_REPLY_TIMEOUT_MS
17
+ DEFAULT_REPLY_TIMEOUT_MS,
18
+ KEY_CHAIN_REPLY_TIMEOUT_MS
18
19
  } from "./libs/timeouts.js";
19
20
  export {
20
21
  BtpsAgent,
@@ -22,6 +23,7 @@ export {
22
23
  BtpsTransporter,
23
24
  DEFAULT_CONNECT_TIMEOUT_MS,
24
25
  DEFAULT_REPLY_TIMEOUT_MS,
26
+ KEY_CHAIN_REPLY_TIMEOUT_MS,
25
27
  MIN_CONNECT_TIMEOUT_MS,
26
28
  MIN_REPLY_TIMEOUT_MS
27
29
  };