@volter/twin-stripe 3.0.0 → 3.0.2
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.
- package/README.md +75 -21
- package/dist/journeys/coverage.json +596 -0
- package/dist/journeys/customer-life.json +6108 -0
- package/dist/journeys/customer-life.outline.md +371 -0
- package/dist/journeys/decisions.json +677 -0
- package/dist/journeys/demand.json +706 -0
- package/dist/journeys/score.json +853 -0
- package/dist/journeys/unreachable.json +102 -0
- package/dist/journeys/vendor-examples.json +8010 -0
- package/dist/spec/SOURCE.md +5 -1
- package/dist/spec/doc-examples.json +445 -0
- package/dist/spec/sources.json +135 -207
- package/dist/src/cli.d.ts +0 -1
- package/dist/src/cli.js +0 -2
- package/dist/src/engine/after-payment.d.ts +0 -1
- package/dist/src/engine/after-payment.js +0 -1
- package/dist/src/engine/common.d.ts +5 -5
- package/dist/src/engine/common.js +13 -11
- package/dist/src/engine/connect.d.ts +0 -21
- package/dist/src/engine/connect.js +1 -82
- package/dist/src/engine/customers.d.ts +0 -8
- package/dist/src/engine/customers.js +0 -22
- package/dist/src/engine/display.d.ts +0 -3
- package/dist/src/engine/display.js +0 -3
- package/dist/src/engine/files.d.ts +0 -7
- package/dist/src/engine/files.js +0 -10
- package/dist/src/engine/invoices.d.ts +6 -9
- package/dist/src/engine/invoices.js +56 -29
- package/dist/src/engine/issuing.d.ts +6 -8
- package/dist/src/engine/issuing.js +19 -10
- package/dist/src/engine/ledger.d.ts +0 -1
- package/dist/src/engine/ledger.js +0 -1
- package/dist/src/engine/oauth.js +1 -2
- package/dist/src/engine/refunds.js +2 -27
- package/dist/src/engine/stripe.d.ts +2 -7
- package/dist/src/engine/stripe.js +34 -83
- package/dist/src/engine/subscriptions.d.ts +0 -1
- package/dist/src/engine/subscriptions.js +0 -1
- package/dist/src/engine/version.d.ts +0 -2
- package/dist/src/engine/version.js +17 -6
- package/dist/src/fetch.js +2 -2
- package/dist/src/generated/surface.gen.json +1 -1
- package/dist/src/generated/ui.gen.json +1 -1
- package/dist/src/index.js +5 -3
- package/dist/src/manifest.js +348 -220
- package/dist/src/screens/billing-portal.js +5 -5
- package/dist/src/screens/{connect-oauth.d.ts → checkout-js.d.ts} +0 -1
- package/dist/src/screens/checkout-js.js +84 -0
- package/dist/src/screens/connect-onboarding.js +3 -3
- package/dist/src/screens/dashboard.d.ts +1 -1
- package/dist/src/screens/dashboard.js +56 -53
- package/dist/src/screens/stripe-js.js +53 -93
- package/dist/src/semantics/account.d.ts +2 -0
- package/dist/src/semantics/account.js +8 -0
- package/dist/src/semantics/accounts.js +3 -1
- package/dist/src/semantics/around.js +3 -6
- package/dist/src/semantics/billing_portal.d.ts +0 -1
- package/dist/src/semantics/billing_portal.js +1 -7
- package/dist/src/semantics/checkout.d.ts +1 -1
- package/dist/src/semantics/checkout.js +18 -15
- package/dist/src/semantics/clock.js +1 -7
- package/dist/src/semantics/customers.d.ts +1 -2
- package/dist/src/semantics/customers.js +32 -38
- package/dist/src/semantics/entitlements.d.ts +0 -2
- package/dist/src/semantics/entitlements.js +4 -50
- package/dist/src/semantics/events.d.ts +2 -3
- package/dist/src/semantics/events.js +6 -11
- package/dist/src/semantics/index.js +16 -38
- package/dist/src/semantics/invoices.d.ts +3 -8
- package/dist/src/semantics/invoices.js +134 -127
- package/dist/src/semantics/issuing.d.ts +6 -0
- package/dist/src/semantics/issuing.js +77 -0
- package/dist/src/semantics/payment_intents.d.ts +0 -1
- package/dist/src/semantics/payment_intents.js +5 -13
- package/dist/src/semantics/payment_methods.d.ts +0 -2
- package/dist/src/semantics/payment_methods.js +2 -26
- package/dist/src/semantics/payouts.d.ts +1 -0
- package/dist/src/semantics/payouts.js +8 -1
- package/dist/src/semantics/products.d.ts +1 -3
- package/dist/src/semantics/products.js +3 -14
- package/dist/src/semantics/refunds.d.ts +1 -2
- package/dist/src/semantics/refunds.js +1 -5
- package/dist/src/semantics/shared.d.ts +64 -336
- package/dist/src/semantics/shared.js +326 -1336
- package/dist/src/semantics/states.d.ts +20 -89
- package/dist/src/semantics/states.js +116 -334
- package/dist/src/semantics/subscriptions.d.ts +1 -2
- package/dist/src/semantics/subscriptions.js +23 -145
- package/dist/src/semantics/test_helpers.d.ts +2 -5
- package/dist/src/semantics/test_helpers.js +121 -43
- package/dist/src/semantics/webhook_endpoints.d.ts +2 -0
- package/dist/src/semantics/webhook_endpoints.js +26 -0
- package/generated/pack-facts.json +3 -3
- package/journeys/coverage.json +596 -0
- package/journeys/customer-life.json +6108 -0
- package/journeys/customer-life.outline.md +371 -0
- package/journeys/decisions.json +677 -0
- package/journeys/demand.json +706 -0
- package/journeys/score.json +853 -0
- package/journeys/unreachable.json +102 -0
- package/journeys/vendor-examples.json +8010 -0
- package/package.json +11 -10
- package/spec/SOURCE.md +5 -1
- package/spec/doc-examples.json +445 -0
- package/spec/sources.json +135 -207
- package/src/cli.ts +0 -3
- package/src/engine/after-payment.ts +0 -2
- package/src/engine/balance.ts +0 -1
- package/src/engine/checkout.ts +0 -1
- package/src/engine/common.ts +19 -17
- package/src/engine/connect.ts +1 -79
- package/src/engine/customers.ts +0 -25
- package/src/engine/display.ts +2 -3
- package/src/engine/files.ts +0 -13
- package/src/engine/invoices.ts +64 -33
- package/src/engine/issuing.ts +16 -11
- package/src/engine/ledger.ts +0 -2
- package/src/engine/oauth.ts +1 -2
- package/src/engine/onboarding.ts +0 -1
- package/src/engine/params.ts +0 -1
- package/src/engine/payment-intents.ts +0 -1
- package/src/engine/payment-methods.ts +0 -1
- package/src/engine/refunds.ts +2 -28
- package/src/engine/renewals.ts +0 -1
- package/src/engine/stripe.ts +35 -83
- package/src/engine/subscriptions.ts +0 -3
- package/src/engine/transfers.ts +0 -1
- package/src/engine/version.ts +15 -7
- package/src/engine/webhooks.ts +0 -2
- package/src/fetch.ts +2 -2
- package/src/generated/surface.gen.json +1 -1
- package/src/generated/ui.gen.json +1 -1
- package/src/index.ts +6 -4
- package/src/manifest.ts +348 -220
- package/src/screens/billing-portal.tsx +5 -7
- package/src/screens/checkout-js.ts +80 -0
- package/src/screens/checkout.tsx +0 -2
- package/src/screens/connect-onboarding.tsx +3 -5
- package/src/screens/dashboard.tsx +55 -73
- package/src/screens/stripe-js.ts +57 -125
- package/src/semantics/account.ts +10 -0
- package/src/semantics/account_links.ts +0 -1
- package/src/semantics/accounts.ts +8 -7
- package/src/semantics/apps.ts +1 -2
- package/src/semantics/around.ts +3 -6
- package/src/semantics/balance.ts +0 -1
- package/src/semantics/balance_transactions.ts +1 -3
- package/src/semantics/billing_portal.ts +1 -7
- package/src/semantics/charges.ts +1 -6
- package/src/semantics/checkout.ts +16 -12
- package/src/semantics/clock.ts +1 -8
- package/src/semantics/coupons.ts +0 -1
- package/src/semantics/customers.ts +32 -35
- package/src/semantics/doors.ts +2 -3
- package/src/semantics/entitlements.ts +1 -45
- package/src/semantics/events.ts +7 -14
- package/src/semantics/index.ts +16 -38
- package/src/semantics/invoice_payments.ts +1 -3
- package/src/semantics/invoices.ts +124 -119
- package/src/semantics/issuing.ts +74 -0
- package/src/semantics/payment_intents.ts +10 -17
- package/src/semantics/payment_methods.ts +2 -25
- package/src/semantics/payouts.ts +9 -3
- package/src/semantics/prices.ts +0 -1
- package/src/semantics/products.ts +4 -14
- package/src/semantics/promotion_codes.ts +0 -1
- package/src/semantics/radar.ts +1 -3
- package/src/semantics/refunds.ts +2 -11
- package/src/semantics/shared.ts +350 -1382
- package/src/semantics/states.ts +109 -330
- package/src/semantics/subscriptions.ts +25 -145
- package/src/semantics/test_helpers.ts +109 -43
- package/src/semantics/transfers.ts +1 -3
- package/src/semantics/webhook_endpoints.ts +27 -0
- package/src/server.ts +0 -1
- package/dist/generated/pack-facts.json +0 -94
- package/dist/src/engine/billing.d.ts +0 -5
- package/dist/src/engine/billing.js +0 -6
- package/dist/src/engine/charges.d.ts +0 -6
- package/dist/src/engine/charges.js +0 -13
- package/dist/src/engine/connect-settings.d.ts +0 -16
- package/dist/src/engine/connect-settings.js +0 -26
- package/dist/src/engine/coupons.d.ts +0 -0
- package/dist/src/engine/coupons.js +0 -5
- package/dist/src/engine/credit-notes.d.ts +0 -1
- package/dist/src/engine/credit-notes.js +0 -5
- package/dist/src/engine/disputes.d.ts +0 -0
- package/dist/src/engine/disputes.js +0 -9
- package/dist/src/engine/entitlements.d.ts +0 -1
- package/dist/src/engine/entitlements.js +0 -4
- package/dist/src/engine/ephemeral-keys.d.ts +0 -0
- package/dist/src/engine/ephemeral-keys.js +0 -4
- package/dist/src/engine/front.d.ts +0 -5
- package/dist/src/engine/front.js +0 -25
- package/dist/src/engine/payment-links.d.ts +0 -1
- package/dist/src/engine/payment-links.js +0 -5
- package/dist/src/engine/plans.d.ts +0 -6
- package/dist/src/engine/plans.js +0 -26
- package/dist/src/engine/platform.d.ts +0 -39
- package/dist/src/engine/platform.js +0 -34
- package/dist/src/engine/products.d.ts +0 -0
- package/dist/src/engine/products.js +0 -4
- package/dist/src/engine/setup-intents.d.ts +0 -1
- package/dist/src/engine/setup-intents.js +0 -4
- package/dist/src/engine/subscription-schedules.d.ts +0 -3
- package/dist/src/engine/subscription-schedules.js +0 -1
- package/dist/src/engine/tax.d.ts +0 -7
- package/dist/src/engine/tax.js +0 -28
- package/dist/src/engine/terminal.d.ts +0 -4
- package/dist/src/engine/terminal.js +0 -20
- package/dist/src/engine/test-clocks.d.ts +0 -5
- package/dist/src/engine/test-clocks.js +0 -9
- package/dist/src/engine/tokens.d.ts +0 -7
- package/dist/src/engine/tokens.js +0 -20
- package/dist/src/engine/treasury.d.ts +0 -23
- package/dist/src/engine/treasury.js +0 -45
- package/dist/src/screens/connect-oauth.js +0 -333
- package/dist/src/semantics/disputes.d.ts +0 -2
- package/dist/src/semantics/disputes.js +0 -5
- package/dist/src/semantics/invoiceitems.d.ts +0 -3
- package/dist/src/semantics/invoiceitems.js +0 -59
- package/dist/src/semantics/setup_intents.d.ts +0 -3
- package/dist/src/semantics/setup_intents.js +0 -41
- package/dist/src/semantics/subscription_items.d.ts +0 -5
- package/dist/src/semantics/subscription_items.js +0 -55
- package/dist/src/semantics/subscription_schedules.d.ts +0 -4
- package/dist/src/semantics/subscription_schedules.js +0 -60
- package/src/engine/billing.ts +0 -16
- package/src/engine/charges.ts +0 -19
- package/src/engine/connect-settings.ts +0 -23
- package/src/engine/coupons.ts +0 -5
- package/src/engine/credit-notes.ts +0 -6
- package/src/engine/disputes.ts +0 -9
- package/src/engine/entitlements.ts +0 -5
- package/src/engine/ephemeral-keys.ts +0 -3
- package/src/engine/front.ts +0 -31
- package/src/engine/payment-links.ts +0 -6
- package/src/engine/plans.ts +0 -42
- package/src/engine/platform.ts +0 -47
- package/src/engine/products.ts +0 -3
- package/src/engine/setup-intents.ts +0 -5
- package/src/engine/subscription-schedules.ts +0 -10
- package/src/engine/tax.ts +0 -39
- package/src/engine/terminal.ts +0 -23
- package/src/engine/test-clocks.ts +0 -11
- package/src/engine/tokens.ts +0 -22
- package/src/engine/treasury.ts +0 -47
- package/src/screens/connect-oauth.tsx +0 -376
- package/src/semantics/disputes.ts +0 -12
- package/src/semantics/invoiceitems.ts +0 -59
- package/src/semantics/setup_intents.ts +0 -45
- package/src/semantics/subscription_items.ts +0 -54
- package/src/semantics/subscription_schedules.ts +0 -66
|
@@ -1,376 +0,0 @@
|
|
|
1
|
-
// STRIPE CONNECT OAUTH (Standard accounts) — a hosted flow (docs/contributing/architecture.md, "Screens") and the two
|
|
2
|
-
// connect.stripe.com endpoints behind it, as docs.stripe.com/connect/oauth-reference and
|
|
3
|
-
// docs.stripe.com/connect/oauth-standard-accounts describe them. A platform sends a person to
|
|
4
|
-
// GET connect.stripe.com/oauth/authorize with its client_id; the person connects (in test mode Stripe lets them "Force-skip
|
|
5
|
-
// the account form", docs.stripe.com/connect/testing#using-oauth) or denies; Stripe sends them back to the redirect_uri
|
|
6
|
-
// with a `code`, the `scope` granted and the `state` (or `error=access_denied`); the platform's server turns the code into
|
|
7
|
-
// the connection with POST connect.stripe.com/oauth/token, authenticated by its secret key, and learns the account id
|
|
8
|
-
// (`stripe_user_id`) it then acts as with the Stripe-Account header. POST connect.stripe.com/oauth/deauthorize revokes the
|
|
9
|
-
// connection. The page is @volter/world-ui's consent piece under Stripe's skin; nothing of Stripe's page is copied.
|
|
10
|
-
//
|
|
11
|
-
// What the documentation says and the twin keeps:
|
|
12
|
-
// - authorize: `client_id` is the platform's (its Connect OAuth settings, ./dashboard.tsx, where OAuth is enabled
|
|
13
|
-
// and the redirect URIs are registered); `response_type` "The only option at the moment is code"; `redirect_uri`, "If
|
|
14
|
-
// provided, this must exactly match one of the ... redirect_uri values in your application settings" and "Defaults to
|
|
15
|
-
// the redirect_uri in your application settings" ("the first URI configured"); `scope` read_write or read_only,
|
|
16
|
-
// "Defaults to read_only"; `state` passed back. `stripe_user[...]` prefills the new account, and "Any parameters with
|
|
17
|
-
// invalid values are silently ignored". Errors: "the user's browser won't be redirected except in the case of
|
|
18
|
-
// access_denied. Instead, errors will be returned in a JSON dictionary" of error, error_description and state, with
|
|
19
|
-
// the codes invalid_scope, invalid_redirect_uri, invalid_request (Missing response_type) and unsupported_response_type.
|
|
20
|
-
// Denied: `error=access_denied&error_description=The%20user%20denied%20your%20request`. Success: code, scope, state.
|
|
21
|
-
// - token: the code "can only be used once and expires in 5 minutes"; "Consuming an authorization code more than once
|
|
22
|
-
// revokes the account connection"; grant_type authorization_code or refresh_token; a refresh `scope` of "equal or lesser
|
|
23
|
-
// scope" and "Any existing access token with the same scope and mode ... is revoked"; the response's scope,
|
|
24
|
-
// stripe_user_id, livemode, token_type "bearer", access_token, stripe_publishable_key and refresh_token; errors
|
|
25
|
-
// invalid_request, invalid_grant ("Authorization code does not exist: {AUTHORIZATION_CODE}", verbatim from the guide),
|
|
26
|
-
// unsupported_grant_type and invalid_scope as `{ error, error_description }`.
|
|
27
|
-
// - deauthorize: client_id and stripe_user_id, answered `{ stripe_user_id }`; errors invalid_request and invalid_client
|
|
28
|
-
// ("stripe_user_id doesn't exist or isn't connected to your application"); afterwards "the account can't be accessed by
|
|
29
|
-
// your platform ... through the API" (../engine/front.ts refuses the Stripe-Account header for it, account_invalid).
|
|
30
|
-
// - events: account.application.authorized when the person connects and account.application.deauthorized when the
|
|
31
|
-
// connection is revoked, each the connected account's (top-level `account`, Connect endpoints), carrying the
|
|
32
|
-
// `application` object ({ id: the client_id, object: 'application', name }).
|
|
33
|
-
//
|
|
34
|
-
// Where the documentation stops and the twin decides:
|
|
35
|
-
// - the twin is a test-mode Stripe: its client_id is a test one (./dashboard.tsx PLATFORM_CLIENT_ID), redirect
|
|
36
|
-
// URIs may be http and localhost ("Your test client_id allows you to ... Set your redirect_uri to a non-HTTPS URL /
|
|
37
|
-
// to localhost"), a code, token and connection are livemode false, and a live secret key (sk_live_) is refused as the
|
|
38
|
-
// documented mode mismatch (invalid_grant at token, invalid_client at deauthorize).
|
|
39
|
-
// - the only way through the page is the test-mode skip: it creates a NEW Standard account from the prefill and connects
|
|
40
|
-
// it; logging in to connect an existing Stripe account is not modelled. A skipped test account can take payments at
|
|
41
|
-
// once (charges and payouts enabled, card_payments and transfers active, nothing due), and controls itself (controller
|
|
42
|
-
// type `account`), since the platform did not create it.
|
|
43
|
-
// - an unknown client_id answers invalid_client "No application matches the supplied client identifier", and a
|
|
44
|
-
// platform that has not enabled OAuth invalid_client naming its settings page; a missing client_id is invalid_request.
|
|
45
|
-
// The JSON errors are HTTP 400; the order of the checks is client_id, OAuth enabled, redirect_uri, response_type,
|
|
46
|
-
// scope. With no redirect URI registered and none given, invalid_redirect_uri. read_only is accepted from any platform
|
|
47
|
-
// (the docs limit it to extensions; the twin does not tell a platform from an extension).
|
|
48
|
-
// - the secret key may come as Bearer, as Basic's user, or as the `client_secret` parameter (the reference's curl uses
|
|
49
|
-
// `-u`, stripe-node a Bearer header); without one the answer is 401 invalid_request, and a key that is not a secret
|
|
50
|
-
// key (sk_…/rk_…) 401 invalid_request too. The token and deauthorize wording other than the one quoted above is the
|
|
51
|
-
// twin's. An expired code is invalid_grant "Authorization code expired: {code}"; a reused one invalid_grant "This
|
|
52
|
-
// authorization code has already been used. All tokens issued with this code have been revoked." and revokes.
|
|
53
|
-
// - tokens are drawn from secrets the World holds (ctx.secret), so none is computable from the account's id:
|
|
54
|
-
// access_token `sk_test_oauth_{account}_{secret of its generation}`, refresh_token `rt_{secret of the code}`,
|
|
55
|
-
// stripe_publishable_key `pk_test_oauth_{account}` (publishable, so public); a refresh answers the same refresh_token. The access_token and publishable key are deprecated by Stripe (use the
|
|
56
|
-
// Stripe-Account header) and act as the account (../engine/front.ts actingAsOAuthKey); a read_only one is not held to
|
|
57
|
-
// reads (manifest todo `stripe.connect.oauth_scope_enforcement`).
|
|
58
|
-
// - concurrency: a code's number is taken with its write in one move; a code redeemed twice at once lets one exchange
|
|
59
|
-
// win, and whichever of the two finishes last revokes the connection, so a double exchange always ends revoked.
|
|
60
|
-
import type { HandlerContext } from '@volter/world-core';
|
|
61
|
-
import { Consent, CONSENT_CSS, flowPage } from '@volter/world-ui';
|
|
62
|
-
import type { Row } from '../engine/common.ts';
|
|
63
|
-
import { PLATFORM_CLIENT_ID, SETTINGS_URL } from '../engine/connect-settings.ts';
|
|
64
|
-
import { OAUTH_CONNECTIONS, publicBusinessName } from '../engine/display.ts';
|
|
65
|
-
import { redactKey } from '../engine/oauth.ts';
|
|
66
|
-
import { accountSettings, nowUnix, PLATFORM_ACCOUNT_ID } from '../engine/stripe.ts';
|
|
67
|
-
import { formOf, notFound, seeOther, STRIPE_CONSENT_SKIN } from './shared.tsx';
|
|
68
|
-
import { connectOAuthSettings, created, decide } from '../semantics/shared.ts';
|
|
69
|
-
|
|
70
|
-
/** A code "expires in 5 minutes". */
|
|
71
|
-
const CODE_TTL_SECONDS = 300;
|
|
72
|
-
const CODES = '_oauth_code';
|
|
73
|
-
/** One connection per connected account (the twin's one platform): its scope, tokens, and whether it was revoked. */
|
|
74
|
-
const CONNECTIONS = OAUTH_CONNECTIONS;
|
|
75
|
-
const SCOPES = ['read_write', 'read_only'] as const;
|
|
76
|
-
type Scope = (typeof SCOPES)[number];
|
|
77
|
-
|
|
78
|
-
const json = (body: Row, status = 200): Response => Response.json(body, { status, headers: { 'request-id': 'req_twin', 'cache-control': 'no-store' } });
|
|
79
|
-
const oauthError = (error: string, description: string, status = 400, extra: Row = {}): Response => json({ error, error_description: description, ...extra }, status);
|
|
80
|
-
|
|
81
|
-
// ── authorize ──
|
|
82
|
-
|
|
83
|
-
/** A query parameter, or undefined when absent (an empty value is absent too, as a browser form sends one). */
|
|
84
|
-
const param = (q: URLSearchParams, k: string): string | undefined => { const v = q.get(k); return v === null || v === '' ? undefined : v; };
|
|
85
|
-
|
|
86
|
-
type Authorize = { redirect: string; scope: Scope; state: string | undefined };
|
|
87
|
-
|
|
88
|
-
/** The authorize request checked as Stripe checks it, or the JSON error it answers. */
|
|
89
|
-
function checked(ctx: HandlerContext, q: URLSearchParams): Authorize | Response {
|
|
90
|
-
const state = param(q, 'state');
|
|
91
|
-
const fail = (error: string, description: string) => oauthError(error, description, 400, state !== undefined ? { state } : {});
|
|
92
|
-
const client = param(q, 'client_id');
|
|
93
|
-
if (!client) return fail('invalid_request', 'No client_id provided.');
|
|
94
|
-
if (client !== PLATFORM_CLIENT_ID) return fail('invalid_client', 'No application matches the supplied client identifier');
|
|
95
|
-
const settings = connectOAuthSettings(ctx);
|
|
96
|
-
if (!settings.oauth_enabled) return fail('invalid_client', `OAuth is not enabled for this application. Enable it in your Connect OAuth settings (${SETTINGS_URL}).`);
|
|
97
|
-
const given = q.get('redirect_uri');
|
|
98
|
-
let redirect: string | undefined;
|
|
99
|
-
if (given !== null) {
|
|
100
|
-
if (!settings.redirect_uris.includes(given)) return fail('invalid_redirect_uri', `Invalid redirect URI '${given}'. Ensure this uri exactly matches one of the uris specified in your application settings`);
|
|
101
|
-
redirect = given;
|
|
102
|
-
} else {
|
|
103
|
-
redirect = settings.redirect_uris[0];
|
|
104
|
-
if (!redirect) return fail('invalid_redirect_uri', 'No redirect URI is configured in your application settings');
|
|
105
|
-
}
|
|
106
|
-
const type = q.get('response_type');
|
|
107
|
-
if (type === null || type === '') return fail('invalid_request', 'Missing response_type parameter.');
|
|
108
|
-
if (type !== 'code') return fail('unsupported_response_type', `Unsupported response_type parameter: ${type}. Currently the only supported response_type is code.`);
|
|
109
|
-
const scope = param(q, 'scope') ?? 'read_only';
|
|
110
|
-
if (!(SCOPES as readonly string[]).includes(scope)) return fail('invalid_scope', `Invalid scope parameter provided: '${scope}'. Accepted scopes are 'read_write' or 'read_only'.`);
|
|
111
|
-
return { redirect, scope: scope as Scope, state };
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/** The redirect_uri with these parameters added, each percent-encoded (a space as %20, as Stripe's examples show). */
|
|
115
|
-
function withParams(uri: string, params: Array<[string, string | undefined]>): string {
|
|
116
|
-
const [base, fragment] = uri.split('#', 2) as [string, string | undefined];
|
|
117
|
-
const added = params.filter((p): p is [string, string] => p[1] !== undefined).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');
|
|
118
|
-
return `${base}${base.includes('?') ? (base.endsWith('?') || base.endsWith('&') ? '' : '&') : '?'}${added}${fragment !== undefined ? `#${fragment}` : ''}`;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
/** The prefill the request carries, invalid values silently dropped (docs.stripe.com/connect/oauth-reference). Only
|
|
122
|
-
* what the new account's object shows the platform, or the page shows the person, is read: the person's birth date and
|
|
123
|
-
* the business address are the account application's, which the twin does not model (the test-mode skip). */
|
|
124
|
-
function prefill(q: URLSearchParams): Record<string, string> {
|
|
125
|
-
const v = (k: string) => param(q, `stripe_user[${k}]`)?.trim() || undefined;
|
|
126
|
-
const out: Record<string, string> = {};
|
|
127
|
-
const keep = (k: string, ok: (s: string) => boolean = () => true) => { const s = v(k); if (s !== undefined && ok(s)) out[k] = s; };
|
|
128
|
-
keep('email', (s) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s));
|
|
129
|
-
keep('url', (s) => /^https?:\/\/\S+$/i.test(s));
|
|
130
|
-
keep('country', (s) => /^[A-Z]{2}$/.test(s));
|
|
131
|
-
keep('phone_number', (s) => /^\d{10}$/.test(s) && out.country !== undefined);
|
|
132
|
-
keep('business_name');
|
|
133
|
-
keep('business_type', (s) => ['sole_prop', 'corporation', 'non_profit', 'partnership', 'llc'].includes(s));
|
|
134
|
-
keep('first_name');
|
|
135
|
-
keep('last_name');
|
|
136
|
-
keep('product_description');
|
|
137
|
-
keep('currency', (s) => /^[a-z]{3}$/.test(s) && out.country !== undefined);
|
|
138
|
-
return out;
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
// the default currency of an account in a country, where the prefill names none (docs.stripe.com/connect/currencies:
|
|
142
|
-
// the account's default is its country's currency); a country outside this list is given usd
|
|
143
|
-
const COUNTRY_CURRENCY: Record<string, string> = { US: 'usd', CA: 'cad', GB: 'gbp', AU: 'aud', NZ: 'nzd', JP: 'jpy', SG: 'sgd', HK: 'hkd', CH: 'chf', SE: 'sek', NO: 'nok', DK: 'dkk', PL: 'pln', MX: 'mxn', BR: 'brl', IN: 'inr', DE: 'eur', FR: 'eur', ES: 'eur', IT: 'eur', NL: 'eur', IE: 'eur', BE: 'eur', AT: 'eur', PT: 'eur', FI: 'eur' };
|
|
144
|
-
const BUSINESS_TYPE: Record<string, string> = { sole_prop: 'individual', corporation: 'company', llc: 'company', partnership: 'company', non_profit: 'non_profit' };
|
|
145
|
-
|
|
146
|
-
/** The Standard account the skipped form creates, from the prefill. */
|
|
147
|
-
async function createAccount(ctx: HandlerContext, p: Record<string, string>): Promise<string> {
|
|
148
|
-
const country = p.country ?? 'US';
|
|
149
|
-
const id = ctx.mint('account');
|
|
150
|
-
const none = { alternatives: [], current_deadline: null, currently_due: [], disabled_reason: null, errors: [], eventually_due: [], past_due: [], pending_verification: [] };
|
|
151
|
-
await created(ctx, 'account', { id }, {
|
|
152
|
-
type: 'standard', country, default_currency: p.currency ?? COUNTRY_CURRENCY[country] ?? 'usd', email: p.email ?? null,
|
|
153
|
-
business_type: p.business_type ? BUSINESS_TYPE[p.business_type] ?? null : null,
|
|
154
|
-
business_profile: { name: p.business_name ?? null, url: p.url ?? null, product_description: p.product_description ?? null, support_phone: p.phone_number ?? null, mcc: null },
|
|
155
|
-
charges_enabled: true, payouts_enabled: true, details_submitted: true,
|
|
156
|
-
capabilities: { card_payments: 'active', transfers: 'active' },
|
|
157
|
-
controller: { type: 'account' },
|
|
158
|
-
requirements: none, future_requirements: none,
|
|
159
|
-
settings: accountSettings(undefined, p.business_name ? { dashboard: { display_name: p.business_name, timezone: 'Etc/UTC' } } : undefined),
|
|
160
|
-
external_accounts: { object: 'list', data: [], has_more: false, total_count: 0, url: `/v1/accounts/${id}/external_accounts` },
|
|
161
|
-
tos_acceptance: { date: null, ip: null, user_agent: null }, metadata: {}, livemode: false,
|
|
162
|
-
}, { operation: 'account.oauth_connect' });
|
|
163
|
-
return id;
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
/** The platform's application as the account.application.* events carry it. */
|
|
167
|
-
function application(ctx: HandlerContext): Row {
|
|
168
|
-
return { id: PLATFORM_CLIENT_ID, object: 'application', name: publicBusinessName(ctx.get('account', PLATFORM_ACCOUNT_ID)) };
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
/** Send one of the account.application.* events as the connected account's: the notice it is sent for (the kernel
|
|
172
|
-
* sends it, ../semantics/events.ts renders it). */
|
|
173
|
-
async function applicationEvent(ctx: HandlerContext, type: 'account.application.authorized' | 'account.application.deauthorized', account: string): Promise<void> {
|
|
174
|
-
await ctx.write('_application_notice', `${account}:${type}:${ctx.occurredAt}`, { account, application: application(ctx) }, type);
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
function page(ctx: HandlerContext, action: string, a: Authorize, p: Record<string, string>): Response {
|
|
178
|
-
const name = publicBusinessName(ctx.get('account', PLATFORM_ACCOUNT_ID));
|
|
179
|
-
const who = [p.email, [p.first_name, p.last_name].filter(Boolean).join(' '), p.business_name].filter((s) => s).join(' · ');
|
|
180
|
-
return flowPage({
|
|
181
|
-
title: `Connect to ${name} – Stripe`,
|
|
182
|
-
css: [CONSENT_CSS, STRIPE_CONSENT_SKIN],
|
|
183
|
-
body: (
|
|
184
|
-
<Consent
|
|
185
|
-
heading={`Connect your Stripe account to ${name}`}
|
|
186
|
-
app={{ name }}
|
|
187
|
-
request="wants to connect to your Stripe account · test mode"
|
|
188
|
-
permissions={[
|
|
189
|
-
a.scope === 'read_write'
|
|
190
|
-
? { title: 'Read and write access', detail: 'Create payments, customers and other data on your account, and read its data' }
|
|
191
|
-
: { title: 'Read-only access', detail: 'Read your account’s data' },
|
|
192
|
-
{ title: 'A new test account', detail: who || 'No details prefilled' },
|
|
193
|
-
]}
|
|
194
|
-
action={action}
|
|
195
|
-
fields={{}}
|
|
196
|
-
deny={{ name: 'decision', value: 'deny', label: 'Deny access' }}
|
|
197
|
-
allow={{ name: 'decision', value: 'skip', label: 'Skip this form' }}
|
|
198
|
-
note={`Test mode: skipping the form creates a new test account and connects it. You will be returned to ${new URL(a.redirect).host}.`}
|
|
199
|
-
/>
|
|
200
|
-
),
|
|
201
|
-
});
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
/** The person connects: a new Standard account, its connection's code, the authorized event, and the redirect. */
|
|
205
|
-
async function connect(ctx: HandlerContext, a: Authorize, p: Record<string, string>): Promise<Response> {
|
|
206
|
-
const account = await createAccount(ctx, p);
|
|
207
|
-
// the code's row id is minted and its value drawn from the World's secret; the row keeps the value's SHA-256 alone
|
|
208
|
-
const id = ctx.mint(CODES);
|
|
209
|
-
const code = `ac_${(await ctx.secret(`stripe-oauth-code:${id}`)).replace(/[^A-Za-z0-9]/g, '').slice(0, 24)}`;
|
|
210
|
-
await ctx.record(CODES, { client_id: PLATFORM_CLIENT_ID, account, scope: a.scope, redirect_uri: a.redirect, expires_at: nowUnix(ctx.occurredAt) + CODE_TTL_SECONDS, used: false, livemode: false, sha256: ctx.crypto.sha256(code) }, id);
|
|
211
|
-
await applicationEvent(ctx, 'account.application.authorized', account);
|
|
212
|
-
return seeOther(withParams(a.redirect, [['scope', a.scope], ['code', code], ['state', a.state]]));
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
async function authorize(ctx: HandlerContext): Promise<Response> {
|
|
216
|
-
const request = ctx.call.request;
|
|
217
|
-
const url = new URL(request.url);
|
|
218
|
-
const form = request.method === 'POST' ? await formOf(request.clone()) : {};
|
|
219
|
-
const a = checked(ctx, url.searchParams);
|
|
220
|
-
if (a instanceof Response) return a;
|
|
221
|
-
const p = prefill(url.searchParams);
|
|
222
|
-
if (request.method === 'GET') return page(ctx, `${url.pathname}${url.search}`, a, p);
|
|
223
|
-
if (form.decision === 'deny') return seeOther(withParams(a.redirect, [['error', 'access_denied'], ['error_description', 'The user denied your request'], ['state', a.state]]));
|
|
224
|
-
if (form.decision === 'skip') return connect(ctx, a, p);
|
|
225
|
-
return page(ctx, `${url.pathname}${url.search}`, a, p);
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
// ── token and deauthorize ──
|
|
229
|
-
|
|
230
|
-
/** The request's parameters: a form, as stripe-node and curl send them, or JSON. */
|
|
231
|
-
async function bodyOf(request: Request): Promise<Record<string, string>> {
|
|
232
|
-
const text = await request.clone().text();
|
|
233
|
-
if ((request.headers.get('content-type') ?? '').includes('json') || text.trim().startsWith('{')) {
|
|
234
|
-
try { return Object.fromEntries(Object.entries(JSON.parse(text) as Row).map(([k, v]) => [k, String(v)])); } catch { return {}; }
|
|
235
|
-
}
|
|
236
|
-
return Object.fromEntries(new URLSearchParams(text));
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
/** The secret key a request carries: Bearer, Basic's user, or the client_secret parameter. */
|
|
240
|
-
function secretKey(request: Request, params: Record<string, string>): string | undefined {
|
|
241
|
-
const header = request.headers.get('authorization') ?? '';
|
|
242
|
-
const bearer = /^bearer\s+(\S+)/i.exec(header)?.[1];
|
|
243
|
-
if (bearer) return bearer;
|
|
244
|
-
const basic = /^basic\s+(\S+)/i.exec(header)?.[1];
|
|
245
|
-
if (basic) { try { const user = atob(basic).split(':')[0]; if (user) return user; } catch { /* not base64 */ } }
|
|
246
|
-
return params.client_secret || undefined;
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
/** The refusal of a request without a usable secret key, or undefined when it has one (answered with whether it is live). */
|
|
250
|
-
function keyRefused(key: string | undefined): Response | undefined {
|
|
251
|
-
if (!key) return oauthError('invalid_request', 'No API key provided. Provide your secret key in the Authorization header, using Bearer auth (e.g. \'Authorization: Bearer YOUR_SECRET_KEY\').', 401);
|
|
252
|
-
if (!/^(sk|rk)_(test|live)_/.test(key)) return oauthError('invalid_request', `Invalid API Key provided: ${redactKey(key)}. This endpoint requires a secret key.`, 401);
|
|
253
|
-
// a connected account's access_token is that account's key, never the platform's ("Make this call using your secret API
|
|
254
|
-
// key", the reference): it neither exchanges codes nor refreshes nor deauthorizes
|
|
255
|
-
if (/^sk_test_oauth_/.test(key)) return oauthError('invalid_request', `Invalid API Key provided: ${redactKey(key)}. This endpoint requires your platform's secret key.`, 401);
|
|
256
|
-
return undefined;
|
|
257
|
-
}
|
|
258
|
-
const live = (key: string): boolean => /^(sk|rk)_live_/.test(key);
|
|
259
|
-
|
|
260
|
-
/** A new access token for a connection: its generation counted from the ones it had. */
|
|
261
|
-
/** A connection's access token of one generation: its account, then a digest of the connection's secret and the
|
|
262
|
-
* generation (the secret read before the atomic move that numbers the generation). */
|
|
263
|
-
// p3: keyed by the connection's secret, drawn from ctx.secret
|
|
264
|
-
const accessToken = (ctx: Pick<HandlerContext, 'crypto'>, secret: string, account: string, n: number): string => `sk_test_oauth_${account}_${ctx.crypto.digest('sha256', `${secret}:${n}`, 'base64url').replace(/[-_]/g, '').slice(0, 24)}`;
|
|
265
|
-
|
|
266
|
-
/** Revoke an account's connection, once: the check and the write are one move, and only the move that revoked it sends
|
|
267
|
-
* account.application.deauthorized. Answers whether this call revoked it. */
|
|
268
|
-
async function revoke(ctx: HandlerContext, account: string): Promise<boolean> {
|
|
269
|
-
const revoked = await decide(ctx, (rows) => {
|
|
270
|
-
const held = rows(CONNECTIONS).find((c) => c.id === account);
|
|
271
|
-
if (!held || held.revoked === true) return { value: false };
|
|
272
|
-
return { value: true, write: { resource: CONNECTIONS, id: account, fields: { revoked: true, access_token: null, revoked_at: nowUnix(ctx.occurredAt) }, operation: 'oauth_connection.revoke' } };
|
|
273
|
-
});
|
|
274
|
-
if (revoked) await applicationEvent(ctx, 'account.application.deauthorized', account);
|
|
275
|
-
return revoked;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
async function token(ctx: HandlerContext): Promise<Response> {
|
|
279
|
-
const request = ctx.call.request;
|
|
280
|
-
const params = await bodyOf(request);
|
|
281
|
-
const key = secretKey(request, params);
|
|
282
|
-
const refused = keyRefused(key);
|
|
283
|
-
if (refused) return refused;
|
|
284
|
-
const grant = params.grant_type;
|
|
285
|
-
if (!grant) return oauthError('invalid_request', 'No grant type specified');
|
|
286
|
-
if (grant !== 'authorization_code' && grant !== 'refresh_token') return oauthError('unsupported_grant_type', `Unsupported grant type: ${grant}. The only currently supported types are authorization_code and refresh_token.`);
|
|
287
|
-
if (grant === 'authorization_code') {
|
|
288
|
-
const code = params.code;
|
|
289
|
-
if (!code) return oauthError('invalid_request', 'No authorization code provided');
|
|
290
|
-
if (live(key!)) return oauthError('invalid_grant', `Authorization code provided does not belong to the livemode of the API key: ${code} is a test mode code, but a live mode key was used.`);
|
|
291
|
-
// a code is spent once: the read and the spend are one move, so two exchanges at once cannot both succeed
|
|
292
|
-
type Redeemed = { outcome: 'missing' } | { outcome: 'used' | 'expired' | 'ok'; row: Row };
|
|
293
|
-
const found = await decide<Redeemed>(ctx, (rows) => {
|
|
294
|
-
const row = rows(CODES).find((r) => r.sha256 === ctx.crypto.sha256(code));
|
|
295
|
-
if (!row) return { value: { outcome: 'missing' } };
|
|
296
|
-
// a second use is marked in the same move, so the exchange that spent it sees it after writing its connection
|
|
297
|
-
if (row.used === true) return { value: { outcome: 'used', row }, write: { resource: CODES, id: String(row.id), fields: { reused: true }, operation: 'oauth_code.reuse' } };
|
|
298
|
-
if (nowUnix(ctx.occurredAt) >= Number(row.expires_at)) return { value: { outcome: 'expired', row } };
|
|
299
|
-
return { value: { outcome: 'ok', row }, write: { resource: CODES, id: String(row.id), fields: { used: true, used_at: nowUnix(ctx.occurredAt) }, operation: 'oauth_code.redeem' } };
|
|
300
|
-
});
|
|
301
|
-
if (found.outcome === 'missing') return oauthError('invalid_grant', `Authorization code does not exist: ${code}`);
|
|
302
|
-
const account = String(found.row.account);
|
|
303
|
-
if (found.outcome === 'used') {
|
|
304
|
-
// "Consuming an authorization code more than once revokes the account connection"
|
|
305
|
-
await revoke(ctx, account);
|
|
306
|
-
return oauthError('invalid_grant', 'This authorization code has already been used. All tokens issued with this code have been revoked.');
|
|
307
|
-
}
|
|
308
|
-
if (found.outcome === 'expired') return oauthError('invalid_grant', `Authorization code expired: ${code}`);
|
|
309
|
-
const granted = String(found.row.scope) as Scope;
|
|
310
|
-
const refresh = `rt_${(await ctx.secret(`stripe-oauth-refresh:${String(found.row.id)}`)).replace(/[-_]/g, '').slice(0, 32)}`;
|
|
311
|
-
const secret = await ctx.secret(`stripe-oauth-access:${account}`);
|
|
312
|
-
const connection = { client_id: PLATFORM_CLIENT_ID, account, scope: granted, code: found.row.id, refresh_token: refresh, access_token: accessToken(ctx, secret, account, 1), access_scope: granted, generation: 1, publishable_key: `pk_test_oauth_${account}`, revoked: false, livemode: false };
|
|
313
|
-
await ctx.record(CONNECTIONS, connection, account);
|
|
314
|
-
// the code used again while this exchange was writing: that use found no connection to revoke, so this one does
|
|
315
|
-
if (ctx.rowsRaw(CODES).some((r) => r.id === found.row.id && r.reused === true)) {
|
|
316
|
-
await revoke(ctx, account);
|
|
317
|
-
return oauthError('invalid_grant', 'This authorization code has already been used. All tokens issued with this code have been revoked.');
|
|
318
|
-
}
|
|
319
|
-
return json(tokenBody(connection, granted));
|
|
320
|
-
}
|
|
321
|
-
const refresh = params.refresh_token;
|
|
322
|
-
if (!refresh) return oauthError('invalid_request', 'No refresh token provided');
|
|
323
|
-
const held = ctx.rowsRaw(CONNECTIONS).find((c) => c.refresh_token === refresh && c.revoked !== true);
|
|
324
|
-
if (!held) return oauthError('invalid_grant', `Refresh token does not exist: ${refresh}`);
|
|
325
|
-
if (live(key!)) return oauthError('invalid_grant', 'The refresh token provided does not belong to the livemode of the API key.');
|
|
326
|
-
const asked = params.scope || String(held.scope);
|
|
327
|
-
if (!(SCOPES as readonly string[]).includes(asked)) return oauthError('invalid_scope', `Invalid scope parameter provided: '${asked}'. Accepted scopes are 'read_write' or 'read_only'.`);
|
|
328
|
-
if (asked === 'read_write' && held.scope !== 'read_write') return oauthError('invalid_scope', `The requested scope 'read_write' is greater than the scope of the refresh token ('${String(held.scope)}').`);
|
|
329
|
-
const account = String(held.id);
|
|
330
|
-
// "Any existing access token with the same scope and mode ... is revoked": the connection holds the one now issued; the
|
|
331
|
-
// generation is read and written in one move, so two refreshes at once issue two tokens, and a refresh never lands
|
|
332
|
-
// on a connection revoked meanwhile
|
|
333
|
-
const secret = await ctx.secret(`stripe-oauth-access:${account}`);
|
|
334
|
-
const renewed = await decide(ctx, (rows) => {
|
|
335
|
-
const now = rows(CONNECTIONS).find((c) => c.id === account && c.revoked !== true);
|
|
336
|
-
if (!now) return { value: undefined };
|
|
337
|
-
const generation = Number(now.generation ?? 1) + 1;
|
|
338
|
-
const fields = { access_token: accessToken(ctx, secret, account, generation), access_scope: asked, generation };
|
|
339
|
-
return { value: { ...now, ...fields }, write: { resource: CONNECTIONS, id: account, fields, operation: 'oauth_connection.refresh' } };
|
|
340
|
-
});
|
|
341
|
-
if (!renewed) return oauthError('invalid_grant', `Refresh token does not exist: ${refresh}`);
|
|
342
|
-
return json(tokenBody(renewed, asked as Scope));
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
/** The token endpoint's answer, as the reference lists it. */
|
|
346
|
-
function tokenBody(c: Row, scope: Scope): Row {
|
|
347
|
-
return { access_token: c.access_token, livemode: false, refresh_token: c.refresh_token, scope, stripe_publishable_key: c.publishable_key, stripe_user_id: c.account ?? c.id, token_type: 'bearer' };
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
async function deauthorize(ctx: HandlerContext): Promise<Response> {
|
|
351
|
-
const request = ctx.call.request;
|
|
352
|
-
const params = await bodyOf(request);
|
|
353
|
-
const key = secretKey(request, params);
|
|
354
|
-
const refused = keyRefused(key);
|
|
355
|
-
if (refused) return refused;
|
|
356
|
-
const client = params.client_id;
|
|
357
|
-
const account = params.stripe_user_id;
|
|
358
|
-
if (!client) return oauthError('invalid_request', 'No client_id provided');
|
|
359
|
-
if (!account) return oauthError('invalid_request', 'No stripe_user_id provided');
|
|
360
|
-
if (client !== PLATFORM_CLIENT_ID) return oauthError('invalid_client', `No such application: '${client}'`);
|
|
361
|
-
if (live(key!)) return oauthError('invalid_client', `The API key mode (live) does not match the mode of the client_id ${client} (test).`);
|
|
362
|
-
// the check and the revocation are one move (revoke): of two deauthorizations at once, one revokes and the other finds
|
|
363
|
-
// the account no longer connected
|
|
364
|
-
if (!(await revoke(ctx, account))) return oauthError('invalid_client', `This application is not connected to stripe account ${account}, or that account does not exist.`);
|
|
365
|
-
return json({ stripe_user_id: account });
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
/** connect.stripe.com's OAuth endpoints; Stripe's 404 for anything else there. */
|
|
369
|
-
export async function screen(ctx: HandlerContext): Promise<Response> {
|
|
370
|
-
const request = ctx.call.request;
|
|
371
|
-
const path = new URL(request.url).pathname.replace(/\/+$/, '');
|
|
372
|
-
if (path === '/oauth/authorize' && (request.method === 'GET' || request.method === 'POST')) return authorize(ctx);
|
|
373
|
-
if (path === '/oauth/token' && request.method === 'POST') return token(ctx);
|
|
374
|
-
if (path === '/oauth/deauthorize' && request.method === 'POST') return deauthorize(ctx);
|
|
375
|
-
return notFound();
|
|
376
|
-
}
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
// Stripe's disputes operations (docs/contributing/architecture.md, "What an author writes"): each handler over the
|
|
2
|
-
// handler contract's context, computing with the engine (../engine/).
|
|
3
|
-
import type { HandlerContext } from '@volter/world-core';
|
|
4
|
-
import type { Row } from '../engine/common.ts';
|
|
5
|
-
import { asBool } from '../engine/stripe.ts';
|
|
6
|
-
import { at, disputesDisputeMissing, keepEvidence, settleDisputeWon } from './shared.ts';
|
|
7
|
-
|
|
8
|
-
export async function GetDisputesDispute(ctx: HandlerContext): Promise<Response> {
|
|
9
|
-
const d = ctx.get('dispute', at(ctx, 'dispute'));
|
|
10
|
-
return d ? ctx.reply(d) : disputesDisputeMissing(ctx, at(ctx, 'dispute'));
|
|
11
|
-
}
|
|
12
|
-
|
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
// Stripe's invoiceitems operations (docs/contributing/architecture.md, "What an author writes"): each handler over the
|
|
2
|
-
// handler contract's context, computing with the engine (../engine/).
|
|
3
|
-
import type { HandlerContext } from '@volter/world-core';
|
|
4
|
-
import type { Row } from '../engine/common.ts';
|
|
5
|
-
import { INV, linesOf } from '../engine/invoices.ts';
|
|
6
|
-
import { nowUnix } from '../engine/stripe.ts';
|
|
7
|
-
import { at, created, fail, invoiceMissing, itemMissing, pricedItem, resyncDraftLines, writeLines } from './shared.ts';
|
|
8
|
-
|
|
9
|
-
// an item is deleted only while its invoice is still editable
|
|
10
|
-
export async function DeleteInvoiceitemsInvoiceitem(ctx: HandlerContext): Promise<Response> {
|
|
11
|
-
const id = at(ctx, 'invoiceitem');
|
|
12
|
-
const it = ctx.get('invoiceitem', id);
|
|
13
|
-
if (!it) return itemMissing(ctx, id);
|
|
14
|
-
const onInvoice = typeof it.invoice === 'string' ? ctx.get(INV, it.invoice) : undefined;
|
|
15
|
-
if (onInvoice && onInvoice.status !== 'draft') return fail(ctx, 'You cannot delete an invoice item that is attached to an invoice that is no longer editable.', 400, 'invoice_not_editable');
|
|
16
|
-
await ctx.write('invoiceitem', id, { deleted: true }, 'invoiceitem.delete');
|
|
17
|
-
if (typeof it.invoice === 'string') await resyncDraftLines(ctx, it.invoice);
|
|
18
|
-
return ctx.reply({ id, object: 'invoiceitem', deleted: true });
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export async function PostInvoiceitems(ctx: HandlerContext): Promise<Response> {
|
|
22
|
-
const params = ctx.params;
|
|
23
|
-
const now = Number(nowUnix(ctx.occurredAt));
|
|
24
|
-
const qty = Number(params.quantity) || 1;
|
|
25
|
-
// the served version names the price in `pricing[price]` ("The pricing information for the invoice item", the served
|
|
26
|
-
// spec); an older version sends `price`. It is kept as the item's price, which the answer renders as `pricing`
|
|
27
|
-
// (../engine/version.ts)
|
|
28
|
-
const { pricing: pricingParam, ...stored } = params;
|
|
29
|
-
const given = (pricingParam as Row | undefined)?.price;
|
|
30
|
-
const priceRef = typeof given === 'string' && given ? given : typeof params.price === 'string' ? params.price : '';
|
|
31
|
-
const priced = priceRef ? pricedItem(ctx, priceRef, qty) : undefined;
|
|
32
|
-
if (priced instanceof Response) return priced;
|
|
33
|
-
const resolvedAmount = priced?.amount;
|
|
34
|
-
let resolvedCurrency = priced?.currency;
|
|
35
|
-
// only a draft invoice takes new items
|
|
36
|
-
const invoiceRef = typeof params.invoice === 'string' ? params.invoice : '';
|
|
37
|
-
let target: Row | undefined;
|
|
38
|
-
if (invoiceRef) {
|
|
39
|
-
target = ctx.get(INV, invoiceRef);
|
|
40
|
-
if (!target) return invoiceMissing(ctx, invoiceRef);
|
|
41
|
-
if (target.status !== 'draft') return fail(ctx, `This invoice cannot have invoice items added because it has status ${String(target.status)}.`, 400, 'invoice_not_editable');
|
|
42
|
-
if (resolvedCurrency === undefined && typeof target.currency === 'string') resolvedCurrency = target.currency;
|
|
43
|
-
}
|
|
44
|
-
// an invoice item is dated by `date`, not `created`; its currency is the price's, else the invoice's
|
|
45
|
-
const item = await created(ctx, 'invoiceitem', { ...stored, ...(priceRef ? { price: priceRef } : {}) }, {
|
|
46
|
-
livemode: false, discountable: true, proration: false, quantity: qty, quantity_decimal: String(qty),
|
|
47
|
-
period: { start: now, end: now }, currency: resolvedCurrency ?? 'usd',
|
|
48
|
-
...(resolvedAmount !== undefined ? { amount: resolvedAmount } : {}),
|
|
49
|
-
}, { timeField: 'date' });
|
|
50
|
-
if (target) {
|
|
51
|
-
await writeLines(ctx, invoiceRef, [...linesOf(target), {
|
|
52
|
-
id: `il_${String(item.id)}`, object: 'line_item', type: 'invoiceitem', amount: Number(item.amount) || 0, currency: String(target.currency ?? item.currency ?? 'usd'),
|
|
53
|
-
quantity: qty, proration: false, invoice_item: item.id, price: item.price ?? null,
|
|
54
|
-
period: item.period ?? { start: now, end: now }, description: (item.description as string) ?? null,
|
|
55
|
-
}]);
|
|
56
|
-
}
|
|
57
|
-
return ctx.reply(item);
|
|
58
|
-
}
|
|
59
|
-
|
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
// Stripe's setup_intents operations (docs/contributing/architecture.md, "What an author writes"): each handler over the
|
|
2
|
-
// handler contract's context, computing with the engine (../engine/).
|
|
3
|
-
import type { HandlerContext } from '@volter/world-core';
|
|
4
|
-
import { SI } from '../engine/setup-intents.ts';
|
|
5
|
-
import { asBool, microdepositsNextAction, mintClientSecret, requiresMicrodeposits, verifyMicrodeposits } from '../engine/stripe.ts';
|
|
6
|
-
import { at, attachable, attachPaymentMethod, confirmOnly, created, fail, load, mergeUpdate, methodFromData, microdepositsAsked, mintMandate, send } from './shared.ts';
|
|
7
|
-
|
|
8
|
-
export async function PostSetupIntents(ctx: HandlerContext): Promise<Response> {
|
|
9
|
-
// mandate_data and return_url each "can only be used with `confirm=true`" (the served spec; shared.ts confirmOnly)
|
|
10
|
-
const unconfirmed = confirmOnly(ctx, ['mandate_data', 'return_url'], asBool(ctx.params.confirm));
|
|
11
|
-
if (unconfirmed) return unconfirmed;
|
|
12
|
-
// the id is minted first so the client secret can carry it: Stripe.js parses the id back out
|
|
13
|
-
const id = typeof ctx.params.id === 'string' && ctx.params.id ? ctx.params.id : ctx.mint(SI);
|
|
14
|
-
// it waits for a payment method until it has one, then for its confirmation (manifest.ts)
|
|
15
|
-
const hasMethod = typeof ctx.params.payment_method === 'string' && ctx.params.payment_method !== '';
|
|
16
|
-
if (hasMethod) ctx.legal(SI, 'status', 'PostSetupIntents', 'requires_payment_method', 'requires_confirmation', id);
|
|
17
|
-
return ctx.reply(
|
|
18
|
-
// allowed_payment_method_types in the served version names the methods (docs.stripe.com/api/setup_intents/create)
|
|
19
|
-
await created(ctx, SI, { ...ctx.params, ...(Array.isArray(ctx.params.allowed_payment_method_types) ? { payment_method_types: ctx.params.allowed_payment_method_types.map(String) } : {}), id }, {
|
|
20
|
-
status: hasMethod ? 'requires_confirmation' : 'requires_payment_method', usage: 'off_session', client_secret: mintClientSecret(id, await ctx.secret(`client-secret:${id}`)), payment_method_types: ['card'],
|
|
21
|
-
next_action: null, latest_attempt: null, last_setup_error: null, livemode: false,
|
|
22
|
-
}),
|
|
23
|
-
);
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
// a bank account that needs micro-deposit verification waits in requires_action; anything else succeeds. The confirm's
|
|
27
|
-
// payment_method_data and mandate_data are instructions, not fields of the SetupIntent.
|
|
28
|
-
export async function PostSetupIntentsIntentConfirm(ctx: HandlerContext): Promise<Response> {
|
|
29
|
-
const loaded = load(ctx, 'PostSetupIntentsIntentConfirm');
|
|
30
|
-
if ('answer' in loaded) return loaded.answer;
|
|
31
|
-
const si = loaded.si;
|
|
32
|
-
const id = String(si.id);
|
|
33
|
-
const given = ctx.params;
|
|
34
|
-
const { payment_method_data: data, mandate_data: _mandate, ...fields } = given;
|
|
35
|
-
const made = await methodFromData(ctx, data);
|
|
36
|
-
const pm = made ?? (typeof ctx.params.payment_method === 'string' ? ctx.params.payment_method : typeof si.payment_method === 'string' ? si.payment_method : undefined);
|
|
37
|
-
if (si.status !== 'requires_action' && (requiresMicrodeposits(ctx.params, si) || microdepositsAsked(ctx, ctx.params, si, pm))) {
|
|
38
|
-
return ctx.reply(await ctx.write(SI, id, mergeUpdate(ctx, SI, id, { ...fields, ...(pm ? { payment_method: pm } : {}), status: 'requires_action', next_action: microdepositsNextAction() }), 'setup_intent.requires_action'));
|
|
39
|
-
}
|
|
40
|
-
// a setup for a customer saves the method to them (docs.stripe.com/payments/save-and-reuse): its payment method is attached
|
|
41
|
-
const customer = typeof si.customer === 'string' ? si.customer : undefined;
|
|
42
|
-
const saved = pm && customer && attachable(ctx, pm) && ctx.get('payment_method', pm)?.customer !== customer ? String((await attachPaymentMethod(ctx, pm, customer)).id) : pm;
|
|
43
|
-
return ctx.reply(await ctx.write(SI, id, mergeUpdate(ctx, SI, id, { ...fields, ...(saved ? { payment_method: saved } : {}), status: 'succeeded' }), 'setup_intent.confirm'));
|
|
44
|
-
}
|
|
45
|
-
|
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
// Stripe's subscription_items operations (docs/contributing/architecture.md, "What an author writes"): each handler over the
|
|
2
|
-
// handler contract's context, computing with the engine (../engine/).
|
|
3
|
-
import type { HandlerContext } from '@volter/world-core';
|
|
4
|
-
import type { Row } from '../engine/common.ts';
|
|
5
|
-
import { subscriptionItemPrice } from '../engine/stripe.ts';
|
|
6
|
-
import { ITEM_ATTRIBUTES, SUB } from '../engine/subscriptions.ts';
|
|
7
|
-
import { at, created, fail, finder, list, newest, subMissing, subscriptionsItemMissing, syncItems, withPeriod } from './shared.ts';
|
|
8
|
-
|
|
9
|
-
export async function DeleteSubscriptionItemsItem(ctx: HandlerContext): Promise<Response> {
|
|
10
|
-
const id = at(ctx, 'item');
|
|
11
|
-
const si = ctx.get('subscription_item', id);
|
|
12
|
-
if (!si) return subscriptionsItemMissing(ctx, id);
|
|
13
|
-
await ctx.write('subscription_item', id, { deleted: true }, 'subscription_item.delete');
|
|
14
|
-
await syncItems(ctx, String(si.subscription));
|
|
15
|
-
return ctx.reply({ id, object: 'subscription_item', deleted: true });
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export async function GetSubscriptionItemsItem(ctx: HandlerContext): Promise<Response> {
|
|
19
|
-
const si = ctx.get('subscription_item', at(ctx, 'item'));
|
|
20
|
-
return si ? ctx.reply(withPeriod(ctx, si)) : subscriptionsItemMissing(ctx, at(ctx, 'item'));
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export async function PostSubscriptionItems(ctx: HandlerContext): Promise<Response> {
|
|
24
|
-
const params = ctx.params;
|
|
25
|
-
const subId = typeof params.subscription === 'string' ? params.subscription : '';
|
|
26
|
-
if (!subId) return fail(ctx, 'Missing required param: subscription.', 400, 'parameter_missing');
|
|
27
|
-
if (!ctx.get(SUB, subId)) return subMissing(ctx, subId);
|
|
28
|
-
const priceRef = typeof params.price === 'string' ? params.price : '';
|
|
29
|
-
if (!priceRef && !(params.price_data && typeof params.price_data === 'object')) return fail(ctx, 'Missing required param: price.', 400, 'parameter_missing');
|
|
30
|
-
if (priceRef && !ctx.get('price', priceRef)) return fail(ctx, `No such price: '${priceRef}'`, 400, 'resource_missing');
|
|
31
|
-
const quantity = params.quantity !== undefined ? Math.max(0, Math.trunc(Number(params.quantity) || 0)) : 1;
|
|
32
|
-
// "metadata: Set of key-value pairs that you can attach to an object" (docs.stripe.com/api/subscription_items/create)
|
|
33
|
-
const metadata = params.metadata && typeof params.metadata === 'object' ? { metadata: params.metadata } : {};
|
|
34
|
-
const body = await created(ctx, 'subscription_item', { subscription: subId, ...(priceRef ? subscriptionItemPrice(priceRef, finder(ctx)) : { price: null, plan: null }), quantity, ...metadata }, { livemode: false, metadata: {} });
|
|
35
|
-
await syncItems(ctx, subId);
|
|
36
|
-
return ctx.reply(withPeriod(ctx, body));
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export async function PostSubscriptionItemsItem(ctx: HandlerContext): Promise<Response> {
|
|
40
|
-
const id = at(ctx, 'item');
|
|
41
|
-
const si = ctx.get('subscription_item', id);
|
|
42
|
-
if (!si) return subscriptionsItemMissing(ctx, id);
|
|
43
|
-
// only the item's own attributes are kept; the update's instructions (off_session, payment_behavior, price_data,
|
|
44
|
-
// proration_behavior, proration_date) are not attributes of the Subscription Item object
|
|
45
|
-
// (docs.stripe.com/api/subscription_items/object lists none of them)
|
|
46
|
-
const fields: Row = Object.fromEntries(Object.entries(ctx.params).filter(([k]) => ITEM_ATTRIBUTES.has(k)));
|
|
47
|
-
if (ctx.params.quantity !== undefined) fields.quantity = Math.max(0, Math.trunc(Number(ctx.params.quantity) || 0));
|
|
48
|
-
if (typeof ctx.params.price === 'string' && ctx.params.price && !ctx.get('price', ctx.params.price)) return fail(ctx, `No such price: '${ctx.params.price}'`, 400, 'resource_missing');
|
|
49
|
-
// the item carries its Price and plan, as the subscription's own items do (subscriptionItemPrice)
|
|
50
|
-
if (typeof ctx.params.price === 'string' && ctx.params.price) Object.assign(fields, subscriptionItemPrice(ctx.params.price, finder(ctx)));
|
|
51
|
-
const out = await ctx.write('subscription_item', id, fields, 'subscription_item.update');
|
|
52
|
-
await syncItems(ctx, String(si.subscription));
|
|
53
|
-
return ctx.reply(withPeriod(ctx, out));
|
|
54
|
-
}
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
// Stripe's subscription_schedules operations (docs/contributing/architecture.md, "What an author writes"): each handler over the
|
|
2
|
-
// handler contract's context, computing with the engine (../engine/).
|
|
3
|
-
import type { HandlerContext } from '@volter/world-core';
|
|
4
|
-
import type { Row } from '../engine/common.ts';
|
|
5
|
-
import { buildSubscriptionItemsList, nowUnix } from '../engine/stripe.ts';
|
|
6
|
-
import { SS } from '../engine/subscription-schedules.ts';
|
|
7
|
-
import { at, created, end, fail, finder, phasesOf, scheduleMissing, storeItems } from './shared.ts';
|
|
8
|
-
|
|
9
|
-
export async function GetSubscriptionSchedulesSchedule(ctx: HandlerContext): Promise<Response> {
|
|
10
|
-
const s = ctx.get(SS, at(ctx, 'schedule'));
|
|
11
|
-
return s ? ctx.reply(s) : scheduleMissing(ctx, at(ctx, 'schedule'));
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
// a schedule starts from a customer or from an existing subscription
|
|
15
|
-
export async function PostSubscriptionSchedules(ctx: HandlerContext): Promise<Response> {
|
|
16
|
-
const params = ctx.params;
|
|
17
|
-
const customer = typeof params.customer === 'string' ? params.customer : '';
|
|
18
|
-
const fromSub = typeof params.from_subscription === 'string' ? params.from_subscription : '';
|
|
19
|
-
if (!customer && !fromSub) return fail(ctx, 'Missing required param: customer (or from_subscription).', 400, 'parameter_missing');
|
|
20
|
-
if (customer && !ctx.get('customer', customer)) return fail(ctx, `No such customer: '${customer}'`, 404, 'resource_missing');
|
|
21
|
-
if (fromSub && !ctx.get('subscription', fromSub)) return fail(ctx, `No such subscription: '${fromSub}'`, 404, 'resource_missing');
|
|
22
|
-
// start_date is an instruction ("now" or when), not a field of the schedule
|
|
23
|
-
const start = params.start_date !== undefined && params.start_date !== 'now' ? Number(params.start_date) : Number(nowUnix(ctx.occurredAt));
|
|
24
|
-
const phases = phasesOf(ctx, Array.isArray(params.phases) ? (params.phases as Row[]) : [], start);
|
|
25
|
-
const { phases: _p, start_date: _s, default_settings: givenDefaults, ...rest } = params;
|
|
26
|
-
const defaults = givenDefaults && typeof givenDefaults === 'object' ? (givenDefaults as Row) : {};
|
|
27
|
-
const schedId = ctx.mint(SS);
|
|
28
|
-
// a schedule for a customer whose first phase starts now starts its subscription at once, on that phase's items
|
|
29
|
-
// (docs.stripe.com/billing/subscriptions/subscription-schedules#managing)
|
|
30
|
-
let subscription = fromSub || null;
|
|
31
|
-
if (!fromSub && phases.length) {
|
|
32
|
-
const now = Number(nowUnix(ctx.occurredAt));
|
|
33
|
-
const subId = ctx.mint('subscription');
|
|
34
|
-
const items = buildSubscriptionItemsList(phases[0]!.items as Row[], subId, now, finder(ctx));
|
|
35
|
-
await created(ctx, 'subscription', { customer, id: subId }, {
|
|
36
|
-
status: 'active', livemode: false, currency: 'usd', collection_method: String((params.default_settings as Row | undefined)?.collection_method ?? 'charge_automatically'),
|
|
37
|
-
cancel_at_period_end: false, start_date: now, billing_cycle_anchor: now, metadata: {}, discounts: [], billing_schedules: [],
|
|
38
|
-
trial_start: null, trial_end: null, current_period_start: now, current_period_end: phases[0]!.end_date, items, schedule: schedId,
|
|
39
|
-
automatic_tax: { enabled: false, liability: null }, billing_mode: { type: 'classic' }, invoice_settings: { issuer: { type: 'self' } },
|
|
40
|
-
});
|
|
41
|
-
await storeItems(ctx, subId, (items.data as Row[]) ?? []);
|
|
42
|
-
subscription = subId;
|
|
43
|
-
}
|
|
44
|
-
return ctx.reply(
|
|
45
|
-
await created(ctx, SS, { ...rest, id: schedId }, {
|
|
46
|
-
status: 'active', livemode: false, phases, current_phase: phases.length ? { start_date: phases[0]!.start_date, end_date: phases[0]!.end_date } : null,
|
|
47
|
-
subscription, released_subscription: null, released_at: null,
|
|
48
|
-
canceled_at: null, completed_at: null, end_behavior: (params.end_behavior as string) ?? 'release',
|
|
49
|
-
renewal_interval: null, metadata: {}, billing_mode: { type: 'classic' },
|
|
50
|
-
// "billing_cycle_anchor: Possible values are phase_start or automatic" and invoice_settings are required (the
|
|
51
|
-
// served spec's default settings); the rest answer what the request set, else null
|
|
52
|
-
default_settings: {
|
|
53
|
-
application_fee_percent: defaults.application_fee_percent ?? null, automatic_tax: { enabled: false, liability: null, disabled_reason: null },
|
|
54
|
-
billing_cycle_anchor: typeof defaults.billing_cycle_anchor === 'string' ? defaults.billing_cycle_anchor : 'automatic', billing_thresholds: null,
|
|
55
|
-
collection_method: typeof defaults.collection_method === 'string' ? defaults.collection_method : 'charge_automatically', default_payment_method: defaults.default_payment_method ?? null,
|
|
56
|
-
description: defaults.description ?? null, invoice_settings: { account_tax_ids: null, days_until_due: null, issuer: { type: 'self' } }, on_behalf_of: null, transfer_data: null,
|
|
57
|
-
},
|
|
58
|
-
// a schedule made from a subscription is its customer's
|
|
59
|
-
customer: customer || String(ctx.get('subscription', fromSub)?.customer ?? ''),
|
|
60
|
-
}),
|
|
61
|
-
);
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
export async function PostSubscriptionSchedulesScheduleRelease(ctx: HandlerContext): Promise<Response> {
|
|
65
|
-
return (end('release'))(ctx);
|
|
66
|
-
}
|