@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,63 @@
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 { computeTrustId } from "../../trust/trustUtils.js";
9
+ class InMemoryTokenStore {
10
+ tokens = new Map();
11
+ 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), {
14
+ token,
15
+ agentId: agentId ?? "anonymous",
16
+ userIdentity,
17
+ createdAt: now.toISOString(),
18
+ expiresAt: expiresAt.toISOString(),
19
+ decryptBy,
20
+ metadata
21
+ });
22
+ }
23
+ makeKey(agentId, token) {
24
+ return computeTrustId(agentId, token);
25
+ }
26
+ async get(agentId, token) {
27
+ const storedToken = this.tokens.get(this.makeKey(agentId, token));
28
+ if (!storedToken)
29
+ return;
30
+ const now = new Date(), expiresAt = new Date(storedToken.expiresAt);
31
+ if (now > expiresAt) {
32
+ this.remove(agentId, token);
33
+ return;
34
+ }
35
+ return storedToken;
36
+ }
37
+ async remove(agentId, token) {
38
+ this.tokens.delete(this.makeKey(agentId, token));
39
+ }
40
+ async consume(agentId, token) {
41
+ const key = this.makeKey(agentId, token), storedToken = this.tokens.get(key);
42
+ if (this.tokens.delete(key), !(!storedToken || new Date() > new Date(storedToken.expiresAt)))
43
+ return storedToken;
44
+ }
45
+ async cleanup() {
46
+ const now = new Date(), expiredTokens = [];
47
+ for (const [token, storedToken] of this.tokens.entries()) {
48
+ const expiresAt = new Date(storedToken.expiresAt);
49
+ now > expiresAt && expiredTokens.push(token);
50
+ }
51
+ for (const token of expiredTokens)
52
+ this.tokens.delete(token);
53
+ }
54
+ get size() {
55
+ return this.tokens.size;
56
+ }
57
+ clear() {
58
+ this.tokens.clear();
59
+ }
60
+ }
61
+ export {
62
+ InMemoryTokenStore
63
+ };
@@ -0,0 +1,135 @@
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 { BTPAuthResDoc, BTPServerResponse } from '../server/types.js';
8
+ import type { BTPTrustRecord } from '../trust/types.js';
9
+ import type { AbstractTrustStore } from '../trust/storage/AbstractTrustStore.js';
10
+ import type { BTPAgentOptions } from '../../client/types/index.js';
11
+ /**
12
+ * Configuration for token generation and validation
13
+ */
14
+ export interface TokenConfig {
15
+ /** Length of the auth token (8-24 characters) */
16
+ authTokenLength?: number;
17
+ /** Character set for auth token generation */
18
+ authTokenAlphabet?: string;
19
+ /** Expiry time for auth tokens in milliseconds */
20
+ authTokenExpiryMs?: number;
21
+ /** Expiry time for refresh tokens in milliseconds */
22
+ refreshTokenExpiryMs?: number;
23
+ }
24
+ /**
25
+ * Server-side configuration for BtpsAuthentication
26
+ */
27
+ export interface ServerAuthConfig {
28
+ /** Trust store for managing trust records */
29
+ trustStore: AbstractTrustStore<BTPTrustRecord>;
30
+ /** Storage for auth tokens */
31
+ tokenStore: TokenStore;
32
+ /** Token configuration */
33
+ tokenConfig?: TokenConfig;
34
+ }
35
+ /**
36
+ * Stored refresh token information
37
+ */
38
+ export interface BTPsTokenDocument {
39
+ /** The refresh token value */
40
+ token: string;
41
+ /** Agent ID associated with the token */
42
+ agentId: string;
43
+ /** User identity associated with the token */
44
+ userIdentity: string;
45
+ /** When the token was created */
46
+ createdAt: string;
47
+ /** When the token expires */
48
+ expiresAt: string;
49
+ /** Identity to decrypt by when decrypting the document */
50
+ decryptBy: string;
51
+ /** Additional metadata */
52
+ metadata?: Record<string, unknown>;
53
+ }
54
+ export type AuthSession = BTPsTokenDocument & {
55
+ publicKeyFingerprint: string;
56
+ refreshToken: string;
57
+ };
58
+ export type AuthAgentOptions = Omit<BTPAgentOptions, 'btpIdentity' | 'agent'>;
59
+ /**
60
+ * Authentication request result
61
+ */
62
+ export interface AuthRequestResponse {
63
+ /** Whether the request was successful */
64
+ success: boolean;
65
+ /** Authentication response from server */
66
+ response?: Omit<BTPServerResponse, 'type' | 'document'> & {
67
+ document: BTPAuthResDoc;
68
+ };
69
+ /** Error if request failed */
70
+ error?: Error;
71
+ }
72
+ /**
73
+ * Authentication validation result
74
+ */
75
+ export interface AuthValidationResult {
76
+ /** Whether the auth token is valid */
77
+ isValid: boolean;
78
+ /** User identity if valid */
79
+ userIdentity?: string;
80
+ /** Error if validation failed */
81
+ error?: Error;
82
+ }
83
+ /**
84
+ * Refresh token store interface for storing and retrieving refresh tokens
85
+ */
86
+ export interface TokenStore<T extends BTPsTokenDocument = BTPsTokenDocument> {
87
+ /** Store a refresh token */
88
+ store(token: string, agentId: string | null, userIdentity: string, expiryMs: number, decryptBy: string, metadata?: Record<string, unknown>): Promise<void>;
89
+ /** Retrieve and validate a refresh token */
90
+ get(agentId: string, token: string): Promise<T | undefined>;
91
+ /** Remove a refresh token */
92
+ remove(agentId: string, token: string): Promise<void>;
93
+ /**
94
+ * Take a token once: return it and remove it in one step, or undefined when
95
+ * there is none or it has expired. Of two calls racing for the same token,
96
+ * exactly one gets it, so one registration code or refresh token is used once.
97
+ */
98
+ consume(agentId: string, token: string): Promise<T | undefined>;
99
+ /** Clean up expired tokens */
100
+ cleanup(): Promise<void>;
101
+ }
102
+ /**
103
+ * Authentication session store interface for client-side session management
104
+ */
105
+ export interface AuthSessionStore {
106
+ /** Store an authentication session */
107
+ store(session: AuthSession): Promise<void>;
108
+ /** Retrieve a session by agent ID */
109
+ getByAgentId(agentId: string): Promise<AuthSession | undefined>;
110
+ /** Retrieve a session by identity */
111
+ getByIdentity(identity: string): Promise<AuthSession | undefined>;
112
+ /** Remove a session */
113
+ remove(agentId: string): Promise<void>;
114
+ /** Clean up expired sessions */
115
+ cleanup(): Promise<void>;
116
+ /** Get all sessions */
117
+ getAll(): Promise<AuthSession[]>;
118
+ }
119
+ /**
120
+ * Agent creation options for server-side
121
+ */
122
+ export interface CreateAgentOptions {
123
+ /** User identity */
124
+ userIdentity: string;
125
+ /** Device public key */
126
+ publicKey: string;
127
+ /** Additional agent information */
128
+ agentInfo?: Record<string, string | string[]>;
129
+ /** Who decided to create this agent */
130
+ decidedBy: string;
131
+ /** Privacy type for communication */
132
+ privacyType?: BTPTrustRecord['privacyType'];
133
+ /** Trust record expiry */
134
+ trustExpiryMs?: number;
135
+ }
@@ -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,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
+
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>>;
@@ -0,0 +1,45 @@
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 { decryptBtpPayload, decryptBtpPayloadWithDecrypter, verifySignature } from "./index.js";
9
+ import { BTPErrorException } from "../error/index.js";
10
+ import { BTP_ERROR_VALIDATION } from "../error/constant.js";
11
+ import { decryptedDocumentProblem } from "../server/schemas/helpers.js";
12
+ import isEmpty from "lodash/isEmpty.js";
13
+ const genDecryptError = (error) => ({
14
+ payload: void 0,
15
+ error
16
+ }), decryptVerify = async (senderPubPem, encryptedPayload, receiverKey) => {
17
+ const { signature, delegation, ...restEncryptedPayload } = encryptedPayload, { isValid, error: sigError } = verifySignature(
18
+ restEncryptedPayload,
19
+ signature,
20
+ senderPubPem
21
+ );
22
+ if (!isValid && sigError)
23
+ return genDecryptError(sigError);
24
+ const { encryption, document } = restEncryptedPayload, hasReceiverKey = typeof receiverKey == "string" ? !isEmpty(receiverKey) : receiverKey !== void 0, needsDecryption = !isEmpty(encryption) && hasReceiverKey && !isEmpty(document) && typeof document == "string";
25
+ let decrypted = { data: document };
26
+ needsDecryption && receiverKey !== void 0 && (decrypted = typeof receiverKey == "string" ? decryptBtpPayload(document, encryption, receiverKey) : await decryptBtpPayloadWithDecrypter(document, encryption, receiverKey));
27
+ const { data: decryptedData, error: decryptionErrors } = decrypted;
28
+ if (decryptionErrors) return genDecryptError(decryptionErrors);
29
+ if (needsDecryption) {
30
+ const problem = decryptedDocumentProblem(decryptedData, restEncryptedPayload);
31
+ if (problem)
32
+ return genDecryptError(new BTPErrorException(BTP_ERROR_VALIDATION, { cause: problem }));
33
+ }
34
+ const decryptedPayload = {
35
+ ...restEncryptedPayload,
36
+ signature
37
+ };
38
+ return decryptedData && (decryptedPayload.document = decryptedData), delegation && (decryptedPayload.delegation = delegation), {
39
+ payload: decryptedPayload,
40
+ error: void 0
41
+ };
42
+ };
43
+ export {
44
+ decryptVerify
45
+ };
@@ -0,0 +1,25 @@
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 AEAD algorithm for every Decrypter implementation. */
8
+ export type DecrypterAlgorithm = 'aes-256-gcm';
9
+ export interface DecryptRequest {
10
+ /** RSA-OAEP-wrapped AES-256 content-encryption key. */
11
+ encryptedKey: Uint8Array;
12
+ /** AES-GCM initialization vector. */
13
+ iv: Uint8Array;
14
+ ciphertext: Uint8Array;
15
+ /** Must be exactly 16 bytes; a shorter tag must be rejected. */
16
+ authTag: Uint8Array;
17
+ /** Additional authenticated data, when present. */
18
+ additionalData?: Uint8Array;
19
+ }
20
+ export interface Decrypter {
21
+ readonly algorithm: DecrypterAlgorithm;
22
+ /** Decrypts `request` and returns the plaintext bytes, or rejects if the
23
+ * key-wrap fails to unwrap or the AEAD tag check fails. */
24
+ decrypt(request: DecryptRequest): Promise<Uint8Array>;
25
+ }
@@ -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,77 @@
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 { BTPCryptoOptions, BTPEncryption, BTPSignature, PemKeys } from './types.js';
8
+ import { BTPErrorException } from '../error/index.js';
9
+ import type { Signer } from './signer-interface.js';
10
+ import type { Decrypter } from './decrypter-interface.js';
11
+ export * from './decryptVerify.js';
12
+ export * from './jcs.js';
13
+ export * from './signEncrypt.js';
14
+ export * from './keygen.js';
15
+ export * from './types.js';
16
+ export * from './signer-interface.js';
17
+ export * from './decrypter-interface.js';
18
+ export * from './pem-signer.js';
19
+ export * from './pem-decrypter.js';
20
+ export declare const encryptBtpPayload: (payload: unknown | undefined, receiverPubPem: string, options?: BTPCryptoOptions["encryption"]) => {
21
+ data: string;
22
+ encryption: {
23
+ algorithm: "aes-256-gcm";
24
+ encryptedKey: string;
25
+ iv: string;
26
+ authTag: string;
27
+ type: import("./types.js").EncryptionMode;
28
+ };
29
+ };
30
+ export declare const decryptBtpPayload: <T = unknown>(payload: unknown | undefined, encryption: BTPEncryption, receiverPrivPem: string) => {
31
+ data?: T;
32
+ error?: BTPErrorException;
33
+ };
34
+ /**
35
+ * Decrypts like `decryptBtpPayload`, through a Decrypter that holds the
36
+ * receiver's private key elsewhere (a KMS, a device) instead of a PEM key.
37
+ */
38
+ export declare const decryptBtpPayloadWithDecrypter: <T = unknown>(payload: unknown | undefined, encryption: BTPEncryption, decrypter: Decrypter) => Promise<{
39
+ data?: T;
40
+ error?: BTPErrorException;
41
+ }>;
42
+ /** The smallest RSA key the SDK encrypts to. */
43
+ export declare const MIN_RSA_KEY_BITS = 2048;
44
+ /**
45
+ * Encrypts a buffer using RSA public key with OAEP and SHA-256
46
+ */
47
+ export declare const encryptRSA: (publicKeyPem: string, data: Buffer) => Buffer;
48
+ /**
49
+ * Decrypts an RSA-encrypted buffer using a private key with OAEP and SHA-256
50
+ */
51
+ export declare const decryptRSA: (privateKeyPem: string, encrypted: Buffer) => Buffer;
52
+ export declare const getFingerprintFromPem: (pem: string, hashAlgorithm?: string) => string;
53
+ export declare const signBtpPayload: (payload: unknown | undefined, senderPemFiles: PemKeys) => BTPSignature;
54
+ /**
55
+ * Signs like `signBtpPayload`, through a Signer that holds the sender's
56
+ * private key elsewhere (a KMS, a device) instead of a PEM key pair.
57
+ */
58
+ export declare const signBtpPayloadWithSigner: (payload: unknown | undefined, signer: Signer) => Promise<BTPSignature>;
59
+ export declare const verifySignature: (payload: unknown | undefined, signature: BTPSignature, senderPubKey: string) => {
60
+ isValid: boolean;
61
+ error?: BTPErrorException;
62
+ };
63
+ export declare const DEFAULT_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
64
+ /**
65
+ * Generate a short, high-entropy, user-specific onboarding token.
66
+ * do not use this for long lived token as there are still chances of collision if compares with trillions of global record
67
+ * This token is suitable for copy-paste flows where the SaaS platform
68
+ * validates the token against a short-lived, user-scoped record (e.g. in Redis).
69
+ *
70
+ * @param userIdentity - Unique user identity string (e.g., "alice$btps.com")
71
+ * @param length - Number of characters in the token (8–24, default 12)
72
+ * @param charactersFrom - Optional character set to generate the token from (default: CrockFord Base32)
73
+ * @returns A short, human-friendly, high-entropy token string
74
+ *
75
+ * @throws Error if length is out of bounds
76
+ */
77
+ export declare function generateUserToken(userIdentity: string, length?: number, charactersFrom?: string): string;
@@ -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
+ };