hono-stripe 0.0.1 → 1.0.2
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/README.md +253 -67
- package/dist/chunk-TV73NTMC.js +77 -0
- package/dist/chunk-TV73NTMC.js.map +1 -0
- package/dist/index.cjs +87 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +76 -175
- package/dist/index.d.ts +76 -175
- package/dist/index.js +67 -110
- package/dist/index.js.map +1 -1
- 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 +72 -17
package/dist/index.cjs
CHANGED
|
@@ -1,14 +1,93 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var adapter = require('hono/adapter');
|
|
4
|
-
var Stripe = require('stripe');
|
|
5
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');
|
|
6
7
|
|
|
7
8
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
8
9
|
|
|
9
|
-
var
|
|
10
|
+
var Stripe2__default = /*#__PURE__*/_interopDefault(Stripe2);
|
|
10
11
|
|
|
11
|
-
// src/
|
|
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
|
+
};
|
|
12
91
|
var isNodeRuntime = () => adapter.getRuntimeKey() === "node";
|
|
13
92
|
var isWorkersRuntime = () => adapter.getRuntimeKey() === "workerd";
|
|
14
93
|
var shouldUseFetchHttpClient = () => !isNodeRuntime();
|
|
@@ -16,14 +95,13 @@ var MAX_CACHE_ENTRIES = 100;
|
|
|
16
95
|
var clientCache = /* @__PURE__ */ new Map();
|
|
17
96
|
var optionsTokens = /* @__PURE__ */ new WeakMap();
|
|
18
97
|
var optionsTokenSeq = 0;
|
|
19
|
-
var cryptoProvider;
|
|
20
98
|
var buildConfig = (options) => {
|
|
21
99
|
const config = { ...options.config };
|
|
22
100
|
if (options.apiVersion) {
|
|
23
101
|
config.apiVersion = options.apiVersion;
|
|
24
102
|
}
|
|
25
103
|
if (!config.httpClient && shouldUseFetchHttpClient()) {
|
|
26
|
-
config.httpClient =
|
|
104
|
+
config.httpClient = Stripe2__default.default.createFetchHttpClient();
|
|
27
105
|
}
|
|
28
106
|
return config;
|
|
29
107
|
};
|
|
@@ -55,7 +133,7 @@ var getStripeClient = (apiKey, options) => {
|
|
|
55
133
|
const cacheKey = getCacheKey(apiKey, opts);
|
|
56
134
|
const cached = clientCache.get(cacheKey);
|
|
57
135
|
if (cached) return cached;
|
|
58
|
-
const client = new
|
|
136
|
+
const client = new Stripe2__default.default(apiKey, buildConfig(opts));
|
|
59
137
|
clientCache.set(cacheKey, client);
|
|
60
138
|
if (clientCache.size > MAX_CACHE_ENTRIES) {
|
|
61
139
|
const oldest = clientCache.keys().next().value;
|
|
@@ -63,12 +141,6 @@ var getStripeClient = (apiKey, options) => {
|
|
|
63
141
|
}
|
|
64
142
|
return client;
|
|
65
143
|
};
|
|
66
|
-
var getCryptoProvider = () => {
|
|
67
|
-
if (!cryptoProvider) {
|
|
68
|
-
cryptoProvider = Stripe__default.default.createSubtleCryptoProvider();
|
|
69
|
-
}
|
|
70
|
-
return cryptoProvider;
|
|
71
|
-
};
|
|
72
144
|
|
|
73
145
|
// src/middleware.ts
|
|
74
146
|
var DEFAULT_SECRET_KEY_VAR = "STRIPE_SECRET_KEY";
|
|
@@ -91,65 +163,12 @@ var stripeMiddleware = (options = {}) => {
|
|
|
91
163
|
};
|
|
92
164
|
};
|
|
93
165
|
|
|
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
166
|
exports.getStripe = getStripe;
|
|
149
167
|
exports.isNodeRuntime = isNodeRuntime;
|
|
150
168
|
exports.isWorkersRuntime = isWorkersRuntime;
|
|
151
169
|
exports.shouldUseFetchHttpClient = shouldUseFetchHttpClient;
|
|
170
|
+
exports.stripeErrorHandler = stripeErrorHandler;
|
|
171
|
+
exports.stripeErrorResponse = stripeErrorResponse;
|
|
152
172
|
exports.stripeMiddleware = stripeMiddleware;
|
|
153
|
-
exports.verifyStripeSignature = verifyStripeSignature;
|
|
154
173
|
//# sourceMappingURL=index.cjs.map
|
|
155
174
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +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"],"mappings":";;;;;;;;;;;AAmBO,I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A,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"]}
|
|
1
|
+
{"version":3,"sources":["../src/context.ts","../src/errors.ts","../src/runtime.ts","../src/middleware.ts"],"names":["Stripe","getDeclineMessage","isSoftDecline","HTTPException","getRuntimeKey","env"],"mappings":";;;;;;;;;;;;AASO,IAAM,SAAA,GAAY,CAAC,CAAA,KAAuB;AAC/C,EAAA,MAAM,MAAA,GAAS,CAAA,CAAE,GAAA,CAAI,QAAQ,CAAA;AAC7B,EAAA,IAAI,CAAC,MAAA,EAAQ;AACX,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KACF;AAAA,EACF;AACA,EAAA,OAAO,MAAA;AACT;ACZA,IAAM,EAAE,QAAO,GAAIA,wBAAA;AAOnB,IAAM,UAAU,CAAC,GAAA,EAAc,UAC7B,KAAA,CAAM,IAAA,CAAK,CAAC,IAAA,KAAS;AACnB,EAAA,MAAM,IAAA,GAAQ,OAA8C,IAAI,CAAA;AAChE,EAAA,OAAO,OAAO,IAAA,KAAS,UAAA,IAAc,GAAA,YAAe,IAAA;AACtD,CAAC,CAAA;AAOH,IAAM,uBAAA,uBAA8B,GAAA,CAAI;AAAA,EACtC,YAAA;AAAA,EACA,WAAA;AAAA,EACA,aAAA;AAAA,EACA;AACF,CAAC,CAAA;AA0BD,IAAM,IAAA,GAAO,CAAC,CAAA,EAAY,MAAA,EAAgB,SAA0B,CAAA,CAAE,IAAA,CAAK,MAAM,MAAe,CAAA;AAmBzF,IAAM,mBAAA,GAAsB,CAAC,CAAA,EAAY,GAAA,EAAkB,MAAA,KAA8B;AAC9F,EAAA,MAAM,IAAA,GAAO,CACX,MAAA,EACA,IAAA,EACA,SACA,KAAA,KAEA,IAAA,CAAK,GAAG,MAAA,EAAQ;AAAA,IACd,KAAA,EAAO,EAAE,IAAA,EAAM,OAAA,EAAS,WAAW,GAAA,CAAI,SAAA,EAAW,GAAG,KAAA;AAAM,GAC5D,CAAA;AAEH,EAAA,IAAI,GAAA,YAAe,OAAO,eAAA,EAAiB;AACzC,IAAA,MAAM,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;AAChC,EAAA,IAAI,WAAA,CAAY,OAAO,iBAAA,EAAmB;AACxC,IAAA,MAAM,MAAA,GAAS,WAAA,CAAY,IAAA,EAAK,CAAE,MAAK,CAAE,KAAA;AACzC,IAAA,IAAI,MAAA,KAAW,MAAA,EAAW,WAAA,CAAY,MAAA,CAAO,MAAM,CAAA;AAAA,EACrD;AACA,EAAA,OAAO,MAAA;AACT,CAAA;;;AChJA,IAAM,sBAAA,GAAyB,mBAAA;AAkBxB,IAAM,gBAAA,GAAmB,CAC9B,OAAA,GAAmC,EAAC,KACH;AACjC,EAAA,MAAM,YAAA,GAAe,QAAQ,YAAA,IAAgB,sBAAA;AAE7C,EAAA,MAAM,eAAe,OAAA,CAAQ,MAAA,GAAS,gBAAgB,OAAA,CAAQ,MAAA,EAAQ,OAAO,CAAA,GAAI,MAAA;AACjF,EAAA,OAAO,OAAO,GAAG,IAAA,KAAS;AACxB,IAAA,IAAI,MAAA,GAAS,YAAA;AACb,IAAA,IAAI,CAAC,MAAA,EAAQ;AACX,MAAA,MAAM,MAAA,GAASK,WAAA,CAAwC,CAAC,CAAA,CAAE,YAAY,CAAA;AACtE,MAAA,IAAI,CAAC,MAAA,EAAQ;AACX,QAAA,MAAM,IAAI,KAAA;AAAA,UACR,yEAAyE,YAAY,CAAA,kCAAA;AAAA,SACvF;AAAA,MACF;AACA,MAAA,MAAA,GAAS,eAAA,CAAgB,QAAQ,OAAO,CAAA;AAAA,IAC1C;AACA,IAAA,CAAA,CAAE,GAAA,CAAI,UAAU,MAAM,CAAA;AACtB,IAAA,MAAM,IAAA,EAAK;AAAA,EACb,CAAA;AACF","file":"index.cjs","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 type { Context, ErrorHandler } from 'hono'\nimport { HTTPException } from 'hono/http-exception'\nimport Stripe from 'stripe'\nimport { getDeclineMessage, isSoftDecline, type Locale } from 'stripe-decline-codes'\n\nconst { errors } = Stripe\n\n/**\n * `instanceof` against SDK error classes that may be missing on some supported\n * stripe versions (peer range is >=17). An undefined class is skipped instead\n * of throwing a TypeError.\n */\nconst isAnyOf = (err: unknown, names: string[]): boolean =>\n names.some((name) => {\n const ctor = (errors as unknown as Record<string, unknown>)[name]\n return typeof ctor === 'function' && err instanceof ctor\n })\n\n/**\n * Decline codes that must not be explained to the customer — revealing that a\n * card is flagged lets fraudsters probe stolen cards. They get the same generic\n * response as `generic_decline`.\n */\nconst SENSITIVE_DECLINE_CODES = new Set([\n 'fraudulent',\n 'lost_card',\n 'stolen_card',\n 'merchant_blacklist',\n])\n\n/** Error body shape returned by {@link stripeErrorHandler}. */\nexport interface StripeErrorBody {\n error: {\n type: string\n /** Developer-facing message (Stripe's raw message — English, technical). */\n message: string\n /** Stripe error code / decline code when present. */\n code?: string\n /**\n * Localized, user-facing guidance for card declines — from\n * `stripe-decline-codes`. Only set on `card_error` when the decline code\n * is known and `locale` matched a translation.\n */\n userMessage?: string\n /**\n * For card declines: whether retrying as-is may succeed (soft decline).\n * `false` means the customer needs a different payment method.\n */\n retryable?: boolean\n /** Stripe request id — safe to surface, useful for support tickets. */\n requestId?: string\n }\n}\n\nconst json = (c: Context, status: number, body: StripeErrorBody) => c.json(body, status as never)\n\ntype StripeError = InstanceType<typeof Stripe.errors.StripeError>\n\n/**\n * Map a `StripeError` to an HTTP response.\n *\n * - `StripeCardError` → 402 (message/decline_code are user-facing, safe;\n * adds localized `userMessage` and `retryable` from stripe-decline-codes)\n * - `StripeInvalidRequestError` / `TemporarySessionExpiredError` → 400\n * - `StripeIdempotencyError` → 409\n * - `StripeSignatureVerificationError` → 400 (raised by `constructEvent` when\n * it escapes our wrappers — e.g. raw SDK verification in user code)\n * - `StripeRateLimitError` / `RateLimitError` → 429\n * - `StripeConnectionError` / `StripeAPIError` → 502 (upstream failure)\n * - `StripeAuthenticationError` / `StripePermissionError` → 500 with a generic\n * message — Stripe's raw message can leak account/key details\n * - Anything else with a client-error `statusCode` → that status; else 502\n */\nexport const stripeErrorResponse = (c: Context, err: StripeError, locale?: Locale): Response => {\n const body = (\n status: number,\n type: string,\n message: string,\n extra?: Partial<StripeErrorBody['error']>,\n ): Response =>\n json(c, status, {\n error: { type, message, requestId: err.requestId, ...extra },\n })\n\n if (err instanceof errors.StripeCardError) {\n const declineCode = err.decline_code || err.code\n if (declineCode && SENSITIVE_DECLINE_CODES.has(declineCode)) {\n return body(402, 'card_error', 'Your card was declined.', {\n code: 'generic_decline',\n userMessage: getDeclineMessage('generic_decline', locale),\n retryable: isSoftDecline('generic_decline'),\n })\n }\n return body(402, 'card_error', err.message, {\n code: declineCode,\n userMessage: declineCode ? getDeclineMessage(declineCode, locale) : undefined,\n // Only a real decline_code classifies soft/hard; `card_declined` etc.\n // in `err.code` say nothing about retryability.\n retryable: err.decline_code ? isSoftDecline(err.decline_code) : undefined,\n })\n }\n if (\n err instanceof errors.StripeInvalidRequestError ||\n err instanceof errors.TemporarySessionExpiredError\n ) {\n return body(400, 'invalid_request', err.message, { code: err.code })\n }\n if (err instanceof errors.StripeIdempotencyError) {\n return body(409, 'idempotency_error', err.message, { code: err.code })\n }\n if (err instanceof errors.StripeSignatureVerificationError) {\n return body(400, 'signature_verification_failed', 'Webhook signature verification failed.')\n }\n if (isAnyOf(err, ['StripeRateLimitError', 'RateLimitError'])) {\n return body(429, 'rate_limit', 'Stripe rate limit reached — retry the request.')\n }\n if (err instanceof errors.StripeConnectionError || err instanceof errors.StripeAPIError) {\n return body(502, 'stripe_unavailable', 'Stripe request failed upstream — safe to retry.')\n }\n if (\n err instanceof errors.StripeAuthenticationError ||\n err instanceof errors.StripePermissionError ||\n isAnyOf(err, ['StripeOAuthError'])\n ) {\n return body(500, 'stripe_auth_error', 'Stripe integration is misconfigured.')\n }\n if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 500) {\n return body(err.statusCode, 'stripe_error', err.message, { code: err.code })\n }\n return body(502, 'stripe_error', 'Stripe request failed.')\n}\n\nexport interface StripeErrorHandlerOptions {\n /**\n * Locale for card-decline `userMessage` — `'en'` (default) or `'ja'`,\n * resolved via `stripe-decline-codes`. Accepts a per-request function, e.g.\n * to follow the `Accept-Language` header:\n * `locale: (c) => c.req.header('accept-language')?.startsWith('ja') ? 'ja' : 'en'`\n */\n locale?: Locale | ((c: Context) => Locale | undefined)\n /**\n * Called for errors that are NOT `StripeError` (after HTTPException\n * passthrough). Default: generic `500 { error: { type: 'internal_error' } }`.\n */\n fallback?: (err: Error, c: Context) => Response | Promise<Response>\n}\n\n/**\n * Hono `onError` handler that maps Stripe SDK errors to the right HTTP status\n * instead of letting every Stripe failure become a 500 (or worse, a 500 that\n * Stripe webhooks then retry forever).\n *\n * Covers errors thrown anywhere in the app — route handlers calling\n * `getStripe(c)` directly, `stripeWebhook` handlers, the `/return` lookup —\n * not just a specific helper. HTTPExceptions (e.g. the 400s thrown by\n * `verifyStripeSignature`) pass through untouched.\n *\n * Card declines additionally carry `error.userMessage` (localized via\n * `stripe-decline-codes`) and `error.retryable` (soft-decline detection), so\n * clients can distinguish \"try again\" from \"use another card\".\n *\n * @example\n * ```ts\n * import { stripeErrorHandler } from 'hono-stripe'\n * app.onError(stripeErrorHandler({ locale: 'ja' }))\n * ```\n */\nexport const stripeErrorHandler = (options?: StripeErrorHandlerOptions): ErrorHandler => {\n return (err, c) => {\n if (err instanceof HTTPException) return err.getResponse()\n if (err instanceof errors.StripeError) {\n const locale = typeof options?.locale === 'function' ? options.locale(c) : options?.locale\n return stripeErrorResponse(c, err, locale)\n }\n if (options?.fallback) return options.fallback(err, c)\n return json(c, 500, {\n error: { type: 'internal_error', message: 'Internal server error' },\n })\n }\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","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"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,82 +1,92 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Context, ErrorHandler, MiddlewareHandler } from 'hono';
|
|
2
2
|
import Stripe from 'stripe';
|
|
3
|
+
import { Locale } from 'stripe-decline-codes';
|
|
4
|
+
import { S as StripeMiddlewareOptions, a as StripeEnv } from './types-D7SNBUi7.cjs';
|
|
5
|
+
export { b as StripeVariables, i as isNodeRuntime, c as isWorkersRuntime, s as shouldUseFetchHttpClient } from './types-D7SNBUi7.cjs';
|
|
3
6
|
|
|
4
7
|
/**
|
|
5
|
-
*
|
|
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.
|
|
8
|
+
* Read the Stripe client injected by {@link stripeMiddleware} from the context.
|
|
25
9
|
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
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.
|
|
10
|
+
* Throws a clear error if the middleware has not run, so misconfiguration
|
|
11
|
+
* fails fast instead of surfacing as an opaque `undefined` later.
|
|
30
12
|
*/
|
|
31
|
-
declare const
|
|
13
|
+
declare const getStripe: (c: Context) => Stripe;
|
|
32
14
|
|
|
15
|
+
/** Error body shape returned by {@link stripeErrorHandler}. */
|
|
16
|
+
interface StripeErrorBody {
|
|
17
|
+
error: {
|
|
18
|
+
type: string;
|
|
19
|
+
/** Developer-facing message (Stripe's raw message — English, technical). */
|
|
20
|
+
message: string;
|
|
21
|
+
/** Stripe error code / decline code when present. */
|
|
22
|
+
code?: string;
|
|
23
|
+
/**
|
|
24
|
+
* Localized, user-facing guidance for card declines — from
|
|
25
|
+
* `stripe-decline-codes`. Only set on `card_error` when the decline code
|
|
26
|
+
* is known and `locale` matched a translation.
|
|
27
|
+
*/
|
|
28
|
+
userMessage?: string;
|
|
29
|
+
/**
|
|
30
|
+
* For card declines: whether retrying as-is may succeed (soft decline).
|
|
31
|
+
* `false` means the customer needs a different payment method.
|
|
32
|
+
*/
|
|
33
|
+
retryable?: boolean;
|
|
34
|
+
/** Stripe request id — safe to surface, useful for support tickets. */
|
|
35
|
+
requestId?: string;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
type StripeError = InstanceType<typeof Stripe.errors.StripeError>;
|
|
33
39
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
40
|
+
* Map a `StripeError` to an HTTP response.
|
|
41
|
+
*
|
|
42
|
+
* - `StripeCardError` → 402 (message/decline_code are user-facing, safe;
|
|
43
|
+
* adds localized `userMessage` and `retryable` from stripe-decline-codes)
|
|
44
|
+
* - `StripeInvalidRequestError` / `TemporarySessionExpiredError` → 400
|
|
45
|
+
* - `StripeIdempotencyError` → 409
|
|
46
|
+
* - `StripeSignatureVerificationError` → 400 (raised by `constructEvent` when
|
|
47
|
+
* it escapes our wrappers — e.g. raw SDK verification in user code)
|
|
48
|
+
* - `StripeRateLimitError` / `RateLimitError` → 429
|
|
49
|
+
* - `StripeConnectionError` / `StripeAPIError` → 502 (upstream failure)
|
|
50
|
+
* - `StripeAuthenticationError` / `StripePermissionError` → 500 with a generic
|
|
51
|
+
* message — Stripe's raw message can leak account/key details
|
|
52
|
+
* - Anything else with a client-error `statusCode` → that status; else 502
|
|
36
53
|
*/
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
54
|
+
declare const stripeErrorResponse: (c: Context, err: StripeError, locale?: Locale) => Response;
|
|
55
|
+
interface StripeErrorHandlerOptions {
|
|
56
|
+
/**
|
|
57
|
+
* Locale for card-decline `userMessage` — `'en'` (default) or `'ja'`,
|
|
58
|
+
* resolved via `stripe-decline-codes`. Accepts a per-request function, e.g.
|
|
59
|
+
* to follow the `Accept-Language` header:
|
|
60
|
+
* `locale: (c) => c.req.header('accept-language')?.startsWith('ja') ? 'ja' : 'en'`
|
|
61
|
+
*/
|
|
62
|
+
locale?: Locale | ((c: Context) => Locale | undefined);
|
|
63
|
+
/**
|
|
64
|
+
* Called for errors that are NOT `StripeError` (after HTTPException
|
|
65
|
+
* passthrough). Default: generic `500 { error: { type: 'internal_error' } }`.
|
|
66
|
+
*/
|
|
67
|
+
fallback?: (err: Error, c: Context) => Response | Promise<Response>;
|
|
68
|
+
}
|
|
40
69
|
/**
|
|
41
|
-
* Hono `
|
|
70
|
+
* Hono `onError` handler that maps Stripe SDK errors to the right HTTP status
|
|
71
|
+
* instead of letting every Stripe failure become a 500 (or worse, a 500 that
|
|
72
|
+
* Stripe webhooks then retry forever).
|
|
73
|
+
*
|
|
74
|
+
* Covers errors thrown anywhere in the app — route handlers calling
|
|
75
|
+
* `getStripe(c)` directly, `stripeWebhook` handlers, the `/return` lookup —
|
|
76
|
+
* not just a specific helper. HTTPExceptions (e.g. the 400s thrown by
|
|
77
|
+
* `verifyStripeSignature`) pass through untouched.
|
|
78
|
+
*
|
|
79
|
+
* Card declines additionally carry `error.userMessage` (localized via
|
|
80
|
+
* `stripe-decline-codes`) and `error.retryable` (soft-decline detection), so
|
|
81
|
+
* clients can distinguish "try again" from "use another card".
|
|
42
82
|
*
|
|
43
83
|
* @example
|
|
44
84
|
* ```ts
|
|
45
|
-
* import {
|
|
46
|
-
*
|
|
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
|
-
* })
|
|
85
|
+
* import { stripeErrorHandler } from 'hono-stripe'
|
|
86
|
+
* app.onError(stripeErrorHandler({ locale: 'ja' }))
|
|
54
87
|
* ```
|
|
55
88
|
*/
|
|
56
|
-
|
|
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
|
-
}
|
|
89
|
+
declare const stripeErrorHandler: (options?: StripeErrorHandlerOptions) => ErrorHandler;
|
|
80
90
|
|
|
81
91
|
/**
|
|
82
92
|
* Hono middleware that initializes a Stripe client and injects it at
|
|
@@ -96,113 +106,4 @@ interface StripeMiddlewareOptions {
|
|
|
96
106
|
*/
|
|
97
107
|
declare const stripeMiddleware: (options?: StripeMiddlewareOptions) => MiddlewareHandler<StripeEnv>;
|
|
98
108
|
|
|
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 };
|
|
109
|
+
export { StripeEnv, type StripeErrorBody, type StripeErrorHandlerOptions, StripeMiddlewareOptions, getStripe, stripeErrorHandler, stripeErrorResponse, stripeMiddleware };
|