@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/square.ts ADDED
@@ -0,0 +1,309 @@
1
+ // Square's signature is base64 HMAC-SHA256 of `<notification URL><raw body>` with the subscription's signature key, in
2
+ // `x-square-hmacsha256-signature`. It carries no time, so a replay is stopped by the ledger's event ids. A payment's event
3
+ // doesn't carry the order's metadata, so after the signature checks out the rail reads the order once to learn who and what.
4
+ // Square sells one-time payments here: subscriptions and a customer portal are Stripe's (PAY022).
5
+
6
+ import {
7
+ PayError,
8
+ type CheckoutLine,
9
+ type CheckoutRequest,
10
+ type PayRail,
11
+ type PurchaseState,
12
+ type RailEvent,
13
+ } from './index'
14
+ import { payerFrom } from './payer'
15
+
16
+ /** Options of `squareRail()`. Secrets default to the environment, which is where they belong. */
17
+ export interface SquareOptions {
18
+ /** `sandbox` talks to connect.squareupsandbox.com with a sandbox token. Default `process.env.SQUARE_ENVIRONMENT` (or
19
+ * `SQUARE_ENV`), else production. Any other value is refused (PAY032) rather than read as production. */
20
+ environment?: 'sandbox' | 'production'
21
+ /** Default `process.env.SQUARE_APPLICATION_ID`. Only checked: a `sandbox-sq0idb-…` id says sandbox, `sq0idp-…`
22
+ * production, and one that disagrees with `environment` is PAY032. */
23
+ applicationId?: string
24
+ /** The API's origin: point it at a local mock. Default from `environment`. */
25
+ api?: string
26
+ /** Pinned, so an account's default version can't reshape these calls. */
27
+ apiVersion?: string
28
+ /** Default `process.env.SQUARE_ACCESS_TOKEN`. */
29
+ accessToken?: string
30
+ /** Default `process.env.SQUARE_LOCATION_ID`: the shop the payments land in. */
31
+ locationId?: string
32
+ /** Default `process.env.SQUARE_WEBHOOK_SIGNATURE_KEY`. */
33
+ signatureKey?: string
34
+ /** The exact URL given to Square for the webhook; it's part of what's signed. Default `process.env.SQUARE_WEBHOOK_URL`. */
35
+ notificationUrl?: string
36
+ /** Default the global one. */
37
+ fetch?: typeof fetch
38
+ }
39
+
40
+ interface Money {
41
+ amount?: number
42
+ currency?: string
43
+ }
44
+ interface SquarePayment {
45
+ id: string
46
+ order_id?: string
47
+ status?: string
48
+ updated_at?: string
49
+ created_at?: string
50
+ customer_id?: string
51
+ total_money?: Money
52
+ amount_money?: Money
53
+ refunded_money?: Money
54
+ buyer_email_address?: string
55
+ card_details?: {
56
+ card?: {
57
+ fingerprint?: string
58
+ card_brand?: string
59
+ last_4?: string
60
+ exp_month?: number
61
+ exp_year?: number
62
+ }
63
+ }
64
+ billing_address?: { first_name?: string; last_name?: string }
65
+ }
66
+
67
+ /** Who paid, from the payment itself: Square puts the card on every card payment. */
68
+ const payerOf = (p: SquarePayment) => {
69
+ const c = p.card_details?.card
70
+ return payerFrom({
71
+ email: p.buyer_email_address,
72
+ name: [p.billing_address?.first_name, p.billing_address?.last_name].filter(Boolean).join(' '),
73
+ card: c && {
74
+ fingerprint: c.fingerprint,
75
+ brand: c.card_brand?.toLowerCase(),
76
+ last4: c.last_4,
77
+ expMonth: c.exp_month,
78
+ expYear: c.exp_year,
79
+ },
80
+ })
81
+ }
82
+ interface SquareEvent {
83
+ event_id?: string
84
+ type?: string
85
+ created_at?: string
86
+ data?: { object?: { payment?: SquarePayment } }
87
+ }
88
+
89
+ const PAYMENT: Record<string, PurchaseState> = {
90
+ APPROVED: 'pending',
91
+ PENDING: 'pending',
92
+ COMPLETED: 'active',
93
+ CANCELED: 'expired',
94
+ FAILED: 'expired',
95
+ }
96
+
97
+ const encoder = new TextEncoder()
98
+ const env = (name: string) => (typeof process === 'undefined' ? undefined : process.env[name])
99
+
100
+ async function signatureOk(key: string, text: string, given: string) {
101
+ const k = await crypto.subtle.importKey(
102
+ 'raw',
103
+ encoder.encode(key),
104
+ { name: 'HMAC', hash: 'SHA-256' },
105
+ false,
106
+ ['verify'],
107
+ )
108
+ let bytes: Uint8Array<ArrayBuffer>
109
+ try {
110
+ bytes = Uint8Array.from(atob(given), (c) => c.charCodeAt(0))
111
+ } catch {
112
+ return false
113
+ }
114
+ return crypto.subtle.verify('HMAC', k, bytes, encoder.encode(text))
115
+ }
116
+
117
+ /** One Square payment as a ledger state: a whole refund is final, a part refund keeps what was bought. */
118
+ function stateOf(p: SquarePayment): PurchaseState | null {
119
+ const paid = p.total_money?.amount ?? p.amount_money?.amount ?? 0
120
+ if (p.refunded_money?.amount && paid && p.refunded_money.amount >= paid) return 'refunded'
121
+ return PAYMENT[p.status ?? ''] ?? null
122
+ }
123
+
124
+ /** `true` for the sandbox, after checking the environment's spelling and the application id against it. */
125
+ export function squareSandbox(options: Pick<SquareOptions, 'environment' | 'applicationId'> = {}) {
126
+ const raw = options.environment ?? env('SQUARE_ENVIRONMENT') ?? env('SQUARE_ENV')
127
+ const value = (raw ?? '').trim().toLowerCase()
128
+ if (value && value !== 'sandbox' && value !== 'production')
129
+ throw new PayError(
130
+ 'PAY032',
131
+ `\`SQUARE_ENVIRONMENT\` is \`${raw}\`: set it to \`sandbox\` or \`production\``,
132
+ 500,
133
+ )
134
+ const sandbox = value === 'sandbox'
135
+ const app = options.applicationId ?? env('SQUARE_APPLICATION_ID')
136
+ if (app && app.startsWith('sandbox-') !== sandbox)
137
+ throw new PayError(
138
+ 'PAY032',
139
+ sandbox
140
+ ? '`SQUARE_ENVIRONMENT` is `sandbox` but `SQUARE_APPLICATION_ID` is a production app: take the token and id from the Sandbox tab of the Developer Console'
141
+ : '`SQUARE_APPLICATION_ID` is a sandbox app (`sandbox-…`) but `SQUARE_ENVIRONMENT` is not `sandbox`: set `SQUARE_ENVIRONMENT=sandbox`, or use the production credentials',
142
+ 500,
143
+ )
144
+ return sandbox
145
+ }
146
+
147
+ const SANDBOX_API = 'https://connect.squareupsandbox.com'
148
+ const PRODUCTION_API = 'https://connect.squareup.com'
149
+
150
+ function squareCall(options: SquareOptions, fetcher: typeof fetch) {
151
+ const version = options.apiVersion ?? '2025-10-16'
152
+ return async function call(path: string, body?: unknown) {
153
+ const sandbox = squareSandbox(options)
154
+ const api = options.api ?? (sandbox ? SANDBOX_API : PRODUCTION_API)
155
+ const token = options.accessToken ?? env('SQUARE_ACCESS_TOKEN')
156
+ if (!token) throw new PayError('PAY003', '`SQUARE_ACCESS_TOKEN` is not set on the server', 500)
157
+ if (!options.api && /placeholder/i.test(token))
158
+ throw new PayError(
159
+ 'PAY003',
160
+ '`SQUARE_ACCESS_TOKEN` is still a placeholder: nothing was sent to Square',
161
+ 500,
162
+ )
163
+ const res = await fetcher(`${api}${path}`, {
164
+ method: body === undefined ? 'GET' : 'POST',
165
+ headers: {
166
+ authorization: `Bearer ${token}`,
167
+ 'content-type': 'application/json',
168
+ 'square-version': version,
169
+ },
170
+ ...(body !== undefined && { body: JSON.stringify(body) }),
171
+ })
172
+ const data = (await res.json().catch(() => null)) as Record<string, unknown> | null
173
+ if (!res.ok) {
174
+ const errors = (data?.errors as { detail?: string }[] | undefined) ?? []
175
+ // A token only works on its own host, and Square says no more than UNAUTHORIZED when it's sent to the other one.
176
+ const hint =
177
+ res.status === 401 && !options.api
178
+ ? sandbox
179
+ ? ' (this is the sandbox host: is `SQUARE_ACCESS_TOKEN` the sandbox token, from the Sandbox tab?)'
180
+ : ' (this is the production host: a sandbox token needs `SQUARE_ENVIRONMENT=sandbox`)'
181
+ : ''
182
+ throw new PayError(
183
+ 'PAY030',
184
+ `Square refused ${path}: ${errors[0]?.detail ?? res.status}${hint}`,
185
+ res.status === 429 ? 503 : 502,
186
+ )
187
+ }
188
+ return data ?? {}
189
+ }
190
+ }
191
+
192
+ const upper = (c: string) => c.toUpperCase()
193
+ const lineItem = (l: CheckoutLine) => ({
194
+ name: l.name,
195
+ quantity: String(l.quantity),
196
+ base_price_money: { amount: l.amount, currency: upper(l.currency) },
197
+ })
198
+
199
+ type Call = ReturnType<typeof squareCall>
200
+
201
+ /** One payment link for a checkout's lines, with the metadata its order carries back to `verify`. */
202
+ async function paymentLink(call: Call, options: SquareOptions, request: CheckoutRequest) {
203
+ const { line, user } = request
204
+ if (line.mode !== 'payment')
205
+ throw new PayError(
206
+ 'PAY022',
207
+ 'The Square rail takes one-time payments: sell subscriptions with Stripe',
208
+ 501,
209
+ )
210
+ const location = options.locationId ?? env('SQUARE_LOCATION_ID')
211
+ if (!location) throw new PayError('PAY003', '`SQUARE_LOCATION_ID` is not set on the server', 500)
212
+ const data = (await call('/v2/online-checkout/payment-links', {
213
+ idempotency_key: request.idempotencyKey.slice(0, 45),
214
+ order: {
215
+ location_id: location,
216
+ ...(line.plan && line.product === 'order' && { reference_id: line.plan.slice(0, 40) }),
217
+ line_items: (request.lines ?? [line]).map(lineItem),
218
+ metadata: {
219
+ kerf_user: user.slice(0, 255),
220
+ kerf_product: line.product,
221
+ ...(line.plan && { kerf_plan: line.plan }),
222
+ },
223
+ },
224
+ checkout_options: { redirect_url: request.successUrl },
225
+ ...(request.email && { pre_populated_data: { buyer_email: request.email } }),
226
+ })) as { payment_link?: { url?: string } }
227
+ const url = data.payment_link?.url
228
+ if (typeof url !== 'string')
229
+ throw new PayError('PAY030', 'Square answered a link with no url', 502)
230
+ return { url }
231
+ }
232
+
233
+ /** The Square `pay.rail` provider: hosted payment links and webhooks verified here. One-time payments only. */
234
+ export function squareRail(options: SquareOptions = {}): PayRail {
235
+ const fetcher = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args))
236
+ const call = squareCall(options, fetcher)
237
+
238
+ async function identity(orderId: string) {
239
+ const { order } = (await call(`/v2/orders/${encodeURIComponent(orderId)}`)) as {
240
+ order?: { metadata?: Record<string, string> }
241
+ }
242
+ const m = order?.metadata ?? {}
243
+ return {
244
+ ...(m.kerf_user && { user: m.kerf_user }),
245
+ ...(m.kerf_product && { product: m.kerf_product }),
246
+ ...(m.kerf_plan && { plan: m.kerf_plan }),
247
+ }
248
+ }
249
+
250
+ return {
251
+ id: 'square',
252
+ modes: ['payment'],
253
+ get sandbox() {
254
+ try {
255
+ return squareSandbox(options)
256
+ } catch {
257
+ return undefined // a misspelled environment: every call says so (PAY032)
258
+ }
259
+ },
260
+ checkout: (request) => paymentLink(call, options, request),
261
+ portal() {
262
+ return Promise.reject(
263
+ new PayError('PAY022', 'Square has no customer portal: a buyer manages nothing here', 501),
264
+ )
265
+ },
266
+ async verify({ body, headers }) {
267
+ const key = options.signatureKey ?? env('SQUARE_WEBHOOK_SIGNATURE_KEY')
268
+ const url = options.notificationUrl ?? env('SQUARE_WEBHOOK_URL')
269
+ if (!key || !url)
270
+ throw new PayError(
271
+ 'PAY011',
272
+ '`SQUARE_WEBHOOK_SIGNATURE_KEY` and `SQUARE_WEBHOOK_URL` must both be set: refusing every webhook rather than trusting one',
273
+ )
274
+ const given = headers.get('x-square-hmacsha256-signature') ?? ''
275
+ if (!given || !(await signatureOk(key, url + body, given)))
276
+ throw new PayError('PAY011', 'the signature does not match this body and URL')
277
+ const event = JSON.parse(body) as SquareEvent
278
+ const p = event.data?.object?.payment
279
+ if (!event.event_id || !p?.order_id || !event.type?.startsWith('payment.')) return []
280
+ const state = stateOf(p)
281
+ if (!state) return []
282
+ const at = Date.parse(p.updated_at ?? event.created_at ?? '') || Date.now()
283
+ const out: RailEvent = {
284
+ id: event.event_id,
285
+ at,
286
+ purchase: p.order_id,
287
+ state,
288
+ ...(await identity(p.order_id)),
289
+ ...(p.customer_id && { customer: p.customer_id }),
290
+ }
291
+ const payer = payerOf(p)
292
+ if (payer) out.payer = payer
293
+ return [out]
294
+ },
295
+ async refund({ purchase }) {
296
+ const { order } = (await call(`/v2/orders/${encodeURIComponent(purchase)}`)) as {
297
+ order?: { tenders?: { payment_id?: string }[]; total_money?: Money }
298
+ }
299
+ const payment = order?.tenders?.[0]?.payment_id
300
+ if (!payment || !order?.total_money)
301
+ throw new PayError('PAY024', `order \`${purchase}\` has no payment to refund`, 404)
302
+ await call('/v2/refunds', {
303
+ idempotency_key: `refund-${purchase}`.slice(0, 45),
304
+ payment_id: payment,
305
+ amount_money: order.total_money,
306
+ })
307
+ },
308
+ }
309
+ }