@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/server.ts ADDED
@@ -0,0 +1,283 @@
1
+ // Delivery is at least once, in any order. An event applies by the rail's own clock, so an old one changes nothing and a
2
+ // repeat lands on what it already wrote; `mark` comes last, because a crash before it should redeliver. A failure answers
3
+ // 500 for the same reason. A terminal state wins a tie: a refund and a renewal in the same second is a refund.
4
+
5
+ import type { Context } from '@kerf-js/start'
6
+ import { makeRails } from './server/rails'
7
+ import { makeLedger, ORDER } from './server/ledger'
8
+ import { checkoutInput } from './server/catalog'
9
+ import { checkoutFor, orderFor, portalFor, webhookFor } from './server/operations'
10
+ import type { ServerExtension } from '@kerf-js/start/extension'
11
+ import {
12
+ PayError,
13
+ type Payer,
14
+ type PayRail,
15
+ type Product,
16
+ type PurchaseState,
17
+ type RailEvent,
18
+ } from './index'
19
+
20
+ declare module '@kerf-js/start' {
21
+ interface Context {
22
+ /** What this user holds, from verified rail events. Await it. */
23
+ entitlements: Entitlements
24
+ }
25
+ interface FnOptions {
26
+ /** Entitlements this call needs, on the server: a typed 403 otherwise. */
27
+ requires?: readonly string[]
28
+ }
29
+ }
30
+
31
+ /** One row of the ledger: where a purchase stands now, whatever rail it came through. */
32
+ export interface Purchase {
33
+ /** `<rail>:<rail's id>`. */
34
+ id: string
35
+ rail: string
36
+ /** Null until an event names them: a dispute can arrive before the payment it disputes. */
37
+ user: string | null
38
+ product: string | null
39
+ plan: string | null
40
+ state: PurchaseState
41
+ /** The rail's time of the last event applied. */
42
+ at: number
43
+ expires: number | null
44
+ customer: string | null
45
+ }
46
+
47
+ /** Where the ledger lives. `drizzlePayStore` in `@kerf-js/start/pay/drizzle`, or write these five for any database. */
48
+ export interface PayStore {
49
+ /** Not durable: refused on a production server (PAY016). */
50
+ readonly memory?: boolean
51
+ seen(event: string): Promise<boolean>
52
+ mark(event: string, at: number): Promise<void>
53
+ purchase(id: string): Promise<Purchase | null>
54
+ /** Insert or replace by `id`. */
55
+ save(purchase: Purchase): Promise<void>
56
+ byUser(user: string): Promise<Purchase[]>
57
+ }
58
+
59
+ /** A ledger in memory, for dev and tests: `clear` empties it. */
60
+ export function memoryPayStore(): PayStore & { clear(): void } {
61
+ const events = new Set<string>()
62
+ const rows = new Map<string, Purchase>()
63
+ return {
64
+ memory: true,
65
+ seen: (e) => Promise.resolve(events.has(e)),
66
+ mark(e) {
67
+ events.add(e)
68
+ return Promise.resolve()
69
+ },
70
+ purchase: (id) => Promise.resolve(rows.get(id) ?? null),
71
+ save(p) {
72
+ rows.set(p.id, p)
73
+ return Promise.resolve()
74
+ },
75
+ byUser: (user) => Promise.resolve([...rows.values()].filter((p) => p.user === user)),
76
+ clear() {
77
+ events.clear()
78
+ rows.clear()
79
+ },
80
+ }
81
+ }
82
+
83
+ /** What one user holds, from the ledger and the catalog. */
84
+ export interface Entitlements {
85
+ /** Await it: a promise is always truthy (PAY015). */
86
+ has(id: string): Promise<boolean>
87
+ list(): Promise<string[]>
88
+ }
89
+
90
+ /** What pay reads of `ctx`: the request's URL, and what `user` reads, `user.id` by default. A real `ctx` fits, and so does a test's. */
91
+ export type PayContext = Partial<Omit<Context, 'request'>> & {
92
+ request: { url: string }
93
+ user?: { id?: string | null } | null
94
+ }
95
+
96
+ /** What `definePay` takes. */
97
+ export interface PayOptions<P extends Product> {
98
+ /** `import * as catalog from './pay/catalog'`, or a list. */
99
+ catalog: readonly P[] | Record<string, P>
100
+ store: PayStore
101
+ /** Paths or URLs a buyer comes back to. They never come from the client. `order` and `orderCancel` may hold `{ref}`. */
102
+ urls: { success: string; cancel: string; portal?: string; order?: string; orderCancel?: string }
103
+ /** Hears each state an order (`pay.order`) moves to, from verified events only: mark it paid here. A throw redelivers. */
104
+ onOrder?: OrderHook
105
+ /** Who a request is. Default `ctx.user?.id`. */
106
+ user?: (ctx: PayContext) => string | null | undefined
107
+ /** With several rails bound, the one that takes payments. One rail needs no choosing. */
108
+ rail?: string
109
+ /** The `pay.rail` slot. Default the generated `kerf:slot/pay.rail`, as any consumer of a slot reads it. */
110
+ slot?: () => Promise<{ load(key: string): Promise<unknown>; providers?: Record<string, unknown> }>
111
+ /** Absolute origin for `urls`, behind a proxy. Default the request's. */
112
+ origin?: string
113
+ /** How long past a paid period access lasts, while a late renewal event arrives. Default 3 days. */
114
+ leeway?: number
115
+ }
116
+
117
+ /** The server log: @kerf-js/start passes its own. */
118
+ export type PayReport = (d: { code: string; severity: string; message: string }) => void
119
+
120
+ /** What a client may ask for: names only. The catalog supplies every amount. */
121
+ export interface CheckoutInput<P extends Product = Product> {
122
+ product: P['id']
123
+ plan?: string
124
+ currency?: string
125
+ quantity?: number
126
+ }
127
+
128
+ /** One line of an order, priced by the app on the server: never from the client. */
129
+ export interface OrderLine {
130
+ name: string
131
+ /** Whole minor units, each. */
132
+ amount: number
133
+ quantity?: number
134
+ }
135
+
136
+ /** What `pay.order` takes: the app's own order id and the lines it priced. */
137
+ export interface OrderInput {
138
+ /** The app's order id, 1–64 of `A-Z a-z 0-9 - _`. It comes back in `onOrder` and in `orderTag(ref)`. */
139
+ ref: string
140
+ lines: readonly OrderLine[]
141
+ /** Lowercase ISO. Default `usd`. */
142
+ currency?: string
143
+ /** What the ledger's one line is called. Default `Order <ref>`. */
144
+ title?: string
145
+ /** A guest's email, for the rail's receipt. */
146
+ email?: string
147
+ }
148
+
149
+ /** `onOrder`: an order's new state, and its row in the ledger. */
150
+ export type OrderHook = (order: {
151
+ ref: string
152
+ state: PurchaseState
153
+ purchase: Purchase
154
+ /** Who paid, when the rail says: email, name, phone and the card's brand, last four and fingerprint. */
155
+ payer?: Payer
156
+ }) => Promise<void> | void
157
+
158
+ /** What `definePay` returns: the ledger's calls, and a `server.extension` that carries them to the server. */
159
+ export interface Pay<P extends Product = Product> extends ServerExtension {
160
+ readonly catalog: readonly P[]
161
+ /** For a mutation's `input`: the catalog decides what can be bought, and the client sends only names. */
162
+ readonly input: {
163
+ readonly '~standard': {
164
+ version: 1
165
+ vendor: 'kerf'
166
+ validate(v: unknown): { value: CheckoutInput<P> } | { issues: { message: string }[] }
167
+ types?: { input: CheckoutInput<P>; output: CheckoutInput<P> }
168
+ }
169
+ }
170
+ /** The hosted checkout's URL, for this buyer. Grants nothing. */
171
+ checkout(ctx: PayContext, input: CheckoutInput<P>): Promise<string>
172
+ /** The hosted page for one order the app priced, signed in or a guest. Pays nothing until `onOrder` hears `active`. */
173
+ order(ctx: PayContext, input: OrderInput): Promise<string>
174
+ /** Where this buyer manages or cancels. */
175
+ portal(ctx: PayContext): Promise<string>
176
+ /** Read for a user id, as a webhook or a job would. In a request, `ctx.entitlements`. */
177
+ entitlements(user: string): Entitlements
178
+ /** `ctx.entitlements` for this context. */
179
+ forContext(ctx: PayContext): Entitlements
180
+ purchases(user: string): Promise<Purchase[]>
181
+ /** One verified delivery. `tags` go on to the app's live readers. */
182
+ webhook(
183
+ rail: string,
184
+ request: Request,
185
+ report?: PayReport,
186
+ ): Promise<{ response: Response; tags: string[] }>
187
+ /** Apply events that have been verified. Anything else must go through `webhook`. */
188
+ ingest(rail: string, events: RailEvent[], report?: PayReport): Promise<string[]>
189
+ refund(purchase: string): Promise<void>
190
+ /** Whether the rail takes test payments, for a "test mode" banner. False when it can't tell. */
191
+ sandbox(rail?: string): Promise<boolean>
192
+ /** A rail in place of the slot: `fakePay`. */
193
+ use(rail: PayRail | undefined): void
194
+ /** Back to the slot, with an empty ledger if it can be emptied: `net.extension` calls this after each test. */
195
+ reset(): void
196
+ }
197
+
198
+ const DAY = 86_400_000
199
+
200
+ /** The one ledger of an app: `src/pay.server.ts` default-exports what this returns. */
201
+ export function definePay<P extends Product>(options: PayOptions<P>): Pay<P> {
202
+ const catalog = (
203
+ Array.isArray(options.catalog) ? options.catalog : Object.values(options.catalog)
204
+ ) as P[]
205
+ const byId = new Map(catalog.map((p) => [p.id, p]))
206
+ if (byId.has(ORDER))
207
+ throw new PayError(
208
+ 'PAY021',
209
+ `\`${ORDER}\` is the id \`pay.order\` records under: name the product something else`,
210
+ )
211
+ const { store, urls, leeway = 3 * DAY } = options
212
+ const userOf = options.user ?? ((ctx) => ctx?.user?.id)
213
+ const slot =
214
+ options.slot ??
215
+ (() => {
216
+ // A generated module, declared in .kerf/slots.d.ts only once bound: an expect-error would be wrong in one case or the other.
217
+ // oxlint-disable-next-line typescript/no-unnecessary-type-assertion -- the cast is what lets this compile when the slot isn't declared
218
+ return import('kerf:slot/pay.rail' as string)
219
+ })
220
+ const rails = makeRails(options, slot)
221
+ const { railFor } = rails
222
+
223
+ const { live, entitlements, ingest } = makeLedger(store, byId, leeway, options.onOrder)
224
+
225
+ const pay: Pay<P> = {
226
+ catalog,
227
+ input: checkoutInput(byId),
228
+ checkout: checkoutFor({ options, urls, userOf, store, railFor, live, byId }),
229
+ order: orderFor({ options, urls, userOf, store, railFor, live, byId }),
230
+ portal: portalFor({ options, urls, userOf, store, railFor, live, byId }),
231
+ entitlements,
232
+ forContext: (ctx) => entitlements(userOf(ctx)),
233
+ purchases: (user) => store.byUser(user),
234
+ ingest,
235
+ webhook: webhookFor(railFor, ingest),
236
+ async refund(id) {
237
+ const p = await store.purchase(id)
238
+ if (!p) throw new PayError('PAY024', `no purchase \`${id}\``, 404)
239
+ const rail = await railFor(p.rail)
240
+ if (!rail.refund) throw new PayError('PAY022', `\`${rail.id}\` can't refund from here`, 501)
241
+ await rail.refund({ purchase: id.slice(p.rail.length + 1) })
242
+ },
243
+ async sandbox(key) {
244
+ return (await railFor(key)).sandbox === true
245
+ },
246
+ use(rail) {
247
+ rails.use(rail)
248
+ },
249
+ reset() {
250
+ rails.use(undefined)
251
+ ;(store as { clear?(): void }).clear?.()
252
+ },
253
+
254
+ // ---- what makes this a `server.extension` ---------------------------------------------------------------------
255
+ async handle(request, path, api) {
256
+ const { response, tags } = await pay.webhook(path, request, (d) => api.report(d))
257
+ await api.invalidate(tags)
258
+ return response
259
+ },
260
+ context: (ctx) => ({ entitlements: pay.forContext(ctx) }),
261
+ async guard(fn, ctx) {
262
+ for (const id of (fn.def.requires as readonly string[] | undefined) ?? [])
263
+ if (!(await ctx.entitlements.has(id)))
264
+ throw new PayError('ENTITLEMENT_REQUIRED', `This needs \`${id}\``, 403)
265
+ },
266
+ options: ['requires'],
267
+ personal: ['entitlements'],
268
+ check(dev) {
269
+ if (store.memory && !dev)
270
+ throw new PayError(
271
+ 'PAY016',
272
+ 'The ledger is in memory: every purchase is gone on the next deploy. Pass a durable `store` to `definePay`',
273
+ 500,
274
+ )
275
+ },
276
+ }
277
+ return pay
278
+ }
279
+
280
+ /** The `server.extension` provider: `src/pay.server.ts` already built it, so this hands it over. */
281
+ export const extension = (app: Pay): ServerExtension => app
282
+
283
+ export type { Payer, PayRail, RailEvent } from './index'
package/src/setup.mjs ADDED
@@ -0,0 +1,121 @@
1
+ // What `kerf add pay` writes, as data: `kerf add` does the writing, so a dry run and a refusal come for free. Plain JS
2
+ // strings, because this loads with the config. `run` only describes: the plugin never touches the disk.
3
+
4
+ const PURCHASE = ['user', 'product', 'plan']
5
+
6
+ /** `purchases` and `pay_events`, as `drizzlePayStore` reads them: times in ms, so a 32-bit integer won't do. */
7
+ function tables(engine) {
8
+ const columns = ({ table, id, str, long }) => `export const purchases = ${table}('purchases', {
9
+ id: ${id}.primaryKey(),
10
+ rail: ${str}.notNull(),
11
+ ${PURCHASE.map((c) => ` ${c}: ${str},`).join('\n')}
12
+ state: ${str}.notNull(),
13
+ at: ${long}.notNull(),
14
+ expires: ${long},
15
+ customer: ${str},
16
+ })
17
+
18
+ export const payEvents = ${table}('pay_events', {
19
+ id: ${id}.primaryKey(),
20
+ at: ${long}.notNull(),
21
+ })
22
+ `
23
+ return {
24
+ sqlite: () =>
25
+ `import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'\n\n${columns({ table: 'sqliteTable', id: 'text()', str: 'text()', long: 'integer()' })}`,
26
+ postgres: () =>
27
+ `import { bigint, pgTable, text } from 'drizzle-orm/pg-core'\n\n${columns({ table: 'pgTable', id: 'text()', str: 'text()', long: "bigint({ mode: 'number' })" })}`,
28
+ mysql: () =>
29
+ `import { bigint, mysqlTable, varchar } from 'drizzle-orm/mysql-core'\n\n${columns({ table: 'mysqlTable', id: 'varchar({ length: 191 })', str: 'varchar({ length: 191 })', long: "bigint({ mode: 'number' })" })}`,
30
+ }[engine]()
31
+ }
32
+
33
+ const catalog = `import { product } from '@kerf-js/pay'
34
+
35
+ // What you sell. Amounts are minor units (999 is $9.99), and no rail's ids belong here: this file reaches the client.
36
+ export const pro = product({
37
+ id: 'pro',
38
+ kind: 'subscription',
39
+ use: 'digital',
40
+ name: 'Pro',
41
+ plans: { month: { usd: 999 }, year: { usd: 7999, trialDays: 7 } },
42
+ grants: ['pro'],
43
+ })
44
+ `
45
+
46
+ const ledger = (
47
+ store,
48
+ ) => `${store === 'drizzle' ? "import { drizzlePayStore } from '@kerf-js/pay/drizzle'\nimport { definePay } from '@kerf-js/pay/server'\nimport { db } from '#/db/index.server'\nimport { payEvents, purchases } from '#/db/schema'\n" : "import { definePay, memoryPayStore } from '@kerf-js/pay/server'\n"}import * as catalog from './pay/catalog'
49
+
50
+ // Served at /_kerf/x/pay/<rail>, the webhook URL to give your provider. A verified event is the only grant.
51
+ export default definePay({ catalog, store: ${store === 'drizzle' ? 'drizzlePayStore(db, { purchases, payEvents })' : 'memoryPayStore()'}, urls: { success: '/', cancel: '/' } })
52
+ `
53
+
54
+ const functions = `import { entitlementTag } from '@kerf-js/pay'
55
+ import { mutation, query, redirect } from '@kerf-js/start'
56
+ import pay from '../pay.server'
57
+
58
+ /** What the signed-in user holds, live: a verified event pokes this user's tag. Render from it; enforce with \`requires\`. */
59
+ export const entitlements = query({
60
+ auth: 'user',
61
+ tags: (_, ctx) => [entitlementTag(ctx.user.id)],
62
+ run: ({ ctx }) => ctx.entitlements.list(),
63
+ })
64
+
65
+ /** \`checkout({ product: 'pro', plan: 'month' })\`: on to the rail's page. It grants nothing. */
66
+ export const checkout = mutation({
67
+ auth: 'user',
68
+ input: pay.input,
69
+ run: async ({ input, ctx }) => redirect(await pay.checkout(ctx, input), 303),
70
+ })
71
+
72
+ /** Where a buyer manages or cancels. */
73
+ export const portal = mutation({
74
+ auth: 'user',
75
+ run: async ({ ctx }) => redirect(await pay.portal(ctx), 303),
76
+ })
77
+ `
78
+
79
+ export const setup = {
80
+ with: ['@kerf-js/pay/stripe'],
81
+ needs: ['db', 'auth'],
82
+ run({ engine, layer, read }) {
83
+ const drizzle = layer === 'drizzle'
84
+ const env = read('src/env.server.ts') ?? ''
85
+ if (!env.includes('STRIPE_SECRET_KEY') && !/server: \{\n/.test(env))
86
+ throw new Error('src/env.server.ts has no `server: {` block to add the Stripe keys to')
87
+ return {
88
+ files: {
89
+ 'src/pay/catalog.ts': catalog,
90
+ 'src/pay.server.ts': ledger(drizzle ? 'drizzle' : 'memory'),
91
+ 'src/server/pay.ts': functions,
92
+ ...(drizzle && { 'src/db/pay.schema.ts': tables(engine) }),
93
+ },
94
+ edits: {
95
+ ...(!env.includes('STRIPE_SECRET_KEY') && {
96
+ 'src/env.server.ts': env.replace(
97
+ 'server: {\n',
98
+ 'server: {\n STRIPE_SECRET_KEY: z.string().min(1),\n STRIPE_WEBHOOK_SECRET: z.string().min(1),\n',
99
+ ),
100
+ }),
101
+ ...(drizzle && {
102
+ 'src/db/schema.ts': `${read('src/db/schema.ts').trimEnd()}\n\nexport * from './pay.schema'\n`,
103
+ }),
104
+ },
105
+ env: {
106
+ STRIPE_MODE: 'test',
107
+ STRIPE_SECRET_KEY: 'sk_test_placeholder',
108
+ STRIPE_WEBHOOK_SECRET: 'whsec_placeholder',
109
+ },
110
+ next: [
111
+ ...(drizzle
112
+ ? ['`kerf db generate`, then reload: the migration applies on the next request']
113
+ : [
114
+ '`src/pay.server.ts` starts on `memoryPayStore()`: write a `PayStore` on your data layer (PAY016)',
115
+ ]),
116
+ 'put your real test keys (`sk_test_…`) in .env; `STRIPE_MODE=test` refuses a live key until you switch it to `live` (PAY032)',
117
+ 'locally, `stripe listen --forward-to localhost:5173/_kerf/x/pay/stripe` and put the `whsec_` it prints in .env; deployed, give Stripe the webhook URL /_kerf/x/pay/stripe',
118
+ ],
119
+ }
120
+ },
121
+ }