@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
package/CHANGELOG.md ADDED
@@ -0,0 +1,171 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@btps/sdk` and the BTPS protocol it implements. The
4
+ format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
5
+ versions follow [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [1.1.1] — 2026-10-19 (alpha)
8
+
9
+ A patch release: the protocol and the API are unchanged.
10
+
11
+ ### Fixed
12
+
13
+ - **The package is about 3.8 MB smaller.** It no longer ships type
14
+ declarations that no entry point can reach: the exports map lets a project
15
+ import only the entry points, so those files were never read. The
16
+ declarations every entry point needs are all still included, and CI now
17
+ type-checks each entry point against the packed package.
18
+
19
+ ### Corrected
20
+
21
+ - The 1.1.0 notes said every trust refusal reads `BTP_ERROR_TRUST_NOT_ALLOWED`.
22
+ Two stay distinct on the wire: an expired trust reads
23
+ `BTP_ERROR_TRUST_EXPIRED`, and an artifact sent without the encryption the
24
+ trust requires reads `BTP_ERROR_PRIVACY_TYPE`. Every other refusal, including
25
+ a trust that was never made, is pending, rejected, revoked or blocked, reads
26
+ `BTP_ERROR_TRUST_NOT_ALLOWED`.
27
+
28
+ ## [1.1.0] — 2026-10-18 (alpha)
29
+
30
+ BTPS 1.1 is the alpha release of the protocol: 1.2 is planned as the beta and
31
+ 1.3 as the general release. A 1.1 server refuses 1.0 artifacts, so both sides
32
+ of an exchange must upgrade together.
33
+
34
+ ### Breaking
35
+
36
+ - **Protocol version 1.1.0.** Servers check every artifact's `version` and
37
+ refuse another major.minor with `BTP_ERROR_VERSION_UNSUPPORTED` (400).
38
+ - **Node.js 24 or later.**
39
+ - **Canonical signing (JCS, RFC 8785).** Signatures are over the canonical
40
+ form, so any implementation in any language produces the same bytes. A line
41
+ that names a member twice is refused.
42
+ - **The 1.1 invoice.** Money is in integer minor units
43
+ (`{ amount: 150000, currency: 'AUD' }` is AUD 1,500.00). The invoice has no
44
+ `status`: status comes from lifecycle events. It may carry several
45
+ attachments (with size and SHA-256), the issuer's address and identifiers,
46
+ and references to other documents. A credit note is an invoice with a
47
+ `credits` reference. The schema is strict: a field it does not name is
48
+ refused.
49
+ - **An artifact's `selector` names the sender's own signing key.** In 1.0,
50
+ `signEncrypt` wrote the receiver's selector.
51
+ - **The domain operator.** A domain names the identity that operates it in its
52
+ `_btps.host` record (`op=<identity>`). Delegations, attestations and
53
+ identity-lookup answers are accepted only from that operator. A SaaS must
54
+ publish `op=` for its domain.
55
+ - **Address characters.** The username is letters, digits, `.`, `_` and `-`
56
+ (up to 64); the domain follows DNS's rules, with international names in
57
+ their `xn--` form; exactly one `$`. Letters compare without case.
58
+ - **Client timeouts.** `connectTimeoutMs` (at least and by default 5 s) and
59
+ `replyTimeoutMs` (at least 10 s, default 20 s) replace the single wait.
60
+ `connectionTimeoutMs` is now only an idle timeout.
61
+ - **Error codes on the wire.** Every refusal carries its exact status and its
62
+ code in `status.error`. A refusal never tells the sender what only the
63
+ receiver knows: a trust that was never made, is pending, rejected, revoked or
64
+ blocked all read `BTP_ERROR_TRUST_NOT_ALLOWED`.
65
+ - **Field limits.** Trust requests, trust responses and lifecycle events have
66
+ a longest length for each text field, and every document's `id` and
67
+ references are limited, the same at every provider
68
+ (`BTP_ERROR_VALIDATION`). An encrypted document is checked by the sender's
69
+ SDK before encrypting and by the receiver's after decrypting. The numbers
70
+ are exported as `BTPS_FIELD_LIMITS`. Every limit is listed on the new
71
+ Limits page of the protocol docs.
72
+ - **`trust.update` and `trust.delete`** edit the user's own trust records at
73
+ their provider and send nothing to the other side.
74
+ - **`BtpsTransporter.getConnectionTTLSeconds()`** returns seconds (it returned
75
+ milliseconds).
76
+
77
+ ### Added
78
+
79
+ - **Protocol golden vectors** for any implementation, in any language:
80
+ addresses, every document type with each field limit at and one over,
81
+ two artifacts exactly as they travel (plain and encrypted), the device key
82
+ proof, the time window, and a manifest of the whole set with each file's
83
+ SHA-256. `yarn verify:btps-vectors` checks them on Node and WebCrypto and
84
+ against the SDK.
85
+ - **Receipts, payslips and letters.** A `BTPS_DOC` now carries an `invoice`,
86
+ a `receipt`, a `payslip` or a `letter`, by its `type`.
87
+
88
+ - A receipt is the invoice without `dueAt` and `paymentLink`, with a
89
+ required `payment`; it may name the invoice it pays (`receipt_for`).
90
+ - A payslip lists earnings, deductions, contributions and leave, each by an
91
+ open code, with decimals written as text.
92
+ - A letter has a title and one body, `text` or `markdown`, and no money.
93
+
94
+ - **Lifecycle events (`BTPS_EVENT`):** `paid`, `partially_paid`, `disputed`,
95
+ `refund_requested`, `refund` and `response`. Each names the invoice it is
96
+ about (`document` and the `relatesTo` artifact id). Replies carry
97
+ `inReplyTo`. An event may come back over the trust that delivered the
98
+ invoice.
99
+ - **`Signer` and `Decrypter` interfaces**, so a platform can keep private keys
100
+ in a KMS or a device keystore. PEM and KMS-shaped implementations are
101
+ included.
102
+ - **Device keys:** registration codes and refresh tokens are taken once,
103
+ atomically. Every refresh is signed by the device's current key.
104
+ `BtpsAuthentication.rotateKey` moves a device to a new key with a proof
105
+ signed by that key.
106
+ - **Identity lookup through the host,** for an address whose key is not in
107
+ DNS, answered and signed by the domain's operator.
108
+ - **Server guards:** a maximum artifact size (`maxArtifactSizeKb`, 5 MB by
109
+ default), a time window for `issuedAt` (`maxArtifactAgeSeconds`,
110
+ 5 minutes by default), and a limit on requests handled at once per
111
+ connection (`maxInFlightPerConnection`, 32 by default). At that limit the
112
+ server reads no more from the connection until one finishes, so a sender
113
+ that does not wait for answers is slowed instead of filling its memory.
114
+ - **`privacyType` is enforced:** a plain artifact over a trust that requires
115
+ encryption is refused (`BTP_ERROR_PRIVACY_TYPE`).
116
+ - **`sentbox.fetch` and `sentbox.delete`** agent actions.
117
+ - **Exports:** `BtpsTransporter`, the transporter's defaults and error codes,
118
+ the timeout, size, time-window and idle defaults, and `CURRENCY_CODES`.
119
+ - **Transporter connections stay open while busy.** The TTL is idle time, a
120
+ connection is never closed while a send waits for its answer, and a full
121
+ pool closes the connection idle longest instead of refusing.
122
+ - **Test suites:** end-to-end journeys (`ci/e2e`) and an attack, spoofing,
123
+ spam and probing suite (`ci/security`), against real servers over TLS.
124
+ - **Documentation:** the client pages, the security best practices
125
+ ("Defending your provider"), and a docs build that fails on any broken link
126
+ (`ci/docs`).
127
+
128
+ ### Fixed
129
+
130
+ - A sender whose published key is not a public key no longer writes a
131
+ console line for every artifact it signs. The refusal
132
+ (`BTP_ERROR_SIG_MISMATCH`) says why in `meta.reason`.
133
+
134
+ - A JSON store with no records no longer reads its file again on every
135
+ lookup.
136
+
137
+ - A client bundle no longer carries the server. `@btps/sdk/client` imported
138
+ the server entry for one constant, and `@btps/sdk/authentication` reached
139
+ the JSON file stores through the trust barrel, so a phone or browser app
140
+ bundled `BtpsServer`, its middleware loader and file locking. The trust
141
+ rules now live apart from the file store; `@btps/sdk/trust` exports the same
142
+ names.
143
+
144
+ - A device can send. Its `artifact.send`, `event.send`, `trust.request` and
145
+ `trust.respond`, addressed to someone else, were refused as a signature
146
+ failure, because the server looked the device up under the receiver. It is
147
+ now looked up under the sender of the artifact it carries.
148
+
149
+ - AES-GCM requires a full 16-byte authentication tag. RSA keys under 2048
150
+ bits are refused.
151
+ - A server with no handler for an artifact refuses it
152
+ (`BTP_ERROR_ARTIFACT_NOT_ACCEPTED`) instead of answering success, and
153
+ answers success only once the handler has returned.
154
+ - Each line gets its own request context, and an answer is correlated to its
155
+ request id. An error the server wrote before it could read an id goes to the
156
+ single pending send.
157
+ - `PING` keeps the connection open. A connection is never closed mid-request.
158
+ - `getServerIdentity()` never returns the private key.
159
+ - Device records are kept apart from trust between identities, so a trusted
160
+ business cannot act as one of the receiver's devices.
161
+ - Device `artifact.send` and `event.send` pass the server's schema, and
162
+ attested delegations verify.
163
+ - `signEncrypt` finds the receiver's key in DNS first, then from the
164
+ receiver's host.
165
+ - `transport()` answers `{ error }` when no connection can be opened instead
166
+ of throwing. The client's `connected` event is typed with what it emits.
167
+ - The default middleware counts an identity's rate limit after signature
168
+ verification. Rate limiting is off unless a provider enables it.
169
+
170
+ [1.1.1]: https://github.com/openbtps/btps-node/releases/tag/v1.1.1
171
+ [1.1.0]: https://github.com/openbtps/btps-node/releases/tag/v1.1.0
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Copyright 2025 Bhupendra Tamang
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+
15
+ ---
16
+
17
+ Apache License
18
+ Version 2.0, January 2004
19
+ http://www.apache.org/licenses/
20
+
21
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
22
+
23
+ 1. Definitions.
24
+
25
+ "License" shall mean the terms and conditions for use, reproduction,
26
+ and distribution as defined by Sections 1 through 9 of this document.
27
+
28
+ "Licensor" shall mean the copyright owner or entity authorized by
29
+ the copyright owner that is granting the License.
30
+
31
+ "Legal Entity" shall mean the union of the acting entity and all
32
+ other entities that control, are controlled by, or are under common
33
+ control with that entity. For the purposes of this definition,
34
+ "control" means (i) the power, direct or indirect, to cause the
35
+ direction or management of such entity, whether by contract or
36
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
37
+ outstanding shares, or (iii) beneficial ownership of such entity.
38
+
39
+ "You" (or "Your") shall mean an individual or Legal Entity
40
+ exercising permissions granted by this License.
41
+
42
+ "Source" form shall mean the preferred form for making modifications,
43
+ including but not limited to software source code, documentation
44
+ source, and configuration files.
45
+
46
+ "Object" form shall mean any form resulting from mechanical
47
+ transformation or translation of a Source form, including but
48
+ not limited to compiled object code, generated documentation,
49
+ and conversions to other media types.
50
+
51
+ "Work" shall mean the work of authorship, whether in Source or
52
+ Object form, made available under the License, as indicated by a
53
+ copyright notice that is included in or attached to the work
54
+ (an example is provided in the Appendix below).
55
+
56
+ "Derivative Works" shall mean any work, whether in Source or Object
57
+ form, that is based on (or derived from) the Work and for which the
58
+ editorial revisions, annotations, elaborations, or other modifications
59
+ represent, as a whole, an original work of authorship. For the purposes
60
+ of this License, Derivative Works shall not include works that remain
61
+ separable from, or merely link (or bind by name) to the interfaces of,
62
+ the Work and Derivative Works thereof.
63
+
64
+ "Contribution" shall mean any work of authorship, including
65
+ the original version of the Work and any modifications or additions
66
+ to that Work or Derivative Works thereof, that is intentionally
67
+ submitted to Licensor for inclusion in the Work by the copyright owner
68
+ or by an individual or Legal Entity authorized to submit on behalf of
69
+ the copyright owner. For the purposes of this definition, "submitted"
70
+ means any form of electronic, verbal, or written communication sent
71
+ to the Licensor or its representatives, including but not limited to
72
+ communication on electronic mailing lists, source code control systems,
73
+ and issue tracking systems that are managed by, or on behalf of, the
74
+ Licensor for the purpose of discussing and improving the Work, but
75
+ excluding communication that is conspicuously marked or otherwise
76
+ designated in writing by the copyright owner as "Not a Contribution."
77
+
78
+ "Contributor" shall mean Licensor and any individual or Legal Entity
79
+ on behalf of whom a Contribution has been received by Licensor and
80
+ subsequently incorporated within the Work.
81
+
82
+ 2. Grant of Copyright License. Subject to the terms and conditions of
83
+ this License, each Contributor hereby grants to You a perpetual,
84
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
85
+ copyright license to reproduce, prepare Derivative Works of,
86
+ publicly display, publicly perform, sublicense, and distribute the
87
+ Work and such Derivative Works in Source or Object form.
88
+
89
+ 3. Grant of Patent License. Subject to the terms and conditions of
90
+ this License, each Contributor hereby grants to You a perpetual,
91
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
92
+ (except as stated in this section) patent license to make, have made,
93
+ use, offer to sell, sell, import, and otherwise transfer the Work,
94
+ where such license applies only to those patent claims licensable
95
+ by such Contributor that are necessarily infringed by their
96
+ Contribution(s) alone or by combination of their Contribution(s)
97
+ with the Work to which such Contribution(s) was submitted. If You
98
+ institute patent litigation against any entity (including a
99
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
100
+ or a Contribution incorporated within the Work constitutes direct
101
+ or contributory patent infringement, then any patent licenses
102
+ granted to You under this License for that Work shall terminate
103
+ as of the date such litigation is filed.
104
+
105
+ 4. Redistribution. You may reproduce and distribute copies of the
106
+ Work or Derivative Works thereof in any medium, with or without
107
+ modifications, and in Source or Object form, provided that You
108
+ meet the following conditions:
109
+
110
+ (a) You must give any other recipients of the Work or
111
+ Derivative Works a copy of this License; and
112
+
113
+ (b) You must cause any modified files to carry prominent notices
114
+ stating that You changed the files; and
115
+
116
+ (c) You must retain, in the Source form of any Derivative Works
117
+ that You distribute, all copyright, patent, trademark, and
118
+ attribution notices from the Source form of the Work,
119
+ excluding those notices that do not pertain to any part of
120
+ the Derivative Works; and
121
+
122
+ (d) If the Work includes a "NOTICE" text file as part of its
123
+ distribution, then any Derivative Works that You distribute must
124
+ include a readable copy of the attribution notices contained
125
+ within such NOTICE file, excluding those notices that do not
126
+ pertain to any part of the Derivative Works, in at least one
127
+ of the following places: within a NOTICE text file distributed
128
+ as part of the Derivative Works; within the Source form or
129
+ documentation, if provided along with the Derivative Works; or,
130
+ within a display generated by the Derivative Works, if and
131
+ wherever such third-party notices normally appear. The contents
132
+ of the NOTICE file are for informational purposes only and
133
+ do not modify the License. You may add Your own attribution
134
+ notices within Derivative Works that You distribute, alongside
135
+ or as an addendum to the NOTICE text from the Work, provided
136
+ that such additional attribution notices cannot be construed
137
+ as modifying the License.
138
+
139
+ You may add Your own copyright statement to Your modifications and
140
+ may provide additional or different license terms and conditions
141
+ for use, reproduction, or distribution of Your modifications, or
142
+ for any such Derivative Works as a whole, provided Your use,
143
+ reproduction, and distribution of the Work otherwise complies with
144
+ the conditions stated in this License.
145
+
146
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
147
+ any Contribution intentionally submitted for inclusion in the Work
148
+ by You to the Licensor shall be under the terms and conditions of
149
+ this License, without any additional terms or conditions.
150
+ Notwithstanding the above, nothing herein shall supersede or modify
151
+ the terms of any separate license agreement you may have executed
152
+ with Licensor regarding such Contributions.
153
+
154
+ 6. Trademarks. This License does not grant permission to use the trade
155
+ names, trademarks, service marks, or product names of the Licensor,
156
+ except as required for reasonable and customary use in describing the
157
+ origin of the Work and reproducing the content of the NOTICE file.
158
+
159
+ 7. Disclaimer of Warranty. Unless required by applicable law or
160
+ agreed to in writing, Licensor provides the Work (and each
161
+ Contributor provides its Contributions) on an "AS IS" BASIS,
162
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
163
+ implied, including, without limitation, any warranties or conditions
164
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
165
+ PARTICULAR PURPOSE. You are solely responsible for determining the
166
+ appropriateness of using or redistributing the Work and assume any
167
+ risks associated with Your exercise of permissions under this License.
168
+
169
+ 8. Limitation of Liability. In no event and under no legal theory,
170
+ whether in tort (including negligence), contract, or otherwise,
171
+ unless required by applicable law (such as deliberate and grossly
172
+ negligent acts) or agreed to in writing, shall any Contributor be
173
+ liable to You for damages, including any direct, indirect, special,
174
+ incidental, or consequential damages of any character arising as a
175
+ result of this License or out of the use or inability to use the
176
+ Work (including but not limited to damages for loss of goodwill,
177
+ work stoppage, computer failure or malfunction, or any and all
178
+ other commercial damages or losses), even if such Contributor
179
+ has been advised of the possibility of such damages.
180
+
181
+ 9. Accepting Warranty or Additional Liability. While redistributing
182
+ the Work or Derivative Works thereof, You may choose to offer,
183
+ and charge a fee for, acceptance of support, warranty, indemnity,
184
+ or other liability obligations and/or rights consistent with this
185
+ License. However, in accepting such obligations, You may act only
186
+ on Your own behalf and on Your sole responsibility, not on behalf
187
+ of any other Contributor, and only if You agree to indemnify,
188
+ defend, and hold each Contributor harmless for any liability
189
+ incurred by, or claims asserted against, such Contributor by reason
190
+ of your accepting any such warranty or additional liability.
package/NOTICE ADDED
@@ -0,0 +1,25 @@
1
+ @btps/sdk – the BTPS SDK for Node.js
2
+ Copyright 2025 Bhupendra Tamang
3
+
4
+ This product includes software developed by Bhupendra Tamang for BTPS, the
5
+ Billing Trust Protocol Secure: signed, encrypted, trust-first delivery of
6
+ invoices and other documents between organisations.
7
+
8
+ Licensed under the Apache License, Version 2.0 (the "License"). You may not
9
+ use this software except in compliance with the License. You may obtain a
10
+ copy of the License at:
11
+
12
+ https://www.apache.org/licenses/LICENSE-2.0
13
+
14
+ Unless required by applicable law or agreed to in writing, software
15
+ distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16
+ WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17
+ License for the specific language governing permissions and limitations
18
+ under the License.
19
+
20
+ This software depends on other open-source packages, each under its own
21
+ license.
22
+
23
+ The License does not grant permission to use the names "BTPS" or "OpenBTPS",
24
+ or related trademarks, except as needed to describe the origin of this
25
+ software (section 6 of the License).
package/README.md CHANGED
@@ -1,3 +1,262 @@
1
- # Temporary Holding Version
1
+ <h1 align="center">BTPS SDK for Node.js</h1>
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center">
4
+ The reference implementation of <strong>BTPS</strong>, the Billing Trust Protocol Secure:<br />
5
+ signed, encrypted, trust-first delivery of invoices and other documents between organisations.
6
+ </p>
7
+
8
+ <p align="center">
9
+ <a href="https://github.com/openbtps/btps-node/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/openbtps/btps-node/actions/workflows/ci.yml/badge.svg?branch=master" /></a>
10
+ <a href="https://www.npmjs.com/package/@btps/sdk"><img alt="npm" src="https://img.shields.io/npm/v/@btps/sdk" /></a>
11
+ <img alt="Node.js 24 or later" src="https://img.shields.io/badge/node-%E2%89%A524-339933" />
12
+ <a href="LICENSE"><img alt="Apache-2.0" src="https://img.shields.io/badge/license-Apache--2.0-blue" /></a>
13
+ <img alt="Status: alpha" src="https://img.shields.io/badge/status-alpha-orange" />
14
+ </p>
15
+
16
+ <p align="center">
17
+ <a href="https://www.openbtps.org/docs/"><strong>Documentation</strong></a> ·
18
+ <a href="https://www.openbtps.org/docs/getting-started/installation">Getting started</a> ·
19
+ <a href="https://www.openbtps.org/docs/protocol/overview">Protocol</a> ·
20
+ <a href="https://www.openbtps.org/docs/roadmap">Roadmap</a> ·
21
+ <a href="CHANGELOG.md">Changelog</a>
22
+ </p>
23
+
24
+ ---
25
+
26
+ ## Why BTPS
27
+
28
+ Invoices still travel by email and portals, where a forged or altered bill
29
+ looks the same as a real one. BTPS replaces that with a protocol in which:
30
+
31
+ - **Addresses look like email but prove who sent them.** `billing$vendor.com`
32
+ is published in DNS with the sender's public key, and every artifact is
33
+ signed by it.
34
+ - **Nothing arrives without trust.** A sender asks first; only once the
35
+ receiver accepts can it deliver documents. A stranger cannot drop a bill in
36
+ your inbox.
37
+ - **Documents are private end to end.** They are encrypted to the receiver's
38
+ key, so the servers in between see only ciphertext.
39
+ - **Any provider talks to any other**, the way any mail server talks to any
40
+ other: the protocol is open, and the rules are the same everywhere.
41
+
42
+ ## Status
43
+
44
+ **1.1 is the alpha release.** The protocol and this SDK are usable and
45
+ tested, and may still change before the general release: 1.2 is planned as
46
+ the beta and 1.3 as the general release. What 1.2 is planned to bring is
47
+ on the [roadmap](https://www.openbtps.org/docs/roadmap); changes are listed
48
+ in the [changelog](CHANGELOG.md). A 1.1 server refuses artifacts of another
49
+ protocol version, so both sides of an exchange upgrade together.
50
+
51
+ ## Features
52
+
53
+ - **Signing:** RSASSA-PKCS1-v1_5 / SHA-256 over the RFC 8785 canonical form
54
+ (JCS), so every implementation, in any language, signs the same bytes.
55
+ - **Encryption:** AES-256-GCM, with the key wrapped by RSA-OAEP / SHA-256.
56
+ - **Trust:** requests, responses, expiry, revocation and blocking, with a
57
+ per-trust choice of encrypted, unencrypted or both.
58
+ - **Documents:** invoices, receipts, payslips and letters, with lifecycle
59
+ events for payment, part payment, dispute and refund.
60
+ - **Devices:** phones and apps register with a one-time code, sign their
61
+ own requests and rotate their keys.
62
+ - **Hosted identities:** a SaaS can send for its users through delegation,
63
+ and keep keys in a KMS or a device keystore through the `Signer` and
64
+ `Decrypter` interfaces.
65
+ - **Built-in protection:** artifact size and age limits, field limits, a cap
66
+ on requests in flight per connection, and strict refusal of malformed or
67
+ ambiguous input. Rate limits and filters are yours to add as
68
+ [middleware](https://www.openbtps.org/docs/protocol/security/best-practices).
69
+
70
+ ## Install
71
+
72
+ ```sh
73
+ npm install @btps/sdk
74
+ ```
75
+
76
+ Requires **Node.js 24 or later**. The package is ESM only.
77
+
78
+ | Import | For |
79
+ | -------------------------- | ------------------------------------------------- |
80
+ | `@btps/sdk/server` | `BtpsServer`, document types, protocol constants |
81
+ | `@btps/sdk/server/core` | default middleware, rate limiter, server settings |
82
+ | `@btps/sdk/client` | `BtpsClient`, `BtpsTransporter`, `BtpsAgent` |
83
+ | `@btps/sdk/crypto` | signing, encryption, `Signer` and `Decrypter` |
84
+ | `@btps/sdk/trust` | trust records and stores |
85
+ | `@btps/sdk/authentication` | device registration, refresh and key rotation |
86
+ | `@btps/sdk/delegation` | `BtpsDelegator`, for sending on a user's behalf |
87
+ | `@btps/sdk/storage` | identity and storage stores |
88
+ | `@btps/sdk/error` | error codes and `BTPErrorException` |
89
+ | `@btps/sdk` | address and DNS utilities |
90
+
91
+ ## Quick start
92
+
93
+ ### Receive: run a server
94
+
95
+ ```ts
96
+ import { readFileSync } from 'node:fs';
97
+ import { BtpsServer } from '@btps/sdk/server';
98
+ import { JsonTrustStore } from '@btps/sdk/trust';
99
+
100
+ const server = new BtpsServer({
101
+ serverIdentity: {
102
+ identity: 'admin$yourdomain.com',
103
+ publicKey: readFileSync('./keys/public.pem', 'utf8'),
104
+ privateKey: readFileSync('./keys/private.pem', 'utf8'),
105
+ },
106
+ trustStore: new JsonTrustStore({ connection: './data/trust.json' }),
107
+ tlsOptions: {
108
+ key: readFileSync('./keys/tls-key.pem', 'utf8'),
109
+ cert: readFileSync('./keys/tls-cert.pem', 'utf8'),
110
+ },
111
+ });
112
+
113
+ // Each artifact here has passed the signature, time-window and trust checks
114
+ // (a trust request, which comes before any trust, is checked for everything else).
115
+ server.onIncomingArtifact('Transporter', async (artifact) => {
116
+ console.log(`${artifact.type} from ${artifact.from}`);
117
+ });
118
+
119
+ await server.start();
120
+ ```
121
+
122
+ `JsonTrustStore` keeps trust in a file, for development. In production,
123
+ implement the store over your database
124
+ ([database integration](https://www.openbtps.org/docs/getting-started/server/database-integration)).
125
+
126
+ ### Send: deliver an invoice
127
+
128
+ ```ts
129
+ import { parseIdentity } from '@btps/sdk';
130
+ import { BtpsTransporter } from '@btps/sdk/client';
131
+ import { signEncrypt } from '@btps/sdk/crypto';
132
+ import type { BTPInvoiceDoc, BTPTransporterArtifact } from '@btps/sdk/server';
133
+
134
+ const from = 'billing$yourdomain.com';
135
+ const to = 'pay$client.com';
136
+ const keys = {
137
+ privateKey: '-----BEGIN PRIVATE KEY-----…',
138
+ publicKey: '-----BEGIN PUBLIC KEY-----…',
139
+ };
140
+
141
+ const invoice: BTPInvoiceDoc = {
142
+ type: 'invoice',
143
+ title: 'Website build',
144
+ id: 'INV-2026-001',
145
+ issuedAt: new Date().toISOString(),
146
+ totalAmount: { amount: 150000, currency: 'AUD' }, // integer minor units: AUD 1,500.00
147
+ lineItems: { columns: ['Item', 'Amount'], rows: [{ Item: 'Website build', Amount: 150000 }] },
148
+ };
149
+
150
+ // Sign, and encrypt to the receiver's published key.
151
+ const { accountName, domainName } = parseIdentity(from)!;
152
+ const { payload, error } = await signEncrypt(
153
+ to,
154
+ { accountName, domainName, pemFiles: keys },
155
+ { version: '1.1.0', type: 'BTPS_DOC', from, to, selector: 'btps1', document: invoice },
156
+ {
157
+ signature: { algorithmHash: 'sha256' },
158
+ encryption: { algorithm: 'aes-256-gcm', mode: 'standardEncrypt' },
159
+ },
160
+ );
161
+ if (error) throw error;
162
+
163
+ // Deliver it: the transporter finds the receiver's server in DNS and keeps a connection pool.
164
+ const transporter = new BtpsTransporter({ maxConnections: 10 });
165
+ const { response, error: sendError } = await transporter.transport(
166
+ to,
167
+ payload as BTPTransporterArtifact,
168
+ );
169
+ ```
170
+
171
+ Before the first invoice, the receiver has to accept a trust request from
172
+ you. The [getting-started guide](https://www.openbtps.org/docs/getting-started/installation)
173
+ walks through keys, DNS records, trust and delivery from the beginning.
174
+
175
+ ## Documentation
176
+
177
+ The full documentation is at **[openbtps.org/docs](https://www.openbtps.org/docs/)**.
178
+ Its source is in [`docs/docusaurus`](docs/docusaurus/docs).
179
+
180
+ - **[Getting started](https://www.openbtps.org/docs/getting-started/installation)**:
181
+ [server](https://www.openbtps.org/docs/getting-started/server/setup),
182
+ [client](https://www.openbtps.org/docs/getting-started/client/setup),
183
+ [transporter](https://www.openbtps.org/docs/getting-started/client/transporter-setup),
184
+ [devices](https://www.openbtps.org/docs/getting-started/client/agent-setup)
185
+ - **[Protocol](https://www.openbtps.org/docs/protocol/overview)**:
186
+ [principles](https://www.openbtps.org/docs/protocol/principles),
187
+ [specifications](https://www.openbtps.org/docs/protocol/specifications/overview),
188
+ [trust records](https://www.openbtps.org/docs/protocol/trust-record),
189
+ [limits](https://www.openbtps.org/docs/protocol/specifications/limits),
190
+ [golden vectors](https://www.openbtps.org/docs/protocol/specifications/golden-vectors)
191
+ - **[Security best practices](https://www.openbtps.org/docs/protocol/security/best-practices)**
192
+ - **[SDK reference](https://www.openbtps.org/docs/sdk/overview)**:
193
+ [API](https://www.openbtps.org/docs/sdk/api-references),
194
+ [types](https://www.openbtps.org/docs/sdk/types-and-interfaces)
195
+
196
+ ## Repository layout
197
+
198
+ ```text
199
+ src/
200
+ ├── server/ BtpsServer: guards, middleware, settings
201
+ ├── client/ BtpsClient, BtpsTransporter, BtpsAgent
202
+ └── core/
203
+ ├── crypto/ signing, encryption, canonical JSON, Signer and Decrypter
204
+ ├── trust/ trust records, rules and stores
205
+ ├── authentication/ device registration, refresh and key rotation
206
+ ├── delegation/ BtpsDelegator
207
+ ├── server/ document schemas, limits and protocol constants
208
+ ├── storage/ identity and storage stores
209
+ ├── error/ BTPErrorException and the error codes
210
+ └── utils/ addresses and DNS
211
+ tests/
212
+ ├── e2e/ journeys between real servers over TLS
213
+ └── security/ attacks, spoofing, flooding and probing
214
+ test/vectors/ the golden vectors
215
+ packages/
216
+ └── verify-btps-vectors/ the golden-vector runner (Node, WebCrypto and the SDK)
217
+ docs/docusaurus/ the documentation site, published at openbtps.org/docs
218
+ examples/
219
+ ├── btps-nest-app/ a provider built on NestJS, built and run in CI
220
+ ├── btps-server-app/ an earlier server example, not yet updated for 1.1
221
+ └── btps-client-app/ an earlier client example, not yet updated for 1.1
222
+ ```
223
+
224
+ Where new code goes, and what it is called, is set out in
225
+ [AGENTS.md](AGENTS.md).
226
+
227
+ ## Implementing BTPS in another language
228
+
229
+ BTPS is a protocol, not this SDK. The
230
+ [golden vectors](test/vectors) are the test of any implementation: addresses,
231
+ every document type and its limits, signed and encrypted artifacts exactly as
232
+ they travel, and the canonical forms they are signed over. An implementation
233
+ in any language that passes them accepts, refuses and produces exactly what
234
+ this one does.
235
+
236
+ ## Quality
237
+
238
+ Every pull request must pass:
239
+
240
+ | Check | What it runs |
241
+ | ------------- | ----------------------------------------------------------------------------------- |
242
+ | `ci/test` | the unit suite, with a coverage gate of 90% of lines |
243
+ | `ci/e2e` | end-to-end journeys between real servers over TLS |
244
+ | `ci/security` | forged, altered, replayed and flooding artifacts, and probing for hidden state |
245
+ | `ci/vectors` | the golden vectors on Node and WebCrypto, and against the SDK |
246
+ | `ci/docs` | the documentation site, which fails on any broken link |
247
+ | packaging | the packed tarball installs and imports, and the example NestJS app builds and runs |
248
+
249
+ ## Security
250
+
251
+ Please report a vulnerability privately, through
252
+ [GitHub's private vulnerability reporting](https://github.com/openbtps/btps-node/security/advisories/new),
253
+ not in a public issue. See [SECURITY.md](SECURITY.md).
254
+
255
+ ## Contributing
256
+
257
+ Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md)
258
+ for setup and the checks to run before opening a pull request.
259
+
260
+ ## License
261
+
262
+ [Apache License 2.0](LICENSE). Copyright 2025 Bhupendra Tamang.
@@ -0,0 +1,20 @@
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 { BtpsClient } from './btpsClient.js';
8
+ import type { BTPAgentOptions, BTPClientResponse, BtpsAgentCommandOptions, BtpsAgentCommandParams, BtpsAgentDoc } from './types/index.js';
9
+ import type { BTPDocType, AgentAction } from '../server/index.js';
10
+ import type { BTPCryptoResponse } from '../core/crypto/types.js';
11
+ export declare class BtpsAgent extends BtpsClient {
12
+ private agentId;
13
+ private readonly signingKey;
14
+ private readonly decryptionKey?;
15
+ constructor(agentOptions: BTPAgentOptions);
16
+ protected getAgentArtifact(commandParams: BtpsAgentCommandParams): Promise<BTPCryptoResponse<BTPDocType>>;
17
+ protected buildTransportArtifact(commandParams: BtpsAgentCommandParams): Promise<BTPCryptoResponse<BTPDocType>>;
18
+ command(actionType: AgentAction, identity: string, document?: BtpsAgentDoc, options?: BtpsAgentCommandOptions, timeoutMs?: number): Promise<BTPClientResponse>;
19
+ destroy(soft?: boolean): void;
20
+ }