@neon-pixels/stripe 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Neon Pixels Studio
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,91 @@
1
- # Temporary Holding Version
1
+ # @neon-pixels/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
+ The Stripe-facing mechanics for a subscription app: a client, webhook verification, subscription mapping, and checkout and billing portal helpers. Prices, plans, limits, and your subscriptions table stay in your app. Nothing here reads `process.env` or a framework's runtime config; pass every value in.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ pnpm add @neon-pixels/stripe stripe
9
+ ```
10
+
11
+ `stripe` is a peer dependency (`^23.0.0`). Your installed SDK version is the API version pin; this package never passes one.
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import type Stripe from "stripe";
17
+ import {
18
+ constructWebhookEvent,
19
+ createBillingPortalSession,
20
+ createCheckoutSession,
21
+ createStripeClient,
22
+ extractSubscriptionData,
23
+ isEntitledStatus,
24
+ isStaleEvent,
25
+ resolveSubscriptionOwner,
26
+ InvalidSignatureError,
27
+ MissingSignatureError,
28
+ } from "@neon-pixels/stripe";
29
+
30
+ const stripe = createStripeClient(secretKeyFromYourConfig);
31
+
32
+ const session = await createCheckoutSession(stripe, {
33
+ customerId, // or customerEmail
34
+ priceId,
35
+ userId: user.id, // your own users.id, not the auth provider's id
36
+ successUrl,
37
+ cancelUrl,
38
+ trialDays: 14, // omit for no trial
39
+ });
40
+
41
+ const portal = await createBillingPortalSession(stripe, {
42
+ customerId,
43
+ returnUrl,
44
+ });
45
+ ```
46
+
47
+ ### Webhook handler
48
+
49
+ ```ts
50
+ let event: Stripe.Event;
51
+ try {
52
+ event = constructWebhookEvent({ stripe, rawBody, signature, secret });
53
+ } catch (error) {
54
+ if (
55
+ error instanceof MissingSignatureError ||
56
+ error instanceof InvalidSignatureError
57
+ ) {
58
+ return respond(400);
59
+ }
60
+ // MissingWebhookSecretError is a server problem: answer 5xx so Stripe retries
61
+ throw error;
62
+ }
63
+
64
+ if (!event.type.startsWith("customer.subscription.")) {
65
+ return respond(200); // handle other event types separately
66
+ }
67
+
68
+ const owner = await resolveSubscriptionOwner(event, {
69
+ findByCustomerId,
70
+ findByUserId,
71
+ });
72
+ // lastEventCreatedAt is the `created` time of the last event you applied
73
+ if (owner && !isStaleEvent(event, owner.lastEventCreatedAt)) {
74
+ const data = extractSubscriptionData(
75
+ event.data.object as Stripe.Subscription,
76
+ );
77
+ const entitled = isEntitledStatus(data.status);
78
+ }
79
+ ```
80
+
81
+ ### API
82
+
83
+ - `createStripeClient(secretKey)` returns a `Stripe` client. Throws `MissingSecretKeyError` for an empty key.
84
+ - `constructWebhookEvent({ stripe, rawBody, signature, secret })` verifies the signature against the raw body and returns the event. Empty or whitespace-only values count as missing. Throws `MissingWebhookSecretError`, `MissingSignatureError`, or `InvalidSignatureError` (all extend `StripeKitError`, which has a `code`). Other errors are rethrown unchanged.
85
+ - `extractSubscriptionData(subscription)` returns `subscriptionId`, `customerId`, `status`, `priceId`, `currentPeriodEnd`, `cancelAtPeriodEnd`, and `trialEnd` (dates are `Date` or `null`).
86
+ - `resolveSubscriptionOwner(event, { findByCustomerId, findByUserId })` looks the owner up by the Stripe customer id first, then by `metadata.userId`. Works on events whose object is a subscription or checkout session (it reads `customer` and `metadata.userId`). Resolves to `undefined` when neither matches.
87
+ - `isEntitledStatus(status)` is `true` for `active`, `trialing`, and `past_due`.
88
+ - `isStaleEvent(event, lastAppliedAt)` is `true` when the event is strictly older than the last one you applied. Pass that event's `created` time (`new Date(event.created * 1000)`), not when you processed it. An equal timestamp is not stale.
89
+ - `createCheckoutSession(stripe, params)` creates a subscription checkout session and writes `userId` to `client_reference_id`, session metadata, and subscription metadata. A trial is added only when `trialDays` is a positive whole number. `buildCheckoutSessionParams` returns the parameters without calling Stripe.
90
+ - `createBillingPortalSession(stripe, { customerId, returnUrl })` returns `{ url }`.
91
+ - `PlanLimitError(message, { plan, limit })` has `status` 403, `code` `plan_limit_reached`, `plan`, and `limit`. You write the message.
@@ -0,0 +1,106 @@
1
+ import Stripe from "stripe";
2
+ /**
3
+ * No API version is passed on purpose: the installed `stripe` SDK version is
4
+ * the pin.
5
+ */
6
+ export declare function createStripeClient(secretKey: string): Stripe;
7
+ type CreateCheckoutSessionParams = {
8
+ /** Existing Stripe customer. Takes precedence over `customerEmail`. */
9
+ customerId?: string | null;
10
+ customerEmail?: string | null;
11
+ priceId: string;
12
+ /** The app's own `users.id`, never the auth provider's id. */
13
+ userId: string;
14
+ successUrl: string;
15
+ cancelUrl: string;
16
+ trialDays?: number | null;
17
+ };
18
+ type CreateBillingPortalSessionParams = {
19
+ customerId: string;
20
+ returnUrl: string;
21
+ };
22
+ export declare function buildCheckoutSessionParams(params: CreateCheckoutSessionParams): Stripe.Checkout.SessionCreateParams;
23
+ export declare function createCheckoutSession(stripe: Pick<Stripe, "checkout">, params: CreateCheckoutSessionParams): Promise<Stripe.Checkout.Session>;
24
+ export declare function createBillingPortalSession(stripe: Pick<Stripe, "billingPortal">, params: CreateBillingPortalSessionParams): Promise<{
25
+ url: string;
26
+ }>;
27
+ type StripeKitErrorCode = "missing-secret-key" | "missing-webhook-secret" | "missing-signature" | "invalid-signature";
28
+ /** Base class for the configuration and webhook errors this package throws. */
29
+ export declare class StripeKitError extends Error {
30
+ name: string;
31
+ readonly code: StripeKitErrorCode;
32
+ constructor(code: StripeKitErrorCode, message: string, options?: ErrorOptions);
33
+ }
34
+ /** The Stripe secret key is empty. A server configuration problem. */
35
+ export declare class MissingSecretKeyError extends StripeKitError {
36
+ name: string;
37
+ constructor();
38
+ }
39
+ /** The webhook signing secret is empty. Answer 5xx so Stripe retries. */
40
+ export declare class MissingWebhookSecretError extends StripeKitError {
41
+ name: string;
42
+ constructor();
43
+ }
44
+ /** The request had no signature header. Answer 4xx. */
45
+ export declare class MissingSignatureError extends StripeKitError {
46
+ name: string;
47
+ constructor();
48
+ }
49
+ /** The signature did not verify against the payload. Answer 4xx. */
50
+ export declare class InvalidSignatureError extends StripeKitError {
51
+ name: string;
52
+ constructor(options?: ErrorOptions);
53
+ }
54
+ /** Thrown when an action exceeds the user's plan. The app writes the message. */
55
+ export declare class PlanLimitError extends Error {
56
+ name: string;
57
+ readonly status = 403;
58
+ readonly code = "plan_limit_reached";
59
+ readonly plan: string;
60
+ readonly limit: number;
61
+ constructor(message: string, details: {
62
+ plan: string;
63
+ limit: number;
64
+ });
65
+ }
66
+ type SubscriptionData = {
67
+ subscriptionId: string;
68
+ customerId: string;
69
+ status: Stripe.Subscription.Status;
70
+ priceId: string | null;
71
+ currentPeriodEnd: Date | null;
72
+ cancelAtPeriodEnd: boolean;
73
+ trialEnd: Date | null;
74
+ };
75
+ export declare function extractSubscriptionData(subscription: Stripe.Subscription): SubscriptionData;
76
+ /** `active`, `trialing`, and `past_due` (the payment retry grace period). */
77
+ export declare function isEntitledStatus(status: string): boolean;
78
+ /**
79
+ * True when the event is strictly older than the last one the app applied.
80
+ * `lastAppliedAt` must be the `created` time of that last event
81
+ * (`new Date(event.created * 1000)`), not the time it was processed. An equal
82
+ * timestamp is not stale: Stripe can emit two events in the same second.
83
+ */
84
+ export declare function isStaleEvent(event: Pick<Stripe.Event, "created">, lastAppliedAt: Date | null | undefined): boolean;
85
+ type SubscriptionOwnerLookups<TOwner> = {
86
+ findByCustomerId: (customerId: string) => Promise<TOwner | null | undefined> | TOwner | null | undefined;
87
+ findByUserId: (userId: string) => Promise<TOwner | null | undefined> | TOwner | null | undefined;
88
+ };
89
+ /**
90
+ * Finds the app's user for an event: by Stripe customer id first, then by the
91
+ * `metadata.userId` the checkout helper wrote. Returns undefined for neither.
92
+ */
93
+ export declare function resolveSubscriptionOwner<TOwner>(event: Pick<Stripe.Event, "data">, lookups: SubscriptionOwnerLookups<TOwner>): Promise<TOwner | undefined>;
94
+ type ConstructWebhookEventParams = {
95
+ stripe: Pick<Stripe, "webhooks">;
96
+ rawBody: string | Uint8Array;
97
+ signature: string | null | undefined;
98
+ secret: string | null | undefined;
99
+ };
100
+ /**
101
+ * Verifies the signature against the raw request body and returns the event.
102
+ * Throws distinct typed errors so an app can answer 4xx for
103
+ * a missing or invalid signature and 5xx for a missing secret.
104
+ */
105
+ export declare function constructWebhookEvent(params: ConstructWebhookEventParams): Stripe.Event;
106
+ export type { ConstructWebhookEventParams, CreateBillingPortalSessionParams, CreateCheckoutSessionParams, StripeKitErrorCode, SubscriptionData, SubscriptionOwnerLookups };
package/dist/index.js ADDED
@@ -0,0 +1,180 @@
1
+ import Stripe from "stripe";
2
+ // src/errors.ts
3
+ /** Base class for the configuration and webhook errors this package throws. */
4
+ var StripeKitError = class extends Error {
5
+ name = "StripeKitError";
6
+ code;
7
+ constructor(code, message, options) {
8
+ super(message, options);
9
+ this.code = code;
10
+ }
11
+ };
12
+ /** The Stripe secret key is empty. A server configuration problem. */
13
+ var MissingSecretKeyError = class extends StripeKitError {
14
+ name = "MissingSecretKeyError";
15
+ constructor() {
16
+ super("missing-secret-key", "The Stripe secret key is empty.");
17
+ }
18
+ };
19
+ /** The webhook signing secret is empty. Answer 5xx so Stripe retries. */
20
+ var MissingWebhookSecretError = class extends StripeKitError {
21
+ name = "MissingWebhookSecretError";
22
+ constructor() {
23
+ super("missing-webhook-secret", "The Stripe webhook secret is empty.");
24
+ }
25
+ };
26
+ /** The request had no signature header. Answer 4xx. */
27
+ var MissingSignatureError = class extends StripeKitError {
28
+ name = "MissingSignatureError";
29
+ constructor() {
30
+ super("missing-signature", "The Stripe signature header is missing.");
31
+ }
32
+ };
33
+ /** The signature did not verify against the payload. Answer 4xx. */
34
+ var InvalidSignatureError = class extends StripeKitError {
35
+ name = "InvalidSignatureError";
36
+ constructor(options) {
37
+ super("invalid-signature", "The Stripe webhook signature is invalid.", options);
38
+ }
39
+ };
40
+ const PLAN_LIMIT_CODE = "plan_limit_reached";
41
+ /** Thrown when an action exceeds the user's plan. The app writes the message. */
42
+ var PlanLimitError = class extends Error {
43
+ name = "PlanLimitError";
44
+ status = 403;
45
+ code = PLAN_LIMIT_CODE;
46
+ plan;
47
+ limit;
48
+ constructor(message, details) {
49
+ super(message);
50
+ this.plan = details.plan;
51
+ this.limit = details.limit;
52
+ }
53
+ };
54
+ // src/client.ts
55
+ /**
56
+ * No API version is passed on purpose: the installed `stripe` SDK version is
57
+ * the pin.
58
+ */
59
+ function createStripeClient(secretKey) {
60
+ if (!secretKey?.trim()) throw new MissingSecretKeyError();
61
+ return new Stripe(secretKey);
62
+ }
63
+ // src/checkout.ts
64
+ function customerFields(params) {
65
+ if (params.customerId) return { customer: params.customerId };
66
+ if (params.customerEmail) return { customer_email: params.customerEmail };
67
+ return {};
68
+ }
69
+ function subscriptionData(params) {
70
+ const data = { metadata: { userId: params.userId } };
71
+ const trialDays = params.trialDays ?? 0;
72
+ if (Number.isInteger(trialDays) && trialDays > 0) data.trial_period_days = trialDays;
73
+ return data;
74
+ }
75
+ function buildCheckoutSessionParams(params) {
76
+ return {
77
+ mode: "subscription",
78
+ line_items: [{
79
+ price: params.priceId,
80
+ quantity: 1
81
+ }],
82
+ success_url: params.successUrl,
83
+ cancel_url: params.cancelUrl,
84
+ client_reference_id: params.userId,
85
+ metadata: { userId: params.userId },
86
+ subscription_data: subscriptionData(params),
87
+ ...customerFields(params)
88
+ };
89
+ }
90
+ function createCheckoutSession(stripe, params) {
91
+ return stripe.checkout.sessions.create(buildCheckoutSessionParams(params));
92
+ }
93
+ async function createBillingPortalSession(stripe, params) {
94
+ return { url: (await stripe.billingPortal.sessions.create({
95
+ customer: params.customerId,
96
+ return_url: params.returnUrl
97
+ })).url };
98
+ }
99
+ // src/subscriptions.ts
100
+ const MILLISECONDS_PER_SECOND = 1e3;
101
+ const ENTITLED_STATUSES = /* @__PURE__ */ new Set([
102
+ "active",
103
+ "trialing",
104
+ "past_due"
105
+ ]);
106
+ function toDate(unixSeconds) {
107
+ if (!unixSeconds) return null;
108
+ return /* @__PURE__ */ new Date(unixSeconds * MILLISECONDS_PER_SECOND);
109
+ }
110
+ function idOf(reference) {
111
+ return typeof reference === "string" ? reference : reference.id;
112
+ }
113
+ /**
114
+ * Reads the period end from the first subscription item, where current Stripe
115
+ * API versions keep it, and falls back to the legacy top-level field.
116
+ */
117
+ function currentPeriodEndOf(subscription) {
118
+ const item = subscription.items?.data?.[0];
119
+ const legacyPeriodEnd = subscription.current_period_end;
120
+ return toDate(item?.current_period_end ?? legacyPeriodEnd);
121
+ }
122
+ function extractSubscriptionData(subscription) {
123
+ return {
124
+ subscriptionId: subscription.id,
125
+ customerId: idOf(subscription.customer),
126
+ status: subscription.status,
127
+ priceId: subscription.items?.data?.[0]?.price?.id ?? null,
128
+ currentPeriodEnd: currentPeriodEndOf(subscription),
129
+ cancelAtPeriodEnd: subscription.cancel_at_period_end,
130
+ trialEnd: toDate(subscription.trial_end)
131
+ };
132
+ }
133
+ /** `active`, `trialing`, and `past_due` (the payment retry grace period). */
134
+ function isEntitledStatus(status) {
135
+ return ENTITLED_STATUSES.has(status);
136
+ }
137
+ /**
138
+ * True when the event is strictly older than the last one the app applied.
139
+ * `lastAppliedAt` must be the `created` time of that last event
140
+ * (`new Date(event.created * 1000)`), not the time it was processed. An equal
141
+ * timestamp is not stale: Stripe can emit two events in the same second.
142
+ */
143
+ function isStaleEvent(event, lastAppliedAt) {
144
+ if (!lastAppliedAt) return false;
145
+ return event.created * MILLISECONDS_PER_SECOND < lastAppliedAt.getTime();
146
+ }
147
+ /**
148
+ * Finds the app's user for an event: by Stripe customer id first, then by the
149
+ * `metadata.userId` the checkout helper wrote. Returns undefined for neither.
150
+ */
151
+ async function resolveSubscriptionOwner(event, lookups) {
152
+ const object = event.data.object;
153
+ const customerId = object.customer ? idOf(object.customer) : null;
154
+ const byCustomer = customerId ? await lookups.findByCustomerId(customerId) : null;
155
+ if (byCustomer != null) return byCustomer;
156
+ const userId = object.metadata?.userId;
157
+ return (userId ? await lookups.findByUserId(userId) : null) ?? void 0;
158
+ }
159
+ // src/webhook.ts
160
+ const SIGNATURE_ERROR_TYPE = "StripeSignatureVerificationError";
161
+ function isSignatureVerificationError(error) {
162
+ return error instanceof Error && error.type === SIGNATURE_ERROR_TYPE;
163
+ }
164
+ /**
165
+ * Verifies the signature against the raw request body and returns the event.
166
+ * Throws distinct typed errors so an app can answer 4xx for
167
+ * a missing or invalid signature and 5xx for a missing secret.
168
+ */
169
+ function constructWebhookEvent(params) {
170
+ const { stripe, rawBody, signature, secret } = params;
171
+ if (!secret?.trim()) throw new MissingWebhookSecretError();
172
+ if (!signature?.trim()) throw new MissingSignatureError();
173
+ try {
174
+ return stripe.webhooks.constructEvent(rawBody, signature, secret);
175
+ } catch (error) {
176
+ if (!isSignatureVerificationError(error)) throw error;
177
+ throw new InvalidSignatureError({ cause: error });
178
+ }
179
+ }
180
+ export { InvalidSignatureError, MissingSecretKeyError, MissingSignatureError, MissingWebhookSecretError, PlanLimitError, StripeKitError, buildCheckoutSessionParams, constructWebhookEvent, createBillingPortalSession, createCheckoutSession, createStripeClient, extractSubscriptionData, isEntitledStatus, isStaleEvent, resolveSubscriptionOwner };
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@neon-pixels/stripe",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "Stripe client, webhook verification, subscription mapping, and checkout helpers.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/neonpixels-studio/packages.git",
10
+ "directory": "packages/stripe"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "engines": {
26
+ "node": "^22.17.0 || ^24.0.0 || >=26.0.0"
27
+ },
28
+ "peerDependencies": {
29
+ "stripe": "^23.0.0"
30
+ },
31
+ "devDependencies": {
32
+ "stripe": "^23.0.0"
33
+ },
34
+ "scripts": {
35
+ "build": "tsdown",
36
+ "typecheck": "tsc --noEmit -p tsconfig.json"
37
+ }
6
38
  }