@ordinatio/billing 1.2.0 → 1.4.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
@@ -12,6 +12,8 @@ The billing rules of a subscription product, pure and with no database, no frame
12
12
 
13
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
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
+
15
17
  ```ts
16
18
  import { definePricePlan, priceFor, accessFor } from '@ordinatio/billing';
17
19
 
package/dist/index.d.ts CHANGED
@@ -225,7 +225,7 @@ type SignatureResult = {
225
225
  ok: true;
226
226
  } | {
227
227
  ok: false;
228
- reason: 'missing' | 'malformed' | 'stale' | 'mismatch';
228
+ reason: 'missing' | 'malformed' | 'stale' | 'mismatch' | 'config';
229
229
  };
230
230
  interface SignatureInput {
231
231
  header: string | null | undefined;
@@ -272,4 +272,40 @@ interface TransactionCompleted {
272
272
  /** The fields of a `transaction.completed` event's `data` that the handshake needs; null for anything that is not a completed transaction. */
273
273
  declare function readPaddleTransaction(data: unknown): TransactionCompleted | null;
274
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 };
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' | 'paused';
284
+ };
285
+ declare function canStartCheckout(record: CheckoutRecord, now: Date): CanStartCheckout;
286
+ /** What a checkout was made for, as text: `month:25`, or `cranberry-crm:month:25` when the catalog key is given (a changed catalog then never reuses a checkout made from the old prices). */
287
+ declare const checkoutKey: (interval: Interval, seats: number, catalogKey?: string) => 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
@@ -198,7 +198,8 @@ function sameText(a, b) {
198
198
  function verifyPaddleSignature(input) {
199
199
  const { header, rawBody, secret, nowSeconds, hmacHex } = input;
200
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" };
201
+ if (typeof rawBody !== "string") return { ok: false, reason: "malformed" };
202
+ if (typeof secret !== "string" || secret === "" || !Number.isFinite(nowSeconds)) return { ok: false, reason: "config" };
202
203
  let ts = null;
203
204
  const hashes = [];
204
205
  for (const part of header.split(";")) {
@@ -215,8 +216,14 @@ function verifyPaddleSignature(input) {
215
216
  }
216
217
  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
218
  const tolerance = input.toleranceSeconds ?? 300;
219
+ if (!Number.isFinite(tolerance) || tolerance < 0) return { ok: false, reason: "config" };
218
220
  if (Math.abs(nowSeconds - Number(ts)) > tolerance) return { ok: false, reason: "stale" };
219
- const expected = hmacHex(secret, `${ts}:${rawBody}`).toLowerCase();
221
+ let expected;
222
+ try {
223
+ expected = hmacHex(secret, `${ts}:${rawBody}`).toLowerCase();
224
+ } catch {
225
+ return { ok: false, reason: "config" };
226
+ }
220
227
  let matched = false;
221
228
  for (const hash of hashes) if (sameText(hash, expected)) matched = true;
222
229
  return matched ? { ok: true } : { ok: false, reason: "mismatch" };
@@ -229,7 +236,7 @@ var when = (value) => {
229
236
  const raw = text(value);
230
237
  if (raw === null) return null;
231
238
  const time = new Date(raw);
232
- return Number.isNaN(time.getTime()) ? null : new Date(Math.floor(time.getTime()));
239
+ return Number.isNaN(time.getTime()) ? null : time;
233
240
  };
234
241
  function readPaddleSubscription(plan, data, priceKeys) {
235
242
  if (!isObject(data)) return { ok: false, reason: "invalid" };
@@ -262,12 +269,13 @@ function readPaddleSubscription(plan, data, priceKeys) {
262
269
  const periodEnd = isObject(data.current_billing_period) ? when(data.current_billing_period.ends_at) : null;
263
270
  const base = { subscriptionId, customerId, interval, paidSeats: seats, snapshotAt };
264
271
  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 } };
272
+ if (status === "active" || status === "trialing" || status === "past_due") {
273
+ if ((action === "cancel" || action === "pause") && effectiveAt === null) return { ok: false, reason: "invalid" };
274
+ if (action === "cancel") return { ok: true, update: { ...base, status: "canceled", currentPeriodEnd: effectiveAt, settledAt: effectiveAt } };
275
+ if (action === "pause") return { ok: true, update: { ...base, status: "paused", currentPeriodEnd: effectiveAt, settledAt: effectiveAt } };
276
+ if (status === "past_due") return { ok: true, update: { ...base, status: "past_due", currentPeriodEnd: periodEnd, settledAt: null } };
268
277
  return { ok: true, update: { ...base, status: "active", currentPeriodEnd: periodEnd, settledAt: null } };
269
278
  }
270
- if (status === "past_due") return { ok: true, update: { ...base, status: "past_due", currentPeriodEnd: periodEnd, settledAt: null } };
271
279
  if (status === "paused") {
272
280
  const pausedAt = when(data.paused_at) ?? snapshotAt;
273
281
  return { ok: true, update: { ...base, status: "paused", currentPeriodEnd: pausedAt, settledAt: pausedAt } };
@@ -282,12 +290,42 @@ function readPaddleTransaction(data) {
282
290
  const custom = isObject(data.custom_data) ? data.custom_data : null;
283
291
  return { transactionId, subscriptionId: text(data.subscription_id), customerId: text(data.customer_id), organizationId: custom === null ? null : text(custom.organization_id) };
284
292
  }
293
+
294
+ // src/checkout.ts
295
+ function canStartCheckout(record, now) {
296
+ if (record === null) return { ok: false, reason: "no_plan" };
297
+ if (record.status === "trialing") return { ok: true };
298
+ if (record.status === "paused") return { ok: false, reason: "paused" };
299
+ if (record.status === "canceled") {
300
+ return record.currentPeriodEnd !== null && record.currentPeriodEnd.getTime() > now.getTime() ? { ok: false, reason: "still_covered" } : { ok: true };
301
+ }
302
+ return { ok: false, reason: "already_paying" };
303
+ }
304
+ var checkoutKey = (interval, seats, catalogKey) => catalogKey ? `${catalogKey}:${interval}:${seats}` : `${interval}:${seats}`;
305
+ var PENDING_CHECKOUT_MS = 30 * 6e4;
306
+ function reusableCheckout(pending, wantedKey, now, maxAgeMs = PENDING_CHECKOUT_MS) {
307
+ if (pending.transactionId === null || pending.transactionId === "" || pending.at === null || pending.key !== wantedKey) return null;
308
+ const age = now.getTime() - pending.at.getTime();
309
+ return age >= 0 && age < maxAgeMs ? pending.transactionId : null;
310
+ }
311
+ function paddleTransactionBody(items, organizationId) {
312
+ if (items.length === 0) throw new Error("A checkout needs at least one item.");
313
+ if (typeof organizationId !== "string" || organizationId === "") throw new Error("A checkout needs the organization id.");
314
+ for (const item of items) {
315
+ if (typeof item.priceId !== "string" || item.priceId === "") throw new Error("Every checkout item needs a price id.");
316
+ if (!Number.isInteger(item.quantity) || item.quantity < 1) throw new Error("Every checkout item needs a whole quantity of at least 1.");
317
+ }
318
+ return { items: items.map((item) => ({ price_id: item.priceId, quantity: item.quantity })), custom_data: { organization_id: organizationId }, collection_mode: "automatic" };
319
+ }
285
320
  export {
286
321
  DAY_MS,
287
322
  InvalidPricePlanError,
323
+ PENDING_CHECKOUT_MS,
288
324
  accessFor,
289
325
  averagePerSeatCents,
290
326
  canAddSeat,
327
+ canStartCheckout,
328
+ checkoutKey,
291
329
  decideLock,
292
330
  definePricePlan,
293
331
  formatCents,
@@ -295,9 +333,11 @@ export {
295
333
  mustCheckOnRenew,
296
334
  paddleCatalog,
297
335
  paddleItems,
336
+ paddleTransactionBody,
298
337
  priceFor,
299
338
  readPaddleSubscription,
300
339
  readPaddleTransaction,
340
+ reusableCheckout,
301
341
  seatLimitFor,
302
342
  seatsUsed,
303
343
  syncPaddleCatalog,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/billing",
3
- "version": "1.2.0",
3
+ "version": "1.4.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",