@fantastic.dev/better-stripe 0.33.0 → 0.34.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 (85) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +30 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +36 -0
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +18 -0
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +36 -0
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +18 -0
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/core/accountClosures.d.ts +15 -0
  12. package/dist/client/core/accountClosures.d.ts.map +1 -0
  13. package/dist/client/core/accountClosures.js +10 -0
  14. package/dist/client/core/accountClosures.js.map +1 -0
  15. package/dist/client/core/accounts.d.ts.map +1 -1
  16. package/dist/client/core/accounts.js +15 -23
  17. package/dist/client/core/accounts.js.map +1 -1
  18. package/dist/client/core/personalAccountMapping.d.ts +8 -0
  19. package/dist/client/core/personalAccountMapping.d.ts.map +1 -0
  20. package/dist/client/core/personalAccountMapping.js +11 -0
  21. package/dist/client/core/personalAccountMapping.js.map +1 -0
  22. package/dist/client/index.d.ts +55 -2
  23. package/dist/client/index.d.ts.map +1 -1
  24. package/dist/client/index.js +13 -0
  25. package/dist/client/index.js.map +1 -1
  26. package/dist/client/publicTypes.d.ts +5 -0
  27. package/dist/client/publicTypes.d.ts.map +1 -0
  28. package/dist/client/publicTypes.js +2 -0
  29. package/dist/client/publicTypes.js.map +1 -0
  30. package/dist/component/_generated/component.d.ts +88 -0
  31. package/dist/component/_generated/component.d.ts.map +1 -1
  32. package/dist/component/accountClosure/helpers.d.ts +18 -0
  33. package/dist/component/accountClosure/helpers.d.ts.map +1 -0
  34. package/dist/component/accountClosure/helpers.js +18 -0
  35. package/dist/component/accountClosure/helpers.js.map +1 -0
  36. package/dist/component/accountClosure/mutations.d.ts +20 -0
  37. package/dist/component/accountClosure/mutations.d.ts.map +1 -0
  38. package/dist/component/accountClosure/mutations.js +55 -0
  39. package/dist/component/accountClosure/mutations.js.map +1 -0
  40. package/dist/component/accountClosure/queries.d.ts +34 -0
  41. package/dist/component/accountClosure/queries.d.ts.map +1 -0
  42. package/dist/component/accountClosure/queries.js +36 -0
  43. package/dist/component/accountClosure/queries.js.map +1 -0
  44. package/dist/component/accountClosure/schema.d.ts +46 -0
  45. package/dist/component/accountClosure/schema.d.ts.map +1 -0
  46. package/dist/component/accountClosure/schema.js +20 -0
  47. package/dist/component/accountClosure/schema.js.map +1 -0
  48. package/dist/component/core/mutations.d.ts.map +1 -1
  49. package/dist/component/core/mutations.js +5 -0
  50. package/dist/component/core/mutations.js.map +1 -1
  51. package/dist/component/core/personalAccountMapping.d.ts +95 -0
  52. package/dist/component/core/personalAccountMapping.d.ts.map +1 -0
  53. package/dist/component/core/personalAccountMapping.js +54 -0
  54. package/dist/component/core/personalAccountMapping.js.map +1 -0
  55. package/dist/component/core/queries.d.ts +27 -0
  56. package/dist/component/core/queries.d.ts.map +1 -1
  57. package/dist/component/core/queries.js +7 -0
  58. package/dist/component/core/queries.js.map +1 -1
  59. package/dist/component/earnings/triggers.d.ts +42 -0
  60. package/dist/component/earnings/triggers.d.ts.map +1 -1
  61. package/dist/component/schema.d.ts +18 -0
  62. package/dist/component/schema.js +2 -0
  63. package/dist/component/schema.js.map +1 -1
  64. package/docs/personal-account-mapping.md +54 -0
  65. package/package.json +3 -2
  66. package/src/client/core/account-close-orchestration.test.ts +131 -0
  67. package/src/client/core/account-closure.test.ts +317 -0
  68. package/src/client/core/accountClosures.ts +37 -0
  69. package/src/client/core/accounts.test.ts +0 -111
  70. package/src/client/core/accounts.ts +24 -29
  71. package/src/client/core/personal-account-mapping.test.ts +71 -0
  72. package/src/client/core/personalAccountMapping.ts +23 -0
  73. package/src/client/index.ts +36 -33
  74. package/src/client/publicTypes.ts +35 -0
  75. package/src/component/_generated/api.ts +8 -0
  76. package/src/component/_generated/component.ts +126 -0
  77. package/src/component/accountClosure/helpers.ts +21 -0
  78. package/src/component/accountClosure/mutations.ts +56 -0
  79. package/src/component/accountClosure/queries.ts +43 -0
  80. package/src/component/accountClosure/schema.ts +20 -0
  81. package/src/component/core/mutations.ts +3 -0
  82. package/src/component/core/personal-account-mapping.test.ts +173 -0
  83. package/src/component/core/personalAccountMapping.ts +81 -0
  84. package/src/component/core/queries.ts +11 -0
  85. package/src/component/schema.ts +2 -0
@@ -0,0 +1,56 @@
1
+ import { v } from "convex/values";
2
+ import { mutation } from "../_generated/server.js";
3
+ import { closureByStripeId } from "./helpers.js";
4
+ import { closureDoc } from "./schema.js";
5
+ /** Trusted host boundary: authenticate and authorize the actor before invoking close. */
6
+ export const prepare = mutation({
7
+ args: { stripeAccountId: v.string() },
8
+ returns: v.object({ closure: closureDoc, isRetry: v.boolean() }),
9
+ handler: async (ctx, { stripeAccountId }) => {
10
+ const existing = await closureByStripeId(ctx, stripeAccountId);
11
+ if (existing) return { closure: existing, isRetry: true };
12
+ const account = await ctx.db
13
+ .query("accounts")
14
+ .withIndex("by_stripe_account_id", (q) =>
15
+ q.eq("stripeAccountId", stripeAccountId),
16
+ )
17
+ .unique();
18
+ const id = await ctx.db.insert("accountClosures", {
19
+ stripeAccountId,
20
+ userId: account?.userId,
21
+ orgId: account?.orgId,
22
+ appliedConfigurations: account?.appliedConfigurations,
23
+ state: "pending",
24
+ });
25
+ const closure = await ctx.db.get("accountClosures", id);
26
+ if (!closure) throw new Error("Closure intent was not persisted");
27
+ return { closure, isRetry: false };
28
+ },
29
+ });
30
+
31
+ export const complete = mutation({
32
+ args: { stripeAccountId: v.string() },
33
+ returns: v.null(),
34
+ handler: async (ctx, { stripeAccountId }) => {
35
+ const closure = await closureByStripeId(ctx, stripeAccountId);
36
+ if (!closure) throw new Error("Closure intent is required");
37
+ if (closure.state === "closed") return null;
38
+ const account = await ctx.db
39
+ .query("accounts")
40
+ .withIndex("by_stripe_account_id", (q) =>
41
+ q.eq("stripeAccountId", stripeAccountId),
42
+ )
43
+ .unique();
44
+ if (
45
+ account &&
46
+ (account.userId !== closure.userId || account.orgId !== closure.orgId)
47
+ )
48
+ throw new Error("Account ownership changed during closure");
49
+ await ctx.db.patch("accountClosures", closure._id, {
50
+ state: "closed",
51
+ closedAt: Date.now(),
52
+ });
53
+ if (account) await ctx.db.delete("accounts", account._id);
54
+ return null;
55
+ },
56
+ });
@@ -0,0 +1,43 @@
1
+ import {
2
+ paginationOptsValidator,
3
+ paginationResultValidator,
4
+ } from "convex/server";
5
+ import { paginator } from "convex-helpers/server/pagination";
6
+ import { v } from "convex/values";
7
+ import { query } from "../_generated/server.js";
8
+ import schema from "../schema.js";
9
+ import { closureByStripeId } from "./helpers.js";
10
+ import { closureDoc } from "./schema.js";
11
+ /** This is provenance, not end-user authentication; hosts must compare the authenticated owner. */
12
+ export const getClosedAccountByStripeId = query({
13
+ args: { stripeAccountId: v.string() },
14
+ returns: v.union(closureDoc, v.null()),
15
+ handler: async (ctx, { stripeAccountId }) => {
16
+ const closure = await closureByStripeId(ctx, stripeAccountId);
17
+ return closure?.state === "closed" ? closure : null;
18
+ },
19
+ });
20
+
21
+ export const listClosedAccountsByUserId = query({
22
+ args: { userId: v.string(), paginationOpts: paginationOptsValidator },
23
+ returns: paginationResultValidator(closureDoc),
24
+ handler: async (ctx, { userId, paginationOpts }) => {
25
+ if (
26
+ !Number.isInteger(paginationOpts.numItems) ||
27
+ paginationOpts.numItems < 1 ||
28
+ paginationOpts.numItems > 100
29
+ )
30
+ throw new Error("Closure history page size must be between 1 and 100");
31
+ return paginator(ctx.db, schema)
32
+ .query("accountClosures")
33
+ .withIndex("by_user_state", (q) =>
34
+ q.eq("userId", userId).eq("orgId", undefined).eq("state", "closed"),
35
+ )
36
+ .order("desc")
37
+ .paginate({
38
+ ...paginationOpts,
39
+ maximumRowsRead: 200,
40
+ maximumBytesRead: 1_000_000,
41
+ });
42
+ },
43
+ });
@@ -0,0 +1,20 @@
1
+ import { defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+ import { appliedConfigurationsValidator } from "../core/validators.js";
4
+
5
+ export const closureFields = {
6
+ stripeAccountId: v.string(),
7
+ userId: v.optional(v.string()),
8
+ orgId: v.optional(v.string()),
9
+ appliedConfigurations: appliedConfigurationsValidator,
10
+ state: v.union(v.literal("pending"), v.literal("closed")),
11
+ closedAt: v.optional(v.number()),
12
+ };
13
+ export const closureDoc = v.object({
14
+ _id: v.id("accountClosures"),
15
+ _creationTime: v.number(),
16
+ ...closureFields,
17
+ });
18
+ export const accountClosuresTable = defineTable(closureFields)
19
+ .index("by_stripe_account_id", ["stripeAccountId"])
20
+ .index("by_user_state", ["userId", "orgId", "state"]);
@@ -1,3 +1,4 @@
1
+ import { canUpsertAccount } from "../accountClosure/helpers.js";
1
2
  import { assertPayoutResetSafe } from "./resetSafety.js";
2
3
  import { v } from "convex/values";
3
4
 
@@ -32,6 +33,7 @@ export const upsertAccount = mutation({
32
33
  },
33
34
  returns: v.null(),
34
35
  handler: async (ctx, args) => {
36
+ if (!(await canUpsertAccount(ctx, args))) return null;
35
37
  const existing = await ctx.db
36
38
  .query("accounts")
37
39
  .withIndex("by_stripe_account_id", (q) =>
@@ -128,6 +130,7 @@ export const upsertAccountInternal = mutation({
128
130
  },
129
131
  returns: v.null(),
130
132
  handler: async (ctx, args) => {
133
+ if (!(await canUpsertAccount(ctx, args))) return null;
131
134
  const existing = await ctx.db
132
135
  .query("accounts")
133
136
  .withIndex("by_stripe_account_id", (q) =>
@@ -0,0 +1,173 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { describe, expect, it } from "vitest";
4
+
5
+ import { api } from "../_generated/api.js";
6
+ import { modules, schema } from "../../test.js";
7
+
8
+ const read = makeFunctionReference<"query", { userId: string }>(
9
+ "core/queries:getPersonalAccountMapping",
10
+ );
11
+ const account = (
12
+ stripeAccountId = "acct_original",
13
+ userId = "user_original",
14
+ orgId?: string,
15
+ ) => ({
16
+ stripeAccountId,
17
+ userId,
18
+ onboardingStatus: "pending" as const,
19
+ ...(orgId === undefined ? {} : { orgId }),
20
+ });
21
+ const fixture = () => convexTest(schema, modules);
22
+
23
+ describe("bounded personal account mapping", () => {
24
+ it("returns a unique reciprocal personal account without requiring financial onboarding", async () => {
25
+ const t = fixture();
26
+ const id = await t.run((ctx) => ctx.db.insert("accounts", account()));
27
+ expect(await t.query(read, { userId: "user_original" })).toEqual({
28
+ status: "unique",
29
+ account: expect.objectContaining({
30
+ _id: id,
31
+ stripeAccountId: "acct_original",
32
+ userId: "user_original",
33
+ onboardingStatus: "pending",
34
+ }),
35
+ });
36
+ });
37
+
38
+ it("distinguishes a missing mapping from a guessed current account", async () => {
39
+ expect(await fixture().query(read, { userId: "user_missing" })).toEqual({
40
+ status: "unavailable",
41
+ reason: "missing",
42
+ });
43
+ });
44
+
45
+ it.each([
46
+ "same user",
47
+ "same Stripe ID",
48
+ "same exact mapping",
49
+ "mixed organization",
50
+ ] as const)(
51
+ "rejects ambiguous %s instead of selecting the first row",
52
+ async (kind) => {
53
+ const t = fixture();
54
+ await t.run(async (ctx) => {
55
+ await ctx.db.insert("accounts", account());
56
+ await ctx.db.insert(
57
+ "accounts",
58
+ kind === "same user"
59
+ ? account("acct_replacement")
60
+ : kind === "same Stripe ID"
61
+ ? account("acct_original", "user_other")
62
+ : kind === "mixed organization"
63
+ ? account("acct_organization", "user_original", "org_one")
64
+ : account(),
65
+ );
66
+ });
67
+ expect(await t.query(read, { userId: "user_original" })).toEqual({
68
+ status: "unavailable",
69
+ reason: "ambiguous",
70
+ });
71
+ expect(
72
+ (
73
+ await t.query(api.core.queries.getAccountByUserId, {
74
+ userId: "user_original",
75
+ })
76
+ )?.stripeAccountId,
77
+ ).toBe("acct_original");
78
+ },
79
+ );
80
+
81
+ it.each(["org_one", ""])(
82
+ "never treats organization scope %j as personal",
83
+ async (orgId) => {
84
+ const t = fixture();
85
+ await t.run((ctx) =>
86
+ ctx.db.insert(
87
+ "accounts",
88
+ account("acct_original", "user_original", orgId),
89
+ ),
90
+ );
91
+ expect(await t.query(read, { userId: "user_original" })).toEqual({
92
+ status: "unavailable",
93
+ reason: "organization",
94
+ });
95
+ },
96
+ );
97
+
98
+ it.each(["acct_", "cus_123", "acct_bad space", "acct_" + "x".repeat(129)])(
99
+ "rejects malformed provider account %j",
100
+ async (stripeAccountId) => {
101
+ const t = fixture();
102
+ await t.run((ctx) => ctx.db.insert("accounts", account(stripeAccountId)));
103
+ expect(await t.query(read, { userId: "user_original" })).toEqual({
104
+ status: "unavailable",
105
+ reason: "invalid_account",
106
+ });
107
+ },
108
+ );
109
+
110
+ it.each(["closed", "pending"] as const)(
111
+ "excludes a stale live row with %s closure provenance",
112
+ async (state) => {
113
+ const t = fixture();
114
+ await t.run(async (ctx) => {
115
+ await ctx.db.insert("accounts", account());
116
+ await ctx.db.insert("accountClosures", {
117
+ stripeAccountId: "acct_original",
118
+ userId: "user_original",
119
+ state,
120
+ });
121
+ });
122
+ expect(await t.query(read, { userId: "user_original" })).toEqual({
123
+ status: "unavailable",
124
+ reason: state === "closed" ? "closed" : "closure_unresolved",
125
+ });
126
+ },
127
+ );
128
+
129
+ it("rejects conflicting closure records rather than choosing one", async () => {
130
+ const t = fixture();
131
+ await t.run(async (ctx) => {
132
+ await ctx.db.insert("accounts", account());
133
+ for (const state of ["pending", "closed"] as const)
134
+ await ctx.db.insert("accountClosures", {
135
+ stripeAccountId: "acct_original",
136
+ userId: "user_original",
137
+ state,
138
+ });
139
+ });
140
+ expect(await t.query(read, { userId: "user_original" })).toEqual({
141
+ status: "unavailable",
142
+ reason: "ambiguous",
143
+ });
144
+ });
145
+
146
+ it.each([
147
+ "",
148
+ " ",
149
+ " user_original",
150
+ "user_original ",
151
+ "user\noriginal",
152
+ "x".repeat(257),
153
+ ])("rejects malformed user selector %j", async (userId) => {
154
+ await expect(fixture().query(read, { userId })).rejects.toThrow(
155
+ "Invalid personal account user selector",
156
+ );
157
+ });
158
+
159
+ it("does not leak another user's mapping or mutate account state", async () => {
160
+ const t = fixture();
161
+ const before = await t.run(async (ctx) => {
162
+ await ctx.db.insert("accounts", account());
163
+ return ctx.db.query("accounts").take(2);
164
+ });
165
+ expect(await t.query(read, { userId: "user_other" })).toEqual({
166
+ status: "unavailable",
167
+ reason: "missing",
168
+ });
169
+ expect(await t.run((ctx) => ctx.db.query("accounts").take(2))).toEqual(
170
+ before,
171
+ );
172
+ });
173
+ });
@@ -0,0 +1,81 @@
1
+ import { type Infer, v } from "convex/values";
2
+
3
+ import type { QueryCtx } from "../_generated/server.js";
4
+ import { accountDocValidator } from "./validators.js";
5
+
6
+ export const personalAccountMappingValidator = v.union(
7
+ v.object({ status: v.literal("unique"), account: accountDocValidator }),
8
+ v.object({
9
+ status: v.literal("unavailable"),
10
+ reason: v.union(
11
+ v.literal("missing"),
12
+ v.literal("ambiguous"),
13
+ v.literal("organization"),
14
+ v.literal("invalid_account"),
15
+ v.literal("closure_unresolved"),
16
+ v.literal("closed"),
17
+ ),
18
+ }),
19
+ );
20
+ export type PersonalAccountMapping = Infer<
21
+ typeof personalAccountMappingValidator
22
+ >;
23
+
24
+ /** Opaque host identity is an exact selector, never an authentication credential. */
25
+ export function assertPersonalAccountUserId(userId: string) {
26
+ if (
27
+ typeof userId !== "string" ||
28
+ !userId.length ||
29
+ userId.length > 256 ||
30
+ userId.trim() !== userId ||
31
+ /[\u0000-\u001f\u007f]/.test(userId)
32
+ )
33
+ throw new Error("Invalid personal account user selector");
34
+ }
35
+
36
+ /** Reusable in query or mutation transactions; no guessed first/newest account or provider writes. */
37
+ export async function resolvePersonalAccountMapping(
38
+ ctx: QueryCtx,
39
+ userId: string,
40
+ ): Promise<PersonalAccountMapping> {
41
+ assertPersonalAccountUserId(userId);
42
+ const candidates = await ctx.db
43
+ .query("accounts")
44
+ .withIndex("by_user_id", (q) => q.eq("userId", userId))
45
+ .take(2);
46
+ if (!candidates.length) return { status: "unavailable", reason: "missing" };
47
+ if (candidates.length !== 1)
48
+ return { status: "unavailable", reason: "ambiguous" };
49
+ const account = candidates[0]!;
50
+ if (account.orgId !== undefined)
51
+ return { status: "unavailable", reason: "organization" };
52
+ if (
53
+ account.userId !== userId ||
54
+ account.stripeAccountId.length > 128 ||
55
+ !/^acct_[A-Za-z0-9_]+$/.test(account.stripeAccountId)
56
+ )
57
+ return { status: "unavailable", reason: "invalid_account" };
58
+ const reciprocal = await ctx.db
59
+ .query("accounts")
60
+ .withIndex("by_stripe_account_id", (q) =>
61
+ q.eq("stripeAccountId", account.stripeAccountId),
62
+ )
63
+ .take(2);
64
+ if (reciprocal.length !== 1 || reciprocal[0]?._id !== account._id)
65
+ return { status: "unavailable", reason: "ambiguous" };
66
+ const closures = await ctx.db
67
+ .query("accountClosures")
68
+ .withIndex("by_stripe_account_id", (q) =>
69
+ q.eq("stripeAccountId", account.stripeAccountId),
70
+ )
71
+ .take(2);
72
+ if (closures.length > 1)
73
+ return { status: "unavailable", reason: "ambiguous" };
74
+ const closure = closures[0];
75
+ if (closure)
76
+ return {
77
+ status: "unavailable",
78
+ reason: closure.state === "closed" ? "closed" : "closure_unresolved",
79
+ };
80
+ return { status: "unique", account };
81
+ }
@@ -2,6 +2,10 @@ import { v } from "convex/values";
2
2
 
3
3
  import { query } from "../_generated/server";
4
4
  import { accountDocValidator, onboardingStatusValidator } from "./validators";
5
+ import {
6
+ personalAccountMappingValidator,
7
+ resolvePersonalAccountMapping,
8
+ } from "./personalAccountMapping.js";
5
9
 
6
10
  // =============================================================================
7
11
  // ACCOUNT QUERIES
@@ -98,3 +102,10 @@ export const getStripeMode = query({
98
102
  return secretKey?.startsWith("sk_test_") ? "test" : "live";
99
103
  },
100
104
  });
105
+
106
+ /** Unique personal mapping evidence only; the host still authenticates its caller. */
107
+ export const getPersonalAccountMapping = query({
108
+ args: { userId: v.string() },
109
+ returns: personalAccountMappingValidator,
110
+ handler: (ctx, { userId }) => resolvePersonalAccountMapping(ctx, userId),
111
+ });
@@ -1,3 +1,4 @@
1
+ import { accountClosuresTable } from "./accountClosure/schema.js";
1
2
  import { jobsTable as payoutWorkerJobsTable } from "./payoutWorker/schema.js";
2
3
  import {
3
4
  financialRevisionsTable,
@@ -90,6 +91,7 @@ export default defineSchema({
90
91
  commissionDecisions: commissionDecisionsTable,
91
92
  // Core
92
93
  accounts: accountsTable,
94
+ accountClosures: accountClosuresTable,
93
95
 
94
96
  // Products
95
97
  products: productsTable,