@btps/sdk 0.0.0-stage → 1.1.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 (155) hide show
  1. package/CHANGELOG.md +171 -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/index.d.ts +11 -0
  12. package/dist/client/constants/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.js +56 -0
  16. package/dist/client/libs/timeouts.d.ts +22 -0
  17. package/dist/client/libs/timeouts.js +19 -0
  18. package/dist/client/types/index.d.ts +155 -0
  19. package/dist/client/types/index.js +7 -0
  20. package/dist/core/authentication/BtpsAuthentication.d.ts +128 -0
  21. package/dist/core/authentication/BtpsAuthentication.js +293 -0
  22. package/dist/core/authentication/index.d.ts +11 -0
  23. package/dist/core/authentication/index.js +12 -0
  24. package/dist/core/authentication/keyProof.d.ts +18 -0
  25. package/dist/core/authentication/keyProof.js +16 -0
  26. package/dist/core/authentication/storage/InMemoryAuthSessionStore.d.ts +55 -0
  27. package/dist/core/authentication/storage/InMemoryAuthSessionStore.js +62 -0
  28. package/dist/core/authentication/storage/InMemoryTokenStore.d.ts +63 -0
  29. package/dist/core/authentication/storage/InMemoryTokenStore.js +63 -0
  30. package/dist/core/authentication/types.d.ts +135 -0
  31. package/dist/core/authentication/types.js +7 -0
  32. package/dist/core/crypto/decryptVerify.d.ts +9 -0
  33. package/dist/core/crypto/decryptVerify.js +45 -0
  34. package/dist/core/crypto/decrypter-interface.d.ts +25 -0
  35. package/dist/core/crypto/decrypter-interface.js +7 -0
  36. package/dist/core/crypto/index.d.ts +77 -0
  37. package/dist/core/crypto/index.js +210 -0
  38. package/dist/core/crypto/jcs.d.ts +28 -0
  39. package/dist/core/crypto/jcs.js +60 -0
  40. package/dist/core/crypto/keygen.d.ts +9 -0
  41. package/dist/core/crypto/keygen.js +35 -0
  42. package/dist/core/crypto/pem-decrypter.d.ts +26 -0
  43. package/dist/core/crypto/pem-decrypter.js +52 -0
  44. package/dist/core/crypto/pem-signer.d.ts +21 -0
  45. package/dist/core/crypto/pem-signer.js +34 -0
  46. package/dist/core/crypto/signEncrypt.d.ts +34 -0
  47. package/dist/core/crypto/signEncrypt.js +75 -0
  48. package/dist/core/crypto/signer-interface.d.ts +22 -0
  49. package/dist/core/crypto/signer-interface.js +7 -0
  50. package/dist/core/crypto/types.d.ts +79 -0
  51. package/dist/core/crypto/types.js +7 -0
  52. package/dist/core/delegation/BtpsDelegator.d.ts +102 -0
  53. package/dist/core/delegation/BtpsDelegator.js +118 -0
  54. package/dist/core/delegation/index.d.ts +7 -0
  55. package/dist/core/delegation/index.js +8 -0
  56. package/dist/core/error/constant.d.ts +66 -0
  57. package/dist/core/error/constant.js +194 -0
  58. package/dist/core/error/index.d.ts +35 -0
  59. package/dist/core/error/index.js +52 -0
  60. package/dist/core/error/types.d.ts +16 -0
  61. package/dist/core/error/types.js +7 -0
  62. package/dist/core/server/constants/btps-protocol.d.ts +17 -0
  63. package/dist/core/server/constants/btps-protocol.js +25 -0
  64. package/dist/core/server/constants/control.d.ts +7 -0
  65. package/dist/core/server/constants/control.js +11 -0
  66. package/dist/core/server/constants/currency.d.ts +7 -0
  67. package/dist/core/server/constants/currency.js +332 -0
  68. package/dist/core/server/constants/index.d.ts +26 -0
  69. package/dist/core/server/constants/index.js +61 -0
  70. package/dist/core/server/constants/limits.d.ts +50 -0
  71. package/dist/core/server/constants/limits.js +50 -0
  72. package/dist/core/server/helpers/BtpsMessageQueue.d.ts +13 -0
  73. package/dist/core/server/helpers/BtpsMessageQueue.js +12 -0
  74. package/dist/core/server/helpers/InMemoryQueue.d.ts +16 -0
  75. package/dist/core/server/helpers/InMemoryQueue.js +35 -0
  76. package/dist/core/server/helpers/index.d.ts +8 -0
  77. package/dist/core/server/helpers/index.js +9 -0
  78. package/dist/core/server/schemas/artifacts/agentSchema.js +51 -0
  79. package/dist/core/server/schemas/artifacts/artifacts.js +21 -0
  80. package/dist/core/server/schemas/artifacts/controlSchema.js +18 -0
  81. package/dist/core/server/schemas/artifacts/identityLookupSchema.js +21 -0
  82. package/dist/core/server/schemas/artifacts/transporterSchema.js +60 -0
  83. package/dist/core/server/schemas/btpsDocsSchema.d.ts +4519 -0
  84. package/dist/core/server/schemas/btpsDocsSchema.js +272 -0
  85. package/dist/core/server/schemas/helpers.js +87 -0
  86. package/dist/core/server/schemas/responseSchema.js +86 -0
  87. package/dist/core/server/schemas/schema.js +70 -0
  88. package/dist/core/server/schemas/shared.js +18 -0
  89. package/dist/core/server/types.d.ts +172 -0
  90. package/dist/core/server/types.js +7 -0
  91. package/dist/core/storage/AbstractIdentityStore.d.ts +17 -0
  92. package/dist/core/storage/AbstractIdentityStore.js +13 -0
  93. package/dist/core/storage/AbstractStorageStore.d.ts +16 -0
  94. package/dist/core/storage/AbstractStorageStore.js +17 -0
  95. package/dist/core/storage/JsonIdentityStore.d.ts +29 -0
  96. package/dist/core/storage/JsonIdentityStore.js +39 -0
  97. package/dist/core/storage/JsonStorageStore.d.ts +59 -0
  98. package/dist/core/storage/JsonStorageStore.js +110 -0
  99. package/dist/core/storage/index.d.ts +11 -0
  100. package/dist/core/storage/index.js +18 -0
  101. package/dist/core/storage/types.d.ts +28 -0
  102. package/dist/core/storage/types.js +7 -0
  103. package/dist/core/trust/index.d.ts +10 -0
  104. package/dist/core/trust/index.js +15 -0
  105. package/dist/core/trust/storage/AbstractTrustStore.d.ts +23 -0
  106. package/dist/core/trust/storage/AbstractTrustStore.js +13 -0
  107. package/dist/core/trust/storage/JsonTrustStore.d.ts +33 -0
  108. package/dist/core/trust/storage/JsonTrustStore.js +42 -0
  109. package/dist/core/trust/trustUtils.d.ts +78 -0
  110. package/dist/core/trust/trustUtils.js +41 -0
  111. package/dist/core/trust/types.d.ts +53 -0
  112. package/dist/core/trust/types.js +7 -0
  113. package/dist/core/utils/identity.d.ts +20 -0
  114. package/dist/core/utils/identity.js +22 -0
  115. package/dist/core/utils/index.d.ts +70 -0
  116. package/dist/core/utils/index.js +124 -0
  117. package/dist/core/utils/types.d.ts +10 -0
  118. package/dist/core/utils/types.js +7 -0
  119. package/dist/core/utils/validation.js +13 -0
  120. package/dist/index.d.ts +7 -0
  121. package/dist/index.js +8 -0
  122. package/dist/server/btpsServer.d.ts +292 -0
  123. package/dist/server/btpsServer.js +827 -0
  124. package/dist/server/index.d.ts +11 -0
  125. package/dist/server/index.js +15 -0
  126. package/dist/server/libs/abstractRateLimiter.d.ts +10 -0
  127. package/dist/server/libs/abstractRateLimiter.js +15 -0
  128. package/dist/server/libs/artifactSizeGuard.d.ts +27 -0
  129. package/dist/server/libs/artifactSizeGuard.js +44 -0
  130. package/dist/server/libs/artifactTimeWindow.d.ts +24 -0
  131. package/dist/server/libs/artifactTimeWindow.js +30 -0
  132. package/dist/server/libs/btpsFactory.d.ts +29 -0
  133. package/dist/server/libs/btpsFactory.js +49 -0
  134. package/dist/server/libs/btpsLightweightFactory.d.ts +35 -0
  135. package/dist/server/libs/btpsLightweightFactory.js +37 -0
  136. package/dist/server/libs/btpsRegistry.d.ts +14 -0
  137. package/dist/server/libs/btpsRegistry.js +16 -0
  138. package/dist/server/libs/btpsSimpleMetricsTracker.d.ts +13 -0
  139. package/dist/server/libs/btpsSimpleMetricsTracker.js +21 -0
  140. package/dist/server/libs/btpsSimpleRateLimiter.d.ts +28 -0
  141. package/dist/server/libs/btpsSimpleRateLimiter.js +46 -0
  142. package/dist/server/libs/connectionTimeout.d.ts +16 -0
  143. package/dist/server/libs/connectionTimeout.js +14 -0
  144. package/dist/server/libs/defaultMiddleware.d.ts +8 -0
  145. package/dist/server/libs/defaultMiddleware.js +128 -0
  146. package/dist/server/libs/inFlightLimit.d.ts +18 -0
  147. package/dist/server/libs/inFlightLimit.js +17 -0
  148. package/dist/server/libs/index.d.ts +18 -0
  149. package/dist/server/libs/index.js +34 -0
  150. package/dist/server/libs/middlewareManager.js +126 -0
  151. package/dist/server/libs/type.d.ts +22 -0
  152. package/dist/server/libs/type.js +7 -0
  153. package/dist/server/types.d.ts +236 -0
  154. package/dist/server/types.js +7 -0
  155. package/package.json +126 -4
@@ -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
+
@@ -0,0 +1,79 @@
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 { BTPAgentArtifact, BTPArtifact, BTPDelegation, BTPDocType, BTPServerResponse, BTPTransporterArtifact } from '../server/types.js';
9
+ import type { Signer } from './signer-interface.js';
10
+ import type { Decrypter } from './decrypter-interface.js';
11
+ export type EncryptionMode = 'none' | 'standardEncrypt' | '2faEncrypt';
12
+ export type EncryptionAlgorithmType = 'aes-256-gcm';
13
+ export type BTPEncryption = {
14
+ algorithm: EncryptionAlgorithmType;
15
+ encryptedKey: string;
16
+ iv: string;
17
+ type: EncryptionMode;
18
+ authTag: string;
19
+ };
20
+ export type SignatureAlgorithmHash = 'sha256';
21
+ export type BTPSignature = {
22
+ algorithmHash: SignatureAlgorithmHash;
23
+ value: string;
24
+ fingerprint: string;
25
+ };
26
+ export type PemKeys = {
27
+ publicKey: string;
28
+ privateKey: string;
29
+ };
30
+ /** A key that signs: a PEM key pair, or a Signer holding the private key elsewhere (a KMS, a device). */
31
+ export type BTPSigningKey = PemKeys | Signer;
32
+ /** A key that decrypts: a PEM private key, or a Decrypter holding it elsewhere (a KMS, a device). */
33
+ export type BTPDecryptionKey = string | Decrypter;
34
+ export type BTPCryptoOptions = {
35
+ signature: {
36
+ algorithmHash: SignatureAlgorithmHash;
37
+ };
38
+ encryption?: {
39
+ algorithm: EncryptionAlgorithmType;
40
+ mode: EncryptionMode;
41
+ };
42
+ };
43
+ type WithGenericDocument<TArtifact extends BTPArtifact, T> = Omit<TArtifact, 'document'> & {
44
+ document: T;
45
+ };
46
+ export type BTPCryptoArtifact<T = BTPDocType> = WithGenericDocument<BTPAgentArtifact, T> | WithGenericDocument<BTPTransporterArtifact, T>;
47
+ export interface BTPCryptoResponse<T = BTPDocType> {
48
+ payload?: BTPCryptoArtifact<T> | BTPServerResponse<T>;
49
+ error?: BTPErrorException;
50
+ }
51
+ export interface VerifyEncryptedPayload<T = unknown | string> {
52
+ document?: T;
53
+ signature: BTPSignature;
54
+ encryption: BTPEncryption | null;
55
+ delegation?: BTPDelegation;
56
+ [key: string]: unknown;
57
+ }
58
+ /**
59
+ * Configuration for key generation
60
+ */
61
+ export interface BTPKeyConfig {
62
+ /** RSA key size in bits */
63
+ keySize?: number;
64
+ /** Key format (default: 'pem') */
65
+ format?: 'pem';
66
+ /** Public key encoding type */
67
+ publicKeyEncoding?: 'spki';
68
+ /** Private key encoding type */
69
+ privateKeyEncoding?: 'pkcs8';
70
+ }
71
+ export interface BTPKeyPair {
72
+ /** Public key in PEM format */
73
+ publicKey: string;
74
+ /** Private key in PEM format */
75
+ privateKey: string;
76
+ /** Public key fingerprint */
77
+ fingerprint: string;
78
+ }
79
+ export {};
@@ -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
+
@@ -0,0 +1,102 @@
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, BTPDelegation, BTPAttestation } from '../server/types.js';
8
+ import type { BTPSigningKey, PemKeys } from '../crypto/types.js';
9
+ import type { Signer } from '../crypto/signer-interface.js';
10
+ /**
11
+ * Delegator configuration options
12
+ */
13
+ export type BtpsDelegatorOptions = {
14
+ identity: string;
15
+ autoInit?: boolean;
16
+ } & ({
17
+ privateKey: PemKeys['privateKey'];
18
+ } | {
19
+ signer: Signer;
20
+ });
21
+ /**
22
+ * Production-grade Delegator for BTPS artifacts
23
+ * Handles delegation and attestation logic for SaaS and user-managed keys
24
+ */
25
+ export declare class BtpsDelegator {
26
+ private readonly identity;
27
+ private readonly key;
28
+ private publicKey?;
29
+ private selector;
30
+ private isInitialized;
31
+ private ready?;
32
+ /**
33
+ * Initialize the delegator
34
+ * @param options - The delegator options
35
+ */
36
+ constructor(options: BtpsDelegatorOptions);
37
+ /**
38
+ * Initialize the delegator
39
+ * This method is called automatically when the delegator is created
40
+ * It verifies the delegator identity and sets the public key
41
+ * @throws BTPErrorException if the delegator identity verification fails
42
+ */
43
+ init(): Promise<void>;
44
+ /**
45
+ * Verify the delegator identity
46
+ * @returns {isValid: boolean, publicKey?: string} - The result of the verification
47
+ */
48
+ protected verifyDelegatorIdentity(): Promise<{
49
+ isValid: boolean;
50
+ publicKey?: string;
51
+ }>;
52
+ /**
53
+ * Verify that a Signer signs with the private key matching the public key
54
+ * @param signer - The Signer holding the private key
55
+ * @param publicKeyPem - The public key in PEM format
56
+ * @returns {Promise<boolean>} - True if the keys match, false otherwise
57
+ */
58
+ protected isSignerMatching(signer: Signer, publicKeyPem: string): Promise<boolean>;
59
+ /**
60
+ * Verify if the private key matches the public key
61
+ * @param privateKeyPem - The private key in PEM format
62
+ * @param publicKeyPem - The public key in PEM format
63
+ * @returns {boolean} - True if the keys match, false otherwise
64
+ */
65
+ protected isKeyPairMatching(privateKeyPem: string, publicKeyPem: string): boolean;
66
+ /**
67
+ * Decorate a BTPTransporterArtifact with delegation and attestation as needed
68
+ * @param artifact The artifact to delegate
69
+ * @param context Delegation context (user type, id, identity)
70
+ * @returns The artifact with delegation (and attestation if required)
71
+ */
72
+ delegateArtifact(agentId: string, agentPubKey: string, artifact: BTPTransporterArtifact, onBehalfOf?: {
73
+ identity: string;
74
+ keyPair: BTPSigningKey;
75
+ }): Promise<BTPTransporterArtifact & {
76
+ delegation: BTPDelegation;
77
+ }>;
78
+ /**
79
+ * The delegator's own signing key, as createDelegation and createAttestation take it
80
+ */
81
+ private ownKey;
82
+ /**
83
+ * Create and sign a delegation
84
+ */
85
+ protected createDelegation(params: {
86
+ artifact: BTPTransporterArtifact;
87
+ delegatorIdentity: string;
88
+ delegatorKey: BTPSigningKey;
89
+ agentId: string;
90
+ agentPubKey: string;
91
+ selector: string;
92
+ }): Promise<BTPDelegation>;
93
+ /**
94
+ * Create and sign an attestation
95
+ */
96
+ protected createAttestation(params: {
97
+ delegation: Omit<BTPDelegation, 'attestation'>;
98
+ attestorIdentity: string;
99
+ attestorKey: BTPSigningKey;
100
+ selector: string;
101
+ }): Promise<BTPAttestation>;
102
+ }
@@ -0,0 +1,118 @@
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 { signBtpPayload, signBtpPayloadWithSigner } from "../crypto/index.js";
9
+ import { getHostAndSelector, resolvePublicKey } from "../utils/index.js";
10
+ import { createSign, createVerify } from "crypto";
11
+ import { BTP_ERROR_SIG_VERIFICATION, BTPErrorException } from "../error/index.js";
12
+ class BtpsDelegator {
13
+ identity;
14
+ key;
15
+ publicKey;
16
+ selector = "btps1";
17
+ isInitialized = !1;
18
+ ready;
19
+ 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
+ }));
22
+ }
23
+ async init() {
24
+ const { publicKey, isValid } = await this.verifyDelegatorIdentity();
25
+ if (!publicKey || !isValid)
26
+ throw new BTPErrorException(BTP_ERROR_SIG_VERIFICATION, {
27
+ cause: "Delegator identity verification failed",
28
+ meta: {
29
+ identity: this.identity,
30
+ publicKey,
31
+ isValid
32
+ }
33
+ });
34
+ this.publicKey = publicKey, this.isInitialized = !0;
35
+ }
36
+ async verifyDelegatorIdentity() {
37
+ const dnsHostAndSelector = await getHostAndSelector(this.identity);
38
+ if (!dnsHostAndSelector) return { isValid: !1, publicKey: void 0 };
39
+ this.selector = dnsHostAndSelector.selector;
40
+ const publicKey = await resolvePublicKey(this.identity, this.selector);
41
+ 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
+ async isSignerMatching(signer, publicKeyPem) {
44
+ const message = Buffer.from("btps-key-validation"), signature = await signer.sign(message);
45
+ return createVerify("sha256").update(message).end().verify(publicKeyPem, signature);
46
+ }
47
+ isKeyPairMatching(privateKeyPem, publicKeyPem) {
48
+ const message = "btps-key-validation", sign = createSign("sha256").update(message).end().sign(privateKeyPem);
49
+ return createVerify("sha256").update(message).end().verify(publicKeyPem, sign);
50
+ }
51
+ async delegateArtifact(agentId, agentPubKey, artifact, onBehalfOf) {
52
+ if (this.ready && await this.ready, !this.isInitialized || !this.publicKey)
53
+ throw new BTPErrorException({ message: "Delegator not initialized" });
54
+ let selector = this.selector;
55
+ if (onBehalfOf) {
56
+ const dnsHostAndSelector = await getHostAndSelector(onBehalfOf.identity);
57
+ if (!dnsHostAndSelector)
58
+ throw new BTPErrorException(BTP_ERROR_SIG_VERIFICATION, {
59
+ cause: "Delegator identity verification failed"
60
+ });
61
+ selector = dnsHostAndSelector.selector;
62
+ }
63
+ const delegation = await this.createDelegation({
64
+ artifact,
65
+ delegatorIdentity: onBehalfOf?.identity ?? this.identity,
66
+ delegatorKey: onBehalfOf?.keyPair ?? this.ownKey(this.publicKey),
67
+ agentId,
68
+ agentPubKey,
69
+ selector
70
+ });
71
+ if (onBehalfOf) {
72
+ const attestation = await this.createAttestation({
73
+ delegation,
74
+ attestorIdentity: this.identity,
75
+ attestorKey: this.ownKey(this.publicKey),
76
+ selector: this.selector
77
+ });
78
+ delegation.attestation = attestation;
79
+ }
80
+ return { ...artifact, delegation };
81
+ }
82
+ ownKey(publicKey) {
83
+ return typeof this.key == "string" ? { privateKey: this.key, publicKey } : this.key;
84
+ }
85
+ async createDelegation(params) {
86
+ const issuedAt = ( new Date()).toISOString(), delegationPayload = {
87
+ ...params.artifact,
88
+ delegation: {
89
+ agentId: params.agentId,
90
+ agentPubKey: params.agentPubKey,
91
+ signedBy: params.delegatorIdentity,
92
+ issuedAt,
93
+ selector: params.selector
94
+ }
95
+ }, signature = "sign" in params.delegatorKey ? await signBtpPayloadWithSigner(delegationPayload, params.delegatorKey) : signBtpPayload(delegationPayload, params.delegatorKey);
96
+ return {
97
+ ...delegationPayload.delegation,
98
+ signature
99
+ };
100
+ }
101
+ async createAttestation(params) {
102
+ const issuedAt = ( new Date()).toISOString(), attestationPayload = {
103
+ ...params.delegation,
104
+ attestation: {
105
+ signedBy: params.attestorIdentity,
106
+ issuedAt,
107
+ selector: params.selector
108
+ }
109
+ }, signature = "sign" in params.attestorKey ? await signBtpPayloadWithSigner(attestationPayload, params.attestorKey) : signBtpPayload(attestationPayload, params.attestorKey);
110
+ return {
111
+ ...attestationPayload.attestation,
112
+ signature
113
+ };
114
+ }
115
+ }
116
+ export {
117
+ BtpsDelegator
118
+ };
@@ -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
+ export * from './BtpsDelegator.js';
@@ -0,0 +1,8 @@
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
+ export * from "./BtpsDelegator.js";