@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,292 @@
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 { BTPTrustRecord } from '../core/trust/index.js';
8
+ import type { BTPAgentArtifact, BTPServerResponse, BTPStatus, BTPTransporterArtifact } from '../core/server/types.js';
9
+ import type { BtpsServerOptions, ProcessedArtifact, ArtifactResCtx } from './types.js';
10
+ import type { AbstractTrustStore } from '../core/trust/storage/AbstractTrustStore.js';
11
+ import type { BTPIdentityRecord } from '../core/storage/types.js';
12
+ import type { AbstractIdentityStore } from '../core/storage/AbstractIdentityStore.js';
13
+ /**
14
+ * BTPS Secure Server over TLS (btps://)
15
+ * Handles encrypted JSON message delivery between trusted parties.
16
+ */
17
+ export declare class BtpsServer {
18
+ private readonly tlsOptions?;
19
+ private readonly serverIdentity;
20
+ private readonly onError?;
21
+ private readonly identityStore?;
22
+ private readonly trustStore;
23
+ private readonly middlewareManager;
24
+ private readonly connectionTimeoutMs;
25
+ private readonly maxArtifactSizeKb;
26
+ private readonly maxInFlightPerConnection;
27
+ private readonly maxArtifactAgeSeconds;
28
+ private readonly dependencies;
29
+ private readonly port;
30
+ private server;
31
+ private emitter;
32
+ private handlerFn;
33
+ /**
34
+ * Creates a new BtpsServer instance
35
+ * @param options - The server options
36
+ */
37
+ constructor(options: BtpsServerOptions);
38
+ /**
39
+ * Initializes the server and loads middleware
40
+ */
41
+ private initialize;
42
+ private updateIdentityInfo;
43
+ /**
44
+ * Handles an incoming TLS socket connection.
45
+ *
46
+ * This method sets up data and error event listeners for the socket and its associated
47
+ * data stream (split2). It handles parsing, validating, verifying, and processing BTPS requests.
48
+ *
49
+ * ⚠️ Important:
50
+ * - Ensures per-connection event handlers are cleaned up via `off()` in the `close` handler.
51
+ * - Prevents `MaxListenersExceededWarning` by avoiding accumulation of handlers
52
+ * across many short-lived connections (e.g. in a spam or high-traffic scenario).
53
+ *
54
+ * @param socket The incoming TLS socket representing a BTPS connection
55
+ */
56
+ private handleConnection;
57
+ private handleControl;
58
+ /**
59
+ * Handles an identity lookup request
60
+ * @param artifact - The identity lookup request artifact
61
+ * @param context - The request and response context
62
+ */
63
+ private handleIdentityLookup;
64
+ /**
65
+ * Executes the complete request pipeline with middleware support
66
+ * use this method inside try catch block to handle errors
67
+ * use this method inside handleConnection method
68
+ */
69
+ private executeRequestPipeline;
70
+ private isResponseSent;
71
+ /**
72
+ * Executes a list of middleware functions
73
+ * @returns true if a response was sent (flow should stop), false otherwise
74
+ */
75
+ private executeMiddleware;
76
+ /**
77
+ * Core agent signature verification (non-negotiable)
78
+ */
79
+ private verifyAgentSignature;
80
+ /**
81
+ * An auth.refresh that names a key other than the agent's current one moves
82
+ * the device to that key. It is already signed by the current key, and must
83
+ * also carry a keyProof signed by the new key, so a stolen refresh token
84
+ * alone cannot move a device to someone else's key.
85
+ */
86
+ private verifyKeyProof;
87
+ /**
88
+ * The identity a device acts for, under which its record is kept. A send
89
+ * (`artifact.send`, `event.send`, `trust.request`, `trust.respond`) is
90
+ * addressed `to` the receiver, so its owner is the sender of the transporter
91
+ * artifact it carries; any other action is on the owner's own account, `to`.
92
+ */
93
+ private deviceOwner;
94
+ /**
95
+ * Gets the public key for an agent based on whether it's onboarding or existing
96
+ */
97
+ private getAgentPublicKey;
98
+ /**
99
+ * Core agent trust verification (non-negotiable)
100
+ */
101
+ private verifyAgentTrust;
102
+ /**
103
+ * Verifies attestation signatures for delegated artifacts
104
+ *
105
+ * This method verifies that a trusted third-party attestor has signed the delegation,
106
+ * providing additional validation for custom managed domain delegations. The attestation
107
+ * serves as a proof that the delegation has been reviewed and approved by a trusted
108
+ * authority.
109
+ *
110
+ * @param delegation - The delegation object containing attestation information
111
+ * @returns Promise resolving to verification result with validity status and optional error
112
+ *
113
+ * @example
114
+ * ```typescript
115
+ * const result = await this.verifyAttestation(delegationWithAttestation);
116
+ * if (!result.isValid) {
117
+ * console.error('Attestation verification failed:', result.error);
118
+ * }
119
+ * ```
120
+ */
121
+ private verifyAttestation;
122
+ /**
123
+ * Core delegation verification (non-negotiable)
124
+ *
125
+ * This method verifies delegated artifacts by performing a multi-step verification process:
126
+ *
127
+ * 1. **Attestation Requirement Check**: Determines if attestation is required based on whether
128
+ * the delegator is the same as the artifact sender (custom managed domain delegation).
129
+ * If required but not provided, returns an error.
130
+ *
131
+ * 2. **Attestation Verification** (if provided): Verifies that a trusted third-party attestor
132
+ * has signed the delegation, providing additional validation for custom managed domains.
133
+ * This involves:
134
+ * - Resolving the attestor's public key
135
+ * - Verifying the attestation signature against the delegation metadata
136
+ *
137
+ * 3. **Delegation Signature Verification**: Verifies that the delegator (main identity) has signed
138
+ * the delegation, proving they authorized the agent to act on their behalf. This involves:
139
+ * - Resolving the delegator's public key
140
+ * - Verifying the delegation signature against the complete artifact (including delegation metadata)
141
+ *
142
+ * 4. **Original Artifact Verification**: Verifies that the original artifact was signed by the
143
+ * delegated agent using their public key. This ensures the agent properly signed the actual
144
+ * message content.
145
+ *
146
+ * This comprehensive verification ensures authorization (delegator approved the delegation),
147
+ * attestation (third-party validation when required), and authenticity (agent properly signed
148
+ * the message) are maintained in delegated operations.
149
+ *
150
+ * @param artifactWithDelegation - The transporter artifact containing delegation information
151
+ * @returns Promise resolving to verification result with validity status and optional error
152
+ *
153
+ * @example
154
+ * ```typescript
155
+ * const result = await this.verifyDelegation(artifactWithDelegation);
156
+ * if (!result.isValid) {
157
+ * console.error('Delegation verification failed:', result.error);
158
+ * }
159
+ * ```
160
+ */
161
+ private verifyDelegation;
162
+ /**
163
+ * Core transporter signature verification (non-negotiable)
164
+ */
165
+ private verifySignature;
166
+ /**
167
+ * A `BTPS_EVENT` must name (`relatesTo`, outside its document) an artifact
168
+ * the platform's trust store says passed between the same two parties. It
169
+ * is checked without decrypting anything, so it holds for self-held keys
170
+ * too. Other artifacts pass.
171
+ */
172
+ private verifyEventRelation;
173
+ /**
174
+ * Core trust verification (non-negotiable)
175
+ */
176
+ private verifyTrust;
177
+ /**
178
+ * A trust records how its artifacts are sent: 'encrypted' refuses one sent in
179
+ * the clear, 'unencrypted' one the receiver did not agree to decrypt, and
180
+ * 'mixed' allows either. A record without one allows either.
181
+ */
182
+ private verifyPrivacyType;
183
+ /**
184
+ * Determines the precise, server-side-only reason a non-trust
185
+ * artifact is refused - never-trusted, expired, revoked, or blocked.
186
+ *
187
+ * Only the expired case gets its own wire
188
+ * code (BTP_ERROR_TRUST_EXPIRED); revoked, blocked, never-trusted, pending
189
+ * and rejected all collapse onto BTP_ERROR_TRUST_NOT_ALLOWED on the wire
190
+ * (see executeRequestPipeline). This method's result is what reqCtx.error
191
+ * carries internally - the exact reason - regardless of what later goes
192
+ * out on the wire.
193
+ *
194
+ * "Expired" means an *accepted* trust whose expiresAt has passed - a
195
+ * blocked, rejected or pending record with a past expiresAt is not
196
+ * "expired", it is whatever it already was, so the expiry check only
197
+ * runs for status === 'accepted'.
198
+ */
199
+ private getTrustRefusalError;
200
+ /**
201
+ * Emits an event and optionally awaits all listeners if `shouldAwait` is true.
202
+ */
203
+ private awaitableEmitIfNeeded;
204
+ /**
205
+ * Whether anything on this server takes artifacts of this type: a handler
206
+ * registered with onIncomingArtifact, forwardTo, or 'before onArtifact'
207
+ * middleware. 'after onArtifact' middleware runs once delivery is done, as
208
+ * metrics do, so it takes nothing.
209
+ */
210
+ private acceptsArtifacts;
211
+ private noHandlerWarning;
212
+ /**
213
+ * Core message processing (non-negotiable)
214
+ */
215
+ private processMessage;
216
+ /**
217
+ * Parses and validates an artifact from a string
218
+ * @param line - The string to parse
219
+ * @returns The parsed and validated artifact or an error
220
+ */
221
+ private _parseAndValidateArtifact;
222
+ /**
223
+ * Checks if an agent action requires immediate response
224
+ */
225
+ private isImmediateAction;
226
+ /**
227
+ * Optionally forwards message to a handler function or HTTP webhook.
228
+ */
229
+ private _forwardArtifact;
230
+ /**
231
+ * Handles socket-related errors by recording metrics and safely terminating the socket.
232
+ *
233
+ * @param error The encountered error
234
+ * @param socket The TLS socket associated with the connection
235
+ * @param action 'destroy' (the default) tears the socket down at once; 'end' sends the error and closes gently
236
+ */
237
+ private handleOnSocketError;
238
+ /**
239
+ * Sends a BTPS error response to the client
240
+ */
241
+ /**
242
+ * What a sender is told about an error. A BTPS error carries its status and
243
+ * its code; a numeric code set by middleware is sent as given. Anything else
244
+ * is internal: a generic 500, so no internal detail ever reaches the wire.
245
+ * The full error stays with the server, keyed by the response id.
246
+ */
247
+ private wireStatus;
248
+ private sendBtpsError;
249
+ /**
250
+ * Sends a BTPS response to the client
251
+ * @param socket - The socket to send the response to
252
+ * @param artifact - The artifact to send
253
+ */
254
+ private sendBtpsResponse;
255
+ /**
256
+ * Returns the BTPS protocol version
257
+ */
258
+ getProtocolVersion(): string;
259
+ /**
260
+ * Prepares a BTPS server response with the given status
261
+ */
262
+ prepareBtpsResponse(status: BTPStatus, reqId?: string): Omit<BTPServerResponse, 'type'>;
263
+ /**
264
+ * Starts the BTPS server
265
+ */
266
+ start(): Promise<void>;
267
+ /**
268
+ * Stops the BTPS server
269
+ */
270
+ stop(): void;
271
+ /**
272
+ * Forwards messages to a handler function
273
+ */
274
+ forwardTo(handler: (msg: ProcessedArtifact) => Promise<void>): void;
275
+ onIncomingArtifact(type: 'Agent', handler: (artifact: BTPAgentArtifact & {
276
+ respondNow: boolean;
277
+ }, resCtx: ArtifactResCtx) => void): void;
278
+ onIncomingArtifact(type: 'Transporter', handler: (artifact: BTPTransporterArtifact) => void | Promise<void>): void;
279
+ /**
280
+ * The server's identity and, when it is configured with a PEM key pair, its
281
+ * public key. Never the private key: middleware is handed this server, and the
282
+ * key stays with the server alone.
283
+ */
284
+ getServerIdentity(): {
285
+ identity: string;
286
+ publicKey?: string;
287
+ };
288
+ getDependencies(): {
289
+ trustStore: AbstractTrustStore<BTPTrustRecord>;
290
+ identityStore?: AbstractIdentityStore<BTPIdentityRecord>;
291
+ };
292
+ }