@fantastic.dev/better-stripe 0.49.0 → 0.50.1

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.
@@ -22,14 +22,6 @@ export declare const begin: import("convex/server").RegisteredMutation<"public",
22
22
  requestKey: string;
23
23
  scopeKey: string;
24
24
  }, Promise<{
25
- reason: "identity_changed" | "revision_changed" | "scope_busy";
26
- retryable: false;
27
- status: "conflict";
28
- } | {
29
- reason: "policy_invalid";
30
- retryable: false;
31
- status: "rejected";
32
- } | {
33
25
  operation: {
34
26
  accountId: string;
35
27
  operationId: import("convex/values").GenericId<"balanceFundingOperations">;
@@ -40,6 +32,14 @@ export declare const begin: import("convex/server").RegisteredMutation<"public",
40
32
  } | {
41
33
  enabled: boolean;
42
34
  status: "unchanged";
35
+ } | {
36
+ reason: "identity_changed" | "revision_changed" | "scope_busy";
37
+ retryable: false;
38
+ status: "conflict";
39
+ } | {
40
+ reason: "policy_invalid";
41
+ retryable: false;
42
+ status: "rejected";
43
43
  } | {
44
44
  reason: "provider_pending";
45
45
  retryable: true;
@@ -395,14 +395,6 @@ export declare const prepare: import("convex/server").RegisteredMutation<"public
395
395
  requestKey: string;
396
396
  scopeKey: string;
397
397
  }, Promise<{
398
- reason: "identity_changed" | "revision_changed" | "scope_busy";
399
- retryable: false;
400
- status: "conflict";
401
- } | {
402
- reason: "policy_invalid";
403
- retryable: false;
404
- status: "rejected";
405
- } | {
406
398
  operation: {
407
399
  accountId: string;
408
400
  operationId: import("convex/values").GenericId<"balanceFundingOperations">;
@@ -413,6 +405,14 @@ export declare const prepare: import("convex/server").RegisteredMutation<"public
413
405
  } | {
414
406
  enabled: boolean;
415
407
  status: "unchanged";
408
+ } | {
409
+ reason: "identity_changed" | "revision_changed" | "scope_busy";
410
+ retryable: false;
411
+ status: "conflict";
412
+ } | {
413
+ reason: "policy_invalid";
414
+ retryable: false;
415
+ status: "rejected";
416
416
  } | {
417
417
  reason: "provider_pending";
418
418
  retryable: true;
@@ -1 +1 @@
1
- {"version":3,"file":"useWorkflowAction.d.ts","sourceRoot":"","sources":["../../../src/react/workflows/useWorkflowAction.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,mBAAmB,CAAC,CAAC,EAAE,IAAI,SAAS,OAAO,EAAE,IAAI;IAC3D,SAAS,EAAE,OAAO,CAAC;IACnB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,MAAM,EAAE,CAAC,GAAG,SAAS,CAAC;IACtB,gFAAgF;IAChF,GAAG,EAAE,CAAC,GAAG,IAAI,EAAE,IAAI,KAAK,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;IAC/C,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB,CAAC;AACF,6GAA6G;AAC7G,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,IAAI,SAAS,OAAO,EAAE,EACzD,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,EACrC,KAAK,GAAE,MAAkB,EACzB,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAK,IAAI,GAC9B,mBAAmB,CAAC,CAAC,EAAE,IAAI,CAAC,CAgE9B"}
1
+ {"version":3,"file":"useWorkflowAction.d.ts","sourceRoot":"","sources":["../../../src/react/workflows/useWorkflowAction.ts"],"names":[],"mappings":"AAYA,MAAM,MAAM,mBAAmB,CAAC,CAAC,EAAE,IAAI,SAAS,OAAO,EAAE,IAAI;IAC3D,SAAS,EAAE,OAAO,CAAC;IACnB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,MAAM,EAAE,CAAC,GAAG,SAAS,CAAC;IACtB,gFAAgF;IAChF,GAAG,EAAE,CAAC,GAAG,IAAI,EAAE,IAAI,KAAK,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;IAC/C,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB,CAAC;AACF,6GAA6G;AAC7G,wBAAgB,iBAAiB,CAAC,CAAC,EAAE,IAAI,SAAS,OAAO,EAAE,EACzD,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,EACrC,KAAK,GAAE,MAAkB,EACzB,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAK,IAAI,GAC9B,mBAAmB,CAAC,CAAC,EAAE,IAAI,CAAC,CAgE9B"}
@@ -1,5 +1,7 @@
1
1
  "use client";
2
- import { useCallback, useEffect, useRef, useState } from "react";
2
+ import { useCallback, useEffect, useInsertionEffect, useRef, useState, } from "react";
3
+ // Ref-only synchronization must precede layout effects in descendants as well.
4
+ const useCommitEffect = typeof window === "undefined" ? useEffect : useInsertionEffect;
3
5
  /** Shared async action lifecycle. Scope identifies the authenticated account/resource, not authorization. */
4
6
  export function useWorkflowAction(action, scope = "default", onSuccess) {
5
7
  const initial = {
@@ -15,11 +17,11 @@ export function useWorkflowAction(action, scope = "default", onSuccess) {
15
17
  const success = useRef(onSuccess);
16
18
  const lifecycle = useRef({ version: 0, mounted: false });
17
19
  const lock = useRef(null);
18
- useEffect(() => {
20
+ useCommitEffect(() => {
19
21
  callback.current = action;
20
22
  success.current = onSuccess;
21
23
  }, [action, onSuccess]);
22
- useEffect(() => {
24
+ useCommitEffect(() => {
23
25
  const version = ++lifecycle.current.version;
24
26
  lifecycle.current.mounted = true;
25
27
  lock.current = null;
@@ -1 +1 @@
1
- {"version":3,"file":"useWorkflowAction.js","sourceRoot":"","sources":["../../../src/react/workflows/useWorkflowAction.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AACb,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AASjE,6GAA6G;AAC7G,MAAM,UAAU,iBAAiB,CAC/B,MAAqC,EACrC,KAAK,GAAW,SAAS,EACzB,SAA+B;IAE/B,MAAM,OAAO,GAAG;QACd,KAAK;QACL,SAAS,EAAE,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,GAAG,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC;AAClC,CAAC"}
@@ -577,6 +577,12 @@ checking that the response still belongs to the mounted scope. `useOnboarding`
577
577
  uses this lifecycle for both create and continue navigation, including its
578
578
  `window.location.assign` fallback. An old response cannot navigate after unmount
579
579
  or scope replacement. Current requests preserve shared pending locks and errors.
580
+ The lifecycle and current action callbacks initialize during the browser commit
581
+ phase, using ref-only insertion effects before parent or child layout effects
582
+ can start work. These effects neither update state nor inspect DOM attachment.
583
+ A layout-started action
584
+ therefore settles normally; later unmount or scope replacement still suppresses
585
+ its stale result. Server rendering remains idle and invokes no action.
580
586
  `uploadDisputeEvidence`, `EvidenceUpload` and the onboarding navigation fix shipped
581
587
  in [0.14.0](https://github.com/FantasticDevHQ/better-stripe/releases/tag/v0.14.0).
582
588
  Version 0.13.0 does not contain them. Consumers must upgrade to
@@ -788,3 +794,12 @@ show no invented timestamp. Result/check times are not bank arrival estimates.
788
794
  The example uses the same package workflow in API and BetterStripe-component
789
795
  views, including seller and affiliate payout panels. No status control is a
790
796
  manual withdrawal request. Unknown outcomes reconcile the original operation.
797
+
798
+ ### Authenticated original setup observations
799
+
800
+ For an acknowledged saved-card request, the server SDK's qualified
801
+ `getSetupIntentFromStripe` reads the exact existing SetupIntent. See
802
+ [original SetupIntent recovery](./setup-intent-recovery.md) for the immutable
803
+ selectors, transient-secret policy and authenticated callback requirements.
804
+ This read does not implement a host redirect/reload route or recover a creation
805
+ whose original ID is unknown.
@@ -0,0 +1,27 @@
1
+ # Read an original saved-card setup
2
+
3
+ `getSetupIntentFromStripe` reads an already acknowledged SetupIntent. It does not create, confirm, attach, search for, or retry creation of a setup. Authenticate the host request and resolve its immutable original tuple before calling it. A URL `setup_intent` or `redirect_status` is not authorization or success evidence.
4
+
5
+ ```ts
6
+ const original = await requireOwnedOriginalSetupRequest(ctx, requestId);
7
+ const observation = await betterStripe.getSetupIntentFromStripe(ctx, {
8
+ userId: original.userId,
9
+ customerAccount: original.customerAccount,
10
+ setupIntentId: original.setupIntentId,
11
+ usage: original.usage,
12
+ });
13
+ await requireSameOriginalSetupAuthority(ctx, original);
14
+ return observation;
15
+ ```
16
+
17
+ The two authorization helpers above belong to the host. They must check the enabled authenticated user, original consent and request, current session and original account association before and after provider I/O. The browser supplies an opaque host request correlation hint, not the customer, user, usage or provider ID selectors. Do not add a permissive example action that forwards those browser selectors.
18
+
19
+ The SDK copies all four primitive selectors before its first await. The host user ID remains a nonempty opaque string, matching existing provisioning. It is compared exactly and is not trimmed or given an invented URL-identifier length limit. It resolves the exact component account with `requireUnique: true`, rejects absent or foreign ownership, and makes one exact platform-realm GET. The result must agree with the original ID, V2 `customer_account`, `metadata.userId` and usage. This matches the platform realm of `createSetupIntent`; it does not infer a connected-account realm or supply host authorization. Provider errors propagate and mismatched observations are rejected.
20
+
21
+ The narrow result contains `setupIntentId`, `customerAccount`, `usage`, supported `status` and `observedAt` in Unix milliseconds. A transient `clientSecret` is included only for `requires_payment_method`, `requires_confirmation` or `requires_action`; those states require a nonempty secret. `processing`, `canceled` and `succeeded` omit it. Never persist or log the secret, put it in analytics, or expose it outside the authenticated original request. The SDK does not return the raw provider object, metadata, card details or payment method.
22
+
23
+ A host may resume the original public `SaveCard` confirmation through its authenticated callbacks and refresh the reactive payment-method list only after a qualified `succeeded` observation. A setup observation does not change an account-wide or subscription default. The host still owns redirect routing, reload correlation, stale-form disposal, translated errors and consent policy. The tagged Vite dashboard's tokenization/attach example is not an authenticated SetupIntent return route; its maintained callback must use the server authorization pattern above before adopting this read.
24
+
25
+ If a dispatch outcome is unknown and the host never acknowledged a SetupIntent ID, this operation cannot recover it. Keep that attempt unknown. Do not search by metadata or repeat creation with a fresh key, and do not assume a provider idempotency retention period provides permanent recovery. This read has no package retry loop or new key; the configured SDK transport may apply its existing read retry policy.
26
+
27
+ Focused tests exercise the actual SDK with synthetic HTTP, including tuple mismatches, strict account selection, incomplete secret policy, terminal secret omission, provider failure and caller-input mutation. They are not live V2 or browser/SCA acceptance. Package source acceptance, an independently verified official release, host adoption and a complete authenticated return/reload flow are separate delivery gates.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.49.0",
3
+ "version": "0.50.1",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -83,7 +83,8 @@
83
83
  "docs/example-balance-funding-cutover.md",
84
84
  "docs/example-recovery-cutover.md",
85
85
  "docs/releasing.md",
86
- "docs/release-handoff.md"
86
+ "docs/release-handoff.md",
87
+ "docs/setup-intent-recovery.md"
87
88
  ],
88
89
  "scripts": {
89
90
  "build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
@@ -0,0 +1,284 @@
1
+ import { componentsGeneric } from "convex/server";
2
+ import Stripe from "stripe";
3
+ import { expect, it, vi } from "vitest";
4
+
5
+ import { STRIPE_API_VERSION } from "../constants.js";
6
+ import type { Component, RunCtx } from "../helpers.js";
7
+ import { BetterStripe } from "../index.js";
8
+
9
+ function fixture() {
10
+ const requests: { method: string; path: string }[] = [];
11
+ const realms: (string | null)[] = [];
12
+ const payloads: string[] = [];
13
+ const setup = {
14
+ id: "seti_original",
15
+ object: "setup_intent",
16
+ customer_account: "acct_original",
17
+ usage: "off_session",
18
+ status: "requires_action",
19
+ client_secret: "seti_original_secret_synthetic",
20
+ metadata: { userId: "owner" },
21
+ };
22
+ let failure: Response | undefined;
23
+ const sdk = new Stripe("sk_test_setup_read_fixture", {
24
+ apiVersion: STRIPE_API_VERSION,
25
+ maxNetworkRetries: 0,
26
+ httpClient: Stripe.createFetchHttpClient(async (url, init) => {
27
+ realms.push(new Headers(init?.headers).get("Stripe-Account"));
28
+ payloads.push(String(init?.body ?? ""));
29
+ requests.push({
30
+ method: init?.method ?? "GET",
31
+ path: new URL(String(url)).pathname,
32
+ });
33
+ if (failure) return failure.clone();
34
+ return new Response(
35
+ JSON.stringify(
36
+ new URL(String(url)).pathname.startsWith("/v1/setup_intents")
37
+ ? setup
38
+ : {
39
+ id: "sub_original",
40
+ object: "subscription",
41
+ customer_account: "acct_original",
42
+ status: "active",
43
+ },
44
+ ),
45
+ { status: 200, headers: { "content-type": "application/json" } },
46
+ );
47
+ }),
48
+ });
49
+ class Client extends BetterStripe {
50
+ protected override stripe() {
51
+ return sdk;
52
+ }
53
+ }
54
+ const client = new Client(
55
+ componentsGeneric().betterStripe as unknown as Component,
56
+ { STRIPE_SECRET_KEY: "sk_test_setup_read_fixture" },
57
+ );
58
+ const runQuery = vi
59
+ .fn()
60
+ .mockResolvedValue({ userId: "owner", stripeAccountId: "acct_original" });
61
+ const ctx: RunCtx = { runQuery };
62
+ const opts = {
63
+ userId: "owner",
64
+ customerAccount: "acct_original",
65
+ setupIntentId: "seti_original",
66
+ usage: "off_session" as const,
67
+ };
68
+ return {
69
+ client,
70
+ ctx,
71
+ requests,
72
+ realms,
73
+ payloads,
74
+ setup,
75
+ runQuery,
76
+ opts,
77
+ fail: (response: Response) => {
78
+ failure = response;
79
+ },
80
+ };
81
+ }
82
+
83
+ it("retains the public exact subscription provider read as an existing positive", async () => {
84
+ const f = fixture();
85
+ expect(
86
+ await f.client.getSubscriptionFromStripe(f.ctx, {
87
+ stripeSubscriptionId: "sub_original",
88
+ }),
89
+ ).toMatchObject({
90
+ id: "sub_original",
91
+ customer_account: "acct_original",
92
+ status: "active",
93
+ });
94
+ expect(f.requests).toEqual([
95
+ { method: "GET", path: "/v1/subscriptions/sub_original" },
96
+ ]);
97
+ });
98
+
99
+ it("provides a public qualified exact existing SetupIntent read for original-request recovery", async () => {
100
+ const f = fixture();
101
+ expect(await f.client.getSetupIntentFromStripe(f.ctx, f.opts)).toEqual({
102
+ setupIntentId: "seti_original",
103
+ customerAccount: "acct_original",
104
+ usage: "off_session",
105
+ status: "requires_action",
106
+ clientSecret: "seti_original_secret_synthetic",
107
+ observedAt: expect.any(Number),
108
+ });
109
+ expect(f.realms).toEqual([null]);
110
+ expect(f.runQuery).toHaveBeenCalledWith(expect.anything(), {
111
+ stripeAccountId: "acct_original",
112
+ requireUnique: true,
113
+ });
114
+ expect(f.requests).toEqual([
115
+ { method: "GET", path: "/v1/setup_intents/seti_original" },
116
+ ]);
117
+ });
118
+
119
+ it.each([
120
+ null,
121
+ { userId: "foreign", stripeAccountId: "acct_original" },
122
+ { userId: "owner", stripeAccountId: "acct_other" },
123
+ ])(
124
+ "rejects missing, ambiguous or foreign original account %j before provider access",
125
+ async (account) => {
126
+ const f = fixture();
127
+ f.runQuery.mockResolvedValue(account);
128
+ await expect(
129
+ f.client.getSetupIntentFromStripe(f.ctx, f.opts),
130
+ ).rejects.toThrow(/account/);
131
+ expect(f.requests).toEqual([]);
132
+ },
133
+ );
134
+
135
+ it.each([
136
+ { id: "seti_other" },
137
+ { customer_account: "acct_other" },
138
+ { metadata: { userId: "foreign" } },
139
+ { usage: "on_session" },
140
+ { status: "invented" },
141
+ { metadata: {} },
142
+ ])("rejects contradictory existing setup response %j", async (override) => {
143
+ const f = fixture();
144
+ Object.assign(f.setup, override);
145
+ await expect(
146
+ f.client.getSetupIntentFromStripe(f.ctx, f.opts),
147
+ ).rejects.toThrow(/original request/);
148
+ expect(f.requests).toHaveLength(1);
149
+ });
150
+
151
+ it.each(["succeeded", "canceled", "processing"])(
152
+ "omits the secret for %s observations",
153
+ async (status) => {
154
+ const f = fixture();
155
+ f.setup.status = status;
156
+ const result = await f.client.getSetupIntentFromStripe(f.ctx, f.opts);
157
+ expect(result.status).toBe(status);
158
+ expect(result).not.toHaveProperty("clientSecret");
159
+ expect(result).not.toHaveProperty("metadata");
160
+ expect(result).not.toHaveProperty("payment_method");
161
+ },
162
+ );
163
+
164
+ it.each([
165
+ "requires_action",
166
+ "requires_confirmation",
167
+ "requires_payment_method",
168
+ ])("requires an available transient secret for %s", async (status) => {
169
+ const f = fixture();
170
+ f.setup.status = status;
171
+ f.setup.client_secret = "";
172
+ await expect(
173
+ f.client.getSetupIntentFromStripe(f.ctx, f.opts),
174
+ ).rejects.toThrow(/secret/);
175
+ });
176
+
177
+ it("freezes every original primitive selector before the first await without freezing the caller", async () => {
178
+ const f = fixture();
179
+ f.runQuery.mockImplementation(async () => {
180
+ Object.assign(f.opts, {
181
+ userId: "foreign",
182
+ customerAccount: "acct_other",
183
+ setupIntentId: "seti_other",
184
+ usage: "on_session",
185
+ });
186
+ return { userId: "owner", stripeAccountId: "acct_original" };
187
+ });
188
+ expect(await f.client.getSetupIntentFromStripe(f.ctx, f.opts)).toMatchObject({
189
+ setupIntentId: "seti_original",
190
+ customerAccount: "acct_original",
191
+ usage: "off_session",
192
+ });
193
+ expect(f.opts.setupIntentId).toBe("seti_other");
194
+ expect(Object.isFrozen(f.opts)).toBe(false);
195
+ expect(f.requests).toEqual([
196
+ { method: "GET", path: "/v1/setup_intents/seti_original" },
197
+ ]);
198
+ });
199
+
200
+ it("preserves provider failure without searching or creating a setup", async () => {
201
+ const f = fixture();
202
+ f.fail(
203
+ new Response(
204
+ JSON.stringify({
205
+ error: {
206
+ message: "synthetic missing setup",
207
+ type: "invalid_request_error",
208
+ code: "resource_missing",
209
+ },
210
+ }),
211
+ { status: 404 },
212
+ ),
213
+ );
214
+ await expect(
215
+ f.client.getSetupIntentFromStripe(f.ctx, f.opts),
216
+ ).rejects.toMatchObject({ code: "resource_missing" });
217
+ expect(f.requests).toEqual([
218
+ { method: "GET", path: "/v1/setup_intents/seti_original" },
219
+ ]);
220
+ });
221
+
222
+ it.each([
223
+ { userId: "" },
224
+ { customerAccount: "acct_bad/realm" },
225
+ { setupIntentId: "seti_bad?query" },
226
+ { usage: "unsupported" },
227
+ ])(
228
+ "rejects invalid original selectors %j before any read",
229
+ async (override) => {
230
+ const f = fixture();
231
+ Object.assign(f.opts, override);
232
+ await expect(
233
+ f.client.getSetupIntentFromStripe(f.ctx, f.opts),
234
+ ).rejects.toThrow(/selectors/);
235
+ expect(f.runQuery).not.toHaveBeenCalled();
236
+ expect(f.requests).toEqual([]);
237
+ },
238
+ );
239
+
240
+ it.each([undefined, "payment_intent"])(
241
+ "rejects a wrong or missing SetupIntent object discriminator %s",
242
+ async (object) => {
243
+ const f = fixture();
244
+ Object.assign(f.setup, { object });
245
+ await expect(
246
+ f.client.getSetupIntentFromStripe(f.ctx, f.opts),
247
+ ).rejects.toThrow(/original request/);
248
+ },
249
+ );
250
+
251
+ it.each(["o".repeat(300), " opaque owner "])(
252
+ "reads an original setup provisioned for opaque host userId %s",
253
+ async (userId) => {
254
+ const f = fixture();
255
+ f.opts.userId = userId;
256
+ f.setup.metadata.userId = userId;
257
+ f.runQuery.mockResolvedValue({
258
+ userId,
259
+ stripeAccountId: f.opts.customerAccount,
260
+ });
261
+ expect(
262
+ await f.client.createSetupIntent(f.ctx, {
263
+ userId,
264
+ customerAccount: f.opts.customerAccount,
265
+ usage: f.opts.usage,
266
+ consent: true,
267
+ idempotencyKey: "original-opaque-user-setup",
268
+ }),
269
+ ).toMatchObject({ setupIntentId: f.opts.setupIntentId });
270
+ expect(new URLSearchParams(f.payloads[0]).get("metadata[userId]")).toBe(
271
+ userId,
272
+ );
273
+ expect(
274
+ await f.client.getSetupIntentFromStripe(f.ctx, f.opts),
275
+ ).toMatchObject({
276
+ setupIntentId: f.opts.setupIntentId,
277
+ customerAccount: f.opts.customerAccount,
278
+ });
279
+ expect(f.requests).toEqual([
280
+ { method: "POST", path: "/v1/setup_intents" },
281
+ { method: "GET", path: "/v1/setup_intents/seti_original" },
282
+ ]);
283
+ },
284
+ );
@@ -0,0 +1,97 @@
1
+ import type Stripe from "stripe";
2
+
3
+ import { getAccountByStripeId } from "../core/accounts.js";
4
+ import type { Component, RunCtx } from "../helpers.js";
5
+
6
+ /** Host-authenticated immutable selectors for an already acknowledged setup. */
7
+ export type SetupIntentReadOptions = {
8
+ userId: string;
9
+ customerAccount: string;
10
+ setupIntentId: string;
11
+ usage: "on_session" | "off_session";
12
+ };
13
+
14
+ export type SetupIntentObservation = {
15
+ setupIntentId: string;
16
+ customerAccount: string;
17
+ usage: "on_session" | "off_session";
18
+ status: Stripe.SetupIntent.Status;
19
+ /** Present only for an incomplete confirmation. Never persist or log it. */
20
+ clientSecret?: string;
21
+ /** Time of this provider observation, in Unix milliseconds. */
22
+ observedAt: number;
23
+ };
24
+
25
+ function validate(opts: SetupIntentReadOptions) {
26
+ if (
27
+ typeof opts.userId !== "string" ||
28
+ !opts.userId ||
29
+ typeof opts.customerAccount !== "string" ||
30
+ opts.customerAccount.length > 255 ||
31
+ !/^acct_[A-Za-z0-9]+$/.test(opts.customerAccount) ||
32
+ typeof opts.setupIntentId !== "string" ||
33
+ opts.setupIntentId.length > 255 ||
34
+ !/^seti_[A-Za-z0-9]+$/.test(opts.setupIntentId) ||
35
+ (opts.usage !== "on_session" && opts.usage !== "off_session")
36
+ )
37
+ throw new Error("Valid original SetupIntent selectors are required.");
38
+ }
39
+
40
+ /** Exact platform-realm GET only. Host authorization is required before and after I/O. */
41
+ export async function getSetupIntentFromStripe(
42
+ stripe: Stripe,
43
+ component: Component,
44
+ ctx: RunCtx,
45
+ input: SetupIntentReadOptions,
46
+ ): Promise<SetupIntentObservation> {
47
+ const opts = {
48
+ userId: input.userId,
49
+ customerAccount: input.customerAccount,
50
+ setupIntentId: input.setupIntentId,
51
+ usage: input.usage,
52
+ };
53
+ validate(opts);
54
+ const account = await getAccountByStripeId(component, ctx, {
55
+ stripeAccountId: opts.customerAccount,
56
+ requireUnique: true,
57
+ });
58
+ if (
59
+ !account ||
60
+ account.stripeAccountId !== opts.customerAccount ||
61
+ account.userId !== opts.userId
62
+ )
63
+ throw new Error("Original customer account is unavailable.");
64
+ const setup = await stripe.setupIntents.retrieve(opts.setupIntentId);
65
+ if (
66
+ setup.object !== "setup_intent" ||
67
+ setup.id !== opts.setupIntentId ||
68
+ setup.customer_account !== opts.customerAccount ||
69
+ setup.metadata?.userId !== opts.userId ||
70
+ setup.usage !== opts.usage ||
71
+ ![
72
+ "requires_payment_method",
73
+ "requires_confirmation",
74
+ "requires_action",
75
+ "processing",
76
+ "canceled",
77
+ "succeeded",
78
+ ].includes(setup.status)
79
+ )
80
+ throw new Error("SetupIntent does not match the original request.");
81
+ const isIncomplete = [
82
+ "requires_payment_method",
83
+ "requires_confirmation",
84
+ "requires_action",
85
+ ].includes(setup.status);
86
+ const clientSecret = isIncomplete ? setup.client_secret : undefined;
87
+ if (isIncomplete && (typeof clientSecret !== "string" || !clientSecret))
88
+ throw new Error("Incomplete SetupIntent secret is unavailable.");
89
+ return {
90
+ setupIntentId: opts.setupIntentId,
91
+ customerAccount: opts.customerAccount,
92
+ usage: opts.usage,
93
+ status: setup.status,
94
+ ...(typeof clientSecret === "string" ? { clientSecret } : {}),
95
+ observedAt: Date.now(),
96
+ };
97
+ }
@@ -1,3 +1,8 @@
1
+ import * as setupIntentRead from "./billing/setup-intent-read.js";
2
+ export type {
3
+ SetupIntentReadOptions,
4
+ SetupIntentObservation,
5
+ } from "./billing/setup-intent-read.js";
1
6
  import * as subscriptionPaymentMethod from "./billing/subscription-payment-method.js";
2
7
  import type {
3
8
  AccountByStripeIdOptions,
@@ -1139,6 +1144,19 @@ export class BetterStripe extends PaymentSourceClient {
1139
1144
  );
1140
1145
  }
1141
1146
 
1147
+ /** Qualified existing setup observation. Host must authenticate the original request. */
1148
+ getSetupIntentFromStripe(
1149
+ ctx: RunCtx,
1150
+ opts: setupIntentRead.SetupIntentReadOptions,
1151
+ ) {
1152
+ return setupIntentRead.getSetupIntentFromStripe(
1153
+ this.stripe(),
1154
+ this.component,
1155
+ ctx,
1156
+ opts,
1157
+ );
1158
+ }
1159
+
1142
1160
  async getSubscriptionFromStripe(
1143
1161
  _ctx: RunCtx,
1144
1162
  opts: providerReads.SubscriptionReadOptions,