@fantastic.dev/better-stripe 0.53.0 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +116 -2
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +58 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +116 -2
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +58 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +3 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/index.js +1 -0
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/client/usage/client.d.ts +2 -2
  16. package/dist/client/usage/client.d.ts.map +1 -1
  17. package/dist/client/usage/client.js +3 -3
  18. package/dist/client/usage/client.js.map +1 -1
  19. package/dist/client/usage/deliveryClient.d.ts +64 -0
  20. package/dist/client/usage/deliveryClient.d.ts.map +1 -0
  21. package/dist/client/usage/deliveryClient.js +60 -0
  22. package/dist/client/usage/deliveryClient.js.map +1 -0
  23. package/dist/client/usage/deliveryProtocol.d.ts +130 -0
  24. package/dist/client/usage/deliveryProtocol.d.ts.map +1 -0
  25. package/dist/client/usage/deliveryProtocol.js +21 -0
  26. package/dist/client/usage/deliveryProtocol.js.map +1 -0
  27. package/dist/client/usage/deliveryProvider.d.ts +32 -0
  28. package/dist/client/usage/deliveryProvider.d.ts.map +1 -0
  29. package/dist/client/usage/deliveryProvider.js +127 -0
  30. package/dist/client/usage/deliveryProvider.js.map +1 -0
  31. package/dist/client/usage/index.d.ts +3 -0
  32. package/dist/client/usage/index.d.ts.map +1 -1
  33. package/dist/client/usage/index.js +1 -0
  34. package/dist/client/usage/index.js.map +1 -1
  35. package/dist/client/webhooks/handler.d.ts.map +1 -1
  36. package/dist/client/webhooks/handler.js +2 -1
  37. package/dist/client/webhooks/handler.js.map +1 -1
  38. package/dist/client/webhooks/meterErrors.d.ts +5 -0
  39. package/dist/client/webhooks/meterErrors.d.ts.map +1 -0
  40. package/dist/client/webhooks/meterErrors.js +98 -0
  41. package/dist/client/webhooks/meterErrors.js.map +1 -0
  42. package/dist/client/webhooks/v2.d.ts.map +1 -1
  43. package/dist/client/webhooks/v2.js +5 -0
  44. package/dist/client/webhooks/v2.js.map +1 -1
  45. package/dist/component/_generated/api.d.ts +14 -0
  46. package/dist/component/_generated/api.d.ts.map +1 -1
  47. package/dist/component/_generated/api.js.map +1 -1
  48. package/dist/component/_generated/component.d.ts +170 -0
  49. package/dist/component/_generated/component.d.ts.map +1 -1
  50. package/dist/component/balanceFunding/mutations.d.ts +43 -43
  51. package/dist/component/earnings/triggers.d.ts +104 -2
  52. package/dist/component/earnings/triggers.d.ts.map +1 -1
  53. package/dist/component/refundHistory/queries.d.ts +1 -1
  54. package/dist/component/schema.d.ts +58 -1
  55. package/dist/component/schema.js +3 -0
  56. package/dist/component/schema.js.map +1 -1
  57. package/dist/component/usage/schema.d.ts +96 -1
  58. package/dist/component/usage/schema.d.ts.map +1 -1
  59. package/dist/component/usage/schema.js +11 -2
  60. package/dist/component/usage/schema.js.map +1 -1
  61. package/dist/component/usageDelivery/bridge.d.ts +25 -0
  62. package/dist/component/usageDelivery/bridge.d.ts.map +1 -0
  63. package/dist/component/usageDelivery/bridge.js +45 -0
  64. package/dist/component/usageDelivery/bridge.js.map +1 -0
  65. package/dist/component/usageDelivery/fields.d.ts +78 -0
  66. package/dist/component/usageDelivery/fields.d.ts.map +1 -0
  67. package/dist/component/usageDelivery/fields.js +38 -0
  68. package/dist/component/usageDelivery/fields.js.map +1 -0
  69. package/dist/component/usageDelivery/helpers.d.ts +83 -0
  70. package/dist/component/usageDelivery/helpers.d.ts.map +1 -0
  71. package/dist/component/usageDelivery/helpers.js +63 -0
  72. package/dist/component/usageDelivery/helpers.js.map +1 -0
  73. package/dist/component/usageDelivery/mutations.d.ts +97 -0
  74. package/dist/component/usageDelivery/mutations.d.ts.map +1 -0
  75. package/dist/component/usageDelivery/mutations.js +153 -0
  76. package/dist/component/usageDelivery/mutations.js.map +1 -0
  77. package/dist/component/usageDelivery/queries.d.ts +113 -0
  78. package/dist/component/usageDelivery/queries.d.ts.map +1 -0
  79. package/dist/component/usageDelivery/queries.js +22 -0
  80. package/dist/component/usageDelivery/queries.js.map +1 -0
  81. package/dist/component/usageDelivery/schema.d.ts +79 -0
  82. package/dist/component/usageDelivery/schema.d.ts.map +1 -0
  83. package/dist/component/usageDelivery/schema.js +30 -0
  84. package/dist/component/usageDelivery/schema.js.map +1 -0
  85. package/dist/component/usageDelivery/steps.d.ts +85 -0
  86. package/dist/component/usageDelivery/steps.d.ts.map +1 -0
  87. package/dist/component/usageDelivery/steps.js +154 -0
  88. package/dist/component/usageDelivery/steps.js.map +1 -0
  89. package/dist/component/usageDelivery/workflow.d.ts +15 -0
  90. package/dist/component/usageDelivery/workflow.d.ts.map +1 -0
  91. package/dist/component/usageDelivery/workflow.js +28 -0
  92. package/dist/component/usageDelivery/workflow.js.map +1 -0
  93. package/docs/README.md +3 -1
  94. package/docs/metering-setup.md +1 -1
  95. package/docs/usage-delivery.md +143 -0
  96. package/package.json +3 -2
  97. package/src/client/index.ts +16 -0
  98. package/src/client/usage/client.ts +5 -2
  99. package/src/client/usage/deliveryClient.ts +130 -0
  100. package/src/client/usage/deliveryProtocol.ts +26 -0
  101. package/src/client/usage/deliveryProvider.test.ts +207 -0
  102. package/src/client/usage/deliveryProvider.ts +155 -0
  103. package/src/client/usage/index.ts +13 -0
  104. package/src/client/webhooks/handler.ts +2 -1
  105. package/src/client/webhooks/meterErrors.test.ts +164 -0
  106. package/src/client/webhooks/meterErrors.ts +118 -0
  107. package/src/client/webhooks/v2.ts +5 -0
  108. package/src/component/_generated/api.ts +14 -0
  109. package/src/component/_generated/component.ts +302 -0
  110. package/src/component/schema.ts +6 -0
  111. package/src/component/usage/schema.ts +11 -2
  112. package/src/component/usageDelivery/bridge.ts +56 -0
  113. package/src/component/usageDelivery/concurrency.test.ts +62 -0
  114. package/src/component/usageDelivery/fields.ts +59 -0
  115. package/src/component/usageDelivery/helpers.ts +77 -0
  116. package/src/component/usageDelivery/mutations.ts +185 -0
  117. package/src/component/usageDelivery/queries.ts +25 -0
  118. package/src/component/usageDelivery/schema.ts +33 -0
  119. package/src/component/usageDelivery/steps.ts +171 -0
  120. package/src/component/usageDelivery/workflow.test.ts +402 -0
  121. package/src/component/usageDelivery/workflow.ts +36 -0
@@ -0,0 +1,207 @@
1
+ import Stripe from "stripe";
2
+ import { expect, it, vi } from "vitest";
3
+ import { componentsGeneric } from "convex/server";
4
+ import type { Component, RunCtx } from "../helpers.js";
5
+ import { STRIPE_API_VERSION } from "../constants.js";
6
+ import { prepareUsageRecord } from "./records.js";
7
+ import { deliverUsageProvider } from "./deliveryProvider.js";
8
+ const scope = {
9
+ stripeAccountId: "acct_platform",
10
+ customerAccount: "acct_buyer",
11
+ meterId: "mtr_calls",
12
+ livemode: false,
13
+ };
14
+ function setup(status = 200, errorCode = "parameter_invalid_integer") {
15
+ const now = Math.floor(Date.now() / 1000);
16
+ const record = prepareUsageRecord({
17
+ scope,
18
+ binding: {
19
+ stripeCustomerId: "cus_buyer",
20
+ stripePriceId: "price_calls",
21
+ eventName: "calls",
22
+ plan: {
23
+ key: "calls",
24
+ version: "v1",
25
+ model: "pay_as_you_go",
26
+ unit: { name: "call", precision: 2 },
27
+ rate: { currency: "usd", unitAmountDecimal: "2" },
28
+ },
29
+ },
30
+ sourceEventId: "one",
31
+ quantity: "1.2",
32
+ occurredAt: now,
33
+ });
34
+ const saved = {
35
+ event: {
36
+ recordJson: JSON.stringify(record),
37
+ subscriptionJson: JSON.stringify({
38
+ subscriptionId: "sub_calls",
39
+ subscriptionItemId: "si_calls",
40
+ stripePriceId: "price_calls",
41
+ period: { start: now - 1, end: now + 86400 },
42
+ interval: "month",
43
+ }),
44
+ },
45
+ outbox: {
46
+ state: "sending",
47
+ attempts: 1,
48
+ definitionVersion: 1,
49
+ providerIdentifier: "bs_usage_event",
50
+ firstSendAt: now,
51
+ leaseUntil: now + 900,
52
+ },
53
+ };
54
+ const ctx = {
55
+ runQuery: vi.fn().mockResolvedValue(saved),
56
+ } as unknown as RunCtx;
57
+ const requests: Array<{
58
+ path: string;
59
+ headers: Headers;
60
+ body: URLSearchParams;
61
+ }> = [];
62
+ const httpClient = Stripe.createFetchHttpClient(async (input, init) => {
63
+ const path = new URL(String(input)).pathname,
64
+ body = new URLSearchParams(String(init?.body ?? ""));
65
+ requests.push({ path, body, headers: new Headers(init?.headers) });
66
+ const value =
67
+ path === "/v1/account"
68
+ ? { id: "acct_platform" }
69
+ : path === "/v1/balance"
70
+ ? { livemode: false }
71
+ : path === "/v1/billing/meters/mtr_calls"
72
+ ? {
73
+ id: "mtr_calls",
74
+ livemode: false,
75
+ status: "active",
76
+ event_name: "calls",
77
+ default_aggregation: { formula: "sum" },
78
+ customer_mapping: {
79
+ type: "by_id",
80
+ event_payload_key: "stripe_customer_id",
81
+ },
82
+ value_settings: { event_payload_key: "value" },
83
+ event_time_window: null,
84
+ }
85
+ : path === "/v1/subscriptions/sub_calls"
86
+ ? {
87
+ id: "sub_calls",
88
+ livemode: false,
89
+ customer: "cus_buyer",
90
+ customer_account: "acct_buyer",
91
+ }
92
+ : status === 200
93
+ ? {
94
+ object: "billing.meter_event",
95
+ identifier: body.get("identifier"),
96
+ event_name: "calls",
97
+ livemode: false,
98
+ timestamp: now,
99
+ created: now,
100
+ payload: { stripe_customer_id: "cus_buyer", value: "120" },
101
+ }
102
+ : {
103
+ error: {
104
+ type: status === 429 ? "rate_limit_error" : "api_error",
105
+ message: "private provider detail",
106
+ code: errorCode,
107
+ },
108
+ };
109
+ if (path === "/v1/billing/meter_events" && status === 0)
110
+ throw new Error("Lost accepted response");
111
+ return new Response(JSON.stringify(value), {
112
+ status: path === "/v1/billing/meter_events" ? status : 200,
113
+ headers: { "content-type": "application/json" },
114
+ });
115
+ });
116
+ const request = {
117
+ scope,
118
+ eventId: "event",
119
+ attempt: 1,
120
+ definitionVersion: 1 as const,
121
+ apiVersion: STRIPE_API_VERSION,
122
+ identifier: "bs_usage_event",
123
+ };
124
+ return { ctx, request, requests, httpClient, saved };
125
+ }
126
+ it("sends scaled native values with stable identifiers and no SDK retries", async () => {
127
+ const f = setup();
128
+ const result = await deliverUsageProvider(
129
+ componentsGeneric().betterStripe as unknown as Component,
130
+ f.ctx,
131
+ f.request,
132
+ { stripeSecretKey: "sk_test_usage", httpClient: f.httpClient },
133
+ );
134
+ expect(result).toMatchObject({
135
+ ...f.request,
136
+ outcome: { status: "accepted" },
137
+ });
138
+ const posts = f.requests.filter((r) => r.path === "/v1/billing/meter_events");
139
+ expect(posts).toHaveLength(1);
140
+ expect(posts[0].body.get("payload[value]")).toBe("120");
141
+ expect(posts[0].headers.get("idempotency-key")).toBe("bs_usage_event");
142
+ expect(posts[0].headers.get("stripe-version")).toBe(STRIPE_API_VERSION);
143
+ });
144
+ it.each([
145
+ [429, "rate_limited"],
146
+ [500, "unknown"],
147
+ [401, "unavailable"],
148
+ [400, "rejected"],
149
+ ])(
150
+ "classifies HTTP %i without leaking raw errors",
151
+ async (status, expected) => {
152
+ const f = setup(status);
153
+ const result = await deliverUsageProvider(
154
+ componentsGeneric().betterStripe as unknown as Component,
155
+ f.ctx,
156
+ f.request,
157
+ { stripeSecretKey: "sk_test_usage", httpClient: f.httpClient },
158
+ );
159
+ expect(result).toMatchObject({ outcome: { status: expected } });
160
+ expect(JSON.stringify(result)).not.toContain("private provider detail");
161
+ expect(
162
+ f.requests.filter((r) => r.path === "/v1/billing/meter_events"),
163
+ ).toHaveLength(1);
164
+ },
165
+ );
166
+ it("does not send after the deduplication window or with unavailable credentials", async () => {
167
+ const f = setup();
168
+ f.saved.outbox.firstSendAt -= 24 * 3600;
169
+ expect(
170
+ await deliverUsageProvider(
171
+ componentsGeneric().betterStripe as unknown as Component,
172
+ f.ctx,
173
+ f.request,
174
+ { stripeSecretKey: "sk_test_usage", httpClient: f.httpClient },
175
+ ),
176
+ ).toMatchObject({ outcome: { status: "unknown" } });
177
+ expect(f.requests).toHaveLength(0);
178
+ const other = setup();
179
+ expect(
180
+ await deliverUsageProvider(
181
+ componentsGeneric().betterStripe as unknown as Component,
182
+ other.ctx,
183
+ other.request,
184
+ {},
185
+ ),
186
+ ).toMatchObject({ outcome: { status: "unavailable" } });
187
+ expect(other.requests).toHaveLength(0);
188
+ });
189
+
190
+ it("holds duplicate/uncertain errors and a lost response instead of retrying transport", async () => {
191
+ for (const [status, code] of [
192
+ [400, "duplicate_meter_event"],
193
+ [0, "lost"],
194
+ ] as const) {
195
+ const f = setup(status, code);
196
+ const result = await deliverUsageProvider(
197
+ componentsGeneric().betterStripe as unknown as Component,
198
+ f.ctx,
199
+ f.request,
200
+ { stripeSecretKey: "sk_test_usage", httpClient: f.httpClient },
201
+ );
202
+ expect(result).toMatchObject({ outcome: { status: "unknown" } });
203
+ expect(
204
+ f.requests.filter((r) => r.path === "/v1/billing/meter_events"),
205
+ ).toHaveLength(1);
206
+ }
207
+ });
@@ -0,0 +1,155 @@
1
+ import Stripe from "stripe";
2
+ import type { StripeApiVersion } from "../stripe-types.js";
3
+ import { z } from "zod";
4
+ import type { Component, RunCtx } from "../helpers.js";
5
+ import { componentRef } from "../webhooks/helpers.js";
6
+ import { resolveStripeApiVersion } from "../apiVersion.js";
7
+ import { scopeSchema, type PreparedUsageRecord } from "./records.js";
8
+ import { verifyRealm, verifyMeter, UsageCatalogError } from "./catalogTypes.js";
9
+ import { subscriptionSnapshot } from "../../component/usage/helpers.js";
10
+ import type { Doc } from "../../component/_generated/dataModel.js";
11
+ export const usageDeliveryRequest = z.strictObject({
12
+ scope: scopeSchema,
13
+ eventId: z.string().min(1).max(100),
14
+ attempt: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
15
+ definitionVersion: z.literal(1),
16
+ apiVersion: z.string(),
17
+ identifier: z
18
+ .string()
19
+ .regex(/^bs_usage_[a-zA-Z0-9_]+$/)
20
+ .max(100),
21
+ });
22
+ export type UsageDeliveryRequest = z.infer<typeof usageDeliveryRequest>;
23
+ export type UsageDeliveryOutcome =
24
+ | { status: "accepted"; created: number }
25
+ | { status: "rate_limited" | "unavailable" | "unknown" | "rejected" };
26
+ export type UsageDeliveryProviderOptions = {
27
+ stripeSecretKey?: string;
28
+ httpClient?: Stripe.HttpClient;
29
+ };
30
+ /** Internal host action only. Options never enter component or Workflow state. */
31
+ export async function deliverUsageProvider(
32
+ component: Component,
33
+ ctx: RunCtx,
34
+ input: UsageDeliveryRequest,
35
+ options: UsageDeliveryProviderOptions,
36
+ ): Promise<UsageDeliveryRequest & { outcome: UsageDeliveryOutcome }> {
37
+ const args = usageDeliveryRequest.parse(input);
38
+ const done = (outcome: UsageDeliveryOutcome) => ({ ...args, outcome });
39
+ if (!options.stripeSecretKey) return done({ status: "unavailable" });
40
+ let writing = false;
41
+ try {
42
+ const apiVersion = resolveStripeApiVersion(args.apiVersion);
43
+ const stripe = new Stripe(options.stripeSecretKey, {
44
+ apiVersion: apiVersion as StripeApiVersion,
45
+ maxNetworkRetries: 0,
46
+ timeout: 15000,
47
+ ...(options.httpClient ? { httpClient: options.httpClient } : {}),
48
+ });
49
+ const read = () =>
50
+ ctx.runQuery(componentRef(component, "usageDelivery/queries/snapshot"), {
51
+ scope: args.scope,
52
+ eventId: args.eventId,
53
+ }) as Promise<{ event: Doc<"usageEvents">; outbox: Doc<"usageOutbox"> }>;
54
+ const saved = await read(),
55
+ record = JSON.parse(saved.event.recordJson) as PreparedUsageRecord;
56
+ const eligible = (outbox: Doc<"usageOutbox">) =>
57
+ outbox.state === "sending" &&
58
+ !outbox.held &&
59
+ outbox.attempts === args.attempt &&
60
+ outbox.definitionVersion === args.definitionVersion &&
61
+ outbox.providerIdentifier === args.identifier &&
62
+ outbox.firstSendAt !== undefined &&
63
+ Date.now() / 1000 - outbox.firstSendAt < 23 * 3600 &&
64
+ (outbox.leaseUntil ?? 0) > Date.now() / 1000 + 60;
65
+ if (
66
+ !eligible(saved.outbox) ||
67
+ record.binding.apiVersion !== apiVersion ||
68
+ JSON.stringify(record.scope) !== JSON.stringify(args.scope)
69
+ )
70
+ return done({ status: "unknown" });
71
+ const now = Math.floor(Date.now() / 1000);
72
+ if (record.occurredAt < now - 35 * 86400 || record.occurredAt > now + 300)
73
+ return done({ status: "rejected" });
74
+ await verifyRealm(stripe, {
75
+ stripeAccountId: args.scope.stripeAccountId,
76
+ livemode: args.scope.livemode,
77
+ });
78
+ const binding = subscriptionSnapshot(saved.event.subscriptionJson);
79
+ const [meter, subscription] = await Promise.all([
80
+ stripe.billing.meters.retrieve(args.scope.meterId),
81
+ stripe.subscriptions.retrieve(binding.subscriptionId),
82
+ ]);
83
+ if (
84
+ meter.id !== args.scope.meterId ||
85
+ subscription.id !== binding.subscriptionId ||
86
+ subscription.livemode !== args.scope.livemode ||
87
+ subscription.customer_account !== args.scope.customerAccount ||
88
+ (typeof subscription.customer === "string"
89
+ ? subscription.customer
90
+ : subscription.customer?.id) !== record.binding.stripeCustomerId
91
+ )
92
+ return done({ status: "rejected" });
93
+ verifyMeter(meter, {
94
+ scope: args.scope,
95
+ plan: record.binding.plan,
96
+ eventName: record.binding.eventName,
97
+ displayName: meter.display_name,
98
+ });
99
+ if (!eligible((await read()).outbox)) return done({ status: "unknown" });
100
+ writing = true;
101
+ const response = await stripe.billing.meterEvents.create(
102
+ {
103
+ event_name: record.binding.eventName,
104
+ identifier: args.identifier,
105
+ timestamp: record.occurredAt,
106
+ payload: {
107
+ stripe_customer_id: record.binding.stripeCustomerId,
108
+ value: record.scaledQuantity,
109
+ },
110
+ },
111
+ { idempotencyKey: args.identifier },
112
+ );
113
+ if (
114
+ response.identifier !== args.identifier ||
115
+ response.event_name !== record.binding.eventName ||
116
+ response.livemode !== args.scope.livemode ||
117
+ response.timestamp !== record.occurredAt ||
118
+ response.payload.stripe_customer_id !== record.binding.stripeCustomerId ||
119
+ String(response.payload.value) !== record.scaledQuantity ||
120
+ !Number.isSafeInteger(response.created) ||
121
+ response.created < 0
122
+ )
123
+ return done({ status: "unknown" });
124
+ return done({ status: "accepted", created: response.created });
125
+ } catch (error) {
126
+ if (!writing)
127
+ return done({
128
+ status:
129
+ error instanceof UsageCatalogError &&
130
+ error.code === "unsupported_scope"
131
+ ? "rejected"
132
+ : "unavailable",
133
+ });
134
+ const status =
135
+ error instanceof Stripe.errors.StripeError ? error.statusCode : undefined;
136
+ if (status === 429) return done({ status: "rate_limited" });
137
+ if (status === 401 || status === 403)
138
+ return done({ status: "unavailable" });
139
+ const code =
140
+ error instanceof Stripe.errors.StripeError ? error.code : undefined;
141
+ if (
142
+ status === 404 ||
143
+ (status === 400 &&
144
+ code !== undefined &&
145
+ [
146
+ "parameter_invalid_integer",
147
+ "parameter_invalid_empty",
148
+ "parameter_missing",
149
+ "resource_missing",
150
+ ].includes(code))
151
+ )
152
+ return done({ status: "rejected" });
153
+ return done({ status: "unknown" });
154
+ }
155
+ }
@@ -32,3 +32,16 @@ export type {
32
32
  UsageProviderCapabilities,
33
33
  UsageContractPort,
34
34
  } from "./boundaries.js";
35
+
36
+ export type {
37
+ UsageDeliveryRequest,
38
+ UsageDeliveryOutcome,
39
+ UsageDeliveryProviderOptions,
40
+ } from "./deliveryProvider.js";
41
+ export type {
42
+ UsageDeliveryRef,
43
+ UsageDeliveryStatus,
44
+ UsageDeliveryStartOptions,
45
+ } from "./deliveryClient.js";
46
+
47
+ export { usageDeliveryArgs, usageDeliveryResult } from "./deliveryProtocol.js";
@@ -1,3 +1,4 @@
1
+ import { isMeterErrorEvent } from "./meterErrors.js";
1
2
  import type Stripe from "stripe";
2
3
 
3
4
  import type { Component } from "../helpers.js";
@@ -41,7 +42,7 @@ export async function handleWebhookRequest(
41
42
  }
42
43
 
43
44
  const eventType = (parsedBody.type as string) ?? "";
44
- const isV2Event = eventType.startsWith("v2.");
45
+ const isV2Event = eventType.startsWith("v2.") || isMeterErrorEvent(eventType);
45
46
 
46
47
  const stripeSecretKey = config?.stripeSecretKey;
47
48
  const stripeApiVersion = config?.stripeApiVersion;
@@ -0,0 +1,164 @@
1
+ import Stripe from "stripe";
2
+ import { expect, it, vi } from "vitest";
3
+ import type { Component } from "../helpers.js";
4
+ import type { WebhookActionCtx } from "../types.js";
5
+ import { componentsGeneric } from "convex/server";
6
+ import { STRIPE_API_VERSION } from "../constants.js";
7
+ const fixture = vi.hoisted(() => ({ stripe: undefined as unknown }));
8
+ vi.mock("./helpers.js", async (importOriginal) => ({
9
+ ...(await importOriginal<typeof import("./helpers.js")>()),
10
+ getStripeClient: () => fixture.stripe,
11
+ }));
12
+ import { handleWebhookRequest } from "./handler.js";
13
+ it("verifies and fetches v1 meter thin events without the snapshot parser", async () => {
14
+ const body = JSON.stringify({
15
+ id: "evt_meter_error",
16
+ object: "v2.core.event",
17
+ type: "v1.billing.meter.error_report_triggered",
18
+ livemode: false,
19
+ related_object: { id: "mtr_calls", type: "billing.meter" },
20
+ });
21
+ const parse = vi.fn().mockResolvedValue({});
22
+ const full = {
23
+ id: "evt_meter_error",
24
+ type: "v1.billing.meter.error_report_triggered",
25
+ livemode: false,
26
+ related_object: { id: "mtr_calls", type: "billing.meter" },
27
+ data: {
28
+ reason: {
29
+ error_types: [
30
+ {
31
+ code: "meter_event_invalid_value",
32
+ sample_errors: [
33
+ {
34
+ error_message: "private raw error",
35
+ request: { idempotency_key: "bs_usage_event" },
36
+ },
37
+ ],
38
+ },
39
+ ],
40
+ },
41
+ },
42
+ };
43
+ fixture.stripe = {
44
+ parseEventNotificationAsync: parse,
45
+ v2: { core: { events: { retrieve: vi.fn().mockResolvedValue(full) } } },
46
+ accounts: { retrieve: vi.fn().mockResolvedValue({ id: "acct_platform" }) },
47
+ balance: { retrieve: vi.fn().mockResolvedValue({ livemode: false }) },
48
+ webhooks: {
49
+ constructEventAsync: vi.fn().mockRejectedValue(new Error("Wrong parser")),
50
+ },
51
+ } as unknown as Stripe;
52
+ const runMutation = vi.fn(async (_ref, args) =>
53
+ typeof args.stripeEventId === "string" && args.eventType
54
+ ? "inserted"
55
+ : { matched: 1, unattributed: 0, truncated: false },
56
+ );
57
+ const ctx = { runMutation, runQuery: vi.fn() } as unknown as WebhookActionCtx;
58
+ const response = await handleWebhookRequest(
59
+ ctx,
60
+ new Request("https://example.test/webhook", {
61
+ method: "POST",
62
+ headers: { "stripe-signature": "verified-fixture" },
63
+ body,
64
+ }),
65
+ componentsGeneric().betterStripe as unknown as Component,
66
+ {
67
+ stripeSecretKey: "sk_test_fixture",
68
+ webhookSecret: "whsec_snapshot",
69
+ webhookSecretV2: "whsec_thin",
70
+ stripeApiVersion: STRIPE_API_VERSION,
71
+ },
72
+ );
73
+ expect(response.status).toBe(200);
74
+ expect(parse).toHaveBeenCalledWith(body, "verified-fixture", "whsec_thin");
75
+ const report = runMutation.mock.calls.find(([, args]) => args.samples)?.[1];
76
+ expect(report).toMatchObject({
77
+ stripeAccountId: "acct_platform",
78
+ livemode: false,
79
+ meterId: "mtr_calls",
80
+ samples: [
81
+ { identifier: "bs_usage_event", code: "meter_event_invalid_value" },
82
+ ],
83
+ });
84
+ expect(JSON.stringify(report)).not.toContain("private raw error");
85
+ });
86
+
87
+ it.each(["event", "account", "balance"])(
88
+ "sanitizes %s retrieval errors before webhook history and logs",
89
+ async (failing) => {
90
+ const privateError = new Error("PRIVATE_PROVIDER_MARKER");
91
+ fixture.stripe = {
92
+ parseEventNotificationAsync: vi.fn().mockResolvedValue({}),
93
+ v2: {
94
+ core: {
95
+ events: {
96
+ retrieve: vi
97
+ .fn()
98
+ .mockImplementation(() =>
99
+ failing === "event"
100
+ ? Promise.reject(privateError)
101
+ : Promise.resolve({}),
102
+ ),
103
+ },
104
+ },
105
+ },
106
+ accounts: {
107
+ retrieve: vi
108
+ .fn()
109
+ .mockImplementation(() =>
110
+ failing === "account"
111
+ ? Promise.reject(privateError)
112
+ : Promise.resolve({ id: "acct_platform" }),
113
+ ),
114
+ },
115
+ balance: {
116
+ retrieve: vi
117
+ .fn()
118
+ .mockImplementation(() =>
119
+ failing === "balance"
120
+ ? Promise.reject(privateError)
121
+ : Promise.resolve({ livemode: false }),
122
+ ),
123
+ },
124
+ };
125
+ const runMutation = vi.fn(async (_ref, args) =>
126
+ args.eventType ? "inserted" : null,
127
+ );
128
+ const logged = vi.spyOn(console, "error").mockImplementation(() => {});
129
+ try {
130
+ const response = await handleWebhookRequest(
131
+ { runMutation, runQuery: vi.fn() } as unknown as WebhookActionCtx,
132
+ new Request("https://example.test/webhook", {
133
+ method: "POST",
134
+ headers: { "stripe-signature": "fixture" },
135
+ body: JSON.stringify({
136
+ id: "evt_private",
137
+ type: "v1.billing.meter.error_report_triggered",
138
+ livemode: false,
139
+ }),
140
+ }),
141
+ componentsGeneric().betterStripe as unknown as Component,
142
+ {
143
+ stripeSecretKey: "sk_test_fixture",
144
+ webhookSecret: "whsec_snapshot",
145
+ webhookSecretV2: "whsec_thin",
146
+ },
147
+ );
148
+ expect(response.status).toBe(500);
149
+ expect(JSON.stringify(runMutation.mock.calls)).not.toContain(
150
+ "PRIVATE_PROVIDER_MARKER",
151
+ );
152
+ expect(
153
+ logged.mock.calls
154
+ .flat()
155
+ .map((value) =>
156
+ value instanceof Error ? value.message : String(value),
157
+ )
158
+ .join(" "),
159
+ ).not.toContain("PRIVATE_PROVIDER_MARKER");
160
+ } finally {
161
+ logged.mockRestore();
162
+ }
163
+ },
164
+ );
@@ -0,0 +1,118 @@
1
+ import { z } from "zod";
2
+ import { componentRef, type WebhookContext } from "./helpers.js";
3
+ import type { V2ThinEvent } from "../types.js";
4
+ const types = [
5
+ "v1.billing.meter.error_report_triggered",
6
+ "v1.billing.meter.no_meter_found",
7
+ ] as const;
8
+ export const isMeterErrorEvent = (type: string) =>
9
+ types.some((value) => value === type);
10
+ const codes = new Set([
11
+ "meter_event_customer_not_found",
12
+ "meter_event_no_customer_defined",
13
+ "meter_event_dimension_count_too_high",
14
+ "archived_meter",
15
+ "timestamp_too_far_in_past",
16
+ "timestamp_in_future",
17
+ "meter_event_value_not_found",
18
+ "meter_event_invalid_value",
19
+ "no_meter",
20
+ ]);
21
+ const reportSchema = z.object({
22
+ id: z.string(),
23
+ type: z.enum(types),
24
+ livemode: z.boolean(),
25
+ related_object: z.object({ id: z.string().optional() }).nullish(),
26
+ data: z.object({
27
+ reason: z.object({
28
+ error_types: z
29
+ .array(
30
+ z.object({
31
+ code: z.string(),
32
+ sample_errors: z
33
+ .array(
34
+ z.object({
35
+ request: z
36
+ .object({
37
+ identifier: z.string().optional(),
38
+ idempotency_key: z.string().optional(),
39
+ })
40
+ .optional(),
41
+ }),
42
+ )
43
+ .optional(),
44
+ }),
45
+ )
46
+ .max(1000),
47
+ }),
48
+ }),
49
+ });
50
+ async function processMeterErrorEvent(
51
+ whCtx: WebhookContext,
52
+ thin: V2ThinEvent,
53
+ ): Promise<void> {
54
+ const { stripe, ctx, component } = whCtx;
55
+ const [raw, account, balance] = await Promise.all([
56
+ stripe.v2.core.events.retrieve(thin.id),
57
+ stripe.accounts.retrieve(null),
58
+ stripe.balance.retrieve(),
59
+ ]);
60
+ const parsed = reportSchema.safeParse(raw);
61
+ if (
62
+ !parsed.success ||
63
+ parsed.data.id !== thin.id ||
64
+ parsed.data.type !== thin.type ||
65
+ parsed.data.livemode !== balance.livemode ||
66
+ thin.livemode !== balance.livemode ||
67
+ (thin.context && thin.context !== account.id)
68
+ )
69
+ throw new Error("Native usage error report scope unavailable");
70
+ const report = parsed.data,
71
+ samples: Array<{ identifier: string; code: string }> = [];
72
+ let truncated = false;
73
+ for (const type of report.data.reason.error_types) {
74
+ if (!codes.has(type.code)) {
75
+ truncated = true;
76
+ continue;
77
+ }
78
+ for (const error of type.sample_errors ?? []) {
79
+ const identifier =
80
+ error.request?.identifier ?? error.request?.idempotency_key;
81
+ if (
82
+ !identifier ||
83
+ !/^bs_usage_[a-zA-Z0-9_]+$/.test(identifier) ||
84
+ identifier.length > 100
85
+ ) {
86
+ truncated = true;
87
+ continue;
88
+ }
89
+ if (samples.length >= 100) {
90
+ truncated = true;
91
+ break;
92
+ }
93
+ samples.push({ identifier, code: type.code });
94
+ }
95
+ }
96
+ await ctx.runMutation(
97
+ componentRef(component, "usageDelivery/mutations/recordErrorReport"),
98
+ {
99
+ stripeAccountId: account.id,
100
+ livemode: report.livemode,
101
+ providerEventId: report.id,
102
+ meterId: report.related_object?.id,
103
+ samples,
104
+ truncated,
105
+ },
106
+ );
107
+ }
108
+
109
+ export async function handleMeterErrorEvent(
110
+ whCtx: WebhookContext,
111
+ thin: V2ThinEvent,
112
+ ): Promise<void> {
113
+ try {
114
+ await processMeterErrorEvent(whCtx, thin);
115
+ } catch {
116
+ throw new Error("Native usage error report unavailable");
117
+ }
118
+ }
@@ -1,3 +1,4 @@
1
+ import { isMeterErrorEvent, handleMeterErrorEvent } from "./meterErrors.js";
1
2
  import { STRIPE_CUSTOMER_PREVIEW_API_VERSION } from "../apiVersion.js";
2
3
  import type Stripe from "stripe";
3
4
 
@@ -44,6 +45,10 @@ export async function handleV2Event(
44
45
  thinEvent: V2ThinEvent,
45
46
  ): Promise<string | null> {
46
47
  const { stripe } = whCtx;
48
+ if (isMeterErrorEvent(thinEvent.type)) {
49
+ await handleMeterErrorEvent(whCtx, thinEvent);
50
+ return null;
51
+ }
47
52
 
48
53
  if (!thinEvent.type.startsWith("v2.core.account")) {
49
54
  console.info(`[better-stripe] Unhandled V2 event type: ${thinEvent.type}`);