@cryptpays/sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/LICENSE +21 -0
  3. package/README.md +194 -2
  4. package/SECURITY.md +42 -0
  5. package/dist/cjs/callback.js +160 -0
  6. package/dist/cjs/callback.js.map +1 -0
  7. package/dist/cjs/client.js +92 -0
  8. package/dist/cjs/client.js.map +1 -0
  9. package/dist/cjs/config.js +95 -0
  10. package/dist/cjs/config.js.map +1 -0
  11. package/dist/cjs/errors.js +60 -0
  12. package/dist/cjs/errors.js.map +1 -0
  13. package/dist/cjs/index.js +27 -0
  14. package/dist/cjs/index.js.map +1 -0
  15. package/dist/cjs/package.json +1 -0
  16. package/dist/cjs/parsers.js +540 -0
  17. package/dist/cjs/parsers.js.map +1 -0
  18. package/dist/cjs/transport.js +178 -0
  19. package/dist/cjs/transport.js.map +1 -0
  20. package/dist/cjs/types.js +18 -0
  21. package/dist/cjs/types.js.map +1 -0
  22. package/dist/cjs/validation.js +139 -0
  23. package/dist/cjs/validation.js.map +1 -0
  24. package/dist/esm/callback.d.ts +43 -0
  25. package/dist/esm/callback.d.ts.map +1 -0
  26. package/dist/esm/callback.js +155 -0
  27. package/dist/esm/callback.js.map +1 -0
  28. package/dist/esm/client.d.ts +16 -0
  29. package/dist/esm/client.d.ts.map +1 -0
  30. package/dist/esm/client.js +88 -0
  31. package/dist/esm/client.js.map +1 -0
  32. package/dist/esm/config.d.ts +35 -0
  33. package/dist/esm/config.d.ts.map +1 -0
  34. package/dist/esm/config.js +90 -0
  35. package/dist/esm/config.js.map +1 -0
  36. package/dist/esm/errors.d.ts +32 -0
  37. package/dist/esm/errors.d.ts.map +1 -0
  38. package/dist/esm/errors.js +46 -0
  39. package/dist/esm/errors.js.map +1 -0
  40. package/dist/esm/index.d.ts +9 -0
  41. package/dist/esm/index.d.ts.map +1 -0
  42. package/dist/esm/index.js +6 -0
  43. package/dist/esm/index.js.map +1 -0
  44. package/dist/esm/parsers.d.ts +21 -0
  45. package/dist/esm/parsers.d.ts.map +1 -0
  46. package/dist/esm/parsers.js +529 -0
  47. package/dist/esm/parsers.js.map +1 -0
  48. package/dist/esm/transport.d.ts +14 -0
  49. package/dist/esm/transport.d.ts.map +1 -0
  50. package/dist/esm/transport.js +174 -0
  51. package/dist/esm/transport.js.map +1 -0
  52. package/dist/esm/types.d.ts +138 -0
  53. package/dist/esm/types.d.ts.map +1 -0
  54. package/dist/esm/types.js +15 -0
  55. package/dist/esm/types.js.map +1 -0
  56. package/dist/esm/validation.d.ts +19 -0
  57. package/dist/esm/validation.d.ts.map +1 -0
  58. package/dist/esm/validation.js +121 -0
  59. package/dist/esm/validation.js.map +1 -0
  60. package/docs/callback-verification.md +95 -0
  61. package/docs/express.md +120 -0
  62. package/docs/fastify.md +80 -0
  63. package/docs/javascript-quick-start.md +41 -0
  64. package/docs/qr-code.md +31 -0
  65. package/docs/transactional-processing.md +92 -0
  66. package/docs/typescript-quick-start.md +53 -0
  67. package/package.json +66 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,42 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format follows Keep a Changelog, and releases use Semantic Versioning.
6
+
7
+ ## [0.1.0] - 2026-12-01
8
+
9
+ ### Added
10
+
11
+ - Add authenticated typed parsing for JSON POST, form POST, and GET callbacks.
12
+ - Add typed callback lifecycle values with `isPending()` and `isConfirmed()` helpers.
13
+ - Add exact-decimal pricing-tier selection without JavaScript number conversion.
14
+ - Adopt the PHP SDK's synthetic language-neutral API and signed callback conformance fixture.
15
+ - Add complete JavaScript, TypeScript, Express, Fastify, transactional processing, and optional address-only QR guidance.
16
+ - Add ESLint, Prettier, declaration validation, and enforced coverage checks as development-only tooling.
17
+ - Add a TypeScript-first public Merchant API client with injectable Fetch API transport and zero runtime dependencies.
18
+ - Add ESM, CommonJS, and TypeScript declaration builds for maintained Node.js 22, 24, and 26 releases.
19
+ - Add typed currency catalog, currency information, pricing, payment creation, callback public key, and server-side payment-log responses.
20
+ - Add exact returned payout-address and callback-identity validation.
21
+ - Add decimal-string validation for monetary and percentage fields and preservation of additive response fields.
22
+ - Add explicit bounded retries for safe reads, disabled by default and prohibited for payment creation.
23
+ - Add RSA-SHA256 callback verification over exact raw request bytes with an inclusive 300-second freshness window.
24
+
25
+ ### Changed
26
+
27
+ - Align strict callback transport validation, required fields, timestamps, signatures, and RSA public-key handling with the published PHP SDK contract.
28
+ - Parse integer and strict HTTP-date `Retry-After` values for bounded safe-read retries.
29
+ - Sanitize printable API exceptions while retaining structured server details through explicit properties.
30
+ - Move the supported runtime matrix to maintained Node.js 22, 24, and 26 releases; Node.js 20 is end-of-life.
31
+
32
+ ### Security
33
+
34
+ - Reject private, encrypted-private, non-RSA, and malformed callback key material before it can be retained or exposed by `CallbackPublicKey`.
35
+ - Reject mixed public/private PEM input, ambiguous callback parameters, duplicate JSON fields, malformed encoding, and conflicting authenticated query/body fields.
36
+
37
+ ### Tests
38
+
39
+ - Add synthetic SPKI and PKCS#1 RSA public-key acceptance tests and private-key boundary regression coverage.
40
+ - Add callback transport, lifecycle, decimal boundary, payment identity, Retry-After, and cross-language conformance regression coverage.
41
+ - Validate backend-derived and shared synthetic callback signature vectors, mocked HTTP behavior, and isolated package consumers.
42
+ - Add minimal-permission CI for Node.js 22, 24, and 26 with frozen Yarn installs, dependency audits, coverage enforcement, and release-archive validation.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CryptPays
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,195 @@
1
- # Temporary Holding Version
1
+ # CryptPays Node.js / TypeScript SDK
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
+ Official server-side client for the public CryptPays Merchant API. Version `0.1.0` is an initial, pre-stable release.
4
+
5
+ The SDK provides currency discovery, currency information, payment-address creation, public pricing, callback public-key retrieval, server-side payment logs, and RSA-SHA256 callback verification. It contains no wallet keys, blockchain signing, payout logic, Admin APIs, private Node APIs, telemetry, or production credentials.
6
+
7
+ ## Requirements
8
+
9
+ - Node.js 22, 24, or 26 while those release lines remain maintained by Node.js
10
+ - Yarn 1.x for repository development
11
+ - The built-in Fetch API or a compatible injected implementation
12
+
13
+ The package is TypeScript-first and ships ESM, CommonJS, and declaration files with no runtime dependencies. Node.js 20 is not supported because it is end-of-life.
14
+
15
+ ## Installation
16
+
17
+ The npm package has not been published yet. After publication, install it with:
18
+
19
+ ```bash
20
+ yarn add @cryptpays/sdk@^0.1.0
21
+ ```
22
+
23
+ Contributors can validate an unpublished checkout by creating a local archive:
24
+
25
+ ```bash
26
+ yarn install --frozen-lockfile
27
+ yarn pack
28
+ # From a separate local consumer project:
29
+ yarn add ./cryptpays-sdk-v0.1.0.tgz
30
+ ```
31
+
32
+ ## Quick start
33
+
34
+ Complete minimal examples are available for [JavaScript](docs/javascript-quick-start.md) and [TypeScript](docs/typescript-quick-start.md).
35
+
36
+ Basic initialization requires no API key or transport setup:
37
+
38
+ ```ts
39
+ import { CryptPaysClient } from '@cryptpays/sdk';
40
+
41
+ const client = new CryptPaysClient();
42
+ ```
43
+
44
+ Timeout and safe-read retry policies remain explicitly configurable:
45
+
46
+ ```ts
47
+ import { CryptPaysClient, RetryPolicy } from '@cryptpays/sdk';
48
+
49
+ const client = new CryptPaysClient({
50
+ requestTimeoutMs: 15_000,
51
+ // Retries remain opt-in and apply only to safe GET methods.
52
+ retryPolicy: RetryPolicy.safeReads({ maxAttempts: 3 }),
53
+ });
54
+ ```
55
+
56
+ The Merchant API is keyless. Do not invent or send an API key. HTTPS is required by default; `allowInsecureHttp` exists only for isolated local tests using a custom base URL. An injected `fetch` implementation is supported for server runtimes, policy enforcement, and testing.
57
+
58
+ Safe-read retries default to HTTP `429`, `502`, `503`, and `504` plus transport failures. Exponential delays and `Retry-After` are honored up to the policy's explicit `maximumDelayMs`; payment creation never enters this retry path.
59
+
60
+ ## Discover currencies and pricing
61
+
62
+ ```ts
63
+ const currencies = await client.listCurrencies();
64
+ const usdt = currencies.bep20_usdt;
65
+
66
+ const info = await client.getCurrencyInfo('bep20_usdt');
67
+ console.log(info.minimumTransaction);
68
+
69
+ const pricing = await client.getPricing();
70
+ const tier = pricing.tierForVolume('10000.000000000000000001');
71
+ console.log(tier?.feePercent);
72
+ ```
73
+
74
+ Currency availability is runtime data. Do not hardcode a network or token list. Monetary amounts, minimums, prices, and percentages are validated and returned as decimal strings; never convert them through JavaScript `number` arithmetic. `tierForVolume()` uses exact decimal-string comparison and half-open tier boundaries; it does not calculate or guarantee a commission, network fee, or settlement amount.
75
+
76
+ ## Create or reuse a payment address
77
+
78
+ ```ts
79
+ import { CallbackTransport, PaymentPriority } from '@cryptpays/sdk';
80
+
81
+ const callbackUrl = 'https://merchant.example/cryptpays/callback?order_id=opaque-random-reference';
82
+ const addressOut = '0x1111111111111111111111111111111111111111';
83
+
84
+ const payment = await client.createPayment({
85
+ ticker: 'bep20_usdt',
86
+ callbackUrl,
87
+ addressOut,
88
+ notifyPending: false,
89
+ callbackTransport: CallbackTransport.JsonPost,
90
+ priority: PaymentPriority.Default,
91
+ });
92
+
93
+ console.log(payment.addressIn, payment.minimumTransactionCoin);
94
+ ```
95
+
96
+ Creation always uses JSON `POST`; callback delivery defaults to JSON `POST`. The SDK compares the returned `address_out` and `callback_url` byte-for-byte with the request and fails closed on a mismatch.
97
+
98
+ Payment creation is never automatically retried. After an uncertain transport outcome, reconcile deliberately with the same exact request identity. The backend may return the existing compatible address and its stored immutable configuration; the SDK does not cache or mutate this behavior.
99
+
100
+ CryptPays creation does not register an order amount, expiration, refund, cancellation, underpayment, or overpayment policy. Do not infer those behaviors from this SDK.
101
+
102
+ ## Callback verification
103
+
104
+ Fetch the public key outside the callback hot path and cache it with an application-managed bounded TTL:
105
+
106
+ ```ts
107
+ import { CallbackVerifier } from '@cryptpays/sdk';
108
+
109
+ const publicKey = await client.getCallbackPublicKey();
110
+ const verifier = new CallbackVerifier(publicKey);
111
+
112
+ // Obtain these values directly from your HTTP framework before parsing the body.
113
+ const verified = verifier.verify({
114
+ method: rawMethod,
115
+ host: externallyConfiguredHostname,
116
+ requestTarget: exactPathAndQuery,
117
+ rawBody: exactBodyBuffer,
118
+ timestamp: timestampHeader,
119
+ signature: signatureHeader,
120
+ });
121
+ // Select the configured transport explicitly after verification.
122
+ const payload = verified.jsonPayload(); // Recommended transport.
123
+
124
+ if (payload.isConfirmed()) {
125
+ // Validate order identity, ticker, destination, transaction and amount,
126
+ // then fulfill this UUID exactly once in durable storage.
127
+ }
128
+ ```
129
+
130
+ `CallbackPublicKey` accepts RSA public-key PEM material only. Private, encrypted-private, non-RSA, and malformed keys are rejected with a generic error before the supplied material is retained or exposed.
131
+
132
+ The verified result supports all gateway callback transports:
133
+
134
+ ```ts
135
+ import { CallbackTransport } from '@cryptpays/sdk';
136
+
137
+ verified.jsonPayload(); // JSON POST (recommended)
138
+ verified.formPayload(); // application/x-www-form-urlencoded POST
139
+ verified.getPayload(); // GET query parameters with an empty body
140
+ verified.payload(CallbackTransport.JsonPost); // Explicit generic form
141
+ ```
142
+
143
+ Parsing uses only the authenticated raw body and exact request target. Duplicate parameters, duplicate top-level JSON keys, malformed percent encoding, conflicting query/body fields, invalid integers, and inconsistent lifecycle fields fail closed. Pending and confirmed callbacks intentionally share one UUID; use `payload.isPending()`, `payload.isConfirmed()`, and `payload.lifecycle` to implement application-owned transactional idempotency.
144
+
145
+ Do not derive the signed hostname from an untrusted `Host` or forwarded-host header. See [Callback verification](docs/callback-verification.md), [transactional processing](docs/transactional-processing.md), [Express](docs/express.md), and [Fastify](docs/fastify.md).
146
+
147
+ For checkout presentation, the optional [address-only QR recipe](docs/qr-code.md) keeps QR generation in the merchant application and adds no SDK dependency.
148
+
149
+ ## Payment logs
150
+
151
+ ```ts
152
+ const logs = await client.getPaymentLogs('bep20_usdt', callbackUrl);
153
+ ```
154
+
155
+ `getPaymentLogs()` is for trusted server-side reconciliation only. The complete callback URL is capability-sensitive, and the response may contain addresses, transaction identifiers, delivery destinations, and merchant response bodies. Never expose this method to browsers or mobile clients, and redact its URL and response from logs and tracing.
156
+
157
+ ## Error handling
158
+
159
+ ```ts
160
+ import { ApiError, TimeoutError, TransportError } from '@cryptpays/sdk';
161
+
162
+ try {
163
+ await client.getPricing();
164
+ } catch (error) {
165
+ if (error instanceof ApiError) {
166
+ console.error(error.statusCode, error.apiCode, error.error);
167
+ } else if (error instanceof TimeoutError) {
168
+ console.error('CryptPays request timed out');
169
+ } else if (error instanceof TransportError) {
170
+ console.error('CryptPays transport failed');
171
+ }
172
+ }
173
+ ```
174
+
175
+ SDK-generated transport and HTTP exception messages omit request URLs, bodies, and server-supplied error text. `ApiError` exposes structured `error`, `apiMessage`, and `validationErrors` properties only for deliberate application access. Your injected `fetch` wrapper may have separate logging or telemetry; configure it to redact callback URLs and payloads.
176
+
177
+ ## Development
178
+
179
+ ```bash
180
+ yarn install --frozen-lockfile
181
+ yarn typecheck
182
+ yarn lint
183
+ yarn format:check
184
+ yarn test
185
+ yarn test:coverage
186
+ yarn build
187
+ yarn test:package
188
+ yarn audit
189
+ ```
190
+
191
+ Tests mock every HTTP request and use the PHP SDK's byte-identical synthetic language-neutral conformance fixture, including deterministic signed JSON, form, and GET vectors. They never create a real payment or call a live CryptPays endpoint. `test:package` validates the release manifest, rejects private-key material and development files, and tests ESM, CommonJS, and declarations from an isolated local installation.
192
+
193
+ ## License
194
+
195
+ Released under the [MIT License](LICENSE).
package/SECURITY.md ADDED
@@ -0,0 +1,42 @@
1
+ # Security policy
2
+
3
+ ## Supported versions
4
+
5
+ The `0.1.x` line is pre-stable and receives security fixes while it is the current development line. A formal long-term support policy will be defined before `1.0.0`.
6
+
7
+ ## Reporting a vulnerability
8
+
9
+ Report suspected vulnerabilities privately to `security@cryptpays.com`. Do not open a public issue containing exploit details, callback URLs, merchant data, transaction records, credentials, wallet material, or production configuration. CryptPays does not promise a bug bounty or a guaranteed response time.
10
+
11
+ Include the affected SDK version, a minimal local reproduction, expected impact, and any suggested mitigation. Use synthetic values and redact capability-bearing callback URLs.
12
+
13
+ ## Security boundaries
14
+
15
+ This package:
16
+
17
+ - calls only the verified public Merchant API surface;
18
+ - contains no authentication secrets, production credentials, private keys, mnemonics, or blockchain signing;
19
+ - never calls Admin, provider-webhook, private Node, wallet, broadcast, payout, or infrastructure APIs;
20
+ - does not automatically retry payment creation;
21
+ - validates the exact returned payout address and callback identity;
22
+ - treats every monetary value as a decimal string;
23
+ - verifies callbacks over the exact raw method, hostname, request target, body, and timestamp;
24
+ - parses JSON, form, and GET callback fields only after verification and rejects ambiguous authenticated input;
25
+ - accepts only supported RSA public-key material for callback verification;
26
+ - disables redirects and retries by default;
27
+ - does not log requests, responses, callback URLs, or callback payloads;
28
+ - performs no telemetry or automatic fulfillment.
29
+
30
+ Applications remain responsible for secret-safe logging, trusted proxy configuration, durable callback idempotency, order validation, authorization around payment logs, dependency updates, public-key caching, and returning HTTP 200 only after successful durable processing. Use a database lock or equivalent atomic transition plus a unique fulfillment constraint; timestamp freshness alone is not replay protection for business effects.
31
+
32
+ Treat `baseUrl`, payment callback URLs, and payout addresses as trusted server-side configuration or validated merchant data, never arbitrary end-user input. A custom `baseUrl` directs the injected fetch implementation to that host. The SDK never dereferences callback URLs; CryptPays also applies server-side callback-destination validation.
33
+
34
+ An injected fetch implementation may have its own logging, tracing, proxy, redirect, or retry behavior. The SDK requests `redirect: "manual"`, but applications must ensure the implementation honors it and redacts request URLs, query strings, and bodies. Payment-log queries contain the complete capability-bearing callback URL.
35
+
36
+ ## Callback URL confidentiality
37
+
38
+ The callback URL is both a payment identity and the lookup input for payment logs. Generate a high-entropy, unguessable per-order reference. Keep the complete URL server-side, redact it from logs and traces, and never expose payment-log lookup through an unauthenticated browser or mobile endpoint.
39
+
40
+ ## Dependency and release integrity
41
+
42
+ Review Yarn dependency advisories, the packed-file manifest, and the release diff before tagging. Publication, npm registration, signing, provenance, and the included MIT license remain subject to project-owner approval. This repository contains no release credentials or automated publishing configuration.
@@ -0,0 +1,160 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CallbackVerifier = exports.CallbackPublicKey = void 0;
4
+ const node_buffer_1 = require("node:buffer");
5
+ const node_crypto_1 = require("node:crypto");
6
+ const node_net_1 = require("node:net");
7
+ const errors_js_1 = require("./errors.js");
8
+ const parsers_js_1 = require("./parsers.js");
9
+ const types_js_1 = require("./types.js");
10
+ const publicKeys = new WeakMap();
11
+ class CallbackPublicKey {
12
+ pem;
13
+ constructor(pem) {
14
+ if (typeof pem !== 'string' ||
15
+ !/^-----BEGIN (PUBLIC KEY|RSA PUBLIC KEY)-----\r?\n(?:[A-Za-z0-9+/=]+\r?\n)+-----END \1-----(?:\r?\n)?$/u.test(pem)) {
16
+ throw new errors_js_1.CallbackVerificationError('The callback verification key must be a supported RSA public key.');
17
+ }
18
+ let key;
19
+ try {
20
+ key = (0, node_crypto_1.createPublicKey)(pem);
21
+ }
22
+ catch {
23
+ throw new errors_js_1.CallbackVerificationError('The callback verification key must be a supported RSA public key.');
24
+ }
25
+ if (key.type !== 'public' || key.asymmetricKeyType !== 'rsa') {
26
+ throw new errors_js_1.CallbackVerificationError('The callback verification key must be a supported RSA public key.');
27
+ }
28
+ this.pem = pem;
29
+ publicKeys.set(this, key);
30
+ }
31
+ }
32
+ exports.CallbackPublicKey = CallbackPublicKey;
33
+ class VerifiedCallbackResult {
34
+ timestamp;
35
+ method;
36
+ host;
37
+ requestTarget;
38
+ #rawBody;
39
+ #canonicalRequest;
40
+ constructor(timestamp, method, host, requestTarget, rawBody, canonicalRequest) {
41
+ this.timestamp = timestamp;
42
+ this.method = method;
43
+ this.host = host;
44
+ this.requestTarget = requestTarget;
45
+ this.#rawBody = node_buffer_1.Buffer.from(rawBody);
46
+ this.#canonicalRequest = node_buffer_1.Buffer.from(canonicalRequest);
47
+ }
48
+ get canonicalRequest() {
49
+ return node_buffer_1.Buffer.from(this.#canonicalRequest);
50
+ }
51
+ rawBody() {
52
+ return node_buffer_1.Buffer.from(this.#rawBody);
53
+ }
54
+ jsonPayload() {
55
+ return this.payload(types_js_1.CallbackTransport.JsonPost);
56
+ }
57
+ formPayload() {
58
+ return this.payload(types_js_1.CallbackTransport.FormPost);
59
+ }
60
+ getPayload() {
61
+ return this.payload(types_js_1.CallbackTransport.Get);
62
+ }
63
+ payload(transport) {
64
+ return (0, parsers_js_1.parseVerifiedCallbackPayload)(this.method, this.requestTarget, this.#rawBody, transport);
65
+ }
66
+ }
67
+ class CallbackVerifier {
68
+ publicKey;
69
+ #freshnessWindowSeconds;
70
+ #clock;
71
+ constructor(publicKey, options = {}) {
72
+ this.publicKey = publicKey;
73
+ const window = options.freshnessWindowSeconds ?? 300;
74
+ if (!Number.isInteger(window) || window < 0 || window > 300) {
75
+ throw new errors_js_1.CallbackVerificationError('The callback freshness window must be an integer from 0 to 300 seconds.');
76
+ }
77
+ this.#freshnessWindowSeconds = window;
78
+ this.#clock = options.clock ?? (() => Math.floor(Date.now() / 1_000));
79
+ }
80
+ verify(request) {
81
+ if (!node_buffer_1.Buffer.isBuffer(request.rawBody)) {
82
+ throw new errors_js_1.CallbackVerificationError('The callback body must be the exact raw request Buffer.');
83
+ }
84
+ const method = this.normalizeMethod(request.method);
85
+ const host = this.normalizeHost(request.host);
86
+ this.assertRequestTarget(request.requestTarget);
87
+ const timestamp = this.validateTimestamp(request.timestamp);
88
+ const signature = this.decodeSignature(request.signature);
89
+ const rawBody = node_buffer_1.Buffer.from(request.rawBody);
90
+ const canonicalRequest = node_buffer_1.Buffer.concat([
91
+ node_buffer_1.Buffer.from(`v1\n${request.timestamp}\n${method}\n${host}\n${request.requestTarget}\n`, 'utf8'),
92
+ rawBody,
93
+ ]);
94
+ const key = publicKeys.get(this.publicKey);
95
+ if (key === undefined || !(0, node_crypto_1.verify)('RSA-SHA256', canonicalRequest, key, signature)) {
96
+ throw new errors_js_1.CallbackVerificationError('The callback signature is invalid.');
97
+ }
98
+ return new VerifiedCallbackResult(timestamp.toString(), method, host, request.requestTarget, rawBody, canonicalRequest);
99
+ }
100
+ validateTimestamp(rawTimestamp) {
101
+ if (typeof rawTimestamp !== 'string' || rawTimestamp.length > 19 || !/^(?:0|[1-9]\d*)$/u.test(rawTimestamp)) {
102
+ throw new errors_js_1.CallbackVerificationError('The callback timestamp is malformed.');
103
+ }
104
+ const timestamp = BigInt(rawTimestamp);
105
+ const now = this.#clock();
106
+ if (!Number.isSafeInteger(now) || now < 0) {
107
+ throw new errors_js_1.CallbackVerificationError('The callback verification clock returned an invalid timestamp.');
108
+ }
109
+ const difference = timestamp >= BigInt(now) ? timestamp - BigInt(now) : BigInt(now) - timestamp;
110
+ if (difference > BigInt(this.#freshnessWindowSeconds)) {
111
+ throw new errors_js_1.CallbackVerificationError('The callback timestamp is outside the accepted freshness window.');
112
+ }
113
+ return timestamp;
114
+ }
115
+ decodeSignature(rawSignature) {
116
+ if (typeof rawSignature !== 'string' ||
117
+ rawSignature === '' ||
118
+ rawSignature.length % 4 !== 0 ||
119
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(rawSignature)) {
120
+ throw new errors_js_1.CallbackVerificationError('The callback signature is not strict Base64.');
121
+ }
122
+ const decoded = node_buffer_1.Buffer.from(rawSignature, 'base64');
123
+ if (decoded.length === 0 || decoded.toString('base64') !== rawSignature) {
124
+ throw new errors_js_1.CallbackVerificationError('The callback signature is not strict Base64.');
125
+ }
126
+ return decoded;
127
+ }
128
+ normalizeMethod(method) {
129
+ if (typeof method !== 'string' || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u.test(method)) {
130
+ throw new errors_js_1.CallbackVerificationError('The callback method is malformed.');
131
+ }
132
+ return method.toUpperCase();
133
+ }
134
+ normalizeHost(host) {
135
+ if (typeof host !== 'string' || host === '' || host !== host.trim() || /[\s/@?#]/u.test(host)) {
136
+ throw new errors_js_1.CallbackVerificationError('The callback hostname is malformed.');
137
+ }
138
+ const normalized = host.toLowerCase();
139
+ if ((0, node_net_1.isIP)(normalized) === 0) {
140
+ if (normalized.length > 253 ||
141
+ normalized.includes(':') ||
142
+ !normalized
143
+ .split('.')
144
+ .every((label) => label.length >= 1 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(label))) {
145
+ throw new errors_js_1.CallbackVerificationError('The callback hostname is malformed.');
146
+ }
147
+ }
148
+ return normalized;
149
+ }
150
+ assertRequestTarget(requestTarget) {
151
+ if (typeof requestTarget !== 'string' ||
152
+ !requestTarget.startsWith('/') ||
153
+ requestTarget.includes('#') ||
154
+ /[\r\n\0]/u.test(requestTarget)) {
155
+ throw new errors_js_1.CallbackVerificationError('The callback request target is malformed.');
156
+ }
157
+ }
158
+ }
159
+ exports.CallbackVerifier = CallbackVerifier;
160
+ //# sourceMappingURL=callback.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"callback.js","sourceRoot":"","sources":["../../src/callback.ts"],"names":[],"mappings":";;;AAAA,6CAAqC;AACrC,6CAAyE;AAEzE,uCAAgC;AAChC,2CAAwD;AACxD,6CAA4D;AAC5D,yCAA+C;AAiB/C,MAAM,UAAU,GAAG,IAAI,OAAO,EAAgC,CAAC;AAE/D,MAAa,iBAAiB;IACZ,GAAG,CAAS;IAE5B,YAAmB,GAAW;QAC5B,IACE,OAAO,GAAG,KAAK,QAAQ;YACvB,CAAC,wGAAwG,CAAC,IAAI,CAC5G,GAAG,CACJ,EACD,CAAC;YACD,MAAM,IAAI,qCAAyB,CAAC,mEAAmE,CAAC,CAAC;QAC3G,CAAC;QAED,IAAI,GAAc,CAAC;QACnB,IAAI,CAAC;YACH,GAAG,GAAG,IAAA,6BAAe,EAAC,GAAG,CAAC,CAAC;QAC7B,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,qCAAyB,CAAC,mEAAmE,CAAC,CAAC;QAC3G,CAAC;QAED,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,IAAI,GAAG,CAAC,iBAAiB,KAAK,KAAK,EAAE,CAAC;YAC7D,MAAM,IAAI,qCAAyB,CAAC,mEAAmE,CAAC,CAAC;QAC3G,CAAC;QAED,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,UAAU,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;IAC5B,CAAC;CACF;AA3BD,8CA2BC;AAeD,MAAM,sBAAsB;IAKR;IACA;IACA;IACA;IAPT,QAAQ,CAAS;IACjB,iBAAiB,CAAS;IAEnC,YACkB,SAAiB,EACjB,MAAc,EACd,IAAY,EACZ,aAAqB,EACrC,OAAe,EACf,gBAAwB;QALR,cAAS,GAAT,SAAS,CAAQ;QACjB,WAAM,GAAN,MAAM,CAAQ;QACd,SAAI,GAAJ,IAAI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C,IAAI,KAAK,CAAC,MAAM,IAAI,EAAE,IAAI,oCAAoC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAChH,CAAC;gBACD,MAAM,IAAI,qCAAyB,CAAC,qCAAqC,CAAC,CAAC;YAC7E,CAAC;QACH,CAAC;QACD,OAAO,UAAU,CAAC;IACpB,CAAC;IAEO,mBAAmB,CAAC,aAAqB;QAC/C,IACE,OAAO,aAAa,KAAK,QAAQ;YACjC,CAAC,aAAa,CAAC,UAAU,CAAC,GAAG,CAAC;YAC9B,aAAa,CAAC,QAAQ,CAAC,GAAG,CAAC;YAC3B,WAAW,CAAC,IAAI,CAAC,aAAa,CAAC,EAC/B,CAAC;YACD,MAAM,IAAI,qCAAyB,CAAC,2CAA2C,CAAC,CAAC;QACnF,CAAC;IACH,CAAC;CACF;AAxHD,4CAwHC"}
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CryptPaysClient = void 0;
4
+ const node_buffer_1 = require("node:buffer");
5
+ const node_crypto_1 = require("node:crypto");
6
+ const config_js_1 = require("./config.js");
7
+ const errors_js_1 = require("./errors.js");
8
+ const parsers_js_1 = require("./parsers.js");
9
+ const transport_js_1 = require("./transport.js");
10
+ const types_js_1 = require("./types.js");
11
+ const validation_js_1 = require("./validation.js");
12
+ const callback_js_1 = require("./callback.js");
13
+ const callbackTransports = new Set(Object.values(types_js_1.CallbackTransport));
14
+ const priorities = new Set(Object.values(types_js_1.PaymentPriority));
15
+ class CryptPaysClient {
16
+ #transport;
17
+ constructor(options = {}) {
18
+ this.#transport = new transport_js_1.ApiTransport((0, config_js_1.resolveClientConfig)(options));
19
+ }
20
+ async listCurrencies() {
21
+ return (0, parsers_js_1.parseCurrencyCatalog)(await this.#transport.getJson('cryptocurrencies'));
22
+ }
23
+ async getCurrencyInfo(ticker) {
24
+ (0, validation_js_1.assertTicker)(ticker);
25
+ const result = (0, parsers_js_1.parseCurrencyInfo)(await this.#transport.getJson(`${encodeURIComponent(ticker)}/info`));
26
+ if (!this.safeEqual(result.ticker, ticker)) {
27
+ throw new errors_js_1.MalformedResponseError('The returned currency ticker does not match the request.');
28
+ }
29
+ return result;
30
+ }
31
+ async createPayment(request) {
32
+ this.validatePaymentRequest(request);
33
+ const result = (0, parsers_js_1.parsePayment)(await this.#transport.postJsonWithoutRetry(`${encodeURIComponent(request.ticker)}/create`, (0, parsers_js_1.createPaymentPayload)(request)));
34
+ if (!this.safeEqual(result.addressOut, request.addressOut)) {
35
+ throw new errors_js_1.MalformedResponseError('The returned payment destination does not match the request.');
36
+ }
37
+ if (!this.safeEqual(result.callbackUrl, request.callbackUrl)) {
38
+ throw new errors_js_1.MalformedResponseError('The returned payment callback does not match the request.');
39
+ }
40
+ return result;
41
+ }
42
+ async getPricing() {
43
+ return (0, parsers_js_1.parsePricingSchedule)(await this.#transport.getJson('pricing'));
44
+ }
45
+ async getCallbackPublicKey() {
46
+ return new callback_js_1.CallbackPublicKey(await this.#transport.getText('pubkey'));
47
+ }
48
+ async getPaymentLogs(ticker, callbackUrl) {
49
+ (0, validation_js_1.assertTicker)(ticker);
50
+ (0, validation_js_1.assertCallbackUrl)(callbackUrl);
51
+ const result = (0, parsers_js_1.parsePaymentLogs)(await this.#transport.getJson(`${encodeURIComponent(ticker)}/logs?callback=${(0, validation_js_1.rfc3986Encode)(callbackUrl)}`));
52
+ if (!this.safeEqual(result.callbackUrl, callbackUrl)) {
53
+ throw new errors_js_1.MalformedResponseError('The returned payment-log callback does not match the request.');
54
+ }
55
+ return result;
56
+ }
57
+ validatePaymentRequest(request) {
58
+ if (request === null || typeof request !== 'object') {
59
+ throw new errors_js_1.InvalidArgumentError('The payment request must be an object.');
60
+ }
61
+ (0, validation_js_1.assertTicker)(request.ticker);
62
+ (0, validation_js_1.assertCallbackUrl)(request.callbackUrl);
63
+ if (typeof request.addressOut !== 'string' ||
64
+ request.addressOut === '' ||
65
+ node_buffer_1.Buffer.byteLength(request.addressOut, 'utf8') > 500) {
66
+ throw new errors_js_1.InvalidArgumentError('The destination address must be a non-empty string of at most 500 bytes.');
67
+ }
68
+ if (request.confirmations !== undefined &&
69
+ (!Number.isSafeInteger(request.confirmations) || request.confirmations < 1)) {
70
+ throw new errors_js_1.InvalidArgumentError('Confirmations must be a positive integer.');
71
+ }
72
+ if (request.callbackTransport !== undefined && !callbackTransports.has(request.callbackTransport)) {
73
+ throw new errors_js_1.InvalidArgumentError('The callback transport is not supported.');
74
+ }
75
+ if (request.priority !== undefined && !priorities.has(request.priority)) {
76
+ throw new errors_js_1.InvalidArgumentError('The payment priority is not supported.');
77
+ }
78
+ if (request.notifyPending !== undefined && typeof request.notifyPending !== 'boolean') {
79
+ throw new errors_js_1.InvalidArgumentError('notifyPending must be a boolean.');
80
+ }
81
+ if (request.convertToUsdt !== undefined && typeof request.convertToUsdt !== 'boolean') {
82
+ throw new errors_js_1.InvalidArgumentError('convertToUsdt must be a boolean.');
83
+ }
84
+ }
85
+ safeEqual(left, right) {
86
+ const leftBytes = node_buffer_1.Buffer.from(left, 'utf8');
87
+ const rightBytes = node_buffer_1.Buffer.from(right, 'utf8');
88
+ return leftBytes.length === rightBytes.length && (0, node_crypto_1.timingSafeEqual)(leftBytes, rightBytes);
89
+ }
90
+ }
91
+ exports.CryptPaysClient = CryptPaysClient;
92
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/client.ts"],"names":[],"mappings":";;;AAAA,6CAAqC;AACrC,6CAA8C;AAC9C,2CAAkD;AAElD,2CAA2E;AAC3E,6CAOsB;AACtB,iDAA8C;AAC9C,yCAAgE;AAShE,mDAAiF;AACjF,+CAAkD;AAElD,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAS,MAAM,CAAC,MAAM,CAAC,4BAAiB,CAAC,CAAC,CAAC;AAC7E,MAAM,UAAU,GAAG,IAAI,GAAG,CAAS,MAAM,CAAC,MAAM,CAAC,0BAAe,CAAC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