@btps/sdk 1.1.2 → 1.2.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/CHANGELOG.md +475 -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 +117 -19
  5. package/dist/client/btpsClient.d.ts +53 -7
  6. package/dist/client/btpsClient.js +266 -137
  7. package/dist/client/btpsTransporter.js +2 -1
  8. package/dist/client/index.d.ts +1 -1
  9. package/dist/client/index.js +3 -1
  10. package/dist/client/libs/schema.js +92 -15
  11. package/dist/client/libs/timeouts.d.ts +6 -0
  12. package/dist/client/libs/timeouts.js +2 -1
  13. package/dist/client/types/index.d.ts +60 -2
  14. package/dist/core/authentication/BtpsAuthentication.d.ts +43 -1
  15. package/dist/core/authentication/BtpsAuthentication.js +152 -36
  16. package/dist/core/authentication/refreshSuccessor.js +47 -0
  17. package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +17 -1
  18. package/dist/core/authentication/storage/InMemoryTokenStore.js +16 -4
  19. package/dist/core/authentication/types.d.ts +82 -0
  20. package/dist/core/crypto/contentKey.d.ts +34 -0
  21. package/dist/core/crypto/contentKey.js +64 -0
  22. package/dist/core/crypto/decryptVerify.d.ts +7 -1
  23. package/dist/core/crypto/decryptVerify.js +23 -5
  24. package/dist/core/crypto/decrypter-interface.d.ts +6 -0
  25. package/dist/core/crypto/index.d.ts +28 -3
  26. package/dist/core/crypto/index.js +34 -20
  27. package/dist/core/crypto/keyResolver.d.ts +48 -0
  28. package/dist/core/crypto/keyResolver.js +46 -0
  29. package/dist/core/crypto/pem-decrypter.d.ts +2 -0
  30. package/dist/core/crypto/pem-decrypter.js +13 -8
  31. package/dist/core/crypto/signEncrypt.d.ts +4 -1
  32. package/dist/core/crypto/signEncrypt.js +20 -5
  33. package/dist/core/crypto/types.d.ts +8 -1
  34. package/dist/core/delegation/BtpsDelegator.d.ts +4 -0
  35. package/dist/core/delegation/BtpsDelegator.js +3 -2
  36. package/dist/core/delegation/verifyTransporterSignature.d.ts +104 -0
  37. package/dist/core/delegation/verifyTransporterSignature.js +224 -0
  38. package/dist/core/error/constant.d.ts +41 -0
  39. package/dist/core/error/constant.js +60 -0
  40. package/dist/core/server/constants/btps-protocol.d.ts +21 -5
  41. package/dist/core/server/constants/btps-protocol.js +46 -8
  42. package/dist/core/server/constants/index.d.ts +7 -3
  43. package/dist/core/server/constants/index.js +19 -4
  44. package/dist/core/server/constants/limits.d.ts +41 -1
  45. package/dist/core/server/constants/limits.js +45 -2
  46. package/dist/core/server/constants/permissions.d.ts +38 -0
  47. package/dist/core/server/constants/permissions.js +38 -0
  48. package/dist/core/server/schemas/artifacts/agentSchema.js +2 -1
  49. package/dist/core/server/schemas/artifacts/artifacts.js +7 -1
  50. package/dist/core/server/schemas/artifacts/controlSchema.js +1 -1
  51. package/dist/core/server/schemas/artifacts/identityLookupSchema.js +10 -1
  52. package/dist/core/server/schemas/artifacts/transporterSchema.js +92 -12
  53. package/dist/core/server/schemas/bounded.js +41 -0
  54. package/dist/core/server/schemas/btpsDocsSchema.d.ts +34522 -1421
  55. package/dist/core/server/schemas/btpsDocsSchema.js +355 -68
  56. package/dist/core/server/schemas/helpers.d.ts +9580 -0
  57. package/dist/core/server/schemas/helpers.js +76 -12
  58. package/dist/core/server/schemas/keyChainSchema.js +53 -0
  59. package/dist/core/server/schemas/responseSchema.js +88 -12
  60. package/dist/core/server/schemas/schema.js +6 -2
  61. package/dist/core/server/schemas/trustValues.d.ts +105 -0
  62. package/dist/core/server/schemas/trustValues.js +117 -0
  63. package/dist/core/server/types.d.ts +104 -6
  64. package/dist/core/storage/AbstractIdentityStore.d.ts +9 -0
  65. package/dist/core/storage/JsonIdentityStore.d.ts +3 -0
  66. package/dist/core/storage/JsonIdentityStore.js +3 -0
  67. package/dist/core/storage/types.d.ts +2 -0
  68. package/dist/core/trust/agreements.d.ts +107 -0
  69. package/dist/core/trust/agreements.js +116 -0
  70. package/dist/core/trust/evidence.d.ts +220 -0
  71. package/dist/core/trust/evidence.js +334 -0
  72. package/dist/core/trust/index.d.ts +10 -0
  73. package/dist/core/trust/index.js +14 -1
  74. package/dist/core/trust/keyRotation.d.ts +148 -0
  75. package/dist/core/trust/keyRotation.js +267 -0
  76. package/dist/core/trust/permissions.d.ts +114 -0
  77. package/dist/core/trust/permissions.js +115 -0
  78. package/dist/core/trust/shaping.d.ts +42 -0
  79. package/dist/core/trust/shaping.js +47 -0
  80. package/dist/core/trust/storage/AbstractTrustStore.d.ts +2 -1
  81. package/dist/core/trust/storage/JsonTrustStore.d.ts +3 -2
  82. package/dist/core/trust/timestamps.d.ts +49 -0
  83. package/dist/core/trust/timestamps.js +78 -0
  84. package/dist/core/trust/trustUtils.d.ts +13 -2
  85. package/dist/core/trust/trustUtils.js +28 -3
  86. package/dist/core/trust/types.d.ts +302 -2
  87. package/dist/core/trust/verification.d.ts +52 -0
  88. package/dist/core/trust/verification.js +55 -0
  89. package/dist/server/btpsServer.d.ts +72 -6
  90. package/dist/server/btpsServer.js +280 -157
  91. package/dist/server/index.d.ts +3 -0
  92. package/dist/server/index.js +17 -1
  93. package/dist/server/libs/agreementOrderCheck.d.ts +29 -0
  94. package/dist/server/libs/agreementOrderCheck.js +29 -0
  95. package/dist/server/libs/artifactTimeWindow.d.ts +2 -2
  96. package/dist/server/libs/artifactTimeWindow.js +2 -1
  97. package/dist/server/libs/detailsRequestLimit.d.ts +27 -0
  98. package/dist/server/libs/detailsRequestLimit.js +28 -0
  99. package/dist/server/libs/detailsResponseCheck.d.ts +27 -0
  100. package/dist/server/libs/detailsResponseCheck.js +27 -0
  101. package/dist/server/libs/eventChainCheck.d.ts +31 -0
  102. package/dist/server/libs/eventChainCheck.js +39 -0
  103. package/dist/server/libs/inFlightLimit.d.ts +10 -0
  104. package/dist/server/libs/inFlightLimit.js +7 -1
  105. package/dist/server/libs/index.d.ts +5 -0
  106. package/dist/server/libs/index.js +10 -0
  107. package/dist/server/libs/keyChains.d.ts +14 -0
  108. package/dist/server/libs/keyChains.js +17 -0
  109. package/dist/server/libs/wrapForAgent.d.ts +20 -0
  110. package/dist/server/libs/wrapForAgent.js +36 -0
  111. package/dist/server/types.d.ts +95 -9
  112. package/package.json +12 -3
@@ -14,6 +14,8 @@ export declare class PemDecrypter implements Decrypter {
14
14
  private readonly privateKeyPem;
15
15
  constructor(options: PemDecrypterOptions);
16
16
  decrypt(request: DecryptRequest): Promise<Uint8Array>;
17
+ /** Since 1.2: the content key itself, unwrapped with RSA-OAEP / SHA-256. */
18
+ unwrapKey(encryptedKey: Uint8Array): Promise<Uint8Array>;
17
19
  }
18
20
  /** Rejects any tag that isn't exactly 16 bytes before it ever reaches
19
21
  * the AEAD check — a short tag is a materially weaker guarantee, not a
@@ -17,16 +17,21 @@ class PemDecrypter {
17
17
  }
18
18
  async decrypt(request) {
19
19
  assertFullLengthAuthTag(request.authTag);
20
- const aesKey = crypto.privateDecrypt(
21
- {
22
- key: this.privateKeyPem,
23
- padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
24
- oaepHash: "sha256"
25
- },
26
- Buffer.from(request.encryptedKey)
27
- );
20
+ const aesKey = Buffer.from(await this.unwrapKey(request.encryptedKey));
28
21
  return decryptAesGcm(aesKey, request);
29
22
  }
23
+ async unwrapKey(encryptedKey) {
24
+ return new Uint8Array(
25
+ crypto.privateDecrypt(
26
+ {
27
+ key: this.privateKeyPem,
28
+ padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
29
+ oaepHash: "sha256"
30
+ },
31
+ Buffer.from(encryptedKey)
32
+ )
33
+ );
34
+ }
30
35
  }
31
36
  function assertFullLengthAuthTag(authTag) {
32
37
  if (authTag.length !== AUTH_TAG_LENGTH)
@@ -8,10 +8,13 @@ import type { ConnectionOptions } from 'tls';
8
8
  import type { Signer } from './signer-interface.js';
9
9
  import { BTPCryptoResponse, PemKeys, BTPCryptoOptions } from './types.js';
10
10
  import { ParsedIdentity } from '../utils/types.js';
11
- /** How signEncrypt reaches a receiver's host when DNS has no key for it. */
11
+ import type { BtpsKeyResolver } from './keyResolver.js';
12
+ /** How signEncrypt finds a receiver's key. */
12
13
  export type ReceiverKeyLookup = {
13
14
  /** TLS options for the connection to the receiver's host */
14
15
  btpMtsOptions?: Omit<ConnectionOptions, 'port' | 'host'>;
16
+ /** Since 1.2: asked for the receiver's key (`encrypt`) in place of DNS; its host is still asked after it */
17
+ keyResolver?: BtpsKeyResolver;
15
18
  };
16
19
  /**
17
20
  * Signs an artifact with the sender's key and, when `to` and encryption
@@ -7,11 +7,13 @@
7
7
 
8
8
  import { randomUUID } from "crypto";
9
9
  import {
10
+ BTP_ERROR_DOCUMENT_TYPE_MISMATCH,
10
11
  BTP_ERROR_IDENTITY,
11
12
  BTP_ERROR_RESOLVE_PUBKEY,
12
13
  BTP_ERROR_VALIDATION
13
14
  } from "../error/constant.js";
14
15
  import { processBtpDocSchema } from "../server/schemas/helpers.js";
16
+ import { composeTrustRequestFor } from "../trust/shaping.js";
15
17
  import { signBtpPayload, signBtpPayloadWithSigner, encryptBtpPayload } from "./index.js";
16
18
  import { getHostAndSelector, parseIdentity, resolvePublicKey } from "../utils/index.js";
17
19
  import { BTPErrorException } from "../error/index.js";
@@ -20,8 +22,8 @@ const genEncryptError = (error) => ({
20
22
  payload: void 0,
21
23
  error
22
24
  }), findReceiverKey = async (to, from, selector, lookup) => {
23
- const inDns = await resolvePublicKey(to, selector);
24
- if (inDns) return inDns;
25
+ const found = lookup?.keyResolver ? await lookup.keyResolver.resolvePublicKey(to, selector, "encrypt") : await resolvePublicKey(to, selector);
26
+ if (found) return found;
25
27
  const { BtpsClient } = await import("../../client/btpsClient.js"), client = new BtpsClient({ to, btpMtsOptions: lookup?.btpMtsOptions, maxRetries: 0 });
26
28
  try {
27
29
  return (await client.resolveIdentity(to, from)).response?.publicKey;
@@ -29,10 +31,22 @@ const genEncryptError = (error) => ({
29
31
  client.destroy();
30
32
  }
31
33
  }, signEncrypt = async (to, sender, payload, options, lookup) => {
32
- const { document, ...restPayload } = payload;
34
+ const composed = to ? await composeTrustRequestFor(to, payload, {
35
+ versionFallback: options?.versionFallback,
36
+ btpMtsOptions: lookup?.btpMtsOptions
37
+ }) : { payload };
38
+ if (composed.error) return genEncryptError(composed.error);
39
+ const { shaped } = composed, { document, ...restPayload } = composed.payload;
33
40
  let encryption = null, encryptedDoc = document;
41
+ const type = document?.type;
42
+ if (restPayload.documentType !== void 0 && type !== restPayload.documentType)
43
+ return genEncryptError(
44
+ new BTPErrorException(BTP_ERROR_DOCUMENT_TYPE_MISMATCH, {
45
+ cause: `the document is a ${String(type)}, not the ${String(restPayload.documentType)} its envelope names`
46
+ })
47
+ );
34
48
  if (to && !isEmpty(options?.encryption)) {
35
- const docSchema = processBtpDocSchema(restPayload.type);
49
+ const version = typeof restPayload.version == "string" ? restPayload.version : void 0, docSchema = processBtpDocSchema(restPayload.type, version);
36
50
  if (docSchema && !docSchema.safeParse(document).success)
37
51
  return genEncryptError(
38
52
  new BTPErrorException(BTP_ERROR_VALIDATION, {
@@ -67,7 +81,8 @@ const genEncryptError = (error) => ({
67
81
  ...docToSign,
68
82
  signature
69
83
  },
70
- error: void 0
84
+ error: void 0,
85
+ ...shaped && { shaped }
71
86
  };
72
87
  };
73
88
  export {
@@ -5,7 +5,7 @@
5
5
  * https://www.apache.org/licenses/LICENSE-2.0
6
6
  */
7
7
  import { BTPErrorException } from '../error/index.js';
8
- import { BTPAgentArtifact, BTPArtifact, BTPDelegation, BTPDocType, BTPServerResponse, BTPTransporterArtifact } from '../server/types.js';
8
+ import { BTPAgentArtifact, BTPArtifact, BTPDelegation, BTPDocType, BTPServerResponse, BTPShaped, BTPTransporterArtifact } from '../server/types.js';
9
9
  import type { Signer } from './signer-interface.js';
10
10
  import type { Decrypter } from './decrypter-interface.js';
11
11
  export type EncryptionMode = 'none' | 'standardEncrypt' | '2faEncrypt';
@@ -39,6 +39,11 @@ export type BTPCryptoOptions = {
39
39
  algorithm: EncryptionAlgorithmType;
40
40
  mode: EncryptionMode;
41
41
  };
42
+ /**
43
+ * Since 1.2, for a trust request with permissions: whether to send it as 1.1 allows when the
44
+ * receiver's server speaks 1.1 (the default), or refuse with its version (`false`).
45
+ */
46
+ versionFallback?: boolean;
42
47
  };
43
48
  type WithGenericDocument<TArtifact extends BTPArtifact, T> = Omit<TArtifact, 'document'> & {
44
49
  document: T;
@@ -47,6 +52,8 @@ export type BTPCryptoArtifact<T = BTPDocType> = WithGenericDocument<BTPAgentArti
47
52
  export interface BTPCryptoResponse<T = BTPDocType> {
48
53
  payload?: BTPCryptoArtifact<T> | BTPServerResponse<T>;
49
54
  error?: BTPErrorException;
55
+ /** Since 1.2: a trust request sent as its 1.1 receiver allows, and what it left out */
56
+ shaped?: BTPShaped;
50
57
  }
51
58
  export interface VerifyEncryptedPayload<T = unknown | string> {
52
59
  document?: T;
@@ -7,12 +7,15 @@
7
7
  import type { BTPTransporterArtifact, BTPDelegation, BTPAttestation } from '../server/types.js';
8
8
  import type { BTPSigningKey, PemKeys } from '../crypto/types.js';
9
9
  import type { Signer } from '../crypto/signer-interface.js';
10
+ import type { BtpsKeyResolver } from '../crypto/keyResolver.js';
10
11
  /**
11
12
  * Delegator configuration options
12
13
  */
13
14
  export type BtpsDelegatorOptions = {
14
15
  identity: string;
15
16
  autoInit?: boolean;
17
+ /** Since 1.2: finds the delegator's own published key; without it, DNS as before */
18
+ keyResolver?: BtpsKeyResolver;
16
19
  } & ({
17
20
  privateKey: PemKeys['privateKey'];
18
21
  } | {
@@ -25,6 +28,7 @@ export type BtpsDelegatorOptions = {
25
28
  export declare class BtpsDelegator {
26
29
  private readonly identity;
27
30
  private readonly key;
31
+ private readonly keyResolver?;
28
32
  private publicKey?;
29
33
  private selector;
30
34
  private isInitialized;
@@ -12,12 +12,13 @@ import { BTP_ERROR_SIG_VERIFICATION, BTPErrorException } from "../error/index.js
12
12
  class BtpsDelegator {
13
13
  identity;
14
14
  key;
15
+ keyResolver;
15
16
  publicKey;
16
17
  selector = "btps1";
17
18
  isInitialized = !1;
18
19
  ready;
19
20
  constructor(options) {
20
- this.identity = options.identity, this.key = "signer" in options ? options.signer : options.privateKey, options.autoInit !== !1 && (this.ready = this.init(), this.ready.catch(() => {
21
+ this.identity = options.identity, this.key = "signer" in options ? options.signer : options.privateKey, this.keyResolver = options.keyResolver, options.autoInit !== !1 && (this.ready = this.init(), this.ready.catch(() => {
21
22
  }));
22
23
  }
23
24
  async init() {
@@ -37,7 +38,7 @@ class BtpsDelegator {
37
38
  const dnsHostAndSelector = await getHostAndSelector(this.identity);
38
39
  if (!dnsHostAndSelector) return { isValid: !1, publicKey: void 0 };
39
40
  this.selector = dnsHostAndSelector.selector;
40
- const publicKey = await resolvePublicKey(this.identity, this.selector);
41
+ const publicKey = this.keyResolver ? await this.keyResolver.resolvePublicKey(this.identity, this.selector, "verify") : await resolvePublicKey(this.identity, this.selector);
41
42
  return publicKey ? { isValid: typeof this.key == "string" ? this.isKeyPairMatching(this.key, publicKey) : await this.isSignerMatching(this.key, publicKey), publicKey } : { isValid: !1, publicKey: void 0 };
42
43
  }
43
44
  async isSignerMatching(signer, publicKeyPem) {
@@ -0,0 +1,104 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+ import { BTPErrorException } from '../error/index.js';
8
+ import type { BTPAttestation, BTPDelegation, BTPTransporterArtifact } from '../server/types.js';
9
+ import type { BtpsKeyResolver } from '../crypto/keyResolver.js';
10
+ import { type BTPCheckedKeyChain } from '../trust/keyRotation.js';
11
+ import type { BTPKeyChainFacts, BTPKeyChainLookup } from '../trust/types.js';
12
+ type Verified = {
13
+ isValid: boolean;
14
+ error?: BTPErrorException;
15
+ };
16
+ /** A signature key: from the resolver when one is given, else from DNS, as without one. */
17
+ export declare const signatureKey: (identity: string, selector: string, keyResolver?: BtpsKeyResolver) => Promise<string | undefined>;
18
+ /**
19
+ * Since 1.2: how a verifier checks a signing key against its identity's key
20
+ * chain, when it does: where it gets a chain, how long a key rotated away as
21
+ * planned is still taken, and how far ahead of its clock a record may be dated.
22
+ */
23
+ export type BTPKeyChainCheck = {
24
+ resolveKeyChain: (identity: string) => Promise<BTPKeyChainLookup>;
25
+ retiredKeyGraceSeconds: number;
26
+ maxSkewSeconds?: number;
27
+ /**
28
+ * Chains already checked, by identity, each kept for `checkedForSeconds`
29
+ * while its records are the same, so a chain's signatures are checked once
30
+ * per window, not on every arrival.
31
+ */
32
+ checked?: Map<string, {
33
+ hash: string;
34
+ chain: BTPCheckedKeyChain;
35
+ until: number;
36
+ }>;
37
+ checkedForSeconds?: number;
38
+ };
39
+ /**
40
+ * Since 1.2: `identity`'s key chain as a verifier online takes it: asked of its
41
+ * host, checked once, and anchored on what DNS publishes for it.
42
+ *
43
+ * - `none`: no chain to be had (a 1.1 host, an unreachable one) or an empty
44
+ * one: its keys are DNS's, as in 1.1;
45
+ * - `refused`: an answer that fails its checks, a DNS lookup that fails (never
46
+ * taken for host-only), or a chain `keyChainProblem` refuses;
47
+ * - `checked`: the chain's facts, anchored online.
48
+ *
49
+ * The chain must end at a key DNS publishes for the identity, at its last
50
+ * selector or the domain's `s=`; only when DNS has neither is it host-only.
51
+ */
52
+ export declare const onlineKeyChain: (identity: string, keyChains: BTPKeyChainCheck) => Promise<{
53
+ status: "none";
54
+ } | {
55
+ status: "refused";
56
+ error: BTPErrorException;
57
+ } | {
58
+ status: "checked";
59
+ facts: BTPKeyChainFacts;
60
+ }>;
61
+ /**
62
+ * Since 1.2: the key `identity` signs with at `selector`, checked against its
63
+ * key chain when `keyChains` is given. With no chain to be had (a 1.1 host, an
64
+ * unreachable one) or an empty one, it is the DNS key, as in 1.1. Otherwise:
65
+ *
66
+ * - the chain must come checked from the host, and end at a key DNS
67
+ * publishes for the identity, at the chain's last selector or the domain's
68
+ * `s=`. Only when DNS has neither is the identity host-only. A DNS lookup
69
+ * that fails refuses: it is never taken for host-only;
70
+ * - the key is the chain's key at `selector`, or the chain's key DNS
71
+ * publishes there (the same key under a later selector);
72
+ * - an expired key is `BTP_ERROR_KEY_REVOKED`, and a key rotated away as
73
+ * planned past the grace `BTP_ERROR_KEY_RETIRED`.
74
+ *
75
+ * No key and no error: none found, refused by the caller as before.
76
+ */
77
+ export declare const checkedSignatureKey: (identity: string, selector: string, keyResolver?: BtpsKeyResolver, keyChains?: BTPKeyChainCheck) => Promise<{
78
+ key?: string;
79
+ error?: BTPErrorException;
80
+ }>;
81
+ /** A delegation's attestation, signed by the attestor over the delegation. */
82
+ export declare const verifyAttestation: (delegation: Omit<BTPDelegation, "attestation"> & {
83
+ attestation: BTPAttestation;
84
+ }, keyResolver?: BtpsKeyResolver, keyChains?: BTPKeyChainCheck) => Promise<Verified>;
85
+ /**
86
+ * A delegated artifact: the delegation is allowed (by the sender itself, or its
87
+ * domain's operator), attested by the operator when the sender delegates for
88
+ * itself, signed by its delegator, and the artifact is signed by the agent.
89
+ */
90
+ export declare const verifyDelegation: (artifactWithDelegation: Omit<BTPTransporterArtifact, "delegation"> & {
91
+ delegation: BTPDelegation;
92
+ }, keyResolver?: BtpsKeyResolver, keyChains?: BTPKeyChainCheck) => Promise<Verified>;
93
+ /**
94
+ * Since 1.2, exported: a transporter artifact's signature, checked as a server
95
+ * checks it on arrival. Signed by its sender's own key from DNS, or, when it is
96
+ * delegated, through `verifyDelegation`. On success it also gives the key that
97
+ * signed the artifact itself, the one to verify it against when decrypting.
98
+ * Since 1.2, every key is found through `keyResolver` when one is given, and,
99
+ * with `keyChains`, checked against its identity's key chain.
100
+ */
101
+ export declare const verifyTransporterSignature: (artifact: BTPTransporterArtifact, keyResolver?: BtpsKeyResolver, keyChains?: BTPKeyChainCheck) => Promise<Verified & {
102
+ signerKey?: string;
103
+ }>;
104
+ export {};
@@ -0,0 +1,224 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) 2025 Bhupendra Tamang
4
+ * Licensed under the Apache License, Version 2.0
5
+ * https://www.apache.org/licenses/LICENSE-2.0
6
+ */
7
+
8
+ import { BTPErrorException } from "../error/index.js";
9
+ import {
10
+ BTP_ERROR_ATTESTATION_VERIFICATION,
11
+ BTP_ERROR_DELEGATION_INVALID,
12
+ BTP_ERROR_DELEGATION_SIG_VERIFICATION,
13
+ BTP_ERROR_RESOLVE_PUBKEY
14
+ } from "../error/constant.js";
15
+ import { createHash } from "crypto";
16
+ import { getFingerprintFromPem, verifySignature } from "../crypto/index.js";
17
+ import { canonicalizeValue } from "../crypto/jcs.js";
18
+ import {
19
+ getDnsIdentityParts,
20
+ getHostAndSelector,
21
+ isDelegationAllowed,
22
+ resolvePublicKey
23
+ } from "../utils/index.js";
24
+ import {
25
+ checkKeyChain,
26
+ keyAt,
27
+ keyChainFactsOf,
28
+ keyChainProblemOf,
29
+ keyChainSignerProblem
30
+ } from "../trust/keyRotation.js";
31
+ const signatureKey = (identity, selector, keyResolver) => keyResolver ? keyResolver.resolvePublicKey(identity, selector, "verify") : resolvePublicKey(identity, selector), CHECKED_SWEEP_AT = 1e4, checkedChainOf = (identity, records, keyChains) => {
32
+ const { checked, checkedForSeconds = 0 } = keyChains;
33
+ if (!checked || checkedForSeconds <= 0) return checkKeyChain(records, identity);
34
+ const key = identity.toLowerCase(), hash = createHash("sha256").update(canonicalizeValue(records), "utf8").digest("hex"), now = Date.now(), kept = checked.get(key);
35
+ if (kept && kept.hash === hash && kept.until > now) return kept.chain;
36
+ const chain = checkKeyChain(records, identity);
37
+ if (checked.size >= CHECKED_SWEEP_AT)
38
+ for (const [name, entry] of checked) entry.until <= now && checked.delete(name);
39
+ return checked.set(key, { hash, chain, until: now + checkedForSeconds * 1e3 }), chain;
40
+ }, refused = (error, cause) => ({
41
+ error: new BTPErrorException(error, { cause })
42
+ }), onlineKeyChain = async (identity, keyChains) => {
43
+ const lookup = await keyChains.resolveKeyChain(identity);
44
+ if (lookup.status === "invalid")
45
+ return {
46
+ status: "refused",
47
+ ...refused(BTP_ERROR_RESOLVE_PUBKEY, `${identity}'s key chain is refused: ${lookup.reason}`)
48
+ };
49
+ if (lookup.status === "unavailable" || lookup.records.length === 0) return { status: "none" };
50
+ const chain = checkedChainOf(identity, lookup.records, keyChains);
51
+ let dns;
52
+ try {
53
+ const fingerprintAt = async (at) => {
54
+ const pem = at === void 0 ? void 0 : await getDnsIdentityParts(identity, at, "pem");
55
+ return typeof pem == "string" ? getFingerprintFromPem(pem) : void 0;
56
+ }, last = keyChainFactsOf(chain, {}).keys.at(-1)?.selector, domain = (await getHostAndSelector(identity))?.selector, fingerprints = [await fingerprintAt(last), await fingerprintAt(domain)].filter(
57
+ (fingerprint) => fingerprint !== void 0
58
+ );
59
+ dns = fingerprints.length ? { kind: "published", fingerprints } : { kind: "hostOnly" };
60
+ } catch (error) {
61
+ return {
62
+ status: "refused",
63
+ ...refused(
64
+ BTP_ERROR_RESOLVE_PUBKEY,
65
+ `could not read ${identity}'s keys in DNS: ${error instanceof Error ? error.message : error}`
66
+ )
67
+ };
68
+ }
69
+ const problem = keyChainProblemOf(chain, {
70
+ fromOperator: !0,
71
+ dns,
72
+ maxSkewSeconds: keyChains.maxSkewSeconds
73
+ });
74
+ return problem ? {
75
+ status: "refused",
76
+ ...refused(BTP_ERROR_RESOLVE_PUBKEY, `${identity}'s key chain is refused: ${problem}`)
77
+ } : {
78
+ status: "checked",
79
+ facts: keyChainFactsOf(chain, { online: { fromOperator: !0, dns } })
80
+ };
81
+ }, checkedSignatureKey = async (identity, selector, keyResolver, keyChains) => {
82
+ if (!keyChains) return { key: await signatureKey(identity, selector, keyResolver) };
83
+ const online = await onlineKeyChain(identity, keyChains);
84
+ if (online.status === "refused") return { error: online.error };
85
+ if (online.status === "none") return { key: await signatureKey(identity, selector, keyResolver) };
86
+ const { facts } = online;
87
+ let key = keyAt(facts, { selector });
88
+ if (!key) {
89
+ const published = await signatureKey(identity, selector, keyResolver);
90
+ if (key = published ? keyAt(facts, { fingerprint: getFingerprintFromPem(published) }) : void 0, !key)
91
+ return refused(
92
+ BTP_ERROR_RESOLVE_PUBKEY,
93
+ `${selector} names no key of ${identity}'s key chain`
94
+ );
95
+ }
96
+ const refusal = keyChainSignerProblem(key, {
97
+ retiredKeyGraceSeconds: keyChains.retiredKeyGraceSeconds
98
+ });
99
+ return refusal ? refused(refusal, `${identity}'s key at ${selector}`) : { key: key.publicKey };
100
+ }, verifyAttestation = async (delegation, keyResolver, keyChains) => {
101
+ const { attestation, ...restDelegation } = delegation, { signature, ...restAttestation } = attestation, { key: attestorPubKey, error: keyError } = await checkedSignatureKey(
102
+ attestation.signedBy,
103
+ attestation.selector,
104
+ keyResolver,
105
+ keyChains
106
+ );
107
+ if (keyError) return { isValid: !1, error: keyError };
108
+ if (!attestorPubKey)
109
+ return {
110
+ isValid: !1,
111
+ error: new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY, {
112
+ cause: `Attestor ${attestation.signedBy} public key not found`,
113
+ meta: { attestation }
114
+ })
115
+ };
116
+ const signedMsg = { ...restDelegation, attestation: restAttestation }, { isValid, error } = verifySignature(signedMsg, signature, attestorPubKey);
117
+ return {
118
+ isValid,
119
+ error: error ? new BTPErrorException(BTP_ERROR_ATTESTATION_VERIFICATION, {
120
+ cause: `Attestation signature verification failed of attestor ${attestation.signedBy}`,
121
+ meta: { attestation }
122
+ }) : void 0
123
+ };
124
+ }, verifyDelegation = async (artifactWithDelegation, keyResolver, keyChains) => {
125
+ const operator = (await getHostAndSelector(artifactWithDelegation.from))?.operator;
126
+ if (!isDelegationAllowed(artifactWithDelegation, operator))
127
+ return {
128
+ isValid: !1,
129
+ error: new BTPErrorException(BTP_ERROR_DELEGATION_INVALID, {
130
+ 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`
131
+ })
132
+ };
133
+ const { delegation, ...restArtifact } = artifactWithDelegation;
134
+ if (delegation.signedBy === artifactWithDelegation.from && !delegation.attestation)
135
+ return {
136
+ isValid: !1,
137
+ error: new BTPErrorException(BTP_ERROR_DELEGATION_INVALID, {
138
+ cause: "Custom managed domain delegation requires attestation. Either provide attestation or directly send without delegation via transporter",
139
+ meta: {
140
+ delegation,
141
+ from: artifactWithDelegation.from
142
+ }
143
+ })
144
+ };
145
+ if (delegation.attestation) {
146
+ if (delegation.attestation.signedBy !== operator)
147
+ return {
148
+ isValid: !1,
149
+ error: new BTPErrorException(BTP_ERROR_ATTESTATION_VERIFICATION, {
150
+ cause: `${delegation.attestation.signedBy} is not the operator of ${artifactWithDelegation.from}'s domain`
151
+ })
152
+ };
153
+ const { isValid: isValid2, error: error2 } = await verifyAttestation(
154
+ delegation,
155
+ keyResolver,
156
+ keyChains
157
+ );
158
+ if (!isValid2) return { isValid: isValid2, error: error2 };
159
+ }
160
+ const { key: delegatorPubKey, error: keyError } = await checkedSignatureKey(
161
+ delegation.signedBy,
162
+ delegation.selector,
163
+ keyResolver,
164
+ keyChains
165
+ );
166
+ if (keyError) return { isValid: !1, error: keyError };
167
+ if (!delegatorPubKey)
168
+ return {
169
+ isValid: !1,
170
+ error: new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY, {
171
+ cause: `Delegator ${delegation.signedBy} public key not found`,
172
+ meta: { delegation }
173
+ })
174
+ };
175
+ const { signature, attestation, ...restDelegation } = delegation, signedMsg = { ...artifactWithDelegation, delegation: restDelegation }, { isValid: isValidDelegation } = verifySignature(signedMsg, signature, delegatorPubKey);
176
+ if (!isValidDelegation)
177
+ return {
178
+ isValid: isValidDelegation,
179
+ error: new BTPErrorException(BTP_ERROR_DELEGATION_SIG_VERIFICATION, {
180
+ cause: `Delegation signature verification failed of delegator ${delegation.signedBy}`,
181
+ meta: {
182
+ delegation
183
+ }
184
+ })
185
+ };
186
+ const { signature: origSignature, ...origSignedMsg } = restArtifact, { isValid, error } = verifySignature(origSignedMsg, origSignature, delegation.agentPubKey);
187
+ return {
188
+ isValid,
189
+ error: error ? new BTPErrorException(BTP_ERROR_DELEGATION_SIG_VERIFICATION, {
190
+ cause: `Delegated artifact's original artifact signature verification failed of agent ${delegation.agentId}`,
191
+ meta: {
192
+ delegation
193
+ }
194
+ }) : void 0
195
+ };
196
+ }, verifyTransporterSignature = async (artifact, keyResolver, keyChains) => {
197
+ if (artifact.delegation) {
198
+ const delegated = await verifyDelegation(
199
+ artifact,
200
+ keyResolver,
201
+ keyChains
202
+ );
203
+ return delegated.isValid ? { ...delegated, signerKey: artifact.delegation.agentPubKey } : delegated;
204
+ }
205
+ const { signature, ...signedMsg } = artifact, { key: publicKey, error: keyError } = await checkedSignatureKey(
206
+ artifact.from,
207
+ artifact.selector,
208
+ keyResolver,
209
+ keyChains
210
+ );
211
+ if (keyError) return { isValid: !1, error: keyError };
212
+ if (!publicKey)
213
+ return { isValid: !1, error: new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY) };
214
+ const verified = verifySignature(signedMsg, signature, publicKey);
215
+ return verified.isValid ? { ...verified, signerKey: publicKey } : verified;
216
+ };
217
+ export {
218
+ checkedSignatureKey,
219
+ onlineKeyChain,
220
+ signatureKey,
221
+ verifyAttestation,
222
+ verifyDelegation,
223
+ verifyTransporterSignature
224
+ };
@@ -29,6 +29,20 @@ export declare const BTP_ERROR_TRUST_EXPIRED: BTPError;
29
29
  export declare const BTP_ERROR_TRUST_REVOKED: BTPError;
30
30
  export declare const BTP_ERROR_TRUST_ALREADY_ACTIVE: BTPError;
31
31
  export declare const BTP_ERROR_EVENT_UNRELATED: BTPError;
32
+ /**
33
+ * Since 1.2: a `withdrawn` or `follows` from the invoice's issuer, a
34
+ * `withdrawn` that does not take back the payer's own open proposal about the
35
+ * same invoice, or a `follows` that names no `withdrawn` about it. It
36
+ * concerns the sender's own events, so the sender is told which.
37
+ */
38
+ export declare const BTP_ERROR_EVENT_CHAIN: BTPError;
39
+ /**
40
+ * Since 1.2: an agreement's answer that is not its sender's turn: from someone
41
+ * who is not a signer, a second answer, out of turn, or after a decline.
42
+ * Raised by the platform's own check in flight (`agreementOrderCheck`
43
+ * middleware), never by the server, with the broken rule in its message.
44
+ */
45
+ export declare const BTP_ERROR_AGREEMENT_ORDER: BTPError;
32
46
  export declare const BTP_ERROR_RESOLVE_DNS: BTPError;
33
47
  export declare const BTP_ERROR_RESOLVE_PUBKEY: BTPError;
34
48
  export declare const BTP_ERROR_RATE_LIMITER: BTPError;
@@ -53,12 +67,39 @@ export declare const BTP_ERROR_UNSUPPORTED_ENCRYPT: BTPError;
53
67
  export declare const BTP_ERROR_DECRYPTION_UNINTENDED: BTPError;
54
68
  export declare const BTP_ERROR_UNKNOWN: BTPError;
55
69
  export declare const BTP_ERROR_AGENT_ID: BTPError;
70
+ /** Since 1.2: a sync that did not come from a device of its own address. */
71
+ export declare const BTP_ERROR_SYNC_NOT_ALLOWED: BTPError;
72
+ /** Since 1.2: something a trust's permissions do not cover, such as a name the request never asked for. */
73
+ export declare const BTP_ERROR_PERMISSION: BTPError;
74
+ /** Since 1.2: a trust answer that leaves out a required permission, or one that cannot be checked. */
75
+ export declare const BTP_ERROR_PERMISSION_REQUIRED: BTPError;
76
+ /** Since 1.2: a document whose type is not the documentType its envelope names. */
77
+ export declare const BTP_ERROR_DOCUMENT_TYPE_MISMATCH: BTPError;
78
+ /** Since 1.2: a details refresh naming a detail its receiver or answerer does not hold by the trust. */
79
+ export declare const BTP_ERROR_DETAILS_NOT_HELD: BTPError;
80
+ /** Since 1.2: a details request over the limit the provider sets; its meta says when to ask again. */
81
+ export declare const BTP_ERROR_DETAILS_RATE_LIMITED: BTPError;
56
82
  export declare const BTP_ERROR_KEY_ROTATION_PROOF: BTPError;
83
+ /** Since 1.2: the device key is older than the server's maxKeyAgeMs. */
84
+ export declare const BTP_ERROR_KEY_TOO_OLD: BTPError;
85
+ /**
86
+ * Since 1.2: signed by a key its identity rotated away from, planned, longer
87
+ * ago than the receiver's retiredKeyGraceSeconds. A stale key: sign again
88
+ * with the current one.
89
+ */
90
+ export declare const BTP_ERROR_KEY_RETIRED: BTPError;
91
+ /**
92
+ * Since 1.2: signed by a key its identity rotated away from with immediate
93
+ * expiry, or expired: compromised or lost. A security incident, not a stale key.
94
+ */
95
+ export declare const BTP_ERROR_KEY_REVOKED: BTPError;
57
96
  export declare const BTP_ERROR_ARTIFACT_TIME_WINDOW: BTPError;
58
97
  export declare const BTP_ERROR_ARTIFACT_TOO_LARGE: BTPError;
59
98
  export declare const BTP_ERROR_VERSION_UNSUPPORTED: BTPError;
60
99
  export declare const BTP_ERROR_PRIVACY_TYPE: BTPError;
61
100
  export declare const BTP_ERROR_ARTIFACT_NOT_ACCEPTED: BTPError;
101
+ /** For a store (trust, identity) to throw when it is briefly unreachable: the sender may send again later. */
102
+ export declare const BTP_ERROR_TEMPORARILY_UNAVAILABLE: BTPError;
62
103
  export declare const BTP_ERROR_SOCKET_TIMEOUT: BTPError;
63
104
  export declare const BTP_ERROR_AUTHENTICATION_INVALID: BTPError;
64
105
  export declare const BTP_ERROR_TIMEOUT: BTPError;