better-auth-streampay 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.
package/dist/index.cjs ADDED
@@ -0,0 +1,878 @@
1
+ 'use strict';
2
+
3
+ var api = require('better-auth/api');
4
+ var zod = require('zod');
5
+ var crypto = require('crypto');
6
+
7
+ // src/plugins/checkout.ts
8
+
9
+ // src/utils/consumer.ts
10
+ async function findConsumerByExternalId(client, { externalId, maxPages = 10, pageSize = 100 }) {
11
+ const hit = await scanConsumers(
12
+ client,
13
+ { maxPages, pageSize },
14
+ (c) => c.external_id === externalId
15
+ );
16
+ return hit?.id ?? null;
17
+ }
18
+ async function findConsumerByIdentifiers(client, identifiers, opts = {}) {
19
+ const { maxPages = 10, pageSize = 100 } = opts;
20
+ return scanConsumers(client, { maxPages, pageSize }, (c) => matchesAnyIdentifier(c, identifiers));
21
+ }
22
+ function matchesAnyIdentifier(consumer, identifiers) {
23
+ if (identifiers.email && consumer.email === identifiers.email) return true;
24
+ if (identifiers.phone_number && consumer.phone_number === identifiers.phone_number) {
25
+ return true;
26
+ }
27
+ if (identifiers.external_id && consumer.external_id === identifiers.external_id) {
28
+ return true;
29
+ }
30
+ if (identifiers.iban && consumer.iban === identifiers.iban) return true;
31
+ return false;
32
+ }
33
+ async function scanConsumers(client, { maxPages, pageSize }, predicate) {
34
+ for (let page = 1; page <= maxPages; page++) {
35
+ const response = await client.listConsumers({ page, size: pageSize });
36
+ const items = response.data ?? [];
37
+ const hit = items.find(predicate);
38
+ if (hit) return hit;
39
+ const total = response.pagination?.total_count ?? 0;
40
+ if (items.length < pageSize || page * pageSize >= total) return null;
41
+ }
42
+ return null;
43
+ }
44
+
45
+ // src/utils/session.ts
46
+ function asSessionUser(user) {
47
+ if (user === null || typeof user !== "object") return null;
48
+ if (!("id" in user) || typeof user.id !== "string") return null;
49
+ const result = { id: user.id };
50
+ if ("email" in user && typeof user.email === "string") {
51
+ result.email = user.email;
52
+ }
53
+ if ("name" in user && typeof user.name === "string") {
54
+ result.name = user.name;
55
+ }
56
+ if ("isAnonymous" in user && user.isAnonymous === true) {
57
+ result.isAnonymous = true;
58
+ }
59
+ if ("streampayConsumerId" in user) {
60
+ const value = user.streampayConsumerId;
61
+ if (typeof value === "string") {
62
+ result.streampayConsumerId = value;
63
+ } else if (value === null) {
64
+ result.streampayConsumerId = null;
65
+ }
66
+ }
67
+ return result;
68
+ }
69
+
70
+ // src/plugins/checkout.ts
71
+ var RelativeOrAbsoluteUrl = zod.z.string().refine((val) => val.startsWith("/") || URL.canParse(val), {
72
+ message: "Must be a valid URL or a relative path starting with /"
73
+ });
74
+ var CheckoutBody = zod.z.object({
75
+ products: zod.z.union([
76
+ zod.z.array(
77
+ zod.z.object({
78
+ productId: zod.z.string().uuid(),
79
+ quantity: zod.z.number().int().positive().optional()
80
+ })
81
+ ),
82
+ zod.z.array(zod.z.string().uuid()),
83
+ zod.z.string().uuid()
84
+ ]).optional(),
85
+ slug: zod.z.string().optional(),
86
+ referenceId: zod.z.string().optional(),
87
+ consumerId: zod.z.string().uuid().optional(),
88
+ name: zod.z.string().min(1).optional(),
89
+ description: zod.z.string().optional(),
90
+ metadata: zod.z.record(zod.z.string(), zod.z.union([zod.z.string(), zod.z.number(), zod.z.boolean()])).optional(),
91
+ successUrl: RelativeOrAbsoluteUrl.optional(),
92
+ failureUrl: RelativeOrAbsoluteUrl.optional(),
93
+ maxNumberOfPayments: zod.z.number().int().positive().optional(),
94
+ validUntil: zod.z.string().datetime().optional(),
95
+ /**
96
+ * Coupon UUIDs to apply at the payment-link level. Maps directly to
97
+ * StreamPay's `CreatePaymentLinkDto.coupons`. Per-item coupons are
98
+ * not yet exposed — add them when an integrator needs them.
99
+ */
100
+ couponIds: zod.z.array(zod.z.string().uuid()).optional(),
101
+ redirect: zod.z.coerce.boolean().optional()
102
+ });
103
+ function buildItem(productId, quantity) {
104
+ return {
105
+ product_id: productId,
106
+ quantity,
107
+ allow_custom_quantity: false
108
+ };
109
+ }
110
+ async function resolveProducts(body, options) {
111
+ if (body.slug) {
112
+ const pool = typeof options.products === "function" ? await options.products() : options.products;
113
+ const hit = pool?.find((p) => p.slug === body.slug);
114
+ if (!hit) {
115
+ throw new api.APIError("BAD_REQUEST", {
116
+ message: `Unknown product slug: ${body.slug}`
117
+ });
118
+ }
119
+ return [buildItem(hit.productId, 1)];
120
+ }
121
+ if (body.products === void 0) {
122
+ throw new api.APIError("BAD_REQUEST", {
123
+ message: "Either `slug` or `products` is required."
124
+ });
125
+ }
126
+ if (typeof body.products === "string") {
127
+ return [buildItem(body.products, 1)];
128
+ }
129
+ if (body.products.length === 0) {
130
+ throw new api.APIError("BAD_REQUEST", {
131
+ message: "`products` must contain at least one item."
132
+ });
133
+ }
134
+ return body.products.map(
135
+ (entry) => typeof entry === "string" ? buildItem(entry, 1) : buildItem(entry.productId, entry.quantity ?? 1)
136
+ );
137
+ }
138
+ function resolveRedirectUrl(urlOrPath, request, baseURL) {
139
+ if (!urlOrPath) return void 0;
140
+ return new URL(urlOrPath, request?.url ?? baseURL).toString();
141
+ }
142
+ async function resolveConsumerId(client, body, user) {
143
+ if (body.consumerId) return body.consumerId;
144
+ if (!user) return null;
145
+ if (user.streampayConsumerId) return user.streampayConsumerId;
146
+ return findConsumerByExternalId(client, { externalId: user.id });
147
+ }
148
+ var checkout = (checkoutOptions = {}) => (client) => {
149
+ return {
150
+ checkout: api.createAuthEndpoint(
151
+ "/checkout",
152
+ {
153
+ method: "POST",
154
+ body: CheckoutBody
155
+ },
156
+ async (ctx) => {
157
+ const session = await api.getSessionFromCtx(ctx);
158
+ const sessionUser = asSessionUser(session?.user);
159
+ if (checkoutOptions.authenticatedUsersOnly) {
160
+ if (!sessionUser) {
161
+ throw new api.APIError("UNAUTHORIZED", {
162
+ message: "You must be logged in to checkout."
163
+ });
164
+ }
165
+ if (sessionUser.isAnonymous) {
166
+ throw new api.APIError("UNAUTHORIZED", {
167
+ message: "Anonymous users cannot checkout."
168
+ });
169
+ }
170
+ }
171
+ const items = await resolveProducts(ctx.body, checkoutOptions);
172
+ const consumerId = await resolveConsumerId(client, ctx.body, sessionUser);
173
+ const successUrl = resolveRedirectUrl(
174
+ ctx.body.successUrl ?? checkoutOptions.successUrl,
175
+ ctx.request,
176
+ ctx.context.baseURL
177
+ );
178
+ const failureUrl = resolveRedirectUrl(
179
+ ctx.body.failureUrl ?? checkoutOptions.failureUrl,
180
+ ctx.request,
181
+ ctx.context.baseURL
182
+ );
183
+ const customMetadata = (() => {
184
+ const base = ctx.body.metadata ?? {};
185
+ const merged = ctx.body.referenceId ? { referenceId: ctx.body.referenceId, ...base } : base;
186
+ return Object.keys(merged).length > 0 ? merged : null;
187
+ })();
188
+ const payload = {
189
+ name: ctx.body.name ?? `Checkout ${(/* @__PURE__ */ new Date()).toISOString()}`,
190
+ description: ctx.body.description ?? null,
191
+ items
192
+ };
193
+ if (consumerId !== null) payload.organization_consumer_id = consumerId;
194
+ if (successUrl) payload.success_redirect_url = successUrl;
195
+ if (failureUrl) payload.failure_redirect_url = failureUrl;
196
+ if (ctx.body.maxNumberOfPayments !== void 0) {
197
+ payload.max_number_of_payments = ctx.body.maxNumberOfPayments;
198
+ }
199
+ if (ctx.body.validUntil !== void 0) {
200
+ payload.valid_until = ctx.body.validUntil;
201
+ }
202
+ if (ctx.body.couponIds && ctx.body.couponIds.length > 0) {
203
+ payload.coupons = ctx.body.couponIds;
204
+ }
205
+ if (customMetadata !== null) payload.custom_metadata = customMetadata;
206
+ if (checkoutOptions.customFields) {
207
+ payload.custom_fields = checkoutOptions.customFields;
208
+ }
209
+ if (checkoutOptions.contactInformationType) {
210
+ payload.contact_information_type = checkoutOptions.contactInformationType;
211
+ }
212
+ try {
213
+ const link = await client.createPaymentLink(payload);
214
+ const url = client.getPaymentUrl(link);
215
+ if (!url) {
216
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
217
+ message: "StreamPay payment link created but no URL was returned."
218
+ });
219
+ }
220
+ return ctx.json({
221
+ url,
222
+ id: link.id ?? null,
223
+ redirect: ctx.body.redirect ?? true
224
+ });
225
+ } catch (err) {
226
+ if (err instanceof api.APIError) throw err;
227
+ const message = err instanceof Error ? err.message : String(err);
228
+ ctx.context.logger.error(`StreamPay checkout creation failed: ${message}`);
229
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
230
+ message: "StreamPay checkout creation failed."
231
+ });
232
+ }
233
+ }
234
+ )
235
+ };
236
+ };
237
+ var PaginationQuery = zod.z.object({
238
+ page: zod.z.coerce.number().int().positive().optional(),
239
+ limit: zod.z.coerce.number().int().positive().max(200).optional()
240
+ }).optional();
241
+ async function requireConsumerId(client, user, maxPages) {
242
+ if (!user) {
243
+ throw new api.APIError("UNAUTHORIZED", { message: "Session user is missing." });
244
+ }
245
+ if (user.streampayConsumerId) return user.streampayConsumerId;
246
+ const resolved = await findConsumerByExternalId(client, {
247
+ externalId: user.id,
248
+ maxPages
249
+ });
250
+ if (!resolved) {
251
+ throw new api.APIError("NOT_FOUND", {
252
+ message: "No StreamPay consumer is linked to this user."
253
+ });
254
+ }
255
+ return resolved;
256
+ }
257
+ function toAPIError(message, err, logger) {
258
+ if (err instanceof api.APIError) throw err;
259
+ const detail = err instanceof Error ? err.message : String(err);
260
+ logger.error(`${message} ${detail}`);
261
+ throw new api.APIError("INTERNAL_SERVER_ERROR", { message });
262
+ }
263
+ function buildPagination(query) {
264
+ const result = {};
265
+ if (query?.page !== void 0) result.page = query.page;
266
+ if (query?.limit !== void 0) result.size = query.limit;
267
+ return result;
268
+ }
269
+ var portal = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
270
+ return {
271
+ state: api.createAuthEndpoint(
272
+ "/consumer/state",
273
+ { method: "GET", use: [api.sessionMiddleware] },
274
+ async (ctx) => {
275
+ const user = asSessionUser(ctx.context.session?.user);
276
+ const consumerId = await requireConsumerId(client, user, consumerLookupMaxPages);
277
+ try {
278
+ const consumer = await client.getConsumer(consumerId);
279
+ return ctx.json(consumer);
280
+ } catch (err) {
281
+ toAPIError("StreamPay getConsumer failed.", err, ctx.context.logger);
282
+ }
283
+ }
284
+ ),
285
+ subscriptions: api.createAuthEndpoint(
286
+ "/consumer/subscriptions/list",
287
+ {
288
+ method: "GET",
289
+ query: PaginationQuery,
290
+ use: [api.sessionMiddleware]
291
+ },
292
+ async (ctx) => {
293
+ const user = asSessionUser(ctx.context.session?.user);
294
+ const consumerId = await requireConsumerId(client, user, consumerLookupMaxPages);
295
+ try {
296
+ const result = await client.listSubscriptions(buildPagination(ctx.query));
297
+ const items = result.data ?? [];
298
+ const filtered = items.filter((s) => s.organization_consumer_id === consumerId);
299
+ return ctx.json({
300
+ data: filtered,
301
+ pagination: result.pagination
302
+ });
303
+ } catch (err) {
304
+ toAPIError("StreamPay listSubscriptions failed.", err, ctx.context.logger);
305
+ }
306
+ }
307
+ ),
308
+ invoices: api.createAuthEndpoint(
309
+ "/consumer/invoices/list",
310
+ {
311
+ method: "GET",
312
+ query: PaginationQuery,
313
+ use: [api.sessionMiddleware]
314
+ },
315
+ async (ctx) => {
316
+ const user = asSessionUser(ctx.context.session?.user);
317
+ const consumerId = await requireConsumerId(client, user, consumerLookupMaxPages);
318
+ try {
319
+ const result = await client.listInvoices(buildPagination(ctx.query));
320
+ const items = result.data ?? [];
321
+ const filtered = items.filter(
322
+ (invoice) => invoice.organization_consumer_id === consumerId
323
+ );
324
+ return ctx.json({ data: filtered, pagination: result.pagination });
325
+ } catch (err) {
326
+ toAPIError("StreamPay listInvoices failed.", err, ctx.context.logger);
327
+ }
328
+ }
329
+ ),
330
+ payments: api.createAuthEndpoint(
331
+ "/consumer/payments/list",
332
+ {
333
+ method: "GET",
334
+ query: zod.z.object({
335
+ page: zod.z.coerce.number().int().positive().optional(),
336
+ limit: zod.z.coerce.number().int().positive().max(200).optional(),
337
+ invoiceId: zod.z.string().uuid().optional()
338
+ }).optional(),
339
+ use: [api.sessionMiddleware]
340
+ },
341
+ async (ctx) => {
342
+ const user = asSessionUser(ctx.context.session?.user);
343
+ await requireConsumerId(client, user, consumerLookupMaxPages);
344
+ const invoiceId = ctx.query?.invoiceId;
345
+ try {
346
+ const params = {};
347
+ if (invoiceId) params.invoice_id = invoiceId;
348
+ const result = await client.listPayments(params);
349
+ return ctx.json(result);
350
+ } catch (err) {
351
+ toAPIError("StreamPay listPayments failed.", err, ctx.context.logger);
352
+ }
353
+ }
354
+ )
355
+ };
356
+ };
357
+ var CancelBody = zod.z.object({
358
+ subscriptionId: zod.z.string().uuid(),
359
+ cancelRelatedInvoices: zod.z.boolean().optional()
360
+ });
361
+ var FreezeBody = zod.z.object({
362
+ subscriptionId: zod.z.string().uuid(),
363
+ freezeStartDatetime: zod.z.string().datetime(),
364
+ freezeEndDatetime: zod.z.string().datetime().nullable().optional(),
365
+ notes: zod.z.string().optional()
366
+ });
367
+ async function assertOwnsSubscription(client, user, subscriptionId, maxPages) {
368
+ if (!user) {
369
+ throw new api.APIError("UNAUTHORIZED", { message: "Session user is missing." });
370
+ }
371
+ const consumerId = user.streampayConsumerId ?? await findConsumerByExternalId(client, { externalId: user.id, maxPages });
372
+ if (!consumerId) {
373
+ throw new api.APIError("NOT_FOUND", {
374
+ message: "No StreamPay consumer is linked to this user."
375
+ });
376
+ }
377
+ const subscription = await client.getSubscription(subscriptionId);
378
+ if (subscription.organization_consumer_id !== consumerId) {
379
+ throw new api.APIError("FORBIDDEN", {
380
+ message: "Subscription does not belong to this user."
381
+ });
382
+ }
383
+ }
384
+ var subscriptions = ({ consumerLookupMaxPages = 10 } = {}) => (client) => {
385
+ return {
386
+ cancelSubscription: api.createAuthEndpoint(
387
+ "/consumer/subscriptions/cancel",
388
+ {
389
+ method: "POST",
390
+ body: CancelBody,
391
+ use: [api.sessionMiddleware]
392
+ },
393
+ async (ctx) => {
394
+ const sessionUser = asSessionUser(ctx.context.session?.user);
395
+ await assertOwnsSubscription(
396
+ client,
397
+ sessionUser,
398
+ ctx.body.subscriptionId,
399
+ consumerLookupMaxPages
400
+ );
401
+ const payload = {
402
+ cancel_related_invoices: ctx.body.cancelRelatedInvoices ?? false
403
+ };
404
+ try {
405
+ const result = await client.cancelSubscription(ctx.body.subscriptionId, payload);
406
+ return ctx.json(result);
407
+ } catch (err) {
408
+ if (err instanceof api.APIError) throw err;
409
+ const message = err instanceof Error ? err.message : String(err);
410
+ ctx.context.logger.error(`StreamPay cancelSubscription failed: ${message}`);
411
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
412
+ message: "Subscription cancellation failed."
413
+ });
414
+ }
415
+ }
416
+ ),
417
+ freezeSubscription: api.createAuthEndpoint(
418
+ "/consumer/subscriptions/freeze",
419
+ {
420
+ method: "POST",
421
+ body: FreezeBody,
422
+ use: [api.sessionMiddleware]
423
+ },
424
+ async (ctx) => {
425
+ const sessionUser = asSessionUser(ctx.context.session?.user);
426
+ await assertOwnsSubscription(
427
+ client,
428
+ sessionUser,
429
+ ctx.body.subscriptionId,
430
+ consumerLookupMaxPages
431
+ );
432
+ const payload = {
433
+ freeze_start_datetime: ctx.body.freezeStartDatetime
434
+ };
435
+ if (ctx.body.freezeEndDatetime !== void 0) {
436
+ payload.freeze_end_datetime = ctx.body.freezeEndDatetime;
437
+ }
438
+ if (ctx.body.notes !== void 0) {
439
+ payload.notes = ctx.body.notes;
440
+ }
441
+ try {
442
+ const result = await client.freezeSubscription(ctx.body.subscriptionId, payload);
443
+ return ctx.json(result);
444
+ } catch (err) {
445
+ if (err instanceof api.APIError) throw err;
446
+ const message = err instanceof Error ? err.message : String(err);
447
+ ctx.context.logger.error(`StreamPay freezeSubscription failed: ${message}`);
448
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
449
+ message: "Subscription freeze failed."
450
+ });
451
+ }
452
+ }
453
+ )
454
+ };
455
+ };
456
+
457
+ // src/webhooks/dispatcher.ts
458
+ var HANDLER_BY_EVENT = {
459
+ PAYMENT_SUCCEEDED: "onPaymentSucceeded",
460
+ PAYMENT_FAILED: "onPaymentFailed",
461
+ PAYMENT_CANCELED: "onPaymentCanceled",
462
+ PAYMENT_REFUNDED: "onPaymentRefunded",
463
+ PAYMENT_MARKED_AS_PAID: "onPaymentMarkedAsPaid",
464
+ INVOICE_CREATED: "onInvoiceCreated",
465
+ INVOICE_SENT: "onInvoiceSent",
466
+ INVOICE_ACCEPTED: "onInvoiceAccepted",
467
+ INVOICE_REJECTED: "onInvoiceRejected",
468
+ INVOICE_COMPLETED: "onInvoiceCompleted",
469
+ INVOICE_CANCELED: "onInvoiceCanceled",
470
+ INVOICE_UPDATED: "onInvoiceUpdated",
471
+ SUBSCRIPTION_CREATED: "onSubscriptionCreated",
472
+ SUBSCRIPTION_ACTIVATED: "onSubscriptionActivated",
473
+ SUBSCRIPTION_INACTIVATED: "onSubscriptionInactivated",
474
+ SUBSCRIPTION_CANCELED: "onSubscriptionCanceled",
475
+ SUBSCRIPTION_FROZEN: "onSubscriptionFrozen",
476
+ SUBSCRIPTION_CYCLE_RENEWAL_FAILED: "onSubscriptionCycleRenewalFailed",
477
+ SUBSCRIPTION_CANCEL_AT_PERIOD_END: "onSubscriptionCancelAtPeriodEnd",
478
+ SUBSCRIPTION_FREEZE_NOW: "onSubscriptionFreezeNow",
479
+ SUBSCRIPTION_UNFREEZE_NOW: "onSubscriptionUnfreezeNow",
480
+ SUBSCRIPTION_UNFREEZE_FUTURE: "onSubscriptionUnfreezeFuture",
481
+ SUBSCRIPTION_FREEZE_CANCEL: "onSubscriptionFreezeCancel",
482
+ PAYMENT_LINK_PAY_ATTEMPT_FAILED: "onPaymentLinkPayAttemptFailed"
483
+ };
484
+ async function dispatchWebhook(payload, handlers) {
485
+ if (handlers.onPayload) await handlers.onPayload(payload);
486
+ const handlerKey = HANDLER_BY_EVENT[payload.event_type];
487
+ if (!handlerKey) return;
488
+ const handler = handlers[handlerKey];
489
+ if (handler) await handler(payload);
490
+ }
491
+ var StreamPayWebhookError = class extends Error {
492
+ reason;
493
+ constructor(reason, message) {
494
+ super(message ?? reason);
495
+ this.name = "StreamPayWebhookError";
496
+ this.reason = reason;
497
+ }
498
+ };
499
+ function parseSignatureHeader(header) {
500
+ const parts = header.split(",");
501
+ let timestamp;
502
+ let signature;
503
+ for (const part of parts) {
504
+ const [key, ...rest] = part.trim().split("=");
505
+ const value = rest.join("=");
506
+ if (key === "t") timestamp = value;
507
+ else if (key === "v1") signature = value;
508
+ }
509
+ if (!timestamp || !signature) return null;
510
+ return { timestamp, signature };
511
+ }
512
+ function hexDecode(hex) {
513
+ if (hex.length === 0 || hex.length % 2 !== 0) return null;
514
+ if (!/^[0-9a-fA-F]+$/.test(hex)) return null;
515
+ return Buffer.from(hex, "hex");
516
+ }
517
+ function verifyWebhook(input) {
518
+ const { secret, rawBody, signatureHeader } = input;
519
+ const toleranceSeconds = input.toleranceSeconds ?? 300;
520
+ const now = input.now ?? (() => Math.floor(Date.now() / 1e3));
521
+ if (!signatureHeader) return { ok: false, reason: "MISSING_HEADER" };
522
+ const parsed = parseSignatureHeader(signatureHeader);
523
+ if (!parsed) return { ok: false, reason: "MALFORMED_HEADER" };
524
+ const ts = Number(parsed.timestamp);
525
+ if (!Number.isFinite(ts) || !Number.isInteger(ts) || ts <= 0) {
526
+ return { ok: false, reason: "INVALID_TIMESTAMP" };
527
+ }
528
+ const delta = Math.abs(now() - ts);
529
+ if (delta > toleranceSeconds) return { ok: false, reason: "EXPIRED" };
530
+ const expected = crypto.createHmac("sha256", secret).update(`${parsed.timestamp}.${rawBody}`).digest();
531
+ const provided = hexDecode(parsed.signature);
532
+ if (!provided || provided.length !== expected.length) {
533
+ return { ok: false, reason: "INVALID_SIGNATURE" };
534
+ }
535
+ if (!crypto.timingSafeEqual(expected, provided)) {
536
+ return { ok: false, reason: "INVALID_SIGNATURE" };
537
+ }
538
+ return { ok: true, timestamp: ts };
539
+ }
540
+ function verifyWebhookOrThrow(input) {
541
+ const result = verifyWebhook(input);
542
+ if (!result.ok) throw new StreamPayWebhookError(result.reason);
543
+ return result.timestamp;
544
+ }
545
+
546
+ // src/plugins/webhooks.ts
547
+ function isStreamPayWebhookPayload(value) {
548
+ if (!value || typeof value !== "object") return false;
549
+ return "event_type" in value && typeof value.event_type === "string";
550
+ }
551
+ function parseWebhookPayload(value) {
552
+ return isStreamPayWebhookPayload(value) ? value : null;
553
+ }
554
+ function toErrorCode(reason) {
555
+ return reason === "MISSING_HEADER" || reason === "INVALID_SIGNATURE" || reason === "EXPIRED" ? "UNAUTHORIZED" : "BAD_REQUEST";
556
+ }
557
+ var webhooks = (options) => (_client) => {
558
+ const { secret, toleranceSeconds, ...handlers } = options;
559
+ return {
560
+ streampayWebhooks: api.createAuthEndpoint(
561
+ "/streampay/webhooks",
562
+ {
563
+ method: "POST",
564
+ metadata: { isAction: false },
565
+ cloneRequest: true
566
+ },
567
+ async (ctx) => {
568
+ if (!secret) {
569
+ ctx.context.logger.error("StreamPay webhook secret is not configured.");
570
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
571
+ message: "StreamPay webhook secret is not configured."
572
+ });
573
+ }
574
+ if (!ctx.request) {
575
+ throw new api.APIError("BAD_REQUEST", { message: "Missing request body." });
576
+ }
577
+ const rawBody = await ctx.request.text();
578
+ const signatureHeader = ctx.request.headers.get("x-webhook-signature");
579
+ try {
580
+ verifyWebhookOrThrow({
581
+ secret,
582
+ rawBody,
583
+ signatureHeader,
584
+ toleranceSeconds: toleranceSeconds ?? 300
585
+ });
586
+ } catch (err) {
587
+ if (err instanceof StreamPayWebhookError) {
588
+ ctx.context.logger.warn(`StreamPay webhook rejected: ${err.reason}`);
589
+ throw new api.APIError(toErrorCode(err.reason), {
590
+ message: `Webhook verification failed: ${err.reason}`
591
+ });
592
+ }
593
+ throw err;
594
+ }
595
+ let parsed;
596
+ try {
597
+ parsed = JSON.parse(rawBody);
598
+ } catch {
599
+ throw new api.APIError("BAD_REQUEST", {
600
+ message: "Webhook body is not valid JSON."
601
+ });
602
+ }
603
+ const payload = parseWebhookPayload(parsed);
604
+ if (!payload) {
605
+ throw new api.APIError("BAD_REQUEST", {
606
+ message: "Webhook body is missing `event_type`."
607
+ });
608
+ }
609
+ try {
610
+ await dispatchWebhook(payload, handlers);
611
+ } catch (err) {
612
+ const message = err instanceof Error ? err.message : String(err);
613
+ ctx.context.logger.error(`StreamPay webhook handler failed: ${message}`);
614
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
615
+ message: "Webhook handler failed. See server logs."
616
+ });
617
+ }
618
+ return ctx.json({ received: true });
619
+ }
620
+ )
621
+ };
622
+ };
623
+
624
+ // src/utils/format-error.ts
625
+ function formatStreamPayError(err) {
626
+ if (!(err instanceof Error)) return String(err);
627
+ if (!("body" in err)) return err.message;
628
+ const { body } = err;
629
+ if (!body || typeof body !== "object") return err.message;
630
+ const envelope = readEnvelopeMessage(body);
631
+ if (envelope !== null) return envelope;
632
+ const validation = readValidationMessage(body);
633
+ if (validation !== null) return validation;
634
+ try {
635
+ return JSON.stringify(body);
636
+ } catch {
637
+ return err.message;
638
+ }
639
+ }
640
+ function readEnvelopeMessage(body) {
641
+ if (!("error" in body) || !body.error || typeof body.error !== "object") {
642
+ return null;
643
+ }
644
+ const error = body.error;
645
+ if ("additional_info" in error && typeof error.additional_info === "string") {
646
+ return error.additional_info;
647
+ }
648
+ if ("message" in error && typeof error.message === "string") {
649
+ return error.message;
650
+ }
651
+ return null;
652
+ }
653
+ function readValidationMessage(body) {
654
+ if (!("detail" in body) || !Array.isArray(body.detail) || body.detail.length === 0) {
655
+ return null;
656
+ }
657
+ return body.detail.map(formatValidationEntry).join("; ");
658
+ }
659
+ function formatValidationEntry(entry) {
660
+ if (!entry || typeof entry !== "object") return String(entry);
661
+ const loc = "loc" in entry && Array.isArray(entry.loc) ? entry.loc.join(".") : "?";
662
+ const msg = "msg" in entry && typeof entry.msg === "string" ? entry.msg : "invalid";
663
+ return `${loc}: ${msg}`;
664
+ }
665
+
666
+ // src/hooks/consumer.ts
667
+ var isAnonymous = (user) => "isAnonymous" in user && user.isAnonymous === true;
668
+ var onBeforeUserCreate = (options) => async (user, context) => {
669
+ if (!context || !options.createConsumerOnSignUp) return void 0;
670
+ if (isAnonymous(user)) return void 0;
671
+ if (!user.email) {
672
+ throw new api.APIError("BAD_REQUEST", {
673
+ message: "StreamPay requires an email address to create a consumer."
674
+ });
675
+ }
676
+ const extras = options.getConsumerCreateParams ? await options.getConsumerCreateParams({ user }) : {};
677
+ const createPayload = {
678
+ name: user.name || user.email,
679
+ email: user.email,
680
+ ...extras
681
+ };
682
+ try {
683
+ const consumer = await options.client.createConsumer(createPayload);
684
+ if (!consumer.id) {
685
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
686
+ message: "StreamPay consumer was created but did not return an id."
687
+ });
688
+ }
689
+ return { data: { streampayConsumerId: consumer.id } };
690
+ } catch (err) {
691
+ if (err instanceof api.APIError) throw err;
692
+ if (isDuplicateConsumerError(err)) {
693
+ const reusedId = await resolveDuplicateConsumer(options, createPayload, context);
694
+ if (reusedId) {
695
+ return { data: { streampayConsumerId: reusedId } };
696
+ }
697
+ }
698
+ throw new api.APIError("INTERNAL_SERVER_ERROR", {
699
+ message: `StreamPay consumer creation failed: ${formatStreamPayError(err)}`
700
+ });
701
+ }
702
+ };
703
+ function isDuplicateConsumerError(err) {
704
+ if (!(err instanceof Error)) return false;
705
+ if (!("body" in err)) return false;
706
+ const { body } = err;
707
+ if (!body || typeof body !== "object") return false;
708
+ if (!("error" in body) || !body.error || typeof body.error !== "object") {
709
+ return false;
710
+ }
711
+ const error = body.error;
712
+ return "code" in error && typeof error.code === "string" && error.code === "DUPLICATE_CONSUMER";
713
+ }
714
+ async function resolveDuplicateConsumer(options, createPayload, context) {
715
+ const identifiers = {
716
+ email: createPayload.email ?? null,
717
+ phone_number: createPayload.phone_number ?? null,
718
+ external_id: createPayload.external_id ?? null,
719
+ iban: createPayload.iban ?? null
720
+ };
721
+ const existing = await findConsumerByIdentifiers(options.client, identifiers);
722
+ if (!existing?.id) {
723
+ return null;
724
+ }
725
+ if (existing.external_id) {
726
+ context.context.logger.error(
727
+ `StreamPay duplicate: consumer ${existing.id} is already linked to external_id=${existing.external_id}`
728
+ );
729
+ throw new api.APIError("CONFLICT", {
730
+ message: "This account cannot be created at this time. Please contact support."
731
+ });
732
+ }
733
+ return existing.id;
734
+ }
735
+ var onAfterUserCreate = (options) => async (user, context) => {
736
+ if (!context || !options.createConsumerOnSignUp) return;
737
+ if (isAnonymous(user)) return;
738
+ const sessionUser = asSessionUser(user);
739
+ if (!sessionUser?.streampayConsumerId) return;
740
+ try {
741
+ await options.client.updateConsumer(sessionUser.streampayConsumerId, {
742
+ external_id: sessionUser.id
743
+ });
744
+ } catch (err) {
745
+ context.context.logger.error(
746
+ `StreamPay consumer external_id link failed: ${formatStreamPayError(err)}`
747
+ );
748
+ }
749
+ };
750
+ var onUserUpdate = (options) => async (user, context) => {
751
+ if (!context || !options.createConsumerOnSignUp) return;
752
+ if (isAnonymous(user)) return;
753
+ const sessionUser = asSessionUser(user);
754
+ if (!sessionUser) return;
755
+ const consumerId = await resolveConsumerId2(options, sessionUser);
756
+ if (!consumerId) return;
757
+ const update = {};
758
+ if (sessionUser.name !== void 0) update.name = sessionUser.name;
759
+ if (sessionUser.email !== void 0) update.email = sessionUser.email;
760
+ try {
761
+ await options.client.updateConsumer(consumerId, update);
762
+ } catch (err) {
763
+ context.context.logger.error(
764
+ `StreamPay consumer update failed: ${formatStreamPayError(err)}`
765
+ );
766
+ }
767
+ };
768
+ var onUserDelete = (options) => async (user, context) => {
769
+ if (!context || !options.createConsumerOnSignUp) return;
770
+ if (isAnonymous(user)) return;
771
+ const sessionUser = asSessionUser(user);
772
+ if (!sessionUser) return;
773
+ const consumerId = await resolveConsumerId2(options, sessionUser);
774
+ if (!consumerId) return;
775
+ try {
776
+ await options.client.deleteConsumer(consumerId);
777
+ } catch (err) {
778
+ context.context.logger.error(
779
+ `StreamPay consumer delete failed: ${formatStreamPayError(err)}`
780
+ );
781
+ }
782
+ };
783
+ async function resolveConsumerId2(options, user) {
784
+ if (user.streampayConsumerId) return user.streampayConsumerId;
785
+ return findConsumerByExternalId(options.client, { externalId: user.id });
786
+ }
787
+
788
+ // src/streampay.ts
789
+ var streampay = (options) => {
790
+ const endpoints = options.use.map((use) => use(options.client)).reduce((acc, plugin) => {
791
+ Object.assign(acc, plugin);
792
+ return acc;
793
+ }, {});
794
+ return {
795
+ id: "streampay",
796
+ endpoints,
797
+ schema: {
798
+ user: {
799
+ fields: {
800
+ streampayConsumerId: {
801
+ type: "string",
802
+ required: false,
803
+ input: false
804
+ }
805
+ }
806
+ }
807
+ },
808
+ init() {
809
+ return {
810
+ options: {
811
+ databaseHooks: {
812
+ user: {
813
+ create: {
814
+ before: onBeforeUserCreate(options),
815
+ after: onAfterUserCreate(options)
816
+ },
817
+ update: {
818
+ after: onUserUpdate(options)
819
+ },
820
+ delete: {
821
+ after: onUserDelete(options)
822
+ }
823
+ }
824
+ }
825
+ }
826
+ };
827
+ }
828
+ };
829
+ };
830
+
831
+ // src/webhooks/events.ts
832
+ var STREAMPAY_EVENT_TYPES = [
833
+ // Payment
834
+ "PAYMENT_SUCCEEDED",
835
+ "PAYMENT_FAILED",
836
+ "PAYMENT_CANCELED",
837
+ "PAYMENT_REFUNDED",
838
+ "PAYMENT_MARKED_AS_PAID",
839
+ // Invoice
840
+ "INVOICE_CREATED",
841
+ "INVOICE_SENT",
842
+ "INVOICE_ACCEPTED",
843
+ "INVOICE_REJECTED",
844
+ "INVOICE_COMPLETED",
845
+ "INVOICE_CANCELED",
846
+ "INVOICE_UPDATED",
847
+ // Subscription
848
+ "SUBSCRIPTION_CREATED",
849
+ "SUBSCRIPTION_ACTIVATED",
850
+ "SUBSCRIPTION_INACTIVATED",
851
+ "SUBSCRIPTION_CANCELED",
852
+ "SUBSCRIPTION_FROZEN",
853
+ "SUBSCRIPTION_CYCLE_RENEWAL_FAILED",
854
+ "SUBSCRIPTION_CANCEL_AT_PERIOD_END",
855
+ "SUBSCRIPTION_FREEZE_NOW",
856
+ "SUBSCRIPTION_UNFREEZE_NOW",
857
+ "SUBSCRIPTION_UNFREEZE_FUTURE",
858
+ "SUBSCRIPTION_FREEZE_CANCEL",
859
+ // Payment Link
860
+ "PAYMENT_LINK_PAY_ATTEMPT_FAILED"
861
+ ];
862
+
863
+ exports.CheckoutBody = CheckoutBody;
864
+ exports.STREAMPAY_EVENT_TYPES = STREAMPAY_EVENT_TYPES;
865
+ exports.StreamPayWebhookError = StreamPayWebhookError;
866
+ exports.checkout = checkout;
867
+ exports.dispatchWebhook = dispatchWebhook;
868
+ exports.findConsumerByExternalId = findConsumerByExternalId;
869
+ exports.findConsumerByIdentifiers = findConsumerByIdentifiers;
870
+ exports.formatStreamPayError = formatStreamPayError;
871
+ exports.portal = portal;
872
+ exports.streampay = streampay;
873
+ exports.subscriptions = subscriptions;
874
+ exports.verifyWebhook = verifyWebhook;
875
+ exports.verifyWebhookOrThrow = verifyWebhookOrThrow;
876
+ exports.webhooks = webhooks;
877
+ //# sourceMappingURL=index.cjs.map
878
+ //# sourceMappingURL=index.cjs.map