@ordinatio/billing 1.0.0 → 1.2.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/README.md CHANGED
@@ -8,6 +8,10 @@ The billing rules of a subscription product, pure and with no database, no frame
8
8
  - `decideLock({ active, others, now })`: use the active team, else switch to the OLDEST other team that is not locked (ties broken by id so the answer never flips), else `locked`.
9
9
  - `seatLimitFor(subscription, plan)`, `seatsUsed`, `canAddSeat(args, plan)`, `mustCheckOnRenew`: a seat is a member or a live pending invite; no limit for a founding team or a trial; once paying, the seats paid for (never under the base, never over the maximum); members above the limit keep working and only new invites are refused.
10
10
 
11
+ - `paddleCatalog(plan, options)`, `paddleItems(plan, seats, interval, priceIds)`, `syncPaddleCatalog(port, catalog, { apply })` (1.1.0): Paddle has no graduated price, so a plan becomes ONE product with a base price and one price per seat band (monthly and yearly, each with a quantity limit equal to the band size). A subscription for N seats is the base plus one item per band reached, and the items add up to exactly `priceFor`. The sync makes only what is missing through an injected port (you write the HTTP), never edits or duplicates, and stops on a duplicate or a price that differs; `apply: false` is a dry run.
12
+
13
+ - `verifyPaddleSignature({ header, rawBody, secret, nowSeconds, hmacHex })`, `readPaddleSubscription(plan, data, priceKeys)`, `readPaddleTransaction(data)` (1.2.0): the receiving end of Paddle's webhooks, pure. The signature check takes the raw body text, accepts any one of several `h1` values (secret rotation), enforces a time window both ways and compares in constant time; the HMAC function is yours to pass in. `readPaddleSubscription` turns the subscription as Paddle's API shows it into the plan fields (status, interval, seats, period end, snapshot time), and refuses an item list that `paddleItems` would not have made. A scheduled cancel is `canceled` until its effective time, a scheduled pause or a paused subscription is `paused`, a scheduled resume never extends access. `accessFor` now treats a `paused` plan like a cancelled one: paying until its end time, then locked with reason `paused`.
14
+
11
15
  ```ts
12
16
  import { definePricePlan, priceFor, accessFor } from '@ordinatio/billing';
13
17
 
package/dist/index.d.ts CHANGED
@@ -81,7 +81,7 @@ type Access = {
81
81
  endsAt: Date;
82
82
  } | {
83
83
  access: 'locked';
84
- reason: 'trial_ended' | 'canceled';
84
+ reason: 'trial_ended' | 'canceled' | 'paused';
85
85
  };
86
86
  /** The trial end for a team created at `now`. */
87
87
  declare function trialEndFrom(now: Date, trialDays: number): Date;
@@ -133,4 +133,143 @@ declare function mustCheckOnRenew(invite: {
133
133
  expiresAt: Date;
134
134
  }, now: Date): boolean;
135
135
 
136
- export { type Access, type Band, type BillingRecord, DAY_MS, type Interval, InvalidPricePlanError, type LockCandidate, type LockDecision, type Price, type PriceLine, type PricePlan, type PricePlanInput, type SeatCheck, type SeatSubscription, accessFor, averagePerSeatCents, canAddSeat, decideLock, definePricePlan, formatCents, isLocked, mustCheckOnRenew, priceFor, seatLimitFor, seatsUsed, trialEndFrom };
136
+ interface PaddlePriceSpec {
137
+ /** `base:month`, `band-11-25:year`: the stable name of the price, stored in Paddle's custom data. */
138
+ key: string;
139
+ interval: Interval;
140
+ name: string;
141
+ description: string;
142
+ /** Whole cents as text, the way Paddle takes an amount. */
143
+ unitAmount: string;
144
+ currency: string;
145
+ quantity: {
146
+ minimum: number;
147
+ maximum: number;
148
+ };
149
+ }
150
+ interface PaddleCatalog {
151
+ catalogKey: string;
152
+ product: {
153
+ name: string;
154
+ description: string;
155
+ taxCategory: string;
156
+ };
157
+ prices: PaddlePriceSpec[];
158
+ }
159
+ interface PaddleCatalogOptions {
160
+ /** Stored in the product's custom data; how a second run finds the product. */
161
+ catalogKey: string;
162
+ productName: string;
163
+ productDescription: string;
164
+ /** Paddle's tax category for the product. Default `saas`. */
165
+ taxCategory?: string;
166
+ currency?: string;
167
+ }
168
+ /** The product and the ten prices (base and each band, monthly and yearly) of a plan, as plain data. */
169
+ declare function paddleCatalog(plan: PricePlan, options: PaddleCatalogOptions): PaddleCatalog;
170
+ type PaddleItems = {
171
+ ok: true;
172
+ items: Array<{
173
+ priceId: string;
174
+ quantity: number;
175
+ }>;
176
+ } | {
177
+ ok: false;
178
+ reason: 'contact_us' | 'invalid' | 'missing_price';
179
+ };
180
+ /** The subscription items for `seats` seats: the base plus one item per band reached. `priceIds` maps a price key (`base:month`) to Paddle's price id. */
181
+ declare function paddleItems(plan: PricePlan, seats: number, interval: Interval, priceIds: Readonly<Record<string, string>>): PaddleItems;
182
+ interface PaddleExistingPrice {
183
+ id: string;
184
+ customKey: string | null;
185
+ unitAmount: string;
186
+ currency: string;
187
+ interval: string | null;
188
+ quantity: {
189
+ minimum: number;
190
+ maximum: number;
191
+ } | null;
192
+ }
193
+ /** What Paddle is asked to do. The port adds the keys to Paddle's custom data. */
194
+ interface PaddleCatalogPort {
195
+ /** Products whose custom data holds this catalog key (the port filters). */
196
+ findProducts(catalogKey: string): Promise<Array<{
197
+ id: string;
198
+ }>>;
199
+ createProduct(catalogKey: string, product: PaddleCatalog['product']): Promise<{
200
+ id: string;
201
+ }>;
202
+ listPrices(productId: string): Promise<PaddleExistingPrice[]>;
203
+ createPrice(productId: string, spec: PaddlePriceSpec): Promise<{
204
+ id: string;
205
+ }>;
206
+ }
207
+ type PaddleSyncResult = {
208
+ ok: true;
209
+ productId: string | null;
210
+ priceIds: Record<string, string>;
211
+ created: string[];
212
+ kept: string[];
213
+ applied: boolean;
214
+ } | {
215
+ ok: false;
216
+ error: 'duplicate_product' | 'duplicate_price' | 'mismatch';
217
+ detail: string;
218
+ };
219
+ /** Makes the product and each missing price. With `apply: false` it changes nothing and says what it would make. A product found twice, a price key found twice, or an existing price that differs from the plan stops it before anything is made. */
220
+ declare function syncPaddleCatalog(port: PaddleCatalogPort, catalog: PaddleCatalog, options: {
221
+ apply: boolean;
222
+ }): Promise<PaddleSyncResult>;
223
+
224
+ type SignatureResult = {
225
+ ok: true;
226
+ } | {
227
+ ok: false;
228
+ reason: 'missing' | 'malformed' | 'stale' | 'mismatch';
229
+ };
230
+ interface SignatureInput {
231
+ header: string | null | undefined;
232
+ rawBody: string;
233
+ secret: string;
234
+ /** Now, in whole seconds since 1970. */
235
+ nowSeconds: number;
236
+ /** HMAC-SHA256 of `message` with `secret`, as lowercase hex. */
237
+ hmacHex: (secret: string, message: string) => string;
238
+ /** Default 300 seconds, in both directions. */
239
+ toleranceSeconds?: number;
240
+ }
241
+ declare function verifyPaddleSignature(input: SignatureInput): SignatureResult;
242
+
243
+ type PlanStatus = 'active' | 'past_due' | 'canceled' | 'paused';
244
+ interface PlanUpdate {
245
+ subscriptionId: string;
246
+ customerId: string;
247
+ status: PlanStatus;
248
+ interval: Interval;
249
+ paidSeats: number;
250
+ /** When access ends for `canceled` and `paused` (and the end of the current period otherwise); null when Paddle gave none. */
251
+ currentPeriodEnd: Date | null;
252
+ /** The cancel or pause time, for a caller that has no stored end. */
253
+ settledAt: Date | null;
254
+ /** Paddle's `updated_at`, cut to whole milliseconds. */
255
+ snapshotAt: Date;
256
+ }
257
+ type SubscriptionReading = {
258
+ ok: true;
259
+ update: PlanUpdate;
260
+ } | {
261
+ ok: false;
262
+ reason: 'invalid' | 'unknown_status' | 'unexpected_items';
263
+ };
264
+ declare function readPaddleSubscription(plan: PricePlan, data: unknown, priceKeys: Readonly<Record<string, string>>): SubscriptionReading;
265
+ interface TransactionCompleted {
266
+ transactionId: string;
267
+ subscriptionId: string | null;
268
+ customerId: string | null;
269
+ /** From OUR custom data: only a way to find the team's row, never trusted by itself. */
270
+ organizationId: string | null;
271
+ }
272
+ /** The fields of a `transaction.completed` event's `data` that the handshake needs; null for anything that is not a completed transaction. */
273
+ declare function readPaddleTransaction(data: unknown): TransactionCompleted | null;
274
+
275
+ export { type Access, type Band, type BillingRecord, DAY_MS, type Interval, InvalidPricePlanError, type LockCandidate, type LockDecision, type PaddleCatalog, type PaddleCatalogOptions, type PaddleCatalogPort, type PaddleExistingPrice, type PaddleItems, type PaddlePriceSpec, type PaddleSyncResult, type PlanStatus, type PlanUpdate, type Price, type PriceLine, type PricePlan, type PricePlanInput, type SeatCheck, type SeatSubscription, type SignatureInput, type SignatureResult, type SubscriptionReading, type TransactionCompleted, accessFor, averagePerSeatCents, canAddSeat, decideLock, definePricePlan, formatCents, isLocked, mustCheckOnRenew, paddleCatalog, paddleItems, priceFor, readPaddleSubscription, readPaddleTransaction, seatLimitFor, seatsUsed, syncPaddleCatalog, trialEndFrom, verifyPaddleSignature };
package/dist/index.js CHANGED
@@ -79,8 +79,8 @@ function accessFor(record, now) {
79
79
  const left = record.trialEndsAt.getTime() - now.getTime();
80
80
  return left > 0 ? { access: "trial", daysLeft: Math.ceil(left / DAY_MS), endsAt: record.trialEndsAt } : { access: "locked", reason: "trial_ended" };
81
81
  }
82
- if (record.status === "canceled") {
83
- return record.currentPeriodEnd !== null && now.getTime() < record.currentPeriodEnd.getTime() ? { access: "full", why: "paying" } : { access: "locked", reason: "canceled" };
82
+ if (record.status === "canceled" || record.status === "paused") {
83
+ return record.currentPeriodEnd !== null && now.getTime() < record.currentPeriodEnd.getTime() ? { access: "full", why: "paying" } : { access: "locked", reason: record.status };
84
84
  }
85
85
  return { access: "full", why: "paying" };
86
86
  }
@@ -108,6 +108,180 @@ function canAddSeat(args, plan) {
108
108
  function mustCheckOnRenew(invite, now) {
109
109
  return invite.expiresAt.getTime() <= now.getTime();
110
110
  }
111
+
112
+ // src/paddle.ts
113
+ var capitalised2 = (word) => word.charAt(0).toUpperCase() + word.slice(1);
114
+ function paddleCatalog(plan, options) {
115
+ const currency = options.currency ?? "USD";
116
+ const prices = [];
117
+ for (const interval of ["month", "year"]) {
118
+ const times = interval === "year" ? plan.yearlyMultiplier : 1;
119
+ const per = interval === "year" ? "a year" : "a month";
120
+ prices.push({
121
+ key: `base:${interval}`,
122
+ interval,
123
+ name: `First ${plan.baseSeats} ${plan.seatNoun}, ${interval === "year" ? "yearly" : "monthly"}`,
124
+ description: `The flat price for the first ${plan.baseSeats} ${plan.seatNoun}, per ${interval}.`,
125
+ unitAmount: String(plan.baseMonthlyCents * times),
126
+ currency,
127
+ quantity: { minimum: 1, maximum: 1 }
128
+ });
129
+ for (const band of plan.bands) {
130
+ prices.push({
131
+ key: `band-${band.from}-${band.to}:${interval}`,
132
+ interval,
133
+ name: `${capitalised2(plan.seatNoun)} ${band.from} to ${band.to}, ${interval === "year" ? "yearly" : "monthly"}`,
134
+ description: `Each of ${plan.seatNoun} ${band.from} to ${band.to}, ${per}.`,
135
+ unitAmount: String(band.monthlyCents * times),
136
+ currency,
137
+ quantity: { minimum: 1, maximum: band.to - band.from + 1 }
138
+ });
139
+ }
140
+ }
141
+ return { catalogKey: options.catalogKey, product: { name: options.productName, description: options.productDescription, taxCategory: options.taxCategory ?? "saas" }, prices };
142
+ }
143
+ function paddleItems(plan, seats, interval, priceIds) {
144
+ const price = priceFor(plan, seats, interval);
145
+ if (!price.ok) return price;
146
+ const items = [];
147
+ for (const line of price.lines) {
148
+ const priceId = Object.hasOwn(priceIds, `${line.key}:${interval}`) ? priceIds[`${line.key}:${interval}`] : void 0;
149
+ if (typeof priceId !== "string" || priceId === "") return { ok: false, reason: "missing_price" };
150
+ items.push({ priceId, quantity: line.quantity });
151
+ }
152
+ return { ok: true, items };
153
+ }
154
+ async function syncPaddleCatalog(port, catalog, options) {
155
+ const products = await port.findProducts(catalog.catalogKey);
156
+ if (products.length > 1) return { ok: false, error: "duplicate_product", detail: `${products.length} products carry the catalog key ${catalog.catalogKey}` };
157
+ const existing = products.length === 1 ? await port.listPrices(products[0].id) : [];
158
+ const byKey = /* @__PURE__ */ new Map();
159
+ for (const price of existing) {
160
+ if (price.customKey === null) continue;
161
+ if (byKey.has(price.customKey)) return { ok: false, error: "duplicate_price", detail: `the price key ${price.customKey} is on more than one price` };
162
+ byKey.set(price.customKey, price);
163
+ }
164
+ for (const spec of catalog.prices) {
165
+ const found = byKey.get(spec.key);
166
+ if (found === void 0) continue;
167
+ const same = found.unitAmount === spec.unitAmount && found.currency === spec.currency && found.interval === spec.interval && found.quantity?.minimum === spec.quantity.minimum && found.quantity?.maximum === spec.quantity.maximum;
168
+ if (!same) return { ok: false, error: "mismatch", detail: `the price ${spec.key} in Paddle differs from the plan (amount, currency, interval or quantity limits); prices are never edited here` };
169
+ }
170
+ const priceIds = {};
171
+ const created = [];
172
+ const kept = [];
173
+ let productId = products[0]?.id ?? null;
174
+ if (productId === null) {
175
+ created.push("product");
176
+ if (options.apply) productId = (await port.createProduct(catalog.catalogKey, catalog.product)).id;
177
+ }
178
+ for (const spec of catalog.prices) {
179
+ const found = byKey.get(spec.key);
180
+ if (found !== void 0) {
181
+ priceIds[spec.key] = found.id;
182
+ kept.push(spec.key);
183
+ continue;
184
+ }
185
+ created.push(spec.key);
186
+ if (options.apply && productId !== null) priceIds[spec.key] = (await port.createPrice(productId, spec)).id;
187
+ }
188
+ return { ok: true, productId, priceIds, created, kept, applied: options.apply };
189
+ }
190
+
191
+ // src/paddle-signature.ts
192
+ function sameText(a, b) {
193
+ let diff = a.length ^ b.length;
194
+ const length = Math.max(a.length, b.length);
195
+ for (let i = 0; i < length; i += 1) diff |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0);
196
+ return diff === 0;
197
+ }
198
+ function verifyPaddleSignature(input) {
199
+ const { header, rawBody, secret, nowSeconds, hmacHex } = input;
200
+ if (typeof header !== "string" || header.trim() === "") return { ok: false, reason: "missing" };
201
+ if (typeof rawBody !== "string" || typeof secret !== "string" || secret === "" || !Number.isFinite(nowSeconds)) return { ok: false, reason: "malformed" };
202
+ let ts = null;
203
+ const hashes = [];
204
+ for (const part of header.split(";")) {
205
+ const at = part.indexOf("=");
206
+ if (at < 1) return { ok: false, reason: "malformed" };
207
+ const name = part.slice(0, at).trim();
208
+ const value = part.slice(at + 1).trim();
209
+ if (name === "ts") {
210
+ if (ts !== null) return { ok: false, reason: "malformed" };
211
+ ts = value;
212
+ } else if (name === "h1") {
213
+ hashes.push(value.toLowerCase());
214
+ }
215
+ }
216
+ if (ts === null || !/^\d{1,12}$/.test(ts) || hashes.length === 0 || hashes.some((hash) => !/^[0-9a-f]{64}$/.test(hash))) return { ok: false, reason: "malformed" };
217
+ const tolerance = input.toleranceSeconds ?? 300;
218
+ if (Math.abs(nowSeconds - Number(ts)) > tolerance) return { ok: false, reason: "stale" };
219
+ const expected = hmacHex(secret, `${ts}:${rawBody}`).toLowerCase();
220
+ let matched = false;
221
+ for (const hash of hashes) if (sameText(hash, expected)) matched = true;
222
+ return matched ? { ok: true } : { ok: false, reason: "mismatch" };
223
+ }
224
+
225
+ // src/paddle-subscription.ts
226
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
227
+ var text = (value) => typeof value === "string" && value !== "" ? value : null;
228
+ var when = (value) => {
229
+ const raw = text(value);
230
+ if (raw === null) return null;
231
+ const time = new Date(raw);
232
+ return Number.isNaN(time.getTime()) ? null : new Date(Math.floor(time.getTime()));
233
+ };
234
+ function readPaddleSubscription(plan, data, priceKeys) {
235
+ if (!isObject(data)) return { ok: false, reason: "invalid" };
236
+ const subscriptionId = text(data.id);
237
+ const customerId = text(data.customer_id);
238
+ const snapshotAt = when(data.updated_at);
239
+ if (subscriptionId === null || customerId === null || snapshotAt === null || !Array.isArray(data.items)) return { ok: false, reason: "invalid" };
240
+ const counts = /* @__PURE__ */ new Map();
241
+ let interval = null;
242
+ for (const raw of data.items) {
243
+ if (!isObject(raw) || !isObject(raw.price)) return { ok: false, reason: "invalid" };
244
+ if (raw.status === "inactive") continue;
245
+ const priceId = text(raw.price.id);
246
+ const key = priceId !== null && Object.hasOwn(priceKeys, priceId) ? priceKeys[priceId] : void 0;
247
+ const quantity = raw.quantity;
248
+ if (key === void 0 || !Number.isSafeInteger(quantity) || quantity < 1) return { ok: false, reason: "unexpected_items" };
249
+ const [name, suffix] = key.split(":");
250
+ if (suffix !== "month" && suffix !== "year" || interval !== null && interval !== suffix || counts.has(name)) return { ok: false, reason: "unexpected_items" };
251
+ interval = suffix;
252
+ counts.set(name, quantity);
253
+ }
254
+ if (interval === null || counts.get("base") !== 1) return { ok: false, reason: "unexpected_items" };
255
+ let seats = plan.baseSeats;
256
+ for (const [name, quantity] of counts) if (name !== "base") seats += quantity;
257
+ const expected = priceFor(plan, seats, interval);
258
+ if (!expected.ok || expected.lines.length !== counts.size || expected.lines.some((line) => counts.get(line.key) !== line.quantity)) return { ok: false, reason: "unexpected_items" };
259
+ const change = isObject(data.scheduled_change) ? data.scheduled_change : null;
260
+ const action = change === null ? null : text(change.action);
261
+ const effectiveAt = change === null ? null : when(change.effective_at);
262
+ const periodEnd = isObject(data.current_billing_period) ? when(data.current_billing_period.ends_at) : null;
263
+ const base = { subscriptionId, customerId, interval, paidSeats: seats, snapshotAt };
264
+ const status = text(data.status);
265
+ if (status === "active" || status === "trialing") {
266
+ if (action === "cancel" && effectiveAt !== null) return { ok: true, update: { ...base, status: "canceled", currentPeriodEnd: effectiveAt, settledAt: effectiveAt } };
267
+ if (action === "pause" && effectiveAt !== null) return { ok: true, update: { ...base, status: "paused", currentPeriodEnd: effectiveAt, settledAt: effectiveAt } };
268
+ return { ok: true, update: { ...base, status: "active", currentPeriodEnd: periodEnd, settledAt: null } };
269
+ }
270
+ if (status === "past_due") return { ok: true, update: { ...base, status: "past_due", currentPeriodEnd: periodEnd, settledAt: null } };
271
+ if (status === "paused") {
272
+ const pausedAt = when(data.paused_at) ?? snapshotAt;
273
+ return { ok: true, update: { ...base, status: "paused", currentPeriodEnd: pausedAt, settledAt: pausedAt } };
274
+ }
275
+ if (status === "canceled") return { ok: true, update: { ...base, status: "canceled", currentPeriodEnd: periodEnd, settledAt: when(data.canceled_at) ?? snapshotAt } };
276
+ return { ok: false, reason: "unknown_status" };
277
+ }
278
+ function readPaddleTransaction(data) {
279
+ if (!isObject(data)) return null;
280
+ const transactionId = text(data.id);
281
+ if (transactionId === null || !transactionId.startsWith("txn_")) return null;
282
+ const custom = isObject(data.custom_data) ? data.custom_data : null;
283
+ return { transactionId, subscriptionId: text(data.subscription_id), customerId: text(data.customer_id), organizationId: custom === null ? null : text(custom.organization_id) };
284
+ }
111
285
  export {
112
286
  DAY_MS,
113
287
  InvalidPricePlanError,
@@ -119,8 +293,14 @@ export {
119
293
  formatCents,
120
294
  isLocked,
121
295
  mustCheckOnRenew,
296
+ paddleCatalog,
297
+ paddleItems,
122
298
  priceFor,
299
+ readPaddleSubscription,
300
+ readPaddleTransaction,
123
301
  seatLimitFor,
124
302
  seatsUsed,
125
- trialEndFrom
303
+ syncPaddleCatalog,
304
+ trialEndFrom,
305
+ verifyPaddleSignature
126
306
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/billing",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "description": "Billing rules for any subscription product, pure and with no database: graduated seat pricing from a plan you pass in (validated once, in integer cents), the trial / paying / locked state machine, which team to use when one is locked, and seat counting with the can-add-a-seat rule",