@ordinatio/billing 1.1.0 → 1.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/README.md CHANGED
@@ -10,6 +10,10 @@ The billing rules of a subscription product, pure and with no database, no frame
10
10
 
11
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
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
+
15
+ - `canStartCheckout(record, now)`, `checkoutKey`, `reusableCheckout`, `paddleTransactionBody` (1.3.0): the rules around a Pay button. A team may start a checkout in its trial, or when a cancelled or paused plan has nothing left that it paid for; never while a plan is active or past due, nor while a cancelled one still covers it, and a team with no plan record (a founding team) never pays. A waiting checkout is reused for 30 minutes for the same interval and seats. The transaction body carries the items and only your organization id. Also in 1.3.0: `verifyPaddleSignature` refuses a tolerance that is not a plain number and never throws when the HMAC does; a scheduled cancel or pause with an unreadable time is refused (not read as nothing scheduled); `past_due` honors a scheduled cancel.
16
+
13
17
  ```ts
14
18
  import { definePricePlan, priceFor, accessFor } from '@ordinatio/billing';
15
19
 
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;
@@ -221,4 +221,91 @@ declare function syncPaddleCatalog(port: PaddleCatalogPort, catalog: PaddleCatal
221
221
  apply: boolean;
222
222
  }): Promise<PaddleSyncResult>;
223
223
 
224
- 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 Price, type PriceLine, type PricePlan, type PricePlanInput, type SeatCheck, type SeatSubscription, accessFor, averagePerSeatCents, canAddSeat, decideLock, definePricePlan, formatCents, isLocked, mustCheckOnRenew, paddleCatalog, paddleItems, priceFor, seatLimitFor, seatsUsed, syncPaddleCatalog, trialEndFrom };
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
+ type CheckoutRecord = {
276
+ status: string;
277
+ currentPeriodEnd: Date | null;
278
+ } | null;
279
+ type CanStartCheckout = {
280
+ ok: true;
281
+ } | {
282
+ ok: false;
283
+ reason: 'no_plan' | 'already_paying' | 'still_covered';
284
+ };
285
+ declare function canStartCheckout(record: CheckoutRecord, now: Date): CanStartCheckout;
286
+ /** What a checkout was made for, as text: `month:25`. */
287
+ declare const checkoutKey: (interval: Interval, seats: number) => string;
288
+ declare const PENDING_CHECKOUT_MS: number;
289
+ /** The waiting transaction id to give the person again, or null when there is none, it is too old, or it was made for something else. */
290
+ declare function reusableCheckout(pending: {
291
+ transactionId: string | null;
292
+ at: Date | null;
293
+ key: string | null;
294
+ }, wantedKey: string, now: Date, maxAgeMs?: number): string | null;
295
+ interface TransactionBody {
296
+ items: Array<{
297
+ price_id: string;
298
+ quantity: number;
299
+ }>;
300
+ custom_data: {
301
+ organization_id: string;
302
+ };
303
+ collection_mode: 'automatic';
304
+ }
305
+ /** The body for Paddle's create-transaction call from the items `paddleItems` made. */
306
+ declare function paddleTransactionBody(items: ReadonlyArray<{
307
+ priceId: string;
308
+ quantity: number;
309
+ }>, organizationId: string): TransactionBody;
310
+
311
+ export { type Access, type Band, type BillingRecord, type CanStartCheckout, type CheckoutRecord, DAY_MS, type Interval, InvalidPricePlanError, type LockCandidate, type LockDecision, PENDING_CHECKOUT_MS, 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 TransactionBody, type TransactionCompleted, accessFor, averagePerSeatCents, canAddSeat, canStartCheckout, checkoutKey, decideLock, definePricePlan, formatCents, isLocked, mustCheckOnRenew, paddleCatalog, paddleItems, paddleTransactionBody, priceFor, readPaddleSubscription, readPaddleTransaction, reusableCheckout, 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
  }
@@ -187,12 +187,139 @@ async function syncPaddleCatalog(port, catalog, options) {
187
187
  }
188
188
  return { ok: true, productId, priceIds, created, kept, applied: options.apply };
189
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 (!Number.isFinite(tolerance) || tolerance < 0) return { ok: false, reason: "malformed" };
219
+ if (Math.abs(nowSeconds - Number(ts)) > tolerance) return { ok: false, reason: "stale" };
220
+ let expected;
221
+ try {
222
+ expected = hmacHex(secret, `${ts}:${rawBody}`).toLowerCase();
223
+ } catch {
224
+ return { ok: false, reason: "mismatch" };
225
+ }
226
+ let matched = false;
227
+ for (const hash of hashes) if (sameText(hash, expected)) matched = true;
228
+ return matched ? { ok: true } : { ok: false, reason: "mismatch" };
229
+ }
230
+
231
+ // src/paddle-subscription.ts
232
+ var isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
233
+ var text = (value) => typeof value === "string" && value !== "" ? value : null;
234
+ var when = (value) => {
235
+ const raw = text(value);
236
+ if (raw === null) return null;
237
+ const time = new Date(raw);
238
+ return Number.isNaN(time.getTime()) ? null : time;
239
+ };
240
+ function readPaddleSubscription(plan, data, priceKeys) {
241
+ if (!isObject(data)) return { ok: false, reason: "invalid" };
242
+ const subscriptionId = text(data.id);
243
+ const customerId = text(data.customer_id);
244
+ const snapshotAt = when(data.updated_at);
245
+ if (subscriptionId === null || customerId === null || snapshotAt === null || !Array.isArray(data.items)) return { ok: false, reason: "invalid" };
246
+ const counts = /* @__PURE__ */ new Map();
247
+ let interval = null;
248
+ for (const raw of data.items) {
249
+ if (!isObject(raw) || !isObject(raw.price)) return { ok: false, reason: "invalid" };
250
+ if (raw.status === "inactive") continue;
251
+ const priceId = text(raw.price.id);
252
+ const key = priceId !== null && Object.hasOwn(priceKeys, priceId) ? priceKeys[priceId] : void 0;
253
+ const quantity = raw.quantity;
254
+ if (key === void 0 || !Number.isSafeInteger(quantity) || quantity < 1) return { ok: false, reason: "unexpected_items" };
255
+ const [name, suffix] = key.split(":");
256
+ if (suffix !== "month" && suffix !== "year" || interval !== null && interval !== suffix || counts.has(name)) return { ok: false, reason: "unexpected_items" };
257
+ interval = suffix;
258
+ counts.set(name, quantity);
259
+ }
260
+ if (interval === null || counts.get("base") !== 1) return { ok: false, reason: "unexpected_items" };
261
+ let seats = plan.baseSeats;
262
+ for (const [name, quantity] of counts) if (name !== "base") seats += quantity;
263
+ const expected = priceFor(plan, seats, interval);
264
+ if (!expected.ok || expected.lines.length !== counts.size || expected.lines.some((line) => counts.get(line.key) !== line.quantity)) return { ok: false, reason: "unexpected_items" };
265
+ const change = isObject(data.scheduled_change) ? data.scheduled_change : null;
266
+ const action = change === null ? null : text(change.action);
267
+ const effectiveAt = change === null ? null : when(change.effective_at);
268
+ const periodEnd = isObject(data.current_billing_period) ? when(data.current_billing_period.ends_at) : null;
269
+ const base = { subscriptionId, customerId, interval, paidSeats: seats, snapshotAt };
270
+ const status = text(data.status);
271
+ if (status === "active" || status === "trialing" || status === "past_due") {
272
+ if ((action === "cancel" || action === "pause") && effectiveAt === null) return { ok: false, reason: "invalid" };
273
+ if (action === "cancel") return { ok: true, update: { ...base, status: "canceled", currentPeriodEnd: effectiveAt, settledAt: effectiveAt } };
274
+ if (action === "pause") return { ok: true, update: { ...base, status: "paused", currentPeriodEnd: effectiveAt, settledAt: effectiveAt } };
275
+ if (status === "past_due") return { ok: true, update: { ...base, status: "past_due", currentPeriodEnd: periodEnd, settledAt: null } };
276
+ return { ok: true, update: { ...base, status: "active", currentPeriodEnd: periodEnd, settledAt: null } };
277
+ }
278
+ if (status === "paused") {
279
+ const pausedAt = when(data.paused_at) ?? snapshotAt;
280
+ return { ok: true, update: { ...base, status: "paused", currentPeriodEnd: pausedAt, settledAt: pausedAt } };
281
+ }
282
+ if (status === "canceled") return { ok: true, update: { ...base, status: "canceled", currentPeriodEnd: periodEnd, settledAt: when(data.canceled_at) ?? snapshotAt } };
283
+ return { ok: false, reason: "unknown_status" };
284
+ }
285
+ function readPaddleTransaction(data) {
286
+ if (!isObject(data)) return null;
287
+ const transactionId = text(data.id);
288
+ if (transactionId === null || !transactionId.startsWith("txn_")) return null;
289
+ const custom = isObject(data.custom_data) ? data.custom_data : null;
290
+ return { transactionId, subscriptionId: text(data.subscription_id), customerId: text(data.customer_id), organizationId: custom === null ? null : text(custom.organization_id) };
291
+ }
292
+
293
+ // src/checkout.ts
294
+ function canStartCheckout(record, now) {
295
+ if (record === null) return { ok: false, reason: "no_plan" };
296
+ if (record.status === "trialing") return { ok: true };
297
+ if (record.status === "canceled" || record.status === "paused") {
298
+ return record.currentPeriodEnd !== null && record.currentPeriodEnd.getTime() > now.getTime() ? { ok: false, reason: "still_covered" } : { ok: true };
299
+ }
300
+ return { ok: false, reason: "already_paying" };
301
+ }
302
+ var checkoutKey = (interval, seats) => `${interval}:${seats}`;
303
+ var PENDING_CHECKOUT_MS = 30 * 6e4;
304
+ function reusableCheckout(pending, wantedKey, now, maxAgeMs = PENDING_CHECKOUT_MS) {
305
+ if (pending.transactionId === null || pending.transactionId === "" || pending.at === null || pending.key !== wantedKey) return null;
306
+ const age = now.getTime() - pending.at.getTime();
307
+ return age >= 0 && age < maxAgeMs ? pending.transactionId : null;
308
+ }
309
+ function paddleTransactionBody(items, organizationId) {
310
+ if (items.length === 0) throw new Error("A checkout needs at least one item.");
311
+ if (typeof organizationId !== "string" || organizationId === "") throw new Error("A checkout needs the organization id.");
312
+ return { items: items.map((item) => ({ price_id: item.priceId, quantity: item.quantity })), custom_data: { organization_id: organizationId }, collection_mode: "automatic" };
313
+ }
190
314
  export {
191
315
  DAY_MS,
192
316
  InvalidPricePlanError,
317
+ PENDING_CHECKOUT_MS,
193
318
  accessFor,
194
319
  averagePerSeatCents,
195
320
  canAddSeat,
321
+ canStartCheckout,
322
+ checkoutKey,
196
323
  decideLock,
197
324
  definePricePlan,
198
325
  formatCents,
@@ -200,9 +327,14 @@ export {
200
327
  mustCheckOnRenew,
201
328
  paddleCatalog,
202
329
  paddleItems,
330
+ paddleTransactionBody,
203
331
  priceFor,
332
+ readPaddleSubscription,
333
+ readPaddleTransaction,
334
+ reusableCheckout,
204
335
  seatLimitFor,
205
336
  seatsUsed,
206
337
  syncPaddleCatalog,
207
- trialEndFrom
338
+ trialEndFrom,
339
+ verifyPaddleSignature
208
340
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/billing",
3
- "version": "1.1.0",
3
+ "version": "1.3.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",