@yaks/stripe 0.0.0-stage → 0.2.36

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.
@@ -0,0 +1,217 @@
1
+ import type { Billed, Costs, Paid, Sale, Seller, Shopped, Shops, Tags } from "@yaks/host/payments";
2
+ import { type Keyed } from "./mod.js";
3
+ /** The slice of a Stripe account read here. Optional throughout: the shape is
4
+ * Stripe's to move, and a field that went missing must leave a readable row
5
+ * rather than a throw in the middle of somebody's onboarding. */ export type Account = {
6
+ id?: string;
7
+ charges_enabled?: boolean;
8
+ details_submitted?: boolean;
9
+ payouts_enabled?: boolean;
10
+ /** `is_controller` true for an account the platform made; unset for one
11
+ * a seller connected */ controller?: {
12
+ is_controller?: boolean;
13
+ };
14
+ };
15
+ /** Stripe's host for Connect's OAuth, and where a seller whose account the
16
+ * platform does not control changes its details: their own dashboard. */ export declare let CONNECT: string;
17
+ export declare let DASHBOARD: string;
18
+ /** What the shops are lent: the key and clock, and the platform's Connect
19
+ * `client_id` (ca_…), which a seller connects an account they already have
20
+ * through; without one they can only open a new one. */ export type Options = Keyed & {
21
+ client?: string;
22
+ publishableKey?: string;
23
+ walletKey?: string;
24
+ };
25
+ /** The address of Stripe's page where a seller connects an account they
26
+ * already have. `read_write` is the only scope a platform may ask for, and
27
+ * `redirect_uri` must be one listed in the platform's OAuth settings. */ export declare let authorizeAt: (client: string, state: string, back: string) => string;
28
+ /** The slice of a completed Checkout Session read here. */ export type Session = {
29
+ id?: string;
30
+ payment_intent?: string | {
31
+ id?: string;
32
+ status?: string;
33
+ } | null;
34
+ payment_status?: string;
35
+ status?: string;
36
+ amount_total?: number;
37
+ currency?: string;
38
+ customer?: string | {
39
+ id?: string;
40
+ } | null;
41
+ customer_email?: string | null;
42
+ customer_details?: {
43
+ email?: string | null;
44
+ name?: string | null;
45
+ };
46
+ metadata?: Record<string, string>;
47
+ /** the one it started, in subscription mode */ subscription?: string | {
48
+ id?: string;
49
+ } | null;
50
+ };
51
+ /** The slice of a charge, or of a dispute about one, read here. */ export type Charge = {
52
+ id?: string;
53
+ /** a dispute's charge */ charge?: string | {
54
+ id?: string;
55
+ };
56
+ payment_intent?: string | {
57
+ id?: string;
58
+ };
59
+ metadata?: Record<string, string>;
60
+ refunded?: boolean;
61
+ amount?: number;
62
+ amount_refunded?: number;
63
+ application_fee?: string | {
64
+ id?: string;
65
+ };
66
+ status?: string;
67
+ };
68
+ /**
69
+ * The account asked for, as the form fields of `POST /v1/accounts`.
70
+ *
71
+ * The controller properties are the whole model. "Charge merchants directly"
72
+ * is these four answers, and each is a sentence about who is responsible for
73
+ * what. They are also, all four, Stripe's own defaults, the combination it
74
+ * documents as the Standard mapping
75
+ * (docs.stripe.com/connect/migrate-to-controller-properties). They are written
76
+ * out anyway, because a liability decision that four omitted parameters happen
77
+ * to make is a liability decision nobody can read, and a default Stripe moves
78
+ * one day would move it silently.
79
+ *
80
+ * `controller[fees][payer] = account`
81
+ * the connected account pays Stripe's processing fee, out of its own
82
+ * money, on its own charge. Not the platform: it is not reselling
83
+ * payments.
84
+ * `controller[losses][payments] = stripe`
85
+ * Stripe, not the platform, carries the negative balance when a dispute
86
+ * is lost. There is no `account` value here and the value is not a
87
+ * mistake: `stripe` is what "the platform is not liable" is called, and
88
+ * the merchant is still the one whose charge is reversed.
89
+ * `controller[stripe_dashboard][type] = full`
90
+ * the seller gets the whole Stripe Dashboard, their own account, where
91
+ * they read their payments, answer their disputes and manage their
92
+ * payouts. `express` is the cut-down one, and Stripe refuses it beside
93
+ * `fees.payer = account`: an Express dashboard is for a platform that
94
+ * pays the fees and carries the losses, which is the opposite of this.
95
+ * `controller[requirement_collection] = stripe`
96
+ * Stripe collects and re-collects the identity requirements, through the
97
+ * Account Link below. The platform never sees, stores or forwards a
98
+ * seller's identity documents, which is exactly the property that lets
99
+ * this integration exist without it becoming a KYC operator.
100
+ *
101
+ * No `capabilities`, deliberately. Stripe requires them only where the account
102
+ * has no Stripe-hosted dashboard; with `full` the payment capabilities are
103
+ * requested automatically for the account's country, and the seller manages
104
+ * them themselves. `transfers` in particular would be wrong: that is the
105
+ * capability a destination charge needs, and a direct charge never transfers.
106
+ *
107
+ * No `type` either. It is deprecated in favour of exactly these four
108
+ * properties, and the two ways of saying one thing are not passed together.
109
+ *
110
+ * `metadata` carries the tags, so an account read back out of Stripe's
111
+ * dashboard says whose it is without a lookup.
112
+ */ export declare let account: (who: {
113
+ email?: string;
114
+ tags: Tags;
115
+ }) => any;
116
+ /** The onboarding link, as the form fields of `POST /v1/account_links`.
117
+ *
118
+ * `account_onboarding` and never `account_update`: Stripe refuses an update
119
+ * link for an account that has its own dashboard, and these all do. A seller
120
+ * changing their details later does it in their own Stripe Dashboard, which is
121
+ * the whole point of giving them one.
122
+ *
123
+ * `return_url` is where Stripe sends them when they finish, and `refresh_url`
124
+ * where it sends them when the link is spent: an Account Link is single-use
125
+ * and expires in about five minutes, since it is an authenticated door into
126
+ * somebody's identity form. Stripe's own instruction for `refresh_url` is
127
+ * "generate a new account link with the same parameters, then redirect", which
128
+ * is asking for onboarding again, so both are `back`. */ export declare let link: (account: string, back: string) => any;
129
+ /** A Stripe account as a seller: `charges_enabled` is `ready` and
130
+ * `details_submitted` is `submitted`.
131
+ *
132
+ * A missing field reads false rather than "unchanged". Stripe sends the whole
133
+ * account object on every `account.updated`, so an absent flag is an absent
134
+ * capability, and a reader that treated it as unchanged would leave a seller
135
+ * marked ready after Stripe stopped them. */ export declare let sellerOf: (a: Account) => Seller;
136
+ /** What Stripe charges a seller in the United States, from its pricing page
137
+ * (stripe.com/pricing) and help pages, read 2026-11-23: 2.9% + 30¢ a
138
+ * domestic card payment, 1.5% more for an international card, a $15 dispute
139
+ * fee returned on a won dispute, processing fees kept on a refund
140
+ * (support.stripe.com/questions/understanding-fees-for-refunded-payments),
141
+ * and payouts on a two-day rolling schedule after a first payout about seven
142
+ * days after the first payment
143
+ * (support.stripe.com/questions/delay-for-first-payout-for-connected-accounts).
144
+ * The account pays them itself (`fees.payer = account`, {@link account}),
145
+ * so these are the seller's costs, as published, and change when Stripe's
146
+ * pricing does. */ export declare let COSTS: Costs;
147
+ /** The longest metadata value Stripe keeps, in characters: the most one
148
+ * tag carries ({@link Shops.tag}). */ export declare let TAG: number;
149
+ /** A return address as Stripe reads it. `{CHECKOUT_SESSION_ID}` is a literal
150
+ * Stripe substitutes the session id for on the way back, and the host hands
151
+ * over an address `URL` wrote, which percent-encodes braces in a query:
152
+ * `%7BCHECKOUT_SESSION_ID%7D` is a string Stripe does not recognise, so the
153
+ * buyer would land on a page that never learns which order it is about. The
154
+ * braces come back, and only those two characters. */ export declare let back: (url: string) => string;
155
+ /** The platform's cut of a sale paid once, in its smallest unit: the rate of
156
+ * its whole total, shipping included, rounded down, and never more than the
157
+ * sale. */ export declare let cut: (sale: Pick<Sale, 'lines' | 'shipping' | 'bps'>) => number;
158
+ /** A seller's name as a statement descriptor suffix: upper case, without the
159
+ * characters Stripe refuses there (`<>\'"*`), at most 22 characters, and ''
160
+ * where no letter is left, which Stripe requires one of. Stripe itself cuts
161
+ * the suffix to what fits after the account's prefix. */ export declare let descriptor: (name: string) => string;
162
+ /** The metadata key a house sale's objects carry, which tells its events on
163
+ * the platform's own account from the platform's plans (`housed`). */ export declare let HOUSE: string;
164
+ /**
165
+ * The Checkout Session, as the form fields of `POST /v1/checkout/sessions`,
166
+ * made on the seller's account (the `Stripe-Account` header `checkout` adds),
167
+ * or on the platform's own for the house: in payment mode for a sale paid
168
+ * once, and in subscription mode for one that says how often it renews, where
169
+ * every line recurs at that interval.
170
+ *
171
+ * The tags ride `metadata`, and the payment or the subscription it makes as
172
+ * well, with the house's mark on a house sale. Lines go out as inline
173
+ * `price_data`, numbered as Stripe's form encoding numbers a list.
174
+ */ export declare let session: (sale: Sale, house?: boolean, embedded?: boolean) => Record<string, unknown>;
175
+ /** A completed session as the sale it made. The buyer's address is
176
+ * `customer_details.email` and only falls back to `customer_email`: the
177
+ * second is the prefill the checkout started with, and the person may have
178
+ * typed a different one on Stripe's page. `payment_status` is the gate and
179
+ * `status` is not: a session can be `complete` with a payment still
180
+ * processing (a bank debit, say), and `paid` is the word Stripe documents as
181
+ * "the funds are available". */ export declare let paidOf: (o: Session) => Paid;
182
+ /** Stripe's shops, every call made with `options` as they read at the
183
+ * time. */ export declare let shops: (options: Options) => Shops;
184
+ /** The slice of a paid invoice read here. */ export type Invoice = {
185
+ id?: string;
186
+ customer?: string | {
187
+ id?: string;
188
+ };
189
+ customer_email?: string | null;
190
+ customer_name?: string | null;
191
+ amount_paid?: number;
192
+ created?: number;
193
+ status_transitions?: {
194
+ paid_at?: number | null;
195
+ };
196
+ parent?: {
197
+ subscription_details?: {
198
+ metadata?: Tags | null;
199
+ };
200
+ };
201
+ subscription_details?: {
202
+ metadata?: Tags | null;
203
+ };
204
+ };
205
+ /** A paid invoice as the period it paid. The subscription's metadata rides
206
+ * the invoice under `parent` since API 2025-03-31.basil, and at its top
207
+ * level before; the time is when it was paid, else when it was made. */ export declare let billedOf: (o: Invoice, subscription: string) => Billed;
208
+ /** Whether a verified event Stripe posted about the platform's own account is
209
+ * about a house sale, which `shopped` reads, rather than about the platform's
210
+ * plans, which ./plans.ts `changed` reads: a checkout carrying the house's
211
+ * mark, or a payment refunded or disputed. The platform's plans read neither
212
+ * of the second, and a refund or dispute of one of theirs reads as a payment
213
+ * the shops know nothing of. */ export declare let housed: (event: unknown) => boolean;
214
+ /** A verified event Stripe posted to the Connect endpoint, read, with the
215
+ * account it happened on: '' for one about a house sale, posted to the
216
+ * platform's own endpoint. */ export declare let shopped: (options: Keyed) => any;
217
+ //# sourceMappingURL=shops.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shops.d.ts","sources":["../shops.ts"],"names":[],"mappings":"AA2CA,cACE,MAAM,EACN,KAAK,EACL,IAAI,EACJ,IAAI,EACJ,MAAM,EAEN,OAAO,EACP,KAAK,EACL,IAAI,mCACiC;AACvC,SAA2B,KAAK,KAAK,mBAA2B;A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AC5B,OAAO,YAAI,UAAW,SAAS,cA4E9B"}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * A `Stripe-Signature` header over exactly these bytes: HMAC-SHA256 of
3
+ * `<timestamp>.<raw body>`, keyed by the endpoint's signing secret. The scheme
4
+ * is the same for a platform endpoint and a Connect one; only the secret
5
+ * differs. @yaks/hook's `refusal('stripe', …)` verifies it.
6
+ */ export declare let signed: (secret: string, raw: string, at: number) => Promise<string>;
7
+ /**
8
+ * A subscription shaped the way ./plans.ts `read` reads one, and no more,
9
+ * tagged with `metadata`: active, paid a month ahead, under ids of its own. A
10
+ * `customer.subscription.*` event carries its subscription whole and is read
11
+ * without asking Stripe back, so this stands in for one Stripe never held.
12
+ * `over` sets the fields a particular delivery turns on, such as a
13
+ * cancellation's `status` and `ended_at`.
14
+ */ export declare let fakeSub: (metadata: Record<string, string>, over?: Record<string, unknown>) => {
15
+ [field: string]: unknown;
16
+ id: string;
17
+ customer: string;
18
+ status: string;
19
+ metadata: Record<string, string>;
20
+ current_period_end: number;
21
+ };
22
+ /**
23
+ * An event about `object`, signed with `secret` as Stripe signs it and posted
24
+ * to `path` through `post`: the door's answer, or a throw where it refused.
25
+ * `on` is the connected account the event is about, which Stripe puts on the
26
+ * envelope rather than in the object; `at` is when Stripe made it, and a
27
+ * redelivery is the same event again, so a test that replays one passes the
28
+ * same moment twice.
29
+ */ export declare let delivered: (post: (path: string, init: RequestInit) => Promise<Response>, path: string, secret: string, type: string, object: unknown, on?: string, at?: number) => Promise<string>;
30
+ //# sourceMappingURL=testing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.d.ts","sources":["../testing.ts"],"names":[],"mappings":"AAEA;;;;;CAKC,GACD,OAAO,YAAI,SACT,QAAQ,MAAM,EACd,KAAK,MAAM,EACX,IAAI,MAAM,KACT,QAAQ,MAAM,EAgBhB;AAED;;;;;;;CAOC,GACD,OAAO,YAAI,UACT,UAAU,OAAO,MAAM,EAAE,MAAM,GAC/B,OAAM,OAAO,MAAM,EAAE,OAAO;GAE3B,OAAO,MAAM,GAAG,OAAO;EACxB,IAAI,MAAM;EACV,UAAU,MAAM;EAChB,QAAQ,MAAM;EACd,UAAU,OAAO,MAAM,EAAE,MAAM;EAC/B,oBAAoB,MAAM;EAW3B;AAED;;;;;;;CAOC,GACD,OAAO,YAAI,YACT,OAAO,MAAM,MAAM,EAAE,MAAM,gBAAgB,QAAQ,WACnD,MAAM,MAAM,EACZ,QAAQ,MAAM,EACd,MAAM,MAAM,EACZ,QAAQ,OAAO,EACf,KAAK,MAAM,EACX,KAAI,MAAM,KACT,QAAQ,MAAM,EAsBhB"}
package/checkout.js ADDED
@@ -0,0 +1,37 @@
1
+ // One payer's plan checkout, reused or expired before its replacement opens.
2
+ import { ask, list } from "./mod.js";
3
+ let digest = async (fields)=>[
4
+ ...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(fields))))
5
+ ].map((byte)=>byte.toString(16).padStart(2, '0')).join('');
6
+ export let checkout = async (options, asked, fields)=>{
7
+ let fingerprint = await digest(fields);
8
+ let open = [];
9
+ let previous;
10
+ for await (let session of list(options, '/v1/checkout/sessions', {
11
+ customer: asked.payer
12
+ })){
13
+ if (session.mode != 'subscription' || session.client_reference_id != asked.reference) continue;
14
+ previous ??= session.id;
15
+ if (session.status == 'open') open.push(session);
16
+ }
17
+ let held = open.find((session)=>session.metadata?._checkout == fingerprint && session.url);
18
+ for (let session of open){
19
+ if (session.id != held?.id) {
20
+ await ask(options, `/v1/checkout/sessions/${encodeURIComponent(session.id)}/expire`, {});
21
+ }
22
+ }
23
+ if (held) return held.url;
24
+ // The previous session is the durable identity of the next attempt. Two
25
+ // callers seeing the same history create once through Stripe's idempotency.
26
+ let made = await ask(options, '/v1/checkout/sessions', {
27
+ ...fields,
28
+ metadata: {
29
+ ...asked.tags,
30
+ _checkout: fingerprint
31
+ }
32
+ }, undefined, 'POST', `plan|${asked.reference}|${previous ?? asked.payer}`);
33
+ let url = String(made.url ?? '');
34
+ if (!url) throw new Error('stripe made a checkout session with no url');
35
+ return url;
36
+ };
37
+ //# sourceMappingURL=checkout.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"checkout.js","sources":["./checkout.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAE7E,SAAS,GAAG,EAAc,IAAI,mBAAkB;AAWhD,IAAI,SAAS,OAAO,SAClB;OACK,IAAI,WACL,MAAM,OAAO,MAAM,CAAC,MAAM,CACxB,WACA,IAAI,cAAc,MAAM,CAAC,KAAK,SAAS,CAAC;GAG7C,CACE,GAAG,CAAC,CAAC,OAAS,KAAK,QAAQ,CAAC,IAAI,QAAQ,CAAC,GAAG,MAAM,IAAI,CAAC;AAE5D,OAAO,IAAI,WAAW,OACpB,SACA,OACA;EAEA,IAAI,cAAc,MAAM,OAAO;EAC/B,IAAI,OAAkB,EAAE;EACxB,IAAI;EACJ,WACE,IAAI,WAAW,KAAc,SAAS,yBAAyB;IAC7D,UAAU,MAAM,KAAK;EACvB,GACA;IACA,IACE,QAAQ,IAAI,IAAI,kBAChB,QAAQ,mBAAmB,IAAI,MAAM,SAAS,EAC9C;IACF,aAAa,QAAQ,EAAE;IACvB,IAAI,QAAQ,MAAM,IAAI,QAAQ,KAAK,IAAI,CAAC;EAC1C;EACA,IAAI,OAAO,KAAK,IAAI,CAAC,CAAC,UACpB,QAAQ,QAAQ,EAAE,aAAa,eAAe,QAAQ,GAAG;EAE3D,KAAK,IAAI,WAAW,KAAM;IACxB,IAAI,QAAQ,EAAE,IAAI,MAAM,IAAI;MAC1B,MAAM,IACJ,SACA,CAAC,sBAAsB,EAAE,mBAAmB,QAAQ,EAAE,EAAE,OAAO,CAAC,EAChE,CAAC;IAEL;EACF;EACA,IAAI,MAAM,OAAO,KAAK,GAAG;EACzB,wEAAwE;EACxE,4EAA4E;EAC5E,IAAI,OAAO,MAAM,IACf,SACA,yBACA;IACE,GAAG,MAAM;IACT,UAAU;MAAE,GAAG,MAAM,IAAI;MAAE,WAAW;IAAY;EACpD,GACA,WACA,QACA,CAAC,KAAK,EAAE,MAAM,SAAS,CAAC,CAAC,EAAE,YAAY,MAAM,KAAK,EAAE;EAEtD,IAAI,MAAM,OAAO,KAAK,GAAG,IAAI;EAC7B,IAAI,CAAC,KAAK,MAAM,IAAI,MAAM;EAC1B,OAAO;AACT,EAAC"}
package/checkout.ts ADDED
@@ -0,0 +1,74 @@
1
+ // One payer's plan checkout, reused or expired before its replacement opens.
2
+ import type { Checkout } from 'jsr:@yaks/host@0.2.36/payments'
3
+ import { ask, type Keyed, list } from './mod.js'
4
+
5
+ type Session = {
6
+ id: string
7
+ mode: string
8
+ status: string
9
+ client_reference_id: string
10
+ metadata?: Record<string, string>
11
+ url?: string
12
+ }
13
+
14
+ let digest = async (fields: Record<string, unknown>): Promise<string> =>
15
+ [
16
+ ...new Uint8Array(
17
+ await crypto.subtle.digest(
18
+ 'SHA-256',
19
+ new TextEncoder().encode(JSON.stringify(fields)),
20
+ ),
21
+ ),
22
+ ]
23
+ .map((byte) => byte.toString(16).padStart(2, '0')).join('')
24
+
25
+ export let checkout = async (
26
+ options: Keyed,
27
+ asked: Checkout,
28
+ fields: Record<string, unknown>,
29
+ ): Promise<string> => {
30
+ let fingerprint = await digest(fields)
31
+ let open: Session[] = []
32
+ let previous: string | undefined
33
+ for await (
34
+ let session of list<Session>(options, '/v1/checkout/sessions', {
35
+ customer: asked.payer,
36
+ })
37
+ ) {
38
+ if (
39
+ session.mode != 'subscription' ||
40
+ session.client_reference_id != asked.reference
41
+ ) continue
42
+ previous ??= session.id
43
+ if (session.status == 'open') open.push(session)
44
+ }
45
+ let held = open.find((session) =>
46
+ session.metadata?._checkout == fingerprint && session.url
47
+ )
48
+ for (let session of open) {
49
+ if (session.id != held?.id) {
50
+ await ask(
51
+ options,
52
+ `/v1/checkout/sessions/${encodeURIComponent(session.id)}/expire`,
53
+ {},
54
+ )
55
+ }
56
+ }
57
+ if (held) return held.url!
58
+ // The previous session is the durable identity of the next attempt. Two
59
+ // callers seeing the same history create once through Stripe's idempotency.
60
+ let made = await ask(
61
+ options,
62
+ '/v1/checkout/sessions',
63
+ {
64
+ ...fields,
65
+ metadata: { ...asked.tags, _checkout: fingerprint },
66
+ },
67
+ undefined,
68
+ 'POST',
69
+ `plan|${asked.reference}|${previous ?? asked.payer}`,
70
+ )
71
+ let url = String(made.url ?? '')
72
+ if (!url) throw new Error('stripe made a checkout session with no url')
73
+ return url
74
+ }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts"]},"name":"@yaks/stripe","version":"0.2.36","license":"Apache-2.0","description":"Stripe's API over fetch, and the plans, shops and signed webhook doors it lends a host as a payment provider.","exports":{".":"./mod.ts","./doors":"./doors.ts","./graph":"./graph.ts","./plans":"./plans.ts","./testing":"./testing.ts","./shops":"./shops.ts"},"imports":{"@yaks/stripe":"./mod.ts","@yaks/stripe/doors":"./doors.ts","@yaks/stripe/graph":"./graph.ts","@yaks/stripe/plans":"./plans.ts","@yaks/stripe/testing":"./testing.ts","@yaks/stripe/shops":"./shops.ts"}}
package/doors.js ADDED
@@ -0,0 +1,36 @@
1
+ // Stripe's webhook doors, as @yaks/host's `Door`s: `webhook`, the endpoint
2
+ // on the platform's own account, which hears about its subscriptions
3
+ // (./plans.ts `changed`) and the house's sales (./shops.ts `housed`), and `connect`, the Connect endpoint, which hears
4
+ // about its sellers' accounts (./shops.ts `shopped`). Stripe delivers the two
5
+ // to endpoints of their own, each signed with its own `whsec_…`, so each door
6
+ // verifies with its own secret, and one verified with the other's hears
7
+ // nothing.
8
+ //
9
+ // The body is read as text once and verified as that exact string: the
10
+ // signature covers the raw bytes, so parsing and re-serializing would verify
11
+ // something Stripe never signed. A body signed with our secret that is not
12
+ // JSON throws, since only our own secret could have signed it.
13
+ import { ours, refusal } from "@yaks/hook";
14
+ import { changed } from "./plans.js";
15
+ import { housed, shopped } from "./shops.js";
16
+ let door = (secret, read, options)=>async (request)=>{
17
+ let key = secret();
18
+ if (!key) return undefined;
19
+ let raw = await request.text();
20
+ let why = await refusal('stripe', key, raw, request.headers, options.clock?.now());
21
+ return why ? {
22
+ refused: why,
23
+ ours: ours(why)
24
+ } : {
25
+ heard: read(JSON.parse(raw))
26
+ };
27
+ };
28
+ /** Stripe's doors, each secret read from `options` as a request arrives. */ export let doors = (options)=>{
29
+ let plan = changed(options);
30
+ let shop = shopped(options);
31
+ return {
32
+ webhook: door(()=>options.doors?.webhook, (event)=>housed(event) ? shop(event) : plan(event), options),
33
+ connect: door(()=>options.doors?.connect, shop, options)
34
+ };
35
+ };
36
+ //# sourceMappingURL=doors.js.map
package/doors.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"doors.js","sources":["./doors.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,qEAAqE;AACrE,uHAAuH;AACvH,8EAA8E;AAC9E,8EAA8E;AAC9E,wEAAwE;AACxE,WAAW;AACX,EAAE;AACF,uEAAuE;AACvE,6EAA6E;AAC7E,2EAA2E;AAC3E,+DAA+D;AAE/D,SAAS,IAAI,EAAE,OAAO,0BAA+B;AACrD,SAAS,OAAO,qBAA4C;AAC5D,SAAS,MAAM,EAA4B,OAAO,qBAAoB;AAStE,IAAI,OAAO,CACT,QACA,MACA,UAEF,OAAO;IACL,IAAI,MAAM;IACV,IAAI,CAAC,KAAK,OAAO;IACjB,IAAI,MAAM,MAAM,QAAQ,IAAI;IAC5B,IAAI,MAAM,MAAM,QACd,UACA,KACA,KACA,QAAQ,OAAO,EACf,QAAQ,KAAK,EAAE;IAEjB,OAAO,MACH;MAAE,SAAS;MAAK,MAAM,KAAK;IAAK,IAChC;MAAE,OAAO,KAAK,KAAK,KAAK,CAAC;IAAM;EACrC;AAEA,0EAA0E,GAC1E,OAAO,IAAI,QAAQ,CAAC;EAClB,IAAI,OAAO,QAAQ;EACnB,IAAI,OAAO,QAAQ;EACnB,OAAO;IACL,SAAS,KACP,IAAM,QAAQ,KAAK,EAAE,SACrB,CAAC,QAAU,OAAO,SAAS,KAAK,SAAS,KAAK,QAC9C;IAEF,SAAS,KAAK,IAAM,QAAQ,KAAK,EAAE,SAAS,MAAM;EACpD;AACF,EAAC"}
package/doors.ts ADDED
@@ -0,0 +1,58 @@
1
+ // Stripe's webhook doors, as @yaks/host's `Door`s: `webhook`, the endpoint
2
+ // on the platform's own account, which hears about its subscriptions
3
+ // (./plans.ts `changed`) and the house's sales (./shops.ts `housed`), and `connect`, the Connect endpoint, which hears
4
+ // about its sellers' accounts (./shops.ts `shopped`). Stripe delivers the two
5
+ // to endpoints of their own, each signed with its own `whsec_…`, so each door
6
+ // verifies with its own secret, and one verified with the other's hears
7
+ // nothing.
8
+ //
9
+ // The body is read as text once and verified as that exact string: the
10
+ // signature covers the raw bytes, so parsing and re-serializing would verify
11
+ // something Stripe never signed. A body signed with our secret that is not
12
+ // JSON throws, since only our own secret could have signed it.
13
+ import type { Door, Heard } from 'jsr:@yaks/host@0.2.36/payments'
14
+ import { ours, refusal } from '@yaks/hook'
15
+ import { changed, type Options as Priced } from './plans.js'
16
+ import { housed, type Options as Shopping, shopped } from './shops.js'
17
+
18
+ /** What a config gives the provider: the plans' key, clock and prices, the
19
+ * shops' Connect client, and each door's signing secret by its name. A door
20
+ * with none hears nothing. */
21
+ export type Options = Priced & Shopping & {
22
+ doors?: { webhook?: string; connect?: string }
23
+ }
24
+
25
+ let door = (
26
+ secret: () => string | undefined,
27
+ read: (event: unknown) => Heard,
28
+ options: Options,
29
+ ): Door =>
30
+ async (request) => {
31
+ let key = secret()
32
+ if (!key) return undefined
33
+ let raw = await request.text()
34
+ let why = await refusal(
35
+ 'stripe',
36
+ key,
37
+ raw,
38
+ request.headers,
39
+ options.clock?.now(),
40
+ )
41
+ return why
42
+ ? { refused: why, ours: ours(why) }
43
+ : { heard: read(JSON.parse(raw)) }
44
+ }
45
+
46
+ /** Stripe's doors, each secret read from `options` as a request arrives. */
47
+ export let doors = (options: Options): Record<string, Door> => {
48
+ let plan = changed(options)
49
+ let shop = shopped(options)
50
+ return {
51
+ webhook: door(
52
+ () => options.doors?.webhook,
53
+ (event) => housed(event) ? shop(event) : plan(event),
54
+ options,
55
+ ),
56
+ connect: door(() => options.doors?.connect, shop, options),
57
+ }
58
+ }
package/graph.js ADDED
@@ -0,0 +1,17 @@
1
+ // The `@yaks/stripe/graph` facet: Stripe as the payment provider it lends its
2
+ // host, named `stripe` (@yaks/host/payments). The config passes it its key,
3
+ // its clock, the prices it sells (./plans.ts `Options`) and its doors'
4
+ // signing secrets (./doors.ts `Options`), each read at its use, so a key set
5
+ // after start-up is used by the next call.
6
+ import { doors } from "./doors.js";
7
+ import { plans } from "./plans.js";
8
+ import { shops } from "./shops.js";
9
+ export let payments = (_host, options)=>({
10
+ stripe: {
11
+ name: 'Stripe',
12
+ plans: plans(options),
13
+ shops: shops(options),
14
+ doors: doors(options)
15
+ }
16
+ });
17
+ //# sourceMappingURL=graph.js.map
package/graph.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph.js","sources":["./graph.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,4EAA4E;AAC5E,uEAAuE;AACvE,6EAA6E;AAC7E,2CAA2C;AAE3C,SAAS,KAAK,qBAAkC;AAChD,SAAS,KAAK,qBAAoB;AAClC,SAAS,KAAK,qBAAoB;AAElC,OAAO,IAAI,WAAW,CACpB,OACA,UAC6B,CAAC;IAC9B,QAAQ;MACN,MAAM;MACN,OAAO,MAAM;MACb,OAAO,MAAM;MACb,OAAO,MAAM;IACf;EACF,CAAC,EAAC"}
package/graph.ts ADDED
@@ -0,0 +1,21 @@
1
+ // The `@yaks/stripe/graph` facet: Stripe as the payment provider it lends its
2
+ // host, named `stripe` (@yaks/host/payments). The config passes it its key,
3
+ // its clock, the prices it sells (./plans.ts `Options`) and its doors'
4
+ // signing secrets (./doors.ts `Options`), each read at its use, so a key set
5
+ // after start-up is used by the next call.
6
+ import type { Payments } from 'jsr:@yaks/host@0.2.36/payments'
7
+ import { doors, type Options } from './doors.js'
8
+ import { plans } from './plans.js'
9
+ import { shops } from './shops.js'
10
+
11
+ export let payments = (
12
+ _host: unknown,
13
+ options: Options,
14
+ ): Record<string, Payments> => ({
15
+ stripe: {
16
+ name: 'Stripe',
17
+ plans: plans(options),
18
+ shops: shops(options),
19
+ doors: doors(options),
20
+ },
21
+ })
package/invoices.js ADDED
@@ -0,0 +1,75 @@
1
+ import { ask, found, list } from "./mod.js";
2
+ export let invoiceMethods = {
3
+ payment_method_types: [
4
+ 'card',
5
+ 'us_bank_account'
6
+ ]
7
+ };
8
+ let product = 'prod_yaks_support_contract';
9
+ export let addOnPrice = async (at, item)=>{
10
+ if (!await found(at, `/v1/products/${product}`)) {
11
+ await ask(at, '/v1/products', {
12
+ id: product,
13
+ name: item.name
14
+ }, undefined, 'POST', product);
15
+ }
16
+ return {
17
+ price_data: {
18
+ product,
19
+ currency: 'usd',
20
+ recurring: {
21
+ interval: 'year'
22
+ },
23
+ unit_amount: item.cents
24
+ },
25
+ metadata: {
26
+ yaks_add_on: item.key
27
+ }
28
+ };
29
+ };
30
+ /** A draft holds the line before Stripe finalizes and sends it. Each step
31
+ * can be replayed, including after Stripe has expired its idempotency keys. */ export let invoiceOnce = async (at, item)=>{
32
+ let invoice;
33
+ for await (let bill of list(at, '/v1/invoices', {
34
+ customer: item.payer
35
+ })){
36
+ if (bill.metadata?.yaks_once == item.key) {
37
+ invoice = bill;
38
+ break;
39
+ }
40
+ }
41
+ let key = `invoice-once|${item.key}`;
42
+ if (!invoice) {
43
+ invoice = await ask(at, '/v1/invoices', {
44
+ customer: item.payer,
45
+ collection_method: 'send_invoice',
46
+ days_until_due: item.due,
47
+ auto_advance: false,
48
+ pending_invoice_items_behavior: 'exclude',
49
+ payment_settings: invoiceMethods,
50
+ metadata: {
51
+ ...item.tags,
52
+ yaks_once: item.key
53
+ }
54
+ }, undefined, 'POST', key);
55
+ }
56
+ if (invoice.status == 'draft') {
57
+ if (!invoice.lines?.data.some((line)=>line.metadata?.yaks_once == item.key)) {
58
+ await ask(at, '/v1/invoiceitems', {
59
+ customer: item.payer,
60
+ invoice: invoice.id,
61
+ amount: item.cents,
62
+ currency: 'usd',
63
+ description: item.name,
64
+ metadata: {
65
+ yaks_once: item.key
66
+ }
67
+ }, undefined, 'POST', `${key}|line`);
68
+ }
69
+ await ask(at, `/v1/invoices/${invoice.id}/finalize`, {
70
+ auto_advance: true
71
+ }, undefined, 'POST', `${key}|finalize`);
72
+ }
73
+ return invoice.id;
74
+ };
75
+ //# sourceMappingURL=invoices.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invoices.js","sources":["./invoices.ts"],"names":[],"mappings":"AACA,SAAS,GAAG,EAAE,KAAK,EAAc,IAAI,mBAAkB;AAEvD,OAAO,IAAI,iBAAiB;EAC1B,sBAAsB;IAAC;IAAQ;GAAkB;AACnD,EAAC;AAED,IAAI,UAAU;AAEd,OAAO,IAAI,aAAa,OAAO,IAAW;EACxC,IAAI,CAAC,MAAM,MAAM,IAAI,CAAC,aAAa,EAAE,SAAS,GAAG;IAC/C,MAAM,IACJ,IACA,gBACA;MAAE,IAAI;MAAS,MAAM,KAAK,IAAI;IAAC,GAC/B,WACA,QACA;EAEJ;EACA,OAAO;IACL,YAAY;MACV;MACA,UAAU;MACV,WAAW;QAAE,UAAU;MAAO;MAC9B,aAAa,KAAK,KAAK;IACzB;IACA,UAAU;MAAE,aAAa,KAAK,GAAG;IAAC;EACpC;AACF,EAAC;AASD;6EAC6E,GAC7E,OAAO,IAAI,cAAc,OAAO,IAAW;EACzC,IAAI;EACJ,WACE,IAAI,QAAQ,KAAW,IAAI,gBAAgB;IAAE,UAAU,KAAK,KAAK;EAAC,GAClE;IACA,IAAI,KAAK,QAAQ,EAAE,aAAa,KAAK,GAAG,EAAE;MACxC,UAAU;MACV;IACF;EACF;EACA,IAAI,MAAM,CAAC,aAAa,EAAE,KAAK,GAAG,EAAE;EACpC,IAAI,CAAC,SAAS;IACZ,UAAU,MAAM,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