@btps/sdk 0.0.0-stage → 1.1.0

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 (167) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/LICENSE +190 -0
  3. package/NOTICE +25 -0
  4. package/README.md +261 -2
  5. package/dist/client/btpsAgent.d.ts +20 -0
  6. package/dist/client/btpsAgent.js +172 -0
  7. package/dist/client/btpsClient.d.ts +202 -0
  8. package/dist/client/btpsClient.js +602 -0
  9. package/dist/client/btpsTransporter.d.ts +52 -0
  10. package/dist/client/btpsTransporter.js +249 -0
  11. package/dist/client/constants.ts/index.d.ts +11 -0
  12. package/dist/client/constants.ts/index.js +20 -0
  13. package/dist/client/index.d.ts +12 -0
  14. package/dist/client/index.js +27 -0
  15. package/dist/client/libs/schema.d.ts +27604 -0
  16. package/dist/client/libs/schema.js +56 -0
  17. package/dist/client/libs/timeouts.d.ts +22 -0
  18. package/dist/client/libs/timeouts.js +19 -0
  19. package/dist/client/types/index.d.ts +155 -0
  20. package/dist/client/types/index.js +7 -0
  21. package/dist/core/authentication/BtpsAuthentication.d.ts +128 -0
  22. package/dist/core/authentication/BtpsAuthentication.js +293 -0
  23. package/dist/core/authentication/index.d.ts +11 -0
  24. package/dist/core/authentication/index.js +12 -0
  25. package/dist/core/authentication/keyProof.d.ts +18 -0
  26. package/dist/core/authentication/keyProof.js +16 -0
  27. package/dist/core/authentication/storage/InMemoryAuthSessionStore.d.ts +55 -0
  28. package/dist/core/authentication/storage/InMemoryAuthSessionStore.js +62 -0
  29. package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +63 -0
  30. package/dist/core/authentication/storage/InMemoryTokenStore.js +63 -0
  31. package/dist/core/authentication/types.d.ts +135 -0
  32. package/dist/core/authentication/types.js +7 -0
  33. package/dist/core/crypto/decryptVerify.d.ts +9 -0
  34. package/dist/core/crypto/decryptVerify.js +45 -0
  35. package/dist/core/crypto/decrypter-interface.d.ts +25 -0
  36. package/dist/core/crypto/decrypter-interface.js +7 -0
  37. package/dist/core/crypto/index.d.ts +77 -0
  38. package/dist/core/crypto/index.js +210 -0
  39. package/dist/core/crypto/jcs.d.ts +28 -0
  40. package/dist/core/crypto/jcs.js +60 -0
  41. package/dist/core/crypto/keygen.d.ts +9 -0
  42. package/dist/core/crypto/keygen.js +35 -0
  43. package/dist/core/crypto/pem-decrypter.d.ts +26 -0
  44. package/dist/core/crypto/pem-decrypter.js +52 -0
  45. package/dist/core/crypto/pem-signer.d.ts +21 -0
  46. package/dist/core/crypto/pem-signer.js +34 -0
  47. package/dist/core/crypto/signEncrypt.d.ts +34 -0
  48. package/dist/core/crypto/signEncrypt.js +75 -0
  49. package/dist/core/crypto/signer-interface.d.ts +22 -0
  50. package/dist/core/crypto/signer-interface.js +7 -0
  51. package/dist/core/crypto/types.d.ts +79 -0
  52. package/dist/core/crypto/types.js +7 -0
  53. package/dist/core/delegation/BtpsDelegator.d.ts +102 -0
  54. package/dist/core/delegation/BtpsDelegator.js +118 -0
  55. package/dist/core/delegation/index.d.ts +7 -0
  56. package/dist/core/delegation/index.js +8 -0
  57. package/dist/core/error/constant.d.ts +66 -0
  58. package/dist/core/error/constant.js +194 -0
  59. package/dist/core/error/index.d.ts +35 -0
  60. package/dist/core/error/index.js +52 -0
  61. package/dist/core/error/types.d.ts +16 -0
  62. package/dist/core/error/types.js +7 -0
  63. package/dist/core/server/constants/btps-protocol.d.ts +17 -0
  64. package/dist/core/server/constants/btps-protocol.js +25 -0
  65. package/dist/core/server/constants/control.d.ts +7 -0
  66. package/dist/core/server/constants/control.js +11 -0
  67. package/dist/core/server/constants/currency.d.ts +7 -0
  68. package/dist/core/server/constants/currency.js +332 -0
  69. package/dist/core/server/constants/index.d.ts +26 -0
  70. package/dist/core/server/constants/index.js +61 -0
  71. package/dist/core/server/constants/limits.d.ts +50 -0
  72. package/dist/core/server/constants/limits.js +50 -0
  73. package/dist/core/server/helpers/BtpsMessageQueue.d.ts +13 -0
  74. package/dist/core/server/helpers/BtpsMessageQueue.js +12 -0
  75. package/dist/core/server/helpers/InMemoryQueue.d.ts +16 -0
  76. package/dist/core/server/helpers/InMemoryQueue.js +35 -0
  77. package/dist/core/server/helpers/index.d.ts +8 -0
  78. package/dist/core/server/helpers/index.js +9 -0
  79. package/dist/core/server/schemas/artifacts/agentSchema.d.ts +4565 -0
  80. package/dist/core/server/schemas/artifacts/agentSchema.js +51 -0
  81. package/dist/core/server/schemas/artifacts/artifacts.d.ts +4920 -0
  82. package/dist/core/server/schemas/artifacts/artifacts.js +21 -0
  83. package/dist/core/server/schemas/artifacts/controlSchema.d.ts +23 -0
  84. package/dist/core/server/schemas/artifacts/controlSchema.js +18 -0
  85. package/dist/core/server/schemas/artifacts/identityLookupSchema.d.ts +32 -0
  86. package/dist/core/server/schemas/artifacts/identityLookupSchema.js +21 -0
  87. package/dist/core/server/schemas/artifacts/transporterSchema.d.ts +553 -0
  88. package/dist/core/server/schemas/artifacts/transporterSchema.js +60 -0
  89. package/dist/core/server/schemas/btpsDocsSchema.d.ts +4519 -0
  90. package/dist/core/server/schemas/btpsDocsSchema.js +272 -0
  91. package/dist/core/server/schemas/helpers.d.ts +1612 -0
  92. package/dist/core/server/schemas/helpers.js +87 -0
  93. package/dist/core/server/schemas/responseSchema.d.ts +6918 -0
  94. package/dist/core/server/schemas/responseSchema.js +86 -0
  95. package/dist/core/server/schemas/schema.d.ts +4916 -0
  96. package/dist/core/server/schemas/schema.js +70 -0
  97. package/dist/core/server/schemas/shared.d.ts +21 -0
  98. package/dist/core/server/schemas/shared.js +18 -0
  99. package/dist/core/server/types.d.ts +172 -0
  100. package/dist/core/server/types.js +7 -0
  101. package/dist/core/storage/AbstractIdentityStore.d.ts +17 -0
  102. package/dist/core/storage/AbstractIdentityStore.js +13 -0
  103. package/dist/core/storage/AbstractStorageStore.d.ts +16 -0
  104. package/dist/core/storage/AbstractStorageStore.js +17 -0
  105. package/dist/core/storage/JsonIdentityStore.d.ts +29 -0
  106. package/dist/core/storage/JsonIdentityStore.js +39 -0
  107. package/dist/core/storage/JsonStorageStore.d.ts +59 -0
  108. package/dist/core/storage/JsonStorageStore.js +110 -0
  109. package/dist/core/storage/index.d.ts +11 -0
  110. package/dist/core/storage/index.js +18 -0
  111. package/dist/core/storage/types.d.ts +28 -0
  112. package/dist/core/storage/types.js +7 -0
  113. package/dist/core/trust/index.d.ts +10 -0
  114. package/dist/core/trust/index.js +15 -0
  115. package/dist/core/trust/storage/AbstractTrustStore.d.ts +23 -0
  116. package/dist/core/trust/storage/AbstractTrustStore.js +13 -0
  117. package/dist/core/trust/storage/JsonTrustStore.d.ts +33 -0
  118. package/dist/core/trust/storage/JsonTrustStore.js +42 -0
  119. package/dist/core/trust/trustUtils.d.ts +78 -0
  120. package/dist/core/trust/trustUtils.js +41 -0
  121. package/dist/core/trust/types.d.ts +53 -0
  122. package/dist/core/trust/types.js +7 -0
  123. package/dist/core/utils/identity.d.ts +20 -0
  124. package/dist/core/utils/identity.js +22 -0
  125. package/dist/core/utils/index.d.ts +70 -0
  126. package/dist/core/utils/index.js +124 -0
  127. package/dist/core/utils/types.d.ts +10 -0
  128. package/dist/core/utils/types.js +7 -0
  129. package/dist/core/utils/validation.d.ts +14 -0
  130. package/dist/core/utils/validation.js +13 -0
  131. package/dist/index.d.ts +7 -0
  132. package/dist/index.js +8 -0
  133. package/dist/server/btpsServer.d.ts +292 -0
  134. package/dist/server/btpsServer.js +827 -0
  135. package/dist/server/index.d.ts +11 -0
  136. package/dist/server/index.js +15 -0
  137. package/dist/server/libs/abstractRateLimiter.d.ts +10 -0
  138. package/dist/server/libs/abstractRateLimiter.js +15 -0
  139. package/dist/server/libs/artifactSizeGuard.d.ts +27 -0
  140. package/dist/server/libs/artifactSizeGuard.js +44 -0
  141. package/dist/server/libs/artifactTimeWindow.d.ts +24 -0
  142. package/dist/server/libs/artifactTimeWindow.js +30 -0
  143. package/dist/server/libs/btpsFactory.d.ts +29 -0
  144. package/dist/server/libs/btpsFactory.js +49 -0
  145. package/dist/server/libs/btpsLightweightFactory.d.ts +35 -0
  146. package/dist/server/libs/btpsLightweightFactory.js +37 -0
  147. package/dist/server/libs/btpsRegistry.d.ts +14 -0
  148. package/dist/server/libs/btpsRegistry.js +16 -0
  149. package/dist/server/libs/btpsSimpleMetricsTracker.d.ts +13 -0
  150. package/dist/server/libs/btpsSimpleMetricsTracker.js +21 -0
  151. package/dist/server/libs/btpsSimpleRateLimiter.d.ts +28 -0
  152. package/dist/server/libs/btpsSimpleRateLimiter.js +46 -0
  153. package/dist/server/libs/connectionTimeout.d.ts +16 -0
  154. package/dist/server/libs/connectionTimeout.js +14 -0
  155. package/dist/server/libs/defaultMiddleware.d.ts +8 -0
  156. package/dist/server/libs/defaultMiddleware.js +128 -0
  157. package/dist/server/libs/inFlightLimit.d.ts +18 -0
  158. package/dist/server/libs/inFlightLimit.js +17 -0
  159. package/dist/server/libs/index.d.ts +18 -0
  160. package/dist/server/libs/index.js +34 -0
  161. package/dist/server/libs/middlewareManager.d.ts +59 -0
  162. package/dist/server/libs/middlewareManager.js +126 -0
  163. package/dist/server/libs/type.d.ts +22 -0
  164. package/dist/server/libs/type.js +7 -0
  165. package/dist/server/types.d.ts +236 -0
  166. package/dist/server/types.js +7 -0
  167. package/package.json +126 -4
@@ -0,0 +1,210 @@
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, { constants, createHash, randomBytes } from "crypto";
9
+ import { performance } from "perf_hooks";
10
+ import {
11
+ BTP_ERROR_UNSUPPORTED_ENCRYPT,
12
+ BTP_ERROR_DECRYPTION_UNINTENDED,
13
+ BTP_ERROR_SIG_MISMATCH,
14
+ BTP_ERROR_SIG_VERIFICATION,
15
+ BTP_ERROR_UNKNOWN
16
+ } from "../error/constant.js";
17
+ import { BTPErrorException } from "../error/index.js";
18
+ import { assertStrictJson, canonicalize, canonicalizeValue } from "./jcs.js";
19
+ import { assertFullLengthAuthTag } from "./pem-decrypter.js";
20
+ export * from "./decryptVerify.js";
21
+ export * from "./jcs.js";
22
+ export * from "./signEncrypt.js";
23
+ export * from "./keygen.js";
24
+ export * from "./types.js";
25
+ export * from "./signer-interface.js";
26
+ export * from "./decrypter-interface.js";
27
+ export * from "./pem-signer.js";
28
+ export * from "./pem-decrypter.js";
29
+ const encryptBtpPayload = (payload = "", receiverPubPem, options = {
30
+ algorithm: "aes-256-gcm",
31
+ mode: "standardEncrypt"
32
+ }) => {
33
+ const aesKey = crypto.randomBytes(32), iv = crypto.randomBytes(12), algorithm = options.algorithm, stringifiedPayload = typeof payload != "string" ? JSON.stringify(payload) : payload, cipher = crypto.createCipheriv(algorithm, aesKey, iv);
34
+ let encryptedPayload = cipher.update(stringifiedPayload, "utf8", "base64");
35
+ encryptedPayload += cipher.final("base64");
36
+ const authTag = cipher.getAuthTag(), encryptedKey = encryptRSA(receiverPubPem, aesKey);
37
+ return {
38
+ data: encryptedPayload,
39
+ encryption: {
40
+ algorithm,
41
+ encryptedKey: encryptedKey.toString("base64"),
42
+ iv: iv.toString("base64"),
43
+ authTag: authTag.toString("base64"),
44
+ type: options.mode
45
+ }
46
+ };
47
+ }, decryptBtpPayload = (payload = "", encryption, receiverPrivPem) => {
48
+ if (encryption.algorithm !== "aes-256-gcm")
49
+ return {
50
+ data: void 0,
51
+ error: new BTPErrorException(BTP_ERROR_UNSUPPORTED_ENCRYPT)
52
+ };
53
+ try {
54
+ const decryptedKey = decryptRSA(
55
+ receiverPrivPem,
56
+ Buffer.from(encryption.encryptedKey, "base64")
57
+ ), authTag = Buffer.from(encryption.authTag, "base64");
58
+ assertFullLengthAuthTag(authTag);
59
+ const decipher = crypto.createDecipheriv(
60
+ encryption.algorithm,
61
+ decryptedKey,
62
+ Buffer.from(encryption.iv, "base64"),
63
+ { authTagLength: 16 }
64
+ );
65
+ decipher.setAuthTag(authTag);
66
+ const stringifiedPayload = typeof payload != "string" ? JSON.stringify(payload) : payload;
67
+ let decryptedPayload = decipher.update(stringifiedPayload, "base64", "utf8");
68
+ return decryptedPayload += decipher.final("utf8"), assertStrictJson(decryptedPayload), {
69
+ data: JSON.parse(decryptedPayload),
70
+ error: void 0
71
+ };
72
+ } catch (err) {
73
+ return { data: void 0, error: decryptionError(err) };
74
+ }
75
+ }, decryptBtpPayloadWithDecrypter = async (payload = "", encryption, decrypter) => {
76
+ if (encryption.algorithm !== "aes-256-gcm")
77
+ return {
78
+ data: void 0,
79
+ error: new BTPErrorException(BTP_ERROR_UNSUPPORTED_ENCRYPT)
80
+ };
81
+ try {
82
+ const stringifiedPayload = typeof payload != "string" ? JSON.stringify(payload) : payload, plaintext = await decrypter.decrypt({
83
+ encryptedKey: Buffer.from(encryption.encryptedKey, "base64"),
84
+ iv: Buffer.from(encryption.iv, "base64"),
85
+ ciphertext: Buffer.from(stringifiedPayload, "base64"),
86
+ authTag: Buffer.from(encryption.authTag, "base64")
87
+ }), decryptedPayload = Buffer.from(plaintext).toString("utf8");
88
+ return assertStrictJson(decryptedPayload), {
89
+ data: JSON.parse(decryptedPayload),
90
+ error: void 0
91
+ };
92
+ } catch (err) {
93
+ return { data: void 0, error: decryptionError(err) };
94
+ }
95
+ }, WRONG_KEY_CODES = [
96
+ "ERR_OSSL_RSA_OAEP_DECODING_ERROR",
97
+ "ERR_OSSL_RSA_DATA_TOO_LARGE_FOR_MODULUS"
98
+ ], decryptionError = (err) => err instanceof BTPErrorException ? err : typeof err == "object" && err !== null && "code" in err && typeof err.code == "string" && WRONG_KEY_CODES.includes(err.code) ? new BTPErrorException(BTP_ERROR_DECRYPTION_UNINTENDED) : err instanceof Error ? new BTPErrorException({ message: err.message, code: err.name }) : new BTPErrorException(BTP_ERROR_UNKNOWN), MIN_RSA_KEY_BITS = 2048, encryptRSA = (publicKeyPem, data) => {
99
+ const bits = crypto.createPublicKey(publicKeyPem).asymmetricKeyDetails?.modulusLength ?? 0;
100
+ if (bits < MIN_RSA_KEY_BITS)
101
+ throw new BTPErrorException(BTP_ERROR_UNSUPPORTED_ENCRYPT, {
102
+ cause: `the receiver's RSA key is ${bits} bits; at least ${MIN_RSA_KEY_BITS} are required`
103
+ });
104
+ return crypto.publicEncrypt(
105
+ {
106
+ key: publicKeyPem,
107
+ padding: constants.RSA_PKCS1_OAEP_PADDING,
108
+ oaepHash: "sha256"
109
+ },
110
+ data
111
+ );
112
+ }, decryptRSA = (privateKeyPem, encrypted) => crypto.privateDecrypt(
113
+ {
114
+ key: privateKeyPem,
115
+ padding: constants.RSA_PKCS1_OAEP_PADDING,
116
+ oaepHash: "sha256"
117
+ },
118
+ encrypted
119
+ ), getFingerprintFromPem = (pem, hashAlgorithm = "sha256") => {
120
+ const normalizedPem = pem.trim();
121
+ if (!normalizedPem.startsWith("-----BEGIN PUBLIC KEY-----") || !normalizedPem.endsWith("-----END PUBLIC KEY-----"))
122
+ throw new BTPErrorException(BTP_ERROR_SIG_MISMATCH, {
123
+ meta: { reason: "Invalid PEM: Must be a public key in SPKI format" }
124
+ });
125
+ const der = crypto.createPublicKey({
126
+ key: normalizedPem,
127
+ format: "pem",
128
+ type: "spki"
129
+ }).export({ format: "der", type: "spki" });
130
+ return crypto.createHash(hashAlgorithm).update(der).digest("base64");
131
+ }, signedBytes = (payload) => Buffer.from(
132
+ typeof payload == "string" ? canonicalize(payload) : canonicalizeValue(payload),
133
+ "utf8"
134
+ ), signBtpPayload = (payload = "", senderPemFiles) => {
135
+ const canonicalPayload = signedBytes(payload), { publicKey, privateKey } = senderPemFiles, algorithmHash = "sha256", signature = crypto.sign("sha256", canonicalPayload, privateKey), senderFingerprint = getFingerprintFromPem(publicKey, "sha256");
136
+ return {
137
+ algorithmHash,
138
+ value: signature.toString("base64"),
139
+ fingerprint: senderFingerprint
140
+ };
141
+ }, signBtpPayloadWithSigner = async (payload = "", signer) => {
142
+ const signature = await signer.sign(signedBytes(payload)), { publicKey } = await signer.getPublicKey();
143
+ return {
144
+ algorithmHash: "sha256",
145
+ value: Buffer.from(signature).toString("base64"),
146
+ fingerprint: getFingerprintFromPem(publicKey, "sha256")
147
+ };
148
+ }, verifySignature = (payload = "", signature, senderPubKey) => {
149
+ let canonicalPayload;
150
+ try {
151
+ canonicalPayload = signedBytes(payload);
152
+ } catch (error) {
153
+ return {
154
+ isValid: !1,
155
+ error: error instanceof BTPErrorException ? error : new BTPErrorException(BTP_ERROR_SIG_VERIFICATION, { cause: error })
156
+ };
157
+ }
158
+ let senderFingerprint, keyProblem;
159
+ try {
160
+ senderFingerprint = getFingerprintFromPem(senderPubKey, signature.algorithmHash);
161
+ } catch (error) {
162
+ const reason = error instanceof BTPErrorException ? error.meta?.reason : void 0;
163
+ keyProblem = typeof reason == "string" ? reason : error instanceof Error ? error.message : String(error);
164
+ }
165
+ if (senderFingerprint !== signature.fingerprint)
166
+ return {
167
+ isValid: !1,
168
+ error: new BTPErrorException(BTP_ERROR_SIG_MISMATCH, {
169
+ meta: {
170
+ expected: senderFingerprint,
171
+ actual: signature.fingerprint,
172
+ ...keyProblem !== void 0 && { reason: keyProblem }
173
+ }
174
+ })
175
+ };
176
+ const isValid = crypto.verify(
177
+ signature.algorithmHash,
178
+ canonicalPayload,
179
+ senderPubKey,
180
+ Buffer.from(signature.value, "base64")
181
+ );
182
+ return {
183
+ isValid,
184
+ error: isValid ? void 0 : new BTPErrorException(BTP_ERROR_SIG_VERIFICATION, {
185
+ meta: { reason: "Signature verification failed despite matching fingerprints" }
186
+ })
187
+ };
188
+ }, DEFAULT_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
189
+ function generateUserToken(userIdentity, length = 12, charactersFrom = DEFAULT_ALPHABET) {
190
+ if (length < 8 || length > 24)
191
+ throw new BTPErrorException({ message: "Token length must be between 8 and 24 characters." });
192
+ const entropyInput = userIdentity + performance.now().toString() + randomBytes(4).toString("hex"), hash = createHash("sha256");
193
+ hash.update(entropyInput);
194
+ const digest = hash.digest(), sliced = new Uint8Array(digest).slice(0, length);
195
+ return Array.from(sliced).map((byte) => charactersFrom[byte % charactersFrom.length]).join("").toUpperCase();
196
+ }
197
+ export {
198
+ DEFAULT_ALPHABET,
199
+ MIN_RSA_KEY_BITS,
200
+ decryptBtpPayload,
201
+ decryptBtpPayloadWithDecrypter,
202
+ decryptRSA,
203
+ encryptBtpPayload,
204
+ encryptRSA,
205
+ generateUserToken,
206
+ getFingerprintFromPem,
207
+ signBtpPayload,
208
+ signBtpPayloadWithSigner,
209
+ verifySignature
210
+ };
@@ -0,0 +1,28 @@
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
+ * Refuses a text that is not JSON, or that names a member twice in any
9
+ * object, at any depth. Two parsers could otherwise read different values
10
+ * from the same signed bytes. (A raw control character inside a string gets
11
+ * past this check; `JSON.parse` refuses it.)
12
+ *
13
+ * @throws {BTPErrorException} BTP_ERROR_CANONICAL_JSON
14
+ */
15
+ export declare const assertStrictJson: (text: string) => void;
16
+ /**
17
+ * The canonical form of an in-memory value: of what `JSON.stringify` would
18
+ * send for it, so `undefined` members are dropped and `toJSON` applies.
19
+ *
20
+ * @throws {BTPErrorException} BTP_ERROR_CANONICAL_JSON
21
+ */
22
+ export declare const canonicalizeValue: (value: unknown) => string;
23
+ /**
24
+ * The canonical form of a JSON text, refusing duplicate member names.
25
+ *
26
+ * @throws {BTPErrorException} BTP_ERROR_CANONICAL_JSON
27
+ */
28
+ export declare const canonicalize: (text: string) => string;
@@ -0,0 +1,60 @@
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 serialize from "canonicalize";
9
+ import { iterator, parse } from "@humanwhocodes/momoa";
10
+ import { BTP_ERROR_CANONICAL_JSON } from "../error/constant.js";
11
+ import { BTPErrorException } from "../error/index.js";
12
+ const canonicalJsonError = (cause) => new BTPErrorException(BTP_ERROR_CANONICAL_JSON, { cause }), isObjectNode = (node) => node.type === "Object", serializeJson = (value) => {
13
+ let canonical;
14
+ try {
15
+ canonical = serialize(value);
16
+ } catch (error) {
17
+ throw canonicalJsonError(error);
18
+ }
19
+ if (canonical === void 0) throw canonicalJsonError("the value has no JSON form");
20
+ return canonical;
21
+ }, assertStrictJson = (text) => {
22
+ let document;
23
+ try {
24
+ document = parse(text, { mode: "json" });
25
+ } catch (error) {
26
+ throw canonicalJsonError(error);
27
+ }
28
+ for (const { node } of iterator(document)) {
29
+ if (!isObjectNode(node)) continue;
30
+ const names = new Set();
31
+ for (const { name } of node.members) {
32
+ const key = name.type === "String" ? name.value : name.name;
33
+ if (names.has(key)) throw canonicalJsonError(`duplicate member name "${key}"`);
34
+ names.add(key);
35
+ }
36
+ }
37
+ }, canonicalizeValue = (value) => {
38
+ let sent;
39
+ try {
40
+ sent = JSON.stringify(value);
41
+ } catch (error) {
42
+ throw canonicalJsonError(error);
43
+ }
44
+ if (sent === void 0) throw canonicalJsonError("the value has no JSON form");
45
+ return serializeJson(JSON.parse(sent));
46
+ }, canonicalize = (text) => {
47
+ assertStrictJson(text);
48
+ let value;
49
+ try {
50
+ value = JSON.parse(text);
51
+ } catch (error) {
52
+ throw canonicalJsonError(error);
53
+ }
54
+ return serializeJson(value);
55
+ };
56
+ export {
57
+ assertStrictJson,
58
+ canonicalize,
59
+ canonicalizeValue
60
+ };
@@ -0,0 +1,9 @@
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 { BTPKeyConfig, BTPKeyPair } from './types.js';
8
+ export declare function generateKeys(accountName: string): Promise<void>;
9
+ export declare const getBTPKeyPair: (keyConfig?: BTPKeyConfig) => BTPKeyPair;
@@ -0,0 +1,35 @@
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 { generateKeyPairSync } from "crypto";
9
+ import { writeFileSync, mkdirSync } from "fs";
10
+ import { join } from "path";
11
+ import { getFingerprintFromPem } from "./index.js";
12
+ async function generateKeys(accountName) {
13
+ const dir = join("keys", accountName);
14
+ mkdirSync(dir, { recursive: !0 });
15
+ const { publicKey, privateKey } = getBTPKeyPair();
16
+ writeFileSync(join(dir, `${accountName}-private.pem`), privateKey), writeFileSync(join(dir, `${accountName}-public.pem`), publicKey), console.log(`\u2705 Keys created for '${accountName}' in ${dir}`);
17
+ }
18
+ const getBTPKeyPair = (keyConfig) => {
19
+ const { publicKey, privateKey } = generateKeyPairSync("rsa", {
20
+ modulusLength: keyConfig?.keySize ?? 2048,
21
+ publicKeyEncoding: {
22
+ type: keyConfig?.publicKeyEncoding ?? "spki",
23
+ format: keyConfig?.format ?? "pem"
24
+ },
25
+ privateKeyEncoding: {
26
+ type: keyConfig?.privateKeyEncoding ?? "pkcs8",
27
+ format: keyConfig?.format ?? "pem"
28
+ }
29
+ }), fingerprint = getFingerprintFromPem(publicKey, "sha256");
30
+ return { publicKey, privateKey, fingerprint };
31
+ };
32
+ export {
33
+ generateKeys,
34
+ getBTPKeyPair
35
+ };
@@ -0,0 +1,26 @@
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 { Decrypter, DecryptRequest } from './decrypter-interface.js';
8
+ export interface PemDecrypterOptions {
9
+ /** PKCS#8 PEM. Held only by this instance — never exposed on Decrypter. */
10
+ privateKey: string;
11
+ }
12
+ export declare class PemDecrypter implements Decrypter {
13
+ readonly algorithm: "aes-256-gcm";
14
+ private readonly privateKeyPem;
15
+ constructor(options: PemDecrypterOptions);
16
+ decrypt(request: DecryptRequest): Promise<Uint8Array>;
17
+ }
18
+ /** Rejects any tag that isn't exactly 16 bytes before it ever reaches
19
+ * the AEAD check — a short tag is a materially weaker guarantee, not a
20
+ * smaller version of the same one. */
21
+ export declare function assertFullLengthAuthTag(authTag: Uint8Array): void;
22
+ /** The local AES-GCM step, once the AES key is unwrapped. A Decrypter whose
23
+ * key holder only unwraps the AES key (as a KMS does) can finish with this.
24
+ * It also pins authTagLength at the cipher level, so Node itself refuses a
25
+ * tag shorter than 16 bytes rather than relying on the pre-check alone. */
26
+ export declare function decryptAesGcm(aesKey: Buffer, request: DecryptRequest): Uint8Array;
@@ -0,0 +1,52 @@
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 { BTP_ERROR_UNSUPPORTED_ENCRYPT } from "../error/constant.js";
11
+ const ALGORITHM = "aes-256-gcm", AUTH_TAG_LENGTH = 16;
12
+ class PemDecrypter {
13
+ algorithm = ALGORITHM;
14
+ privateKeyPem;
15
+ constructor(options) {
16
+ this.privateKeyPem = options.privateKey;
17
+ }
18
+ async decrypt(request) {
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
+ );
28
+ return decryptAesGcm(aesKey, request);
29
+ }
30
+ }
31
+ function assertFullLengthAuthTag(authTag) {
32
+ if (authTag.length !== AUTH_TAG_LENGTH)
33
+ throw new BTPErrorException(BTP_ERROR_UNSUPPORTED_ENCRYPT, {
34
+ cause: `AES-GCM auth tag must be ${AUTH_TAG_LENGTH} bytes, got ${authTag.length}`
35
+ });
36
+ }
37
+ function decryptAesGcm(aesKey, request) {
38
+ const decipher = crypto.createDecipheriv("aes-256-gcm", aesKey, Buffer.from(request.iv), {
39
+ authTagLength: AUTH_TAG_LENGTH
40
+ });
41
+ request.additionalData && decipher.setAAD(Buffer.from(request.additionalData)), decipher.setAuthTag(Buffer.from(request.authTag));
42
+ const plaintext = Buffer.concat([
43
+ decipher.update(Buffer.from(request.ciphertext)),
44
+ decipher.final()
45
+ ]);
46
+ return new Uint8Array(plaintext);
47
+ }
48
+ export {
49
+ PemDecrypter,
50
+ assertFullLengthAuthTag,
51
+ decryptAesGcm
52
+ };
@@ -0,0 +1,21 @@
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 { Signer, SignerPublicKey } from './signer-interface.js';
8
+ export interface PemSignerOptions {
9
+ /** SPKI PEM. */
10
+ publicKey: string;
11
+ /** PKCS#8 PEM. Held only by this instance — never exposed on Signer. */
12
+ privateKey: string;
13
+ }
14
+ export declare class PemSigner implements Signer {
15
+ readonly algorithm: "RSASSA_PKCS1_V1_5_SHA_256";
16
+ private readonly publicKeyPem;
17
+ private readonly privateKeyPem;
18
+ constructor(options: PemSignerOptions);
19
+ sign(data: Uint8Array): Promise<Uint8Array>;
20
+ getPublicKey(): Promise<SignerPublicKey>;
21
+ }
@@ -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
+
8
+ import crypto from "crypto";
9
+ const ALGORITHM = "RSASSA_PKCS1_V1_5_SHA_256";
10
+ class PemSigner {
11
+ algorithm = ALGORITHM;
12
+ publicKeyPem;
13
+ privateKeyPem;
14
+ constructor(options) {
15
+ this.publicKeyPem = options.publicKey, this.privateKeyPem = options.privateKey;
16
+ }
17
+ async sign(data) {
18
+ const signature = crypto.sign("sha256", Buffer.from(data), this.privateKeyPem);
19
+ return new Uint8Array(signature);
20
+ }
21
+ async getPublicKey() {
22
+ return {
23
+ publicKey: this.publicKeyPem,
24
+ fingerprint: fingerprintFromPem(this.publicKeyPem)
25
+ };
26
+ }
27
+ }
28
+ function fingerprintFromPem(publicKeyPem) {
29
+ const der = crypto.createPublicKey({ key: publicKeyPem, format: "pem", type: "spki" }).export({ format: "der", type: "spki" });
30
+ return crypto.createHash("sha256").update(der).digest("base64");
31
+ }
32
+ export {
33
+ PemSigner
34
+ };
@@ -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 { ConnectionOptions } from 'tls';
8
+ import type { Signer } from './signer-interface.js';
9
+ import { BTPCryptoResponse, PemKeys, BTPCryptoOptions } from './types.js';
10
+ import { ParsedIdentity } from '../utils/types.js';
11
+ /** How signEncrypt reaches a receiver's host when DNS has no key for it. */
12
+ export type ReceiverKeyLookup = {
13
+ /** TLS options for the connection to the receiver's host */
14
+ btpMtsOptions?: Omit<ConnectionOptions, 'port' | 'host'>;
15
+ };
16
+ /**
17
+ * Signs an artifact with the sender's key and, when `to` and encryption
18
+ * options are given, encrypts its document to the receiver's current key.
19
+ *
20
+ * `payload.selector` is the sender's own selector: the one its signing key
21
+ * is published at, which the receiver uses to verify the signature. The
22
+ * receiver's key is found at the selector the receiver's own host record
23
+ * names: in DNS, or else from the receiver's host (`lookup` gives the TLS
24
+ * options for that connection).
25
+ */
26
+ export declare const signEncrypt: <T = unknown>(to: string | undefined, sender: ParsedIdentity & ({
27
+ pemFiles: PemKeys;
28
+ } | {
29
+ signer: Signer;
30
+ }), payload: {
31
+ document: T;
32
+ selector?: string;
33
+ [key: string]: unknown;
34
+ }, options?: BTPCryptoOptions, lookup?: ReceiverKeyLookup) => Promise<BTPCryptoResponse<T>>;
@@ -0,0 +1,75 @@
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 { randomUUID } from "crypto";
9
+ import {
10
+ BTP_ERROR_IDENTITY,
11
+ BTP_ERROR_RESOLVE_PUBKEY,
12
+ BTP_ERROR_VALIDATION
13
+ } from "../error/constant.js";
14
+ import { processBtpDocSchema } from "../server/schemas/helpers.js";
15
+ import { signBtpPayload, signBtpPayloadWithSigner, encryptBtpPayload } from "./index.js";
16
+ import { getHostAndSelector, parseIdentity, resolvePublicKey } from "../utils/index.js";
17
+ import { BTPErrorException } from "../error/index.js";
18
+ import isEmpty from "lodash/isEmpty.js";
19
+ const genEncryptError = (error) => ({
20
+ payload: void 0,
21
+ error
22
+ }), findReceiverKey = async (to, from, selector, lookup) => {
23
+ const inDns = await resolvePublicKey(to, selector);
24
+ if (inDns) return inDns;
25
+ const { BtpsClient } = await import("../../client/btpsClient.js"), client = new BtpsClient({ to, btpMtsOptions: lookup?.btpMtsOptions, maxRetries: 0 });
26
+ try {
27
+ return (await client.resolveIdentity(to, from)).response?.publicKey;
28
+ } finally {
29
+ client.destroy();
30
+ }
31
+ }, signEncrypt = async (to, sender, payload, options, lookup) => {
32
+ const { document, ...restPayload } = payload;
33
+ let encryption = null, encryptedDoc = document;
34
+ if (to && !isEmpty(options?.encryption)) {
35
+ const docSchema = processBtpDocSchema(restPayload.type);
36
+ if (docSchema && !docSchema.safeParse(document).success)
37
+ return genEncryptError(
38
+ new BTPErrorException(BTP_ERROR_VALIDATION, {
39
+ cause: "Document type does not match the artifact type"
40
+ })
41
+ );
42
+ if (!parseIdentity(to)) return genEncryptError(new BTPErrorException(BTP_ERROR_IDENTITY));
43
+ const receiverHost = await getHostAndSelector(to), from = `${sender.accountName}$${sender.domainName}`, receiverPubPem = receiverHost ? await findReceiverKey(to, from, receiverHost.selector, lookup) : void 0;
44
+ if (!receiverPubPem) return genEncryptError(new BTPErrorException(BTP_ERROR_RESOLVE_PUBKEY));
45
+ try {
46
+ const encryptedData = isEmpty(options?.encryption) ? { encryption: null, data: encryptedDoc } : encryptBtpPayload(encryptedDoc, receiverPubPem, options?.encryption);
47
+ encryption = encryptedData.encryption, encryptedDoc = encryptedData.data;
48
+ } catch (error) {
49
+ return genEncryptError(error);
50
+ }
51
+ }
52
+ const docToSign = {
53
+ ...restPayload,
54
+ id: restPayload?.id ?? randomUUID(),
55
+ issuedAt: restPayload?.issuedAt ?? ( new Date()).toISOString(),
56
+ document: encryption ? encryptedDoc : document,
57
+ encryption
58
+ };
59
+ let signature;
60
+ try {
61
+ signature = "signer" in sender ? await signBtpPayloadWithSigner(docToSign, sender.signer) : signBtpPayload(docToSign, sender.pemFiles);
62
+ } catch (error) {
63
+ return genEncryptError(error);
64
+ }
65
+ return {
66
+ payload: {
67
+ ...docToSign,
68
+ signature
69
+ },
70
+ error: void 0
71
+ };
72
+ };
73
+ export {
74
+ signEncrypt
75
+ };
@@ -0,0 +1,22 @@
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
+ /** The single supported signing algorithm, by its KMS name: RSA PKCS#1 v1.5
8
+ * with SHA-256. */
9
+ export type SignerAlgorithm = 'RSASSA_PKCS1_V1_5_SHA_256';
10
+ export interface SignerPublicKey {
11
+ /** SPKI PEM. */
12
+ publicKey: string;
13
+ /** SHA-256 digest of the DER-encoded SPKI public key, base64-encoded. */
14
+ fingerprint: string;
15
+ }
16
+ export interface Signer {
17
+ readonly algorithm: SignerAlgorithm;
18
+ /** Signs `data` and returns the raw signature bytes. */
19
+ sign(data: Uint8Array): Promise<Uint8Array>;
20
+ /** Returns this signer's own public key — never its private key. */
21
+ getPublicKey(): Promise<SignerPublicKey>;
22
+ }
@@ -0,0 +1,7 @@
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
+