@ordinatio/billing 1.1.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
@@ -10,6 +10,8 @@ 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
+
13
15
  ```ts
14
16
  import { definePricePlan, priceFor, accessFor } from '@ordinatio/billing';
15
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;
@@ -221,4 +221,55 @@ 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
+ 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
  }
@@ -187,6 +187,101 @@ 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 (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
+ }
190
285
  export {
191
286
  DAY_MS,
192
287
  InvalidPricePlanError,
@@ -201,8 +296,11 @@ export {
201
296
  paddleCatalog,
202
297
  paddleItems,
203
298
  priceFor,
299
+ readPaddleSubscription,
300
+ readPaddleTransaction,
204
301
  seatLimitFor,
205
302
  seatsUsed,
206
303
  syncPaddleCatalog,
207
- trialEndFrom
304
+ trialEndFrom,
305
+ verifyPaddleSignature
208
306
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/billing",
3
- "version": "1.1.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",