@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,128 @@
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 } from '../server/types.js';
8
+ import { generateUserToken, type BTPSigningKey } from '../crypto/index.js';
9
+ import type { ServerAuthConfig, AuthRequestResponse, AuthValidationResult, CreateAgentOptions, AuthAgentOptions } from './types.js';
10
+ import { BTPErrorException } from '../error/index.js';
11
+ export declare class BtpsAuthentication {
12
+ private readonly tokenConfig;
13
+ private readonly trustStore;
14
+ private readonly tokenStore;
15
+ /**
16
+ * Private constructor - use factory methods instead
17
+ */
18
+ constructor(config: ServerAuthConfig);
19
+ /**
20
+ * Create an agent trust record
21
+ * @param options - Agent creation options
22
+ * @returns Created trust record
23
+ */
24
+ private createAgentTrustRecord;
25
+ /**
26
+ * Fetch an authentication session
27
+ * @param agentId - The agent ID
28
+ * @param payload - The payload to send to the server
29
+ * @param type - The type of session to fetch
30
+ * @param agentOptions - The agent options
31
+ * @returns The authentication session
32
+ */
33
+ private static _fetchAuthSession;
34
+ /**
35
+ * Generate a unique agent ID
36
+ * @returns Generated agent ID
37
+ */
38
+ static generateAgentId(prefix?: string): string;
39
+ /**
40
+ * Generate a refresh token
41
+ * @returns Generated refresh token
42
+ */
43
+ static generateRefreshToken(size?: number): string;
44
+ /**
45
+ * Generate a user authentication token (server-side)
46
+ * @param userIdentity - User identity to generate token for
47
+ * @returns Generated authentication token
48
+ */
49
+ static generateAuthToken: typeof generateUserToken;
50
+ /**
51
+ * Store an authentication token (server-side)
52
+ * @param token - The auth token to store
53
+ * @param userIdentity - User identity associated with the token
54
+ * @param metadata - Optional metadata to store with the token
55
+ */
56
+ storeAuthToken(token: string, userIdentity: string, decryptBy: string, metadata?: Record<string, unknown>): Promise<void>;
57
+ /**
58
+ * Validate an authentication token (server-side)
59
+ * @param token - The auth token to validate
60
+ * @param identity - The identity to validate the token for
61
+ * @returns Validation result with user identity if valid
62
+ */
63
+ validateAuthToken(userIdentity: string, token: string): Promise<AuthValidationResult>;
64
+ /**
65
+ * Validate a refresh token and reissue a new refresh token
66
+ * @param agentId - The agent ID
67
+ * @param refreshToken - The refresh token to validate
68
+ * @param options - Optional agent options
69
+ * @returns New authentication response with agent ID and refresh token
70
+ */
71
+ validateAndReissueRefreshToken(agentId: string, refreshToken: string, options: Omit<CreateAgentOptions, 'userIdentity' | 'publicKey'> & {
72
+ publicKey?: string;
73
+ decryptBy: string;
74
+ }): Promise<{
75
+ data?: BTPAuthResDoc;
76
+ error?: BTPErrorException;
77
+ }>;
78
+ /**
79
+ * Create an agent and trust record (server-side)
80
+ * @param options - Agent creation options
81
+ * @returns Generated authentication response with agent ID and refresh token
82
+ */
83
+ createAgent(options: CreateAgentOptions, decryptBy: string): Promise<BTPAuthResDoc>;
84
+ /**
85
+ * Authenticate using an auth token (client-side)
86
+ * @param authToken - The authentication token from the server
87
+ * @param keyPair - Generated key pair for this device, or a Signer holding its key in the device's keystore
88
+ * @param agentInfo - Optional agent information
89
+ * @returns NewAuthentication result with session details
90
+ */
91
+ static authenticate(identity: string, authToken: string, keyPair: BTPSigningKey, agentInfo?: Record<string, string | string[]>, agentOptions?: AuthAgentOptions): Promise<AuthRequestResponse>;
92
+ /**
93
+ * Refresh an authentication session (client-side)
94
+ * @param refreshToken - The refresh token to use
95
+ * @param agentInfo - Optional agent information
96
+ * @param agentOptions - Optional agent options
97
+ * @returns renewed authentication session or error
98
+ */
99
+ static refreshSession(agentId: string, identity: string, refreshToken: string, keyPair: BTPSigningKey, agentInfo?: Record<string, string | string[]>, agentOptions?: AuthAgentOptions): Promise<AuthRequestResponse>;
100
+ /**
101
+ * Refresh an authentication session and move the device to a new key (client-side).
102
+ * The refresh is signed by the current key and carries a proof signed by the new
103
+ * key, so the server accepts the new key only from the device that holds both.
104
+ * After it succeeds, the device signs with the new key.
105
+ * @param currentKey - The key the server holds for this device today
106
+ * @param newKey - The key to move to: a PEM key pair, or a Signer holding it
107
+ * @returns renewed authentication session or error
108
+ */
109
+ static rotateKey(agentId: string, identity: string, refreshToken: string, currentKey: BTPSigningKey, newKey: BTPSigningKey, agentInfo?: Record<string, string | string[]>, agentOptions?: AuthAgentOptions): Promise<AuthRequestResponse>;
110
+ /**
111
+ * Validate a refresh token (server-side)
112
+ * @param agentId - The agent ID
113
+ * @param refreshToken - The refresh token to validate
114
+ * @returns Validation result with agent details if valid
115
+ */
116
+ validateRefreshToken(agentId: string, refreshToken: string): Promise<{
117
+ isValid: false;
118
+ error?: Error;
119
+ } | {
120
+ isValid: true;
121
+ agentId: string;
122
+ userIdentity: string;
123
+ }>;
124
+ /**
125
+ * Clean up expired tokens and sessions
126
+ */
127
+ cleanup(): Promise<void>;
128
+ }
@@ -0,0 +1,293 @@
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, randomBytes } from "crypto";
9
+ import { BtpsAgent } from "../../client/btpsAgent.js";
10
+ import { computeAgentTrustId } from "../trust/trustUtils.js";
11
+ import {
12
+ generateUserToken,
13
+ getFingerprintFromPem,
14
+ DEFAULT_ALPHABET,
15
+ signBtpPayload,
16
+ signBtpPayloadWithSigner
17
+ } from "../crypto/index.js";
18
+ import { keyProofPayload } from "./keyProof.js";
19
+ import { isValidIdentity, pemToBase64 } from "../utils/index.js";
20
+ import { BTP_ERROR_AUTHENTICATION_INVALID, BTP_ERROR_IDENTITY } from "../error/constant.js";
21
+ import { BTPErrorException, transformToBTPErrorException } from "../error/index.js";
22
+ const DEFAULT_TOKEN_CONFIG = {
23
+ authTokenLength: 12,
24
+ authTokenAlphabet: DEFAULT_ALPHABET,
25
+ authTokenExpiryMs: 15 * 60 * 1e3,
26
+
27
+ refreshTokenExpiryMs: 7 * 24 * 60 * 60 * 1e3
28
+
29
+ };
30
+ class BtpsAuthentication {
31
+ tokenConfig;
32
+ trustStore;
33
+ tokenStore;
34
+ constructor(config) {
35
+ this.tokenConfig = {
36
+ ...DEFAULT_TOKEN_CONFIG,
37
+ ...config.tokenConfig ?? {}
38
+ }, this.trustStore = config.trustStore, this.tokenStore = config.tokenStore;
39
+ }
40
+ async createAgentTrustRecord(options) {
41
+ const { userIdentity, publicKey, agentInfo, decidedBy, privacyType, trustExpiryMs } = options, now = new Date(), agentId = BtpsAuthentication.generateAgentId(), trustRecord = {
42
+ senderId: agentId,
43
+ receiverId: userIdentity,
44
+ status: "accepted",
45
+ createdAt: now.toISOString(),
46
+ decidedBy,
47
+ decidedAt: now.toISOString(),
48
+ expiresAt: trustExpiryMs ? new Date(now.getTime() + trustExpiryMs).toISOString() : new Date(now.getTime() + this.tokenConfig.refreshTokenExpiryMs).toISOString(),
49
+ publicKeyBase64: pemToBase64(publicKey),
50
+ publicKeyFingerprint: getFingerprintFromPem(publicKey, "sha256"),
51
+ keyHistory: [],
52
+ privacyType: privacyType ?? "encrypted",
53
+ metadata: {
54
+ agentInfo: agentInfo ?? {}
55
+ }
56
+ };
57
+ return {
58
+ ...await this.trustStore.create(trustRecord, computeAgentTrustId(agentId, userIdentity)),
59
+ expiresAt: trustRecord.expiresAt
60
+ };
61
+ }
62
+ static async _fetchAuthSession(agentId, payload, type = "auth", agentOptions) {
63
+ const { keyPair, newKey, identity, authToken, agentInfo } = payload, commandAction = type === "refresh" ? "auth.refresh" : "auth.request";
64
+ try {
65
+ const options = {
66
+ ...agentOptions,
67
+ agent: "sign" in keyPair ? { id: agentId, signer: keyPair } : {
68
+ id: agentId,
69
+ identityKey: keyPair.privateKey,
70
+ identityCert: keyPair.publicKey
71
+ },
72
+ btpIdentity: identity
73
+ }, agent = new BtpsAgent(options), announcedKey = newKey ?? keyPair, publicKey = "sign" in announcedKey ? (await announcedKey.getPublicKey()).publicKey : announcedKey.publicKey, authRequest = {
74
+ identity,
75
+ authToken,
76
+ publicKey,
77
+ agentInfo
78
+ };
79
+ if (newKey) {
80
+ const proofPayload = keyProofPayload(agentId, identity, publicKey);
81
+ authRequest.keyProof = "sign" in newKey ? await signBtpPayloadWithSigner(proofPayload, newKey) : signBtpPayload(proofPayload, newKey);
82
+ }
83
+ const { response, error } = await agent.command(commandAction, identity, authRequest);
84
+ if (error) return { success: !1, error };
85
+ if (!response || !response.status.ok || !response.document || response.type === "btps_error")
86
+ return {
87
+ success: !1,
88
+ error: new BTPErrorException(BTP_ERROR_AUTHENTICATION_INVALID, {
89
+ cause: "Invalid authentication response",
90
+ meta: { agentId, identity, authToken, agentInfo, response }
91
+ })
92
+ };
93
+ const authResponse = response.document;
94
+ if (!authResponse.agentId || !authResponse.refreshToken)
95
+ return {
96
+ success: !1,
97
+ error: new BTPErrorException(BTP_ERROR_AUTHENTICATION_INVALID, {
98
+ cause: "Invalid authentication response format",
99
+ meta: { agentId, identity, authToken, agentInfo, response }
100
+ })
101
+ };
102
+ const { type: type2, ...restResponse } = response;
103
+ return {
104
+ success: !0,
105
+ response: {
106
+ ...restResponse,
107
+ document: authResponse
108
+ }
109
+ };
110
+ } catch (error) {
111
+ return {
112
+ success: !1,
113
+ error: transformToBTPErrorException(error)
114
+ };
115
+ }
116
+ }
117
+ static generateAgentId(prefix = "btps_ag") {
118
+ return `${prefix}_${randomUUID()}`;
119
+ }
120
+ static generateRefreshToken(size = 32) {
121
+ return randomBytes(size).toString("base64url");
122
+ }
123
+ static generateAuthToken = generateUserToken;
124
+ async storeAuthToken(token, userIdentity, decryptBy, metadata) {
125
+ await this.tokenStore.store(
126
+ token,
127
+ null,
128
+ userIdentity,
129
+ this.tokenConfig.authTokenExpiryMs,
130
+ decryptBy,
131
+ metadata
132
+ );
133
+ }
134
+ async validateAuthToken(userIdentity, token) {
135
+ try {
136
+ const storedToken = await this.tokenStore.consume(userIdentity, token);
137
+ return storedToken ? {
138
+ isValid: !0,
139
+ userIdentity: storedToken.userIdentity
140
+ } : {
141
+ isValid: !1,
142
+ error: new BTPErrorException({ message: "Invalid or expired auth token" })
143
+ };
144
+ } catch (error) {
145
+ return {
146
+ isValid: !1,
147
+ error: error instanceof Error ? error : new BTPErrorException({ message: "Token validation failed" })
148
+ };
149
+ }
150
+ }
151
+ async validateAndReissueRefreshToken(agentId, refreshToken, options) {
152
+ const storedToken = await this.tokenStore.consume(agentId, refreshToken);
153
+ if (!storedToken)
154
+ return {
155
+ data: void 0,
156
+ error: new BTPErrorException(BTP_ERROR_AUTHENTICATION_INVALID, {
157
+ cause: "Invalid or expired refresh token",
158
+ meta: { agentId, refreshToken }
159
+ })
160
+ };
161
+ const { userIdentity } = storedToken, computedId = computeAgentTrustId(agentId, userIdentity), trustRecord = await this.trustStore.getById(computedId);
162
+ if (!trustRecord)
163
+ return {
164
+ data: void 0,
165
+ error: new BTPErrorException(BTP_ERROR_AUTHENTICATION_INVALID, {
166
+ cause: `Trust record not found for ${agentId} \u2192 ${userIdentity}`,
167
+ meta: { agentId, userIdentity, refreshToken }
168
+ })
169
+ };
170
+ const patch = {
171
+ ...trustRecord,
172
+ expiresAt: new Date(
173
+ Date.now() + (options.trustExpiryMs ?? this.tokenConfig.refreshTokenExpiryMs)
174
+ ).toISOString()
175
+ }, { agentInfo, decidedBy, privacyType, publicKey } = options;
176
+ if (patch.metadata = {
177
+ agentInfo: agentInfo ?? trustRecord.metadata?.agentInfo ?? {}
178
+ }, publicKey) {
179
+ const previousFingerprint = trustRecord.publicKeyFingerprint, currentFingerprint = getFingerprintFromPem(publicKey, "sha256");
180
+ previousFingerprint !== currentFingerprint && (patch.keyHistory = trustRecord.keyHistory || [], patch.keyHistory.push({
181
+ fingerprint: previousFingerprint,
182
+ firstSeen: trustRecord.decidedAt,
183
+ lastSeen: ( new Date()).toISOString()
184
+ }), patch.publicKeyBase64 = pemToBase64(publicKey), patch.publicKeyFingerprint = currentFingerprint);
185
+ }
186
+ patch.decidedBy = decidedBy, patch.privacyType = privacyType ?? patch.privacyType, patch.status = "accepted", patch.decidedAt = ( new Date()).toISOString();
187
+ try {
188
+ await this.trustStore.update(computedId, patch);
189
+ } catch (error) {
190
+ const remainingMs = new Date(storedToken.expiresAt).getTime() - Date.now();
191
+ return remainingMs > 0 && await this.tokenStore.store(
192
+ refreshToken,
193
+ agentId,
194
+ userIdentity,
195
+ remainingMs,
196
+ storedToken.decryptBy,
197
+ storedToken.metadata
198
+ ), {
199
+ data: void 0,
200
+ error: transformToBTPErrorException(error)
201
+ };
202
+ }
203
+ const newRefreshToken = BtpsAuthentication.generateRefreshToken();
204
+ return await this.tokenStore.store(
205
+ newRefreshToken,
206
+ agentId,
207
+ userIdentity,
208
+ this.tokenConfig.refreshTokenExpiryMs,
209
+ options.decryptBy,
210
+ { agentInfo }
211
+ ), {
212
+ data: {
213
+ agentId,
214
+ refreshToken: newRefreshToken,
215
+ expiresAt: patch.expiresAt,
216
+ decryptBy: options.decryptBy
217
+ }
218
+ };
219
+ }
220
+ async createAgent(options, decryptBy) {
221
+ const expiry = options.trustExpiryMs ?? this.tokenConfig.refreshTokenExpiryMs, trustRecord = await this.createAgentTrustRecord({ ...options, trustExpiryMs: expiry }), { senderId: agentId, receiverId: userIdentity, metadata, expiresAt } = trustRecord, agentInfo = metadata?.agentInfo, refreshToken = BtpsAuthentication.generateRefreshToken();
222
+ return await this.tokenStore.store(
223
+ refreshToken,
224
+ agentId,
225
+ userIdentity,
226
+ this.tokenConfig.refreshTokenExpiryMs,
227
+ decryptBy,
228
+ { agentInfo }
229
+ ), {
230
+ agentId,
231
+ refreshToken,
232
+ expiresAt,
233
+ decryptBy
234
+ };
235
+ }
236
+ static async authenticate(identity, authToken, keyPair, agentInfo, agentOptions) {
237
+ return isValidIdentity(identity) ? await this._fetchAuthSession(
238
+ "temp",
239
+ { keyPair, identity, authToken, agentInfo },
240
+ "auth",
241
+ agentOptions
242
+ ) : {
243
+ success: !1,
244
+ error: new BTPErrorException(BTP_ERROR_IDENTITY)
245
+ };
246
+ }
247
+ static async refreshSession(agentId, identity, refreshToken, keyPair, agentInfo, agentOptions) {
248
+ return isValidIdentity(identity) ? await this._fetchAuthSession(
249
+ agentId,
250
+ { keyPair, identity, authToken: refreshToken, agentInfo },
251
+ "refresh",
252
+ agentOptions
253
+ ) : {
254
+ success: !1,
255
+ error: new BTPErrorException(BTP_ERROR_IDENTITY)
256
+ };
257
+ }
258
+ static async rotateKey(agentId, identity, refreshToken, currentKey, newKey, agentInfo, agentOptions) {
259
+ return isValidIdentity(identity) ? await this._fetchAuthSession(
260
+ agentId,
261
+ { keyPair: currentKey, newKey, identity, authToken: refreshToken, agentInfo },
262
+ "refresh",
263
+ agentOptions
264
+ ) : {
265
+ success: !1,
266
+ error: new BTPErrorException(BTP_ERROR_IDENTITY)
267
+ };
268
+ }
269
+ async validateRefreshToken(agentId, refreshToken) {
270
+ try {
271
+ const storedToken = await this.tokenStore.get(agentId, refreshToken);
272
+ return storedToken ? {
273
+ isValid: !0,
274
+ agentId: storedToken.agentId,
275
+ userIdentity: storedToken.userIdentity
276
+ } : {
277
+ isValid: !1,
278
+ error: new BTPErrorException({ message: "Invalid or expired refresh token" })
279
+ };
280
+ } catch (error) {
281
+ return {
282
+ isValid: !1,
283
+ error: transformToBTPErrorException(error)
284
+ };
285
+ }
286
+ }
287
+ async cleanup() {
288
+ await this.tokenStore.cleanup(), await this.tokenStore.cleanup();
289
+ }
290
+ }
291
+ export {
292
+ BtpsAuthentication
293
+ };
@@ -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
+ }