@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,11 @@
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 './types.js';
8
+ export * from './BtpsAuthentication.js';
9
+ export * from './keyProof.js';
10
+ export * from './storage/InMemoryAuthSessionStore.js';
11
+ export * from './storage/InMemoryTokenStore.js';
@@ -0,0 +1,12 @@
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 "./types.js";
9
+ export * from "./BtpsAuthentication.js";
10
+ export * from "./keyProof.js";
11
+ export * from "./storage/InMemoryAuthSessionStore.js";
12
+ export * from "./storage/InMemoryTokenStore.js";
@@ -0,0 +1,18 @@
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
+ * What a device's new key signs when the device moves to it, on an
9
+ * `auth.refresh`: the agent, its identity and the new key itself. The refresh
10
+ * as a whole is signed by the current key, so the two signatures together
11
+ * show that one device holds both keys.
12
+ */
13
+ export declare const keyProofPayload: (agentId: string, identity: string, publicKey: string) => {
14
+ type: string;
15
+ agentId: string;
16
+ identity: string;
17
+ publicKey: string;
18
+ };
@@ -0,0 +1,16 @@
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
+ const keyProofPayload = (agentId, identity, publicKey) => ({
9
+ type: "btps_key_proof",
10
+ agentId,
11
+ identity,
12
+ publicKey
13
+ });
14
+ export {
15
+ keyProofPayload
16
+ };
@@ -0,0 +1,55 @@
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 { AuthSessionStore, AuthSession } from '../types.js';
8
+ /**
9
+ * In-memory implementation of AuthSessionStore for storing client-side authentication sessions
10
+ * Suitable for development and testing. For production, use a persistent store.
11
+ */
12
+ export declare class InMemoryAuthSessionStore implements AuthSessionStore {
13
+ private sessions;
14
+ private identityIndex;
15
+ /**
16
+ * Store an authentication session in memory
17
+ * @param session - The authentication session to store
18
+ */
19
+ store(session: AuthSession): Promise<void>;
20
+ /**
21
+ * Retrieve a session by agent ID
22
+ * @param agentId - The agent ID to look up
23
+ * @returns The authentication session or undefined if not found/expired
24
+ */
25
+ getByAgentId(agentId: string): Promise<AuthSession | undefined>;
26
+ /**
27
+ * Retrieve a session by identity and server identity
28
+ * @param identity - The user identity
29
+ * @param serverIdentity - The server identity
30
+ * @returns The authentication session or undefined if not found/expired
31
+ */
32
+ getByIdentity(identity: string): Promise<AuthSession | undefined>;
33
+ /**
34
+ * Remove a session from storage
35
+ * @param agentId - The agent ID of the session to remove
36
+ */
37
+ remove(agentId: string): Promise<void>;
38
+ /**
39
+ * Clean up expired sessions from storage
40
+ */
41
+ cleanup(): Promise<void>;
42
+ /**
43
+ * Get all stored sessions
44
+ * @returns Array of all authentication sessions
45
+ */
46
+ getAll(): Promise<AuthSession[]>;
47
+ /**
48
+ * Get the total number of stored sessions (for debugging/testing)
49
+ */
50
+ get size(): number;
51
+ /**
52
+ * Clear all sessions (for testing)
53
+ */
54
+ clear(): void;
55
+ }
@@ -0,0 +1,62 @@
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
+ class InMemoryAuthSessionStore {
9
+ sessions = new Map();
10
+ identityIndex = new Map();
11
+
12
+ async store(session) {
13
+ this.sessions.set(session.agentId, session);
14
+ const identityKey = `${session.userIdentity}`;
15
+ this.identityIndex.set(identityKey, session.agentId);
16
+ }
17
+ async getByAgentId(agentId) {
18
+ const session = this.sessions.get(agentId);
19
+ if (!session)
20
+ return;
21
+ const now = new Date(), expiresAt = new Date(session.expiresAt);
22
+ if (now > expiresAt) {
23
+ await this.remove(agentId);
24
+ return;
25
+ }
26
+ return session;
27
+ }
28
+ async getByIdentity(identity) {
29
+ const agentId = this.identityIndex.get(identity);
30
+ if (agentId)
31
+ return this.getByAgentId(agentId);
32
+ }
33
+ async remove(agentId) {
34
+ const session = this.sessions.get(agentId);
35
+ if (session) {
36
+ const identityKey = session.userIdentity;
37
+ this.identityIndex.delete(identityKey);
38
+ }
39
+ this.sessions.delete(agentId);
40
+ }
41
+ async cleanup() {
42
+ const now = new Date(), expiredAgentIds = [];
43
+ for (const [agentId, session] of this.sessions.entries()) {
44
+ const expiresAt = new Date(session.expiresAt);
45
+ now > expiresAt && expiredAgentIds.push(agentId);
46
+ }
47
+ for (const agentId of expiredAgentIds)
48
+ await this.remove(agentId);
49
+ }
50
+ async getAll() {
51
+ return await this.cleanup(), Array.from(this.sessions.values());
52
+ }
53
+ get size() {
54
+ return this.sessions.size;
55
+ }
56
+ clear() {
57
+ this.sessions.clear(), this.identityIndex.clear();
58
+ }
59
+ }
60
+ export {
61
+ InMemoryAuthSessionStore
62
+ };
@@ -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
+ import { TokenStore, BTPsTokenDocument } from '../types.js';
8
+ /**
9
+ * In-memory implementation of RefreshTokenStore for storing refresh tokens
10
+ * Suitable for development and testing. For production, use a persistent store.
11
+ */
12
+ export declare class InMemoryTokenStore<T extends BTPsTokenDocument = BTPsTokenDocument> implements TokenStore<T> {
13
+ private tokens;
14
+ /**
15
+ * Store a refresh token in memory
16
+ * @param token - The refresh token value
17
+ * @param agentId - Agent ID associated with the token
18
+ * @param userIdentity - User identity associated with the token
19
+ * @param expiryMs - Token expiry time in milliseconds
20
+ * @param metadata - Optional metadata to store with the token
21
+ */
22
+ store(token: string, agentId: string | null, userIdentity: string, expiryMs: number, decryptBy: string, metadata?: Record<string, unknown>): Promise<void>;
23
+ /**
24
+ * Make a key for the token store
25
+ * @param agentId - The agent ID
26
+ * @param token - The refresh token
27
+ * @returns The key
28
+ */
29
+ private makeKey;
30
+ /**
31
+ * Retrieve and validate a refresh token
32
+ * @param agentId - The agent ID
33
+ * @param token - The refresh token to retrieve
34
+ * @returns The stored token information or null if not found/expired
35
+ */
36
+ get(agentId: string, token: string): Promise<T | undefined>;
37
+ /**
38
+ * Remove a refresh token from storage
39
+ * @param agentId - The agent ID
40
+ * @param token - The refresh token to remove
41
+ */
42
+ remove(agentId: string, token: string): Promise<void>;
43
+ /**
44
+ * Take a token once. The read and the delete happen in one synchronous step,
45
+ * so no other call can take the same token in between.
46
+ * @param agentId - The agent ID (or the user identity, for an auth token)
47
+ * @param token - The token to take
48
+ * @returns The stored token, or undefined when there is none or it has expired
49
+ */
50
+ consume(agentId: string, token: string): Promise<T | undefined>;
51
+ /**
52
+ * Clean up expired tokens from storage
53
+ */
54
+ cleanup(): Promise<void>;
55
+ /**
56
+ * Get the total number of stored tokens (for debugging/testing)
57
+ */
58
+ get size(): number;
59
+ /**
60
+ * Clear all tokens (for testing)
61
+ */
62
+ clear(): void;
63
+ }
@@ -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;