@btps/sdk 1.1.3 → 1.2.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/CHANGELOG.md +422 -0
  2. package/bin/verify-evidence-bundle.mjs +96 -0
  3. package/dist/client/btpsAgent.d.ts +10 -1
  4. package/dist/client/btpsAgent.js +116 -18
  5. package/dist/client/btpsClient.d.ts +53 -7
  6. package/dist/client/btpsClient.js +265 -147
  7. package/dist/client/index.d.ts +1 -1
  8. package/dist/client/index.js +3 -1
  9. package/dist/client/libs/schema.js +78 -13
  10. package/dist/client/libs/timeouts.d.ts +6 -0
  11. package/dist/client/libs/timeouts.js +2 -1
  12. package/dist/client/types/index.d.ts +54 -2
  13. package/dist/core/authentication/BtpsAuthentication.d.ts +43 -1
  14. package/dist/core/authentication/BtpsAuthentication.js +152 -36
  15. package/dist/core/authentication/refreshSuccessor.js +47 -0
  16. package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +17 -1
  17. package/dist/core/authentication/storage/InMemoryTokenStore.js +16 -4
  18. package/dist/core/authentication/types.d.ts +82 -0
  19. package/dist/core/crypto/contentKey.d.ts +34 -0
  20. package/dist/core/crypto/contentKey.js +64 -0
  21. package/dist/core/crypto/decryptVerify.d.ts +7 -1
  22. package/dist/core/crypto/decryptVerify.js +23 -5
  23. package/dist/core/crypto/decrypter-interface.d.ts +6 -0
  24. package/dist/core/crypto/index.d.ts +12 -0
  25. package/dist/core/crypto/index.js +7 -1
  26. package/dist/core/crypto/keyResolver.d.ts +48 -0
  27. package/dist/core/crypto/keyResolver.js +46 -0
  28. package/dist/core/crypto/pem-decrypter.d.ts +2 -0
  29. package/dist/core/crypto/pem-decrypter.js +13 -8
  30. package/dist/core/crypto/signEncrypt.d.ts +4 -1
  31. package/dist/core/crypto/signEncrypt.js +20 -5
  32. package/dist/core/crypto/types.d.ts +8 -1
  33. package/dist/core/delegation/BtpsDelegator.d.ts +4 -0
  34. package/dist/core/delegation/BtpsDelegator.js +3 -2
  35. package/dist/core/delegation/verifyTransporterSignature.d.ts +104 -0
  36. package/dist/core/delegation/verifyTransporterSignature.js +224 -0
  37. package/dist/core/error/constant.d.ts +39 -0
  38. package/dist/core/error/constant.js +55 -0
  39. package/dist/core/server/constants/btps-protocol.d.ts +21 -5
  40. package/dist/core/server/constants/btps-protocol.js +46 -8
  41. package/dist/core/server/constants/index.d.ts +7 -3
  42. package/dist/core/server/constants/index.js +19 -4
  43. package/dist/core/server/constants/limits.d.ts +18 -0
  44. package/dist/core/server/constants/limits.js +19 -1
  45. package/dist/core/server/constants/permissions.d.ts +38 -0
  46. package/dist/core/server/constants/permissions.js +38 -0
  47. package/dist/core/server/schemas/artifacts/agentSchema.js +2 -1
  48. package/dist/core/server/schemas/artifacts/artifacts.js +7 -1
  49. package/dist/core/server/schemas/artifacts/controlSchema.js +1 -1
  50. package/dist/core/server/schemas/artifacts/identityLookupSchema.js +10 -1
  51. package/dist/core/server/schemas/artifacts/transporterSchema.js +92 -12
  52. package/dist/core/server/schemas/bounded.js +2 -2
  53. package/dist/core/server/schemas/btpsDocsSchema.d.ts +34185 -1084
  54. package/dist/core/server/schemas/btpsDocsSchema.js +300 -42
  55. package/dist/core/server/schemas/helpers.d.ts +9580 -0
  56. package/dist/core/server/schemas/helpers.js +76 -12
  57. package/dist/core/server/schemas/keyChainSchema.js +53 -0
  58. package/dist/core/server/schemas/responseSchema.js +52 -9
  59. package/dist/core/server/schemas/schema.js +3 -1
  60. package/dist/core/server/schemas/trustValues.d.ts +105 -0
  61. package/dist/core/server/schemas/trustValues.js +117 -0
  62. package/dist/core/server/types.d.ts +104 -6
  63. package/dist/core/storage/AbstractIdentityStore.d.ts +9 -0
  64. package/dist/core/storage/JsonIdentityStore.d.ts +3 -0
  65. package/dist/core/storage/JsonIdentityStore.js +3 -0
  66. package/dist/core/storage/types.d.ts +2 -0
  67. package/dist/core/trust/agreements.d.ts +107 -0
  68. package/dist/core/trust/agreements.js +116 -0
  69. package/dist/core/trust/evidence.d.ts +220 -0
  70. package/dist/core/trust/evidence.js +334 -0
  71. package/dist/core/trust/index.d.ts +10 -0
  72. package/dist/core/trust/index.js +14 -1
  73. package/dist/core/trust/keyRotation.d.ts +148 -0
  74. package/dist/core/trust/keyRotation.js +267 -0
  75. package/dist/core/trust/permissions.d.ts +114 -0
  76. package/dist/core/trust/permissions.js +115 -0
  77. package/dist/core/trust/shaping.d.ts +42 -0
  78. package/dist/core/trust/shaping.js +47 -0
  79. package/dist/core/trust/storage/AbstractTrustStore.d.ts +2 -1
  80. package/dist/core/trust/storage/JsonTrustStore.d.ts +3 -2
  81. package/dist/core/trust/timestamps.d.ts +49 -0
  82. package/dist/core/trust/timestamps.js +78 -0
  83. package/dist/core/trust/trustUtils.d.ts +13 -2
  84. package/dist/core/trust/trustUtils.js +28 -3
  85. package/dist/core/trust/types.d.ts +302 -2
  86. package/dist/core/trust/verification.d.ts +52 -0
  87. package/dist/core/trust/verification.js +55 -0
  88. package/dist/server/btpsServer.d.ts +70 -5
  89. package/dist/server/btpsServer.js +263 -143
  90. package/dist/server/index.d.ts +3 -0
  91. package/dist/server/index.js +17 -1
  92. package/dist/server/libs/agreementOrderCheck.d.ts +29 -0
  93. package/dist/server/libs/agreementOrderCheck.js +29 -0
  94. package/dist/server/libs/artifactTimeWindow.d.ts +2 -2
  95. package/dist/server/libs/artifactTimeWindow.js +2 -1
  96. package/dist/server/libs/detailsRequestLimit.d.ts +27 -0
  97. package/dist/server/libs/detailsRequestLimit.js +28 -0
  98. package/dist/server/libs/detailsResponseCheck.d.ts +27 -0
  99. package/dist/server/libs/detailsResponseCheck.js +27 -0
  100. package/dist/server/libs/eventChainCheck.d.ts +31 -0
  101. package/dist/server/libs/eventChainCheck.js +39 -0
  102. package/dist/server/libs/inFlightLimit.d.ts +10 -0
  103. package/dist/server/libs/inFlightLimit.js +7 -1
  104. package/dist/server/libs/index.d.ts +5 -0
  105. package/dist/server/libs/index.js +10 -0
  106. package/dist/server/libs/keyChains.d.ts +14 -0
  107. package/dist/server/libs/keyChains.js +17 -0
  108. package/dist/server/libs/wrapForAgent.d.ts +20 -0
  109. package/dist/server/libs/wrapForAgent.js +36 -0
  110. package/dist/server/types.d.ts +95 -9
  111. package/package.json +12 -3
@@ -4,13 +4,15 @@
4
4
  * Licensed under the Apache License, Version 2.0
5
5
  * https://www.apache.org/licenses/LICENSE-2.0
6
6
  */
7
- import { TokenStore, BTPsTokenDocument } from '../types.js';
7
+ import { TokenStore, BTPsTokenDocument, BTPSealedSuccessor } from '../types.js';
8
8
  /**
9
9
  * In-memory implementation of RefreshTokenStore for storing refresh tokens
10
10
  * Suitable for development and testing. For production, use a persistent store.
11
11
  */
12
12
  export declare class InMemoryTokenStore<T extends BTPsTokenDocument = BTPsTokenDocument> implements TokenStore<T> {
13
13
  private tokens;
14
+ /** Each consumed token, until it would have expired: how a second use is told from a made-up one. */
15
+ private consumed;
14
16
  /**
15
17
  * Store a refresh token in memory
16
18
  * @param token - The refresh token value
@@ -48,6 +50,20 @@ export declare class InMemoryTokenStore<T extends BTPsTokenDocument = BTPsTokenD
48
50
  * @returns The stored token, or undefined when there is none or it has expired
49
51
  */
50
52
  consume(agentId: string, token: string): Promise<T | undefined>;
53
+ /**
54
+ * The token as it was when consumed, until it would have expired.
55
+ * @param agentId - The agent ID (or the user identity, for an auth token)
56
+ * @param token - The token
57
+ * @returns The consumed token, or undefined when it was never consumed or has expired
58
+ */
59
+ isConsumed(agentId: string, token: string): Promise<T | undefined>;
60
+ /**
61
+ * Keep the sealed answer a consumed token was rotated with on its mark.
62
+ * @param agentId - The agent ID
63
+ * @param token - The consumed token
64
+ * @param successor - The sealed answer
65
+ */
66
+ markSuccessor(agentId: string, token: string, successor: BTPSealedSuccessor): Promise<void>;
51
67
  /**
52
68
  * Clean up expired tokens from storage
53
69
  */
@@ -8,9 +8,10 @@
8
8
  import { computeTrustId } from "../../trust/trustUtils.js";
9
9
  class InMemoryTokenStore {
10
10
  tokens = new Map();
11
+ consumed = new Map();
11
12
  async store(token, agentId, userIdentity, expiryMs, decryptBy, metadata) {
12
- const now = new Date(), expiresAt = new Date(now.getTime() + expiryMs);
13
- this.tokens.set(this.makeKey(agentId ?? userIdentity, token), {
13
+ const now = new Date(), expiresAt = new Date(now.getTime() + expiryMs), key = this.makeKey(agentId ?? userIdentity, token);
14
+ this.consumed.delete(key), this.tokens.set(key, {
14
15
  token,
15
16
  agentId: agentId ?? "anonymous",
16
17
  userIdentity,
@@ -40,7 +41,16 @@ class InMemoryTokenStore {
40
41
  async consume(agentId, token) {
41
42
  const key = this.makeKey(agentId, token), storedToken = this.tokens.get(key);
42
43
  if (this.tokens.delete(key), !(!storedToken || new Date() > new Date(storedToken.expiresAt)))
43
- return storedToken;
44
+ return this.consumed.set(key, { ...storedToken, consumedAt: ( new Date()).toISOString() }), storedToken;
45
+ }
46
+ async isConsumed(agentId, token) {
47
+ const consumedToken = this.consumed.get(this.makeKey(agentId, token));
48
+ if (!(!consumedToken || new Date() > new Date(consumedToken.expiresAt)))
49
+ return consumedToken;
50
+ }
51
+ async markSuccessor(agentId, token, successor) {
52
+ const key = this.makeKey(agentId, token), consumedToken = this.consumed.get(key);
53
+ consumedToken && this.consumed.set(key, { ...consumedToken, successor });
44
54
  }
45
55
  async cleanup() {
46
56
  const now = new Date(), expiredTokens = [];
@@ -50,12 +60,14 @@ class InMemoryTokenStore {
50
60
  }
51
61
  for (const token of expiredTokens)
52
62
  this.tokens.delete(token);
63
+ for (const [key, consumedToken] of this.consumed.entries())
64
+ now > new Date(consumedToken.expiresAt) && this.consumed.delete(key);
53
65
  }
54
66
  get size() {
55
67
  return this.tokens.size;
56
68
  }
57
69
  clear() {
58
- this.tokens.clear();
70
+ this.tokens.clear(), this.consumed.clear();
59
71
  }
60
72
  }
61
73
  export {
@@ -31,7 +31,67 @@ export interface ServerAuthConfig {
31
31
  tokenStore: TokenStore;
32
32
  /** Token configuration */
33
33
  tokenConfig?: TokenConfig;
34
+ /**
35
+ * Since 1.2, optional and off by default: the oldest a device key may be. A
36
+ * refresh signed by an older key is refused with `BTP_ERROR_KEY_TOO_OLD`,
37
+ * and the same refresh token stays usable, so the device moves to a new key
38
+ * (`rotateKey`) and is let in. A key's age runs from when it came into use:
39
+ * when the key before it was retired, or when the device registered.
40
+ */
41
+ maxKeyAgeMs?: number;
42
+ /**
43
+ * Since 1.2: how long, in milliseconds, a just-rotated refresh token's old
44
+ * value still works, so a device that lost the answer to its refresh can ask
45
+ * again. Inside the window the same answer comes back, the same new token
46
+ * included; after it, a second use is theft. Default 30 000; 0 turns it off.
47
+ * Needs a token store with `isConsumed` and `markSuccessor`; without them it is 0.
48
+ */
49
+ refreshGraceMs?: number;
50
+ }
51
+ /**
52
+ * Since 1.2: the answer to a refresh, kept on the old token's consumed mark so a
53
+ * retry gets the same answer. Sealed with AES-256-GCM under a key derived
54
+ * (HKDF-SHA256) from the old token's value, bound to the device and the user,
55
+ * so only whoever holds the old token can open it and it cannot be moved to
56
+ * another device. Never the new token in plain text.
57
+ */
58
+ export interface BTPSealedSuccessor {
59
+ /** When the old token was rotated, as an ISO 8601 timestamp: the grace window runs from here */
60
+ at: string;
61
+ /** Base64 */
62
+ iv: string;
63
+ /** Base64 */
64
+ ciphertext: string;
65
+ /** Base64 */
66
+ tag: string;
67
+ }
68
+ /** Since 1.2: a device moved to a new key. */
69
+ export interface BTPKeyRotatedInfo {
70
+ agentId: string;
71
+ identity: string;
72
+ previousFingerprint: string;
73
+ fingerprint: string;
74
+ /** When the device moved to the new key, as an ISO 8601 timestamp */
75
+ at: string;
34
76
  }
77
+ /** Since 1.2: a refresh token was used a second time, which only a copy of it can do. */
78
+ export interface BTPRefreshTokenReusedInfo {
79
+ agentId: string;
80
+ identity: string;
81
+ /** The fingerprint of the key the revoked device held, when its record was found */
82
+ fingerprint?: string;
83
+ /** When the token was used again, as an ISO 8601 timestamp */
84
+ at: string;
85
+ }
86
+ /**
87
+ * Since 1.2, what BtpsAuthentication tells its listeners. With none attached,
88
+ * nothing happens. A listener that throws is warned about and never breaks a refresh.
89
+ */
90
+ export type BtpsAuthenticationEvents = {
91
+ keyRotated: (info: BTPKeyRotatedInfo) => void;
92
+ /** The device was revoked: whoever holds the newer token, the device or a thief, is refused. */
93
+ refreshTokenReused: (info: BTPRefreshTokenReusedInfo) => void;
94
+ };
35
95
  /**
36
96
  * Stored refresh token information
37
97
  */
@@ -50,6 +110,10 @@ export interface BTPsTokenDocument {
50
110
  decryptBy: string;
51
111
  /** Additional metadata */
52
112
  metadata?: Record<string, unknown>;
113
+ /** Since 1.2, on a consumed refresh token only: the answer it was rotated with, sealed */
114
+ successor?: BTPSealedSuccessor;
115
+ /** Since 1.2, on a consumed refresh token only: when `consume` took it, ISO 8601 */
116
+ consumedAt?: string;
53
117
  }
54
118
  export type AuthSession = BTPsTokenDocument & {
55
119
  publicKeyFingerprint: string;
@@ -96,6 +160,24 @@ export interface TokenStore<T extends BTPsTokenDocument = BTPsTokenDocument> {
96
160
  * exactly one gets it, so one registration code or refresh token is used once.
97
161
  */
98
162
  consume(agentId: string, token: string): Promise<T | undefined>;
163
+ /**
164
+ * Since 1.2, optional: the token as it was when `consume` took it, kept until
165
+ * it would have expired; undefined for a token never taken, or past its life.
166
+ * Storing a token again clears the mark. With it, a refresh token used a
167
+ * second time is theft: the device is revoked and `refreshTokenReused` fires.
168
+ * Without it, a second use is refused as an unknown token, as in 1.1. The
169
+ * mark carries `consumedAt`, when `consume` took the token: a second use
170
+ * while the first refresh is still being made is told to try again, not
171
+ * taken for theft.
172
+ */
173
+ isConsumed?(agentId: string, token: string): Promise<T | undefined>;
174
+ /**
175
+ * Since 1.2, optional: keep `successor` on a consumed token's mark, so
176
+ * `isConsumed` returns it. It is sealed, never the new token in plain text.
177
+ * With it and `isConsumed`, a refresh retried inside `refreshGraceMs` gets its
178
+ * first answer again; without it, the grace window is off.
179
+ */
180
+ markSuccessor?(agentId: string, token: string, successor: BTPSealedSuccessor): Promise<void>;
99
181
  /** Clean up expired tokens */
100
182
  cleanup(): Promise<void>;
101
183
  }
@@ -0,0 +1,34 @@
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 type { BTPTransporterArtifact } from '../server/types.js';
8
+ import type { BTPDecryptionKey } from './types.js';
9
+ /** Since 1.2: an artifact's content key, wrapped to another key, kept beside the artifact. */
10
+ export type BTPContentKeySidecar = {
11
+ /** The content key, RSA-OAEP-wrapped to the key with this fingerprint, base64 */
12
+ encryptedKey: string;
13
+ /** The SHA-256 fingerprint of the key it is wrapped to, base64 */
14
+ recipientFingerprint: string;
15
+ };
16
+ type Encrypted = Pick<BTPTransporterArtifact, 'encryption' | 'document'>;
17
+ /**
18
+ * Since 1.2: the artifact's content key, unwrapped with the key it was
19
+ * wrapped to (`oldKey`, a PEM private key or a Decrypter with `unwrapKey`),
20
+ * checked to open the document, and wrapped to `newPublicKey` (SPKI PEM). The
21
+ * artifact itself is not changed. Keep the side-car beside it, and confirm it
22
+ * with `contentKeyOpens` before deleting the old private key.
23
+ */
24
+ export declare const wrapContentKeyFor: (artifact: Encrypted, oldKey: BTPDecryptionKey, newPublicKey: string) => Promise<BTPContentKeySidecar>;
25
+ /**
26
+ * Since 1.2: whether a side-car opens its artifact with `newKey`: the content
27
+ * key unwraps, and the document's AES-GCM tag checks. Given a PEM private
28
+ * key, the side-car must also name it (`recipientFingerprint`), so one stored
29
+ * against another key fails even when the unwrap happens to work. Only when
30
+ * every stored artifact wrapped to an old key has a side-car that opens may
31
+ * that old private key be deleted.
32
+ */
33
+ export declare const contentKeyOpens: (artifact: Encrypted, sidecar: BTPContentKeySidecar, newKey: BTPDecryptionKey) => Promise<boolean>;
34
+ export {};
@@ -0,0 +1,64 @@
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 crypto from "crypto";
9
+ import { BTPErrorException } from "../error/index.js";
10
+ import {
11
+ BTP_ERROR_DECRYPTION_UNINTENDED,
12
+ BTP_ERROR_UNSUPPORTED_ENCRYPT
13
+ } from "../error/constant.js";
14
+ import { decryptRSA, encryptRSA, getFingerprintFromPem } from "./index.js";
15
+ const encryptionOf = (artifact) => {
16
+ const { encryption, document } = artifact;
17
+ if (!encryption?.encryptedKey || typeof document != "string")
18
+ throw new BTPErrorException(BTP_ERROR_UNSUPPORTED_ENCRYPT, {
19
+ cause: "Only an encrypted artifact has a content key"
20
+ });
21
+ if (encryption.algorithm !== "aes-256-gcm")
22
+ throw new BTPErrorException(BTP_ERROR_UNSUPPORTED_ENCRYPT);
23
+ return { ...encryption, document };
24
+ }, unwrap = async (encryptedKey, key) => {
25
+ const wrapped = Buffer.from(encryptedKey, "base64");
26
+ if (typeof key == "string") return decryptRSA(key, wrapped);
27
+ if (key.unwrapKey) return Buffer.from(await key.unwrapKey(wrapped));
28
+ throw new BTPErrorException(BTP_ERROR_UNSUPPORTED_ENCRYPT, {
29
+ cause: "The Decrypter has no unwrapKey, so it cannot give the content key"
30
+ });
31
+ }, opens = (contentKey, artifact) => {
32
+ const { iv, authTag, document } = encryptionOf(artifact);
33
+ try {
34
+ const decipher = crypto.createDecipheriv("aes-256-gcm", contentKey, Buffer.from(iv, "base64"));
35
+ return decipher.setAuthTag(Buffer.from(authTag, "base64")), decipher.update(Buffer.from(document, "base64")), decipher.final(), !0;
36
+ } catch {
37
+ return !1;
38
+ }
39
+ }, wrapContentKeyFor = async (artifact, oldKey, newPublicKey) => {
40
+ const contentKey = await unwrap(encryptionOf(artifact).encryptedKey, oldKey);
41
+ if (!opens(contentKey, artifact))
42
+ throw new BTPErrorException(BTP_ERROR_DECRYPTION_UNINTENDED, {
43
+ cause: "The old key's content key does not open the document"
44
+ });
45
+ return {
46
+ encryptedKey: encryptRSA(newPublicKey, contentKey).toString("base64"),
47
+ recipientFingerprint: getFingerprintFromPem(newPublicKey)
48
+ };
49
+ }, contentKeyOpens = async (artifact, sidecar, newKey) => {
50
+ try {
51
+ if (typeof newKey == "string") {
52
+ const publicKey = crypto.createPublicKey(newKey).export({ type: "spki", format: "pem" });
53
+ if (getFingerprintFromPem(publicKey.toString()) !== sidecar.recipientFingerprint)
54
+ return !1;
55
+ }
56
+ return opens(await unwrap(sidecar.encryptedKey, newKey), artifact);
57
+ } catch {
58
+ return !1;
59
+ }
60
+ };
61
+ export {
62
+ contentKeyOpens,
63
+ wrapContentKeyFor
64
+ };
@@ -6,4 +6,10 @@
6
6
  */
7
7
 
8
8
  import { BTPCryptoResponse, BTPDecryptionKey, VerifyEncryptedPayload } from './types.js';
9
- export declare const decryptVerify: <T = unknown>(senderPubPem: string, encryptedPayload: VerifyEncryptedPayload<T>, receiverKey?: BTPDecryptionKey) => Promise<BTPCryptoResponse<T>>;
9
+ /**
10
+ * Verifies an artifact's signature, then decrypts its document and checks it.
11
+ * Since 1.2, `contentKey` is the document's content key wrapped to the
12
+ * receiver's own key instead of the envelope's (a device's `agentKey.key`): the
13
+ * signature is checked over the artifact as sent, and only the decryption uses it.
14
+ */
15
+ export declare const decryptVerify: <T = unknown>(senderPubPem: string, encryptedPayload: VerifyEncryptedPayload<T>, receiverKey?: BTPDecryptionKey, contentKey?: string) => Promise<BTPCryptoResponse<T>>;
@@ -7,29 +7,47 @@
7
7
 
8
8
  import { decryptBtpPayload, decryptBtpPayloadWithDecrypter, verifySignature } from "./index.js";
9
9
  import { BTPErrorException } from "../error/index.js";
10
- import { BTP_ERROR_VALIDATION } from "../error/constant.js";
10
+ import {
11
+ BTP_ERROR_DOCUMENT_TYPE_MISMATCH,
12
+ BTP_ERROR_SIG_VERIFICATION,
13
+ BTP_ERROR_VALIDATION
14
+ } from "../error/constant.js";
11
15
  import { decryptedDocumentProblem } from "../server/schemas/helpers.js";
16
+ import { verifierRefusal } from "../trust/verification.js";
12
17
  import isEmpty from "lodash/isEmpty.js";
13
18
  const genDecryptError = (error) => ({
14
19
  payload: void 0,
15
20
  error
16
- }), decryptVerify = async (senderPubPem, encryptedPayload, receiverKey) => {
21
+ }), decryptVerify = async (senderPubPem, encryptedPayload, receiverKey, contentKey) => {
17
22
  const { signature, delegation, ...restEncryptedPayload } = encryptedPayload, { isValid, error: sigError } = verifySignature(
18
23
  restEncryptedPayload,
19
24
  signature,
20
25
  senderPubPem
21
26
  );
22
- if (!isValid && sigError)
23
- return genDecryptError(sigError);
27
+ if (!isValid)
28
+ return genDecryptError(sigError ?? new BTPErrorException(BTP_ERROR_SIG_VERIFICATION));
24
29
  const { encryption, document } = restEncryptedPayload, hasReceiverKey = typeof receiverKey == "string" ? !isEmpty(receiverKey) : receiverKey !== void 0, needsDecryption = !isEmpty(encryption) && hasReceiverKey && !isEmpty(document) && typeof document == "string";
25
30
  let decrypted = { data: document };
26
- needsDecryption && receiverKey !== void 0 && (decrypted = typeof receiverKey == "string" ? decryptBtpPayload(document, encryption, receiverKey) : await decryptBtpPayloadWithDecrypter(document, encryption, receiverKey));
31
+ if (needsDecryption && receiverKey !== void 0) {
32
+ const wrapped = contentKey !== void 0 && encryption ? { ...encryption, encryptedKey: contentKey } : encryption;
33
+ decrypted = typeof receiverKey == "string" ? decryptBtpPayload(document, wrapped, receiverKey) : await decryptBtpPayloadWithDecrypter(document, wrapped, receiverKey);
34
+ }
27
35
  const { data: decryptedData, error: decryptionErrors } = decrypted;
28
36
  if (decryptionErrors) return genDecryptError(decryptionErrors);
29
37
  if (needsDecryption) {
30
38
  const problem = decryptedDocumentProblem(decryptedData, restEncryptedPayload);
31
39
  if (problem)
32
40
  return genDecryptError(new BTPErrorException(BTP_ERROR_VALIDATION, { cause: problem }));
41
+ const { documentType } = restEncryptedPayload, type = decryptedData?.type;
42
+ if (documentType !== void 0 && type !== documentType)
43
+ return genDecryptError(
44
+ new BTPErrorException(BTP_ERROR_DOCUMENT_TYPE_MISMATCH, {
45
+ cause: `the document is a ${String(type)}, not the ${documentType} its envelope names`
46
+ })
47
+ );
48
+ const { verification } = decryptedData ?? {}, verifier = restEncryptedPayload.type === "TRUST_REQ" && verification ? await verifierRefusal(verification.verifiedBy) : void 0;
49
+ if (verifier)
50
+ return genDecryptError(new BTPErrorException(verifier.error, { cause: verifier.problem }));
33
51
  }
34
52
  const decryptedPayload = {
35
53
  ...restEncryptedPayload,
@@ -22,4 +22,10 @@ export interface Decrypter {
22
22
  /** Decrypts `request` and returns the plaintext bytes, or rejects if the
23
23
  * key-wrap fails to unwrap or the AEAD tag check fails. */
24
24
  decrypt(request: DecryptRequest): Promise<Uint8Array>;
25
+ /**
26
+ * Since 1.2, optional: unwraps an RSA-OAEP-wrapped AES-256 content key and
27
+ * returns it, so a provider can wrap it again to one of its user's devices
28
+ * (`wrapForAgent`). A KMS decrypter makes the same call inside `decrypt`.
29
+ */
30
+ unwrapKey?(encryptedKey: Uint8Array): Promise<Uint8Array>;
25
31
  }
@@ -12,6 +12,8 @@ import type { Decrypter } from './decrypter-interface.js';
12
12
  export * from './decryptVerify.js';
13
13
  export * from './jcs.js';
14
14
  export * from './signEncrypt.js';
15
+ export * from './keyResolver.js';
16
+ export * from './contentKey.js';
15
17
  export * from './keygen.js';
16
18
  export * from './types.js';
17
19
  export * from './signer-interface.js';
@@ -63,6 +65,16 @@ export declare const encryptRSA: (publicKeyPem: string, data: Buffer) => Buffer;
63
65
  */
64
66
  export declare const decryptRSA: (privateKeyPem: string, encrypted: Buffer) => Buffer;
65
67
  export declare const getFingerprintFromPem: (pem: string, hashAlgorithm?: string) => string;
68
+ /**
69
+ * Since 1.2: what a sync names of the send it copies (`syncOf`): the sent
70
+ * artifact's id, and the lowercase hex SHA-256 of its RFC 8785 form, signature included.
71
+ */
72
+ export declare const syncOfArtifact: (artifact: {
73
+ id: string;
74
+ }) => {
75
+ id: string;
76
+ sha256: string;
77
+ };
66
78
  export declare const signBtpPayload: (payload: unknown | undefined, senderPemFiles: PemKeys) => BTPSignature;
67
79
  /**
68
80
  * Signs like `signBtpPayload`, through a Signer that holds the sender's
@@ -21,6 +21,8 @@ import { assertFullLengthAuthTag } from "./pem-decrypter.js";
21
21
  export * from "./decryptVerify.js";
22
22
  export * from "./jcs.js";
23
23
  export * from "./signEncrypt.js";
24
+ export * from "./keyResolver.js";
25
+ export * from "./contentKey.js";
24
26
  export * from "./keygen.js";
25
27
  export * from "./types.js";
26
28
  export * from "./signer-interface.js";
@@ -137,7 +139,10 @@ const documentTypeError = (document, documentType) => {
137
139
  type: "spki"
138
140
  }).export({ format: "der", type: "spki" });
139
141
  return crypto.createHash(hashAlgorithm).update(der).digest("base64");
140
- }, signedBytes = (payload) => Buffer.from(
142
+ }, syncOfArtifact = (artifact) => ({
143
+ id: artifact.id,
144
+ sha256: crypto.createHash("sha256").update(canonicalizeValue(artifact), "utf8").digest("hex")
145
+ }), signedBytes = (payload) => Buffer.from(
141
146
  typeof payload == "string" ? canonicalize(payload) : canonicalizeValue(payload),
142
147
  "utf8"
143
148
  ), signBtpPayload = (payload = "", senderPemFiles) => {
@@ -214,5 +219,6 @@ export {
214
219
  getFingerprintFromPem,
215
220
  signBtpPayload,
216
221
  signBtpPayloadWithSigner,
222
+ syncOfArtifact,
217
223
  verifySignature
218
224
  };
@@ -0,0 +1,48 @@
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 type { ConnectionOptions } from 'tls';
8
+ import type { BTPKeyChainLookup } from '../trust/types.js';
9
+ /** What a key is looked up for: checking a signature, or encrypting to a receiver. */
10
+ export type BTPKeyUse = 'verify' | 'encrypt';
11
+ /** Since 1.2: the longest a key chain is trusted from a cache, in seconds, unless a server sets `keyChainMaxCacheSeconds`. */
12
+ export declare const DEFAULT_KEY_CHAIN_MAX_CACHE_SECONDS = 300;
13
+ /**
14
+ * Since 1.2: finds the public keys BTPS checks and encrypts with, so a
15
+ * provider can put its own cache in front of every lookup. Given as the
16
+ * `keyResolver` option of BtpsServer, BtpsClient (and so BtpsAgent and
17
+ * BtpsTransporter), BtpsDelegator, and signEncrypt's `lookup`. It only finds
18
+ * keys: every signature, time window and delegation rule stays inside BTPS.
19
+ */
20
+ export interface BtpsKeyResolver {
21
+ /** The PEM public key of `identity` at `selector`, or undefined when there is none. */
22
+ resolvePublicKey(identity: string, selector: string, use: BTPKeyUse): Promise<string | undefined>;
23
+ /**
24
+ * Since 1.2, optional: `identity`'s key chain, from its host (see
25
+ * `BtpsClient.lookupKeyChain`). A resolver that caches it keeps an answer no
26
+ * longer than the server's `keyChainMaxCacheSeconds`: that is the longest a
27
+ * revoked key can still be taken.
28
+ */
29
+ resolveKeyChain?(identity: string): Promise<BTPKeyChainLookup>;
30
+ }
31
+ /**
32
+ * Since 1.2: the lookup BTPS does without a resolver, to wrap with a cache. A
33
+ * signature key is looked up in DNS only. A receiver's key is looked up in DNS
34
+ * first, then from the receiver's host, in an answer its domain's operator
35
+ * signed; that needs `from`, the sender's own identity, and the TLS options
36
+ * for the connection. Without `from`, an encryption key is looked up in DNS only.
37
+ *
38
+ * Since 1.2, it also gives an identity's key chain from its host, asking as
39
+ * `from`, and keeps each answer (a chain, or none to be had) for
40
+ * `keyChainMaxCacheSeconds`. An answer that fails its checks is not kept.
41
+ * Without `from`, it has no `resolveKeyChain`, so a server given it still
42
+ * asks for chains itself, as its own identity.
43
+ */
44
+ export declare const createDefaultKeyResolver: (options?: {
45
+ from?: string;
46
+ btpMtsOptions?: Omit<ConnectionOptions, "port" | "host">;
47
+ keyChainMaxCacheSeconds?: number;
48
+ }) => BtpsKeyResolver;
@@ -0,0 +1,46 @@
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 { resolvePublicKey } from "../utils/index.js";
9
+ const DEFAULT_KEY_CHAIN_MAX_CACHE_SECONDS = 300, createDefaultKeyResolver = (options) => {
10
+ const clientFor = async (identity) => {
11
+ const { BtpsClient } = await import("../../client/btpsClient.js");
12
+ return new BtpsClient({ to: identity, btpMtsOptions: options?.btpMtsOptions, maxRetries: 0 });
13
+ }, maxAgeMs = (options?.keyChainMaxCacheSeconds ?? DEFAULT_KEY_CHAIN_MAX_CACHE_SECONDS) * 1e3, chains = new Map(), from = options?.from;
14
+ return {
15
+ async resolvePublicKey(identity, selector, use) {
16
+ const inDns = await resolvePublicKey(identity, selector);
17
+ if (inDns || use === "verify" || !options?.from) return inDns;
18
+ const client = await clientFor(identity);
19
+ try {
20
+ return (await client.resolveIdentity(identity, options.from)).response?.publicKey;
21
+ } finally {
22
+ client.destroy();
23
+ }
24
+ },
25
+
26
+ ...from && {
27
+ async resolveKeyChain(identity) {
28
+ const key = identity.toLowerCase(), cached = chains.get(key);
29
+ if (cached && cached.until > Date.now()) return cached.lookup;
30
+ const client = await clientFor(identity);
31
+ try {
32
+ const lookup = await client.lookupKeyChain(identity, from), now = Date.now();
33
+ if (lookup.status === "invalid" ? chains.delete(key) : chains.set(key, { lookup, until: now + maxAgeMs }), chains.size > 1e4)
34
+ for (const [name, kept] of chains) kept.until <= now && chains.delete(name);
35
+ return lookup;
36
+ } finally {
37
+ client.destroy();
38
+ }
39
+ }
40
+ }
41
+ };
42
+ };
43
+ export {
44
+ DEFAULT_KEY_CHAIN_MAX_CACHE_SECONDS,
45
+ createDefaultKeyResolver
46
+ };
@@ -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 {