@ordinatio/billing 1.2.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
@@ -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
@@ -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';
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
@@ -215,8 +215,14 @@ function verifyPaddleSignature(input) {
215
215
  }
216
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
217
  const tolerance = input.toleranceSeconds ?? 300;
218
+ if (!Number.isFinite(tolerance) || tolerance < 0) return { ok: false, reason: "malformed" };
218
219
  if (Math.abs(nowSeconds - Number(ts)) > tolerance) return { ok: false, reason: "stale" };
219
- const expected = hmacHex(secret, `${ts}:${rawBody}`).toLowerCase();
220
+ let expected;
221
+ try {
222
+ expected = hmacHex(secret, `${ts}:${rawBody}`).toLowerCase();
223
+ } catch {
224
+ return { ok: false, reason: "mismatch" };
225
+ }
220
226
  let matched = false;
221
227
  for (const hash of hashes) if (sameText(hash, expected)) matched = true;
222
228
  return matched ? { ok: true } : { ok: false, reason: "mismatch" };
@@ -229,7 +235,7 @@ var when = (value) => {
229
235
  const raw = text(value);
230
236
  if (raw === null) return null;
231
237
  const time = new Date(raw);
232
- return Number.isNaN(time.getTime()) ? null : new Date(Math.floor(time.getTime()));
238
+ return Number.isNaN(time.getTime()) ? null : time;
233
239
  };
234
240
  function readPaddleSubscription(plan, data, priceKeys) {
235
241
  if (!isObject(data)) return { ok: false, reason: "invalid" };
@@ -262,12 +268,13 @@ function readPaddleSubscription(plan, data, priceKeys) {
262
268
  const periodEnd = isObject(data.current_billing_period) ? when(data.current_billing_period.ends_at) : null;
263
269
  const base = { subscriptionId, customerId, interval, paidSeats: seats, snapshotAt };
264
270
  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 } };
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 } };
268
276
  return { ok: true, update: { ...base, status: "active", currentPeriodEnd: periodEnd, settledAt: null } };
269
277
  }
270
- if (status === "past_due") return { ok: true, update: { ...base, status: "past_due", currentPeriodEnd: periodEnd, settledAt: null } };
271
278
  if (status === "paused") {
272
279
  const pausedAt = when(data.paused_at) ?? snapshotAt;
273
280
  return { ok: true, update: { ...base, status: "paused", currentPeriodEnd: pausedAt, settledAt: pausedAt } };
@@ -282,12 +289,37 @@ function readPaddleTransaction(data) {
282
289
  const custom = isObject(data.custom_data) ? data.custom_data : null;
283
290
  return { transactionId, subscriptionId: text(data.subscription_id), customerId: text(data.customer_id), organizationId: custom === null ? null : text(custom.organization_id) };
284
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
+ }
285
314
  export {
286
315
  DAY_MS,
287
316
  InvalidPricePlanError,
317
+ PENDING_CHECKOUT_MS,
288
318
  accessFor,
289
319
  averagePerSeatCents,
290
320
  canAddSeat,
321
+ canStartCheckout,
322
+ checkoutKey,
291
323
  decideLock,
292
324
  definePricePlan,
293
325
  formatCents,
@@ -295,9 +327,11 @@ export {
295
327
  mustCheckOnRenew,
296
328
  paddleCatalog,
297
329
  paddleItems,
330
+ paddleTransactionBody,
298
331
  priceFor,
299
332
  readPaddleSubscription,
300
333
  readPaddleTransaction,
334
+ reusableCheckout,
301
335
  seatLimitFor,
302
336
  seatsUsed,
303
337
  syncPaddleCatalog,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/billing",
3
- "version": "1.2.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",