@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/test.ts ADDED
@@ -0,0 +1,323 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto'
2
+ import { clock, net } from '@kerf-js/core/test'
3
+ import { definePay, memoryPayStore, type Pay, type PayOptions, type Purchase } from './server'
4
+ import {
5
+ PayError,
6
+ type CheckoutRequest,
7
+ type Interval,
8
+ type Payer,
9
+ type PayRail,
10
+ type Product,
11
+ type PurchaseState,
12
+ type RailEvent,
13
+ } from './index'
14
+
15
+ const DAY = 86_400_000
16
+ const PERIOD: Record<Interval, number> = {
17
+ day: DAY,
18
+ week: 7 * DAY,
19
+ month: 30 * DAY,
20
+ year: 365 * DAY,
21
+ }
22
+ const TERMS = {
23
+ 'renewal-failed': 'grace',
24
+ 'grace-expired': 'expired',
25
+ recovered: 'active',
26
+ cancel: 'expired',
27
+ pause: 'paused',
28
+ resume: 'active',
29
+ refund: 'refunded',
30
+ revoke: 'revoked',
31
+ } as const
32
+
33
+ /** What `simulate` can make the rail do next. */
34
+ export type PayScenario = 'renewal' | keyof typeof TERMS
35
+
36
+ interface Bought {
37
+ id: string
38
+ user: string
39
+ product: string
40
+ plan?: string
41
+ interval?: Interval
42
+ state: PurchaseState
43
+ expires?: number
44
+ customer: string
45
+ }
46
+
47
+ /** A rail in memory and the handles a test drives it by, as `fakePay` returns them. */
48
+ export interface FakePay {
49
+ readonly pay: Pay
50
+ readonly rail: PayRail
51
+ /** Every checkout opened, newest last. */
52
+ readonly sessions: CheckoutRequest[]
53
+ /** Every delivery and how the app answered. */
54
+ readonly deliveries: { event: RailEvent; status: number }[]
55
+ /** The buyer finishes the hosted page: the newest open session, or the one for `user`. `payer` is who the rail says
56
+ * paid (a card's fingerprint, an email), as `onOrder` hears it. */
57
+ complete(user?: string, payer?: Payer): Promise<string>
58
+ /** The buyer closes the page. Nothing happens, as nothing does on a real rail. */
59
+ abandon(user?: string): void
60
+ /** A whole purchase, with no checkout screen in the way. */
61
+ buy(user: string, product: string, plan?: string): Promise<string>
62
+ /**
63
+ * What the rail does next: `renewal` moves a clock to the period's end first. `purchase` defaults to the newest.
64
+ * `renewal-failed`, `grace-expired`, `recovered`, `cancel`, `pause`, `resume`, `refund`, `revoke`.
65
+ */
66
+ simulate(what: PayScenario, purchase?: string): Promise<void>
67
+ /** The last event again: a redelivery. */
68
+ redeliver(): Promise<number>
69
+ /** An event by hand, in any order. `{ forged: true }` signs it with the wrong key. */
70
+ deliver(event: RailEvent, options?: { forged?: boolean }): Promise<number>
71
+ entitlements(user: string): Promise<string[]>
72
+ purchases(user: string): Promise<Purchase[]>
73
+ }
74
+
75
+ const sign = (secret: string, t: number, body: string) =>
76
+ createHmac('sha256', secret).update(`${t}.${body}`).digest('hex')
77
+ const SECRET = 'fake-pay-signing-key'
78
+
79
+ function fakeRail(
80
+ sessions: CheckoutRequest[],
81
+ next: (prefix: string) => string,
82
+ refund: (purchase: string) => Promise<void>,
83
+ ): PayRail {
84
+ const rail: PayRail = {
85
+ id: 'fake',
86
+ sandbox: true,
87
+ checkout(request) {
88
+ sessions.push(request)
89
+ return Promise.resolve({ url: `https://fake-pay.test/checkout/${next('cs')}` })
90
+ },
91
+ portal: ({ customer }) => Promise.resolve({ url: `https://fake-pay.test/portal/${customer}` }),
92
+ verify({ body, headers }) {
93
+ const [t, v1] = (headers.get('x-fake-signature') ?? '').split(',')
94
+ const want = Buffer.from(sign(SECRET, Number(t), body)),
95
+ got = Buffer.from(v1 ?? '')
96
+ if (want.length !== got.length || !timingSafeEqual(want, got))
97
+ throw new PayError('PAY011', 'no valid fake signature')
98
+ return JSON.parse(body)
99
+ },
100
+ async refund({ purchase }) {
101
+ await refund(purchase)
102
+ },
103
+ }
104
+
105
+ return rail
106
+ }
107
+
108
+ async function post(pay: Pay, deliveries: FakePay['deliveries'], event: RailEvent, secret: string) {
109
+ const body = JSON.stringify([event]),
110
+ t = Date.now()
111
+ const request = new Request('http://localhost/_kerf/pay/fake', {
112
+ method: 'POST',
113
+ body,
114
+ headers: { 'x-fake-signature': `${t},${sign(secret, t, body)}` },
115
+ })
116
+ const { response, tags } = await pay.webhook('fake', request)
117
+ deliveries.push({ event, status: response.status })
118
+ if (tags.length && net.subscriptions().length) await net.poke(...tags)
119
+ return response.status
120
+ }
121
+
122
+ async function open(
123
+ s: CheckoutRequest,
124
+ purchases: Map<string, Bought>,
125
+ next: (prefix: string) => string,
126
+ deliver: FakePay['deliver'],
127
+ event: (b: Bought) => RailEvent,
128
+ ) {
129
+ const { line, user } = s
130
+ const b: Bought = {
131
+ id: next(line.mode === 'subscription' ? 'sub' : 'pay'),
132
+ user,
133
+ product: line.product,
134
+ state: line.trialDays ? 'trial' : 'active',
135
+ customer: s.customer ?? next('cus'),
136
+ ...(line.plan && { plan: line.plan }),
137
+ ...(line.interval && { interval: line.interval }),
138
+ }
139
+ if (b.interval)
140
+ b.expires = Date.now() + (line.trialDays ? line.trialDays * DAY : PERIOD[b.interval])
141
+ purchases.set(b.id, b)
142
+ await deliver(event(b))
143
+ return b.id
144
+ }
145
+
146
+ function take(sessions: CheckoutRequest[], user?: string) {
147
+ const i = user ? sessions.findLastIndex((s) => s.user === user) : sessions.length - 1
148
+ if (i < 0)
149
+ throw new Error(
150
+ `fakePay: no open checkout${user ? ` for ${user}` : ''}: call \`checkout\` first`,
151
+ )
152
+ return sessions.splice(i, 1)[0]!
153
+ }
154
+
155
+ /** A delivery that says who paid, when the test gave one. */
156
+ const paidBy =
157
+ (deliver: FakePay['deliver'], payer?: Payer): FakePay['deliver'] =>
158
+ (e, o) =>
159
+ deliver({ ...e, ...(payer && { payer }) }, o)
160
+
161
+ /** `fakePay(pay)` with the app's own `definePay`, or `fakePay({ catalog })`. It backs `ctx.entitlements` for this test. */
162
+ export function fakePay(
163
+ app: Pay | (Pick<PayOptions<Product>, 'catalog'> & Partial<PayOptions<Product>>),
164
+ ): FakePay {
165
+ const sessions: CheckoutRequest[] = [],
166
+ deliveries: FakePay['deliveries'] = []
167
+ const purchases = new Map<string, Bought>()
168
+ let seq = 0,
169
+ last: RailEvent | undefined
170
+ const next = (prefix: string) => `${prefix}_${++seq}`
171
+
172
+ const rail = fakeRail(sessions, next, (purchase) => simulate('refund', purchase))
173
+
174
+ const pay: Pay =
175
+ 'webhook' in app
176
+ ? app
177
+ : definePay({ store: memoryPayStore(), urls: { success: '/', cancel: '/' }, ...app })
178
+ pay.use(rail)
179
+ net.extension(pay)
180
+
181
+ const deliver: FakePay['deliver'] = (event, options) => {
182
+ if (!options?.forged) last = event
183
+ return post(pay, deliveries, event, options?.forged ? 'not-the-key' : SECRET)
184
+ }
185
+
186
+ const event = (b: Bought): RailEvent => ({
187
+ id: next('evt'),
188
+ at: Date.now(),
189
+ purchase: b.id,
190
+ state: b.state,
191
+ user: b.user,
192
+ product: b.product,
193
+ ...(b.plan && { plan: b.plan }),
194
+ customer: b.customer,
195
+ ...(b.expires !== undefined && { expires: b.expires }),
196
+ })
197
+
198
+ async function simulate(what: PayScenario, id?: string) {
199
+ const b = id ? purchases.get(id) : [...purchases.values()].at(-1)
200
+ if (!b) throw new Error(`fakePay: no purchase${id ? ` \`${id}\`` : ' yet'} to ${what}`)
201
+ if (what === 'renewal' || what === 'renewal-failed') {
202
+ if (!b.interval)
203
+ throw new Error(`fakePay: \`${b.id}\` is one payment: only a subscription renews`)
204
+ if (clock.installed) await clock.advance(Math.max(0, b.expires! - Date.now()))
205
+ }
206
+ if (what === 'renewal')
207
+ Object.assign(b, { state: 'active', expires: b.expires! + PERIOD[b.interval!] })
208
+ else b.state = TERMS[what]
209
+ await deliver(event(b))
210
+ }
211
+
212
+ return {
213
+ pay,
214
+ rail,
215
+ sessions,
216
+ deliveries,
217
+ deliver,
218
+ simulate,
219
+ complete: (user, payer) =>
220
+ open(take(sessions, user), purchases, next, paidBy(deliver, payer), event),
221
+ abandon: (user) => void take(sessions, user),
222
+ async buy(user, product, plan) {
223
+ await pay.checkout(
224
+ { user: { id: user }, request: { url: 'http://localhost/' } },
225
+ { product, ...(plan && { plan }) },
226
+ )
227
+ return open(take(sessions, user), purchases, next, deliver, event)
228
+ },
229
+ redeliver() {
230
+ if (!last) throw new Error('fakePay: nothing delivered yet')
231
+ return post(pay, deliveries, last, SECRET)
232
+ },
233
+ entitlements: (user) => pay.entitlements(user).list(),
234
+ purchases: (user) => pay.purchases(user),
235
+ }
236
+ }
237
+
238
+ /** One requirement of a suite, and how the rail did. */
239
+ export interface Check {
240
+ name: string
241
+ ok: boolean
242
+ detail: string
243
+ }
244
+
245
+ /** What `payRailSuite` needs: the rail, and a way to make a delivery it would accept. */
246
+ export interface PayRailSuiteOptions {
247
+ rail: PayRail
248
+ /** A delivery the rail would accept, `age` ms old, for a purchase event. Omit `age` for one just sent. */
249
+ delivery: (age?: number) => { body: string; headers: Headers }
250
+ /** How old a delivery may be before a rail refuses it as a replay. Without it the replay check isn't run. */
251
+ tolerance?: number
252
+ }
253
+
254
+ /** One Check per requirement of `pay.rail@1`, against whatever `fetch` the rail was given. Any `ok: false` is P119. */
255
+ export async function payRailSuite({
256
+ rail,
257
+ delivery,
258
+ tolerance,
259
+ }: PayRailSuiteOptions): Promise<Check[]> {
260
+ const out: Check[] = []
261
+ const check = (name: string, ok: boolean, detail = '') => void out.push({ name, ok, detail })
262
+ const refused = async (d: { body: string; headers: Headers }) => {
263
+ try {
264
+ await rail.verify(d)
265
+ return false
266
+ } catch (e) {
267
+ return (e as { code?: string } | null)?.code === 'PAY011'
268
+ }
269
+ }
270
+ const good = delivery()
271
+ const events = await rail.verify(good)
272
+ const e = events[0]
273
+ check('a genuine delivery verifies', events.length > 0, `${events.length} events`)
274
+ check(
275
+ 'an event has an id, a time in ms and a purchase',
276
+ !!e && typeof e.id === 'string' && e.id !== '' && e.at > 1e11 && typeof e.purchase === 'string',
277
+ JSON.stringify(e),
278
+ )
279
+ check(
280
+ 'the same delivery gives the same id, so a repeat is a no-op',
281
+ (await rail.verify(good))[0]?.id === e?.id,
282
+ )
283
+ check(
284
+ 'a changed byte is refused',
285
+ await refused({ body: `${good.body} `, headers: good.headers }),
286
+ )
287
+ check('no signature is refused', await refused({ body: good.body, headers: new Headers() }))
288
+ if (tolerance)
289
+ check('an old delivery is refused as a replay', await refused(delivery(tolerance + 60_000)))
290
+ const subscriptions = rail.modes?.includes('subscription') ?? true
291
+ const line = subscriptions
292
+ ? ({
293
+ product: 'pro',
294
+ name: 'Pro',
295
+ amount: 999,
296
+ currency: 'usd',
297
+ mode: 'subscription',
298
+ plan: 'month',
299
+ interval: 'month',
300
+ quantity: 1,
301
+ } as const)
302
+ : ({
303
+ product: 'pie',
304
+ name: 'Pie',
305
+ amount: 2400,
306
+ currency: 'usd',
307
+ mode: 'payment',
308
+ quantity: 1,
309
+ } as const)
310
+ const { url } = await rail.checkout({
311
+ user: 'u1',
312
+ line,
313
+ successUrl: 'https://app.test/ok',
314
+ cancelUrl: 'https://app.test/no',
315
+ idempotencyKey: 'k1',
316
+ })
317
+ check('`checkout` answers an absolute URL', /^https?:\/\//.test(url), url)
318
+ if (subscriptions) {
319
+ const portal = await rail.portal({ customer: 'c1', returnUrl: 'https://app.test/account' })
320
+ check('`portal` answers an absolute URL', /^https?:\/\//.test(portal.url), portal.url)
321
+ }
322
+ return out
323
+ }
@@ -0,0 +1,10 @@
1
+ import type { PluginInstance } from '@kerf-js/core/plugin'
2
+
3
+ declare const plugin: (options?: {
4
+ prices?: Record<string, string>
5
+ api?: string
6
+ apiVersion?: string
7
+ tolerance?: number
8
+ }) => PluginInstance<unknown>
9
+ /** `stripe()` for `kerf.config.ts`: Stripe as a `pay.rail` provider. Keys stay in the environment. */
10
+ export default plugin
@@ -0,0 +1,41 @@
1
+ // stripe() for kerf.config.ts: this package as the `pay.rail` provider for the web. Options are in the generated slot
2
+ // module, so they name env vars and never hold a key (PAY003). Another provider is this one line swapped for another.
3
+ import { definePlugin, defineSlot, provide } from '@kerf-js/core/plugin'
4
+
5
+ const slot = defineSlot({
6
+ id: 'pay.rail',
7
+ version: 1,
8
+ cardinality: 'keyed',
9
+ sides: ['server', 'client', 'native'],
10
+ })
11
+
12
+ export const stripe = definePlugin({
13
+ name: '@kerf-js/pay/stripe',
14
+ version: '0.0.0',
15
+ kerf: '*',
16
+ permissions: {
17
+ net: ['api.stripe.com'],
18
+ env: ['STRIPE_SECRET_KEY', 'STRIPE_WEBHOOK_SECRET', 'STRIPE_MODE', 'STRIPE_PUBLISHABLE_KEY'],
19
+ },
20
+ contribute: (options) => ({
21
+ provides: [
22
+ provide(slot, {
23
+ key: 'stripe',
24
+ sides: { server: { module: '@kerf-js/pay/stripe', export: 'stripeRail', options } },
25
+ }),
26
+ ],
27
+ agents: {
28
+ title: 'Pay rail: Stripe',
29
+ text: 'Stripe Checkout, server side only: `STRIPE_SECRET_KEY`, and `STRIPE_WEBHOOK_SECRET` for `/_kerf/x/pay/stripe`, the webhook URL to give Stripe. Test mode is an `sk_test_` key; `STRIPE_MODE=test` makes a live key an error (PAY032). Test card 4242 4242 4242 4242; `stripe listen --forward-to localhost:5173/_kerf/x/pay/stripe` for local webhooks.',
30
+ },
31
+ map: [
32
+ {
33
+ want: 'Change the payment provider',
34
+ call: 'replace this plugin in `plugins`: app code stays',
35
+ have: 'Stripe Checkout',
36
+ },
37
+ ],
38
+ }),
39
+ })
40
+
41
+ export default stripe