hono-stripe 0.0.0-stage → 0.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 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,175 @@
1
- # Temporary Holding Version
1
+ # hono-stripe
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Stripe middleware and helpers for [Hono](https://hono.dev) — works on Cloudflare Workers and Node.
4
+
5
+ `hono-stripe` injects a configured Stripe client into your Hono context and gives
6
+ you thin helpers for the two things a payment backend needs first: creating a
7
+ **PaymentIntent / Checkout Session** (to hand a `client_secret` to the frontend)
8
+ and **verifying webhook signatures**. It handles the edge-runtime gotchas
9
+ (`createFetchHttpClient`, async webhook verification) for you.
10
+
11
+ > **Status:** early development (`0.0.1`). The goal is to upstream this as
12
+ > `@hono/stripe` to [honojs/middleware](https://github.com/honojs/middleware)
13
+ > once it has proven itself — see [Upstream plan](#upstream-plan). The current
14
+ > maintainer intends to keep maintaining it through and after that move.
15
+
16
+ ## Where it fits — the 3 layers
17
+
18
+ A full Hono + Stripe stack is three small pieces, each owning one job:
19
+
20
+ | Layer | Package | Responsibility |
21
+ | -- | -- | -- |
22
+ | **Backend — client + intent/session** | **`hono-stripe`** (this) | Inject `c.var.stripe`; create PaymentIntents / Checkout Sessions; verify webhook signatures |
23
+ | Backend — webhook routing | [`@kotodayori/hono`](https://www.npmjs.com/package/@kotodayori/hono) | Typed, per-event webhook routing on top of a verified event |
24
+ | Frontend — payment UI | [stripe-pwa-elements](https://github.com/stripe/stripe-pwa-elements) | `<stripe-payment-element>` web components (no React required) |
25
+
26
+ `hono-stripe` deliberately stops at **verifying** the webhook. Event dispatch /
27
+ typed routing is the job of `@kotodayori/hono` — reach for it when you outgrow
28
+ the primitive here.
29
+
30
+ ## Install
31
+
32
+ ```sh
33
+ npm install hono-stripe stripe hono
34
+ ```
35
+
36
+ `stripe` and `hono` are peer dependencies — you bring your own versions.
37
+
38
+ ## Starter template
39
+
40
+ A runnable full-stack example (Hono + Cloudflare Workers + stripe-pwa-elements UI,
41
+ with both PaymentIntent and Checkout Session flows) lives in
42
+ [`examples/cloudflare-workers`](./examples/cloudflare-workers). Clone, set your
43
+ test keys, `pnpm dev`.
44
+
45
+ ## Quick start
46
+
47
+ ### Cloudflare Workers
48
+
49
+ ```ts
50
+ import { Hono } from 'hono'
51
+ import {
52
+ stripeMiddleware,
53
+ createPaymentIntent,
54
+ verifyStripeSignature,
55
+ type StripeEnv,
56
+ } from 'hono-stripe'
57
+
58
+ type Bindings = { STRIPE_SECRET_KEY: string; STRIPE_WEBHOOK_SECRET: string }
59
+
60
+ const app = new Hono<{ Bindings: Bindings } & StripeEnv>()
61
+
62
+ // Reads STRIPE_SECRET_KEY from the Workers env binding.
63
+ // On Workers, Stripe.createFetchHttpClient() is applied automatically.
64
+ app.use(stripeMiddleware())
65
+
66
+ app.post('/api/payment-intent', async (c) => {
67
+ // Decide the amount on the server (e.g. from a price id / cart lookup),
68
+ // never trust an amount sent by the client.
69
+ const intent = await createPaymentIntent(c, { amount: 1400, currency: 'usd' })
70
+ return c.json({ clientSecret: intent.client_secret })
71
+ })
72
+
73
+ app.post('/api/webhook', async (c) => {
74
+ const event = await verifyStripeSignature(c, { secret: c.env.STRIPE_WEBHOOK_SECRET })
75
+ // Hand `event` to @kotodayori/hono for typed routing, or switch on event.type.
76
+ return c.body(null, 200)
77
+ })
78
+
79
+ export default app
80
+ ```
81
+
82
+ `.dev.vars` (Workers local dev — **test keys only**, never commit real keys):
83
+
84
+ ```
85
+ STRIPE_SECRET_KEY=sk_test_...
86
+ STRIPE_WEBHOOK_SECRET=whsec_...
87
+ ```
88
+
89
+ ### Node
90
+
91
+ ```ts
92
+ import { serve } from '@hono/node-server'
93
+ import { Hono } from 'hono'
94
+ import { stripeMiddleware, createPaymentIntent, type StripeEnv } from 'hono-stripe'
95
+
96
+ const app = new Hono<StripeEnv>()
97
+ app.use(stripeMiddleware()) // reads process.env.STRIPE_SECRET_KEY
98
+
99
+ app.post('/api/payment-intent', async (c) => {
100
+ const intent = await createPaymentIntent(c, { amount: 1400, currency: 'usd' })
101
+ return c.json({ clientSecret: intent.client_secret })
102
+ })
103
+
104
+ serve(app)
105
+ ```
106
+
107
+ ## API
108
+
109
+ ### `stripeMiddleware(options?)`
110
+
111
+ Initializes a Stripe client and sets it at `c.var.stripe`. The secret key is
112
+ resolved in order:
113
+
114
+ 1. `options.apiKey` (explicit)
115
+ 2. Workers env binding `c.env[secretKeyVar]`
116
+ 3. `process.env[secretKeyVar]`
117
+
118
+ `secretKeyVar` defaults to `STRIPE_SECRET_KEY`. On non-Node runtimes the SDK is
119
+ initialized with `Stripe.createFetchHttpClient()`. Clients are cached per key.
120
+
121
+ | Option | Type | Description |
122
+ | -- | -- | -- |
123
+ | `apiKey` | `string` | Secret key passed directly |
124
+ | `secretKeyVar` | `string` | Env / `process.env` key name (default `STRIPE_SECRET_KEY`) |
125
+ | `apiVersion` | `string` | Stripe API version override |
126
+ | `config` | `Stripe.StripeConfig` | Extra config; an explicit `httpClient` here wins |
127
+
128
+ ### `createPaymentIntent(c, params, options?)` / `createCheckoutSession(c, params, options?)`
129
+
130
+ Thin wrappers over `stripe.paymentIntents.create` /
131
+ `stripe.checkout.sessions.create` that forward params verbatim. To drive the
132
+ frontend with a `client_secret` (the Checkout Sessions mode used by
133
+ stripe-pwa-elements), pass the client-side `ui_mode` for your Stripe version
134
+ (`'custom'` on recent Stripe, `'elements'` on older SDKs).
135
+
136
+ ### `verifyStripeSignature(c, { secret, signatureHeader?, tolerance? })`
137
+
138
+ Reads the raw body and verifies it with `constructEventAsync` (the async form
139
+ required where WebCrypto is async, e.g. Workers), returning the verified
140
+ `Stripe.Event`. Throws if the signature header is missing or invalid.
141
+
142
+ ### `getStripe(c)`
143
+
144
+ Returns `c.var.stripe`, throwing a clear error if the middleware has not run.
145
+
146
+ ### Runtime helpers
147
+
148
+ `isNodeRuntime()`, `isWorkersRuntime()`, `shouldUseFetchHttpClient()` are
149
+ exported for advanced/diagnostic use.
150
+
151
+ ## Bundle size
152
+
153
+ Staying thin is a feature. CI enforces a [size-limit](https://github.com/ai/size-limit)
154
+ budget on the built artifacts (`.size-limit.json`) and posts the current sizes
155
+ to each PR, so accidental bloat fails the build instead of slipping in. Run it
156
+ locally with:
157
+
158
+ ```sh
159
+ pnpm run size
160
+ ```
161
+
162
+ The library itself adds ~1 kB (brotli) per format; `stripe`/`hono` are peers and
163
+ are not bundled.
164
+
165
+ ## Upstream plan
166
+
167
+ `hono-stripe` is built to be proposed to
168
+ [honojs/middleware](https://github.com/honojs/middleware) as `@hono/stripe`.
169
+ To keep that path open it depends on **`stripe` and `hono` as peers only** — no
170
+ other runtime dependencies. If the proposal is accepted, `hono-stripe` will be
171
+ deprecated with a pointer to `@hono/stripe`.
172
+
173
+ ## License
174
+
175
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,155 @@
1
+ 'use strict';
2
+
3
+ var adapter = require('hono/adapter');
4
+ var Stripe = require('stripe');
5
+ var httpException = require('hono/http-exception');
6
+
7
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
+
9
+ var Stripe__default = /*#__PURE__*/_interopDefault(Stripe);
10
+
11
+ // src/middleware.ts
12
+ var isNodeRuntime = () => adapter.getRuntimeKey() === "node";
13
+ var isWorkersRuntime = () => adapter.getRuntimeKey() === "workerd";
14
+ var shouldUseFetchHttpClient = () => !isNodeRuntime();
15
+ var MAX_CACHE_ENTRIES = 100;
16
+ var clientCache = /* @__PURE__ */ new Map();
17
+ var optionsTokens = /* @__PURE__ */ new WeakMap();
18
+ var optionsTokenSeq = 0;
19
+ var cryptoProvider;
20
+ var buildConfig = (options) => {
21
+ const config = { ...options.config };
22
+ if (options.apiVersion) {
23
+ config.apiVersion = options.apiVersion;
24
+ }
25
+ if (!config.httpClient && shouldUseFetchHttpClient()) {
26
+ config.httpClient = Stripe__default.default.createFetchHttpClient();
27
+ }
28
+ return config;
29
+ };
30
+ var hasNonSerializableConfig = (config) => {
31
+ if (config.httpClient !== void 0) return true;
32
+ return Object.values(config).some((value) => typeof value === "function");
33
+ };
34
+ var computeOptionsToken = (options) => {
35
+ const { apiVersion, config } = options;
36
+ if (config && hasNonSerializableConfig(config)) {
37
+ return `#${++optionsTokenSeq}`;
38
+ }
39
+ try {
40
+ return JSON.stringify({ apiVersion, config });
41
+ } catch {
42
+ return `#${++optionsTokenSeq}`;
43
+ }
44
+ };
45
+ var getCacheKey = (apiKey, options) => {
46
+ let token = optionsTokens.get(options);
47
+ if (token === void 0) {
48
+ token = computeOptionsToken(options);
49
+ optionsTokens.set(options, token);
50
+ }
51
+ return `${apiKey}:${token}`;
52
+ };
53
+ var getStripeClient = (apiKey, options) => {
54
+ const opts = options ?? {};
55
+ const cacheKey = getCacheKey(apiKey, opts);
56
+ const cached = clientCache.get(cacheKey);
57
+ if (cached) return cached;
58
+ const client = new Stripe__default.default(apiKey, buildConfig(opts));
59
+ clientCache.set(cacheKey, client);
60
+ if (clientCache.size > MAX_CACHE_ENTRIES) {
61
+ const oldest = clientCache.keys().next().value;
62
+ if (oldest !== void 0) clientCache.delete(oldest);
63
+ }
64
+ return client;
65
+ };
66
+ var getCryptoProvider = () => {
67
+ if (!cryptoProvider) {
68
+ cryptoProvider = Stripe__default.default.createSubtleCryptoProvider();
69
+ }
70
+ return cryptoProvider;
71
+ };
72
+
73
+ // src/middleware.ts
74
+ var DEFAULT_SECRET_KEY_VAR = "STRIPE_SECRET_KEY";
75
+ var stripeMiddleware = (options = {}) => {
76
+ const secretKeyVar = options.secretKeyVar ?? DEFAULT_SECRET_KEY_VAR;
77
+ const staticStripe = options.apiKey ? getStripeClient(options.apiKey, options) : void 0;
78
+ return async (c, next) => {
79
+ let stripe = staticStripe;
80
+ if (!stripe) {
81
+ const apiKey = adapter.env(c)[secretKeyVar];
82
+ if (!apiKey) {
83
+ throw new Error(
84
+ `hono-stripe: Stripe secret key not found. Pass { apiKey } or set the "${secretKeyVar}" env binding / process.env value.`
85
+ );
86
+ }
87
+ stripe = getStripeClient(apiKey, options);
88
+ }
89
+ c.set("stripe", stripe);
90
+ await next();
91
+ };
92
+ };
93
+
94
+ // src/context.ts
95
+ var getStripe = (c) => {
96
+ const stripe = c.get("stripe");
97
+ if (!stripe) {
98
+ throw new Error(
99
+ "hono-stripe: Stripe client not found on context. Did you register stripeMiddleware() before this handler?"
100
+ );
101
+ }
102
+ return stripe;
103
+ };
104
+
105
+ // src/helpers.ts
106
+ var withIdempotencyKey = (options) => {
107
+ if (options?.idempotencyKey) {
108
+ return { ...options, idempotencyKey: options.idempotencyKey };
109
+ }
110
+ if (typeof globalThis.crypto?.randomUUID !== "function") {
111
+ throw new Error(
112
+ "hono-stripe: crypto.randomUUID is not available in this runtime to auto-generate an idempotency key. Pass a stable { idempotencyKey } explicitly."
113
+ );
114
+ }
115
+ return { ...options, idempotencyKey: globalThis.crypto.randomUUID() };
116
+ };
117
+ var createPaymentIntent = (c, params, options) => getStripe(c).paymentIntents.create(params, withIdempotencyKey(options));
118
+ var createCheckoutSession = (c, params, options) => getStripe(c).checkout.sessions.create(params, withIdempotencyKey(options));
119
+ var DEFAULT_SIGNATURE_HEADER = "stripe-signature";
120
+ var verifyStripeSignature = async (c, options) => {
121
+ const stripe = getStripe(c);
122
+ const signature = c.req.header(options.signatureHeader ?? DEFAULT_SIGNATURE_HEADER);
123
+ if (!signature) {
124
+ throw new httpException.HTTPException(400, {
125
+ message: "hono-stripe: missing Stripe signature header on webhook request."
126
+ });
127
+ }
128
+ const payload = await c.req.text();
129
+ const cryptoProvider2 = shouldUseFetchHttpClient() ? getCryptoProvider() : void 0;
130
+ try {
131
+ return await stripe.webhooks.constructEventAsync(
132
+ payload,
133
+ signature,
134
+ options.secret,
135
+ options.tolerance,
136
+ cryptoProvider2
137
+ );
138
+ } catch (err) {
139
+ throw new httpException.HTTPException(400, {
140
+ message: err instanceof Error ? err.message : "hono-stripe: webhook signature verification failed.",
141
+ cause: err
142
+ });
143
+ }
144
+ };
145
+
146
+ exports.createCheckoutSession = createCheckoutSession;
147
+ exports.createPaymentIntent = createPaymentIntent;
148
+ exports.getStripe = getStripe;
149
+ exports.isNodeRuntime = isNodeRuntime;
150
+ exports.isWorkersRuntime = isWorkersRuntime;
151
+ exports.shouldUseFetchHttpClient = shouldUseFetchHttpClient;
152
+ exports.stripeMiddleware = stripeMiddleware;
153
+ exports.verifyStripeSignature = verifyStripeSignature;
154
+ //# sourceMappingURL=index.cjs.map
155
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/runtime.ts","../src/middleware.ts","../src/context.ts","../src/helpers.ts","../src/webhook.ts"],"names":["getRuntimeKey","Stripe","env","HTTPException","cryptoProvider"],"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OAAA;AAAA,MACA,SAAA;AAAA,MACA,OAAA,CAAQ,MAAA;AAAA,MACR,OAAA,CAAQ,SAAA;AAAA,MACRA;AAAA,KACF;AAAA,EACF,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,IAAID,4BAAc,GAAA,EAAK;AAAA,MAC3B,OAAA,EACE,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,qDAAA;AAAA,MACvC,KAAA,EAAO;AAAA,KACR,CAAA;AAAA,EACH;AACF","file":"index.cjs","sourcesContent":["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","import type { MiddlewareHandler } from 'hono'\nimport { env } from 'hono/adapter'\nimport { getStripeClient } from './runtime'\nimport type { StripeEnv, StripeMiddlewareOptions } from './types'\n\nconst DEFAULT_SECRET_KEY_VAR = 'STRIPE_SECRET_KEY'\n\n/**\n * Hono middleware that initializes a Stripe client and injects it at\n * `c.var.stripe`.\n *\n * - Resolves the secret key from an explicit option, a Cloudflare Workers env\n * binding, or `process.env` — in that order.\n * - On edge runtimes (Workers) it automatically applies\n * `Stripe.createFetchHttpClient()` so the SDK works without Node's HTTP stack.\n * - Clients are cached per secret key and reused across requests.\n *\n * @example\n * ```ts\n * const app = new Hono<StripeEnv>()\n * app.use(stripeMiddleware()) // reads STRIPE_SECRET_KEY from env binding / process.env\n * ```\n */\nexport const stripeMiddleware = (\n options: StripeMiddlewareOptions = {},\n): MiddlewareHandler<StripeEnv> => {\n const secretKeyVar = options.secretKeyVar ?? DEFAULT_SECRET_KEY_VAR\n // When apiKey is known at registration time, build the client once and reuse it.\n const staticStripe = options.apiKey ? getStripeClient(options.apiKey, options) : undefined\n return async (c, next) => {\n let stripe = staticStripe\n if (!stripe) {\n const apiKey = env<Record<string, string | undefined>>(c)[secretKeyVar]\n if (!apiKey) {\n throw new Error(\n `hono-stripe: Stripe secret key not found. Pass { apiKey } or set the \"${secretKeyVar}\" env binding / process.env value.`,\n )\n }\n stripe = getStripeClient(apiKey, options)\n }\n c.set('stripe', stripe)\n await next()\n }\n}\n","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 type { Context } from 'hono'\nimport type Stripe from 'stripe'\nimport { getStripe } from './context'\n\n/**\n * Return a copy of `options` that is guaranteed to carry an `idempotencyKey`.\n *\n * If the caller already supplied `options.idempotencyKey` it is preserved\n * untouched; otherwise a freshly generated `crypto.randomUUID()` is used. The\n * caller's object is never mutated — a new object is always returned.\n *\n * Throws a clear error (rather than a raw `TypeError`) if `crypto.randomUUID`\n * is unavailable in the current runtime — pass a stable `options.idempotencyKey`\n * explicitly in that case instead of relying on auto-generation.\n */\nconst withIdempotencyKey = (options?: Stripe.RequestOptions): Stripe.RequestOptions => {\n if (options?.idempotencyKey) {\n return { ...options, idempotencyKey: options.idempotencyKey }\n }\n if (typeof globalThis.crypto?.randomUUID !== 'function') {\n throw new Error(\n 'hono-stripe: crypto.randomUUID is not available in this runtime to auto-generate an idempotency key. Pass a stable { idempotencyKey } explicitly.',\n )\n }\n return { ...options, idempotencyKey: globalThis.crypto.randomUUID() }\n}\n\n/**\n * Create a PaymentIntent using the Stripe client on the context.\n *\n * The returned `client_secret` is what the frontend (e.g. the\n * `<stripe-payment-element>` web component from stripe-pwa-elements) needs to\n * confirm the payment.\n *\n * Security note: decide `amount`/`currency` on the server from a trusted source\n * (price IDs, a cart looked up by id) rather than trusting values sent by the\n * client. See the README for the recommended pattern.\n *\n * Idempotency note: when the caller does not supply `options.idempotencyKey`,\n * a fresh per-call `crypto.randomUUID()` is set as the idempotency key. This\n * only protects stripe-node's own automatic network retries of a single\n * invocation — it does NOT protect against a client double-submitting the same\n * request, because every server invocation generates a brand new key. To guard\n * against client-side duplicate submissions, pass a STABLE `idempotencyKey` via\n * `options`, derived from the business operation (e.g. a cart id or order id),\n * so retries of the same logical operation collapse to one PaymentIntent.\n *\n * @example\n * ```ts\n * app.post('/api/payment-intent', async (c) => {\n * const intent = await createPaymentIntent(c, { amount: 1400, currency: 'usd' })\n * return c.json({ clientSecret: intent.client_secret })\n * })\n * ```\n */\nexport const createPaymentIntent = (\n c: Context,\n params: Stripe.PaymentIntentCreateParams,\n options?: Stripe.RequestOptions,\n): Promise<Stripe.PaymentIntent> =>\n getStripe(c).paymentIntents.create(params, withIdempotencyKey(options))\n\n/**\n * Create a Checkout Session.\n *\n * This is a thin pass-through over `stripe.checkout.sessions.create` — it does\n * not hard-code a `ui_mode`, since the accepted values differ across the Stripe\n * versions this package supports as a peer. To drive the frontend with a\n * `client_secret` (the Checkout Sessions mode used by stripe-pwa-elements),\n * pass the client-side UI mode for your Stripe version (e.g. `ui_mode: 'custom'`\n * on recent Stripe, `'elements'` on older SDKs).\n *\n * Idempotency note: when the caller does not supply `options.idempotencyKey`,\n * a fresh per-call `crypto.randomUUID()` is set as the idempotency key. This\n * only protects stripe-node's own automatic network retries of a single\n * invocation — it does NOT protect against a client double-submitting the same\n * request, because every server invocation generates a brand new key. To guard\n * against client-side duplicate submissions, pass a STABLE `idempotencyKey` via\n * `options`, derived from the business operation (e.g. a cart id or order id),\n * so retries of the same logical operation collapse to one Checkout Session.\n *\n * @example\n * ```ts\n * app.post('/api/checkout-session', async (c) => {\n * const session = await createCheckoutSession(c, {\n * ui_mode: 'custom',\n * mode: 'payment',\n * line_items: [{ price: 'price_123', quantity: 1 }],\n * })\n * return c.json({ clientSecret: session.client_secret })\n * })\n * ```\n */\nexport const createCheckoutSession = (\n c: Context,\n params: Stripe.Checkout.SessionCreateParams,\n options?: Stripe.RequestOptions,\n): Promise<Stripe.Checkout.Session> =>\n getStripe(c).checkout.sessions.create(params, withIdempotencyKey(options))\n","import type { Context } from 'hono'\nimport { HTTPException } from 'hono/http-exception'\nimport type Stripe from 'stripe'\nimport { getStripe } from './context'\nimport { getCryptoProvider, shouldUseFetchHttpClient } from './runtime'\n\nconst DEFAULT_SIGNATURE_HEADER = 'stripe-signature'\n\nexport interface VerifyStripeSignatureOptions {\n /** Webhook signing secret (`whsec_...`). */\n secret: string\n /** Header carrying the signature. Default: `stripe-signature`. */\n signatureHeader?: string\n /** Allowed timestamp tolerance in seconds. Defaults to Stripe's value (300s). */\n tolerance?: number\n}\n\n/**\n * Verify a Stripe webhook signature and return the parsed, verified event.\n *\n * This is intentionally a thin primitive: it reads the raw body, verifies the\n * signature with `constructEventAsync` (the async form required on Cloudflare\n * Workers, where WebCrypto is async), and returns the `Stripe.Event`.\n *\n * The SubtleCrypto provider is only supplied on non-Node (edge) runtimes. On\n * Node the provider arg is left `undefined` so stripe-node auto-selects its\n * Node crypto provider — passing SubtleCrypto there would needlessly require a\n * global `crypto.subtle`.\n *\n * It deliberately does **not** do event routing or per-type dispatch — that is\n * the job of `@kotodayori/hono`, which offers typed webhook routing on top of a\n * verified event. Reach for that when you outgrow this primitive.\n *\n * @throws {HTTPException} 400 if the signature header is missing or\n * verification fails — the correct response to Stripe (a 500 would make Stripe\n * retry the delivery and pollute server error monitoring).\n *\n * @example\n * ```ts\n * app.post('/api/webhook', async (c) => {\n * const event = await verifyStripeSignature(c, { secret: c.env.STRIPE_WEBHOOK_SECRET })\n * // hand `event` to @kotodayori/hono for typed routing, or switch on event.type\n * return c.body(null, 200)\n * })\n * ```\n */\nexport const verifyStripeSignature = async (\n c: Context,\n options: VerifyStripeSignatureOptions,\n): Promise<Stripe.Event> => {\n const stripe = getStripe(c)\n const signature = c.req.header(options.signatureHeader ?? DEFAULT_SIGNATURE_HEADER)\n if (!signature) {\n throw new HTTPException(400, {\n message: 'hono-stripe: missing Stripe signature header on webhook request.',\n })\n }\n const payload = await c.req.text()\n // Only supply the SubtleCrypto provider on edge runtimes that need it. When\n // the provider arg is omitted (`undefined`), stripe-node auto-selects the\n // right one per runtime — its Node crypto provider on Node, SubtleCrypto on\n // the edge. Forcing SubtleCrypto onto Node would needlessly require a global\n // `crypto.subtle`, so we let stripe-node pick on Node.\n const cryptoProvider = shouldUseFetchHttpClient() ? getCryptoProvider() : undefined\n try {\n return await stripe.webhooks.constructEventAsync(\n payload,\n signature,\n options.secret,\n options.tolerance,\n cryptoProvider,\n )\n } catch (err) {\n throw new HTTPException(400, {\n message:\n err instanceof Error ? err.message : 'hono-stripe: webhook signature verification failed.',\n cause: err,\n })\n }\n}\n"]}
@@ -0,0 +1,208 @@
1
+ import { MiddlewareHandler, Context } from 'hono';
2
+ import Stripe from 'stripe';
3
+
4
+ /**
5
+ * The Stripe client config type (second constructor argument).
6
+ *
7
+ * `StripeConfig` is a top-level export of `stripe` rather than a member of the
8
+ * `Stripe` namespace, so we derive it from the constructor to stay robust
9
+ * across the supported peer range.
10
+ */
11
+ type StripeClientConfig = NonNullable<ConstructorParameters<typeof Stripe>[1]>;
12
+ /**
13
+ * True when running on a Node.js runtime.
14
+ *
15
+ * Delegates to Hono's `getRuntimeKey()` so this stays consistent with the
16
+ * runtime detection used by `env()` for secret-key resolution.
17
+ */
18
+ declare const isNodeRuntime: () => boolean;
19
+ /**
20
+ * True when running on Cloudflare Workers (`workerd`).
21
+ */
22
+ declare const isWorkersRuntime: () => boolean;
23
+ /**
24
+ * Whether the Stripe SDK should use the Fetch-based HTTP client.
25
+ *
26
+ * On Cloudflare Workers (and other non-Node edge runtimes) the default Node
27
+ * `http`/`https` client is unavailable, so Stripe must be initialized with
28
+ * `Stripe.createFetchHttpClient()`. This is the single most common "gotcha"
29
+ * when running stripe-node on the edge, and hono-stripe handles it for you.
30
+ */
31
+ declare const shouldUseFetchHttpClient: () => boolean;
32
+
33
+ /**
34
+ * Variables injected into the Hono context by {@link stripeMiddleware}.
35
+ * Use together with {@link StripeEnv} so `c.var.stripe` is typed.
36
+ */
37
+ type StripeVariables = {
38
+ stripe: Stripe;
39
+ };
40
+ /**
41
+ * Hono `Env` fragment contributed by hono-stripe.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * import { Hono } from 'hono'
46
+ * import { stripeMiddleware, type StripeEnv } from 'hono-stripe'
47
+ *
48
+ * const app = new Hono<StripeEnv>()
49
+ * app.use(stripeMiddleware())
50
+ * app.post('/api/payment-intent', (c) => {
51
+ * c.var.stripe // typed as Stripe
52
+ * // ...
53
+ * })
54
+ * ```
55
+ */
56
+ type StripeEnv = {
57
+ Variables: StripeVariables;
58
+ };
59
+ /**
60
+ * Options for {@link stripeMiddleware}.
61
+ *
62
+ * The secret key is resolved in this order:
63
+ * 1. {@link StripeMiddlewareOptions.apiKey} (explicit)
64
+ * 2. Cloudflare Workers env binding `c.env[secretKeyVar]`
65
+ * 3. `process.env[secretKeyVar]` (Node)
66
+ */
67
+ interface StripeMiddlewareOptions {
68
+ /** Secret key passed directly. Skips env-binding / process.env resolution. */
69
+ apiKey?: string;
70
+ /** Name of the env binding / `process.env` key holding the secret key. Default: `STRIPE_SECRET_KEY`. */
71
+ secretKeyVar?: string;
72
+ /** Stripe API version override. Defaults to the SDK's pinned version. */
73
+ apiVersion?: StripeClientConfig['apiVersion'];
74
+ /**
75
+ * Extra Stripe config. Merged last, so an explicit `httpClient` here
76
+ * overrides the automatic Workers `createFetchHttpClient()` selection.
77
+ */
78
+ config?: StripeClientConfig;
79
+ }
80
+
81
+ /**
82
+ * Hono middleware that initializes a Stripe client and injects it at
83
+ * `c.var.stripe`.
84
+ *
85
+ * - Resolves the secret key from an explicit option, a Cloudflare Workers env
86
+ * binding, or `process.env` — in that order.
87
+ * - On edge runtimes (Workers) it automatically applies
88
+ * `Stripe.createFetchHttpClient()` so the SDK works without Node's HTTP stack.
89
+ * - Clients are cached per secret key and reused across requests.
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * const app = new Hono<StripeEnv>()
94
+ * app.use(stripeMiddleware()) // reads STRIPE_SECRET_KEY from env binding / process.env
95
+ * ```
96
+ */
97
+ declare const stripeMiddleware: (options?: StripeMiddlewareOptions) => MiddlewareHandler<StripeEnv>;
98
+
99
+ /**
100
+ * Read the Stripe client injected by {@link stripeMiddleware} from the context.
101
+ *
102
+ * Throws a clear error if the middleware has not run, so misconfiguration
103
+ * fails fast instead of surfacing as an opaque `undefined` later.
104
+ */
105
+ declare const getStripe: (c: Context) => Stripe;
106
+
107
+ /**
108
+ * Create a PaymentIntent using the Stripe client on the context.
109
+ *
110
+ * The returned `client_secret` is what the frontend (e.g. the
111
+ * `<stripe-payment-element>` web component from stripe-pwa-elements) needs to
112
+ * confirm the payment.
113
+ *
114
+ * Security note: decide `amount`/`currency` on the server from a trusted source
115
+ * (price IDs, a cart looked up by id) rather than trusting values sent by the
116
+ * client. See the README for the recommended pattern.
117
+ *
118
+ * Idempotency note: when the caller does not supply `options.idempotencyKey`,
119
+ * a fresh per-call `crypto.randomUUID()` is set as the idempotency key. This
120
+ * only protects stripe-node's own automatic network retries of a single
121
+ * invocation — it does NOT protect against a client double-submitting the same
122
+ * request, because every server invocation generates a brand new key. To guard
123
+ * against client-side duplicate submissions, pass a STABLE `idempotencyKey` via
124
+ * `options`, derived from the business operation (e.g. a cart id or order id),
125
+ * so retries of the same logical operation collapse to one PaymentIntent.
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * app.post('/api/payment-intent', async (c) => {
130
+ * const intent = await createPaymentIntent(c, { amount: 1400, currency: 'usd' })
131
+ * return c.json({ clientSecret: intent.client_secret })
132
+ * })
133
+ * ```
134
+ */
135
+ declare const createPaymentIntent: (c: Context, params: Stripe.PaymentIntentCreateParams, options?: Stripe.RequestOptions) => Promise<Stripe.PaymentIntent>;
136
+ /**
137
+ * Create a Checkout Session.
138
+ *
139
+ * This is a thin pass-through over `stripe.checkout.sessions.create` — it does
140
+ * not hard-code a `ui_mode`, since the accepted values differ across the Stripe
141
+ * versions this package supports as a peer. To drive the frontend with a
142
+ * `client_secret` (the Checkout Sessions mode used by stripe-pwa-elements),
143
+ * pass the client-side UI mode for your Stripe version (e.g. `ui_mode: 'custom'`
144
+ * on recent Stripe, `'elements'` on older SDKs).
145
+ *
146
+ * Idempotency note: when the caller does not supply `options.idempotencyKey`,
147
+ * a fresh per-call `crypto.randomUUID()` is set as the idempotency key. This
148
+ * only protects stripe-node's own automatic network retries of a single
149
+ * invocation — it does NOT protect against a client double-submitting the same
150
+ * request, because every server invocation generates a brand new key. To guard
151
+ * against client-side duplicate submissions, pass a STABLE `idempotencyKey` via
152
+ * `options`, derived from the business operation (e.g. a cart id or order id),
153
+ * so retries of the same logical operation collapse to one Checkout Session.
154
+ *
155
+ * @example
156
+ * ```ts
157
+ * app.post('/api/checkout-session', async (c) => {
158
+ * const session = await createCheckoutSession(c, {
159
+ * ui_mode: 'custom',
160
+ * mode: 'payment',
161
+ * line_items: [{ price: 'price_123', quantity: 1 }],
162
+ * })
163
+ * return c.json({ clientSecret: session.client_secret })
164
+ * })
165
+ * ```
166
+ */
167
+ declare const createCheckoutSession: (c: Context, params: Stripe.Checkout.SessionCreateParams, options?: Stripe.RequestOptions) => Promise<Stripe.Checkout.Session>;
168
+
169
+ interface VerifyStripeSignatureOptions {
170
+ /** Webhook signing secret (`whsec_...`). */
171
+ secret: string;
172
+ /** Header carrying the signature. Default: `stripe-signature`. */
173
+ signatureHeader?: string;
174
+ /** Allowed timestamp tolerance in seconds. Defaults to Stripe's value (300s). */
175
+ tolerance?: number;
176
+ }
177
+ /**
178
+ * Verify a Stripe webhook signature and return the parsed, verified event.
179
+ *
180
+ * This is intentionally a thin primitive: it reads the raw body, verifies the
181
+ * signature with `constructEventAsync` (the async form required on Cloudflare
182
+ * Workers, where WebCrypto is async), and returns the `Stripe.Event`.
183
+ *
184
+ * The SubtleCrypto provider is only supplied on non-Node (edge) runtimes. On
185
+ * Node the provider arg is left `undefined` so stripe-node auto-selects its
186
+ * Node crypto provider — passing SubtleCrypto there would needlessly require a
187
+ * global `crypto.subtle`.
188
+ *
189
+ * It deliberately does **not** do event routing or per-type dispatch — that is
190
+ * the job of `@kotodayori/hono`, which offers typed webhook routing on top of a
191
+ * verified event. Reach for that when you outgrow this primitive.
192
+ *
193
+ * @throws {HTTPException} 400 if the signature header is missing or
194
+ * verification fails — the correct response to Stripe (a 500 would make Stripe
195
+ * retry the delivery and pollute server error monitoring).
196
+ *
197
+ * @example
198
+ * ```ts
199
+ * app.post('/api/webhook', async (c) => {
200
+ * const event = await verifyStripeSignature(c, { secret: c.env.STRIPE_WEBHOOK_SECRET })
201
+ * // hand `event` to @kotodayori/hono for typed routing, or switch on event.type
202
+ * return c.body(null, 200)
203
+ * })
204
+ * ```
205
+ */
206
+ declare const verifyStripeSignature: (c: Context, options: VerifyStripeSignatureOptions) => Promise<Stripe.Event>;
207
+
208
+ export { type StripeEnv, type StripeMiddlewareOptions, type StripeVariables, type VerifyStripeSignatureOptions, createCheckoutSession, createPaymentIntent, getStripe, isNodeRuntime, isWorkersRuntime, shouldUseFetchHttpClient, stripeMiddleware, verifyStripeSignature };
@@ -0,0 +1,208 @@
1
+ import { MiddlewareHandler, Context } from 'hono';
2
+ import Stripe from 'stripe';
3
+
4
+ /**
5
+ * The Stripe client config type (second constructor argument).
6
+ *
7
+ * `StripeConfig` is a top-level export of `stripe` rather than a member of the
8
+ * `Stripe` namespace, so we derive it from the constructor to stay robust
9
+ * across the supported peer range.
10
+ */
11
+ type StripeClientConfig = NonNullable<ConstructorParameters<typeof Stripe>[1]>;
12
+ /**
13
+ * True when running on a Node.js runtime.
14
+ *
15
+ * Delegates to Hono's `getRuntimeKey()` so this stays consistent with the
16
+ * runtime detection used by `env()` for secret-key resolution.
17
+ */
18
+ declare const isNodeRuntime: () => boolean;
19
+ /**
20
+ * True when running on Cloudflare Workers (`workerd`).
21
+ */
22
+ declare const isWorkersRuntime: () => boolean;
23
+ /**
24
+ * Whether the Stripe SDK should use the Fetch-based HTTP client.
25
+ *
26
+ * On Cloudflare Workers (and other non-Node edge runtimes) the default Node
27
+ * `http`/`https` client is unavailable, so Stripe must be initialized with
28
+ * `Stripe.createFetchHttpClient()`. This is the single most common "gotcha"
29
+ * when running stripe-node on the edge, and hono-stripe handles it for you.
30
+ */
31
+ declare const shouldUseFetchHttpClient: () => boolean;
32
+
33
+ /**
34
+ * Variables injected into the Hono context by {@link stripeMiddleware}.
35
+ * Use together with {@link StripeEnv} so `c.var.stripe` is typed.
36
+ */
37
+ type StripeVariables = {
38
+ stripe: Stripe;
39
+ };
40
+ /**
41
+ * Hono `Env` fragment contributed by hono-stripe.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * import { Hono } from 'hono'
46
+ * import { stripeMiddleware, type StripeEnv } from 'hono-stripe'
47
+ *
48
+ * const app = new Hono<StripeEnv>()
49
+ * app.use(stripeMiddleware())
50
+ * app.post('/api/payment-intent', (c) => {
51
+ * c.var.stripe // typed as Stripe
52
+ * // ...
53
+ * })
54
+ * ```
55
+ */
56
+ type StripeEnv = {
57
+ Variables: StripeVariables;
58
+ };
59
+ /**
60
+ * Options for {@link stripeMiddleware}.
61
+ *
62
+ * The secret key is resolved in this order:
63
+ * 1. {@link StripeMiddlewareOptions.apiKey} (explicit)
64
+ * 2. Cloudflare Workers env binding `c.env[secretKeyVar]`
65
+ * 3. `process.env[secretKeyVar]` (Node)
66
+ */
67
+ interface StripeMiddlewareOptions {
68
+ /** Secret key passed directly. Skips env-binding / process.env resolution. */
69
+ apiKey?: string;
70
+ /** Name of the env binding / `process.env` key holding the secret key. Default: `STRIPE_SECRET_KEY`. */
71
+ secretKeyVar?: string;
72
+ /** Stripe API version override. Defaults to the SDK's pinned version. */
73
+ apiVersion?: StripeClientConfig['apiVersion'];
74
+ /**
75
+ * Extra Stripe config. Merged last, so an explicit `httpClient` here
76
+ * overrides the automatic Workers `createFetchHttpClient()` selection.
77
+ */
78
+ config?: StripeClientConfig;
79
+ }
80
+
81
+ /**
82
+ * Hono middleware that initializes a Stripe client and injects it at
83
+ * `c.var.stripe`.
84
+ *
85
+ * - Resolves the secret key from an explicit option, a Cloudflare Workers env
86
+ * binding, or `process.env` — in that order.
87
+ * - On edge runtimes (Workers) it automatically applies
88
+ * `Stripe.createFetchHttpClient()` so the SDK works without Node's HTTP stack.
89
+ * - Clients are cached per secret key and reused across requests.
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * const app = new Hono<StripeEnv>()
94
+ * app.use(stripeMiddleware()) // reads STRIPE_SECRET_KEY from env binding / process.env
95
+ * ```
96
+ */
97
+ declare const stripeMiddleware: (options?: StripeMiddlewareOptions) => MiddlewareHandler<StripeEnv>;
98
+
99
+ /**
100
+ * Read the Stripe client injected by {@link stripeMiddleware} from the context.
101
+ *
102
+ * Throws a clear error if the middleware has not run, so misconfiguration
103
+ * fails fast instead of surfacing as an opaque `undefined` later.
104
+ */
105
+ declare const getStripe: (c: Context) => Stripe;
106
+
107
+ /**
108
+ * Create a PaymentIntent using the Stripe client on the context.
109
+ *
110
+ * The returned `client_secret` is what the frontend (e.g. the
111
+ * `<stripe-payment-element>` web component from stripe-pwa-elements) needs to
112
+ * confirm the payment.
113
+ *
114
+ * Security note: decide `amount`/`currency` on the server from a trusted source
115
+ * (price IDs, a cart looked up by id) rather than trusting values sent by the
116
+ * client. See the README for the recommended pattern.
117
+ *
118
+ * Idempotency note: when the caller does not supply `options.idempotencyKey`,
119
+ * a fresh per-call `crypto.randomUUID()` is set as the idempotency key. This
120
+ * only protects stripe-node's own automatic network retries of a single
121
+ * invocation — it does NOT protect against a client double-submitting the same
122
+ * request, because every server invocation generates a brand new key. To guard
123
+ * against client-side duplicate submissions, pass a STABLE `idempotencyKey` via
124
+ * `options`, derived from the business operation (e.g. a cart id or order id),
125
+ * so retries of the same logical operation collapse to one PaymentIntent.
126
+ *
127
+ * @example
128
+ * ```ts
129
+ * app.post('/api/payment-intent', async (c) => {
130
+ * const intent = await createPaymentIntent(c, { amount: 1400, currency: 'usd' })
131
+ * return c.json({ clientSecret: intent.client_secret })
132
+ * })
133
+ * ```
134
+ */
135
+ declare const createPaymentIntent: (c: Context, params: Stripe.PaymentIntentCreateParams, options?: Stripe.RequestOptions) => Promise<Stripe.PaymentIntent>;
136
+ /**
137
+ * Create a Checkout Session.
138
+ *
139
+ * This is a thin pass-through over `stripe.checkout.sessions.create` — it does
140
+ * not hard-code a `ui_mode`, since the accepted values differ across the Stripe
141
+ * versions this package supports as a peer. To drive the frontend with a
142
+ * `client_secret` (the Checkout Sessions mode used by stripe-pwa-elements),
143
+ * pass the client-side UI mode for your Stripe version (e.g. `ui_mode: 'custom'`
144
+ * on recent Stripe, `'elements'` on older SDKs).
145
+ *
146
+ * Idempotency note: when the caller does not supply `options.idempotencyKey`,
147
+ * a fresh per-call `crypto.randomUUID()` is set as the idempotency key. This
148
+ * only protects stripe-node's own automatic network retries of a single
149
+ * invocation — it does NOT protect against a client double-submitting the same
150
+ * request, because every server invocation generates a brand new key. To guard
151
+ * against client-side duplicate submissions, pass a STABLE `idempotencyKey` via
152
+ * `options`, derived from the business operation (e.g. a cart id or order id),
153
+ * so retries of the same logical operation collapse to one Checkout Session.
154
+ *
155
+ * @example
156
+ * ```ts
157
+ * app.post('/api/checkout-session', async (c) => {
158
+ * const session = await createCheckoutSession(c, {
159
+ * ui_mode: 'custom',
160
+ * mode: 'payment',
161
+ * line_items: [{ price: 'price_123', quantity: 1 }],
162
+ * })
163
+ * return c.json({ clientSecret: session.client_secret })
164
+ * })
165
+ * ```
166
+ */
167
+ declare const createCheckoutSession: (c: Context, params: Stripe.Checkout.SessionCreateParams, options?: Stripe.RequestOptions) => Promise<Stripe.Checkout.Session>;
168
+
169
+ interface VerifyStripeSignatureOptions {
170
+ /** Webhook signing secret (`whsec_...`). */
171
+ secret: string;
172
+ /** Header carrying the signature. Default: `stripe-signature`. */
173
+ signatureHeader?: string;
174
+ /** Allowed timestamp tolerance in seconds. Defaults to Stripe's value (300s). */
175
+ tolerance?: number;
176
+ }
177
+ /**
178
+ * Verify a Stripe webhook signature and return the parsed, verified event.
179
+ *
180
+ * This is intentionally a thin primitive: it reads the raw body, verifies the
181
+ * signature with `constructEventAsync` (the async form required on Cloudflare
182
+ * Workers, where WebCrypto is async), and returns the `Stripe.Event`.
183
+ *
184
+ * The SubtleCrypto provider is only supplied on non-Node (edge) runtimes. On
185
+ * Node the provider arg is left `undefined` so stripe-node auto-selects its
186
+ * Node crypto provider — passing SubtleCrypto there would needlessly require a
187
+ * global `crypto.subtle`.
188
+ *
189
+ * It deliberately does **not** do event routing or per-type dispatch — that is
190
+ * the job of `@kotodayori/hono`, which offers typed webhook routing on top of a
191
+ * verified event. Reach for that when you outgrow this primitive.
192
+ *
193
+ * @throws {HTTPException} 400 if the signature header is missing or
194
+ * verification fails — the correct response to Stripe (a 500 would make Stripe
195
+ * retry the delivery and pollute server error monitoring).
196
+ *
197
+ * @example
198
+ * ```ts
199
+ * app.post('/api/webhook', async (c) => {
200
+ * const event = await verifyStripeSignature(c, { secret: c.env.STRIPE_WEBHOOK_SECRET })
201
+ * // hand `event` to @kotodayori/hono for typed routing, or switch on event.type
202
+ * return c.body(null, 200)
203
+ * })
204
+ * ```
205
+ */
206
+ declare const verifyStripeSignature: (c: Context, options: VerifyStripeSignatureOptions) => Promise<Stripe.Event>;
207
+
208
+ export { type StripeEnv, type StripeMiddlewareOptions, type StripeVariables, type VerifyStripeSignatureOptions, createCheckoutSession, createPaymentIntent, getStripe, isNodeRuntime, isWorkersRuntime, shouldUseFetchHttpClient, stripeMiddleware, verifyStripeSignature };
package/dist/index.js ADDED
@@ -0,0 +1,142 @@
1
+ import { getRuntimeKey, env } from 'hono/adapter';
2
+ import Stripe from 'stripe';
3
+ import { HTTPException } from 'hono/http-exception';
4
+
5
+ // src/middleware.ts
6
+ var isNodeRuntime = () => getRuntimeKey() === "node";
7
+ var isWorkersRuntime = () => getRuntimeKey() === "workerd";
8
+ var shouldUseFetchHttpClient = () => !isNodeRuntime();
9
+ var MAX_CACHE_ENTRIES = 100;
10
+ var clientCache = /* @__PURE__ */ new Map();
11
+ var optionsTokens = /* @__PURE__ */ new WeakMap();
12
+ var optionsTokenSeq = 0;
13
+ var cryptoProvider;
14
+ var buildConfig = (options) => {
15
+ const config = { ...options.config };
16
+ if (options.apiVersion) {
17
+ config.apiVersion = options.apiVersion;
18
+ }
19
+ if (!config.httpClient && shouldUseFetchHttpClient()) {
20
+ config.httpClient = Stripe.createFetchHttpClient();
21
+ }
22
+ return config;
23
+ };
24
+ var hasNonSerializableConfig = (config) => {
25
+ if (config.httpClient !== void 0) return true;
26
+ return Object.values(config).some((value) => typeof value === "function");
27
+ };
28
+ var computeOptionsToken = (options) => {
29
+ const { apiVersion, config } = options;
30
+ if (config && hasNonSerializableConfig(config)) {
31
+ return `#${++optionsTokenSeq}`;
32
+ }
33
+ try {
34
+ return JSON.stringify({ apiVersion, config });
35
+ } catch {
36
+ return `#${++optionsTokenSeq}`;
37
+ }
38
+ };
39
+ var getCacheKey = (apiKey, options) => {
40
+ let token = optionsTokens.get(options);
41
+ if (token === void 0) {
42
+ token = computeOptionsToken(options);
43
+ optionsTokens.set(options, token);
44
+ }
45
+ return `${apiKey}:${token}`;
46
+ };
47
+ var getStripeClient = (apiKey, options) => {
48
+ const opts = options ?? {};
49
+ const cacheKey = getCacheKey(apiKey, opts);
50
+ const cached = clientCache.get(cacheKey);
51
+ if (cached) return cached;
52
+ const client = new Stripe(apiKey, buildConfig(opts));
53
+ clientCache.set(cacheKey, client);
54
+ if (clientCache.size > MAX_CACHE_ENTRIES) {
55
+ const oldest = clientCache.keys().next().value;
56
+ if (oldest !== void 0) clientCache.delete(oldest);
57
+ }
58
+ return client;
59
+ };
60
+ var getCryptoProvider = () => {
61
+ if (!cryptoProvider) {
62
+ cryptoProvider = Stripe.createSubtleCryptoProvider();
63
+ }
64
+ return cryptoProvider;
65
+ };
66
+
67
+ // src/middleware.ts
68
+ var DEFAULT_SECRET_KEY_VAR = "STRIPE_SECRET_KEY";
69
+ var stripeMiddleware = (options = {}) => {
70
+ const secretKeyVar = options.secretKeyVar ?? DEFAULT_SECRET_KEY_VAR;
71
+ const staticStripe = options.apiKey ? getStripeClient(options.apiKey, options) : void 0;
72
+ return async (c, next) => {
73
+ let stripe = staticStripe;
74
+ if (!stripe) {
75
+ const apiKey = env(c)[secretKeyVar];
76
+ if (!apiKey) {
77
+ throw new Error(
78
+ `hono-stripe: Stripe secret key not found. Pass { apiKey } or set the "${secretKeyVar}" env binding / process.env value.`
79
+ );
80
+ }
81
+ stripe = getStripeClient(apiKey, options);
82
+ }
83
+ c.set("stripe", stripe);
84
+ await next();
85
+ };
86
+ };
87
+
88
+ // src/context.ts
89
+ var getStripe = (c) => {
90
+ const stripe = c.get("stripe");
91
+ if (!stripe) {
92
+ throw new Error(
93
+ "hono-stripe: Stripe client not found on context. Did you register stripeMiddleware() before this handler?"
94
+ );
95
+ }
96
+ return stripe;
97
+ };
98
+
99
+ // src/helpers.ts
100
+ var withIdempotencyKey = (options) => {
101
+ if (options?.idempotencyKey) {
102
+ return { ...options, idempotencyKey: options.idempotencyKey };
103
+ }
104
+ if (typeof globalThis.crypto?.randomUUID !== "function") {
105
+ throw new Error(
106
+ "hono-stripe: crypto.randomUUID is not available in this runtime to auto-generate an idempotency key. Pass a stable { idempotencyKey } explicitly."
107
+ );
108
+ }
109
+ return { ...options, idempotencyKey: globalThis.crypto.randomUUID() };
110
+ };
111
+ var createPaymentIntent = (c, params, options) => getStripe(c).paymentIntents.create(params, withIdempotencyKey(options));
112
+ var createCheckoutSession = (c, params, options) => getStripe(c).checkout.sessions.create(params, withIdempotencyKey(options));
113
+ var DEFAULT_SIGNATURE_HEADER = "stripe-signature";
114
+ var verifyStripeSignature = async (c, options) => {
115
+ const stripe = getStripe(c);
116
+ const signature = c.req.header(options.signatureHeader ?? DEFAULT_SIGNATURE_HEADER);
117
+ if (!signature) {
118
+ throw new HTTPException(400, {
119
+ message: "hono-stripe: missing Stripe signature header on webhook request."
120
+ });
121
+ }
122
+ const payload = await c.req.text();
123
+ const cryptoProvider2 = shouldUseFetchHttpClient() ? getCryptoProvider() : void 0;
124
+ try {
125
+ return await stripe.webhooks.constructEventAsync(
126
+ payload,
127
+ signature,
128
+ options.secret,
129
+ options.tolerance,
130
+ cryptoProvider2
131
+ );
132
+ } catch (err) {
133
+ throw new HTTPException(400, {
134
+ message: err instanceof Error ? err.message : "hono-stripe: webhook signature verification failed.",
135
+ cause: err
136
+ });
137
+ }
138
+ };
139
+
140
+ export { createCheckoutSession, createPaymentIntent, getStripe, isNodeRuntime, isWorkersRuntime, shouldUseFetchHttpClient, stripeMiddleware, verifyStripeSignature };
141
+ //# sourceMappingURL=index.js.map
142
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/runtime.ts","../src/middleware.ts","../src/context.ts","../src/helpers.ts","../src/webhook.ts"],"names":["cryptoProvider"],"mappings":";;;;;AAmBO,IAAM,aAAA,GAAgB,MAAe,aAAA,EAAc,KAAM;AAKzD,IAAM,gBAAA,GAAmB,MAAe,aAAA,EAAc,KAAM;AAU5D,IAAM,wBAAA,GAA2B,MAAe,CAAC,aAAA;AAKxD,IAAM,iBAAA,GAAoB,GAAA;AAK1B,IAAM,WAAA,uBAAkB,GAAA,EAAoB;AAO5C,IAAI,aAAA,uBAAoB,OAAA,EAAwB;AAChD,IAAI,eAAA,GAAkB,CAAA;AAGtB,IAAI,cAAA;AAMJ,IAAM,WAAA,GAAc,CAAC,OAAA,KAAyD;AAC5E,EAAA,MAAM,MAAA,GAA6B,EAAE,GAAG,OAAA,CAAQ,MAAA,EAAO;AACvD,EAAA,IAAI,QAAQ,UAAA,EAAY;AACtB,IAAA,MAAA,CAAO,aAAa,OAAA,CAAQ,UAAA;AAAA,EAC9B;AACA,EAAA,IAAI,CAAC,MAAA,CAAO,UAAA,IAAc,wBAAA,EAAyB,EAAG;AACpD,IAAA,MAAA,CAAO,UAAA,GAAa,OAAO,qBAAA,EAAsB;AAAA,EACnD;AACA,EAAA,OAAO,MAAA;AACT,CAAA;AAYA,IAAM,wBAAA,GAA2B,CAAC,MAAA,KAAwC;AACxE,EAAA,IAAI,MAAA,CAAO,UAAA,KAAe,MAAA,EAAW,OAAO,IAAA;AAC5C,EAAA,OAAO,MAAA,CAAO,OAAO,MAAM,CAAA,CAAE,KAAK,CAAC,KAAA,KAAU,OAAO,KAAA,KAAU,UAAU,CAAA;AAC1E,CAAA;AAYA,IAAM,mBAAA,GAAsB,CAAC,OAAA,KAA6C;AACxE,EAAA,MAAM,EAAE,UAAA,EAAY,MAAA,EAAO,GAAI,OAAA;AAC/B,EAAA,IAAI,MAA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AA,GAAiB,wBAAA,EAAyB,GAAI,iBAAA,EAAkB,GAAI,MAAA;AAC1E,EAAA,IAAI;AACF,IAAA,OAAO,MAAM,OAAO,QAAA,CAAS,mBAAA;AAAA,MAC3B,OAAA;AAAA,MACA,SAAA;AAAA,MACA,OAAA,CAAQ,MAAA;AAAA,MACR,OAAA,CAAQ,SAAA;AAAA,MACRA;AAAA,KACF;AAAA,EACF,SAAS,GAAA,EAAK;AACZ,IAAA,MAAM,IAAI,cAAc,GAAA,EAAK;AAAA,MAC3B,OAAA,EACE,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,qDAAA;AAAA,MACvC,KAAA,EAAO;AAAA,KACR,CAAA;AAAA,EACH;AACF","file":"index.js","sourcesContent":["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","import type { MiddlewareHandler } from 'hono'\nimport { env } from 'hono/adapter'\nimport { getStripeClient } from './runtime'\nimport type { StripeEnv, StripeMiddlewareOptions } from './types'\n\nconst DEFAULT_SECRET_KEY_VAR = 'STRIPE_SECRET_KEY'\n\n/**\n * Hono middleware that initializes a Stripe client and injects it at\n * `c.var.stripe`.\n *\n * - Resolves the secret key from an explicit option, a Cloudflare Workers env\n * binding, or `process.env` — in that order.\n * - On edge runtimes (Workers) it automatically applies\n * `Stripe.createFetchHttpClient()` so the SDK works without Node's HTTP stack.\n * - Clients are cached per secret key and reused across requests.\n *\n * @example\n * ```ts\n * const app = new Hono<StripeEnv>()\n * app.use(stripeMiddleware()) // reads STRIPE_SECRET_KEY from env binding / process.env\n * ```\n */\nexport const stripeMiddleware = (\n options: StripeMiddlewareOptions = {},\n): MiddlewareHandler<StripeEnv> => {\n const secretKeyVar = options.secretKeyVar ?? DEFAULT_SECRET_KEY_VAR\n // When apiKey is known at registration time, build the client once and reuse it.\n const staticStripe = options.apiKey ? getStripeClient(options.apiKey, options) : undefined\n return async (c, next) => {\n let stripe = staticStripe\n if (!stripe) {\n const apiKey = env<Record<string, string | undefined>>(c)[secretKeyVar]\n if (!apiKey) {\n throw new Error(\n `hono-stripe: Stripe secret key not found. Pass { apiKey } or set the \"${secretKeyVar}\" env binding / process.env value.`,\n )\n }\n stripe = getStripeClient(apiKey, options)\n }\n c.set('stripe', stripe)\n await next()\n }\n}\n","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 type { Context } from 'hono'\nimport type Stripe from 'stripe'\nimport { getStripe } from './context'\n\n/**\n * Return a copy of `options` that is guaranteed to carry an `idempotencyKey`.\n *\n * If the caller already supplied `options.idempotencyKey` it is preserved\n * untouched; otherwise a freshly generated `crypto.randomUUID()` is used. The\n * caller's object is never mutated — a new object is always returned.\n *\n * Throws a clear error (rather than a raw `TypeError`) if `crypto.randomUUID`\n * is unavailable in the current runtime — pass a stable `options.idempotencyKey`\n * explicitly in that case instead of relying on auto-generation.\n */\nconst withIdempotencyKey = (options?: Stripe.RequestOptions): Stripe.RequestOptions => {\n if (options?.idempotencyKey) {\n return { ...options, idempotencyKey: options.idempotencyKey }\n }\n if (typeof globalThis.crypto?.randomUUID !== 'function') {\n throw new Error(\n 'hono-stripe: crypto.randomUUID is not available in this runtime to auto-generate an idempotency key. Pass a stable { idempotencyKey } explicitly.',\n )\n }\n return { ...options, idempotencyKey: globalThis.crypto.randomUUID() }\n}\n\n/**\n * Create a PaymentIntent using the Stripe client on the context.\n *\n * The returned `client_secret` is what the frontend (e.g. the\n * `<stripe-payment-element>` web component from stripe-pwa-elements) needs to\n * confirm the payment.\n *\n * Security note: decide `amount`/`currency` on the server from a trusted source\n * (price IDs, a cart looked up by id) rather than trusting values sent by the\n * client. See the README for the recommended pattern.\n *\n * Idempotency note: when the caller does not supply `options.idempotencyKey`,\n * a fresh per-call `crypto.randomUUID()` is set as the idempotency key. This\n * only protects stripe-node's own automatic network retries of a single\n * invocation — it does NOT protect against a client double-submitting the same\n * request, because every server invocation generates a brand new key. To guard\n * against client-side duplicate submissions, pass a STABLE `idempotencyKey` via\n * `options`, derived from the business operation (e.g. a cart id or order id),\n * so retries of the same logical operation collapse to one PaymentIntent.\n *\n * @example\n * ```ts\n * app.post('/api/payment-intent', async (c) => {\n * const intent = await createPaymentIntent(c, { amount: 1400, currency: 'usd' })\n * return c.json({ clientSecret: intent.client_secret })\n * })\n * ```\n */\nexport const createPaymentIntent = (\n c: Context,\n params: Stripe.PaymentIntentCreateParams,\n options?: Stripe.RequestOptions,\n): Promise<Stripe.PaymentIntent> =>\n getStripe(c).paymentIntents.create(params, withIdempotencyKey(options))\n\n/**\n * Create a Checkout Session.\n *\n * This is a thin pass-through over `stripe.checkout.sessions.create` — it does\n * not hard-code a `ui_mode`, since the accepted values differ across the Stripe\n * versions this package supports as a peer. To drive the frontend with a\n * `client_secret` (the Checkout Sessions mode used by stripe-pwa-elements),\n * pass the client-side UI mode for your Stripe version (e.g. `ui_mode: 'custom'`\n * on recent Stripe, `'elements'` on older SDKs).\n *\n * Idempotency note: when the caller does not supply `options.idempotencyKey`,\n * a fresh per-call `crypto.randomUUID()` is set as the idempotency key. This\n * only protects stripe-node's own automatic network retries of a single\n * invocation — it does NOT protect against a client double-submitting the same\n * request, because every server invocation generates a brand new key. To guard\n * against client-side duplicate submissions, pass a STABLE `idempotencyKey` via\n * `options`, derived from the business operation (e.g. a cart id or order id),\n * so retries of the same logical operation collapse to one Checkout Session.\n *\n * @example\n * ```ts\n * app.post('/api/checkout-session', async (c) => {\n * const session = await createCheckoutSession(c, {\n * ui_mode: 'custom',\n * mode: 'payment',\n * line_items: [{ price: 'price_123', quantity: 1 }],\n * })\n * return c.json({ clientSecret: session.client_secret })\n * })\n * ```\n */\nexport const createCheckoutSession = (\n c: Context,\n params: Stripe.Checkout.SessionCreateParams,\n options?: Stripe.RequestOptions,\n): Promise<Stripe.Checkout.Session> =>\n getStripe(c).checkout.sessions.create(params, withIdempotencyKey(options))\n","import type { Context } from 'hono'\nimport { HTTPException } from 'hono/http-exception'\nimport type Stripe from 'stripe'\nimport { getStripe } from './context'\nimport { getCryptoProvider, shouldUseFetchHttpClient } from './runtime'\n\nconst DEFAULT_SIGNATURE_HEADER = 'stripe-signature'\n\nexport interface VerifyStripeSignatureOptions {\n /** Webhook signing secret (`whsec_...`). */\n secret: string\n /** Header carrying the signature. Default: `stripe-signature`. */\n signatureHeader?: string\n /** Allowed timestamp tolerance in seconds. Defaults to Stripe's value (300s). */\n tolerance?: number\n}\n\n/**\n * Verify a Stripe webhook signature and return the parsed, verified event.\n *\n * This is intentionally a thin primitive: it reads the raw body, verifies the\n * signature with `constructEventAsync` (the async form required on Cloudflare\n * Workers, where WebCrypto is async), and returns the `Stripe.Event`.\n *\n * The SubtleCrypto provider is only supplied on non-Node (edge) runtimes. On\n * Node the provider arg is left `undefined` so stripe-node auto-selects its\n * Node crypto provider — passing SubtleCrypto there would needlessly require a\n * global `crypto.subtle`.\n *\n * It deliberately does **not** do event routing or per-type dispatch — that is\n * the job of `@kotodayori/hono`, which offers typed webhook routing on top of a\n * verified event. Reach for that when you outgrow this primitive.\n *\n * @throws {HTTPException} 400 if the signature header is missing or\n * verification fails — the correct response to Stripe (a 500 would make Stripe\n * retry the delivery and pollute server error monitoring).\n *\n * @example\n * ```ts\n * app.post('/api/webhook', async (c) => {\n * const event = await verifyStripeSignature(c, { secret: c.env.STRIPE_WEBHOOK_SECRET })\n * // hand `event` to @kotodayori/hono for typed routing, or switch on event.type\n * return c.body(null, 200)\n * })\n * ```\n */\nexport const verifyStripeSignature = async (\n c: Context,\n options: VerifyStripeSignatureOptions,\n): Promise<Stripe.Event> => {\n const stripe = getStripe(c)\n const signature = c.req.header(options.signatureHeader ?? DEFAULT_SIGNATURE_HEADER)\n if (!signature) {\n throw new HTTPException(400, {\n message: 'hono-stripe: missing Stripe signature header on webhook request.',\n })\n }\n const payload = await c.req.text()\n // Only supply the SubtleCrypto provider on edge runtimes that need it. When\n // the provider arg is omitted (`undefined`), stripe-node auto-selects the\n // right one per runtime — its Node crypto provider on Node, SubtleCrypto on\n // the edge. Forcing SubtleCrypto onto Node would needlessly require a global\n // `crypto.subtle`, so we let stripe-node pick on Node.\n const cryptoProvider = shouldUseFetchHttpClient() ? getCryptoProvider() : undefined\n try {\n return await stripe.webhooks.constructEventAsync(\n payload,\n signature,\n options.secret,\n options.tolerance,\n cryptoProvider,\n )\n } catch (err) {\n throw new HTTPException(400, {\n message:\n err instanceof Error ? err.message : 'hono-stripe: webhook signature verification failed.',\n cause: err,\n })\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "hono-stripe",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.1",
4
+ "description": "Stripe middleware and helpers for Hono — Stripe client injection, PaymentIntent/Checkout Session helpers, and Webhook signature verification. Works on Cloudflare Workers and Node.",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "sideEffects": false,
22
+ "keywords": [
23
+ "hono",
24
+ "stripe",
25
+ "middleware",
26
+ "payment",
27
+ "cloudflare-workers",
28
+ "edge",
29
+ "webhook",
30
+ "payment-intent",
31
+ "checkout"
32
+ ],
33
+ "author": "hideokamoto",
34
+ "license": "MIT",
35
+ "engines": {
36
+ "node": ">=20"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/hideokamoto/hono-stripe.git"
41
+ },
42
+ "homepage": "https://github.com/hideokamoto/hono-stripe#readme",
43
+ "bugs": {
44
+ "url": "https://github.com/hideokamoto/hono-stripe/issues"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public",
48
+ "provenance": true
49
+ },
50
+ "peerDependencies": {
51
+ "hono": ">=4",
52
+ "stripe": ">=17"
53
+ },
54
+ "devDependencies": {
55
+ "@size-limit/file": "^11.1.6",
56
+ "@types/node": "^22.10.2",
57
+ "hono": "^4.12.25",
58
+ "size-limit": "^11.1.6",
59
+ "stripe": "^22.2.1",
60
+ "tsup": "^8.5.1",
61
+ "typescript": "^6.0.3",
62
+ "vitest": "^4.1.9"
63
+ },
64
+ "scripts": {
65
+ "build": "tsup",
66
+ "dev": "tsup --watch",
67
+ "typecheck": "tsc --noEmit",
68
+ "test": "vitest run",
69
+ "test:watch": "vitest",
70
+ "size": "size-limit",
71
+ "size:json": "size-limit --json"
72
+ }
6
73
  }