@ghostpaygg/node 0.0.0-stage → 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/CHANGELOG.md +19 -0
- package/README.md +176 -2
- package/dist/index.cjs +456 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +2655 -0
- package/dist/index.d.ts +2655 -0
- package/dist/index.js +423 -0
- package/dist/index.js.map +1 -0
- package/package.json +38 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
- `rates.list()`: entries no longer have `as_of` (it was the request time, not the rate's time).
|
|
6
|
+
- `webhookDeliveries.retry()`: only for `FAILED` deliveries; queues and returns a **new** delivery (201) that follows
|
|
7
|
+
the endpoint's `auto_retry`. `replay()` skips events that already have a pending delivery to the endpoint.
|
|
8
|
+
- `transactions.list({ status })` accepts only deposit or withdrawal statuses and filters the matching kind.
|
|
9
|
+
|
|
10
|
+
## 1.0.0
|
|
11
|
+
|
|
12
|
+
- Networks: Ethereum (ETH, USDT, USDC, DAI), Bitcoin, Solana, Litecoin (TON removed before release; no memo fields).
|
|
13
|
+
- Withdrawals have no fee: `network_fee_max` is held, `network_fee` (actual cost) is set on completion. Quotes need `address`.
|
|
14
|
+
- `addresses.topUps()`: zero-fee merchant funding addresses; `top_up` on addresses and deposits.
|
|
15
|
+
|
|
16
|
+
- First release: every GhostPay API v1 call, typed from the OpenAPI spec.
|
|
17
|
+
- Webhook verification (Standard Webhooks) with typed events, secret rotation and replay protection.
|
|
18
|
+
- Automatic idempotency keys reused across retries; withdrawals keyed by `external_id`.
|
|
19
|
+
- Auto-pagination and `events.since()` for catching up after downtime.
|
package/README.md
CHANGED
|
@@ -1,3 +1,177 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ghostpaygg/node
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Official Node.js client for the GhostPay API: deposit addresses, invoices, withdrawals and signed webhooks.
|
|
4
|
+
|
|
5
|
+
- Fully typed from the OpenAPI spec (every request, response and webhook event)
|
|
6
|
+
- Safe retries: every `POST` gets an Idempotency-Key that is reused on retry, so a timeout never pays twice
|
|
7
|
+
- Webhook verification built in (Standard Webhooks), with typed events
|
|
8
|
+
- Auto-pagination with `for await`
|
|
9
|
+
- No runtime dependencies; Node 18+, ESM and CommonJS
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install @ghostpaygg/node
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Quick start
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { GhostPay } from "@ghostpaygg/node";
|
|
19
|
+
|
|
20
|
+
const gp = new GhostPay({
|
|
21
|
+
apiKey: process.env.GHOSTPAY_API_KEY, // gp_live_…
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
// A permanent deposit address for a player (same address on every call)
|
|
25
|
+
const address = await gp.addresses.getOrCreate({ customer: "player_42", network: "solana" });
|
|
26
|
+
console.log(address.address, address.accepts.map((c) => `${c.currency} min ${c.min_deposit}`));
|
|
27
|
+
|
|
28
|
+
// Pay a player out
|
|
29
|
+
const payout = await gp.withdrawals.create({
|
|
30
|
+
external_id: "payout_9001", // your id; also makes the call idempotent across retries and restarts
|
|
31
|
+
customer: "player_42",
|
|
32
|
+
currency: "USDT",
|
|
33
|
+
network: "solana",
|
|
34
|
+
address: "7xKX…",
|
|
35
|
+
amount: "25.50", // amounts are always decimal strings
|
|
36
|
+
});
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Networks: `ethereum` (ETH, USDT, USDC, DAI), `bitcoin` (BTC), `solana` (SOL, USDT, USDC), `litecoin` (LTC).
|
|
40
|
+
|
|
41
|
+
## Webhooks
|
|
42
|
+
|
|
43
|
+
Verify every webhook against the **raw** body before using it:
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
import express from "express";
|
|
47
|
+
import { Webhook, WebhookVerificationError } from "@ghostpaygg/node";
|
|
48
|
+
|
|
49
|
+
const webhook = new Webhook(process.env.GHOSTPAY_WEBHOOK_SECRET!); // whsec_…
|
|
50
|
+
|
|
51
|
+
app.post("/webhooks/ghostpay", express.raw({ type: "application/json" }), async (req, res) => {
|
|
52
|
+
let event;
|
|
53
|
+
try {
|
|
54
|
+
event = webhook.verify(req.body, req.headers);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (error instanceof WebhookVerificationError) return res.status(400).send(error.message);
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (await alreadyProcessed(event.id)) return res.sendStatus(200); // delivery is at-least-once
|
|
61
|
+
|
|
62
|
+
switch (event.type) {
|
|
63
|
+
case "deposit.credited": // final: credit the player now
|
|
64
|
+
await creditPlayer(event.data.customer, event.data.currency, event.data.net_amount, event.data.id);
|
|
65
|
+
break;
|
|
66
|
+
case "withdrawal.completed":
|
|
67
|
+
await markPayoutDone(event.data.external_id, event.data.tx_hash);
|
|
68
|
+
break;
|
|
69
|
+
case "withdrawal.failed": // the amount is back in your GhostPay balance
|
|
70
|
+
await refundPlayer(event.data.external_id, event.data.failure_reason);
|
|
71
|
+
break;
|
|
72
|
+
}
|
|
73
|
+
res.sendStatus(200);
|
|
74
|
+
});
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
- `event` is typed by `event.type`: `event.data` is a `Deposit`, `Withdrawal` or `Invoice`.
|
|
78
|
+
- Credit players on `deposit.credited` only, never on `deposit.pending`.
|
|
79
|
+
- De-duplicate on `event.id`, and use `event.data.version` (it only increases) to ignore stale updates; events can arrive out of order.
|
|
80
|
+
- Timestamps older than 5 minutes are rejected (`new Webhook(secret, { toleranceSec })` to change).
|
|
81
|
+
- While rotating secrets, pass both: `new Webhook([newSecret, oldSecret])`.
|
|
82
|
+
- Without a framework: `webhook.verify(rawBodyStringOrBuffer, headers)` accepts fetch `Headers` or Node's `req.headers`.
|
|
83
|
+
|
|
84
|
+
### Catching up after downtime
|
|
85
|
+
|
|
86
|
+
Missed webhooks are retried for about a day, but you can also read the event log yourself. Store the id of the last
|
|
87
|
+
event you processed:
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
for await (const event of gp.events.since(lastEventId)) {
|
|
91
|
+
await handle(event);
|
|
92
|
+
lastEventId = event.id;
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Pagination
|
|
97
|
+
|
|
98
|
+
`list()` calls return one page when awaited, or every item when iterated:
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
const page = await gp.deposits.list({ status: "CREDITED", limit: 100 }); // { data, has_more }
|
|
102
|
+
|
|
103
|
+
for await (const deposit of gp.deposits.list({ customer: "player_42" })) {
|
|
104
|
+
// fetches further pages as needed
|
|
105
|
+
}
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Errors
|
|
109
|
+
|
|
110
|
+
```ts
|
|
111
|
+
import { GhostPayApiError, GhostPayConnectionError } from "@ghostpaygg/node";
|
|
112
|
+
|
|
113
|
+
try {
|
|
114
|
+
await gp.withdrawals.create({ … });
|
|
115
|
+
} catch (error) {
|
|
116
|
+
if (error instanceof GhostPayApiError) {
|
|
117
|
+
// error.status, error.code (stable), error.message, error.param
|
|
118
|
+
if (error.code === "insufficient_balance") { … }
|
|
119
|
+
if (error.code === "invalid_address") { … }
|
|
120
|
+
} else if (error instanceof GhostPayConnectionError) {
|
|
121
|
+
// no response (error.timedOut tells you if it timed out): retry with the same external_id / idempotencyKey
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Codes: `invalid_request`, `unauthorized`, `forbidden`, `not_found`, `conflict`, `idempotency_key_reused`,
|
|
127
|
+
`insufficient_balance`, `invalid_address`, `below_minimum`, `network_paused`, `withdrawals_paused`,
|
|
128
|
+
`currency_not_supported`, `invalid_state`, `network_fee_unavailable` (503, retry shortly), `api_error`.
|
|
129
|
+
|
|
130
|
+
## Retries and idempotency
|
|
131
|
+
|
|
132
|
+
Network errors, timeouts, `429` and `5xx` are retried (default 2 retries, exponential backoff) with the **same**
|
|
133
|
+
Idempotency-Key, so the server replays the first result instead of acting twice.
|
|
134
|
+
|
|
135
|
+
- Every `POST` gets a random key per call. Pass your own with `{ idempotencyKey }` to make retries safe across process restarts.
|
|
136
|
+
- `withdrawals.create` uses `withdrawal:<external_id>` automatically when you pass an `external_id`.
|
|
137
|
+
- `result.lastResponse.idempotentReplayed` is `true` when the response was a replay.
|
|
138
|
+
- `webhookEndpoints.create` is not retried once sent (its response holds a secret and is never stored for replay).
|
|
139
|
+
|
|
140
|
+
## Options
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
new GhostPay({
|
|
144
|
+
apiKey: "gp_live_…",
|
|
145
|
+
baseUrl: "https://api.ghostpay.gg", // default
|
|
146
|
+
timeoutMs: 30_000, // per attempt
|
|
147
|
+
maxRetries: 2,
|
|
148
|
+
appInfo: "my-casino/1.4", // appended to the User-Agent
|
|
149
|
+
fetch: customFetch, // e.g. a proxy agent
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
// Per call
|
|
153
|
+
await gp.withdrawals.get("wd_…", { timeoutMs: 5_000, maxRetries: 0, signal: abortController.signal });
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
Every result has a non-enumerable `lastResponse` with `status`, `headers`, `idempotentReplayed` and `idempotencyKey`.
|
|
157
|
+
|
|
158
|
+
## All calls
|
|
159
|
+
|
|
160
|
+
| Resource | Calls |
|
|
161
|
+
|---|---|
|
|
162
|
+
| `networks`, `currencies`, `rates`, `balances` | `list()` |
|
|
163
|
+
| `customers` | `upsert`, `list`, `get`, `getByExternalId` |
|
|
164
|
+
| `addresses` | `getOrCreate`, `list`, `get` (id or on-chain address), `retire`, `topUps` (your own zero-fee funding addresses) |
|
|
165
|
+
| `deposits` | `list`, `get` |
|
|
166
|
+
| `invoices` | `create`, `list`, `get`, `cancel` |
|
|
167
|
+
| `withdrawals` | `quote`, `create`, `list`, `get`, `getByExternalId`, `cancel` |
|
|
168
|
+
| `webhookEndpoints` | `create`, `list`, `get`, `update`, `delete`, `test`, `replay` |
|
|
169
|
+
| `webhookDeliveries` | `list`, `get`, `retry` |
|
|
170
|
+
| `events` | `list`, `get`, `since` |
|
|
171
|
+
| `transactions` | `list` (deposits, top-ups, withdrawals, payouts), `get` (with webhook history) |
|
|
172
|
+
| `stats` | `get` (balances and daily volume in USD) |
|
|
173
|
+
| `settings` | `get` |
|
|
174
|
+
| `checkout` (public, no API key) | `get`, `select` |
|
|
175
|
+
| `webhooks` | `verify` |
|
|
176
|
+
|
|
177
|
+
All types are exported: `import type { Deposit, Withdrawal, Invoice, WebhookEvent, … } from "@ghostpaygg/node"`.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
GhostPay: () => GhostPay,
|
|
24
|
+
GhostPayApiError: () => GhostPayApiError,
|
|
25
|
+
GhostPayConnectionError: () => GhostPayConnectionError,
|
|
26
|
+
GhostPayError: () => GhostPayError,
|
|
27
|
+
VERSION: () => VERSION,
|
|
28
|
+
Webhook: () => Webhook,
|
|
29
|
+
WebhookVerificationError: () => WebhookVerificationError,
|
|
30
|
+
default: () => GhostPay
|
|
31
|
+
});
|
|
32
|
+
module.exports = __toCommonJS(index_exports);
|
|
33
|
+
|
|
34
|
+
// src/http.ts
|
|
35
|
+
var import_node_crypto = require("crypto");
|
|
36
|
+
|
|
37
|
+
// src/errors.ts
|
|
38
|
+
var GhostPayError = class extends Error {
|
|
39
|
+
name = "GhostPayError";
|
|
40
|
+
};
|
|
41
|
+
var GhostPayApiError = class extends GhostPayError {
|
|
42
|
+
name = "GhostPayApiError";
|
|
43
|
+
status;
|
|
44
|
+
code;
|
|
45
|
+
param;
|
|
46
|
+
headers;
|
|
47
|
+
raw;
|
|
48
|
+
constructor(status, code, message, param, headers, raw) {
|
|
49
|
+
super(message);
|
|
50
|
+
this.status = status;
|
|
51
|
+
this.code = code;
|
|
52
|
+
this.param = param;
|
|
53
|
+
this.headers = headers;
|
|
54
|
+
this.raw = raw;
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
var GhostPayConnectionError = class extends GhostPayError {
|
|
58
|
+
name = "GhostPayConnectionError";
|
|
59
|
+
timedOut;
|
|
60
|
+
constructor(message, timedOut, options) {
|
|
61
|
+
super(message, options);
|
|
62
|
+
this.timedOut = timedOut;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
var WebhookVerificationError = class extends GhostPayError {
|
|
66
|
+
name = "WebhookVerificationError";
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
// src/version.ts
|
|
70
|
+
var VERSION = "1.0.0";
|
|
71
|
+
|
|
72
|
+
// src/http.ts
|
|
73
|
+
var RETRY_BASE_MS = 500;
|
|
74
|
+
var RETRY_MAX_MS = 8e3;
|
|
75
|
+
var DEFAULT_BASE_URL = "https://api.ghostpay.gg";
|
|
76
|
+
var HttpClient = class {
|
|
77
|
+
constructor(options) {
|
|
78
|
+
this.options = options;
|
|
79
|
+
this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
80
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch;
|
|
81
|
+
if (!this.fetchImpl) throw new GhostPayError("No fetch available: use Node 18+ or pass options.fetch");
|
|
82
|
+
this.userAgent = `ghostpay-node/${VERSION} node/${process.versions.node}${options.appInfo ? ` ${options.appInfo}` : ""}`;
|
|
83
|
+
}
|
|
84
|
+
options;
|
|
85
|
+
baseUrl;
|
|
86
|
+
fetchImpl;
|
|
87
|
+
userAgent;
|
|
88
|
+
async request(spec, options = {}) {
|
|
89
|
+
const auth = spec.auth ?? true;
|
|
90
|
+
if (auth && !this.options.apiKey) throw new GhostPayError("This call needs an API key: new GhostPay({ apiKey, baseUrl })");
|
|
91
|
+
const url = this.baseUrl + spec.path + queryString(spec.query);
|
|
92
|
+
const idempotencyKey = spec.method === "POST" ? options.idempotencyKey ?? (0, import_node_crypto.randomUUID)() : void 0;
|
|
93
|
+
const headers = {
|
|
94
|
+
accept: "application/json",
|
|
95
|
+
"user-agent": this.userAgent,
|
|
96
|
+
...auth ? { authorization: `Bearer ${this.options.apiKey}` } : {},
|
|
97
|
+
...idempotencyKey ? { "idempotency-key": idempotencyKey } : {},
|
|
98
|
+
...spec.body !== void 0 ? { "content-type": "application/json" } : {},
|
|
99
|
+
...options.headers
|
|
100
|
+
};
|
|
101
|
+
const body = spec.body !== void 0 ? JSON.stringify(spec.body) : void 0;
|
|
102
|
+
const maxRetries = options.maxRetries ?? this.options.maxRetries ?? 2;
|
|
103
|
+
const timeoutMs = options.timeoutMs ?? this.options.timeoutMs ?? 3e4;
|
|
104
|
+
for (let attempt = 0; ; attempt++) {
|
|
105
|
+
let response;
|
|
106
|
+
let text;
|
|
107
|
+
try {
|
|
108
|
+
({ response, text } = await this.send(url, { method: spec.method, headers, ...body !== void 0 ? { body } : {} }, timeoutMs, options.signal));
|
|
109
|
+
} catch (error2) {
|
|
110
|
+
if (options.signal?.aborted) throw error2;
|
|
111
|
+
const sent = !(error2 instanceof GhostPayConnectionError && isRefused(error2));
|
|
112
|
+
if (attempt < maxRetries && (spec.method === "GET" || !sent || spec.retryAfterSend !== false)) {
|
|
113
|
+
await sleep(backoff(attempt));
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
throw error2;
|
|
117
|
+
}
|
|
118
|
+
const parsed = text ? safeJson(text) : void 0;
|
|
119
|
+
if (response.ok) {
|
|
120
|
+
if (parsed === void 0 && text) throw new GhostPayError(`Invalid JSON from ${spec.method} ${spec.path} (HTTP ${response.status})`);
|
|
121
|
+
return withMeta(parsed, {
|
|
122
|
+
status: response.status,
|
|
123
|
+
headers: response.headers,
|
|
124
|
+
idempotentReplayed: response.headers.get("idempotent-replayed") === "true",
|
|
125
|
+
idempotencyKey
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
const error = toApiError(response, parsed, text);
|
|
129
|
+
if (attempt < maxRetries && retryable(error) && (spec.method === "GET" || spec.retryAfterSend !== false)) {
|
|
130
|
+
await sleep(retryAfterMs(response.headers) ?? backoff(attempt));
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/** Every item of a cursor-paginated list, fetching pages as needed. */
|
|
137
|
+
async *paginate(path, query, options) {
|
|
138
|
+
let after = query.after ?? void 0;
|
|
139
|
+
for (; ; ) {
|
|
140
|
+
const page = await this.request({ method: "GET", path, query: { ...query, after } }, options);
|
|
141
|
+
for (const item of page.data) yield item;
|
|
142
|
+
const last = page.data[page.data.length - 1];
|
|
143
|
+
if (!page.has_more || !last) return;
|
|
144
|
+
after = last.id;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
async send(url, init, timeoutMs, signal) {
|
|
148
|
+
const controller = new AbortController();
|
|
149
|
+
let timedOut = false;
|
|
150
|
+
const timer = setTimeout(() => {
|
|
151
|
+
timedOut = true;
|
|
152
|
+
controller.abort();
|
|
153
|
+
}, timeoutMs);
|
|
154
|
+
const onAbort = () => controller.abort(signal?.reason);
|
|
155
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
156
|
+
try {
|
|
157
|
+
const response = await this.fetchImpl(url, { ...init, signal: controller.signal });
|
|
158
|
+
return { response, text: await response.text() };
|
|
159
|
+
} catch (error) {
|
|
160
|
+
if (signal?.aborted) throw error;
|
|
161
|
+
if (timedOut) throw new GhostPayConnectionError(`Request timed out after ${timeoutMs} ms`, true, { cause: error });
|
|
162
|
+
throw new GhostPayConnectionError(`Could not reach GhostPay: ${error?.message ?? error}`, false, { cause: error });
|
|
163
|
+
} finally {
|
|
164
|
+
clearTimeout(timer);
|
|
165
|
+
signal?.removeEventListener("abort", onAbort);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
function listResult(http, path, query = {}, options) {
|
|
170
|
+
let pending;
|
|
171
|
+
const first = () => pending ??= http.request({ method: "GET", path, query }, options);
|
|
172
|
+
return {
|
|
173
|
+
then: (onFulfilled, onRejected) => first().then(onFulfilled, onRejected),
|
|
174
|
+
catch: (onRejected) => first().catch(onRejected),
|
|
175
|
+
finally: (onFinally) => first().finally(onFinally),
|
|
176
|
+
[Symbol.toStringTag]: "ListResult",
|
|
177
|
+
[Symbol.asyncIterator]: () => http.paginate(path, query, options)
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
function withMeta(value, meta) {
|
|
181
|
+
const target = value && typeof value === "object" ? value : {};
|
|
182
|
+
Object.defineProperty(target, "lastResponse", { value: meta, enumerable: false });
|
|
183
|
+
return target;
|
|
184
|
+
}
|
|
185
|
+
function toApiError(response, parsed, text) {
|
|
186
|
+
const envelope = parsed?.error;
|
|
187
|
+
const code = envelope?.code ?? (response.status >= 500 ? "api_error" : "invalid_request");
|
|
188
|
+
const message = envelope?.message ?? `HTTP ${response.status}${text ? `: ${text.slice(0, 200)}` : ""}`;
|
|
189
|
+
return new GhostPayApiError(response.status, code, message, envelope?.param, response.headers, parsed ?? text);
|
|
190
|
+
}
|
|
191
|
+
function retryable(error) {
|
|
192
|
+
if (error.status === 429 || error.status >= 500) return true;
|
|
193
|
+
return error.status === 409 && error.code === "conflict" && !error.param && /idempotency-key/i.test(error.message);
|
|
194
|
+
}
|
|
195
|
+
function isRefused(error) {
|
|
196
|
+
const cause = error.cause?.cause;
|
|
197
|
+
return cause?.code === "ECONNREFUSED" || cause?.code === "ENOTFOUND" || cause?.code === "EAI_AGAIN";
|
|
198
|
+
}
|
|
199
|
+
function backoff(attempt) {
|
|
200
|
+
const base = Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** attempt);
|
|
201
|
+
return base / 2 + Math.random() * (base / 2);
|
|
202
|
+
}
|
|
203
|
+
function retryAfterMs(headers) {
|
|
204
|
+
const value = headers.get("retry-after");
|
|
205
|
+
if (!value) return void 0;
|
|
206
|
+
const seconds = Number(value);
|
|
207
|
+
if (Number.isFinite(seconds)) return Math.min(RETRY_MAX_MS * 4, Math.max(0, seconds * 1e3));
|
|
208
|
+
const date = Date.parse(value);
|
|
209
|
+
return Number.isFinite(date) ? Math.min(RETRY_MAX_MS * 4, Math.max(0, date - Date.now())) : void 0;
|
|
210
|
+
}
|
|
211
|
+
function queryString(query) {
|
|
212
|
+
if (!query) return "";
|
|
213
|
+
const params = new URLSearchParams();
|
|
214
|
+
for (const [key, value] of Object.entries(query)) if (value !== void 0 && value !== null) params.set(key, String(value));
|
|
215
|
+
const text = params.toString();
|
|
216
|
+
return text ? `?${text}` : "";
|
|
217
|
+
}
|
|
218
|
+
function safeJson(text) {
|
|
219
|
+
try {
|
|
220
|
+
return JSON.parse(text);
|
|
221
|
+
} catch {
|
|
222
|
+
return void 0;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
function sleep(ms) {
|
|
226
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// src/webhooks.ts
|
|
230
|
+
var import_node_crypto2 = require("crypto");
|
|
231
|
+
var PREFIX = "whsec_";
|
|
232
|
+
var Webhook = class {
|
|
233
|
+
keys;
|
|
234
|
+
toleranceSec;
|
|
235
|
+
constructor(secret, options = {}) {
|
|
236
|
+
const secrets = Array.isArray(secret) ? secret : [secret];
|
|
237
|
+
if (secrets.length === 0 || secrets.some((value) => typeof value !== "string" || value.length === 0)) {
|
|
238
|
+
throw new WebhookVerificationError("A webhook signing secret (whsec_\u2026) is required");
|
|
239
|
+
}
|
|
240
|
+
this.keys = secrets.map(decodeSecret);
|
|
241
|
+
this.toleranceSec = options.toleranceSec ?? 300;
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Checks the signature and timestamp and returns the parsed, typed event. `payload` must be the raw request body,
|
|
245
|
+
* exactly as received (e.g. `express.raw({ type: "application/json" })`), never re-serialized JSON.
|
|
246
|
+
*/
|
|
247
|
+
verify(payload, headers, now = /* @__PURE__ */ new Date()) {
|
|
248
|
+
const body = rawBody(payload);
|
|
249
|
+
const id = header(headers, "webhook-id");
|
|
250
|
+
const timestamp = header(headers, "webhook-timestamp");
|
|
251
|
+
const signatures = header(headers, "webhook-signature");
|
|
252
|
+
if (!id || !timestamp || !signatures) throw new WebhookVerificationError("Missing webhook-id, webhook-timestamp or webhook-signature header");
|
|
253
|
+
const seconds = Number(timestamp);
|
|
254
|
+
if (!/^\d+$/.test(timestamp) || !Number.isSafeInteger(seconds)) throw new WebhookVerificationError("Invalid webhook-timestamp");
|
|
255
|
+
const skew = Math.floor(now.getTime() / 1e3) - seconds;
|
|
256
|
+
if (skew > this.toleranceSec) throw new WebhookVerificationError("Webhook timestamp is too old");
|
|
257
|
+
if (skew < -this.toleranceSec) throw new WebhookVerificationError("Webhook timestamp is in the future");
|
|
258
|
+
const expected = this.keys.map((key) => sign(key, id, timestamp, body));
|
|
259
|
+
const valid = signatures.split(" ").some((entry) => {
|
|
260
|
+
const [version, signature] = entry.split(",", 2);
|
|
261
|
+
if (version !== "v1" || !signature) return false;
|
|
262
|
+
const given = Buffer.from(signature, "base64");
|
|
263
|
+
return expected.some((candidate) => given.length === candidate.length && (0, import_node_crypto2.timingSafeEqual)(given, candidate));
|
|
264
|
+
});
|
|
265
|
+
if (!valid) throw new WebhookVerificationError("No matching webhook signature");
|
|
266
|
+
let event;
|
|
267
|
+
try {
|
|
268
|
+
event = JSON.parse(body.toString("utf8"));
|
|
269
|
+
} catch {
|
|
270
|
+
throw new WebhookVerificationError("Webhook body is not valid JSON");
|
|
271
|
+
}
|
|
272
|
+
if (!event || typeof event !== "object" || event.id !== id) throw new WebhookVerificationError("Webhook body id does not match webhook-id");
|
|
273
|
+
return event;
|
|
274
|
+
}
|
|
275
|
+
/** The `webhook-signature` header value for a body (for your own tests). */
|
|
276
|
+
sign(id, timestamp, payload) {
|
|
277
|
+
const seconds = String(typeof timestamp === "number" ? timestamp : Math.floor(timestamp.getTime() / 1e3));
|
|
278
|
+
return `v1,${sign(this.keys[0], id, seconds, rawBody(payload)).toString("base64")}`;
|
|
279
|
+
}
|
|
280
|
+
};
|
|
281
|
+
function sign(key, id, timestamp, body) {
|
|
282
|
+
return (0, import_node_crypto2.createHmac)("sha256", key).update(`${id}.${timestamp}.`).update(body).digest();
|
|
283
|
+
}
|
|
284
|
+
function decodeSecret(secret) {
|
|
285
|
+
const key = Buffer.from(secret.startsWith(PREFIX) ? secret.slice(PREFIX.length) : secret, "base64");
|
|
286
|
+
if (key.length === 0) throw new WebhookVerificationError("Invalid webhook signing secret");
|
|
287
|
+
return key;
|
|
288
|
+
}
|
|
289
|
+
function rawBody(payload) {
|
|
290
|
+
if (typeof payload === "string") return Buffer.from(payload, "utf8");
|
|
291
|
+
if (payload instanceof Uint8Array) return Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength);
|
|
292
|
+
throw new WebhookVerificationError(
|
|
293
|
+
"Pass the raw request body (string or Buffer), not parsed JSON: re-serializing changes the bytes and breaks the signature"
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
function header(headers, name) {
|
|
297
|
+
if (typeof headers.get === "function") return headers.get(name) ?? void 0;
|
|
298
|
+
const record = headers;
|
|
299
|
+
const key = Object.keys(record).find((candidate) => candidate.toLowerCase() === name);
|
|
300
|
+
const value = key === void 0 ? void 0 : record[key];
|
|
301
|
+
return Array.isArray(value) ? value.join(" ") : value;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// src/client.ts
|
|
305
|
+
var seg = (value) => encodeURIComponent(value);
|
|
306
|
+
var GhostPay = class {
|
|
307
|
+
networks;
|
|
308
|
+
currencies;
|
|
309
|
+
rates;
|
|
310
|
+
balances;
|
|
311
|
+
customers;
|
|
312
|
+
addresses;
|
|
313
|
+
deposits;
|
|
314
|
+
invoices;
|
|
315
|
+
withdrawals;
|
|
316
|
+
webhookEndpoints;
|
|
317
|
+
webhookDeliveries;
|
|
318
|
+
events;
|
|
319
|
+
transactions;
|
|
320
|
+
stats;
|
|
321
|
+
settings;
|
|
322
|
+
checkout;
|
|
323
|
+
webhooks;
|
|
324
|
+
constructor(options) {
|
|
325
|
+
const http = new HttpClient(options);
|
|
326
|
+
const get = (path, query, opts) => http.request({ method: "GET", path, query }, opts);
|
|
327
|
+
const post = (path, body, opts, extra) => http.request({ method: "POST", path, body, ...extra }, opts);
|
|
328
|
+
this.networks = {
|
|
329
|
+
/** Every network, with confirmations and whether deposits/withdrawals are on. */
|
|
330
|
+
list: (opts) => get("/v1/networks", void 0, opts)
|
|
331
|
+
};
|
|
332
|
+
this.currencies = {
|
|
333
|
+
/** Enabled currencies with your minimums and fees. */
|
|
334
|
+
list: (opts) => get("/v1/currencies", void 0, opts)
|
|
335
|
+
};
|
|
336
|
+
this.rates = {
|
|
337
|
+
/** Indicative USD price per currency. */
|
|
338
|
+
list: (opts) => get("/v1/rates", void 0, opts)
|
|
339
|
+
};
|
|
340
|
+
this.balances = {
|
|
341
|
+
/** Available, on-hold and pending balance per currency. */
|
|
342
|
+
list: (opts) => get("/v1/balances", void 0, opts)
|
|
343
|
+
};
|
|
344
|
+
this.customers = {
|
|
345
|
+
/** Create the customer, or update its metadata if `external_id` exists. */
|
|
346
|
+
upsert: (params, opts) => post("/v1/customers", params, opts),
|
|
347
|
+
list: (params = {}, opts) => listResult(http, "/v1/customers", params, opts),
|
|
348
|
+
/** By `cus_…` id or `ext:<external_id>`. */
|
|
349
|
+
get: (customer, opts) => get(`/v1/customers/${seg(customer)}`, void 0, opts),
|
|
350
|
+
getByExternalId: (externalId, opts) => get(`/v1/customers/${seg(`ext:${externalId}`)}`, void 0, opts)
|
|
351
|
+
};
|
|
352
|
+
this.addresses = {
|
|
353
|
+
/** The customer's permanent deposit address for the network's address scope (created on first call; `lastResponse.status` 201). */
|
|
354
|
+
getOrCreate: (params, opts) => post("/v1/addresses", params, opts),
|
|
355
|
+
list: (params = {}, opts) => listResult(http, "/v1/addresses", params, opts),
|
|
356
|
+
/** By `addr_…` id or the on-chain address. */
|
|
357
|
+
get: (address, opts) => get(`/v1/addresses/${seg(address)}`, void 0, opts),
|
|
358
|
+
/** Stop handing this address out; payments to it are still credited. */
|
|
359
|
+
retire: (address, opts) => post(`/v1/addresses/${seg(address)}/retire`, void 0, opts),
|
|
360
|
+
/** Your own addresses for funding your balance, one per address scope; credited with no fees. */
|
|
361
|
+
topUps: (opts) => get("/v1/top-up-addresses", void 0, opts)
|
|
362
|
+
};
|
|
363
|
+
this.deposits = {
|
|
364
|
+
list: (params = {}, opts) => listResult(http, "/v1/deposits", params, opts),
|
|
365
|
+
get: (id, opts) => get(`/v1/deposits/${seg(id)}`, void 0, opts)
|
|
366
|
+
};
|
|
367
|
+
this.invoices = {
|
|
368
|
+
create: (params, opts) => post("/v1/invoices", params, opts),
|
|
369
|
+
list: (params = {}, opts) => listResult(http, "/v1/invoices", params, opts),
|
|
370
|
+
get: (id, opts) => get(`/v1/invoices/${seg(id)}`, void 0, opts),
|
|
371
|
+
/** Only while `NEW`. */
|
|
372
|
+
cancel: (id, opts) => post(`/v1/invoices/${seg(id)}/cancel`, void 0, opts)
|
|
373
|
+
};
|
|
374
|
+
this.withdrawals = {
|
|
375
|
+
/** Fee, total and whether your balance covers it. Creates nothing. */
|
|
376
|
+
quote: (params, opts) => post("/v1/withdrawals/quote", params, opts),
|
|
377
|
+
/**
|
|
378
|
+
* Pays out from your balance. The Idempotency-Key defaults to `withdrawal:<external_id>` when you give an
|
|
379
|
+
* `external_id`, so retrying the same payout (even after a restart) can never pay twice.
|
|
380
|
+
*/
|
|
381
|
+
create: (params, opts = {}) => post("/v1/withdrawals", params, {
|
|
382
|
+
...opts,
|
|
383
|
+
...opts.idempotencyKey === void 0 && params.external_id ? { idempotencyKey: `withdrawal:${params.external_id}` } : {}
|
|
384
|
+
}),
|
|
385
|
+
list: (params = {}, opts) => listResult(http, "/v1/withdrawals", params, opts),
|
|
386
|
+
/** By `wd_…` id or your external id. */
|
|
387
|
+
get: (withdrawal, opts) => get(`/v1/withdrawals/${seg(withdrawal)}`, void 0, opts),
|
|
388
|
+
getByExternalId: (externalId, opts) => get(`/v1/withdrawals/${seg(`ext:${externalId}`)}`, void 0, opts),
|
|
389
|
+
/** Only before it is sent. The hold returns to your available balance. */
|
|
390
|
+
cancel: (withdrawal, opts) => post(`/v1/withdrawals/${seg(withdrawal)}/cancel`, void 0, opts)
|
|
391
|
+
};
|
|
392
|
+
this.webhookEndpoints = {
|
|
393
|
+
/** The response's `secret` is shown only once: store it. Not retried once sent (a retry would create a second endpoint). */
|
|
394
|
+
create: (params, opts) => post("/v1/webhook-endpoints", params, opts, { retryAfterSend: false }),
|
|
395
|
+
list: (params = {}, opts) => listResult(http, "/v1/webhook-endpoints", params, opts),
|
|
396
|
+
get: (id, opts) => get(`/v1/webhook-endpoints/${seg(id)}`, void 0, opts),
|
|
397
|
+
update: (id, params, opts) => http.request({ method: "PATCH", path: `/v1/webhook-endpoints/${seg(id)}`, body: params }, opts),
|
|
398
|
+
delete: (id, opts) => http.request({ method: "DELETE", path: `/v1/webhook-endpoints/${seg(id)}` }, opts),
|
|
399
|
+
/** Sends a `ping` event to this endpoint. */
|
|
400
|
+
test: (id, opts) => post(`/v1/webhook-endpoints/${seg(id)}/test`, void 0, opts),
|
|
401
|
+
/** Re-sends matching events created in `[from, to]` as new deliveries; events already queued for the endpoint are skipped. */
|
|
402
|
+
replay: (id, params, opts) => post(`/v1/webhook-endpoints/${seg(id)}/replay`, params, opts)
|
|
403
|
+
};
|
|
404
|
+
this.webhookDeliveries = {
|
|
405
|
+
list: (params = {}, opts) => listResult(http, "/v1/webhook-deliveries", params, opts),
|
|
406
|
+
/** With every attempt (status code, response body, timing). */
|
|
407
|
+
get: (id, opts) => get(`/v1/webhook-deliveries/${seg(id)}`, void 0, opts),
|
|
408
|
+
/** Re-sends a FAILED delivery's event as a new delivery (returned), retried per the endpoint's `auto_retry`. */
|
|
409
|
+
retry: (id, opts) => post(`/v1/webhook-deliveries/${seg(id)}/retry`, void 0, opts)
|
|
410
|
+
};
|
|
411
|
+
this.events = {
|
|
412
|
+
/** One page: newest first, or oldest first after `params.after`. */
|
|
413
|
+
list: (params = {}, opts) => get("/v1/events", params, opts),
|
|
414
|
+
get: (id, opts) => get(`/v1/events/${seg(id)}`, void 0, opts),
|
|
415
|
+
/**
|
|
416
|
+
* Every event after `after` (default: from the very first), oldest first, across pages. Store the last id you
|
|
417
|
+
* processed and pass it next time to catch up after downtime.
|
|
418
|
+
*/
|
|
419
|
+
since: (after = "evt_0", params = {}, opts) => http.paginate("/v1/events", { ...params, after }, opts)
|
|
420
|
+
};
|
|
421
|
+
this.transactions = {
|
|
422
|
+
/** Deposits, top-ups, withdrawals and payouts, newest first. */
|
|
423
|
+
list: (params = {}, opts) => listResult(http, "/v1/transactions", params, opts),
|
|
424
|
+
/** With the full deposit or withdrawal and every event about it, including webhook deliveries. */
|
|
425
|
+
get: (id, opts) => get(`/v1/transactions/${seg(id)}`, void 0, opts)
|
|
426
|
+
};
|
|
427
|
+
this.stats = {
|
|
428
|
+
/** Balances and daily volume in USD at current rates (default 30 days). */
|
|
429
|
+
get: (params = {}, opts) => get("/v1/stats", params, opts)
|
|
430
|
+
};
|
|
431
|
+
this.settings = {
|
|
432
|
+
get: (opts) => get("/v1/settings", void 0, opts)
|
|
433
|
+
};
|
|
434
|
+
this.checkout = {
|
|
435
|
+
/** Public: what a payer needs to pay an invoice (no API key needed). */
|
|
436
|
+
get: (invoiceId, opts) => http.request({ method: "GET", path: `/v1/checkout/${seg(invoiceId)}`, auth: false }, opts),
|
|
437
|
+
/** Public: choose the payment currency once, while the invoice is `NEW`. */
|
|
438
|
+
select: (invoiceId, params, opts) => post(`/v1/checkout/${seg(invoiceId)}/select`, params, opts, { auth: false })
|
|
439
|
+
};
|
|
440
|
+
this.webhooks = {
|
|
441
|
+
/** Verify a webhook request and return the typed event (see `Webhook.verify`). */
|
|
442
|
+
verify: (payload, headers, secret, options2) => new Webhook(secret, options2).verify(payload, headers)
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
};
|
|
446
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
447
|
+
0 && (module.exports = {
|
|
448
|
+
GhostPay,
|
|
449
|
+
GhostPayApiError,
|
|
450
|
+
GhostPayConnectionError,
|
|
451
|
+
GhostPayError,
|
|
452
|
+
VERSION,
|
|
453
|
+
Webhook,
|
|
454
|
+
WebhookVerificationError
|
|
455
|
+
});
|
|
456
|
+
//# sourceMappingURL=index.cjs.map
|