@1st-flock/donations-embed-node 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 +21 -0
- package/README.md +236 -0
- package/dist/index.cjs +648 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +381 -0
- package/dist/index.d.ts +381 -0
- package/dist/index.js +625 -0
- package/dist/index.js.map +1 -0
- package/dist/webhooks-DBoxlrQm.d.cts +438 -0
- package/dist/webhooks-DBoxlrQm.d.ts +438 -0
- package/dist/webhooks.cjs +181 -0
- package/dist/webhooks.cjs.map +1 -0
- package/dist/webhooks.d.cts +1 -0
- package/dist/webhooks.d.ts +1 -0
- package/dist/webhooks.js +178 -0
- package/dist/webhooks.js.map +1 -0
- package/package.json +66 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,648 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var crypto = require('crypto');
|
|
4
|
+
var buffer = require('buffer');
|
|
5
|
+
|
|
6
|
+
// src/_const.ts
|
|
7
|
+
var SDK_VERSION = "1.0.0";
|
|
8
|
+
var DEFAULT_BASE_URL = "https://api.1stflock.com";
|
|
9
|
+
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
10
|
+
var DEFAULT_MAX_RETRIES = 3;
|
|
11
|
+
var DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
|
|
12
|
+
var MAX_KEY_LENGTH = 255;
|
|
13
|
+
var USE_CASE_RE = /^[a-z0-9][a-z0-9_\-.]*$/;
|
|
14
|
+
function idempotencyKey(usage) {
|
|
15
|
+
const uuid = crypto.randomUUID();
|
|
16
|
+
if (usage === void 0) {
|
|
17
|
+
return uuid;
|
|
18
|
+
}
|
|
19
|
+
if (typeof usage !== "string" || !USE_CASE_RE.test(usage)) {
|
|
20
|
+
throw new TypeError(
|
|
21
|
+
"idempotency usage must be a non-empty lowercase ASCII tag matching /^[a-z0-9][a-z0-9_\\-.]*$/"
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
const key = `${usage}:${uuid}`;
|
|
25
|
+
if (key.length > MAX_KEY_LENGTH) {
|
|
26
|
+
throw new RangeError(
|
|
27
|
+
`generated idempotency key exceeds ${MAX_KEY_LENGTH} chars`
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
return key;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// src/errors.ts
|
|
34
|
+
var DonationsEmbedError = class extends Error {
|
|
35
|
+
constructor(message) {
|
|
36
|
+
super(message);
|
|
37
|
+
this.name = "DonationsEmbedError";
|
|
38
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
var ApiError = class extends DonationsEmbedError {
|
|
42
|
+
statusCode;
|
|
43
|
+
code;
|
|
44
|
+
message;
|
|
45
|
+
details;
|
|
46
|
+
requestId;
|
|
47
|
+
constructor(statusCode, message, init = {}) {
|
|
48
|
+
const code = init.code ?? null;
|
|
49
|
+
const requestId = init.requestId ?? null;
|
|
50
|
+
const prefix = code !== null ? `[${statusCode} ${code}]` : `[${statusCode}]`;
|
|
51
|
+
const formatted = requestId !== null ? `${prefix} ${message} (request_id=${requestId})` : `${prefix} ${message}`;
|
|
52
|
+
super(message);
|
|
53
|
+
this.name = "ApiError";
|
|
54
|
+
this.statusCode = statusCode;
|
|
55
|
+
this.code = code;
|
|
56
|
+
this.message = message;
|
|
57
|
+
this.details = init.details ?? null;
|
|
58
|
+
this.requestId = requestId;
|
|
59
|
+
Object.defineProperty(this, "_formatted", {
|
|
60
|
+
value: formatted,
|
|
61
|
+
enumerable: false,
|
|
62
|
+
writable: false
|
|
63
|
+
});
|
|
64
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
65
|
+
}
|
|
66
|
+
toString() {
|
|
67
|
+
const formatted = this._formatted;
|
|
68
|
+
return formatted ? `${this.name}: ${formatted}` : super.toString();
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
var AuthError = class extends ApiError {
|
|
72
|
+
constructor(statusCode, message, init) {
|
|
73
|
+
super(statusCode, message, init);
|
|
74
|
+
this.name = "AuthError";
|
|
75
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
var ForbiddenError = class extends ApiError {
|
|
79
|
+
constructor(statusCode, message, init) {
|
|
80
|
+
super(statusCode, message, init);
|
|
81
|
+
this.name = "ForbiddenError";
|
|
82
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
var NotFoundError = class extends ApiError {
|
|
86
|
+
constructor(statusCode, message, init) {
|
|
87
|
+
super(statusCode, message, init);
|
|
88
|
+
this.name = "NotFoundError";
|
|
89
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
var ValidationError = class extends ApiError {
|
|
93
|
+
constructor(statusCode, message, init) {
|
|
94
|
+
super(statusCode, message, init);
|
|
95
|
+
this.name = "ValidationError";
|
|
96
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
var ConflictError = class extends ApiError {
|
|
100
|
+
constructor(statusCode, message, init) {
|
|
101
|
+
super(statusCode, message, init);
|
|
102
|
+
this.name = "ConflictError";
|
|
103
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
var GoneError = class extends ApiError {
|
|
107
|
+
constructor(statusCode, message, init) {
|
|
108
|
+
super(statusCode, message, init);
|
|
109
|
+
this.name = "GoneError";
|
|
110
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
var RateLimitError = class extends ApiError {
|
|
114
|
+
retryAfterSeconds;
|
|
115
|
+
constructor(statusCode, message, init = {}) {
|
|
116
|
+
super(statusCode, message, init);
|
|
117
|
+
this.name = "RateLimitError";
|
|
118
|
+
this.retryAfterSeconds = init.retryAfterSeconds ?? null;
|
|
119
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
var BadGatewayError = class extends ApiError {
|
|
123
|
+
constructor(statusCode, message, init) {
|
|
124
|
+
super(statusCode, message, init);
|
|
125
|
+
this.name = "BadGatewayError";
|
|
126
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
var ServiceUnavailableError = class extends ApiError {
|
|
130
|
+
constructor(statusCode, message, init) {
|
|
131
|
+
super(statusCode, message, init);
|
|
132
|
+
this.name = "ServiceUnavailableError";
|
|
133
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
var WebhookError = class extends DonationsEmbedError {
|
|
137
|
+
constructor(message) {
|
|
138
|
+
super(message);
|
|
139
|
+
this.name = "WebhookError";
|
|
140
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
var WebhookSignatureError = class extends WebhookError {
|
|
144
|
+
constructor(message) {
|
|
145
|
+
super(message);
|
|
146
|
+
this.name = "WebhookSignatureError";
|
|
147
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
var WebhookTimestampError = class extends WebhookError {
|
|
151
|
+
constructor(message) {
|
|
152
|
+
super(message);
|
|
153
|
+
this.name = "WebhookTimestampError";
|
|
154
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
var WebhookFormatError = class extends WebhookError {
|
|
158
|
+
constructor(message) {
|
|
159
|
+
super(message);
|
|
160
|
+
this.name = "WebhookFormatError";
|
|
161
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
// src/_http.ts
|
|
166
|
+
var RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([500, 502, 503, 504]);
|
|
167
|
+
function buildUserAgent() {
|
|
168
|
+
const nodeVersion = process.versions.node;
|
|
169
|
+
return `@1st-flock/donations-embed-node/${SDK_VERSION} node/${nodeVersion}`;
|
|
170
|
+
}
|
|
171
|
+
function buildQueryString(query) {
|
|
172
|
+
if (!query) return "";
|
|
173
|
+
const params = new URLSearchParams();
|
|
174
|
+
for (const [k, v] of Object.entries(query)) {
|
|
175
|
+
if (v === null || v === void 0) continue;
|
|
176
|
+
params.append(k, String(v));
|
|
177
|
+
}
|
|
178
|
+
const s = params.toString();
|
|
179
|
+
return s.length === 0 ? "" : `?${s}`;
|
|
180
|
+
}
|
|
181
|
+
function parseRetryAfter(value) {
|
|
182
|
+
if (value === null) return null;
|
|
183
|
+
const n = Number.parseFloat(value.trim());
|
|
184
|
+
return Number.isFinite(n) ? n : null;
|
|
185
|
+
}
|
|
186
|
+
function sleep(delayMs) {
|
|
187
|
+
return new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
188
|
+
}
|
|
189
|
+
function backoffDelayMs(attempt) {
|
|
190
|
+
const base = Math.min(2e4, 250 * 2 ** (attempt - 1));
|
|
191
|
+
return base / 2 + Math.random() * (base / 2);
|
|
192
|
+
}
|
|
193
|
+
var HttpTransport = class {
|
|
194
|
+
apiKey;
|
|
195
|
+
baseUrl;
|
|
196
|
+
fetchFn;
|
|
197
|
+
maxRetries;
|
|
198
|
+
timeoutMs;
|
|
199
|
+
logger;
|
|
200
|
+
userAgent;
|
|
201
|
+
constructor(opts) {
|
|
202
|
+
this.apiKey = opts.apiKey;
|
|
203
|
+
this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
204
|
+
this.fetchFn = opts.fetch ?? globalThis.fetch;
|
|
205
|
+
if (typeof this.fetchFn !== "function") {
|
|
206
|
+
throw new Error(
|
|
207
|
+
"global fetch is unavailable; pass `fetch` explicitly or run on Node 18+"
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
this.maxRetries = opts.maxRetries ?? DEFAULT_MAX_RETRIES;
|
|
211
|
+
this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
212
|
+
this.logger = opts.logger ?? { debug: () => void 0 };
|
|
213
|
+
this.userAgent = buildUserAgent();
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Send a request and return the parsed JSON response body.
|
|
217
|
+
*
|
|
218
|
+
* Returns `null` for `204 No Content`; throws a typed
|
|
219
|
+
* {@link ApiError} subclass on every non-2xx status code that
|
|
220
|
+
* survives the retry policy.
|
|
221
|
+
*/
|
|
222
|
+
async request(opts) {
|
|
223
|
+
const url = `${this.baseUrl}${opts.path}${buildQueryString(opts.query)}`;
|
|
224
|
+
const headers = this.buildHeaders(
|
|
225
|
+
opts.idempotencyKey,
|
|
226
|
+
opts.body !== void 0
|
|
227
|
+
);
|
|
228
|
+
const bodyJson = opts.body !== void 0 ? JSON.stringify(opts.body) : void 0;
|
|
229
|
+
let lastResponse = null;
|
|
230
|
+
let attempt = 0;
|
|
231
|
+
const totalAttempts = Math.max(1, this.maxRetries + 1);
|
|
232
|
+
while (attempt < totalAttempts) {
|
|
233
|
+
attempt += 1;
|
|
234
|
+
try {
|
|
235
|
+
const res = await this.sendOnce(url, opts.method, headers, bodyJson);
|
|
236
|
+
lastResponse = res;
|
|
237
|
+
if (RETRYABLE_STATUS_CODES.has(res.status)) {
|
|
238
|
+
if (attempt < totalAttempts) {
|
|
239
|
+
const delay = backoffDelayMs(attempt);
|
|
240
|
+
this.logger.debug(
|
|
241
|
+
`donations-embed: retrying ${opts.method} ${opts.path} after ${res.status} (attempt ${attempt})`
|
|
242
|
+
);
|
|
243
|
+
await sleep(delay);
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
if (res.status >= 400) {
|
|
248
|
+
throw await this.buildErrorFromResponse(res);
|
|
249
|
+
}
|
|
250
|
+
return await this.parseResponseBody(res);
|
|
251
|
+
} catch (err) {
|
|
252
|
+
if (err instanceof ApiError) throw err;
|
|
253
|
+
if (attempt < totalAttempts) {
|
|
254
|
+
const delay = backoffDelayMs(attempt);
|
|
255
|
+
this.logger.debug(
|
|
256
|
+
`donations-embed: retrying ${opts.method} ${opts.path} after transport error (attempt ${attempt}): ${err.message}`
|
|
257
|
+
);
|
|
258
|
+
await sleep(delay);
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
throw err;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (lastResponse !== null) {
|
|
265
|
+
throw await this.buildErrorFromResponse(lastResponse);
|
|
266
|
+
}
|
|
267
|
+
throw new ApiError(0, "request did not produce a response");
|
|
268
|
+
}
|
|
269
|
+
buildHeaders(idempotencyKey2, hasBody) {
|
|
270
|
+
const headers = {
|
|
271
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
272
|
+
"User-Agent": this.userAgent,
|
|
273
|
+
Accept: "application/json"
|
|
274
|
+
};
|
|
275
|
+
if (hasBody) {
|
|
276
|
+
headers["Content-Type"] = "application/json";
|
|
277
|
+
}
|
|
278
|
+
if (idempotencyKey2 !== void 0) {
|
|
279
|
+
headers["Idempotency-Key"] = idempotencyKey2;
|
|
280
|
+
}
|
|
281
|
+
return headers;
|
|
282
|
+
}
|
|
283
|
+
async sendOnce(url, method, headers, body) {
|
|
284
|
+
const controller = new AbortController();
|
|
285
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
286
|
+
try {
|
|
287
|
+
return await this.fetchFn(url, {
|
|
288
|
+
method,
|
|
289
|
+
headers,
|
|
290
|
+
body,
|
|
291
|
+
signal: controller.signal
|
|
292
|
+
});
|
|
293
|
+
} finally {
|
|
294
|
+
clearTimeout(timer);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
async parseResponseBody(res) {
|
|
298
|
+
if (res.status === 204) return null;
|
|
299
|
+
const text = await res.text();
|
|
300
|
+
if (text.length === 0) return null;
|
|
301
|
+
try {
|
|
302
|
+
return JSON.parse(text);
|
|
303
|
+
} catch (err) {
|
|
304
|
+
throw new ApiError(
|
|
305
|
+
res.status,
|
|
306
|
+
`response body did not parse as JSON: ${err.message}`,
|
|
307
|
+
{ requestId: res.headers.get("x-request-id") }
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
/** Map a 4xx / 5xx response onto the right {@link ApiError} subclass. */
|
|
312
|
+
async buildErrorFromResponse(res) {
|
|
313
|
+
const requestId = res.headers.get("x-request-id");
|
|
314
|
+
const retryAfter = parseRetryAfter(res.headers.get("retry-after"));
|
|
315
|
+
let code = null;
|
|
316
|
+
let message = res.statusText || `HTTP ${res.status}`;
|
|
317
|
+
let details = null;
|
|
318
|
+
try {
|
|
319
|
+
const text = await res.text();
|
|
320
|
+
if (text.length > 0) {
|
|
321
|
+
const payload = JSON.parse(text);
|
|
322
|
+
if (typeof payload === "object" && payload !== null) {
|
|
323
|
+
if (typeof payload.code === "string") code = payload.code;
|
|
324
|
+
if (typeof payload.message === "string") message = payload.message;
|
|
325
|
+
const rawDetails = payload.details;
|
|
326
|
+
if (typeof rawDetails === "object" && rawDetails !== null && !Array.isArray(rawDetails)) {
|
|
327
|
+
details = rawDetails;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
} catch {
|
|
332
|
+
}
|
|
333
|
+
const init = { code, details, requestId };
|
|
334
|
+
const status = res.status;
|
|
335
|
+
switch (status) {
|
|
336
|
+
case 401:
|
|
337
|
+
return new AuthError(status, message, init);
|
|
338
|
+
case 403:
|
|
339
|
+
return new ForbiddenError(status, message, init);
|
|
340
|
+
case 404:
|
|
341
|
+
return new NotFoundError(status, message, init);
|
|
342
|
+
case 400:
|
|
343
|
+
case 422:
|
|
344
|
+
return new ValidationError(status, message, init);
|
|
345
|
+
case 409:
|
|
346
|
+
return new ConflictError(status, message, init);
|
|
347
|
+
case 410:
|
|
348
|
+
return new GoneError(status, message, init);
|
|
349
|
+
case 429:
|
|
350
|
+
return new RateLimitError(status, message, {
|
|
351
|
+
...init,
|
|
352
|
+
retryAfterSeconds: retryAfter
|
|
353
|
+
});
|
|
354
|
+
case 502:
|
|
355
|
+
return new BadGatewayError(status, message, init);
|
|
356
|
+
case 503:
|
|
357
|
+
return new ServiceUnavailableError(status, message, init);
|
|
358
|
+
default:
|
|
359
|
+
return new ApiError(status, message, init);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
// src/client.ts
|
|
365
|
+
function validateSecretKeyFormat(apiKey) {
|
|
366
|
+
if (typeof apiKey !== "string" || apiKey.length === 0) {
|
|
367
|
+
throw new TypeError("apiKey must be a non-empty string");
|
|
368
|
+
}
|
|
369
|
+
if (!apiKey.startsWith("sk_live_") && !apiKey.startsWith("sk_test_")) {
|
|
370
|
+
throw new TypeError(
|
|
371
|
+
"apiKey must be a secret key (sk_live_\u2026 or sk_test_\u2026); publishable keys (pk_\u2026) are browser-only and not accepted server-side"
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
var Client = class {
|
|
376
|
+
transport;
|
|
377
|
+
constructor(options) {
|
|
378
|
+
validateSecretKeyFormat(options.apiKey);
|
|
379
|
+
this.transport = new HttpTransport({
|
|
380
|
+
apiKey: options.apiKey,
|
|
381
|
+
baseUrl: options.baseUrl,
|
|
382
|
+
fetch: options.fetch,
|
|
383
|
+
maxRetries: options.retries,
|
|
384
|
+
timeoutMs: options.timeout,
|
|
385
|
+
logger: options.logger
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
// ---------------------------------------------------------------- donations
|
|
389
|
+
/**
|
|
390
|
+
* List donations, ordered `(created_at DESC, id DESC)`.
|
|
391
|
+
*
|
|
392
|
+
* @param params - Optional cursor / limit / fund / donor filters.
|
|
393
|
+
* @returns A page of donations plus an optional `next_cursor`.
|
|
394
|
+
*/
|
|
395
|
+
listDonations(params = {}) {
|
|
396
|
+
return this.transport.request({
|
|
397
|
+
method: "GET",
|
|
398
|
+
path: "/v1/embed/donations",
|
|
399
|
+
query: {
|
|
400
|
+
cursor: params.cursor,
|
|
401
|
+
limit: params.limit,
|
|
402
|
+
fund_id: params.fundId,
|
|
403
|
+
donor_email: params.donorEmail
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Fetch a single donation by ID.
|
|
409
|
+
*
|
|
410
|
+
* Cross-organization access collapses to `404` (raises
|
|
411
|
+
* {@link NotFoundError}).
|
|
412
|
+
*/
|
|
413
|
+
getDonation(donationId) {
|
|
414
|
+
return this.transport.request({
|
|
415
|
+
method: "GET",
|
|
416
|
+
path: `/v1/embed/donations/${encodeURIComponent(donationId)}`
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
/**
|
|
420
|
+
* Refund a donation in full or part.
|
|
421
|
+
*
|
|
422
|
+
* @param donationId - The donation to refund.
|
|
423
|
+
* @param params - Optional amount + reason.
|
|
424
|
+
* @param options - Optional idempotency key (use
|
|
425
|
+
* {@link idempotencyKey} to generate one tagged with a use-case
|
|
426
|
+
* prefix).
|
|
427
|
+
* @returns The {@link RefundResponse} describing the issued refund.
|
|
428
|
+
* Idempotent replays return the original response without
|
|
429
|
+
* re-contacting the gateway.
|
|
430
|
+
*/
|
|
431
|
+
refundDonation(donationId, params = {}, options = {}) {
|
|
432
|
+
const body = {};
|
|
433
|
+
if (params.amountCents !== void 0) {
|
|
434
|
+
body.amount_cents = params.amountCents;
|
|
435
|
+
}
|
|
436
|
+
if (params.reason !== void 0) {
|
|
437
|
+
body.reason = params.reason;
|
|
438
|
+
}
|
|
439
|
+
return this.transport.request({
|
|
440
|
+
method: "POST",
|
|
441
|
+
path: `/v1/embed/donations/${encodeURIComponent(donationId)}/refund`,
|
|
442
|
+
body,
|
|
443
|
+
idempotencyKey: options.idempotencyKey
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
// ----------------------------------------------------------------- recurring
|
|
447
|
+
/**
|
|
448
|
+
* List recurring schedules, ordered `(created_at DESC, id DESC)`.
|
|
449
|
+
*
|
|
450
|
+
* @returns A page of recurring schedules plus an optional `next_cursor`.
|
|
451
|
+
*/
|
|
452
|
+
listRecurring(params = {}) {
|
|
453
|
+
return this.transport.request({
|
|
454
|
+
method: "GET",
|
|
455
|
+
path: "/v1/embed/recurring",
|
|
456
|
+
query: {
|
|
457
|
+
cursor: params.cursor,
|
|
458
|
+
limit: params.limit,
|
|
459
|
+
status: params.status
|
|
460
|
+
}
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Cancel a recurring schedule.
|
|
465
|
+
*
|
|
466
|
+
* Idempotent: a second call against an already-cancelled schedule
|
|
467
|
+
* returns `already_cancelled: true` without re-emitting a webhook.
|
|
468
|
+
*/
|
|
469
|
+
cancelRecurring(recurringId, options = {}) {
|
|
470
|
+
return this.transport.request({
|
|
471
|
+
method: "POST",
|
|
472
|
+
path: `/v1/embed/recurring/${encodeURIComponent(recurringId)}/cancel`,
|
|
473
|
+
idempotencyKey: options.idempotencyKey
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
// ------------------------------------------------------------------ webhooks
|
|
477
|
+
/**
|
|
478
|
+
* Queue a synthetic webhook event for delivery.
|
|
479
|
+
*
|
|
480
|
+
* The synthetic event's `data.object.synthetic` flag is set so
|
|
481
|
+
* downstream code can branch on it during integration testing.
|
|
482
|
+
*
|
|
483
|
+
* @param eventType - Which event type to fire. Defaults to
|
|
484
|
+
* `"donation.created"`.
|
|
485
|
+
*/
|
|
486
|
+
testWebhook(eventType = "donation.created") {
|
|
487
|
+
return this.transport.request({
|
|
488
|
+
method: "POST",
|
|
489
|
+
path: "/v1/embed/webhooks/test",
|
|
490
|
+
body: { event_type: eventType }
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
};
|
|
494
|
+
|
|
495
|
+
// src/models/events.ts
|
|
496
|
+
var WEBHOOK_EVENT_TYPES = [
|
|
497
|
+
"donation.created",
|
|
498
|
+
"donation.completed",
|
|
499
|
+
"donation.failed",
|
|
500
|
+
"donation.refunded",
|
|
501
|
+
"recurring.activated",
|
|
502
|
+
"recurring.payment_succeeded",
|
|
503
|
+
"recurring.payment_failed",
|
|
504
|
+
"recurring.cancelled",
|
|
505
|
+
"key.frozen"
|
|
506
|
+
];
|
|
507
|
+
function isWebhookEvent(value) {
|
|
508
|
+
if (typeof value !== "object" || value === null) return false;
|
|
509
|
+
const v = value;
|
|
510
|
+
if (typeof v.id !== "string") return false;
|
|
511
|
+
if (typeof v.created !== "number") return false;
|
|
512
|
+
if (typeof v.live_mode !== "boolean") return false;
|
|
513
|
+
if (typeof v.type !== "string") return false;
|
|
514
|
+
if (!WEBHOOK_EVENT_TYPES.includes(v.type)) return false;
|
|
515
|
+
if (typeof v.data !== "object" || v.data === null) return false;
|
|
516
|
+
const data = v.data;
|
|
517
|
+
if (typeof data.object !== "object" || data.object === null) return false;
|
|
518
|
+
return true;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// src/webhooks.ts
|
|
522
|
+
function parseSignatureHeader(header) {
|
|
523
|
+
if (!header) {
|
|
524
|
+
throw new WebhookFormatError("Flock-Signature header is missing or empty");
|
|
525
|
+
}
|
|
526
|
+
let timestamp = null;
|
|
527
|
+
const digests = [];
|
|
528
|
+
for (const raw of header.split(",")) {
|
|
529
|
+
const part = raw.trim();
|
|
530
|
+
if (part.startsWith("t=")) {
|
|
531
|
+
const tsRaw = part.slice(2);
|
|
532
|
+
if (!/^\d+$/.test(tsRaw)) {
|
|
533
|
+
throw new WebhookFormatError(
|
|
534
|
+
`timestamp segment in Flock-Signature is not an integer: ${JSON.stringify(part)}`
|
|
535
|
+
);
|
|
536
|
+
}
|
|
537
|
+
timestamp = Number.parseInt(tsRaw, 10);
|
|
538
|
+
} else if (part.startsWith("v1=")) {
|
|
539
|
+
const digest = part.slice(3);
|
|
540
|
+
if (!/^[0-9a-f]{64}$/.test(digest)) {
|
|
541
|
+
throw new WebhookFormatError(
|
|
542
|
+
`v1 signature segment is not a 64-char hex digest: ${JSON.stringify(part)}`
|
|
543
|
+
);
|
|
544
|
+
}
|
|
545
|
+
digests.push(digest);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
if (timestamp === null) {
|
|
549
|
+
throw new WebhookFormatError(
|
|
550
|
+
"Flock-Signature is missing the required t=<unix_ts> segment"
|
|
551
|
+
);
|
|
552
|
+
}
|
|
553
|
+
if (digests.length === 0) {
|
|
554
|
+
throw new WebhookFormatError("Flock-Signature has no v1=<hex> segments");
|
|
555
|
+
}
|
|
556
|
+
return { timestamp, digests };
|
|
557
|
+
}
|
|
558
|
+
function computeExpected(secret, timestamp, body) {
|
|
559
|
+
const hmac = crypto.createHmac("sha256", secret);
|
|
560
|
+
hmac.update(`${timestamp}.`, "utf8");
|
|
561
|
+
hmac.update(body);
|
|
562
|
+
return hmac.digest("hex");
|
|
563
|
+
}
|
|
564
|
+
function constantTimeEqualHex(a, b) {
|
|
565
|
+
if (a.length !== b.length) return false;
|
|
566
|
+
const aBuf = buffer.Buffer.from(a, "utf8");
|
|
567
|
+
const bBuf = buffer.Buffer.from(b, "utf8");
|
|
568
|
+
return crypto.timingSafeEqual(aBuf, bBuf);
|
|
569
|
+
}
|
|
570
|
+
function coerceBody(body) {
|
|
571
|
+
if (typeof body === "string") {
|
|
572
|
+
return buffer.Buffer.from(body, "utf8");
|
|
573
|
+
}
|
|
574
|
+
return body;
|
|
575
|
+
}
|
|
576
|
+
function verifyWebhook(body, signature, secret, options = {}) {
|
|
577
|
+
const tolerance = options.toleranceSeconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS;
|
|
578
|
+
if (typeof secret !== "string" || secret.length === 0) {
|
|
579
|
+
throw new WebhookFormatError("secret must be a non-empty string");
|
|
580
|
+
}
|
|
581
|
+
const { timestamp, digests } = parseSignatureHeader(signature);
|
|
582
|
+
const current = options.now ?? Date.now() / 1e3;
|
|
583
|
+
if (Math.abs(current - timestamp) > tolerance) {
|
|
584
|
+
throw new WebhookTimestampError(
|
|
585
|
+
`webhook timestamp ${timestamp} is outside the ${tolerance}s tolerance (current=${Math.floor(current)})`
|
|
586
|
+
);
|
|
587
|
+
}
|
|
588
|
+
const bodyBytes = coerceBody(body);
|
|
589
|
+
const expected = computeExpected(secret, timestamp, bodyBytes);
|
|
590
|
+
let matched = false;
|
|
591
|
+
for (const d of digests) {
|
|
592
|
+
if (constantTimeEqualHex(expected, d)) {
|
|
593
|
+
matched = true;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
if (!matched) {
|
|
597
|
+
throw new WebhookSignatureError(
|
|
598
|
+
"webhook signature did not match \u2014 wrong secret or tampered body"
|
|
599
|
+
);
|
|
600
|
+
}
|
|
601
|
+
let decoded;
|
|
602
|
+
try {
|
|
603
|
+
decoded = buffer.Buffer.from(bodyBytes).toString("utf8");
|
|
604
|
+
} catch (err) {
|
|
605
|
+
throw new WebhookFormatError(
|
|
606
|
+
`webhook body is not valid UTF-8: ${err.message}`
|
|
607
|
+
);
|
|
608
|
+
}
|
|
609
|
+
let payload;
|
|
610
|
+
try {
|
|
611
|
+
payload = JSON.parse(decoded);
|
|
612
|
+
} catch (err) {
|
|
613
|
+
throw new WebhookFormatError(
|
|
614
|
+
`webhook body did not parse as JSON: ${err.message}`
|
|
615
|
+
);
|
|
616
|
+
}
|
|
617
|
+
if (!isWebhookEvent(payload)) {
|
|
618
|
+
throw new WebhookFormatError(
|
|
619
|
+
"webhook body did not match any known event schema"
|
|
620
|
+
);
|
|
621
|
+
}
|
|
622
|
+
return payload;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
exports.ApiError = ApiError;
|
|
626
|
+
exports.AuthError = AuthError;
|
|
627
|
+
exports.BadGatewayError = BadGatewayError;
|
|
628
|
+
exports.Client = Client;
|
|
629
|
+
exports.ConflictError = ConflictError;
|
|
630
|
+
exports.DEFAULT_WEBHOOK_TOLERANCE_SECONDS = DEFAULT_WEBHOOK_TOLERANCE_SECONDS;
|
|
631
|
+
exports.DonationsEmbedError = DonationsEmbedError;
|
|
632
|
+
exports.ForbiddenError = ForbiddenError;
|
|
633
|
+
exports.GoneError = GoneError;
|
|
634
|
+
exports.NotFoundError = NotFoundError;
|
|
635
|
+
exports.RateLimitError = RateLimitError;
|
|
636
|
+
exports.ServiceUnavailableError = ServiceUnavailableError;
|
|
637
|
+
exports.VERSION = SDK_VERSION;
|
|
638
|
+
exports.ValidationError = ValidationError;
|
|
639
|
+
exports.WEBHOOK_EVENT_TYPES = WEBHOOK_EVENT_TYPES;
|
|
640
|
+
exports.WebhookError = WebhookError;
|
|
641
|
+
exports.WebhookFormatError = WebhookFormatError;
|
|
642
|
+
exports.WebhookSignatureError = WebhookSignatureError;
|
|
643
|
+
exports.WebhookTimestampError = WebhookTimestampError;
|
|
644
|
+
exports.idempotencyKey = idempotencyKey;
|
|
645
|
+
exports.isWebhookEvent = isWebhookEvent;
|
|
646
|
+
exports.verifyWebhook = verifyWebhook;
|
|
647
|
+
//# sourceMappingURL=index.cjs.map
|
|
648
|
+
//# sourceMappingURL=index.cjs.map
|