@fantastic.dev/better-stripe 0.33.0 → 0.35.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 (314) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +30 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +522 -2
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +261 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +522 -2
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +261 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/connect/refundCommandEvidence.d.ts +14 -0
  12. package/dist/client/connect/refundCommandEvidence.d.ts.map +1 -0
  13. package/dist/client/connect/refundCommandEvidence.js +20 -0
  14. package/dist/client/connect/refundCommandEvidence.js.map +1 -0
  15. package/dist/client/connect/refundCommandNormalization.d.ts +11 -0
  16. package/dist/client/connect/refundCommandNormalization.d.ts.map +1 -0
  17. package/dist/client/connect/refundCommandNormalization.js +12 -0
  18. package/dist/client/connect/refundCommandNormalization.js.map +1 -0
  19. package/dist/client/core/accountClosures.d.ts +15 -0
  20. package/dist/client/core/accountClosures.d.ts.map +1 -0
  21. package/dist/client/core/accountClosures.js +10 -0
  22. package/dist/client/core/accountClosures.js.map +1 -0
  23. package/dist/client/core/accounts.d.ts.map +1 -1
  24. package/dist/client/core/accounts.js +15 -23
  25. package/dist/client/core/accounts.js.map +1 -1
  26. package/dist/client/core/personalAccountMapping.d.ts +8 -0
  27. package/dist/client/core/personalAccountMapping.d.ts.map +1 -0
  28. package/dist/client/core/personalAccountMapping.js +11 -0
  29. package/dist/client/core/personalAccountMapping.js.map +1 -0
  30. package/dist/client/financialObservations.d.ts +42 -0
  31. package/dist/client/financialObservations.d.ts.map +1 -0
  32. package/dist/client/financialObservations.js +58 -0
  33. package/dist/client/financialObservations.js.map +1 -0
  34. package/dist/client/financialOwnership.d.ts +52 -0
  35. package/dist/client/financialOwnership.d.ts.map +1 -0
  36. package/dist/client/financialOwnership.js +72 -0
  37. package/dist/client/financialOwnership.js.map +1 -0
  38. package/dist/client/index.d.ts +57 -4
  39. package/dist/client/index.d.ts.map +1 -1
  40. package/dist/client/index.js +15 -2
  41. package/dist/client/index.js.map +1 -1
  42. package/dist/client/observationPagination.d.ts +10 -0
  43. package/dist/client/observationPagination.d.ts.map +1 -0
  44. package/dist/client/observationPagination.js +12 -0
  45. package/dist/client/observationPagination.js.map +1 -0
  46. package/dist/client/publicTypes.d.ts +10 -0
  47. package/dist/client/publicTypes.d.ts.map +1 -0
  48. package/dist/client/publicTypes.js +2 -0
  49. package/dist/client/publicTypes.js.map +1 -0
  50. package/dist/client/readContracts.d.ts +29 -0
  51. package/dist/client/readContracts.d.ts.map +1 -1
  52. package/dist/client/readContracts.js +10 -0
  53. package/dist/client/readContracts.js.map +1 -1
  54. package/dist/client/transferObservations.d.ts +59 -0
  55. package/dist/client/transferObservations.d.ts.map +1 -0
  56. package/dist/client/transferObservations.js +82 -0
  57. package/dist/client/transferObservations.js.map +1 -0
  58. package/dist/component/_generated/component.d.ts +594 -0
  59. package/dist/component/_generated/component.d.ts.map +1 -1
  60. package/dist/component/accountClosure/helpers.d.ts +18 -0
  61. package/dist/component/accountClosure/helpers.d.ts.map +1 -0
  62. package/dist/component/accountClosure/helpers.js +18 -0
  63. package/dist/component/accountClosure/helpers.js.map +1 -0
  64. package/dist/component/accountClosure/mutations.d.ts +20 -0
  65. package/dist/component/accountClosure/mutations.d.ts.map +1 -0
  66. package/dist/component/accountClosure/mutations.js +55 -0
  67. package/dist/component/accountClosure/mutations.js.map +1 -0
  68. package/dist/component/accountClosure/queries.d.ts +34 -0
  69. package/dist/component/accountClosure/queries.d.ts.map +1 -0
  70. package/dist/component/accountClosure/queries.js +36 -0
  71. package/dist/component/accountClosure/queries.js.map +1 -0
  72. package/dist/component/accountClosure/schema.d.ts +46 -0
  73. package/dist/component/accountClosure/schema.d.ts.map +1 -0
  74. package/dist/component/accountClosure/schema.js +20 -0
  75. package/dist/component/accountClosure/schema.js.map +1 -0
  76. package/dist/component/affiliateRecovery/mutations.d.ts.map +1 -1
  77. package/dist/component/affiliateRecovery/mutations.js +4 -1
  78. package/dist/component/affiliateRecovery/mutations.js.map +1 -1
  79. package/dist/component/connect/mutations.d.ts.map +1 -1
  80. package/dist/component/connect/mutations.js +18 -2
  81. package/dist/component/connect/mutations.js.map +1 -1
  82. package/dist/component/connect/queries.d.ts +8 -0
  83. package/dist/component/connect/queries.d.ts.map +1 -1
  84. package/dist/component/connect/reversalClaims.d.ts.map +1 -1
  85. package/dist/component/connect/reversalClaims.js +7 -1
  86. package/dist/component/connect/reversalClaims.js.map +1 -1
  87. package/dist/component/connect/reversalReceipts.d.ts.map +1 -1
  88. package/dist/component/connect/reversalReceipts.js +2 -0
  89. package/dist/component/connect/reversalReceipts.js.map +1 -1
  90. package/dist/component/connect/schema.d.ts +11 -1
  91. package/dist/component/connect/schema.d.ts.map +1 -1
  92. package/dist/component/connect/schema.js +9 -1
  93. package/dist/component/connect/schema.js.map +1 -1
  94. package/dist/component/connect/validators.d.ts +9 -1
  95. package/dist/component/connect/validators.d.ts.map +1 -1
  96. package/dist/component/connect/validators.js +2 -0
  97. package/dist/component/connect/validators.js.map +1 -1
  98. package/dist/component/core/mutations.d.ts.map +1 -1
  99. package/dist/component/core/mutations.js +5 -0
  100. package/dist/component/core/mutations.js.map +1 -1
  101. package/dist/component/core/personalAccountMapping.d.ts +95 -0
  102. package/dist/component/core/personalAccountMapping.d.ts.map +1 -0
  103. package/dist/component/core/personalAccountMapping.js +54 -0
  104. package/dist/component/core/personalAccountMapping.js.map +1 -0
  105. package/dist/component/core/queries.d.ts +27 -0
  106. package/dist/component/core/queries.d.ts.map +1 -1
  107. package/dist/component/core/queries.js +7 -0
  108. package/dist/component/core/queries.js.map +1 -1
  109. package/dist/component/earnings/triggers.d.ts +468 -2
  110. package/dist/component/earnings/triggers.d.ts.map +1 -1
  111. package/dist/component/earnings/triggers.js +7 -1
  112. package/dist/component/earnings/triggers.js.map +1 -1
  113. package/dist/component/financialObservations/continuation.d.ts +7 -0
  114. package/dist/component/financialObservations/continuation.d.ts.map +1 -0
  115. package/dist/component/financialObservations/continuation.js +131 -0
  116. package/dist/component/financialObservations/continuation.js.map +1 -0
  117. package/dist/component/financialObservations/generations.d.ts +6 -0
  118. package/dist/component/financialObservations/generations.d.ts.map +1 -0
  119. package/dist/component/financialObservations/generations.js +46 -0
  120. package/dist/component/financialObservations/generations.js.map +1 -0
  121. package/dist/component/financialObservations/mutations.d.ts +62 -0
  122. package/dist/component/financialObservations/mutations.d.ts.map +1 -0
  123. package/dist/component/financialObservations/mutations.js +69 -0
  124. package/dist/component/financialObservations/mutations.js.map +1 -0
  125. package/dist/component/financialObservations/queries.d.ts +307 -0
  126. package/dist/component/financialObservations/queries.d.ts.map +1 -0
  127. package/dist/component/financialObservations/queries.js +219 -0
  128. package/dist/component/financialObservations/queries.js.map +1 -0
  129. package/dist/component/financialObservations/schema.d.ts +182 -0
  130. package/dist/component/financialObservations/schema.d.ts.map +1 -0
  131. package/dist/component/financialObservations/schema.js +53 -0
  132. package/dist/component/financialObservations/schema.js.map +1 -0
  133. package/dist/component/financialObservations/settlement.d.ts +7 -0
  134. package/dist/component/financialObservations/settlement.d.ts.map +1 -0
  135. package/dist/component/financialObservations/settlement.js +118 -0
  136. package/dist/component/financialObservations/settlement.js.map +1 -0
  137. package/dist/component/financialObservations/settlementHelpers.d.ts +46 -0
  138. package/dist/component/financialObservations/settlementHelpers.d.ts.map +1 -0
  139. package/dist/component/financialObservations/settlementHelpers.js +70 -0
  140. package/dist/component/financialObservations/settlementHelpers.js.map +1 -0
  141. package/dist/component/financialObservations/transferBatches.d.ts +12 -0
  142. package/dist/component/financialObservations/transferBatches.d.ts.map +1 -0
  143. package/dist/component/financialObservations/transferBatches.js +76 -0
  144. package/dist/component/financialObservations/transferBatches.js.map +1 -0
  145. package/dist/component/financialObservations/transferContinuation.d.ts +5 -0
  146. package/dist/component/financialObservations/transferContinuation.d.ts.map +1 -0
  147. package/dist/component/financialObservations/transferContinuation.js +35 -0
  148. package/dist/component/financialObservations/transferContinuation.js.map +1 -0
  149. package/dist/component/financialObservations/transferContinuationState.d.ts +8 -0
  150. package/dist/component/financialObservations/transferContinuationState.d.ts.map +1 -0
  151. package/dist/component/financialObservations/transferContinuationState.js +69 -0
  152. package/dist/component/financialObservations/transferContinuationState.js.map +1 -0
  153. package/dist/component/financialObservations/transferContinuationSteps.d.ts +5 -0
  154. package/dist/component/financialObservations/transferContinuationSteps.d.ts.map +1 -0
  155. package/dist/component/financialObservations/transferContinuationSteps.js +174 -0
  156. package/dist/component/financialObservations/transferContinuationSteps.js.map +1 -0
  157. package/dist/component/financialObservations/transferHelpers.d.ts +18 -0
  158. package/dist/component/financialObservations/transferHelpers.d.ts.map +1 -0
  159. package/dist/component/financialObservations/transferHelpers.js +37 -0
  160. package/dist/component/financialObservations/transferHelpers.js.map +1 -0
  161. package/dist/component/financialObservations/transferReferenceSchema.d.ts +56 -0
  162. package/dist/component/financialObservations/transferReferenceSchema.d.ts.map +1 -0
  163. package/dist/component/financialObservations/transferReferenceSchema.js +21 -0
  164. package/dist/component/financialObservations/transferReferenceSchema.js.map +1 -0
  165. package/dist/component/financialObservations/transferSchema.d.ts +237 -0
  166. package/dist/component/financialObservations/transferSchema.d.ts.map +1 -0
  167. package/dist/component/financialObservations/transferSchema.js +65 -0
  168. package/dist/component/financialObservations/transferSchema.js.map +1 -0
  169. package/dist/component/financialObservations/transfers.d.ts +7 -0
  170. package/dist/component/financialObservations/transfers.d.ts.map +1 -0
  171. package/dist/component/financialObservations/transfers.js +79 -0
  172. package/dist/component/financialObservations/transfers.js.map +1 -0
  173. package/dist/component/financialOwnership/helpers.d.ts +37 -0
  174. package/dist/component/financialOwnership/helpers.d.ts.map +1 -0
  175. package/dist/component/financialOwnership/helpers.js +76 -0
  176. package/dist/component/financialOwnership/helpers.js.map +1 -0
  177. package/dist/component/financialOwnership/mutations.d.ts +28 -0
  178. package/dist/component/financialOwnership/mutations.d.ts.map +1 -0
  179. package/dist/component/financialOwnership/mutations.js +74 -0
  180. package/dist/component/financialOwnership/mutations.js.map +1 -0
  181. package/dist/component/financialOwnership/queries.d.ts +57 -0
  182. package/dist/component/financialOwnership/queries.d.ts.map +1 -0
  183. package/dist/component/financialOwnership/queries.js +50 -0
  184. package/dist/component/financialOwnership/queries.js.map +1 -0
  185. package/dist/component/financialOwnership/schema.d.ts +140 -0
  186. package/dist/component/financialOwnership/schema.d.ts.map +1 -0
  187. package/dist/component/financialOwnership/schema.js +35 -0
  188. package/dist/component/financialOwnership/schema.js.map +1 -0
  189. package/dist/component/payoutRelease/queries.d.ts +2 -2
  190. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  191. package/dist/component/refundHistory/commandBinding.d.ts +17 -0
  192. package/dist/component/refundHistory/commandBinding.d.ts.map +1 -0
  193. package/dist/component/refundHistory/commandBinding.js +41 -0
  194. package/dist/component/refundHistory/commandBinding.js.map +1 -0
  195. package/dist/component/refundHistory/commandEvidence.d.ts +50 -0
  196. package/dist/component/refundHistory/commandEvidence.d.ts.map +1 -0
  197. package/dist/component/refundHistory/commandEvidence.js +54 -0
  198. package/dist/component/refundHistory/commandEvidence.js.map +1 -0
  199. package/dist/component/refundHistory/commandEvidenceValidator.d.ts +89 -0
  200. package/dist/component/refundHistory/commandEvidenceValidator.d.ts.map +1 -0
  201. package/dist/component/refundHistory/commandEvidenceValidator.js +8 -0
  202. package/dist/component/refundHistory/commandEvidenceValidator.js.map +1 -0
  203. package/dist/component/refundHistory/commandFields.d.ts +8 -0
  204. package/dist/component/refundHistory/commandFields.d.ts.map +1 -0
  205. package/dist/component/refundHistory/commandFields.js +9 -0
  206. package/dist/component/refundHistory/commandFields.js.map +1 -0
  207. package/dist/component/refundHistory/mutations.d.ts +8 -0
  208. package/dist/component/refundHistory/mutations.d.ts.map +1 -0
  209. package/dist/component/refundHistory/mutations.js +25 -0
  210. package/dist/component/refundHistory/mutations.js.map +1 -0
  211. package/dist/component/refundHistory/queries.d.ts +51 -0
  212. package/dist/component/refundHistory/queries.d.ts.map +1 -1
  213. package/dist/component/refundHistory/queries.js +14 -0
  214. package/dist/component/refundHistory/queries.js.map +1 -1
  215. package/dist/component/schema.d.ts +261 -1
  216. package/dist/component/schema.js +14 -0
  217. package/dist/component/schema.js.map +1 -1
  218. package/dist/component/settlement/mutations.d.ts.map +1 -1
  219. package/dist/component/settlement/mutations.js +5 -1
  220. package/dist/component/settlement/mutations.js.map +1 -1
  221. package/dist/shared/refundCommandScope.d.ts +10 -0
  222. package/dist/shared/refundCommandScope.d.ts.map +1 -0
  223. package/dist/shared/refundCommandScope.js +9 -0
  224. package/dist/shared/refundCommandScope.js.map +1 -0
  225. package/docs/financial-observations.md +159 -0
  226. package/docs/financial-ownership.md +54 -0
  227. package/docs/personal-account-mapping.md +54 -0
  228. package/docs/refund-command-evidence.md +49 -0
  229. package/package.json +6 -2
  230. package/src/client/connect/refundCommandEvidence.ts +41 -0
  231. package/src/client/connect/refundCommandNormalization.ts +28 -0
  232. package/src/client/core/account-close-orchestration.test.ts +131 -0
  233. package/src/client/core/account-closure.test.ts +317 -0
  234. package/src/client/core/accountClosures.ts +37 -0
  235. package/src/client/core/accounts.test.ts +0 -111
  236. package/src/client/core/accounts.ts +24 -29
  237. package/src/client/core/personal-account-mapping.test.ts +71 -0
  238. package/src/client/core/personalAccountMapping.ts +23 -0
  239. package/src/client/financialObservations.test.ts +109 -0
  240. package/src/client/financialObservations.ts +106 -0
  241. package/src/client/financialOwnership.test.ts +80 -0
  242. package/src/client/financialOwnership.ts +116 -0
  243. package/src/client/index.ts +38 -35
  244. package/src/client/observationPagination.ts +11 -0
  245. package/src/client/publicTypes.ts +72 -0
  246. package/src/client/readContracts.ts +21 -0
  247. package/src/client/refund-command-evidence.test.ts +68 -0
  248. package/src/client/refund-command-normalization.test.ts +61 -0
  249. package/src/client/transferContinuation.test.ts +94 -0
  250. package/src/client/transferObservations.test.ts +98 -0
  251. package/src/client/transferObservations.ts +180 -0
  252. package/src/component/_generated/api.ts +52 -0
  253. package/src/component/_generated/component.ts +716 -0
  254. package/src/component/accountClosure/helpers.ts +21 -0
  255. package/src/component/accountClosure/mutations.ts +56 -0
  256. package/src/component/accountClosure/queries.ts +43 -0
  257. package/src/component/accountClosure/schema.ts +20 -0
  258. package/src/component/affiliateRecovery/mutations.ts +10 -1
  259. package/src/component/connect/mutations.ts +29 -2
  260. package/src/component/connect/reversalClaims.ts +19 -1
  261. package/src/component/connect/reversalReceipts.ts +2 -0
  262. package/src/component/connect/schema.ts +9 -1
  263. package/src/component/connect/validators.ts +2 -0
  264. package/src/component/core/mutations.ts +3 -0
  265. package/src/component/core/personal-account-mapping.test.ts +173 -0
  266. package/src/component/core/personalAccountMapping.ts +81 -0
  267. package/src/component/core/queries.ts +11 -0
  268. package/src/component/core/reset.test.ts +8 -1
  269. package/src/component/earnings/earnings-totals.test.ts +14 -10
  270. package/src/component/earnings/triggers.ts +9 -1
  271. package/src/component/financialObservations/continuation.test.ts +445 -0
  272. package/src/component/financialObservations/continuation.ts +159 -0
  273. package/src/component/financialObservations/generations.ts +53 -0
  274. package/src/component/financialObservations/mutations.ts +75 -0
  275. package/src/component/financialObservations/observation-boundaries.test.ts +466 -0
  276. package/src/component/financialObservations/queries.ts +246 -0
  277. package/src/component/financialObservations/schema.ts +68 -0
  278. package/src/component/financialObservations/settlement-observations.test.ts +86 -0
  279. package/src/component/financialObservations/settlement.ts +142 -0
  280. package/src/component/financialObservations/settlementHelpers.ts +92 -0
  281. package/src/component/financialObservations/transfer-batches.test.ts +61 -0
  282. package/src/component/financialObservations/transfer-boundaries.test.ts +116 -0
  283. package/src/component/financialObservations/transfer-continuation-guards.test.ts +428 -0
  284. package/src/component/financialObservations/transfer-continuation.test.ts +154 -0
  285. package/src/component/financialObservations/transfer-observations.test.ts +212 -0
  286. package/src/component/financialObservations/transfer-overflow.test.ts +181 -0
  287. package/src/component/financialObservations/transfer-writers.test.ts +162 -0
  288. package/src/component/financialObservations/transferBatches.ts +96 -0
  289. package/src/component/financialObservations/transferContinuation.ts +53 -0
  290. package/src/component/financialObservations/transferContinuationState.ts +85 -0
  291. package/src/component/financialObservations/transferContinuationSteps.ts +232 -0
  292. package/src/component/financialObservations/transferHelpers.ts +38 -0
  293. package/src/component/financialObservations/transferReferenceSchema.ts +20 -0
  294. package/src/component/financialObservations/transferSchema.ts +74 -0
  295. package/src/component/financialObservations/transfers.ts +99 -0
  296. package/src/component/financialOwnership/financial-ownership.test.ts +102 -0
  297. package/src/component/financialOwnership/helpers.ts +98 -0
  298. package/src/component/financialOwnership/mutations.ts +83 -0
  299. package/src/component/financialOwnership/ownership-boundaries.test.ts +308 -0
  300. package/src/component/financialOwnership/queries.ts +65 -0
  301. package/src/component/financialOwnership/schema.ts +35 -0
  302. package/src/component/refundHistory/command-evidence.test.ts +288 -0
  303. package/src/component/refundHistory/command-normalization-resource.test.ts +77 -0
  304. package/src/component/refundHistory/command-normalization.test.ts +229 -0
  305. package/src/component/refundHistory/command-provenance.test.ts +59 -0
  306. package/src/component/refundHistory/commandBinding.ts +54 -0
  307. package/src/component/refundHistory/commandEvidence.ts +71 -0
  308. package/src/component/refundHistory/commandEvidenceValidator.ts +18 -0
  309. package/src/component/refundHistory/commandFields.ts +9 -0
  310. package/src/component/refundHistory/mutations.ts +33 -0
  311. package/src/component/refundHistory/queries.ts +15 -0
  312. package/src/component/schema.ts +24 -0
  313. package/src/component/settlement/mutations.ts +5 -1
  314. package/src/shared/refundCommandScope.ts +19 -0
@@ -0,0 +1,98 @@
1
+ import type { QueryCtx } from "../_generated/server.js";
2
+ import {
3
+ assertPersonalAccountUserId,
4
+ resolvePersonalAccountMapping,
5
+ } from "../core/personalAccountMapping.js";
6
+
7
+ export type Owner = { userId: string; orgId?: string };
8
+ export function assertSelector(value: string) {
9
+ assertPersonalAccountUserId(value);
10
+ }
11
+ export function assertOwner(owner: Owner) {
12
+ assertSelector(owner.userId);
13
+ if (owner.orgId !== undefined) assertSelector(owner.orgId);
14
+ }
15
+ export function sameOwner(a: Owner, b: Owner) {
16
+ return a.userId === b.userId && a.orgId === b.orgId;
17
+ }
18
+ export async function registrationByKey(ctx: QueryCtx, bucketKey: string) {
19
+ const rows = await ctx.db
20
+ .query("financialOwnership")
21
+ .withIndex("by_bucket_key", (q) => q.eq("bucketKey", bucketKey))
22
+ .take(2);
23
+ if (rows.length > 1)
24
+ throw new Error("Financial ownership registration is ambiguous");
25
+ return rows[0] ?? null;
26
+ }
27
+ export async function ownerGeneration(ctx: QueryCtx, owner: Owner) {
28
+ const rows = await ctx.db
29
+ .query("financialOwnershipGenerations")
30
+ .withIndex("by_owner", (q) =>
31
+ q.eq("userId", owner.userId).eq("orgId", owner.orgId),
32
+ )
33
+ .take(2);
34
+ if (rows.length > 1)
35
+ throw new Error("Financial ownership generation is ambiguous");
36
+ if (
37
+ rows[0] &&
38
+ (!Number.isSafeInteger(rows[0].generation) || rows[0].generation < 1)
39
+ )
40
+ throw new Error("Financial ownership generation is invalid");
41
+ return rows[0] ?? null;
42
+ }
43
+ /** Physical provenance only; neither onboarding nor financial eligibility is established. */
44
+ export async function physicalSource(
45
+ ctx: QueryCtx,
46
+ bucketKey: string,
47
+ owner: Owner,
48
+ ) {
49
+ if (bucketKey.length > 128 || !/^acct_[A-Za-z0-9_]+$/.test(bucketKey))
50
+ throw new Error("Physical financial ownership is unavailable");
51
+ const closures = await ctx.db
52
+ .query("accountClosures")
53
+ .withIndex("by_stripe_account_id", (q) =>
54
+ q.eq("stripeAccountId", bucketKey),
55
+ )
56
+ .take(2);
57
+ const accounts = await ctx.db
58
+ .query("accounts")
59
+ .withIndex("by_stripe_account_id", (q) =>
60
+ q.eq("stripeAccountId", bucketKey),
61
+ )
62
+ .take(2);
63
+ if (closures.length > 1 || accounts.length > 1)
64
+ throw new Error("Physical financial ownership is ambiguous");
65
+ const closed = closures[0];
66
+ if (closed) {
67
+ if (
68
+ closed.state !== "closed" ||
69
+ closed.userId !== owner.userId ||
70
+ closed.orgId !== owner.orgId ||
71
+ (accounts[0] && !sameOwner(accounts[0], owner))
72
+ )
73
+ throw new Error("Historical financial ownership is unavailable");
74
+ return { integration: "component-closure", recordId: closed._id };
75
+ }
76
+ if (owner.orgId === undefined) {
77
+ const mapping = await resolvePersonalAccountMapping(ctx, owner.userId);
78
+ if (
79
+ mapping.status !== "unique" ||
80
+ mapping.account.stripeAccountId !== bucketKey
81
+ )
82
+ throw new Error("Physical financial ownership is unavailable");
83
+ return { integration: "component-account", recordId: mapping.account._id };
84
+ }
85
+ const organizations = await ctx.db
86
+ .query("accounts")
87
+ .withIndex("by_org_id", (q) => q.eq("orgId", owner.orgId))
88
+ .take(2);
89
+ const account = accounts[0];
90
+ if (
91
+ !account ||
92
+ organizations.length !== 1 ||
93
+ organizations[0]?._id !== account._id ||
94
+ !sameOwner(account, owner)
95
+ )
96
+ throw new Error("Organization financial ownership is unavailable");
97
+ return { integration: "component-account", recordId: account._id };
98
+ }
@@ -0,0 +1,83 @@
1
+ import { v } from "convex/values";
2
+ import { mutation } from "../_generated/server.js";
3
+ import {
4
+ assertOwner,
5
+ assertSelector,
6
+ ownerGeneration,
7
+ physicalSource,
8
+ registrationByKey,
9
+ sameOwner,
10
+ } from "./helpers.js";
11
+ import { ownerFields, registrationResult, sourceValidator } from "./schema.js";
12
+
13
+ /** Trusted host-server provenance. Authenticate and verify logical source ownership before calling. */
14
+ export const register = mutation({
15
+ args: {
16
+ bucketKey: v.string(),
17
+ kind: v.union(v.literal("stripe_account"), v.literal("logical")),
18
+ ...ownerFields,
19
+ source: v.optional(sourceValidator),
20
+ },
21
+ returns: registrationResult,
22
+ handler: async (ctx, args) => {
23
+ assertOwner(args);
24
+ assertSelector(args.bucketKey);
25
+ if (args.kind === "logical") {
26
+ if (!args.source)
27
+ throw new Error("Trusted logical ownership source is required");
28
+ assertSelector(args.source.integration);
29
+ assertSelector(args.source.recordId);
30
+ } else if (args.source !== undefined)
31
+ throw new Error("Physical ownership proof is component-owned");
32
+ const existing = await registrationByKey(ctx, args.bucketKey);
33
+ if (existing) {
34
+ if (
35
+ !sameOwner(existing, args) ||
36
+ existing.kind !== args.kind ||
37
+ (args.kind === "logical" &&
38
+ (existing.source.integration !== args.source!.integration ||
39
+ existing.source.recordId !== args.source!.recordId))
40
+ )
41
+ throw new Error("Financial ownership is immutable");
42
+ return {
43
+ status: "registered" as const,
44
+ coverage: "unknown" as const,
45
+ registration: existing,
46
+ };
47
+ }
48
+ const source =
49
+ args.kind === "logical"
50
+ ? args.source!
51
+ : await physicalSource(ctx, args.bucketKey, args);
52
+ const prior = await ownerGeneration(ctx, args);
53
+ const generation = (prior?.generation ?? 0) + 1;
54
+ if (!Number.isSafeInteger(generation))
55
+ throw new Error("Financial ownership generation overflow");
56
+ const owner = {
57
+ userId: args.userId,
58
+ ...(args.orgId === undefined ? {} : { orgId: args.orgId }),
59
+ };
60
+ if (prior)
61
+ await ctx.db.patch("financialOwnershipGenerations", prior._id, {
62
+ generation,
63
+ });
64
+ else
65
+ await ctx.db.insert("financialOwnershipGenerations", {
66
+ ...owner,
67
+ generation,
68
+ });
69
+ const id = await ctx.db.insert("financialOwnership", {
70
+ bucketKey: args.bucketKey,
71
+ kind: args.kind,
72
+ ...owner,
73
+ source,
74
+ generation,
75
+ });
76
+ const registration = (await ctx.db.get("financialOwnership", id))!;
77
+ return {
78
+ status: "registered" as const,
79
+ coverage: "unknown" as const,
80
+ registration,
81
+ };
82
+ },
83
+ });
@@ -0,0 +1,308 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { describe, expect, it } from "vitest";
4
+ import { modules, schema } from "../../test.js";
5
+ const register = makeFunctionReference<"mutation">(
6
+ "financialOwnership/mutations:register",
7
+ );
8
+ const lookup = makeFunctionReference<"query">(
9
+ "financialOwnership/queries:lookup",
10
+ );
11
+ const discover = makeFunctionReference<"query">(
12
+ "financialOwnership/queries:discover",
13
+ );
14
+ const physical = {
15
+ bucketKey: "acct_one",
16
+ kind: "stripe_account",
17
+ userId: "user_one",
18
+ };
19
+ const logical = {
20
+ bucketKey: "unassigned:key",
21
+ kind: "logical",
22
+ userId: "user_one",
23
+ source: { integration: "trusted-host", recordId: "source_one" },
24
+ };
25
+ const account = {
26
+ stripeAccountId: "acct_one",
27
+ userId: "user_one",
28
+ onboardingStatus: "pending" as const,
29
+ };
30
+ const fixture = () => convexTest(schema, modules);
31
+
32
+ describe("physical ownership proof and isolation", () => {
33
+ it.each([
34
+ "missing",
35
+ "foreign",
36
+ "duplicate_user",
37
+ "duplicate_provider",
38
+ "organization",
39
+ "pending_closure",
40
+ ])("rejects %s current proof atomically", async (kind) => {
41
+ const t = fixture();
42
+ await t.run(async (ctx) => {
43
+ if (kind !== "missing")
44
+ await ctx.db.insert("accounts", {
45
+ ...account,
46
+ ...(kind === "foreign" ? { userId: "other" } : {}),
47
+ ...(kind === "organization" ? { orgId: "org_one" } : {}),
48
+ });
49
+ if (kind === "duplicate_user")
50
+ await ctx.db.insert("accounts", {
51
+ ...account,
52
+ stripeAccountId: "acct_two",
53
+ });
54
+ if (kind === "duplicate_provider")
55
+ await ctx.db.insert("accounts", { ...account, userId: "other" });
56
+ if (kind === "pending_closure")
57
+ await ctx.db.insert("accountClosures", {
58
+ stripeAccountId: account.stripeAccountId,
59
+ userId: account.userId,
60
+ state: "pending",
61
+ });
62
+ });
63
+ await expect(t.mutation(register, physical)).rejects.toThrow();
64
+ expect(await t.query(lookup, { bucketKey: physical.bucketKey })).toEqual({
65
+ status: "unknown",
66
+ coverage: "unknown",
67
+ });
68
+ expect(
69
+ await t.query(discover, {
70
+ userId: physical.userId,
71
+ paginationOpts: { numItems: 10, cursor: null },
72
+ }),
73
+ ).toMatchObject({ generation: 0, page: [], coverage: "unknown" });
74
+ });
75
+ it("preserves historical closure ownership without reviving active discovery", async () => {
76
+ const t = fixture();
77
+ await t.run((ctx) =>
78
+ ctx.db.insert("accountClosures", {
79
+ stripeAccountId: account.stripeAccountId,
80
+ userId: account.userId,
81
+ state: "closed",
82
+ closedAt: 10,
83
+ }),
84
+ );
85
+ const result = await t.mutation(register, physical);
86
+ expect(result).toMatchObject({
87
+ coverage: "unknown",
88
+ registration: {
89
+ userId: account.userId,
90
+ source: { integration: "component-closure" },
91
+ },
92
+ });
93
+ expect(await t.run((ctx) => ctx.db.query("accounts").take(2))).toEqual([]);
94
+ });
95
+ it.each(["duplicate", "foreign", "ownerless", "pending", "conflicting_live"])(
96
+ "rejects %s historical proof",
97
+ async (kind) => {
98
+ const t = fixture();
99
+ await t.run(async (ctx) => {
100
+ const closure = {
101
+ stripeAccountId: account.stripeAccountId,
102
+ ...(kind === "ownerless"
103
+ ? {}
104
+ : { userId: kind === "foreign" ? "other" : account.userId }),
105
+ state:
106
+ kind === "pending" ? ("pending" as const) : ("closed" as const),
107
+ };
108
+ await ctx.db.insert("accountClosures", closure);
109
+ if (kind === "duplicate")
110
+ await ctx.db.insert("accountClosures", closure);
111
+ if (kind === "conflicting_live")
112
+ await ctx.db.insert("accounts", { ...account, userId: "other" });
113
+ });
114
+ await expect(t.mutation(register, physical)).rejects.toThrow();
115
+ },
116
+ );
117
+ it("keeps organization registration separate from personal owner discovery", async () => {
118
+ const t = fixture();
119
+ await t.run((ctx) =>
120
+ ctx.db.insert("accounts", { ...account, orgId: "org_one" }),
121
+ );
122
+ const result = await t.mutation(register, {
123
+ ...physical,
124
+ orgId: "org_one",
125
+ });
126
+ expect(result).toMatchObject({ registration: { orgId: "org_one" } });
127
+ const personal = await t.query(discover, {
128
+ userId: physical.userId,
129
+ paginationOpts: { numItems: 10, cursor: null },
130
+ });
131
+ expect(personal).toMatchObject({
132
+ page: [],
133
+ generation: 0,
134
+ coverage: "unknown",
135
+ });
136
+ expect(
137
+ await t.query(discover, {
138
+ userId: physical.userId,
139
+ orgId: "org_one",
140
+ paginationOpts: { numItems: 10, cursor: null },
141
+ }),
142
+ ).toMatchObject({ page: [result.registration], generation: 1 });
143
+ await expect(
144
+ t.mutation(register, { ...physical, orgId: "org_other" }),
145
+ ).rejects.toThrow("immutable");
146
+ });
147
+ it("rejects ambiguous organization scope instead of selecting its first mapping", async () => {
148
+ const t = fixture();
149
+ await t.run(async (ctx) => {
150
+ await ctx.db.insert("accounts", { ...account, orgId: "org_one" });
151
+ await ctx.db.insert("accounts", {
152
+ ...account,
153
+ stripeAccountId: "acct_two",
154
+ orgId: "org_one",
155
+ });
156
+ });
157
+ await expect(
158
+ t.mutation(register, { ...physical, orgId: "org_one" }),
159
+ ).rejects.toThrow("unavailable");
160
+ });
161
+ });
162
+
163
+ describe("immutable registry and bounded discovery", () => {
164
+ it("retains byte-identical financial rows and the original receipt through closure replay", async () => {
165
+ const t = fixture();
166
+ await t.run(async (ctx) => {
167
+ await ctx.db.insert("accounts", account);
168
+ await ctx.db.insert("transfers", {
169
+ stripeTransferId: "tr_original",
170
+ sourceChargeId: "ch_original",
171
+ destinationAccountId: "acct_one",
172
+ amount: 125,
173
+ currency: "jpy",
174
+ status: "paid",
175
+ role: "affiliate",
176
+ });
177
+ await ctx.db.insert("settlementAllocations", {
178
+ sourceChargeId: "ch_original",
179
+ gross: 200,
180
+ currency: "jpy",
181
+ processingFee: 10,
182
+ platformNet: 65,
183
+ transfers: [
184
+ { destinationAccountId: "acct_one", role: "affiliate", amount: 125 },
185
+ ],
186
+ });
187
+ });
188
+ const snapshot = () =>
189
+ t.run(async (ctx) =>
190
+ JSON.stringify({
191
+ transfers: await ctx.db.query("transfers").take(10),
192
+ allocations: await ctx.db.query("settlementAllocations").take(10),
193
+ }),
194
+ );
195
+ const before = await snapshot();
196
+ const registered = await t.mutation(register, physical);
197
+ await t.run(async (ctx) => {
198
+ await ctx.db.insert("accountClosures", {
199
+ stripeAccountId: "acct_one",
200
+ userId: "user_one",
201
+ state: "closed",
202
+ closedAt: 20,
203
+ });
204
+ const rows = await ctx.db.query("accounts").take(2);
205
+ await ctx.db.delete("accounts", rows[0]!._id);
206
+ });
207
+ expect(await t.mutation(register, physical)).toEqual(registered);
208
+ await expect(
209
+ t.mutation(register, { ...physical, userId: "other" }),
210
+ ).rejects.toThrow("immutable");
211
+ expect(await snapshot()).toBe(before);
212
+ });
213
+ it("rejects corrupted generation rather than certifying a non-monotonic registration", async () => {
214
+ const t = fixture();
215
+ await t.run((ctx) =>
216
+ ctx.db.insert("financialOwnershipGenerations", {
217
+ userId: "user_one",
218
+ generation: -1,
219
+ }),
220
+ );
221
+ await expect(t.mutation(register, logical)).rejects.toThrow("generation");
222
+ expect(
223
+ await t.query(lookup, { bucketKey: logical.bucketKey }),
224
+ ).toMatchObject({ status: "unknown", coverage: "unknown" });
225
+ });
226
+
227
+ it("concurrent matching logical registrations share one immutable receipt", async () => {
228
+ const t = fixture();
229
+ const [a, b] = await Promise.all([
230
+ t.mutation(register, logical),
231
+ t.mutation(register, logical),
232
+ ]);
233
+ expect(a).toEqual(b);
234
+ expect(a.registration.generation).toBe(1);
235
+ await expect(
236
+ t.mutation(register, { ...physical, bucketKey: logical.bucketKey }),
237
+ ).rejects.toThrow("immutable");
238
+ });
239
+ it.each(["", " leading", "trailing ", "x".repeat(257), "bad\u0000key"])(
240
+ "rejects invalid selector %j without partial registration",
241
+ async (bucketKey) => {
242
+ const t = fixture();
243
+ await expect(
244
+ t.mutation(register, { ...logical, bucketKey }),
245
+ ).rejects.toThrow();
246
+ expect(
247
+ await t.query(discover, {
248
+ userId: logical.userId,
249
+ paginationOpts: { numItems: 10, cursor: null },
250
+ }),
251
+ ).toMatchObject({ generation: 0, page: [] });
252
+ },
253
+ );
254
+ it("does not accept a claimed coverage flag or missing logical source", async () => {
255
+ const t = fixture();
256
+ await expect(
257
+ t.mutation(register, { ...logical, complete: true }),
258
+ ).rejects.toThrow();
259
+ await expect(
260
+ t.mutation(register, { ...logical, source: undefined }),
261
+ ).rejects.toThrow("source");
262
+ });
263
+ it("continues past100 owned buckets without leaking a foreign or organization record", async () => {
264
+ const t = fixture();
265
+ for (let i = 0; i < 103; i++)
266
+ await t.mutation(register, { ...logical, bucketKey: `opaque_${i}` });
267
+ await t.mutation(register, {
268
+ ...logical,
269
+ bucketKey: "foreign",
270
+ userId: "user_other",
271
+ });
272
+ await t.mutation(register, {
273
+ ...logical,
274
+ bucketKey: "organization",
275
+ orgId: "org_one",
276
+ });
277
+ let cursor: string | null = null;
278
+ const keys: string[] = [];
279
+ for (let page = 0; page < 10; page++) {
280
+ const result: {
281
+ coverage: string;
282
+ generation: number;
283
+ isDone: boolean;
284
+ continueCursor: string;
285
+ page: { bucketKey: string }[];
286
+ } = await t.query(discover, {
287
+ userId: logical.userId,
288
+ paginationOpts: { numItems: 20, cursor },
289
+ });
290
+ expect(result.coverage).toBe("unknown");
291
+ expect(result.generation).toBe(103);
292
+ keys.push(
293
+ ...result.page.map((row: { bucketKey: string }) => row.bucketKey),
294
+ );
295
+ if (result.isDone) break;
296
+ cursor = result.continueCursor;
297
+ }
298
+ expect(new Set(keys).size).toBe(103);
299
+ expect(keys).not.toContain("foreign");
300
+ expect(keys).not.toContain("organization");
301
+ await expect(
302
+ t.query(discover, {
303
+ userId: logical.userId,
304
+ paginationOpts: { numItems: 101, cursor: null },
305
+ }),
306
+ ).rejects.toThrow("page size");
307
+ });
308
+ });
@@ -0,0 +1,65 @@
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 {
10
+ assertOwner,
11
+ assertSelector,
12
+ ownerGeneration,
13
+ registrationByKey,
14
+ } from "./helpers.js";
15
+ import { ownerFields, registrationDoc, registrationResult } from "./schema.js";
16
+
17
+ /** Trusted host reader; a bucket key is not end-user authorization. */
18
+ export const lookup = query({
19
+ args: { bucketKey: v.string() },
20
+ returns: v.union(
21
+ registrationResult,
22
+ v.object({ status: v.literal("unknown"), coverage: v.literal("unknown") }),
23
+ ),
24
+ handler: async (ctx, { bucketKey }) => {
25
+ assertSelector(bucketKey);
26
+ const registration = await registrationByKey(ctx, bucketKey);
27
+ return registration
28
+ ? {
29
+ status: "registered" as const,
30
+ coverage: "unknown" as const,
31
+ registration,
32
+ }
33
+ : { status: "unknown" as const, coverage: "unknown" as const };
34
+ },
35
+ });
36
+ export const discover = query({
37
+ args: { ...ownerFields, paginationOpts: paginationOptsValidator },
38
+ returns: v.object({
39
+ ...paginationResultValidator(registrationDoc).fields,
40
+ coverage: v.literal("unknown"),
41
+ generation: v.number(),
42
+ }),
43
+ handler: async (ctx, args) => {
44
+ assertOwner(args);
45
+ if (
46
+ !Number.isInteger(args.paginationOpts.numItems) ||
47
+ args.paginationOpts.numItems < 1 ||
48
+ args.paginationOpts.numItems > 100
49
+ )
50
+ throw new Error("Ownership page size must be between 1 and 100");
51
+ const generation = (await ownerGeneration(ctx, args))?.generation ?? 0;
52
+ const page = await paginator(ctx.db, schema)
53
+ .query("financialOwnership")
54
+ .withIndex("by_owner", (q) =>
55
+ q.eq("userId", args.userId).eq("orgId", args.orgId),
56
+ )
57
+ .order("desc")
58
+ .paginate({
59
+ ...args.paginationOpts,
60
+ maximumRowsRead: 200,
61
+ maximumBytesRead: 1_000_000,
62
+ });
63
+ return { ...page, coverage: "unknown" as const, generation };
64
+ },
65
+ });
@@ -0,0 +1,35 @@
1
+ import { defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+
4
+ export const ownerFields = {
5
+ userId: v.string(),
6
+ orgId: v.optional(v.string()),
7
+ };
8
+ export const sourceValidator = v.object({
9
+ integration: v.string(),
10
+ recordId: v.string(),
11
+ });
12
+ export const registrationFields = {
13
+ bucketKey: v.string(),
14
+ kind: v.union(v.literal("stripe_account"), v.literal("logical")),
15
+ ...ownerFields,
16
+ source: sourceValidator,
17
+ generation: v.number(),
18
+ };
19
+ export const registrationDoc = v.object({
20
+ ...registrationFields,
21
+ _id: v.id("financialOwnership"),
22
+ _creationTime: v.number(),
23
+ });
24
+ export const ownershipTable = defineTable(registrationFields)
25
+ .index("by_bucket_key", ["bucketKey"])
26
+ .index("by_owner", ["userId", "orgId"]);
27
+ export const generationsTable = defineTable({
28
+ ...ownerFields,
29
+ generation: v.number(),
30
+ }).index("by_owner", ["userId", "orgId"]);
31
+ export const registrationResult = v.object({
32
+ status: v.literal("registered"),
33
+ coverage: v.literal("unknown"),
34
+ registration: registrationDoc,
35
+ });