@kerf-js/pay 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/stripe.ts ADDED
@@ -0,0 +1,397 @@
1
+ // Stripe's signature is HMAC-SHA256 of `<t>.<raw body>`, in a header `t=…,v1=…` that can carry several `v1` while a secret
2
+ // rolls. Stripe has no ordering guarantee, so each event carries the object's `created` or the event's own time, and the
3
+ // ledger orders by that. A price is the catalog's unless `prices` maps `pro.month` to a Stripe id, on the server.
4
+
5
+ import {
6
+ PayError,
7
+ type CheckoutLine,
8
+ type PayRail,
9
+ type PurchaseState,
10
+ type RailEvent,
11
+ } from './index'
12
+ import { stripePayer } from './payer'
13
+
14
+ /** Options of `stripeRail()`. The keys default to the environment, which is where they belong. */
15
+ export interface StripeOptions {
16
+ /** Stripe Price ids by `<product>.<plan>` or `<product>`, from your own config. Default: amounts from the catalog. */
17
+ prices?: Record<string, string>
18
+ /** The API's origin: point it at a local mock. */
19
+ api?: string
20
+ /** Pinned, so an account's default version can't reshape these calls. */
21
+ apiVersion?: string
22
+ /** Seconds a signed delivery stays acceptable. Default 300, Stripe's own. */
23
+ tolerance?: number
24
+ /** ISO countries a `shipping` product delivers to. Default US and CA. */
25
+ shippingCountries?: string[]
26
+ /** `test` (sandbox) or `live`: what the keys must be, so a live key can't slip into a dev server or a test key into a
27
+ * shop. Default `process.env.STRIPE_MODE`; unset, the secret key's prefix decides. A mismatch is PAY032. */
28
+ mode?: 'test' | 'live'
29
+ /** Default `process.env.STRIPE_SECRET_KEY`: `sk_test_…` or `rk_test_…` in test mode, `sk_live_…`/`rk_live_…` live. */
30
+ secretKey?: string
31
+ /** Checked against the secret key when set, since a page that loads Stripe.js needs the matching one. Default
32
+ * `process.env.STRIPE_PUBLISHABLE_KEY`; nothing here sends it anywhere. */
33
+ publishableKey?: string
34
+ /** Default `process.env.STRIPE_WEBHOOK_SECRET`. */
35
+ webhookSecret?: string
36
+ /** Default the global one. */
37
+ fetch?: typeof fetch
38
+ }
39
+
40
+ const STATES: Record<string, PurchaseState> = {
41
+ active: 'active',
42
+ trialing: 'trial',
43
+ past_due: 'grace',
44
+ unpaid: 'billing-retry',
45
+ paused: 'paused',
46
+ canceled: 'expired',
47
+ incomplete_expired: 'expired',
48
+ incomplete: 'pending',
49
+ }
50
+
51
+ const API = 'https://api.stripe.com'
52
+ const encoder = new TextEncoder()
53
+ const env = (name: string) => (typeof process === 'undefined' ? undefined : process.env[name])
54
+
55
+ /** `test` or `live` from a Stripe key's prefix (`sk_`, `rk_`, `pk_`), undefined for anything else. */
56
+ export function stripeKeyMode(key: string | undefined): 'test' | 'live' | undefined {
57
+ const m = /^(?:sk|rk|pk)_(test|live)_/.exec(key ?? '')
58
+ return m ? (m[1] as 'test' | 'live') : undefined
59
+ }
60
+
61
+ /** The mode asked for, by option or `STRIPE_MODE`. A value other than `test` or `live` is refused, not guessed at. */
62
+ function wantedMode(options: StripeOptions): 'test' | 'live' | undefined {
63
+ const raw = options.mode ?? env('STRIPE_MODE')
64
+ if (raw === undefined || raw === '') return undefined
65
+ const mode = raw.trim().toLowerCase()
66
+ if (mode === 'test' || mode === 'sandbox') return 'test'
67
+ if (mode === 'live' || mode === 'production') return 'live'
68
+ throw new PayError('PAY032', `\`STRIPE_MODE\` is \`${raw}\`: set it to \`test\` or \`live\``, 500)
69
+ }
70
+
71
+ /** The mode the keys are in, after checking they agree with each other and with `STRIPE_MODE`. */
72
+ function keyMode(options: StripeOptions, key: string) {
73
+ const wanted = wantedMode(options)
74
+ const mode = stripeKeyMode(key)
75
+ if (wanted && mode && wanted !== mode)
76
+ throw new PayError(
77
+ 'PAY032',
78
+ wanted === 'test'
79
+ ? '`STRIPE_MODE` is `test` but `STRIPE_SECRET_KEY` is a live key: nothing was sent. Use the `sk_test_` key from the dashboard in test mode'
80
+ : '`STRIPE_MODE` is `live` but `STRIPE_SECRET_KEY` is a test key: no real payment would be taken. Use the `sk_live_` key',
81
+ 500,
82
+ )
83
+ const publishable = options.publishableKey ?? env('STRIPE_PUBLISHABLE_KEY')
84
+ const other = stripeKeyMode(publishable)
85
+ if (publishable && mode && other && other !== mode)
86
+ throw new PayError(
87
+ 'PAY032',
88
+ `\`STRIPE_PUBLISHABLE_KEY\` is a ${other} key and \`STRIPE_SECRET_KEY\` a ${mode} one: take both from the same mode`,
89
+ 500,
90
+ )
91
+ return mode ?? wanted
92
+ }
93
+
94
+ const fromHex = (s: string) =>
95
+ /^[0-9a-f]{64}$/.test(s) ? Uint8Array.from(s.match(/../g)!, (b) => parseInt(b, 16)) : undefined
96
+
97
+ /** The runtime's constant-time compare. */
98
+ async function verified(secret: string, text: string, signatures: string[]) {
99
+ const key = await crypto.subtle.importKey(
100
+ 'raw',
101
+ encoder.encode(secret),
102
+ { name: 'HMAC', hash: 'SHA-256' },
103
+ false,
104
+ ['verify'],
105
+ )
106
+ const message = encoder.encode(text)
107
+ let ok = false
108
+ for (const s of signatures) {
109
+ const bytes = fromHex(s)
110
+ if (bytes && (await crypto.subtle.verify('HMAC', key, bytes, message))) ok = true
111
+ }
112
+ return ok
113
+ }
114
+
115
+ /** Stripe's form encoding: `a[b][0]=c`. */
116
+ function form(body: Record<string, unknown>) {
117
+ const out = new URLSearchParams()
118
+ const put = (key: string, v: unknown) => {
119
+ if (v === undefined || v === null) return
120
+ if (Array.isArray(v)) v.forEach((x, i) => put(`${key}[${i}]`, x))
121
+ else if (typeof v === 'object') for (const [k, x] of Object.entries(v)) put(`${key}[${k}]`, x)
122
+ else out.append(key, `${v as string | number | boolean}`)
123
+ }
124
+ for (const [k, v] of Object.entries(body)) put(k, v)
125
+ return out
126
+ }
127
+
128
+ const seconds = (s?: number | null) => (s ? s * 1000 : undefined)
129
+ /** The fields of a Stripe object that an event can carry, whichever kind of object it is. */
130
+ interface StripeObject {
131
+ id: string
132
+ status: string
133
+ customer?: unknown
134
+ metadata?: Record<string, string> | null
135
+ mode?: string
136
+ payment_intent?: unknown
137
+ payment_status?: string
138
+ refunded?: boolean
139
+ current_period_end?: number | null
140
+ items?: { data?: { current_period_end?: number | null }[] } | null
141
+ customer_details?: { email?: string | null; name?: string | null; phone?: string | null } | null
142
+ }
143
+ interface StripeEvent {
144
+ id?: string
145
+ type: string
146
+ created: number
147
+ data?: { object?: StripeObject }
148
+ }
149
+
150
+ /** A reference that Stripe expands into its object on some API versions. */
151
+ const id = (x: unknown): string | undefined =>
152
+ typeof x === 'string' ? x : (x as { id?: string } | null | undefined)?.id
153
+ const identity = (object: StripeObject) => {
154
+ const m = object?.metadata ?? {}
155
+ return {
156
+ ...(m.kerf_user && { user: m.kerf_user }),
157
+ ...(m.kerf_product && { product: m.kerf_product }),
158
+ ...(m.kerf_plan && { plan: m.kerf_plan }),
159
+ }
160
+ }
161
+
162
+ /** A subscription's paid-through time, which moved onto its items in 2025 API versions. */
163
+ const periodEnd = (sub: StripeObject) =>
164
+ seconds(sub.current_period_end ?? sub.items?.data?.[0]?.current_period_end)
165
+
166
+ /** One Stripe event as the ledger's, or null for one that says nothing about access. */
167
+ function normalise(event: StripeEvent): RailEvent | null {
168
+ const object = event.data?.object
169
+ if (!event.id || !object) return null
170
+ const base = { id: event.id, at: event.created * 1000 }
171
+ const { type } = event
172
+ if (type.startsWith('customer.subscription.')) {
173
+ const state = STATES[object.status]
174
+ if (!state) return null
175
+ const customer = id(object.customer)
176
+ const expires = periodEnd(object)
177
+ return {
178
+ ...base,
179
+ purchase: object.id,
180
+ state,
181
+ ...identity(object),
182
+ ...(customer && { customer }),
183
+ ...(expires && { expires }),
184
+ }
185
+ }
186
+ if (
187
+ type === 'checkout.session.completed' ||
188
+ type === 'checkout.session.async_payment_succeeded' ||
189
+ type === 'checkout.session.async_payment_failed'
190
+ ) {
191
+ if (object.mode !== 'payment') return null // `customer.subscription.*` says what a subscription is doing, trial included
192
+ const purchase = id(object.payment_intent)
193
+ if (!purchase) return null
194
+ const customer = id(object.customer)
195
+ const state: PurchaseState = type.endsWith('failed')
196
+ ? 'expired'
197
+ : object.payment_status === 'unpaid'
198
+ ? 'pending'
199
+ : 'active'
200
+ return { ...base, purchase, state, ...identity(object), ...(customer && { customer }) }
201
+ }
202
+ if (type === 'charge.refunded') {
203
+ const purchase = id(object.payment_intent)
204
+ return purchase && object.refunded
205
+ ? { ...base, purchase, state: 'refunded', ...identity(object) }
206
+ : null // `refunded` is whole: a part refund keeps what was bought
207
+ }
208
+ if (type === 'charge.dispute.created' || type === 'charge.dispute.closed') {
209
+ const purchase = id(object.payment_intent)
210
+ if (!purchase) return null
211
+ if (type.endsWith('created')) return { ...base, purchase, state: 'revoked' }
212
+ return object.status === 'won' ? { ...base, purchase, state: 'active' } : null
213
+ }
214
+ return null
215
+ }
216
+
217
+ function stripeCall(
218
+ options: StripeOptions,
219
+ api: string,
220
+ apiVersion: string,
221
+ fetcher: typeof fetch,
222
+ ) {
223
+ const secret = () => {
224
+ const key = options.secretKey ?? env('STRIPE_SECRET_KEY')
225
+ if (!key) throw new PayError('PAY003', '`STRIPE_SECRET_KEY` is not set on the server', 500)
226
+ keyMode(options, key)
227
+ if (api === API && /placeholder/i.test(key))
228
+ throw new PayError(
229
+ 'PAY003',
230
+ '`STRIPE_SECRET_KEY` is still the placeholder `kerf add pay` wrote: nothing was sent to Stripe',
231
+ 500,
232
+ ) // a mock may take one
233
+ return key
234
+ }
235
+
236
+ async function call(path: string, body: Record<string, unknown>, idempotencyKey?: string) {
237
+ const res = await fetcher(`${api}${path}`, {
238
+ method: 'POST',
239
+ headers: {
240
+ authorization: `Bearer ${secret()}`,
241
+ 'content-type': 'application/x-www-form-urlencoded',
242
+ 'stripe-version': apiVersion,
243
+ ...(idempotencyKey && { 'idempotency-key': idempotencyKey }),
244
+ },
245
+ body: form(body),
246
+ })
247
+ const data = (await res.json().catch(() => null)) as {
248
+ url?: string
249
+ error?: { message?: string }
250
+ } | null
251
+ if (!res.ok)
252
+ throw new PayError(
253
+ 'PAY030',
254
+ `Stripe refused ${path}: ${data?.error?.message ?? res.status}`,
255
+ res.status === 429 ? 503 : 502,
256
+ )
257
+ return data
258
+ }
259
+
260
+ /** A read: no body, no idempotency. */
261
+ async function get(path: string) {
262
+ const res = await fetcher(`${api}${path}`, {
263
+ method: 'GET',
264
+ headers: { authorization: `Bearer ${secret()}`, 'stripe-version': apiVersion },
265
+ })
266
+ if (!res.ok) throw new PayError('PAY030', `Stripe refused ${path}: ${res.status}`, 502)
267
+ return (await res.json()) as unknown
268
+ }
269
+
270
+ return Object.assign(call, { get })
271
+ }
272
+
273
+ async function verifyStripe(
274
+ options: StripeOptions,
275
+ tolerance: number,
276
+ { body, headers }: Parameters<PayRail['verify']>[0],
277
+ get: (path: string) => Promise<unknown>,
278
+ ) {
279
+ const signing = options.webhookSecret ?? env('STRIPE_WEBHOOK_SECRET')
280
+ if (!signing)
281
+ throw new PayError(
282
+ 'PAY011',
283
+ '`STRIPE_WEBHOOK_SECRET` is not set: refusing every webhook rather than trusting one',
284
+ )
285
+ const parts = (headers.get('stripe-signature') ?? '').split(',').map((p) => p.trim().split('='))
286
+ const t = Number(parts.find(([k]) => k === 't')?.[1])
287
+ const given = parts.filter(([k]) => k === 'v1').map(([, v]) => v ?? '')
288
+ if (!Number.isInteger(t) || !given.length)
289
+ throw new PayError('PAY011', 'no `stripe-signature` to check')
290
+ if (!(await verified(signing, `${t}.${body}`, given)))
291
+ throw new PayError('PAY011', 'the signature does not match this body')
292
+ if (Math.abs(Date.now() / 1000 - t) > tolerance)
293
+ throw new PayError('PAY011', 'the signature is too old: a replay, or a clock adrift')
294
+ const raw = JSON.parse(body) as StripeEvent
295
+ const event = normalise(raw)
296
+ if (!event) return []
297
+ // a paid checkout says who paid: the session has their details, the payment's charge has the card
298
+ if (
299
+ event.state === 'active' &&
300
+ raw.type.startsWith('checkout.session.') &&
301
+ event.purchase.startsWith('pi_')
302
+ ) {
303
+ const payer = await stripePayer(raw.data!.object!.customer_details, event.purchase, get)
304
+ if (payer) event.payer = payer
305
+ }
306
+ return [event]
307
+ }
308
+
309
+ /** Test mode or not, for `rail.sandbox`; undefined while it can't tell, or the keys disagree (every call says PAY032). */
310
+ function sandboxOf(options: StripeOptions) {
311
+ try {
312
+ const key = options.secretKey ?? env('STRIPE_SECRET_KEY')
313
+ const mode = key ? keyMode(options, key) : wantedMode(options)
314
+ return mode === undefined ? undefined : mode === 'test'
315
+ } catch {
316
+ return undefined
317
+ }
318
+ }
319
+
320
+ /** The Stripe `pay.rail` provider: hosted Checkout, the customer portal, and webhooks verified here. */
321
+ export function stripeRail(options: StripeOptions = {}): PayRail {
322
+ const { prices = {}, api = API, apiVersion = '2025-09-30.clover', tolerance = 300 } = options
323
+ const fetcher = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args))
324
+ const call = stripeCall(options, api, apiVersion, fetcher)
325
+
326
+ function lineItem(line: CheckoutLine) {
327
+ const known = prices[line.plan ? `${line.product}.${line.plan}` : line.product]
328
+ if (known) return { price: known, quantity: line.quantity }
329
+ return {
330
+ quantity: line.quantity,
331
+ price_data: {
332
+ currency: line.currency,
333
+ unit_amount: line.amount,
334
+ product_data: { name: line.name },
335
+ ...(line.interval && { recurring: { interval: line.interval } }),
336
+ },
337
+ }
338
+ }
339
+
340
+ return {
341
+ id: 'stripe',
342
+ get sandbox() {
343
+ return sandboxOf(options)
344
+ },
345
+ async checkout(request) {
346
+ const { line, user, customer } = request
347
+ const metadata = {
348
+ kerf_user: user,
349
+ kerf_product: line.product,
350
+ ...(line.plan && { kerf_plan: line.plan }),
351
+ }
352
+ const session = await call(
353
+ '/v1/checkout/sessions',
354
+ {
355
+ mode: line.mode,
356
+ line_items: (request.lines ?? [line]).map(lineItem),
357
+ success_url: request.successUrl,
358
+ cancel_url: request.cancelUrl,
359
+ client_reference_id: user,
360
+ customer,
361
+ customer_email: customer ? undefined : request.email,
362
+ metadata,
363
+ // What the later events carry: a charge and a subscription don't inherit the session's metadata.
364
+ ...(line.mode === 'subscription'
365
+ ? { subscription_data: { metadata, trial_period_days: line.trialDays } }
366
+ : {
367
+ payment_intent_data: { metadata },
368
+ customer_creation: customer ? undefined : 'always',
369
+ ...(line.shipping && {
370
+ shipping_address_collection: {
371
+ allowed_countries: options.shippingCountries ?? ['US', 'CA'],
372
+ },
373
+ }),
374
+ }),
375
+ },
376
+ request.idempotencyKey,
377
+ )
378
+ if (typeof session?.url !== 'string')
379
+ throw new PayError('PAY030', 'Stripe answered a session with no url', 502)
380
+ return { url: session.url }
381
+ },
382
+ async portal({ customer, returnUrl }) {
383
+ const session = await call('/v1/billing_portal/sessions', { customer, return_url: returnUrl })
384
+ return { url: session!.url! }
385
+ },
386
+ verify: (delivery) => verifyStripe(options, tolerance, delivery, call.get),
387
+ async refund({ purchase }) {
388
+ if (!purchase.startsWith('pi_'))
389
+ throw new PayError(
390
+ 'PAY022',
391
+ 'Only a one-time payment refunds here: a subscription is cancelled in the portal',
392
+ 400,
393
+ )
394
+ await call('/v1/refunds', { payment_intent: purchase }, `refund:${purchase}`)
395
+ },
396
+ }
397
+ }