@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/payer.ts ADDED
@@ -0,0 +1,71 @@
1
+ // Who paid, read off a rail's payment: for an app matching a buyer to its own customers. Every field is optional, and
2
+ // a field the rail left empty is left out.
3
+ import type { Payer } from './index'
4
+
5
+ type Maybe<T> = T | null | undefined
6
+ type Card = NonNullable<Payer['card']>
7
+
8
+ /** A payer holding only what the rail knew, or undefined when it knew nothing. */
9
+ export function payerFrom(p: {
10
+ email?: Maybe<string>
11
+ name?: Maybe<string>
12
+ phone?: Maybe<string>
13
+ card?: Maybe<{ [K in keyof Card]?: Maybe<Card[K]> }>
14
+ }): Payer | undefined {
15
+ const card: Card = {}
16
+ for (const [k, v] of Object.entries(p.card ?? {})) if (v) Object.assign(card, { [k]: v })
17
+ const out: Payer = {}
18
+ if (p.email) out.email = p.email
19
+ if (p.name) out.name = p.name
20
+ if (p.phone) out.phone = p.phone
21
+ if (Object.keys(card).length) out.card = card
22
+ return Object.keys(out).length ? out : undefined
23
+ }
24
+
25
+ interface StripeCharge {
26
+ billing_details?: { email?: string | null; name?: string | null; phone?: string | null } | null
27
+ payment_method_details?: {
28
+ card?: {
29
+ fingerprint?: string
30
+ brand?: string
31
+ last4?: string
32
+ exp_month?: number
33
+ exp_year?: number
34
+ } | null
35
+ } | null
36
+ }
37
+
38
+ /** A paid Checkout session's payer: its customer details, then the card off the payment's charge. A failed read leaves
39
+ * the card out rather than the event: the order is paid either way. */
40
+ export async function stripePayer(
41
+ details:
42
+ | { email?: string | null; name?: string | null; phone?: string | null }
43
+ | null
44
+ | undefined,
45
+ intent: string,
46
+ get: (path: string) => Promise<unknown>,
47
+ ): Promise<Payer | undefined> {
48
+ let charge: StripeCharge | null = null
49
+ try {
50
+ const pi = (await get(
51
+ `/v1/payment_intents/${encodeURIComponent(intent)}?expand[]=latest_charge`,
52
+ )) as { latest_charge?: StripeCharge | string | null } | null
53
+ if (pi && typeof pi.latest_charge === 'object') charge = pi.latest_charge
54
+ } catch {
55
+ // the card is a nicety; the payment is the fact
56
+ }
57
+ const b = charge?.billing_details
58
+ const c = charge?.payment_method_details?.card
59
+ return payerFrom({
60
+ email: details?.email ?? b?.email,
61
+ name: details?.name ?? b?.name,
62
+ phone: details?.phone ?? b?.phone,
63
+ card: c && {
64
+ fingerprint: c.fingerprint,
65
+ brand: c.brand,
66
+ last4: c.last4,
67
+ expMonth: c.exp_month,
68
+ expYear: c.exp_year,
69
+ },
70
+ })
71
+ }
@@ -0,0 +1,80 @@
1
+ import { PayError, type CheckoutLine, type Interval, type Plan, type Product } from '../index'
2
+ import type { CheckoutInput, Pay } from '../server'
3
+
4
+ const issue = (message: string) => ({ issues: [{ message }] })
5
+
6
+ /** Resolve a checkout line from the catalog. */
7
+ export function lineOf<P extends Product>(
8
+ byId: Map<string, P>,
9
+ input: CheckoutInput<P>,
10
+ ): CheckoutLine {
11
+ const p = byId.get(input.product)
12
+ if (!p) throw new PayError('PAY021', `no product \`${input.product}\``, 404)
13
+ const subscription = p.kind === 'subscription'
14
+ const name = subscription ? (input.plan ?? Object.keys(p.plans!)[0]) : undefined
15
+ const row: Plan | undefined = subscription ? p.plans![name as keyof typeof p.plans] : p.price
16
+ if (!row) throw new PayError('PAY021', `\`${p.id}\` has no plan \`${input.plan}\``, 404)
17
+ const currency =
18
+ input.currency ?? Object.keys(row).find((k) => k !== 'trialDays' && k !== 'interval')!
19
+ const amount = row[currency]
20
+ if (typeof amount !== 'number')
21
+ throw new PayError('PAY021', `\`${p.id}\` has no ${currency} price`, 404)
22
+ return {
23
+ product: p.id,
24
+ name: p.name ?? p.id,
25
+ amount,
26
+ currency,
27
+ mode: subscription ? 'subscription' : 'payment',
28
+ quantity: subscription ? 1 : (input.quantity ?? 1),
29
+ ...(subscription
30
+ ? {
31
+ plan: name!,
32
+ interval: (row.interval ?? name) as Interval,
33
+ ...(row.trialDays ? { trialDays: row.trialDays } : {}),
34
+ }
35
+ : {}),
36
+ ...(p.shipping ? { shipping: true } : {}),
37
+ }
38
+ }
39
+
40
+ /** Validate checkout input against this catalog. */
41
+ export function checkoutInput<P extends Product>(byId: Map<string, P>): Pay<P>['input'] {
42
+ return {
43
+ '~standard': {
44
+ version: 1,
45
+ vendor: 'kerf',
46
+ validate(v: unknown) {
47
+ const { product, plan, currency, quantity } = (
48
+ v && typeof v === 'object' ? v : {}
49
+ ) as Partial<Record<keyof CheckoutInput, unknown>>
50
+ if (typeof product !== 'string') return issue('`product` is required')
51
+ const p = byId.get(product)
52
+ if (!p) return issue(`no product \`${product}\``)
53
+ if (plan !== undefined && (typeof plan !== 'string' || !p.plans || !(plan in p.plans)))
54
+ return issue(
55
+ `\`${p.id}\` has no plan \`${typeof plan === 'string' ? plan : JSON.stringify(plan)}\``,
56
+ )
57
+ if (currency !== undefined && typeof currency !== 'string')
58
+ return issue('`currency` is a string')
59
+ if (
60
+ quantity !== undefined &&
61
+ !(
62
+ typeof quantity === 'number' &&
63
+ Number.isInteger(quantity) &&
64
+ quantity > 0 &&
65
+ quantity < 1000
66
+ )
67
+ )
68
+ return issue('`quantity` is a whole number under 1000')
69
+ return {
70
+ value: {
71
+ product,
72
+ ...(plan !== undefined && { plan }),
73
+ ...(currency !== undefined && { currency }),
74
+ ...(quantity !== undefined && { quantity }),
75
+ },
76
+ }
77
+ },
78
+ },
79
+ }
80
+ }
@@ -0,0 +1,89 @@
1
+ import {
2
+ entitlementTag,
3
+ orderTag,
4
+ type Product,
5
+ type PurchaseState,
6
+ type RailEvent,
7
+ } from '../index'
8
+ import type { Entitlements, OrderHook, PayReport, PayStore, Purchase } from '../server'
9
+
10
+ const ACCESS: ReadonlySet<PurchaseState> = new Set(['active', 'trial', 'grace'])
11
+ const FINAL: ReadonlySet<PurchaseState> = new Set(['refunded', 'revoked'])
12
+ /** The product id every `pay.order` is recorded under; its plan is the app's order ref. */
13
+ export const ORDER = 'order'
14
+
15
+ /** Derive access and apply verified events against one store. */
16
+ export function makeLedger<P extends Product>(
17
+ store: PayStore,
18
+ byId: Map<string, P>,
19
+ leeway: number,
20
+ onOrder?: OrderHook,
21
+ ) {
22
+ const live = (p: Purchase) =>
23
+ ACCESS.has(p.state) && (p.expires === null || Date.now() < p.expires + leeway)
24
+
25
+ async function granted(user: string) {
26
+ const out = new Set<string>()
27
+ for (const p of await store.byUser(user))
28
+ if (live(p)) for (const g of byId.get(p.product!)?.grants ?? []) out.add(g)
29
+ return [...out].sort()
30
+ }
31
+
32
+ const entitlements = (user: string | null | undefined): Entitlements => {
33
+ let list: Promise<string[]> | undefined
34
+ const read = () => (list ??= user ? granted(user) : Promise.resolve([]))
35
+ return { has: (id) => read().then((l) => l.includes(id)), list: read }
36
+ }
37
+
38
+ /** One event onto its purchase. Identity always merges; state moves only forward on the rail's clock. */
39
+ async function apply(rail: string, e: RailEvent, report?: PayReport): Promise<string[]> {
40
+ const id = `${rail}:${e.purchase}`
41
+ const had = await store.purchase(id)
42
+ const newer =
43
+ !had || e.at > had.at || (e.at === had.at && (!FINAL.has(had.state) || FINAL.has(e.state)))
44
+ const next: Purchase = {
45
+ id,
46
+ rail,
47
+ user: had?.user ?? e.user ?? null,
48
+ product: had?.product ?? e.product ?? null,
49
+ plan: e.plan ?? had?.plan ?? null,
50
+ customer: e.customer ?? had?.customer ?? null,
51
+ state: newer ? e.state : had.state,
52
+ at: newer ? e.at : had.at,
53
+ expires: newer ? (e.expires ?? had?.expires ?? null) : had.expires,
54
+ }
55
+ await store.save(next)
56
+ // An order (`pay.order`) grants nothing: the app hears its state, before the event is marked, so a throw redelivers.
57
+ if (next.product === ORDER && next.plan) {
58
+ if (newer && had?.state !== next.state)
59
+ await onOrder?.({
60
+ ref: next.plan,
61
+ state: next.state,
62
+ purchase: next,
63
+ ...(e.payer && { payer: e.payer }),
64
+ })
65
+ return ['orders', orderTag(next.plan)]
66
+ }
67
+ if (next.product && !byId.has(next.product))
68
+ report?.({
69
+ code: 'PAY021',
70
+ severity: 'warning',
71
+ message: `purchase \`${id}\` is for \`${next.product}\`, which isn't in the catalog: it grants nothing`,
72
+ })
73
+ return next.user ? [entitlementTag(next.user)] : []
74
+ }
75
+
76
+ async function ingest(rail: string, events: RailEvent[], report?: PayReport) {
77
+ const tags = new Set<string>()
78
+ for (const e of events) {
79
+ const key = `${rail}:${e.id}`
80
+ if (await store.seen(key)) continue
81
+ const poked = await apply(rail, e, report)
82
+ await store.mark(key, e.at)
83
+ for (const t of poked) tags.add(t)
84
+ }
85
+ return [...tags]
86
+ }
87
+
88
+ return { live, entitlements, ingest }
89
+ }
@@ -0,0 +1,215 @@
1
+ import { PayError, type CheckoutLine, type PayRail, type Product, type RailEvent } from '../index'
2
+ import type {
3
+ CheckoutInput,
4
+ OrderInput,
5
+ PayContext,
6
+ PayOptions,
7
+ PayReport,
8
+ PayStore,
9
+ Purchase,
10
+ } from '../server'
11
+ import { lineOf } from './catalog'
12
+ import { ORDER } from './ledger'
13
+
14
+ const BODY = 1 << 20
15
+ const hex = async (s: string) =>
16
+ [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s)))]
17
+ .map((b) => b.toString(16).padStart(2, '0'))
18
+ .join('')
19
+ const errorMessage = (e: unknown) => String((e as Error | null)?.message ?? e)
20
+
21
+ type Services<P extends Product> = {
22
+ options: PayOptions<P>
23
+ urls: PayOptions<P>['urls']
24
+ userOf: (ctx: PayContext) => string | null | undefined
25
+ store: PayStore
26
+ railFor: (key?: string) => Promise<PayRail>
27
+ live: (purchase: Purchase) => boolean
28
+ byId: Map<string, P>
29
+ }
30
+
31
+ /** Create the checkout operation for this pay instance. */
32
+ export function checkoutFor<P extends Product>({
33
+ options,
34
+ urls,
35
+ userOf,
36
+ store,
37
+ railFor,
38
+ live,
39
+ byId,
40
+ }: Services<P>) {
41
+ async function checkout(ctx: PayContext, input: CheckoutInput<P>) {
42
+ const user = userOf(ctx)
43
+ if (!user)
44
+ throw new PayError(
45
+ 'PAY010',
46
+ 'Sign in before buying: a purchase has to belong to someone',
47
+ 401,
48
+ )
49
+ const line = lineOf(byId, input)
50
+ const rail = await railFor()
51
+ const mine = await store.byUser(user)
52
+ if (line.mode === 'subscription' && mine.some((p) => p.product === line.product && live(p)))
53
+ throw new PayError('PAY023', `You already have \`${line.product}\``, 409)
54
+ const origin = options.origin ?? new URL(ctx.request.url).origin
55
+ const customer = mine.find((p) => p.customer && p.rail === rail.id)?.customer ?? undefined
56
+ const idempotencyKey = await hex(JSON.stringify([user, line, Math.floor(Date.now() / 60_000)]))
57
+ const { url } = await rail.checkout({
58
+ user,
59
+ ...(customer && { customer }),
60
+ line,
61
+ successUrl: new URL(urls.success, origin).href,
62
+ cancelUrl: new URL(urls.cancel, origin).href,
63
+ idempotencyKey,
64
+ })
65
+ return url
66
+ }
67
+ return checkout
68
+ }
69
+
70
+ /** Create the portal operation for this pay instance. */
71
+ export function portalFor<P extends Product>({
72
+ options,
73
+ urls,
74
+ userOf,
75
+ store,
76
+ railFor,
77
+ }: Services<P>) {
78
+ async function portal(ctx: PayContext) {
79
+ const user = userOf(ctx)
80
+ if (!user) throw new PayError('PAY010', 'Sign in first', 401)
81
+ const rail = await railFor()
82
+ const customer = (await store.byUser(user)).find(
83
+ (p) => p.customer && p.rail === rail.id,
84
+ )?.customer
85
+ if (!customer)
86
+ throw new PayError('PAY024', 'Nothing to manage yet: this user has bought nothing here', 404)
87
+ const origin = options.origin ?? new URL(ctx.request.url).origin
88
+ return (
89
+ await rail.portal({ customer, returnUrl: new URL(urls.portal ?? urls.cancel, origin).href })
90
+ ).url
91
+ }
92
+ return portal
93
+ }
94
+
95
+ /** Create the verified delivery operation for this pay instance. */
96
+ export function webhookFor(
97
+ railFor: (key?: string) => Promise<PayRail>,
98
+ ingest: (rail: string, events: RailEvent[], report?: PayReport) => Promise<string[]>,
99
+ ) {
100
+ async function webhook(key: string, request: Request, report?: PayReport) {
101
+ const plain = (body: string, status: number) => ({
102
+ response: new Response(body, { status, headers: { 'content-type': 'text/plain' } }),
103
+ tags: [],
104
+ })
105
+ if (request.method !== 'POST') return plain('Method not allowed', 405)
106
+ let rail: PayRail
107
+ try {
108
+ rail = await railFor(key)
109
+ } catch {
110
+ return plain('Not found', 404)
111
+ }
112
+ if (Number(request.headers.get('content-length') ?? 0) > BODY) return plain('Too large', 413)
113
+ const body = await request.text() // the exact bytes: a parsed and re-encoded body can't be verified
114
+ if (body.length > BODY) return plain('Too large', 413)
115
+ let events: RailEvent[]
116
+ try {
117
+ events = await rail.verify({ body, headers: request.headers })
118
+ } catch (e) {
119
+ // A retry can't fix this one, and the reason stays in the log: a forger learns nothing.
120
+ report?.({
121
+ code: (e as { code?: string } | null)?.code ?? 'PAY011',
122
+ severity: 'error',
123
+ message: `a ${key} webhook failed verification: ${errorMessage(e)}`,
124
+ })
125
+ return plain('Bad signature', 400)
126
+ }
127
+ try {
128
+ return {
129
+ response: new Response('{"received":true}', {
130
+ headers: { 'content-type': 'application/json' },
131
+ }),
132
+ tags: await ingest(rail.id, events, report),
133
+ }
134
+ } catch (e) {
135
+ report?.({
136
+ code: 'E_PAY',
137
+ severity: 'error',
138
+ message: `a ${key} webhook failed, and it will be redelivered: ${errorMessage(e)}`,
139
+ })
140
+ return plain('Try again', 500)
141
+ }
142
+ }
143
+ return webhook
144
+ }
145
+
146
+ const REF = /^[A-Za-z0-9_-]{1,64}$/
147
+
148
+ /** Check an order's lines, which the app priced on the server, and sum them into the ledger's one line. */
149
+ export function orderLines(input: OrderInput): { line: CheckoutLine; lines: CheckoutLine[] } {
150
+ const { ref, currency = 'usd' } = input
151
+ if (!REF.test(ref))
152
+ throw new PayError(
153
+ 'PAY021',
154
+ `order ref \`${ref}\` must be 1–64 letters, digits, \`-\` or \`_\``,
155
+ )
156
+ if (!/^[a-z]{3}$/.test(currency))
157
+ throw new PayError('PAY008', `\`${currency}\` isn't a lowercase ISO currency`)
158
+ if (!input.lines.length || input.lines.length > 100)
159
+ throw new PayError('PAY021', `order \`${ref}\` needs 1 to 100 lines`)
160
+ const lines = input.lines.map((l): CheckoutLine => {
161
+ const quantity = l.quantity ?? 1
162
+ if (!Number.isSafeInteger(l.amount) || l.amount < 0)
163
+ throw new PayError(
164
+ 'PAY008',
165
+ `\`${l.name}\`: ${l.amount} isn't whole minor units (999 is $9.99)`,
166
+ )
167
+ if (!Number.isInteger(quantity) || quantity < 1 || quantity > 999)
168
+ throw new PayError('PAY021', `\`${l.name}\`: quantity ${quantity} is out of range`)
169
+ return {
170
+ product: ORDER,
171
+ plan: ref,
172
+ name: l.name.slice(0, 250),
173
+ amount: l.amount,
174
+ currency,
175
+ mode: 'payment',
176
+ quantity,
177
+ }
178
+ })
179
+ const total = lines.reduce((sum, l) => sum + l.amount * l.quantity, 0)
180
+ if (total <= 0) throw new PayError('PAY021', `order \`${ref}\` totals nothing`)
181
+ return {
182
+ line: {
183
+ product: ORDER,
184
+ plan: ref,
185
+ name: input.title ?? `Order ${ref}`,
186
+ amount: total,
187
+ currency,
188
+ mode: 'payment',
189
+ quantity: 1,
190
+ },
191
+ lines,
192
+ }
193
+ }
194
+
195
+ /** Create the order operation: one payment for lines the app priced, signed in or not. */
196
+ export function orderFor<P extends Product>({ options, urls, userOf, railFor }: Services<P>) {
197
+ async function order(ctx: PayContext, input: OrderInput) {
198
+ const { line, lines } = orderLines(input)
199
+ const rail = await railFor()
200
+ const origin = options.origin ?? new URL(ctx.request.url).origin
201
+ const back = (path: string) => new URL(path.replaceAll('{ref}', input.ref), origin).href
202
+ const { url } = await rail.checkout({
203
+ user: userOf(ctx) ?? `guest:${input.ref}`,
204
+ line,
205
+ lines,
206
+ ...(input.email && { email: input.email }),
207
+ successUrl: back(urls.order ?? urls.success),
208
+ cancelUrl: back(urls.orderCancel ?? urls.cancel),
209
+ // One session per order: paying twice for the same ref can't happen from a double click.
210
+ idempotencyKey: await hex(JSON.stringify(['order', input.ref, line.amount])),
211
+ })
212
+ return url
213
+ }
214
+ return order
215
+ }
@@ -0,0 +1,45 @@
1
+ import { PayError, type PayRail, type Product } from '../index'
2
+ import type { PayOptions } from '../server'
3
+
4
+ /** Keep one override and provider cache for this pay instance. */
5
+ export function makeRails<P extends Product>(
6
+ options: PayOptions<P>,
7
+ slot: () => Promise<{
8
+ load: (key: string) => Promise<unknown>
9
+ providers?: Record<string, unknown>
10
+ }>,
11
+ ) {
12
+ let override: PayRail | undefined
13
+ const rails = new Map<string, Promise<PayRail>>()
14
+
15
+ async function railFor(key?: string): Promise<PayRail> {
16
+ if (override) return override
17
+ const { load, providers = {} } = await slot()
18
+ const bound = Object.keys(providers).filter((k) => providers[k])
19
+ if (!bound.length)
20
+ throw new PayError(
21
+ 'P101',
22
+ '`pay.rail` has no provider: add one to `plugins` in kerf.config.ts',
23
+ 500,
24
+ )
25
+ const pick = key ?? options.rail ?? (bound.length === 1 ? bound[0] : undefined)
26
+ if (!pick || !bound.includes(pick))
27
+ throw new PayError(
28
+ 'PAY022',
29
+ pick
30
+ ? `no rail \`${pick}\` is bound (${bound.join(', ')})`
31
+ : `${bound.join(' and ')} are both bound: set \`rail\` in \`definePay\``,
32
+ 500,
33
+ )
34
+ let r = rails.get(pick)
35
+ if (!r) rails.set(pick, (r = load(pick) as Promise<PayRail>))
36
+ return r
37
+ }
38
+
39
+ return {
40
+ railFor,
41
+ use: (rail: PayRail | undefined) => {
42
+ override = rail
43
+ },
44
+ }
45
+ }