@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/checks.mjs ADDED
@@ -0,0 +1,379 @@
1
+ import { configChecks } from './checks/config.mjs'
2
+ // TypeScript is loaded here, not in plugin.mjs, so a config load doesn't pay for it. A regex decides which files parse.
3
+ // The client is everything in `src` that isn't a server module. `src/pay/catalog.ts` is client code on purpose: it holds
4
+ // names and amounts, which is why a rail's ids don't go there (PAY012).
5
+
6
+ import ts from 'typescript'
7
+
8
+ const isServer = (rel) => rel.startsWith('src/server/') || /\.server\.[cm]?[jt]sx?$/.test(rel)
9
+
10
+ const KEY = /\b(?:(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{6,}|whsec_[A-Za-z0-9]{6,})\b/g
11
+ const PLACEHOLDER = /placeholder|example|your|xxxx/i
12
+ const SERVER_ENV =
13
+ /\b(?:process\.env|import\.meta\.env)\.\w*STRIPE_(?:SECRET_KEY|WEBHOOK_SECRET|RESTRICTED_KEY)\b/g
14
+ const RAIL_ID = /^(?:price|prod|plink)_[A-Za-z0-9]{8,}$/
15
+ const STRIPE_EVENT =
16
+ /['"`](?:checkout\.session\.completed|customer\.subscription\.\w+|invoice\.paid|invoice\.payment_\w+|payment_intent\.succeeded|charge\.refunded)['"`]/
17
+ const VERIFIED = /constructEvent|verifyWebhook|\.webhook\(|\.verify\(|stripe-signature/i
18
+ const SECRET_OPTION = /\bstripe\(\s*\{[^}]*\b(?:secretKey|webhookSecret)\b/
19
+ const PAID_NAME = /pro\b|paid|premium|entitle|purchas|subscri|unlock|grant|isPro|hasAccess/i
20
+ const MONEY = /[$€£¥]\s?\d/
21
+
22
+ const parse = (rel, text) =>
23
+ ts.createSourceFile(
24
+ rel,
25
+ text,
26
+ ts.ScriptTarget.Latest,
27
+ true,
28
+ /\.[jt]sx$/.test(rel) ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
29
+ )
30
+
31
+ function walk(node, visit) {
32
+ visit(node)
33
+ ts.forEachChild(node, (c) => walk(c, visit))
34
+ }
35
+
36
+ const at = (sf, rel, node) => ({ file: rel, start: node.getStart(sf), end: node.getEnd() })
37
+ const spanOf = (rel, index, length) => ({ file: rel, start: index, end: index + length })
38
+ const isTest = (rel) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(rel) || rel.startsWith('test/')
39
+ const prop = (object, name) => object.properties.find((p) => p.name?.getText() === name)
40
+ const callee = (node) => (ts.isCallExpression(node) ? node.expression.getText() : '')
41
+ const isFunction = (n) =>
42
+ ts.isArrowFunction(n) ||
43
+ ts.isFunctionExpression(n) ||
44
+ ts.isFunctionDeclaration(n) ||
45
+ ts.isMethodDeclaration(n)
46
+
47
+ function enclosing(node) {
48
+ for (let n = node.parent; n; n = n.parent) if (isFunction(n)) return n
49
+ return undefined
50
+ }
51
+
52
+ /** PAY003: a key in the source, or a server secret read where the client can reach it. */
53
+ function secrets(rel, text, server, out) {
54
+ for (const m of text.matchAll(KEY)) {
55
+ if (PLACEHOLDER.test(m[0])) continue
56
+ out.push({
57
+ code: 'PAY003',
58
+ ...spanOf(rel, m.index, m[0].length),
59
+ why: `A key is in the source: \`${m[0].slice(0, 8)}…\`. Anyone who can read this can charge or refund as you, and it stays in git after you delete it.`,
60
+ })
61
+ }
62
+ if (!server)
63
+ for (const m of text.matchAll(SERVER_ENV))
64
+ out.push({
65
+ code: 'PAY003',
66
+ ...spanOf(rel, m.index, m[0].length),
67
+ why: `\`${m[0]}\` is read in client code: a build inlines it, or it is undefined there.`,
68
+ })
69
+ }
70
+
71
+ /** PAY012: a rail's own id where the client bundle gets it. */
72
+ function railIds(rel, sf, out) {
73
+ walk(sf, (n) => {
74
+ if ((ts.isStringLiteral(n) || ts.isNoSubstitutionTemplateLiteral(n)) && RAIL_ID.test(n.text))
75
+ out.push({
76
+ code: 'PAY012',
77
+ ...at(sf, rel, n),
78
+ why: `\`${n.text}\` is a rail's id in client code: the page now names a rail, and a client that sends a price picks its own.`,
79
+ })
80
+ })
81
+ }
82
+
83
+ /** PAY008: a float or a bare number in `product({ … })`, with the integer as an edit for two-decimal currencies. */
84
+ function money(rel, sf, out) {
85
+ const amounts = (object, path) => {
86
+ for (const p of object.properties) {
87
+ if (!ts.isPropertyAssignment(p) || !/^[a-z]{3}$/.test(p.name.getText())) continue
88
+ const v = p.initializer
89
+ if (!ts.isNumericLiteral(v) || Number.isInteger(Number(v.text))) continue
90
+ const fixed = String(Math.round(Number(v.text) * 100))
91
+ const place = at(sf, rel, v)
92
+ out.push({
93
+ code: 'PAY008',
94
+ ...place,
95
+ why: `\`${path}.${p.name.getText()}\` is ${v.text}: money is whole minor units, and a float rounds differently on each rail.`,
96
+ fix: {
97
+ description: `Write ${fixed}, assuming a currency with two decimals`,
98
+ safe: false,
99
+ edits: [{ start: place.start, end: place.end, text: fixed }],
100
+ },
101
+ })
102
+ }
103
+ }
104
+ walk(sf, (n) => {
105
+ if (callee(n) !== 'product' || !n.arguments[0] || !ts.isObjectLiteralExpression(n.arguments[0]))
106
+ return
107
+ const def = n.arguments[0]
108
+ const id = prop(def, 'id')?.initializer?.text ?? 'product'
109
+ const price = prop(def, 'price')?.initializer
110
+ if (price && ts.isNumericLiteral(price))
111
+ out.push({
112
+ code: 'PAY008',
113
+ ...at(sf, rel, price),
114
+ why: `\`${id}\`'s price has no currency: ${price.text} of what?`,
115
+ })
116
+ if (price && ts.isObjectLiteralExpression(price)) amounts(price, `${id}.price`)
117
+ const plans = prop(def, 'plans')?.initializer
118
+ if (plans && ts.isObjectLiteralExpression(plans))
119
+ for (const p of plans.properties)
120
+ if (ts.isPropertyAssignment(p) && ts.isObjectLiteralExpression(p.initializer))
121
+ amounts(p.initializer, `${id}.${p.name.getText()}`)
122
+ })
123
+ }
124
+
125
+ /** PAY004: paid state written on the client on the strength of `checkout()` returning. */
126
+ function clientGrants(rel, sf, out) {
127
+ const writes = (scope, from) => {
128
+ walk(scope, (n) => {
129
+ if (n.getStart(sf) < from) return
130
+ const target =
131
+ ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.EqualsToken
132
+ ? n.left.getText()
133
+ : ts.isCallExpression(n) && /(^|\.)(setItem|set)$/.test(callee(n))
134
+ ? `${callee(n)} ${n.arguments[0]?.getText() ?? ''}`
135
+ : undefined
136
+ if (target && PAID_NAME.test(target))
137
+ out.push({
138
+ code: 'PAY004',
139
+ ...at(sf, rel, n),
140
+ why: `\`${n.getText().slice(0, 60)}\` follows \`checkout()\`, which only opens the rail's page. Nobody has paid yet, and a refund would never undo this.`,
141
+ })
142
+ })
143
+ }
144
+ walk(sf, (n) => {
145
+ if (callee(n) !== 'checkout') return
146
+ const up = n.parent
147
+ if (ts.isAwaitExpression(up)) {
148
+ const fn = enclosing(n)
149
+ if (fn?.body) writes(fn.body, n.getEnd())
150
+ }
151
+ if (
152
+ ts.isPropertyAccessExpression(up) &&
153
+ up.name.text === 'then' &&
154
+ ts.isCallExpression(up.parent) &&
155
+ up.parent.arguments[0]
156
+ )
157
+ writes(up.parent.arguments[0], 0)
158
+ })
159
+ }
160
+
161
+ /** PAY005: a price typed into the page beside something sold. */
162
+ function hardcoded(rel, sf, out) {
163
+ walk(sf, (n) => {
164
+ if (ts.isJsxText(n) && MONEY.test(n.text))
165
+ out.push({
166
+ code: 'PAY005',
167
+ ...at(sf, rel, n),
168
+ why: `\`${n.text.trim().slice(0, 40)}\` is a price typed by hand: it drifts from what \`checkout\` charges.`,
169
+ })
170
+ })
171
+ }
172
+
173
+ /** PAY015: `ctx.entitlements.has()` used as if it were a boolean. A promise is truthy, so this lets everyone in. */
174
+ function unawaited(rel, sf, out) {
175
+ walk(sf, (n) => {
176
+ if (!/(^|\.)entitlements\.has$/.test(callee(n))) return
177
+ const up = n.parent
178
+ const tested =
179
+ (ts.isIfStatement(up) && up.expression === n) ||
180
+ (ts.isConditionalExpression(up) && up.condition === n) ||
181
+ (ts.isPrefixUnaryExpression(up) && up.operator === ts.SyntaxKind.ExclamationToken) ||
182
+ (ts.isBinaryExpression(up) &&
183
+ [ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken].includes(
184
+ up.operatorToken.kind,
185
+ ))
186
+ if (!tested) return
187
+ const place = at(sf, rel, n)
188
+ const fn = enclosing(n)
189
+ const async = fn?.modifiers?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword)
190
+ const edit = async && {
191
+ fix: {
192
+ description: 'Await it',
193
+ safe: true,
194
+ edits: [{ start: place.start, end: place.start, text: 'await ' }],
195
+ },
196
+ }
197
+ out.push({
198
+ code: 'PAY015',
199
+ ...place,
200
+ why: `\`${n.getText()}\` isn't awaited: it is a promise, which is always truthy, so the check passes for everyone.`,
201
+ ...edit,
202
+ })
203
+ })
204
+ }
205
+
206
+ /** PAY010: a buyer no one has signed in. */
207
+ function anonymous(rel, sf, out) {
208
+ walk(sf, (n) => {
209
+ if (
210
+ callee(n) !== 'mutation' ||
211
+ !n.arguments[0] ||
212
+ !ts.isObjectLiteralExpression(n.arguments[0])
213
+ )
214
+ return
215
+ const def = n.arguments[0]
216
+ if (/\.checkout\(\s*ctx\b/.test(def.getText()) && !prop(def, 'auth'))
217
+ out.push({
218
+ code: 'PAY010',
219
+ ...at(sf, rel, n),
220
+ why: "This mutation opens a checkout with no `auth: 'user'`: a purchase with no owner can't be restored or granted.",
221
+ })
222
+ })
223
+ }
224
+
225
+ /** PAY011: a webhook that believes what it's sent. */
226
+ function webhooks(rel, text, sf, out) {
227
+ if (STRIPE_EVENT.test(text) && /\.json\(\)|JSON\.parse/.test(text) && !VERIFIED.test(text)) {
228
+ const m = STRIPE_EVENT.exec(text)
229
+ out.push({
230
+ code: 'PAY011',
231
+ ...spanOf(rel, m.index, m[0].length),
232
+ why: `This handles ${m[0]} without checking a signature: anyone who finds the URL can POST themselves a purchase.`,
233
+ })
234
+ }
235
+ if (!/\bPayRail\b/.test(text)) return
236
+ walk(sf, (n) => {
237
+ if (
238
+ !((ts.isMethodDeclaration(n) || ts.isPropertyAssignment(n)) && n.name.getText() === 'verify')
239
+ )
240
+ return
241
+ const fn = ts.isPropertyAssignment(n) ? n.initializer : n
242
+ if (!/\bheaders\b/.test(fn.getText()))
243
+ out.push({
244
+ code: 'PAY011',
245
+ ...at(sf, rel, n.name),
246
+ why: "This rail's `verify` never reads `headers`, so it can't be checking a signature.",
247
+ })
248
+ })
249
+ }
250
+
251
+ /** Every id the server really enforces: `requires` and awaited `entitlements.has`, in server modules and route `load`s. */
252
+ function enforced(rel, sf, ids) {
253
+ walk(sf, (n) => {
254
+ if (/(^|\.)entitlements\.has$/.test(callee(n)) && n.arguments[0]?.text)
255
+ ids.add(n.arguments[0].text)
256
+ if (
257
+ ts.isPropertyAssignment(n) &&
258
+ n.name.getText() === 'requires' &&
259
+ ts.isArrayLiteralExpression(n.initializer)
260
+ )
261
+ for (const e of n.initializer.elements) if (e.text) ids.add(e.text)
262
+ })
263
+ }
264
+
265
+ /** Client reads of `entitlements`: `mine.value?.includes('pro')`, wherever the file got that list from. */
266
+ function clientReads(rel, sf, reads) {
267
+ if (!/\bentitlements\b/.test(sf.text)) return
268
+ walk(sf, (n) => {
269
+ if (
270
+ !ts.isCallExpression(n) ||
271
+ !/\.(includes|has)$/.test(n.expression.getText()) ||
272
+ !n.arguments[0]?.text
273
+ )
274
+ return
275
+ reads.push({ rel, sf, node: n, id: n.arguments[0].text })
276
+ })
277
+ }
278
+
279
+ /** A server entry in the client graph: it would carry the ledger, and it can't run there. */
280
+ function serverImports(rel, text, out) {
281
+ for (const m of text.matchAll(/from\s+['"](@kerf-js\/pay\/(?:server|drizzle))['"]/g))
282
+ out.push({
283
+ code: 'PAY017',
284
+ ...spanOf(rel, m.index, m[0].length),
285
+ why: `\`${m[1]}\` is imported in client code: the ledger runs on the server only.`,
286
+ })
287
+ }
288
+
289
+ function unmatchedReads(reads, known, out) {
290
+ for (const r of reads) {
291
+ if (known.has(r.id)) continue
292
+ out.push({
293
+ code: 'PAY013',
294
+ ...at(r.sf, r.rel, r.node),
295
+ why: `\`${r.id}\` is checked only on the client: no \`requires\` or \`ctx.entitlements.has\` on the server names it, so a request made by hand gets the same thing as a paying user.`,
296
+ help: `Add \`requires: ['${r.id}']\` to the query or mutation it protects, or check \`await ctx.entitlements.has('${r.id}')\` in the route's \`load\``,
297
+ })
298
+ }
299
+ }
300
+
301
+ /** @param {import('@kerf-js/core/plugin').CheckContext} ctx */
302
+ export function run(ctx) {
303
+ const out = []
304
+ const rels = ctx.files.filter((r) => r.startsWith('src/') && !isTest(r) && !r.endsWith('.d.ts'))
305
+ const rails = Object.entries(ctx.slots['pay.rail'] ?? {}).filter(([, name]) => name)
306
+ const payFile = ['ts', 'mts', 'js', 'mjs']
307
+ .map((x) => `src/pay.server.${x}`)
308
+ .find((rel) => ctx.exists(rel))
309
+ const known = new Set()
310
+ const reads = []
311
+
312
+ for (const rel of rels) {
313
+ const text = ctx.read(rel)
314
+ const server = isServer(rel)
315
+ secrets(rel, text, server, out)
316
+ if (!server) serverImports(rel, text, out)
317
+ if (
318
+ !(
319
+ /@kerf-js\/pay|entitlements|requires:|\bcheckout\b|\bproduct\(|PayRail|price_|prod_|plink_/.test(
320
+ text,
321
+ ) || STRIPE_EVENT.test(text)
322
+ )
323
+ )
324
+ continue
325
+ const sf = parse(rel, text)
326
+ webhooks(rel, text, sf, out)
327
+ money(rel, sf, out)
328
+ unawaited(rel, sf, out)
329
+ enforced(rel, sf, known)
330
+ if (server) anonymous(rel, sf, out)
331
+ else {
332
+ railIds(rel, sf, out)
333
+ if (/\bcheckout\b/.test(text)) {
334
+ clientGrants(rel, sf, out)
335
+ hardcoded(rel, sf, out)
336
+ }
337
+ clientReads(rel, sf, reads)
338
+ }
339
+ }
340
+
341
+ unmatchedReads(reads, known, out)
342
+
343
+ configChecks({ ctx, out, secrets, spanOf, isTest, SECRET_OPTION })
344
+
345
+ const config = ctx.files.find((r) => r.startsWith('kerf.config.')) ?? 'kerf.config.ts'
346
+ if (!payFile) {
347
+ out.push({
348
+ code: 'PAY014',
349
+ file: config,
350
+ why: 'This plugin is in `plugins`, but there is no `src/pay.server.ts`: no webhook is mounted, so a payment would grant nothing.',
351
+ })
352
+ return out
353
+ }
354
+ if (!rails.length)
355
+ out.push({
356
+ code: 'PAY018',
357
+ file: payFile,
358
+ why: '`src/pay.server.ts` needs a `pay.rail` provider, and nothing provides it: every checkout fails.',
359
+ })
360
+ const text = ctx.read(payFile)
361
+ const m = /memoryPayStore\(/.exec(text)
362
+ if (m)
363
+ out.push({
364
+ code: 'PAY016',
365
+ ...spanOf(payFile, m.index, m[0].length - 1),
366
+ why: 'The ledger is in memory: purchases are gone on restart, and a production server refuses to start with it.',
367
+ })
368
+ if (rails.some(([key]) => key === 'stripe')) {
369
+ const env = ['.env.example', 'src/env.server.ts'].map((rel) => ctx.read(rel)).join('\n')
370
+ if (!env.includes('STRIPE_WEBHOOK_SECRET'))
371
+ out.push({
372
+ code: 'PAY011',
373
+ file: payFile,
374
+ why: 'Nothing declares `STRIPE_WEBHOOK_SECRET`. Without it the rail refuses every webhook, so no purchase ever lands.',
375
+ help: 'Add `STRIPE_WEBHOOK_SECRET` to `.env.example` and `src/env.server.ts`',
376
+ })
377
+ }
378
+ return out
379
+ }
package/src/drizzle.ts ADDED
@@ -0,0 +1,57 @@
1
+ import { eq, getTableName, type AnyColumn, type SQL, type Table } from 'drizzle-orm'
2
+ import type { DbHandle } from '@kerf-js/start/db/core'
3
+ import type { PayStore, Purchase } from './server'
4
+
5
+ /** A Drizzle client as far as the ledger uses one: the dialects' builders share no type, so this names what they have in common. */
6
+ interface LedgerClient {
7
+ select(fields?: Record<string, AnyColumn>): {
8
+ from(table: Table): {
9
+ where(on: SQL | undefined): Promise<Purchase[]> & { limit(n: number): Promise<Purchase[]> }
10
+ }
11
+ }
12
+ insert(table: Table): {
13
+ values(row: object): Promise<unknown> & {
14
+ onDuplicateKeyUpdate(update: { set: object }): Promise<unknown>
15
+ onConflictDoNothing(): Promise<unknown>
16
+ onConflictDoUpdate(update: { target: AnyColumn; set: object }): Promise<unknown>
17
+ }
18
+ }
19
+ }
20
+
21
+ /** A `PayStore` on the app's Drizzle tables, on Postgres, SQLite or MySQL. */
22
+ export function drizzlePayStore(
23
+ db: { $kerf: DbHandle },
24
+ tables: {
25
+ purchases: Table & { id: AnyColumn; user: AnyColumn }
26
+ payEvents: Table & { id: AnyColumn }
27
+ },
28
+ ): PayStore {
29
+ const { purchases, payEvents } = tables
30
+ const client = db as unknown as LedgerClient
31
+ const mysql = db.$kerf.dialect === 'mysql'
32
+ db.$kerf.exempt.add(getTableName(purchases)).add(getTableName(payEvents)) // written by a webhook, not by a server function
33
+ return {
34
+ seen: async (id) =>
35
+ (
36
+ await client
37
+ .select({ id: payEvents.id })
38
+ .from(payEvents)
39
+ .where(eq(payEvents.id, id))
40
+ .limit(1)
41
+ ).length > 0,
42
+ async mark(id, at) {
43
+ const insert = client.insert(payEvents).values({ id, at })
44
+ await (mysql ? insert.onDuplicateKeyUpdate({ set: { id } }) : insert.onConflictDoNothing())
45
+ },
46
+ purchase: async (id) =>
47
+ (await client.select().from(purchases).where(eq(purchases.id, id)).limit(1))[0] ?? null,
48
+ async save(row: Purchase) {
49
+ const { id: _id, ...set } = row
50
+ const insert = client.insert(purchases).values(row)
51
+ await (mysql
52
+ ? insert.onDuplicateKeyUpdate({ set })
53
+ : insert.onConflictDoUpdate({ target: purchases.id, set }))
54
+ },
55
+ byUser: (user) => client.select().from(purchases).where(eq(purchases.user, user)),
56
+ }
57
+ }
package/src/index.ts ADDED
@@ -0,0 +1,265 @@
1
+ // `checkout()` never grants anything: the grant arrives from a verified rail event.
2
+
3
+ /** How a product is paid for: a subscription renews, a one-time purchase stays, a consumable is used up. */
4
+ export type ProductKind = 'subscription' | 'one-time' | 'consumable'
5
+ /** What the buyer gets: app stores care, and `physical` goods ship. */
6
+ export type ProductUse = 'digital' | 'physical' | 'service'
7
+ /** How often a subscription bills. */
8
+ export type Interval = 'day' | 'week' | 'month' | 'year'
9
+
10
+ /** Minor units per ISO currency: `{ usd: 999 }` is $9.99. Integers, always (PAY008). */
11
+ export type Amounts = Record<string, number>
12
+
13
+ /** A subscription's billing option: `Amounts`, with an optional trial and an interval when the plan's name isn't one. */
14
+ export interface Plan {
15
+ [currency: string]: unknown
16
+ trialDays?: number
17
+ interval?: Interval
18
+ }
19
+
20
+ /** What `product()` takes. `G` is the entitlements it grants and `P` the names of its plans. */
21
+ export interface ProductDef<G extends string = string, P extends string = string> {
22
+ id: string
23
+ kind: ProductKind
24
+ use: ProductUse
25
+ /** Display name at checkout. Default: the id. */
26
+ name?: string
27
+ /** A subscription's billing options: `{ month: { usd: 999 }, year: { usd: 7999, trialDays: 7 } }`. */
28
+ plans?: Record<P, Plan>
29
+ /** A one-time or consumable product's price. */
30
+ price?: Amounts
31
+ /** The entitlements a live purchase of this product gives. */
32
+ grants?: readonly G[]
33
+ /** One-time and physical goods: collect an address. */
34
+ shipping?: boolean
35
+ }
36
+
37
+ /** A checked, frozen product, as `product()` returns it. */
38
+ export interface Product<G extends string = string, P extends string = string> extends ProductDef<
39
+ G,
40
+ P
41
+ > {
42
+ readonly grants: readonly G[]
43
+ }
44
+
45
+ const INTERVALS: readonly string[] = ['day', 'week', 'month', 'year']
46
+ const META = new Set(['trialDays', 'interval'])
47
+
48
+ /** Thrown with a stable `code`. `answer` is the shape @kerf-js/start sends any plugin's error to the client in. */
49
+ export class PayError extends Error {
50
+ override name = 'PayError'
51
+ constructor(
52
+ readonly code: string,
53
+ message: string,
54
+ readonly status = 400,
55
+ ) {
56
+ super(message)
57
+ }
58
+ get answer() {
59
+ return { code: this.code, message: this.message, status: this.status }
60
+ }
61
+ }
62
+
63
+ const amounts = (p: object) => Object.entries(p).filter(([k]) => !META.has(k)) as [string, number][]
64
+
65
+ function checkAmounts(id: string, list: [string, unknown][]) {
66
+ if (!list.length)
67
+ throw new PayError(
68
+ 'PAY008',
69
+ `\`${id}\` has no amount: give one in minor units with its currency, like \`{ usd: 999 }\``,
70
+ )
71
+ for (const [currency, n] of list) {
72
+ if (!/^[a-z]{3}$/.test(currency))
73
+ throw new PayError('PAY008', `\`${id}\`: \`${currency}\` isn't a lowercase ISO currency`)
74
+ if (!Number.isSafeInteger(n) || (n as number) < 0)
75
+ throw new PayError(
76
+ 'PAY008',
77
+ `\`${id}\`: ${currency} ${String(n)} isn't whole minor units (999 is $9.99)`,
78
+ )
79
+ }
80
+ }
81
+
82
+ /** One thing you sell. The only place products are defined, and safe in the client graph: it holds no rail's ids. */
83
+ export function product<const G extends string = never, const P extends string = never>(
84
+ def: ProductDef<G, P>,
85
+ ): Product<G, P> {
86
+ const { id, kind, plans, price: amount } = def
87
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(id))
88
+ throw new PayError(
89
+ 'PAY021',
90
+ `product id \`${id}\` must be lowercase letters, digits and dashes`,
91
+ )
92
+ if (kind === 'subscription') {
93
+ if (!plans || !Object.keys(plans).length)
94
+ throw new PayError('PAY021', `subscription \`${id}\` has no \`plans\``)
95
+ if (amount)
96
+ throw new PayError('PAY021', `subscription \`${id}\` is priced per plan: drop \`price\``)
97
+ for (const [name, p] of Object.entries<Plan>(plans)) {
98
+ checkAmounts(`${id}.${name}`, amounts(p))
99
+ if (intervalOf(name, p) === null)
100
+ throw new PayError(
101
+ 'PAY021',
102
+ `plan \`${id}.${name}\` is no interval: name it \`month\` or \`year\`, or add \`interval\``,
103
+ )
104
+ }
105
+ } else {
106
+ if (plans)
107
+ throw new PayError(
108
+ 'PAY021',
109
+ `\`${id}\` is ${kind}: \`plans\` are for subscriptions, so use \`price\``,
110
+ )
111
+ checkAmounts(id, Object.entries(amount ?? {}))
112
+ }
113
+ return Object.freeze({ ...def, grants: Object.freeze([...(def.grants ?? [])]) })
114
+ }
115
+
116
+ const intervalOf = (name: string, p: Plan): Interval | null =>
117
+ p.interval ?? (INTERVALS.includes(name) ? (name as Interval) : null)
118
+
119
+ /** One figure to show a buyer, as `price()` returns it. */
120
+ export interface Price {
121
+ amount: number
122
+ currency: string
123
+ /** Formatted for the reader's locale: `$9.99`. */
124
+ display: string
125
+ plan?: string
126
+ interval?: Interval
127
+ trialDays?: number
128
+ }
129
+
130
+ /** The figure in major units, by the currency's own exponent: JPY has none, KWD has three. */
131
+ function formatted(amount: number, currency: string, locale?: string) {
132
+ const f = new Intl.NumberFormat(locale, { style: 'currency', currency: currency.toUpperCase() })
133
+ return f.format(amount / 10 ** (f.resolvedOptions().maximumFractionDigits ?? 2))
134
+ }
135
+
136
+ /** The price of a product or one of its plans. The first currency listed, unless you name one. */
137
+ export function price<P extends string>(
138
+ p: Product<string, P>,
139
+ plan?: P,
140
+ options: { currency?: string; locale?: string } = {},
141
+ ): Price {
142
+ const row: Record<string, unknown> | undefined =
143
+ plan === undefined
144
+ ? (p.price ?? (p.plans && (Object.values(p.plans)[0] as Plan)))
145
+ : p.plans?.[plan]
146
+ const name = plan ?? (p.plans ? Object.keys(p.plans)[0] : undefined)
147
+ if (!row) throw new PayError('PAY021', `\`${p.id}\` has no plan \`${String(plan)}\``)
148
+ const list = amounts(row)
149
+ const pick = options.currency ? list.find(([c]) => c === options.currency) : list[0]
150
+ if (!pick) throw new PayError('PAY021', `\`${p.id}\` has no ${options.currency} price`)
151
+ const [currency, amount] = pick
152
+ const plain = { amount, currency, display: formatted(amount, currency, options.locale) }
153
+ if (!name) return plain
154
+ const meta = row as Plan
155
+ return {
156
+ ...plain,
157
+ plan: name,
158
+ interval: intervalOf(name, meta)!,
159
+ ...(meta.trialDays ? { trialDays: meta.trialDays } : {}),
160
+ }
161
+ }
162
+
163
+ /** What a query reads, tagged so a verified event pokes it: `tags: (_, ctx) => [entitlementTag(ctx.user.id)]`. */
164
+ export const entitlementTag = (user: string) => `entitlements:${user}`
165
+
166
+ /** What a verified event pokes for one order: `tags: (input) => [orderTag(input.ref)]`. Every order also pokes `orders`. */
167
+ export const orderTag = (ref: string) => `order:${ref}`
168
+
169
+ // ---- pay.rail@1 ---------------------------------------------------------------------------------------------------
170
+
171
+ /** What a purchase is doing now, on any rail. */
172
+ export type PurchaseState =
173
+ | 'pending'
174
+ | 'active'
175
+ | 'trial'
176
+ | 'grace'
177
+ | 'billing-retry'
178
+ | 'paused'
179
+ | 'expired'
180
+ | 'refunded'
181
+ | 'revoked'
182
+
183
+ /** One line a rail charges for, from the catalog. It never comes from the client. */
184
+ export interface CheckoutLine {
185
+ product: string
186
+ plan?: string
187
+ name: string
188
+ amount: number
189
+ currency: string
190
+ mode: 'subscription' | 'payment'
191
+ interval?: Interval
192
+ trialDays?: number
193
+ quantity: number
194
+ shipping?: boolean
195
+ }
196
+
197
+ /** What `checkout` asks of a rail: who is buying, what, and where the buyer comes back to. */
198
+ export interface CheckoutRequest {
199
+ /** Who is buying: attached to the rail's records, and read back from its events. */
200
+ user: string
201
+ /** This user's id on the rail, when a purchase gave one. */
202
+ customer?: string
203
+ line: CheckoutLine
204
+ /** An order's own lines, priced on the server (`pay.order`): charged in place of `line`, which sums them. */
205
+ lines?: readonly CheckoutLine[]
206
+ /** A guest's email, for the receipt, when the rail has no customer for them. */
207
+ email?: string
208
+ successUrl: string
209
+ cancelUrl: string
210
+ /** The same click twice gives one session. */
211
+ idempotencyKey: string
212
+ }
213
+
214
+ /** Who paid, as the rail saw it: for matching a buyer to the app's own customers. Every field is optional. */
215
+ export interface Payer {
216
+ email?: string
217
+ name?: string
218
+ phone?: string
219
+ /** The card used. `fingerprint` is the rail's stable id for the card number (the same card gives the same one, never
220
+ * the number itself): what lets an app know a returning card without asking for anything. */
221
+ card?: {
222
+ fingerprint?: string
223
+ brand?: string
224
+ last4?: string
225
+ expMonth?: number
226
+ expYear?: number
227
+ }
228
+ }
229
+
230
+ /** A rail's event, normalised. `checkout` and these are all that a rail and the ledger say to each other. */
231
+ export interface RailEvent {
232
+ /** The rail's own id for the event: what makes a redelivery a no-op. */
233
+ id: string
234
+ /** The rail's own clock, in ms: events arrive out of order, and this orders them. */
235
+ at: number
236
+ /** The rail's id for the purchase: a subscription, a payment. */
237
+ purchase: string
238
+ state: PurchaseState
239
+ /** Set when the rail's event carries them; an event for a purchase nobody knows without them is dropped. */
240
+ user?: string
241
+ product?: string
242
+ plan?: string
243
+ customer?: string
244
+ /** When a paid period ends, in ms. */
245
+ expires?: number
246
+ /** Who paid, when the event says. Never stored in the ledger: it goes to `onOrder` and no further. */
247
+ payer?: Payer
248
+ }
249
+
250
+ /**
251
+ * `pay.rail@1`. A provider implements this and declares it for the `server` side. `verify` is the only way in for an
252
+ * event: it gets the exact bytes received, and throws `PayError('PAY011', …)` for anything it can't prove.
253
+ */
254
+ export interface PayRail {
255
+ readonly id: string
256
+ /** What it can sell. Default both; a rail without `subscription` has no portal to offer. */
257
+ readonly modes?: readonly ('payment' | 'subscription')[]
258
+ checkout(request: CheckoutRequest): Promise<{ url: string }>
259
+ /** Where a buyer manages or cancels. */
260
+ portal(request: { customer: string; returnUrl: string }): Promise<{ url: string }>
261
+ verify(request: { body: string; headers: Headers }): RailEvent[] | Promise<RailEvent[]>
262
+ refund?(request: { purchase: string }): Promise<void>
263
+ /** True in the provider's sandbox (Stripe test mode, Square sandbox); undefined when it can't tell. */
264
+ readonly sandbox?: boolean | undefined
265
+ }