@volter/twin-stripe 0.1.2 → 2.0.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.
Files changed (229) hide show
  1. package/README.md +96 -27
  2. package/client/dashboard-api.ts +286 -0
  3. package/client/stripe-mirror.css +272 -159
  4. package/client/stripe-mirror.tsx +1384 -541
  5. package/dist/client/dashboard-api.d.ts +107 -0
  6. package/dist/client/dashboard-api.js +238 -0
  7. package/dist/client/dashboard-api.ts +286 -0
  8. package/dist/client/stripe-mirror.bundle.js +236 -0
  9. package/dist/client/stripe-mirror.css +275 -0
  10. package/dist/client/stripe-mirror.d.ts +134 -0
  11. package/dist/client/stripe-mirror.js +823 -0
  12. package/dist/client/stripe-mirror.tsx +1534 -0
  13. package/dist/src/cli.d.ts +2 -0
  14. package/dist/src/cli.js +39 -0
  15. package/dist/src/generated/events.gen.json +1 -0
  16. package/dist/src/generated/surface.gen.json +1 -0
  17. package/dist/src/generated/ui.gen.json +1 -0
  18. package/dist/src/index.d.ts +14 -0
  19. package/dist/src/index.js +75 -0
  20. package/dist/src/manifest.d.ts +2 -0
  21. package/dist/src/manifest.js +1070 -0
  22. package/dist/src/screens/checkout.d.ts +31 -0
  23. package/dist/src/screens/checkout.js +255 -0
  24. package/dist/src/screens/connect-oauth.d.ts +27 -0
  25. package/dist/src/screens/connect-oauth.js +414 -0
  26. package/dist/src/screens/connect-settings.d.ts +22 -0
  27. package/dist/src/screens/connect-settings.js +103 -0
  28. package/dist/src/screens/consent-skin.d.ts +4 -0
  29. package/dist/src/screens/consent-skin.js +18 -0
  30. package/dist/src/screens/financial-connections.d.ts +5 -0
  31. package/dist/src/screens/financial-connections.js +90 -0
  32. package/dist/src/screens/identity.d.ts +5 -0
  33. package/dist/src/screens/identity.js +86 -0
  34. package/dist/src/screens/industries.d.ts +1 -0
  35. package/dist/src/screens/industries.js +267 -0
  36. package/dist/src/screens/onboarding.d.ts +13 -0
  37. package/dist/src/screens/onboarding.js +225 -0
  38. package/dist/src/screens/portal.d.ts +5 -0
  39. package/dist/src/screens/portal.js +216 -0
  40. package/dist/src/screens/public-details.d.ts +5 -0
  41. package/dist/src/screens/public-details.js +90 -0
  42. package/dist/src/semantics/after-payment.d.ts +22 -0
  43. package/dist/src/semantics/after-payment.js +99 -0
  44. package/dist/src/semantics/apps-secrets.d.ts +2 -0
  45. package/dist/src/semantics/apps-secrets.js +54 -0
  46. package/dist/src/semantics/balance.d.ts +11 -0
  47. package/dist/src/semantics/balance.js +195 -0
  48. package/dist/src/semantics/billing.d.ts +2 -0
  49. package/dist/src/semantics/billing.js +220 -0
  50. package/dist/src/semantics/charges.d.ts +28 -0
  51. package/dist/src/semantics/charges.js +209 -0
  52. package/dist/src/semantics/checkout.d.ts +15 -0
  53. package/dist/src/semantics/checkout.js +316 -0
  54. package/dist/src/semantics/connect.d.ts +5 -0
  55. package/dist/src/semantics/connect.js +493 -0
  56. package/dist/src/semantics/coupons.d.ts +6 -0
  57. package/dist/src/semantics/coupons.js +92 -0
  58. package/dist/src/semantics/credit-notes.d.ts +2 -0
  59. package/dist/src/semantics/credit-notes.js +172 -0
  60. package/dist/src/semantics/customers.d.ts +6 -0
  61. package/dist/src/semantics/customers.js +429 -0
  62. package/dist/src/semantics/disputes.d.ts +2 -0
  63. package/dist/src/semantics/disputes.js +51 -0
  64. package/dist/src/semantics/entitlements.d.ts +2 -0
  65. package/dist/src/semantics/entitlements.js +95 -0
  66. package/dist/src/semantics/ephemeral-keys.d.ts +2 -0
  67. package/dist/src/semantics/ephemeral-keys.js +34 -0
  68. package/dist/src/semantics/files.d.ts +2 -0
  69. package/dist/src/semantics/files.js +125 -0
  70. package/dist/src/semantics/invoices.d.ts +18 -0
  71. package/dist/src/semantics/invoices.js +545 -0
  72. package/dist/src/semantics/issuing.d.ts +13 -0
  73. package/dist/src/semantics/issuing.js +575 -0
  74. package/dist/src/semantics/ledger.d.ts +59 -0
  75. package/dist/src/semantics/ledger.js +200 -0
  76. package/dist/src/semantics/payment-intents.d.ts +18 -0
  77. package/dist/src/semantics/payment-intents.js +404 -0
  78. package/dist/src/semantics/payment-links.d.ts +2 -0
  79. package/dist/src/semantics/payment-links.js +133 -0
  80. package/dist/src/semantics/payment-methods.d.ts +20 -0
  81. package/dist/src/semantics/payment-methods.js +140 -0
  82. package/dist/src/semantics/plans.d.ts +5 -0
  83. package/dist/src/semantics/plans.js +121 -0
  84. package/dist/src/semantics/platform.d.ts +9 -0
  85. package/dist/src/semantics/platform.js +206 -0
  86. package/dist/src/semantics/products.d.ts +2 -0
  87. package/dist/src/semantics/products.js +140 -0
  88. package/dist/src/semantics/radar.d.ts +2 -0
  89. package/dist/src/semantics/radar.js +83 -0
  90. package/dist/src/semantics/refunds.d.ts +9 -0
  91. package/dist/src/semantics/refunds.js +195 -0
  92. package/dist/src/semantics/renewals.d.ts +47 -0
  93. package/dist/src/semantics/renewals.js +251 -0
  94. package/dist/src/semantics/setup-intents.d.ts +2 -0
  95. package/dist/src/semantics/setup-intents.js +84 -0
  96. package/dist/src/semantics/shared.d.ts +82 -0
  97. package/dist/src/semantics/shared.js +203 -0
  98. package/dist/src/semantics/subscription-schedules.d.ts +2 -0
  99. package/dist/src/semantics/subscription-schedules.js +119 -0
  100. package/dist/src/semantics/subscriptions.d.ts +11 -0
  101. package/dist/src/semantics/subscriptions.js +605 -0
  102. package/dist/src/semantics/tax.d.ts +2 -0
  103. package/dist/src/semantics/tax.js +197 -0
  104. package/dist/src/semantics/terminal.d.ts +5 -0
  105. package/dist/src/semantics/terminal.js +182 -0
  106. package/dist/src/semantics/test-cards.d.ts +4 -0
  107. package/dist/src/semantics/test-cards.js +7 -0
  108. package/dist/src/semantics/test-clocks.d.ts +6 -0
  109. package/dist/src/semantics/test-clocks.js +73 -0
  110. package/dist/src/semantics/tokens.d.ts +4 -0
  111. package/dist/src/semantics/tokens.js +44 -0
  112. package/dist/src/semantics/transfers.d.ts +2 -0
  113. package/dist/src/semantics/transfers.js +154 -0
  114. package/dist/src/semantics/treasury.d.ts +2 -0
  115. package/dist/src/semantics/treasury.js +377 -0
  116. package/dist/src/semantics/webhook-endpoints.d.ts +3 -0
  117. package/dist/src/semantics/webhook-endpoints.js +85 -0
  118. package/dist/src/stripe-budget.d.ts +55 -0
  119. package/dist/src/stripe-budget.js +155 -0
  120. package/dist/src/stripe-capabilities.d.ts +3 -0
  121. package/dist/src/stripe-capabilities.js +5695 -0
  122. package/dist/src/stripe-conformance.d.ts +43 -0
  123. package/dist/src/stripe-conformance.js +105 -0
  124. package/dist/src/stripe-connector.d.ts +161 -0
  125. package/dist/src/stripe-connector.js +414 -0
  126. package/dist/src/stripe-emit.d.ts +2 -0
  127. package/dist/src/stripe-emit.js +145 -0
  128. package/dist/src/stripe-events.d.ts +93 -0
  129. package/dist/src/stripe-events.js +392 -0
  130. package/dist/src/stripe-js.d.ts +4 -0
  131. package/dist/src/stripe-js.js +70 -0
  132. package/dist/src/stripe-mirror-ui.d.ts +15 -0
  133. package/dist/src/stripe-mirror-ui.js +87 -0
  134. package/dist/src/stripe-params.d.ts +3 -0
  135. package/dist/src/stripe-params.js +43 -0
  136. package/dist/src/stripe-perform-harness.d.ts +9 -0
  137. package/dist/src/stripe-perform-harness.js +26 -0
  138. package/dist/src/stripe-server.d.ts +33 -0
  139. package/dist/src/stripe-server.js +393 -0
  140. package/dist/src/stripe-shared.d.ts +109 -0
  141. package/dist/src/stripe-shared.js +276 -0
  142. package/dist/src/stripe-twin.d.ts +155 -0
  143. package/dist/src/stripe-twin.js +1232 -0
  144. package/dist/src/stripe-ui-conformance.d.ts +5 -0
  145. package/dist/src/stripe-ui-conformance.js +79 -0
  146. package/dist/src/stripe-ui-structure.d.ts +3 -0
  147. package/dist/src/stripe-ui-structure.js +168 -0
  148. package/dist/src/stripe-version.d.ts +12 -0
  149. package/dist/src/stripe-version.js +287 -0
  150. package/dist/test-fixtures/stripe-known-deviations.json +110 -0
  151. package/dist/test-fixtures/stripe-openapi-operations.SOURCE.md +14 -0
  152. package/dist/test-fixtures/stripe-openapi-operations.json +4717 -0
  153. package/dist/test-fixtures/stripe-schemas.SOURCE.md +35 -0
  154. package/dist/test-fixtures/stripe-schemas.json +3813 -0
  155. package/package.json +18 -10
  156. package/src/cli.ts +7 -7
  157. package/src/generated/events.gen.json +1 -0
  158. package/src/generated/surface.gen.json +1 -0
  159. package/src/generated/ui.gen.json +1 -0
  160. package/src/index.ts +34 -10
  161. package/src/manifest.ts +1102 -0
  162. package/src/screens/checkout.tsx +267 -0
  163. package/src/screens/connect-oauth.tsx +400 -0
  164. package/src/screens/connect-settings.tsx +121 -0
  165. package/src/screens/consent-skin.ts +20 -0
  166. package/src/screens/financial-connections.tsx +101 -0
  167. package/src/screens/identity.tsx +96 -0
  168. package/src/screens/industries.ts +267 -0
  169. package/src/screens/onboarding.tsx +243 -0
  170. package/src/screens/portal.tsx +220 -0
  171. package/src/screens/public-details.tsx +105 -0
  172. package/src/semantics/after-payment.ts +118 -0
  173. package/src/semantics/apps-secrets.ts +58 -0
  174. package/src/semantics/balance.ts +209 -0
  175. package/src/semantics/billing.ts +216 -0
  176. package/src/semantics/charges.ts +220 -0
  177. package/src/semantics/checkout.ts +310 -0
  178. package/src/semantics/connect.ts +487 -0
  179. package/src/semantics/coupons.ts +97 -0
  180. package/src/semantics/credit-notes.ts +168 -0
  181. package/src/semantics/customers.ts +432 -0
  182. package/src/semantics/disputes.ts +62 -0
  183. package/src/semantics/entitlements.ts +94 -0
  184. package/src/semantics/ephemeral-keys.ts +34 -0
  185. package/src/semantics/files.ts +143 -0
  186. package/src/semantics/invoices.ts +545 -0
  187. package/src/semantics/issuing.ts +590 -0
  188. package/src/semantics/ledger.ts +253 -0
  189. package/src/semantics/payment-intents.ts +420 -0
  190. package/src/semantics/payment-links.ts +148 -0
  191. package/src/semantics/payment-methods.ts +145 -0
  192. package/src/semantics/plans.ts +131 -0
  193. package/src/semantics/platform.ts +220 -0
  194. package/src/semantics/products.ts +154 -0
  195. package/src/semantics/radar.ts +85 -0
  196. package/src/semantics/refunds.ts +218 -0
  197. package/src/semantics/renewals.ts +274 -0
  198. package/src/semantics/setup-intents.ts +87 -0
  199. package/src/semantics/shared.ts +226 -0
  200. package/src/semantics/subscription-schedules.ts +129 -0
  201. package/src/semantics/subscriptions.ts +610 -0
  202. package/src/semantics/tax.ts +220 -0
  203. package/src/semantics/terminal.ts +195 -0
  204. package/src/semantics/test-cards.ts +7 -0
  205. package/src/semantics/test-clocks.ts +77 -0
  206. package/src/semantics/tokens.ts +52 -0
  207. package/src/semantics/transfers.ts +174 -0
  208. package/src/semantics/treasury.ts +383 -0
  209. package/src/semantics/webhook-endpoints.ts +87 -0
  210. package/src/stripe-budget.ts +4 -4
  211. package/src/stripe-capabilities.ts +2258 -380
  212. package/src/stripe-conformance.ts +19 -7
  213. package/src/stripe-connector.ts +68 -40
  214. package/src/stripe-emit.ts +15 -8
  215. package/src/stripe-events.ts +102 -40
  216. package/src/stripe-js.ts +70 -0
  217. package/src/stripe-mirror-ui.ts +28 -298
  218. package/src/stripe-params.ts +44 -0
  219. package/src/stripe-perform-harness.ts +29 -0
  220. package/src/stripe-server.ts +318 -38
  221. package/src/stripe-shared.ts +297 -0
  222. package/src/stripe-twin.ts +434 -5325
  223. package/src/stripe-ui-conformance.ts +70 -107
  224. package/src/stripe-ui-structure.ts +124 -348
  225. package/src/stripe-version.ts +281 -0
  226. package/test-fixtures/stripe-known-deviations.json +8 -8
  227. package/test-fixtures/stripe-openapi-operations.json +1188 -2855
  228. package/test-fixtures/stripe-schemas.json +85 -12
  229. package/src/stripe-form.ts +0 -35
@@ -7,18 +7,151 @@
7
7
  // The surface is a plain `fetch` (`createStripeTwinFetch`) and the SERVER is one line of
8
8
  // `Bun.serve` around it — see that factory's docstring for why (a serverless entry has no
9
9
  // port to bind, so it mounts the fetch in-process).
10
- import { handleStripeTwinRequest } from './stripe-twin.ts';
11
- import { worldNow, statefulTwinManifest} from '@volter/twin';
10
+ import { bindSemantics, coreFor, createDerivedFetch, crossCutting, readParams, semanticsContext, serveHttp, vendorError, type DerivedCall, type DerivedFetch } from '@volter/world-core';
11
+ import { stripeCheckoutFlow } from './screens/checkout.tsx';
12
+ import { stripeJs } from './stripe-js.ts';
13
+ import { stripeFinancialConnectionsFlow } from './screens/financial-connections.tsx';
14
+ import { stripeIdentityFlow } from './screens/identity.tsx';
15
+ import { stripeOnboardingFlow } from './screens/onboarding.tsx';
16
+ import { stripePortalFlow } from './screens/portal.tsx';
17
+ import { stripePublicDetailsFlow } from './screens/public-details.tsx';
18
+ import { connectionRevoked, oauthKeyAccount, redactKey, stripeConnectOAuthFlow } from './screens/connect-oauth.tsx';
19
+ import { stripeConnectSettingsFlow } from './screens/connect-settings.tsx';
20
+ import surface from './generated/surface.gen.json' with { type: 'json' };
21
+ import { manifest } from './manifest.ts';
22
+ import { appsSecrets } from './semantics/apps-secrets.ts';
23
+ import { balances } from './semantics/balance.ts';
24
+ import { billing } from './semantics/billing.ts';
25
+ import { charges } from './semantics/charges.ts';
26
+ import { checkout } from './semantics/checkout.ts';
27
+ import { connect } from './semantics/connect.ts';
28
+ import { coupons } from './semantics/coupons.ts';
29
+ import { creditNotes } from './semantics/credit-notes.ts';
30
+ import { customers } from './semantics/customers.ts';
31
+ import { disputes } from './semantics/disputes.ts';
32
+ import { entitlements } from './semantics/entitlements.ts';
33
+ import { ephemeralKeys } from './semantics/ephemeral-keys.ts';
34
+ import { files } from './semantics/files.ts';
35
+ import { invoices } from './semantics/invoices.ts';
36
+ import { issuing, lapseRealtimeRequests } from './semantics/issuing.ts';
37
+ import { paymentIntents } from './semantics/payment-intents.ts';
38
+ import { paymentLinks } from './semantics/payment-links.ts';
39
+ import { paymentMethods } from './semantics/payment-methods.ts';
40
+ import { platform } from './semantics/platform.ts';
41
+ import { plans } from './semantics/plans.ts';
42
+ import { products } from './semantics/products.ts';
43
+ import { radar } from './semantics/radar.ts';
44
+ import { refunds } from './semantics/refunds.ts';
45
+ import { setupIntents } from './semantics/setup-intents.ts';
46
+ import { subscriptionSchedules } from './semantics/subscription-schedules.ts';
47
+ import { subscriptions } from './semantics/subscriptions.ts';
48
+ import { tax } from './semantics/tax.ts';
49
+ import { terminal } from './semantics/terminal.ts';
50
+ import { testClocks } from './semantics/test-clocks.ts';
51
+ import { ledger } from './semantics/ledger.ts';
52
+ import { tokens } from './semantics/tokens.ts';
53
+ import { transfers } from './semantics/transfers.ts';
54
+ import { treasury } from './semantics/treasury.ts';
55
+ import { webhookEndpoints } from './semantics/webhook-endpoints.ts';
56
+ import { advancePayouts, balanceBody, payDuePayouts } from './semantics/balance.ts';
57
+ import { settleDueEntries } from './semantics/ledger.ts';
58
+ import { settleHeldRefunds } from './semantics/refunds.ts';
59
+ import { settleBankDebits } from './semantics/payment-intents.ts';
60
+ import { lapseCoupons } from './semantics/coupons.ts';
61
+ import { finishClockAdvances } from './semantics/test-clocks.ts';
62
+ import { settleTopups } from './semantics/terminal.ts';
63
+ import { finishReportRuns } from './semantics/platform.ts';
64
+ import { advanceBilling } from './semantics/renewals.ts';
65
+ import { refuseParameters } from './stripe-params.ts';
66
+ import { afterStripeWrite, handleStripeDoor, PLATFORM_ACCOUNT_ID } from './stripe-twin.ts';
67
+ import { worldNow, statefulTwinManifest} from '@volter/world-core';
68
+ import { expandOf, render, servesCurrent, withoutEndpointSecret } from './stripe-version.ts';
12
69
 
13
70
  /** Options shared by the fetch handler and the Bun.serve wrapper around it. `port` is a
14
71
  * BIND concern the fetch ignores; it stays in one shape so a caller configures the twin
15
72
  * once whichever way it is mounted. */
16
- export type StripeTwinOptions = { root?: string; port?: number; readOnly?: boolean };
73
+ export type StripeTwinOptions = { root?: string; port?: number; readOnly?: boolean; /** the World instant, when a caller pins it */ clock?: () => string };
74
+
75
+ // ── what a publishable key may call ──
76
+ // "Publishable API key pk_... | Safe to expose: Yes | API key for Stripe.js, Elements, and mobile SDKs. It can identify
77
+ // your account and create tokens or PaymentMethods from payment details, but it can't perform sensitive operations such
78
+ // as creating charges or reading account data" (docs.stripe.com/keys). The served spec names the calls a publishable key
79
+ // makes with an object's client secret: "You can retrieve a PaymentIntent client-side using a publishable key when the
80
+ // client_secret is provided in the query string" (GET /v1/payment_intents/{intent}), "Client-side retrieval using a
81
+ // publishable key is allowed when the client_secret is provided" (GET /v1/setup_intents/{intent}), "Required if a
82
+ // publishable key is used to retrieve the source" (GET /v1/sources/{source}), and the confirm and verify_microdeposits
83
+ // calls that take "The client secret of the PaymentIntent" (or SetupIntent). Anything else is refused with Stripe's
84
+ // code: "secret_key_required | The API key provided is a publishable key, but a secret key is required"
85
+ // (docs.stripe.com/error-codes), as 403, "The API key doesn't have permissions to perform the request"
86
+ // (docs.stripe.com/api/errors).
87
+ // Where the documentation stops and the twin decides: the list above is the whole of what a publishable key may call
88
+ // (Stripe publishes no complete list); a client-secret call without the secret answers parameter_missing, and one with a
89
+ // secret that is not the object's answers the object's 404, as though the key could not see it.
90
+ const PUBLISHABLE_CREATES = new Set(['PostTokens', 'PostPaymentMethods']);
91
+ const BY_CLIENT_SECRET: Record<string, { type: string; param: string }> = {
92
+ GetPaymentIntentsIntent: { type: 'payment_intent', param: 'intent' },
93
+ PostPaymentIntentsIntentConfirm: { type: 'payment_intent', param: 'intent' },
94
+ PostPaymentIntentsIntentVerifyMicrodeposits: { type: 'payment_intent', param: 'intent' },
95
+ GetSetupIntentsIntent: { type: 'setup_intent', param: 'intent' },
96
+ PostSetupIntentsIntentConfirm: { type: 'setup_intent', param: 'intent' },
97
+ PostSetupIntentsIntentVerifyMicrodeposits: { type: 'setup_intent', param: 'intent' },
98
+ GetSourcesSource: { type: 'source', param: 'source' },
99
+ };
100
+
101
+ /** Stripe's refusal of a call a publishable key may not make, or undefined when the key may make it. */
102
+ async function publishableKeyRefused(call: DerivedCall, scope: { root?: string; clock?: () => string }): Promise<Response | undefined> {
103
+ const key = /^bearer\s+(\S+)/i.exec(call.request.headers.get('authorization') ?? '')?.[1] ?? '';
104
+ if (!key.startsWith('pk_')) return undefined;
105
+ if (PUBLISHABLE_CREATES.has(call.operation.id)) return undefined;
106
+ const scoped = BY_CLIENT_SECRET[call.operation.id];
107
+ if (!scoped) return vendorError(manifest, { status: 403, code: 'secret_key_required', message: 'The API key provided is a publishable key, but a secret key is required.' });
108
+ const params = await readParams(manifest, call.request.clone(), call.operation);
109
+ const secret = typeof params.client_secret === 'string' ? params.client_secret : '';
110
+ if (!secret) return vendorError(manifest, { status: 400, code: 'parameter_missing', param: 'client_secret', message: 'Missing required param: client_secret.' });
111
+ const id = call.params[scoped.param] ?? '';
112
+ // the context reads a body of its own, so the handler after this still has the request's
113
+ const ctx = await semanticsContext(manifest, call.request.clone(), call.operation, scope);
114
+ return ctx.get(scoped.type, id)?.client_secret === secret ? undefined : wrongClientSecret(scoped, id);
115
+ }
116
+
117
+ // ── an account whose OAuth connection was revoked ──
118
+ // "After revocation, the account can't be accessed by your platform in the Dashboard or through the API"
119
+ // (docs.stripe.com/connect/oauth-reference, deauthorize; so too a connection revoked by a reused code). A call made as it
120
+ // (the Stripe-Account header) or naming it (/v1/accounts/{account}…) is refused with the error Stripe documents for a
121
+ // Stripe-Account the key cannot use: "account_invalid | The account ID provided as a value for the Stripe-Account header
122
+ // is invalid" (docs.stripe.com/error-codes), as 403, "The API key doesn't have permissions to perform the request"
123
+ // (docs.stripe.com/api/errors). Where the documentation stops and the twin decides: the message's wording; an account
124
+ // the platform created itself, or never connected by OAuth, is not affected.
125
+ async function revokedAccountRefused(call: DerivedCall, scope: { root?: string; clock?: () => string }): Promise<Response | undefined> {
126
+ const named = [call.request.headers.get('stripe-account') ?? undefined, call.operation.path.startsWith('/v1/accounts/{account}') ? call.params.account : undefined].filter((a): a is string => !!a);
127
+ if (!named.length) return undefined;
128
+ const ctx = await semanticsContext(manifest, new Request(call.request.url), call.operation, scope); // the rows only: no body read
129
+ const revoked = named.find((a) => connectionRevoked(ctx, a));
130
+ if (!revoked) return undefined;
131
+ const key = requestKey(call.request);
132
+ return vendorError(manifest, { status: 403, code: 'account_invalid', message: `The provided key '${redactKey(key)}' does not have access to account '${revoked}' (or that account does not exist). Application access may have been revoked.` });
133
+ }
134
+
135
+ /** The API key a request carries: Bearer, or Basic's user (`curl -u sk_…:`, docs.stripe.com/api/authentication). */
136
+ function requestKey(request: Request): string {
137
+ const header = request.headers.get('authorization') ?? '';
138
+ const bearer = /^bearer\s+(\S+)/i.exec(header)?.[1];
139
+ if (bearer) return bearer;
140
+ const basic = /^basic\s+(\S+)/i.exec(header)?.[1];
141
+ if (basic) { try { return atob(basic).split(':')[0] ?? ''; } catch { return ''; } }
142
+ return '';
143
+ }
144
+
145
+ /** A client-secret call whose secret is not the object's: answered as though the key could not see it (the twin's
146
+ * decision, above). */
147
+ function wrongClientSecret(scoped: { type: string; param: string }, id: string): Response {
148
+ return vendorError(manifest, { status: 404, code: 'resource_missing', param: scoped.param, message: `No such ${scoped.type}: '${id}'` });
149
+ }
17
150
 
18
151
  /**
19
152
  * The whole Stripe serve path as a plain `(Request) => Response` — the `/twin` manifest
20
153
  * door, the header threading (idempotency key, pinned API version, Connect account) and
21
- * the dispatch into `handleStripeTwinRequest`. NOTHING about it is port-bound.
154
+ * the derived dispatch over the hand-written routes. NOTHING about it is port-bound.
22
155
  *
23
156
  * Why this is the factory and `createStripeTwinServer` is a wrapper (runtime contract R12,
24
157
  * the Cloudflare ruling): a Durable Object / Worker entry has no loopback ports — it mounts
@@ -33,49 +166,196 @@ export type StripeTwinOptions = { root?: string; port?: number; readOnly?: boole
33
166
  * `finally` fires when `fn` RETURNS, i.e. at the first `await`, restoring the previous store
34
167
  * under the rest of the request.
35
168
  */
36
- export function createStripeTwinFetch(options: StripeTwinOptions): (request: Request) => Promise<Response> {
169
+ export function createStripeTwinFetch(options: StripeTwinOptions): DerivedFetch {
37
170
  const readOnly = options.readOnly ?? false;
38
- return async function stripeTwinFetch(request: Request): Promise<Response> {
171
+ const scope = { ...(options.root !== undefined ? { root: options.root } : {}), ...(options.clock ? { clock: options.clock } : {}) };
172
+ // The derived dispatch owns the API: an operation with a semantics handler is served by it, one on a
173
+ // resource the manifest declares by the derived core, and one neither models answers Stripe's
174
+ // unrecognized-URL 404.
175
+ const guard = crossCutting(manifest, { readOnly, ...scope });
176
+ const handlerMap = { ...billing, ...paymentIntents, ...customers, ...products, ...plans, ...charges, ...refunds, ...setupIntents, ...paymentMethods, ...subscriptions, ...invoices, ...checkout, ...ephemeralKeys, ...disputes, ...balances, ...coupons, ...creditNotes, ...subscriptionSchedules, ...entitlements, ...testClocks, ...webhookEndpoints, ...connect, ...transfers, ...appsSecrets, ...tokens, ...files, ...tax, ...paymentLinks, ...radar, ...issuing, ...terminal, ...treasury, ...platform, ...ledger };
177
+ const core = coreFor(manifest, scope);
178
+ const derived = createDerivedFetch({
179
+ surface,
180
+ handlers: bindSemantics(manifest, handlerMap, scope),
181
+ core,
182
+ // after the credential and the version, a publishable key is held to the client-side calls, then a request's
183
+ // parameters are checked against the operation's (stripe-params.ts)
184
+ around: (call, next) => guard(call, async () => (await publishableKeyRefused(call, scope)) ?? (await revokedAccountRefused(call, scope)) ?? (await refuseParameters(call)) ?? next()),
185
+ gap: (request) => vendorError(manifest, { status: 404, message: `Unrecognized request URL (${request.method}: ${new URL(request.url).pathname}).` }),
186
+ });
187
+ // the hosted flows sit beside the API: checkout.stripe.com's payment page, billing.stripe.com's customer portal,
188
+ // connect.stripe.com's onboarding and its OAuth endpoints (screens/connect-oauth.tsx), verify.stripe.com's identity
189
+ // check and the bank-linking flow Stripe.js opens, and the Dashboard's Public details page
190
+ // (dashboard.stripe.com/settings/public, the platform's customer-facing name) and Connect OAuth settings
191
+ // (dashboard.stripe.com/settings/connect/onboarding-options/oauth: the client_id, OAuth on, the redirect URIs);
192
+ // a read-only twin takes no payments and moves nothing
193
+ const flows = [stripeCheckoutFlow(scope), stripePortalFlow(scope), stripeOnboardingFlow(scope), stripeIdentityFlow(scope), stripeFinancialConnectionsFlow(scope), stripePublicDetailsFlow(scope), stripeConnectOAuthFlow(scope), stripeConnectSettingsFlow(scope)];
194
+ // the twin's own doors sit in front of the API: discovery, and what stands in for an act Stripe's API
195
+ // does not have (stripe-twin.ts)
196
+ // GET /twin: what this twin is (not Stripe's; a host reads it)
197
+ function discovery(): Response {
198
+ return Response.json(statefulTwinManifest({ vendor: 'stripe', twinOf: 'the Stripe REST API', stores: 'customers, payment objects, checkout sessions, products/prices and webhook endpoints (signed events)' }));
199
+ }
200
+ // /_twin/…: a door's body is read as the API's is: a form, or JSON
201
+ const twinDoor = async (request: Request, url: URL): Promise<Response | undefined> => {
202
+ const answer = await handleStripeDoor({
203
+ method: request.method, path: url.pathname, readOnly,
204
+ occurredAt: options.clock ? options.clock() : worldNow(),
205
+ ...(options.root !== undefined ? { root: options.root } : {}),
206
+ }, await readParams(manifest, request));
207
+ return answer && Response.json(answer.body, { status: answer.status, headers: { 'request-id': 'req_twin' } });
208
+ };
209
+ const door = async (request: Request): Promise<Response | undefined> => {
39
210
  const url = new URL(request.url);
40
- // GET /twin — the discovery manifest (education inside the twin).
41
- if (request.method === 'GET' && url.pathname.replace(/\/+$/, '') === '/twin') {
42
- return Response.json(statefulTwinManifest({ vendor: 'stripe', twinOf: 'the Stripe REST API', stores: 'customers, payment objects, checkout sessions, products/prices and webhook endpoints (signed events)' }));
211
+ if (request.method === 'GET' && url.pathname.replace(/\/+$/, '') === '/twin') return discovery();
212
+ return url.pathname.startsWith('/_twin/') ? twinDoor(request, url) : undefined;
213
+ };
214
+ // time's moves Stripe makes on its own (a subscription renewing at its period's end, its renewal charged an hour
215
+ // later: semantics/renewals.ts; each account's automatic payouts: semantics/balance.ts) are caught up to the World's clock before anything is answered, so every door
216
+ // (the API, the hosted pages) reads the account as it stands now
217
+ const billingClock = (surface.operations as Array<{ id: string; method: string; path: string; class: string }>).find((o) => o.id === 'GetSubscriptions')!;
218
+ const catchUp = async (request: Request): Promise<void> => {
219
+ if (readOnly) return;
220
+ const ctx = await semanticsContext(manifest, new Request(request.url), billingClock, scope);
221
+ // a test clock advanced by the last request has reached its time (semantics/test-clocks.ts)
222
+ await finishClockAdvances(ctx);
223
+ await advanceBilling(ctx);
224
+ // a submitted bank debit settles (in test mode at once) before anything is answered (semantics/payment-intents.ts)
225
+ await settleBankDebits(ctx);
226
+ // a coupon past its redeem_by is no longer valid (semantics/coupons.ts)
227
+ await lapseCoupons(ctx);
228
+ // a top-up's funds arrive five days after it is made (semantics/terminal.ts)
229
+ await settleTopups(ctx);
230
+ // a report run completes (semantics/platform.ts)
231
+ await finishReportRuns(ctx);
232
+ // a real-time authorization request no one answered is decided when its window ends (semantics/issuing.ts)
233
+ await lapseRealtimeRequests(ctx);
234
+ // a refund held for want of balance is made when funds cover it, before any payout takes them (semantics/refunds.ts)
235
+ await settleHeldRefunds(ctx);
236
+ await advancePayouts(ctx);
237
+ };
238
+ // Time's EVENTS, sent on the vendor's clock through a twin-only drain door, as the qstash and vercel twins send
239
+ // theirs (a caller — a runner's drainer — drives each move). POST /_twin/drain catches time up as every request
240
+ // does, then writes what time settled on each account: payouts whose arrival date came (pending → paid, sent as
241
+ // payout.paid) and funds that came due (pending → available), for which the account is sent one balance.available
242
+ // ("Occurs whenever your Stripe balance has been updated (e.g., when a charge is available to be paid out)",
243
+ // docs.stripe.com/api/events/types) carrying its Balance, when an entry that settled adds to it ("This event is not
244
+ // fired for negative transactions", the same page); a connected account's events go to Connect endpoints.
245
+ // A read already sees these moves; the drain is what makes Stripe's events about them arrive. Answers what it sent.
246
+ const drain = async (request: Request): Promise<Response> => {
247
+ if (readOnly) return Response.json({ error: 'twin is read-only; omit readOnly to accept writes' }, { status: 405 });
248
+ await catchUp(request);
249
+ const at = (account?: string) => semanticsContext(manifest, new Request(request.url, account ? { headers: { 'stripe-account': account } } : {}), billingClock, scope);
250
+ const platformCtx = await at();
251
+ const accounts = [undefined, ...platformCtx.rows('account').map((a) => String(a.id)).filter((id) => id !== PLATFORM_ACCOUNT_ID)];
252
+ const delivered: Array<{ type: string; id?: string; account?: string }> = [];
253
+ for (const account of accounts) {
254
+ const ctx = account ? await at(account) : platformCtx;
255
+ for (const id of await payDuePayouts(ctx)) delivered.push({ type: 'payout.paid', id, ...(account ? { account } : {}) });
256
+ if ((await settleDueEntries(ctx)).some((t) => Number(t.net) > 0)) {
257
+ await afterStripeWrite('balance', 'balance.available', balanceBody(ctx), options.root, ctx.occurredAt, undefined, account);
258
+ delivered.push({ type: 'balance.available', ...(account ? { account } : {}) });
259
+ }
43
260
  }
44
- const body = request.method === 'GET' ? '' : await request.text();
45
- // Stripe sends the idempotency key as the `Idempotency-Key` request header; the
46
- // real SDK sets it from { idempotencyKey } on a write call. Thread it through so
47
- // a replay returns the stored response without re-applying the write.
48
- const idempotencyKey = request.headers.get('idempotency-key') ?? undefined;
49
- // Stripe pins API behavior via the `Stripe-Version` request header; the real SDK
50
- // sets it from { apiVersion }. Thread it through so the twin can reflect it (and
51
- // reject a malformed value with a 400) exactly like real Stripe.
52
- const apiVersion = request.headers.get('stripe-version') ?? undefined;
53
- // Connect: the SDK sets `Stripe-Account` from { stripeAccount } to act on behalf of a
54
- // connected account. Thread it through so account-scoped writes (e.g. a payout created
55
- // on the connected account's balance) are attributed to that account, like real Stripe.
56
- const stripeAccount = request.headers.get('stripe-account') ?? undefined;
57
- const { status, body: out } = await handleStripeTwinRequest({
58
- method: request.method,
59
- path: url.pathname + (url.search || ''),
60
- body,
61
- readOnly,
62
- ...(apiVersion ? { apiVersion } : {}),
63
- ...(stripeAccount ? { stripeAccount } : {}),
64
- // The WORLD instant (R9): served `created` epochs come from the world clock, never
65
- // wall time. Embedded/test callers pass their own occurredAt.
66
- occurredAt: worldNow(),
67
- ...(idempotencyKey ? { idempotencyKey } : {}),
68
- ...(options.root !== undefined ? { root: options.root } : {}),
69
- });
70
- return new Response(JSON.stringify(out), { status, headers: { 'content-type': 'application/json', 'request-id': 'req_twin' } });
261
+ return Response.json({ delivered });
262
+ };
263
+ const served = async (request: Request): Promise<Response> => {
264
+ if (request.method === 'POST' && new URL(request.url).pathname.replace(/\/+$/, '') === '/_twin/drain') return drain(request);
265
+ const opened = await door(request);
266
+ if (opened) return opened;
267
+ // the client library an application's page loads from js.stripe.com (stripe-js.ts); it moves nothing, so a
268
+ // read-only twin serves it too
269
+ const library = stripeJs(request);
270
+ if (library) return library;
271
+ await catchUp(request);
272
+ if (!readOnly) for (const flow of flows) { const page = await flow(request); if (page) return page; }
273
+ const acting = await actingAsOAuthKey(request);
274
+ if (acting instanceof Response) return acting;
275
+ // an update's metadata is merged into what the object holds before the handler or the core serves it (mergeMetadata)
276
+ return derived(readOnly ? acting : await mergeMetadata(acting, (op) => !(op.id in handlerMap) && core.owns(op), scope));
71
277
  };
278
+ // A connected account's OAuth keys (screens/connect-oauth.tsx): the token endpoint's access_token is "Use the
279
+ // Stripe-Account header with your platform's secret key (that can make requests on behalf of this Stripe account)" and
280
+ // its stripe_publishable_key the same with the publishable key (docs.stripe.com/connect/oauth-reference): a request made
281
+ // with one acts as that account, as a request with the Stripe-Account header does. A key no live connection holds (its
282
+ // connection revoked, or replaced by a refresh: "Any existing access token with the same scope and mode ... is
283
+ // revoked") is Stripe's unknown key, 401 "Invalid API Key provided" (docs.stripe.com/api/authentication, docs.stripe.com
284
+ // /error-codes); one sent with a Stripe-Account header naming another account cannot act as it (account_invalid).
285
+ // Where the documentation stops and the twin decides: the messages' wording; a read_only key is not held to reads
286
+ // (manifest todo stripe.connect.oauth_scope_enforcement).
287
+ const actingAsOAuthKey = async (request: Request): Promise<Request | Response> => {
288
+ const key = requestKey(request);
289
+ if (!/^(sk|pk)_test_oauth_/.test(key)) return request;
290
+ const held = oauthKeyAccount(await semanticsContext(manifest, new Request(request.url), billingClock, scope), key);
291
+ if (!held) return vendorError(manifest, { status: 401, message: `Invalid API Key provided: ${redactKey(key)}` });
292
+ const named = request.headers.get('stripe-account');
293
+ if (named && named !== held.account) return vendorError(manifest, { status: 403, code: 'account_invalid', message: `The provided key '${redactKey(key)}' does not have access to account '${named}' (or that account does not exist). Application access may have been revoked.` });
294
+ const headers = new Headers(request.headers);
295
+ headers.set('stripe-account', held.account);
296
+ const bodied = request.method !== 'GET' && request.method !== 'HEAD';
297
+ return new Request(request.url, { method: request.method, headers, ...(bodied ? { body: await request.arrayBuffer() } : {}) });
298
+ };
299
+ // every answer in the shape of the API version the caller is served (stripe-version.ts)
300
+ const rendered = async (request: Request): Promise<Response> => {
301
+ const expand = expandOf(request.clone());
302
+ const creates = request.method === 'POST' && new URL(request.url).pathname.replace(/\/+$/, '') === '/v1/webhook_endpoints';
303
+ const res = await served(request);
304
+ const pinned = request.headers.get('stripe-version');
305
+ if (!(res.headers.get('content-type') ?? '').includes('json')) return res;
306
+ if (!servesCurrent(pinned) && creates) return res;
307
+ const body = await res.json();
308
+ // a webhook endpoint's `secret` is "Only returned at creation" (docs.stripe.com/api/webhook_endpoints/object)
309
+ const answered = creates ? body : withoutEndpointSecret(body);
310
+ return new Response(JSON.stringify(servesCurrent(pinned) ? render(answered, pinned, await expand) : answered), { status: res.status, statusText: res.statusText, headers: res.headers });
311
+ };
312
+ return Object.assign(rendered, { owners: derived.owners });
72
313
  }
73
314
 
74
- export function createStripeTwinServer(options: StripeTwinOptions): { port: number; stop: () => void } {
75
- const server = Bun.serve({
315
+ export async function createStripeTwinServer(options: StripeTwinOptions): Promise<{ port: number; stop: () => void }> {
316
+ const server = await serveHttp({
76
317
  port: options.port ?? 0,
77
318
  idleTimeout: 60,
78
319
  fetch: createStripeTwinFetch(options),
79
320
  });
80
321
  return { port: server.port ?? options.port ?? 0, stop: () => server.stop(true) };
81
322
  }
323
+
324
+ // the update operations, by their path as a pattern, for mergeMetadata
325
+ const UPDATES = (surface.operations as Array<DerivedCall['operation']>).filter((o) => o.class === 'update' && o.method.toUpperCase() === 'POST')
326
+ .map((op) => ({ op, re: new RegExp(`^${op.path.replace(/[.*+?^$()|[\]\\]/g, '\\$&').replace(/\\\{[^}]+\\\}|\{[^}]+\}/g, '([^/]+)')}/?$`) }));
327
+
328
+ /** An update's `metadata`, merged into what the object holds before anything serves the update. "This parameter uses a
329
+ * merge mechanism, which allows you to add new key-value pairs to an object in an update call without affecting any
330
+ * existing metadata"; "Pass in the key with an empty string as the value to remove the key from the metadata"; "Pass an
331
+ * empty string as the value for the metadata attribute to delete all of the keys simultaneously"
332
+ * (docs.stripe.com/metadata). The derived core already merges a nested hash where the manifest leaves `update` at
333
+ * `merge` (dropping keys set to ""), so only a clear-all is rewritten for it; where a handler or a `replace` update
334
+ * stores the request's metadata whole, the request is rewritten to carry the merged hash, so every door stores the same
335
+ * answer. The request is rewritten as JSON (readParams reads either). */
336
+ async function mergeMetadata(request: Request, coreMerges: (op: DerivedCall['operation']) => boolean, scope: { root?: string; clock?: () => string }): Promise<Request> {
337
+ if (request.method !== 'POST' || (request.headers.get('content-type') ?? '').includes('multipart')) return request;
338
+ const path = new URL(request.url).pathname;
339
+ let op: DerivedCall['operation'] | undefined;
340
+ let id = '';
341
+ for (const u of UPDATES) { const m = u.re.exec(path); if (m) { op = u.op; id = decodeURIComponent(m.at(-1) ?? ''); break; } }
342
+ if (!op?.resource) return request;
343
+ const params = await readParams(manifest, request.clone(), op);
344
+ if (!('metadata' in params)) return request;
345
+ const given = params.metadata;
346
+ // a plan is kept as the recurring price it is (semantics/plans.ts)
347
+ const resource = op.resource === 'plan' ? 'price' : op.resource;
348
+ const ctx = await semanticsContext(manifest, request.clone(), op, scope);
349
+ const held = ctx.get(resource, id)?.metadata;
350
+ const prior = held && typeof held === 'object' ? (held as Record<string, unknown>) : {};
351
+ const merges = coreMerges(op) && manifest.resources[resource]?.update !== 'replace';
352
+ let metadata: Record<string, unknown>;
353
+ if (given === '') metadata = merges ? Object.fromEntries(Object.keys(prior).map((k) => [k, ''])) : {};
354
+ else if (given && typeof given === 'object' && !Array.isArray(given)) {
355
+ if (merges) return request;
356
+ metadata = Object.fromEntries(Object.entries({ ...prior, ...(given as Record<string, unknown>) }).filter(([, v]) => v !== ''));
357
+ } else return request;
358
+ const headers = new Headers(request.headers);
359
+ headers.set('content-type', 'application/json');
360
+ return new Request(request.url, { method: request.method, headers, body: JSON.stringify({ ...params, metadata }) });
361
+ }