hono-stripe 0.0.0-stage → 1.0.1
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/LICENSE +21 -0
- package/README.md +339 -2
- package/dist/chunk-TV73NTMC.js +77 -0
- package/dist/chunk-TV73NTMC.js.map +1 -0
- package/dist/index.cjs +174 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +109 -0
- package/dist/index.d.ts +109 -0
- package/dist/index.js +99 -0
- package/dist/index.js.map +1 -0
- package/dist/testing.cjs +62 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +59 -0
- package/dist/testing.d.ts +59 -0
- package/dist/testing.js +58 -0
- package/dist/testing.js.map +1 -0
- package/dist/types-D7SNBUi7.d.cts +80 -0
- package/dist/types-D7SNBUi7.d.ts +80 -0
- package/dist/ui.cjs +47 -0
- package/dist/ui.cjs.map +1 -0
- package/dist/ui.d.cts +89 -0
- package/dist/ui.d.ts +89 -0
- package/dist/ui.js +43 -0
- package/dist/ui.js.map +1 -0
- package/dist/webhooks.cjs +196 -0
- package/dist/webhooks.cjs.map +1 -0
- package/dist/webhooks.d.cts +221 -0
- package/dist/webhooks.d.ts +221 -0
- package/dist/webhooks.js +115 -0
- package/dist/webhooks.js.map +1 -0
- package/package.json +105 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hidetaka Okamoto
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,340 @@
|
|
|
1
|
-
#
|
|
1
|
+
# hono-stripe
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> The all-in-one Stripe toolkit for [Hono](https://hono.dev) and HonoX — works on Cloudflare Workers and Node.
|
|
4
|
+
|
|
5
|
+
One install covers the whole server-side Stripe integration:
|
|
6
|
+
|
|
7
|
+
| Module | What you get |
|
|
8
|
+
| -- | -- |
|
|
9
|
+
| `hono-stripe` | Stripe client middleware (`c.var.stripe`), Stripe→HTTP error mapping for `app.onError` |
|
|
10
|
+
| `hono-stripe/webhook` | `stripeWebhook` — verify + **typed per-event routing** + delivery dedupe (in-memory, or your own atomic store) |
|
|
11
|
+
| `hono-stripe/testing` | Real-signature webhook fixtures for tests and local dev — no `stripe listen` required |
|
|
12
|
+
| `hono-stripe/ui` | hono/jsx (HonoX) components that render a working Payment Element form — no React |
|
|
13
|
+
|
|
14
|
+
It handles the edge-runtime gotchas for you (`createFetchHttpClient`, async
|
|
15
|
+
webhook verification via WebCrypto) and keeps `stripe`/`hono` as peer
|
|
16
|
+
dependencies — you bring your own versions.
|
|
17
|
+
|
|
18
|
+
> **Status:** early development (`0.x`). API may change between minor versions.
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
npm install hono-stripe stripe hono
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Quick start
|
|
27
|
+
|
|
28
|
+
### Cloudflare Workers
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { Hono } from 'hono'
|
|
32
|
+
import {
|
|
33
|
+
stripeMiddleware,
|
|
34
|
+
getStripe,
|
|
35
|
+
stripeErrorHandler,
|
|
36
|
+
type StripeEnv,
|
|
37
|
+
} from 'hono-stripe'
|
|
38
|
+
import { stripeWebhook } from 'hono-stripe/webhook'
|
|
39
|
+
|
|
40
|
+
type Bindings = {
|
|
41
|
+
STRIPE_SECRET_KEY: string
|
|
42
|
+
STRIPE_WEBHOOK_SECRET: string
|
|
43
|
+
DB: D1Database // backs the dedupe store — see "Deduplication stores" in the webhooks guide
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const app = new Hono<{ Bindings: Bindings } & StripeEnv>()
|
|
47
|
+
|
|
48
|
+
// Stripe SDK errors → right HTTP statuses (card decline → 402, not 500).
|
|
49
|
+
app.onError(stripeErrorHandler())
|
|
50
|
+
|
|
51
|
+
// Reads STRIPE_SECRET_KEY from the Workers env binding.
|
|
52
|
+
// On Workers, Stripe.createFetchHttpClient() is applied automatically.
|
|
53
|
+
app.use(stripeMiddleware())
|
|
54
|
+
|
|
55
|
+
app.post('/api/payment-intent', async (c) => {
|
|
56
|
+
// Decide the amount on the server (e.g. from a price id / cart lookup),
|
|
57
|
+
// never trust an amount sent by the client.
|
|
58
|
+
const intent = await getStripe(c).paymentIntents.create({ amount: 1400, currency: 'usd' })
|
|
59
|
+
return c.json({ clientSecret: intent.client_secret })
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
// Verify + route + dedupe in one middleware. `event.data.object` is typed
|
|
63
|
+
// per event name — the stripe SDK discriminates events by `type`.
|
|
64
|
+
app.post(
|
|
65
|
+
'/api/webhook',
|
|
66
|
+
stripeWebhook({
|
|
67
|
+
// c.env only exists at request time — resolve the store lazily per request.
|
|
68
|
+
// Your atomic StripeEventStore (D1 example in the webhooks guide).
|
|
69
|
+
dedupe: (c) => d1EventStore(c.env.DB),
|
|
70
|
+
on: {
|
|
71
|
+
'payment_intent.succeeded': (event) => {
|
|
72
|
+
console.log('paid', event.data.object.id) // Stripe.PaymentIntent
|
|
73
|
+
},
|
|
74
|
+
'checkout.session.completed': async (event) => {
|
|
75
|
+
await fulfillOrder(event.data.object) // Stripe.Checkout.Session
|
|
76
|
+
},
|
|
77
|
+
},
|
|
78
|
+
}),
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
export default app
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`.dev.vars` (Workers local dev — **test keys only**, never commit real keys):
|
|
85
|
+
|
|
86
|
+
```
|
|
87
|
+
STRIPE_SECRET_KEY=sk_test_...
|
|
88
|
+
STRIPE_WEBHOOK_SECRET=whsec_...
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### Node
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import { serve } from '@hono/node-server'
|
|
95
|
+
import { Hono } from 'hono'
|
|
96
|
+
import { stripeMiddleware, getStripe, type StripeEnv } from 'hono-stripe'
|
|
97
|
+
|
|
98
|
+
const app = new Hono<StripeEnv>()
|
|
99
|
+
app.use(stripeMiddleware()) // reads process.env.STRIPE_SECRET_KEY
|
|
100
|
+
|
|
101
|
+
app.post('/api/payment-intent', async (c) => {
|
|
102
|
+
const intent = await getStripe(c).paymentIntents.create({ amount: 1400, currency: 'usd' })
|
|
103
|
+
return c.json({ clientSecret: intent.client_secret })
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
serve(app)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Webhooks — `hono-stripe/webhook`
|
|
110
|
+
|
|
111
|
+
`stripeWebhook` composes the three things every Stripe webhook endpoint needs:
|
|
112
|
+
|
|
113
|
+
1. **Verify** — `constructEventAsync` (async WebCrypto, Workers-safe). Missing
|
|
114
|
+
or bad signatures get a `400`, not a `500`, so Stripe doesn't retry
|
|
115
|
+
invalid requests.
|
|
116
|
+
2. **Route** — handlers keyed by event type, with `event.data.object` narrowed
|
|
117
|
+
to the concrete resource type for every event type the SDK knows.
|
|
118
|
+
3. **Dedupe** — Stripe retries deliveries for up to ~3 days. Pass a store to
|
|
119
|
+
acknowledge repeat deliveries without re-running the handler.
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
import { stripeWebhook, memoryEventStore } from 'hono-stripe/webhook'
|
|
123
|
+
|
|
124
|
+
app.post('/webhook', stripeWebhook({
|
|
125
|
+
// Secret resolution order: `secret` (string or (c) => string) →
|
|
126
|
+
// env binding / process.env[webhookSecretVar] (default STRIPE_WEBHOOK_SECRET)
|
|
127
|
+
secret: (c) => c.env.STRIPE_WEBHOOK_SECRET,
|
|
128
|
+
|
|
129
|
+
// memoryEventStore() for dev / single-isolate Node; production needs an
|
|
130
|
+
// atomic store (see "Deduplication stores").
|
|
131
|
+
dedupe: memoryEventStore(),
|
|
132
|
+
|
|
133
|
+
on: {
|
|
134
|
+
'customer.subscription.deleted': async (event, c) => {
|
|
135
|
+
await downgrade(event.data.object.customer)
|
|
136
|
+
},
|
|
137
|
+
},
|
|
138
|
+
|
|
139
|
+
// Optional: override the default 200 for verified-but-unhandled events.
|
|
140
|
+
onUnhandled: (event, c) => c.json({ ignored: event.type }),
|
|
141
|
+
}))
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
The Stripe client for verification comes from `c.var.stripe` when
|
|
145
|
+
`stripeMiddleware()` has run; otherwise `stripeWebhook` builds one from
|
|
146
|
+
`apiKey` / `STRIPE_SECRET_KEY` (verification is local HMAC — no API call).
|
|
147
|
+
|
|
148
|
+
- A handler may `return c.json(...)` / `Response` (sent verbatim) or return
|
|
149
|
+
nothing (`200 { received: true }`).
|
|
150
|
+
- A handler that throws surfaces as a `500` via Hono's error handling, so
|
|
151
|
+
Stripe retries — and since dedupe records only after a successful handler,
|
|
152
|
+
retries are processed normally.
|
|
153
|
+
- `verifyStripeSignature(c, { secret })` remains available from
|
|
154
|
+
`hono-stripe/webhook` as the bare primitive if you want a `switch` instead
|
|
155
|
+
of a router.
|
|
156
|
+
|
|
157
|
+
### `StripeEventStore`
|
|
158
|
+
|
|
159
|
+
Bring your own backend (D1, Upstash, DB) by implementing two methods:
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
interface StripeEventStore {
|
|
163
|
+
claim(eventId: string, ttlSeconds: number): Promise<boolean> // atomic
|
|
164
|
+
release(eventId: string): Promise<void>
|
|
165
|
+
}
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`claim` must be atomic (conditional insert, Durable Object, `SET NX`, …), so
|
|
169
|
+
concurrent deliveries of one event run the handler once; the claim is released
|
|
170
|
+
if the handler throws or returns non-2xx. `memoryEventStore()` is provided for
|
|
171
|
+
dev and single-process use. **Workers KV is eventually consistent and cannot
|
|
172
|
+
provide an atomic claim — do not use it for dedupe.** See the
|
|
173
|
+
[webhooks guide](docs/src/content/docs/guides/webhooks.md) for D1 /
|
|
174
|
+
DynamoDB examples. Default retention is 3 days.
|
|
175
|
+
|
|
176
|
+
## Testing — `hono-stripe/testing`
|
|
177
|
+
|
|
178
|
+
Webhook signatures are just HMAC-SHA256 over `${timestamp}.${payload}`. This
|
|
179
|
+
module produces **real** signatures with WebCrypto, so they verify against the
|
|
180
|
+
actual Stripe SDK on every runtime — run the full verify → route → dedupe path
|
|
181
|
+
in `vitest` without `stripe listen` or network access.
|
|
182
|
+
|
|
183
|
+
```ts
|
|
184
|
+
import { Hono } from 'hono'
|
|
185
|
+
import { stripeWebhook } from 'hono-stripe/webhook'
|
|
186
|
+
import { createTestEvent, createWebhookRequest } from 'hono-stripe/testing'
|
|
187
|
+
|
|
188
|
+
const app = new Hono().post('/webhook', stripeWebhook({
|
|
189
|
+
apiKey: 'sk_test_x',
|
|
190
|
+
secret: 'whsec_test',
|
|
191
|
+
on: { 'payment_intent.succeeded': handler },
|
|
192
|
+
}))
|
|
193
|
+
|
|
194
|
+
const res = await app.request(await createWebhookRequest(
|
|
195
|
+
createTestEvent('payment_intent.succeeded', { id: 'pi_1', amount: 1400 }),
|
|
196
|
+
{ secret: 'whsec_test' },
|
|
197
|
+
))
|
|
198
|
+
expect(res.status).toBe(200)
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
| Export | Purpose |
|
|
202
|
+
| -- | -- |
|
|
203
|
+
| `signStripePayload(payload, secret, timestamp?)` | `t=...,v1=...` header value; backdate `timestamp` to test tolerance handling |
|
|
204
|
+
| `createTestEvent(type, object, options?)` | `Stripe.Event`-shaped fixture around your `data.object` |
|
|
205
|
+
| `createWebhookRequest(event \| payload, { secret, url?, timestamp? })` | `Request` with a valid signature, ready for `app.request()` or `fetch` |
|
|
206
|
+
|
|
207
|
+
## Payment UI — `hono-stripe/ui`
|
|
208
|
+
|
|
209
|
+
Server-render a working [stripe-pwa-elements](https://github.com/stripe/stripe-pwa-elements)
|
|
210
|
+
`<stripe-payment-element>` from hono/jsx or HonoX — no React, no frontend build
|
|
211
|
+
step. The component code loads from a CDN as an ES module.
|
|
212
|
+
|
|
213
|
+
```tsx
|
|
214
|
+
import { StripePaymentForm } from 'hono-stripe/ui'
|
|
215
|
+
|
|
216
|
+
app.get('/', (c) =>
|
|
217
|
+
c.html(<StripePaymentForm
|
|
218
|
+
endpoint="/api/payment-intent" // POST → { clientSecret, publishableKey? }
|
|
219
|
+
publishableKey={c.env.STRIPE_PUBLISHABLE_KEY}
|
|
220
|
+
/>)
|
|
221
|
+
)
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
Two modes:
|
|
225
|
+
|
|
226
|
+
- **`endpoint`**: the browser POSTs to your endpoint and assigns the returned
|
|
227
|
+
`clientSecret` to the element (e.g. a PaymentIntent or Checkout Session
|
|
228
|
+
created via `getStripe(c)` above).
|
|
229
|
+
- **`clientSecret`**: pass a secret created during SSR — rendered as an element
|
|
230
|
+
attribute, no client-side fetch.
|
|
231
|
+
|
|
232
|
+
```tsx
|
|
233
|
+
app.get('/', async (c) => {
|
|
234
|
+
const intent = await getStripe(c).paymentIntents.create({ amount: 1400, currency: 'usd' })
|
|
235
|
+
return c.html(<StripePaymentForm
|
|
236
|
+
clientSecret={intent.client_secret!}
|
|
237
|
+
publishableKey={c.env.STRIPE_PUBLISHABLE_KEY}
|
|
238
|
+
/>)
|
|
239
|
+
})
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
`intent="checkout"` switches to Checkout Session mode
|
|
243
|
+
(`checkout-session-client-secret`). `StripeElementsScript` (the `<script
|
|
244
|
+
type="module">` loader) is rendered automatically; pass `src` to self-host
|
|
245
|
+
instead of using the CDN.
|
|
246
|
+
|
|
247
|
+
## API — `hono-stripe`
|
|
248
|
+
|
|
249
|
+
### `stripeMiddleware(options?)`
|
|
250
|
+
|
|
251
|
+
Initializes a Stripe client and sets it at `c.var.stripe`. The secret key is
|
|
252
|
+
resolved in order:
|
|
253
|
+
|
|
254
|
+
1. `options.apiKey` (explicit)
|
|
255
|
+
2. Workers env binding `c.env[secretKeyVar]`
|
|
256
|
+
3. `process.env[secretKeyVar]`
|
|
257
|
+
|
|
258
|
+
`secretKeyVar` defaults to `STRIPE_SECRET_KEY`. On non-Node runtimes the SDK is
|
|
259
|
+
initialized with `Stripe.createFetchHttpClient()`. Clients are cached per key.
|
|
260
|
+
|
|
261
|
+
| Option | Type | Description |
|
|
262
|
+
| -- | -- | -- |
|
|
263
|
+
| `apiKey` | `string` | Secret key passed directly |
|
|
264
|
+
| `secretKeyVar` | `string` | Env / `process.env` key name (default `STRIPE_SECRET_KEY`) |
|
|
265
|
+
| `apiVersion` | `string` | Stripe API version override |
|
|
266
|
+
| `config` | `Stripe.StripeConfig` | Extra config; an explicit `httpClient` here wins |
|
|
267
|
+
|
|
268
|
+
### `stripeErrorHandler(options?)`
|
|
269
|
+
|
|
270
|
+
A Hono `onError` handler that maps Stripe SDK errors to the right HTTP status
|
|
271
|
+
instead of letting every Stripe failure become a `500`:
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
import { stripeErrorHandler } from 'hono-stripe'
|
|
275
|
+
|
|
276
|
+
app.onError(stripeErrorHandler({ locale: 'ja' })) // 'en' default
|
|
277
|
+
|
|
278
|
+
// or per-request — e.g. follow Accept-Language:
|
|
279
|
+
app.onError(stripeErrorHandler({
|
|
280
|
+
locale: (c) => c.req.header('accept-language')?.startsWith('ja') ? 'ja' : 'en',
|
|
281
|
+
}))
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
Card declines get extra fields your client can render directly —
|
|
285
|
+
`error.userMessage` is the localized "what to do next" text and
|
|
286
|
+
`error.retryable` distinguishes a soft decline (worth retrying, e.g.
|
|
287
|
+
`insufficient_funds`) from a hard one (`fraudulent`, `stolen_card`). Both come
|
|
288
|
+
from [stripe-decline-codes](https://github.com/hideokamoto/stripe-decline-codes).
|
|
289
|
+
|
|
290
|
+
| Stripe error | Status | Notes |
|
|
291
|
+
| -- | -- | -- |
|
|
292
|
+
| `StripeCardError` | 402 | `code` = decline_code, plus `userMessage` (localized via `stripe-decline-codes`) and `retryable` (soft-decline detection) |
|
|
293
|
+
| `StripeInvalidRequestError`, `TemporarySessionExpiredError` | 400 | |
|
|
294
|
+
| `StripeSignatureVerificationError` | 400 | details not leaked |
|
|
295
|
+
| `StripeIdempotencyError` | 409 | |
|
|
296
|
+
| `StripeRateLimitError` | 429 | |
|
|
297
|
+
| `StripeConnectionError`, `StripeAPIError` | 502 | upstream failure — safe to retry |
|
|
298
|
+
| `StripeAuthenticationError`, `StripePermissionError` | 500 | generic message — never leaks key details |
|
|
299
|
+
| Other `StripeError` with 4xx `statusCode` | that status | |
|
|
300
|
+
| Other `StripeError` | 502 | |
|
|
301
|
+
| `HTTPException` | untouched | pass-through |
|
|
302
|
+
| Anything else | 500 | or `options.fallback(err, c)` |
|
|
303
|
+
|
|
304
|
+
### `getStripe(c)`
|
|
305
|
+
|
|
306
|
+
Returns `c.var.stripe`, throwing a clear error if the middleware has not run.
|
|
307
|
+
|
|
308
|
+
### Runtime helpers
|
|
309
|
+
|
|
310
|
+
`isNodeRuntime()`, `isWorkersRuntime()`, `shouldUseFetchHttpClient()` are
|
|
311
|
+
exported for advanced/diagnostic use.
|
|
312
|
+
|
|
313
|
+
## Starter template
|
|
314
|
+
|
|
315
|
+
A runnable full-stack example (Hono + Cloudflare Workers + Payment Element UI,
|
|
316
|
+
with both PaymentIntent and Checkout Session flows) lives in
|
|
317
|
+
[`examples/cloudflare-workers`](./examples/cloudflare-workers). Clone, set your
|
|
318
|
+
test keys, `pnpm dev`.
|
|
319
|
+
|
|
320
|
+
## Documentation
|
|
321
|
+
|
|
322
|
+
The docs site lives in [`docs/`](./docs) (Starlight + TypeDoc, deployed to
|
|
323
|
+
Cloudflare Workers Static Assets). Run it locally with `pnpm -C docs dev`; see
|
|
324
|
+
[`docs/README.md`](./docs/README.md) for build/deploy details.
|
|
325
|
+
|
|
326
|
+
## Bundle size
|
|
327
|
+
|
|
328
|
+
Staying thin is a feature. CI enforces a
|
|
329
|
+
[size-limit](https://github.com/ai/size-limit) budget per entry point
|
|
330
|
+
(`.size-limit.json`) and posts the current sizes to each PR. `stripe`/`hono`
|
|
331
|
+
are peers and are never bundled. The browser-side payment components load from
|
|
332
|
+
a CDN, so they're not in your server bundle either.
|
|
333
|
+
|
|
334
|
+
```sh
|
|
335
|
+
pnpm run size
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
## License
|
|
339
|
+
|
|
340
|
+
MIT
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { getRuntimeKey } from 'hono/adapter';
|
|
2
|
+
import Stripe from 'stripe';
|
|
3
|
+
|
|
4
|
+
// src/context.ts
|
|
5
|
+
var getStripe = (c) => {
|
|
6
|
+
const stripe = c.get("stripe");
|
|
7
|
+
if (!stripe) {
|
|
8
|
+
throw new Error(
|
|
9
|
+
"hono-stripe: Stripe client not found on context. Did you register stripeMiddleware() before this handler?"
|
|
10
|
+
);
|
|
11
|
+
}
|
|
12
|
+
return stripe;
|
|
13
|
+
};
|
|
14
|
+
var isNodeRuntime = () => getRuntimeKey() === "node";
|
|
15
|
+
var isWorkersRuntime = () => getRuntimeKey() === "workerd";
|
|
16
|
+
var shouldUseFetchHttpClient = () => !isNodeRuntime();
|
|
17
|
+
var MAX_CACHE_ENTRIES = 100;
|
|
18
|
+
var clientCache = /* @__PURE__ */ new Map();
|
|
19
|
+
var optionsTokens = /* @__PURE__ */ new WeakMap();
|
|
20
|
+
var optionsTokenSeq = 0;
|
|
21
|
+
var cryptoProvider;
|
|
22
|
+
var buildConfig = (options) => {
|
|
23
|
+
const config = { ...options.config };
|
|
24
|
+
if (options.apiVersion) {
|
|
25
|
+
config.apiVersion = options.apiVersion;
|
|
26
|
+
}
|
|
27
|
+
if (!config.httpClient && shouldUseFetchHttpClient()) {
|
|
28
|
+
config.httpClient = Stripe.createFetchHttpClient();
|
|
29
|
+
}
|
|
30
|
+
return config;
|
|
31
|
+
};
|
|
32
|
+
var hasNonSerializableConfig = (config) => {
|
|
33
|
+
if (config.httpClient !== void 0) return true;
|
|
34
|
+
return Object.values(config).some((value) => typeof value === "function");
|
|
35
|
+
};
|
|
36
|
+
var computeOptionsToken = (options) => {
|
|
37
|
+
const { apiVersion, config } = options;
|
|
38
|
+
if (config && hasNonSerializableConfig(config)) {
|
|
39
|
+
return `#${++optionsTokenSeq}`;
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
return JSON.stringify({ apiVersion, config });
|
|
43
|
+
} catch {
|
|
44
|
+
return `#${++optionsTokenSeq}`;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
var getCacheKey = (apiKey, options) => {
|
|
48
|
+
let token = optionsTokens.get(options);
|
|
49
|
+
if (token === void 0) {
|
|
50
|
+
token = computeOptionsToken(options);
|
|
51
|
+
optionsTokens.set(options, token);
|
|
52
|
+
}
|
|
53
|
+
return `${apiKey}:${token}`;
|
|
54
|
+
};
|
|
55
|
+
var getStripeClient = (apiKey, options) => {
|
|
56
|
+
const opts = options ?? {};
|
|
57
|
+
const cacheKey = getCacheKey(apiKey, opts);
|
|
58
|
+
const cached = clientCache.get(cacheKey);
|
|
59
|
+
if (cached) return cached;
|
|
60
|
+
const client = new Stripe(apiKey, buildConfig(opts));
|
|
61
|
+
clientCache.set(cacheKey, client);
|
|
62
|
+
if (clientCache.size > MAX_CACHE_ENTRIES) {
|
|
63
|
+
const oldest = clientCache.keys().next().value;
|
|
64
|
+
if (oldest !== void 0) clientCache.delete(oldest);
|
|
65
|
+
}
|
|
66
|
+
return client;
|
|
67
|
+
};
|
|
68
|
+
var getCryptoProvider = () => {
|
|
69
|
+
if (!cryptoProvider) {
|
|
70
|
+
cryptoProvider = Stripe.createSubtleCryptoProvider();
|
|
71
|
+
}
|
|
72
|
+
return cryptoProvider;
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export { getCryptoProvider, getStripe, getStripeClient, isNodeRuntime, isWorkersRuntime, shouldUseFetchHttpClient };
|
|
76
|
+
//# sourceMappingURL=chunk-TV73NTMC.js.map
|
|
77
|
+
//# sourceMappingURL=chunk-TV73NTMC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/context.ts","../src/runtime.ts"],"names":[],"mappings":"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","file":"chunk-TV73NTMC.js","sourcesContent":["import type { Context } from 'hono'\nimport type Stripe from 'stripe'\n\n/**\n * Read the Stripe client injected by {@link stripeMiddleware} from the context.\n *\n * Throws a clear error if the middleware has not run, so misconfiguration\n * fails fast instead of surfacing as an opaque `undefined` later.\n */\nexport const getStripe = (c: Context): Stripe => {\n const stripe = c.get('stripe') as Stripe | undefined\n if (!stripe) {\n throw new Error(\n 'hono-stripe: Stripe client not found on context. Did you register stripeMiddleware() before this handler?',\n )\n }\n return stripe\n}\n","import { getRuntimeKey } from 'hono/adapter'\nimport Stripe from 'stripe'\nimport type { StripeMiddlewareOptions } from './types'\n\n/**\n * The Stripe client config type (second constructor argument).\n *\n * `StripeConfig` is a top-level export of `stripe` rather than a member of the\n * `Stripe` namespace, so we derive it from the constructor to stay robust\n * across the supported peer range.\n */\nexport type StripeClientConfig = NonNullable<ConstructorParameters<typeof Stripe>[1]>\n\n/**\n * True when running on a Node.js runtime.\n *\n * Delegates to Hono's `getRuntimeKey()` so this stays consistent with the\n * runtime detection used by `env()` for secret-key resolution.\n */\nexport const isNodeRuntime = (): boolean => getRuntimeKey() === 'node'\n\n/**\n * True when running on Cloudflare Workers (`workerd`).\n */\nexport const isWorkersRuntime = (): boolean => getRuntimeKey() === 'workerd'\n\n/**\n * Whether the Stripe SDK should use the Fetch-based HTTP client.\n *\n * On Cloudflare Workers (and other non-Node edge runtimes) the default Node\n * `http`/`https` client is unavailable, so Stripe must be initialized with\n * `Stripe.createFetchHttpClient()`. This is the single most common \"gotcha\"\n * when running stripe-node on the edge, and hono-stripe handles it for you.\n */\nexport const shouldUseFetchHttpClient = (): boolean => !isNodeRuntime()\n\n// Maximum number of Stripe clients retained. Bounds memory (and retained\n// secrets) in multi-tenant / key-rotation setups where many distinct secret\n// keys flow through the middleware over the process lifetime.\nconst MAX_CACHE_ENTRIES = 100\n\n// One Stripe client per unique (key + config) — reused across requests.\n// Insertion order is significant: `Map` preserves it, so the first-inserted\n// entry is the oldest and is evicted first (FIFO) once the cap is exceeded.\nconst clientCache = new Map<string, Stripe>()\n\n// Stable per-options-object identity token, keyed by object identity. Lets the\n// cache key distinguish two options objects whose `config` is non-serializable\n// or otherwise not comparable via `JSON.stringify` (e.g. a custom `httpClient`),\n// while a repeated call with the same options object reuses its token without\n// re-serializing. A `WeakMap` lets tokens be GC'd alongside their options.\nlet optionsTokens = new WeakMap<object, string>()\nlet optionsTokenSeq = 0\n\n// SubtleCrypto provider is required for async webhook verification on the edge.\nlet cryptoProvider: ReturnType<typeof Stripe.createSubtleCryptoProvider> | undefined\n\n/**\n * Build the Stripe client config, applying the Fetch HTTP client automatically\n * on edge runtimes unless the caller supplied their own `httpClient`.\n */\nconst buildConfig = (options: StripeMiddlewareOptions): StripeClientConfig => {\n const config: StripeClientConfig = { ...options.config }\n if (options.apiVersion) {\n config.apiVersion = options.apiVersion\n }\n if (!config.httpClient && shouldUseFetchHttpClient()) {\n config.httpClient = Stripe.createFetchHttpClient()\n }\n return config\n}\n\n/**\n * Whether a config carries values that a JSON representation cannot faithfully\n * compare, so keying by its serialized form would let distinct configs collide.\n *\n * A custom `httpClient` is a runtime object/class instance whose *identity*\n * (not its often-empty enumerable shape) determines behavior — two different\n * clients both serialize to the same string — so its mere presence is treated\n * as non-serializable. Function-valued config is likewise flagged because\n * `JSON.stringify` silently drops functions.\n */\nconst hasNonSerializableConfig = (config: StripeClientConfig): boolean => {\n if (config.httpClient !== undefined) return true\n return Object.values(config).some((value) => typeof value === 'function')\n}\n\n/**\n * Compute a stable token identifying the client-construction inputs of an\n * options object.\n *\n * For plainly serializable options the token is the JSON form, so two distinct\n * but equivalent options objects share a client. When `config` is\n * non-serializable (custom `httpClient`, functions) or `JSON.stringify` throws\n * (e.g. circular refs), a unique token is minted instead, so such options never\n * collide with one another.\n */\nconst computeOptionsToken = (options: StripeMiddlewareOptions): string => {\n const { apiVersion, config } = options\n if (config && hasNonSerializableConfig(config)) {\n return `#${++optionsTokenSeq}`\n }\n try {\n return JSON.stringify({ apiVersion, config })\n } catch {\n return `#${++optionsTokenSeq}`\n }\n}\n\n/**\n * Build the cache key from the secret key and the options that affect client\n * construction, so the same key initialized with different config does not\n * silently reuse the first client.\n *\n * The per-options token is memoized in a `WeakMap` keyed by the options object\n * identity: the same options object (the common per-middleware case) reuses its\n * token without re-running `JSON.stringify` on every request.\n */\nconst getCacheKey = (apiKey: string, options: StripeMiddlewareOptions): string => {\n let token = optionsTokens.get(options)\n if (token === undefined) {\n token = computeOptionsToken(options)\n optionsTokens.set(options, token)\n }\n return `${apiKey}:${token}`\n}\n\n/**\n * Get (or lazily create and cache) a Stripe client for the given secret key\n * and options. The cache is bounded to {@link MAX_CACHE_ENTRIES}; the oldest\n * entry is evicted (FIFO) when the cap would be exceeded.\n *\n * `options` is typed as required, but this is also a public entry point that\n * an untyped JS caller can invoke with `undefined`/`null`. Normalize to `{}`\n * up front so that never reaches the `WeakMap` used internally, which throws\n * on a non-object key.\n */\nexport const getStripeClient = (apiKey: string, options: StripeMiddlewareOptions): Stripe => {\n const opts = options ?? {}\n const cacheKey = getCacheKey(apiKey, opts)\n const cached = clientCache.get(cacheKey)\n if (cached) return cached\n const client = new Stripe(apiKey, buildConfig(opts))\n clientCache.set(cacheKey, client)\n if (clientCache.size > MAX_CACHE_ENTRIES) {\n const oldest = clientCache.keys().next().value\n if (oldest !== undefined) clientCache.delete(oldest)\n }\n return client\n}\n\n/**\n * Get (or lazily create) the shared SubtleCrypto provider used to verify\n * webhook signatures asynchronously on runtimes without Node crypto.\n */\nexport const getCryptoProvider = (): ReturnType<typeof Stripe.createSubtleCryptoProvider> => {\n if (!cryptoProvider) {\n cryptoProvider = Stripe.createSubtleCryptoProvider()\n }\n return cryptoProvider\n}\n\n/** Test-only: current number of cached Stripe clients. */\nexport const __cacheSize = (): number => clientCache.size\n\n/** Test-only: reset the internal caches. */\nexport const __resetCaches = (): void => {\n clientCache.clear()\n optionsTokens = new WeakMap<object, string>()\n optionsTokenSeq = 0\n cryptoProvider = undefined\n}\n"]}
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var httpException = require('hono/http-exception');
|
|
4
|
+
var Stripe2 = require('stripe');
|
|
5
|
+
var stripeDeclineCodes = require('stripe-decline-codes');
|
|
6
|
+
var adapter = require('hono/adapter');
|
|
7
|
+
|
|
8
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
9
|
+
|
|
10
|
+
var Stripe2__default = /*#__PURE__*/_interopDefault(Stripe2);
|
|
11
|
+
|
|
12
|
+
// src/context.ts
|
|
13
|
+
var getStripe = (c) => {
|
|
14
|
+
const stripe = c.get("stripe");
|
|
15
|
+
if (!stripe) {
|
|
16
|
+
throw new Error(
|
|
17
|
+
"hono-stripe: Stripe client not found on context. Did you register stripeMiddleware() before this handler?"
|
|
18
|
+
);
|
|
19
|
+
}
|
|
20
|
+
return stripe;
|
|
21
|
+
};
|
|
22
|
+
var { errors } = Stripe2__default.default;
|
|
23
|
+
var isAnyOf = (err, names) => names.some((name) => {
|
|
24
|
+
const ctor = errors[name];
|
|
25
|
+
return typeof ctor === "function" && err instanceof ctor;
|
|
26
|
+
});
|
|
27
|
+
var SENSITIVE_DECLINE_CODES = /* @__PURE__ */ new Set([
|
|
28
|
+
"fraudulent",
|
|
29
|
+
"lost_card",
|
|
30
|
+
"stolen_card",
|
|
31
|
+
"merchant_blacklist"
|
|
32
|
+
]);
|
|
33
|
+
var json = (c, status, body) => c.json(body, status);
|
|
34
|
+
var stripeErrorResponse = (c, err, locale) => {
|
|
35
|
+
const body = (status, type, message, extra) => json(c, status, {
|
|
36
|
+
error: { type, message, requestId: err.requestId, ...extra }
|
|
37
|
+
});
|
|
38
|
+
if (err instanceof errors.StripeCardError) {
|
|
39
|
+
const declineCode = err.decline_code || err.code;
|
|
40
|
+
if (declineCode && SENSITIVE_DECLINE_CODES.has(declineCode)) {
|
|
41
|
+
return body(402, "card_error", "Your card was declined.", {
|
|
42
|
+
code: "generic_decline",
|
|
43
|
+
userMessage: stripeDeclineCodes.getDeclineMessage("generic_decline", locale),
|
|
44
|
+
retryable: stripeDeclineCodes.isSoftDecline("generic_decline")
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
return body(402, "card_error", err.message, {
|
|
48
|
+
code: declineCode,
|
|
49
|
+
userMessage: declineCode ? stripeDeclineCodes.getDeclineMessage(declineCode, locale) : void 0,
|
|
50
|
+
// Only a real decline_code classifies soft/hard; `card_declined` etc.
|
|
51
|
+
// in `err.code` say nothing about retryability.
|
|
52
|
+
retryable: err.decline_code ? stripeDeclineCodes.isSoftDecline(err.decline_code) : void 0
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
if (err instanceof errors.StripeInvalidRequestError || err instanceof errors.TemporarySessionExpiredError) {
|
|
56
|
+
return body(400, "invalid_request", err.message, { code: err.code });
|
|
57
|
+
}
|
|
58
|
+
if (err instanceof errors.StripeIdempotencyError) {
|
|
59
|
+
return body(409, "idempotency_error", err.message, { code: err.code });
|
|
60
|
+
}
|
|
61
|
+
if (err instanceof errors.StripeSignatureVerificationError) {
|
|
62
|
+
return body(400, "signature_verification_failed", "Webhook signature verification failed.");
|
|
63
|
+
}
|
|
64
|
+
if (isAnyOf(err, ["StripeRateLimitError", "RateLimitError"])) {
|
|
65
|
+
return body(429, "rate_limit", "Stripe rate limit reached \u2014 retry the request.");
|
|
66
|
+
}
|
|
67
|
+
if (err instanceof errors.StripeConnectionError || err instanceof errors.StripeAPIError) {
|
|
68
|
+
return body(502, "stripe_unavailable", "Stripe request failed upstream \u2014 safe to retry.");
|
|
69
|
+
}
|
|
70
|
+
if (err instanceof errors.StripeAuthenticationError || err instanceof errors.StripePermissionError || isAnyOf(err, ["StripeOAuthError"])) {
|
|
71
|
+
return body(500, "stripe_auth_error", "Stripe integration is misconfigured.");
|
|
72
|
+
}
|
|
73
|
+
if (typeof err.statusCode === "number" && err.statusCode >= 400 && err.statusCode < 500) {
|
|
74
|
+
return body(err.statusCode, "stripe_error", err.message, { code: err.code });
|
|
75
|
+
}
|
|
76
|
+
return body(502, "stripe_error", "Stripe request failed.");
|
|
77
|
+
};
|
|
78
|
+
var stripeErrorHandler = (options) => {
|
|
79
|
+
return (err, c) => {
|
|
80
|
+
if (err instanceof httpException.HTTPException) return err.getResponse();
|
|
81
|
+
if (err instanceof errors.StripeError) {
|
|
82
|
+
const locale = typeof options?.locale === "function" ? options.locale(c) : options?.locale;
|
|
83
|
+
return stripeErrorResponse(c, err, locale);
|
|
84
|
+
}
|
|
85
|
+
if (options?.fallback) return options.fallback(err, c);
|
|
86
|
+
return json(c, 500, {
|
|
87
|
+
error: { type: "internal_error", message: "Internal server error" }
|
|
88
|
+
});
|
|
89
|
+
};
|
|
90
|
+
};
|
|
91
|
+
var isNodeRuntime = () => adapter.getRuntimeKey() === "node";
|
|
92
|
+
var isWorkersRuntime = () => adapter.getRuntimeKey() === "workerd";
|
|
93
|
+
var shouldUseFetchHttpClient = () => !isNodeRuntime();
|
|
94
|
+
var MAX_CACHE_ENTRIES = 100;
|
|
95
|
+
var clientCache = /* @__PURE__ */ new Map();
|
|
96
|
+
var optionsTokens = /* @__PURE__ */ new WeakMap();
|
|
97
|
+
var optionsTokenSeq = 0;
|
|
98
|
+
var buildConfig = (options) => {
|
|
99
|
+
const config = { ...options.config };
|
|
100
|
+
if (options.apiVersion) {
|
|
101
|
+
config.apiVersion = options.apiVersion;
|
|
102
|
+
}
|
|
103
|
+
if (!config.httpClient && shouldUseFetchHttpClient()) {
|
|
104
|
+
config.httpClient = Stripe2__default.default.createFetchHttpClient();
|
|
105
|
+
}
|
|
106
|
+
return config;
|
|
107
|
+
};
|
|
108
|
+
var hasNonSerializableConfig = (config) => {
|
|
109
|
+
if (config.httpClient !== void 0) return true;
|
|
110
|
+
return Object.values(config).some((value) => typeof value === "function");
|
|
111
|
+
};
|
|
112
|
+
var computeOptionsToken = (options) => {
|
|
113
|
+
const { apiVersion, config } = options;
|
|
114
|
+
if (config && hasNonSerializableConfig(config)) {
|
|
115
|
+
return `#${++optionsTokenSeq}`;
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
return JSON.stringify({ apiVersion, config });
|
|
119
|
+
} catch {
|
|
120
|
+
return `#${++optionsTokenSeq}`;
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
var getCacheKey = (apiKey, options) => {
|
|
124
|
+
let token = optionsTokens.get(options);
|
|
125
|
+
if (token === void 0) {
|
|
126
|
+
token = computeOptionsToken(options);
|
|
127
|
+
optionsTokens.set(options, token);
|
|
128
|
+
}
|
|
129
|
+
return `${apiKey}:${token}`;
|
|
130
|
+
};
|
|
131
|
+
var getStripeClient = (apiKey, options) => {
|
|
132
|
+
const opts = options ?? {};
|
|
133
|
+
const cacheKey = getCacheKey(apiKey, opts);
|
|
134
|
+
const cached = clientCache.get(cacheKey);
|
|
135
|
+
if (cached) return cached;
|
|
136
|
+
const client = new Stripe2__default.default(apiKey, buildConfig(opts));
|
|
137
|
+
clientCache.set(cacheKey, client);
|
|
138
|
+
if (clientCache.size > MAX_CACHE_ENTRIES) {
|
|
139
|
+
const oldest = clientCache.keys().next().value;
|
|
140
|
+
if (oldest !== void 0) clientCache.delete(oldest);
|
|
141
|
+
}
|
|
142
|
+
return client;
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
// src/middleware.ts
|
|
146
|
+
var DEFAULT_SECRET_KEY_VAR = "STRIPE_SECRET_KEY";
|
|
147
|
+
var stripeMiddleware = (options = {}) => {
|
|
148
|
+
const secretKeyVar = options.secretKeyVar ?? DEFAULT_SECRET_KEY_VAR;
|
|
149
|
+
const staticStripe = options.apiKey ? getStripeClient(options.apiKey, options) : void 0;
|
|
150
|
+
return async (c, next) => {
|
|
151
|
+
let stripe = staticStripe;
|
|
152
|
+
if (!stripe) {
|
|
153
|
+
const apiKey = adapter.env(c)[secretKeyVar];
|
|
154
|
+
if (!apiKey) {
|
|
155
|
+
throw new Error(
|
|
156
|
+
`hono-stripe: Stripe secret key not found. Pass { apiKey } or set the "${secretKeyVar}" env binding / process.env value.`
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
stripe = getStripeClient(apiKey, options);
|
|
160
|
+
}
|
|
161
|
+
c.set("stripe", stripe);
|
|
162
|
+
await next();
|
|
163
|
+
};
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
exports.getStripe = getStripe;
|
|
167
|
+
exports.isNodeRuntime = isNodeRuntime;
|
|
168
|
+
exports.isWorkersRuntime = isWorkersRuntime;
|
|
169
|
+
exports.shouldUseFetchHttpClient = shouldUseFetchHttpClient;
|
|
170
|
+
exports.stripeErrorHandler = stripeErrorHandler;
|
|
171
|
+
exports.stripeErrorResponse = stripeErrorResponse;
|
|
172
|
+
exports.stripeMiddleware = stripeMiddleware;
|
|
173
|
+
//# sourceMappingURL=index.cjs.map
|
|
174
|
+
//# sourceMappingURL=index.cjs.map
|