@cosmosapp/pay_sdk 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cosmos Pay
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 ADDED
@@ -0,0 +1,458 @@
1
+ <div align="center">
2
+
3
+ # ๐Ÿช @cosmosapp/pay_sdk
4
+
5
+ **The object-oriented JavaScript / TypeScript SDK for the [Cosmos Pay](#) Payments API**
6
+
7
+ Stellar **SEP-7 payment intents** ยท **webhooks** ยท **products** ยท **customers** ยท **analytics**
8
+
9
+ [![CI](https://github.com/CosmosPay/CosmosJS_SDK/actions/workflows/ci.yml/badge.svg)](https://github.com/CosmosPay/CosmosJS_SDK/actions/workflows/ci.yml)
10
+ [![npm version](https://img.shields.io/npm/v/@cosmosapp/pay_sdk?style=flat-square&color=7c3aed)](https://www.npmjs.com/package/@cosmosapp/pay_sdk)
11
+ [![npm downloads](https://img.shields.io/npm/dm/@cosmosapp/pay_sdk?style=flat-square&color=7c3aed)](https://www.npmjs.com/package/@cosmosapp/pay_sdk)
12
+ [![types](https://img.shields.io/npm/types/@cosmosapp/pay_sdk?style=flat-square&color=3178c6)](https://www.npmjs.com/package/@cosmosapp/pay_sdk)
13
+ [![node](https://img.shields.io/node/v/@cosmosapp/pay_sdk?style=flat-square&color=339933)](https://nodejs.org)
14
+ [![license](https://img.shields.io/npm/l/@cosmosapp/pay_sdk?style=flat-square&color=22c55e)](./LICENSE)
15
+
16
+ </div>
17
+
18
+ ---
19
+
20
+ Designed in the style of **discord.js**: one atomic `Client`, every resource split into its own
21
+ manager, and rich structure classes that can act on themselves.
22
+
23
+ ```ts
24
+ import { Client } from '@cosmosapp/pay_sdk';
25
+
26
+ // You only bring your API key โ€” the gateway URL and other internals are pre-configured for you.
27
+ const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });
28
+
29
+ const intent = await client.paymentIntents.createPay({ destination: 'G...', amount: '10' });
30
+ console.log(intent.uri); // web+stellar:pay?destination=...
31
+ ```
32
+
33
+ ## โœจ Features
34
+
35
+ - โœ… **TypeScript & JavaScript** โ€” full typings, works in both **CJS** and **ESM**.
36
+ - โœ… **Zero runtime dependencies** โ€” native `fetch` + `node:crypto`, nothing else.
37
+ - โœ… **Atomic, discord.js-style API** โ€” `client.paymentIntents`, `client.webhooks`, โ€ฆ
38
+ - โœ… **Self-acting structures** โ€” `intent.validate()`, `endpoint.rotateSecret()`, `product.deactivate()`.
39
+ - โœ… **Built-in webhook signature verification** + ready-made `http` / Express handlers.
40
+ - โœ… **Resilient by default** โ€” automatic retries, timeouts and structured errors.
41
+
42
+ ## ๐Ÿ“‘ Table of contents
43
+
44
+ - [Installation](#-installation)
45
+ - [Authentication](#-authentication)
46
+ - [Quick start](#-quick-start)
47
+ - [The client at a glance](#-the-client-at-a-glance)
48
+ - [Payment intents](#-payment-intents)
49
+ - [Webhooks](#-webhooks)
50
+ - [Products & customers](#-products--customers)
51
+ - [Analytics & health](#-analytics--health)
52
+ - [Error handling](#-error-handling)
53
+ - [Observability](#-observability)
54
+ - [Configuration reference](#-configuration-reference)
55
+ - [TypeScript](#-typescript)
56
+ - [Running the tests locally](#-running-the-tests-locally)
57
+ - [CI/CD & publishing](#-cicd--publishing)
58
+ - [License](#-license)
59
+
60
+ ## ๐Ÿ“ฆ Installation
61
+
62
+ ```bash
63
+ npm install @cosmosapp/pay_sdk
64
+ # or
65
+ pnpm add @cosmosapp/pay_sdk
66
+ # or
67
+ yarn add @cosmosapp/pay_sdk
68
+ ```
69
+
70
+ Requires **Node.js โ‰ฅ 18** (for the global `fetch`). On older runtimes pass a `fetch` polyfill via the `fetch` option.
71
+
72
+ ## ๐Ÿ”‘ Authentication
73
+
74
+ **You only need your API key.** Everything else โ€” the gateway URL, the API version, and other
75
+ infrastructure details โ€” is part of the SDK's **shared configuration**, maintained by Cosmos Pay
76
+ and filled in for you.
77
+
78
+ ```ts
79
+ const client = new Client({
80
+ apiKey: 'prod_xxx', // or dv_xxx for testnet
81
+ });
82
+ ```
83
+
84
+ The **network** (testnet vs mainnet) is determined by the API key type
85
+ (`dv_` โ†’ testnet, `prod_` โ†’ mainnet) โ€” you don't configure it.
86
+
87
+ <details>
88
+ <summary><b>Shared configuration (advanced)</b></summary>
89
+
90
+ The internal defaults live in `Client.shared` and can be overridden globally (once, at startup) โ€”
91
+ useful for self-hosting or pointing at a staging gateway:
92
+
93
+ ```ts
94
+ import { Client } from '@cosmosapp/pay_sdk';
95
+
96
+ Client.shared.baseURL = 'https://staging.cosmospay.io';
97
+ // every client created afterwards inherits this
98
+ ```
99
+
100
+ Or per-client (rarely needed):
101
+
102
+ ```ts
103
+ const client = new Client({
104
+ apiKey: '...',
105
+ baseURL: 'http://localhost:3000', // override the gateway
106
+ // direct, gateway-bypassing access for local dev:
107
+ gatewaySecret: process.env.APISIX_GATEWAY_SECRET,
108
+ consumerUsername: 'cosmos_demo',
109
+ });
110
+ ```
111
+
112
+ These overrides (`baseURL`, `version`, `gatewaySecret`, `consumerUsername`) are all optional โ€” a
113
+ normal integration never sets them.
114
+
115
+ </details>
116
+
117
+ ## ๐Ÿš€ Quick start
118
+
119
+ ```ts
120
+ import { Client } from '@cosmosapp/pay_sdk';
121
+
122
+ const client = new Client({ apiKey: process.env.COSMOS_PAY_API_KEY });
123
+
124
+ // Create a SEP-7 `pay` intent (no source โ†’ URI + QR)
125
+ const pay = await client.paymentIntents.createPay({
126
+ destination: 'GCALNQQBXAPZ2WIRSDDBMSTAKCUH5SG6U76YBFLQLIXJTF7FE5AX7AOO',
127
+ amount: '120.1234567',
128
+ assetCode: 'USDC',
129
+ assetIssuer: 'GCRCUE2C5TBNIPYHMEP7NK5RWTT2WBSZ75CMARH7GDOHDDCQH3XANFOB',
130
+ msg: 'Order #24',
131
+ });
132
+
133
+ console.log(pay.uri); // web+stellar:pay?destination=...
134
+ console.log(pay.qr); // data:image/png;base64,...
135
+
136
+ // Later, validate a submitted transaction against the intent
137
+ const outcome = await pay.validate('3389e9f0d6b3e3f1c2a1...');
138
+ if (outcome.valid) console.log('Settled!', outcome.status);
139
+ ```
140
+
141
+ ## ๐Ÿงญ The client at a glance
142
+
143
+ | Manager | Resource | Key methods |
144
+ | ------------------------ | --------------------------------- | ----------- |
145
+ | `client.paymentIntents` | Stellar SEP-7 payment intents | `createTx` ยท `createPay` ยท `fetch` ยท `list` ยท `update` ยท `delete` ยท `validate` |
146
+ | `client.webhooks` | Webhook endpoints + deliveries | `create` ยท `list` ยท `fetch` ยท `rotateSecret` ยท `ping` ยท `on(...)` ยท `process` |
147
+ | `client.products` | Products / prices | `create` ยท `list` ยท `fetch` ยท `update` ยท `delete` |
148
+ | `client.customers` | Customers | `create` ยท `list` ยท `fetch` ยท `update` ยท `delete` |
149
+ | `client.analytics` | Read-only metrics & logs | `summary` ยท `balances` ยท `apiLogs` ยท `webhookLogs` |
150
+ | `client.health` | Liveness / readiness probes | `liveness` ยท `readiness` |
151
+
152
+ ## ๐Ÿ’ณ Payment intents
153
+
154
+ ```ts
155
+ // tx intent (source known โ†’ unsigned XDR + tx URI + QR)
156
+ const tx = await client.paymentIntents.createTx({
157
+ source: 'G...PAYER',
158
+ destination: 'G...MERCHANT',
159
+ amount: '25.5',
160
+ memo: '123456789', // optional MEMO_ID (auto-generated otherwise)
161
+ });
162
+ console.log(tx.xdr, tx.uri, tx.qr);
163
+
164
+ // pay intent (no source)
165
+ const pay = await client.paymentIntents.createPay({ destination: 'G...', amount: '10' });
166
+
167
+ // fetch one
168
+ const intent = await client.paymentIntents.fetch('pi_123');
169
+
170
+ // list (paginated + filtered)
171
+ const page = await client.paymentIntents.list({ status: 'SUCCEEDED', take: 50, skip: 0 });
172
+ console.log(page.items, page.total);
173
+
174
+ // update / cancel / delete
175
+ await intent.edit({ reference: 'order_1234' });
176
+ await intent.cancel();
177
+ await intent.delete();
178
+
179
+ // validate a submitted tx (finalizes status + fires webhook)
180
+ const outcome = await intent.validate('<txHash>');
181
+ ```
182
+
183
+ Each `PaymentIntent` exposes typed helpers: `isTx`, `isPay`, `isSucceeded`, `isPending`, `assetLabel`,
184
+ and the action methods `fetch()`, `edit()`, `validate()`, `cancel()`, `delete()`.
185
+
186
+ ## ๐Ÿ”” Webhooks
187
+
188
+ ```ts
189
+ // register an endpoint โ€” the secret is returned ONCE
190
+ const endpoint = await client.webhooks.create({
191
+ url: 'https://me.example.com/hooks/cosmos',
192
+ eventTypes: ['PAYMENT_INTENT_SUCCEEDED', 'PAYMENT_INTENT_FAILED'],
193
+ });
194
+ console.log(endpoint.secret); // whsec_... โ€” store it now!
195
+
196
+ // manage it
197
+ await endpoint.disable();
198
+ await endpoint.enable();
199
+ await endpoint.ping();
200
+ const rotated = await endpoint.rotateSecret();
201
+ console.log(rotated.secret);
202
+
203
+ // audit trail
204
+ const deliveries = await endpoint.fetchDeliveries({ status: 'FAILED' });
205
+ for (const d of deliveries.items) await d.redeliver();
206
+
207
+ await endpoint.delete();
208
+ ```
209
+
210
+ ### Receiving events โ€” `client.webhooks.on(...)`
211
+
212
+ Subscribe to events the discord.js way. You can listen with the raw type, its camelCase alias, or
213
+ `event` for everything:
214
+
215
+ ```ts
216
+ client.webhooks.on('paymentIntentSucceeded', (event) => {
217
+ console.log('Paid!', event.data.id, event.data.amount);
218
+ });
219
+
220
+ client.webhooks.on('PAYMENT_INTENT_FAILED', (event) => { /* ... */ });
221
+
222
+ client.webhooks.on('event', (event) => {
223
+ console.log('any event:', event.type);
224
+ });
225
+ ```
226
+
227
+ Then feed incoming HTTP requests into the listener. The SDK verifies the HMAC signature for you and
228
+ dispatches the event. Set the secret once on the client (or pass `{ secret }` to the handler):
229
+
230
+ ```ts
231
+ const client = new Client({
232
+ apiKey: process.env.COSMOS_PAY_API_KEY,
233
+ webhookSecret: process.env.COSMOS_WEBHOOK_SECRET, // the whsec_... from create/rotate
234
+ });
235
+ ```
236
+
237
+ **Node.js `http` (zero dependencies):**
238
+
239
+ ```ts
240
+ import { createServer } from 'node:http';
241
+
242
+ createServer(client.webhooks.createHandler()).listen(4242);
243
+ // โ†’ verifies the signature, emits the event, replies 200 (or 400 on a bad signature)
244
+ ```
245
+
246
+ **Express:**
247
+
248
+ ```ts
249
+ import express from 'express';
250
+ const app = express();
251
+
252
+ // must receive the RAW body so the signature matches
253
+ app.post(
254
+ '/hooks/cosmos',
255
+ express.raw({ type: '*/*' }),
256
+ client.webhooks.middleware(),
257
+ (req, res) => {
258
+ // req.cosmosEvent is the verified event; listeners have already fired
259
+ res.sendStatus(200);
260
+ },
261
+ );
262
+ ```
263
+
264
+ ### Verifying signatures manually
265
+
266
+ Prefer to handle dispatch yourself? Use the lower-level helpers. The dispatcher signs each POST with
267
+ `X-Cosmos-Signature: t=<unixSeconds>,v1=<hmacSha256>`:
268
+
269
+ ```ts
270
+ import { Webhooks } from '@cosmosapp/pay_sdk';
271
+
272
+ const event = Webhooks.constructEvent(
273
+ rawBody, // RAW body (Buffer or string)
274
+ req.header('X-Cosmos-Signature'),
275
+ process.env.COSMOS_WEBHOOK_SECRET,
276
+ );
277
+ ```
278
+
279
+ `Webhooks.verify(rawBody, header, secret)` returns `true` or throws;
280
+ `Webhooks.constructEvent(...)` verifies **and** parses the JSON event. Both accept a
281
+ `{ toleranceSeconds }` option (default 300s replay window). Equivalently,
282
+ `client.webhooks.process(rawBody, header, { secret })` does the same and emits the event to your
283
+ `on(...)` listeners.
284
+
285
+ ## ๐Ÿ›๏ธ Products & customers
286
+
287
+ ```ts
288
+ const product = await client.products.create({
289
+ name: 'Pro plan โ€” monthly',
290
+ amount: '49.00',
291
+ assetCode: 'USDC',
292
+ kind: 'recurring',
293
+ });
294
+ await product.deactivate();
295
+
296
+ const customer = await client.customers.create({
297
+ name: 'Acme Inc.',
298
+ email: 'billing@acme.com',
299
+ account: 'G...',
300
+ });
301
+ await customer.edit({ note: 'VIP, net-30' });
302
+ const customers = await client.customers.list(); // includes payment stats
303
+ ```
304
+
305
+ ## ๐Ÿ“Š Analytics & health
306
+
307
+ ```ts
308
+ const summary = await client.analytics.summary(); // totals, volume, webhook health, 30-day series
309
+ const balances = await client.analytics.balances(); // settled + pending per asset
310
+ const apiLogs = await client.analytics.apiLogs();
311
+ const hookLogs = await client.analytics.webhookLogs();
312
+
313
+ await client.health.liveness(); // true
314
+ const ready = await client.health.readiness(); // { status, info, details }
315
+ ```
316
+
317
+ ## โš ๏ธ Error handling
318
+
319
+ ```ts
320
+ import { CosmosPayAPIError, CosmosPayRequestError } from '@cosmosapp/pay_sdk';
321
+
322
+ try {
323
+ await client.paymentIntents.fetch('missing');
324
+ } catch (err) {
325
+ if (err instanceof CosmosPayAPIError) {
326
+ console.error(err.status, err.code, err.body); // e.g. 404
327
+ } else if (err instanceof CosmosPayRequestError) {
328
+ console.error('Network/timeout:', err.cause);
329
+ }
330
+ }
331
+ ```
332
+
333
+ Transient failures (network errors, `408`, `429`, `5xx`) are retried automatically
334
+ (default 2 retries, honoring `Retry-After`).
335
+
336
+ ## ๐Ÿ“ก Observability
337
+
338
+ The client re-emits REST telemetry:
339
+
340
+ ```ts
341
+ client.on('request', ({ method, url }) => {});
342
+ client.on('response', ({ status, url }) => {});
343
+ client.on('rateLimited', ({ url }) => {});
344
+ ```
345
+
346
+ ## โš™๏ธ Configuration reference
347
+
348
+ ```ts
349
+ new Client({
350
+ apiKey: 'prod_xxx', // required โ€” the only thing you normally set
351
+ webhookSecret: 'whsec_...', // default secret for the webhook listener
352
+ timeout: 30_000, // ms
353
+ retries: 2,
354
+ headers: { 'X-Trace': 'abc' }, // extra headers on every request
355
+ fetch: customFetch, // custom fetch implementation
356
+
357
+ // Advanced / internal โ€” pre-filled from Client.shared, rarely overridden:
358
+ baseURL: 'https://...', // gateway URL
359
+ version: 'v1', // route prefix
360
+ gatewaySecret: '...', // direct access (X-Gateway-Secret)
361
+ consumerUsername: '...', // direct access (X-Consumer-Username)
362
+ });
363
+ ```
364
+
365
+ ## ๐Ÿงฉ TypeScript
366
+
367
+ Everything is fully typed. Import option/entity types and enums directly:
368
+
369
+ ```ts
370
+ import {
371
+ Client,
372
+ PaymentIntentStatus,
373
+ WebhookEventType,
374
+ type CreateTxPaymentIntentOptions,
375
+ type PaymentIntentData,
376
+ } from '@cosmosapp/pay_sdk';
377
+ ```
378
+
379
+ ## ๐Ÿงช Running the tests locally
380
+
381
+ The test suite runs **entirely offline** with the built-in Node test runner (`node:test`) โ€” no network,
382
+ no API key and no extra dependencies. Every HTTP call is served by an injected fake `fetch`, and the
383
+ webhook tests sign payloads with real `node:crypto`.
384
+
385
+ ```bash
386
+ npm install # dev deps only (typescript, tsup, โ€ฆ)
387
+ npm test # builds the SDK, then runs node --test
388
+ ```
389
+
390
+ What's covered:
391
+
392
+ | Suite | What it verifies |
393
+ | ---------------------------- | ---------------- |
394
+ | `test/client.test.mjs` | construction, required `apiKey`, shared-config resolution, auth headers, telemetry events |
395
+ | `test/rest.test.mjs` | URL/version building, query serialization, retry on `429`/`5xx`, structured errors |
396
+ | `test/payment-intents.test.mjs` | `createTx`/`createPay`/`fetch`/`list`/`validate`, request bodies, caching, structure helpers |
397
+ | `test/webhooks.test.mjs` | HMAC `verify`/`constructEvent`, replay tolerance, `on(...)` dispatch, bad-signature rejection |
398
+ | `test/structures.test.mjs` | `PaymentIntent` accessors, `toJSON`, `valueOf`, error classes |
399
+
400
+ Run a single file while developing:
401
+
402
+ ```bash
403
+ node --test test/webhooks.test.mjs
404
+ ```
405
+
406
+ > The `pretest` hook builds `dist/` first, so the tests exercise the exact artifact that gets published to npm.
407
+
408
+ ## ๐Ÿค– CI/CD & publishing
409
+
410
+ This repo ships two GitHub Actions workflows under [`.github/workflows/`](./.github/workflows):
411
+
412
+ | Workflow | Trigger | What it does |
413
+ | -------- | ------- | ------------ |
414
+ | **`ci.yml`** | every push & PR to `main` | `npm ci` โ†’ typecheck โ†’ build โ†’ test, on Node **18 / 20 / 22** |
415
+ | **`release.yml`** | every push to `main` (or manual run) | **auto-detects a version bump** โ†’ typecheck โ†’ test โ†’ `npm publish --provenance`; skips if the version is unchanged |
416
+
417
+ Publishing is **fully automatic**: there's no Release to create and no tag to push. `release.yml`
418
+ runs on every push to `main`, compares `package.json`'s version against what's already on npm, and
419
+ publishes only when it's new. Unchanged version โ†’ the job skips cleanly (no red โŒ).
420
+
421
+ ### One-time setup (the GitHub environment variable)
422
+
423
+ 1. **Create an npm automation token** โ€” npm โ†’ _Access Tokens_ โ†’ _Generate New Token_ โ†’ **Automation**
424
+ (or a _Granular_ token with publish rights for `@cosmosapp/pay_sdk`). The token's account must be a
425
+ member of the **`@cosmosapp`** npm organization.
426
+ 2. **Add it to GitHub** โ€” repo โ†’ _Settings_ โ†’ _Secrets and variables_ โ†’ _Actions_ โ†’
427
+ **New repository secret**, named exactly:
428
+
429
+ ```
430
+ NPM_TOKEN
431
+ ```
432
+
433
+ The `release.yml` job reads it as `NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}`.
434
+ It's scoped to a `release` [Environment](https://docs.github.com/actions/deployments/managing-environments-for-deployment) โ€”
435
+ create an Environment called **`release`** and add the secret there (or remove the
436
+ `environment: release` line from the workflow to use a plain repo secret instead).
437
+
438
+ ### Shipping a new version
439
+
440
+ ```bash
441
+ npm version patch # or minor / major โ€” bumps package.json (+ git tag)
442
+ git push --follow-tags # push to main โ†’ release.yml publishes automatically
443
+ ```
444
+
445
+ That's it. The job **never republishes an existing version** (it checks npm first), so re-running or
446
+ pushing unrelated commits is always safe. Packages ship with
447
+ [**npm provenance**](https://docs.npmjs.com/generating-provenance-statements) (`id-token: write` +
448
+ `--provenance`), giving consumers a verifiable link back to this repo and commit.
449
+
450
+ > **First publish:** the `@cosmosapp` org and the `NPM_TOKEN` secret must exist before the first run.
451
+ > Because the name is scoped, `publishConfig.access` is set to `public` so it isn't published private.
452
+
453
+ > Only `dist/`, `README.md` and `LICENSE` are published (`package.json#files`) โ€” source, tests and
454
+ > workflows never ship in the tarball. Verify locally with `npm pack --dry-run`.
455
+
456
+ ## ๐Ÿ“„ License
457
+
458
+ [MIT](./LICENSE)