@hjam91/billing 0.0.0-stage → 0.7.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.
@@ -0,0 +1,393 @@
1
+ /**
2
+ * Wire types shared by the SDK's entry points. Type-only: importing this file
3
+ * pulls no code into a bundle, so the browser-side `react` entry can use it.
4
+ */
5
+ /**
6
+ * Why an account is (or is not) entitled.
7
+ * - trial / paid / grace / exempt / free / none come from the billing service.
8
+ * free (since 0.4.0, additive): the app has not launched its pricing yet
9
+ * (prelaunch 'free'); everyone is entitled and no trial clock runs.
10
+ * - unverified is SDK-only: the service could not be reached and nothing
11
+ * was cached (see `source`).
12
+ */
13
+ export type EntitlementReason = 'trial' | 'paid' | 'grace' | 'exempt' | 'free' | 'none' | 'unverified';
14
+ export interface Entitlement {
15
+ account_id: string;
16
+ active: boolean;
17
+ reason: EntitlementReason;
18
+ plan: string | null;
19
+ quantity: number | null;
20
+ trial_ends_at: string | null;
21
+ current_period_end: string | null;
22
+ renews: boolean;
23
+ grace_ends_at: string | null;
24
+ covered_by_account_id: string | null;
25
+ /** Stripe status of the subscription the verdict is about (null without one). Since 0.2.0. */
26
+ subscription_status: string | null;
27
+ /** True while the latest payment failed (past_due / unpaid): show "fix your card". Since 0.2.0. */
28
+ payment_failed: boolean;
29
+ computed_at: string;
30
+ /**
31
+ * Since 0.5.0, only for apps that define features: feature id -> what the account may do
32
+ * (balances included). Apps without features never get this field.
33
+ */
34
+ features?: Record<string, FeatureEntry>;
35
+ }
36
+ /** Since 0.5.0. */
37
+ export type FeatureType = 'boolean' | 'metered' | 'static' | 'credit_system';
38
+ /**
39
+ * Why a feature is (or is not) allowed. 'unverified' is SDK-only: the service could not
40
+ * answer (see `source`), as for entitlements.
41
+ */
42
+ export type FeatureReason = 'ok' | 'unlimited' | 'exempt' | 'insufficient_balance' | 'not_in_plan' | 'no_plan' | 'disabled' | 'spend_cap_reached' | 'unverified';
43
+ /** Where the account's features come from: its exemption, its (or its payer's) subscription, a local trial, the app's default plan. */
44
+ export type PlanSource = 'exempt' | 'subscription' | 'covered' | 'lifetime' | 'trial' | 'default' | null;
45
+ /** One feature in an entitlement's `features` map (since 0.5.0). */
46
+ export interface FeatureEntry {
47
+ type: FeatureType;
48
+ allowed: boolean;
49
+ /** included - usage; null for boolean, unlimited and exempt. */
50
+ balance: number | null;
51
+ included: number | null;
52
+ usage: number | null;
53
+ unlimited: boolean;
54
+ resets_at: string | null;
55
+ reason: FeatureReason;
56
+ /** Since 0.6.0, only when credits / grants / overage / rollover are in play: grants (and an unwritten rollover) left. */
57
+ granted?: number;
58
+ overage_allowed?: boolean;
59
+ /** Overage units this period. */
60
+ overage_units?: number;
61
+ /** Since 0.6.0, a feature drawing from a credit pool: balances are in the pool's credits. */
62
+ credit_feature_id?: string;
63
+ credit_rate?: number;
64
+ }
65
+ /** POST /v1/check through the SDK (since 0.5.0). Never thrown: see `source`. */
66
+ export interface CheckResult {
67
+ account_id: string;
68
+ feature_id: string;
69
+ allowed: boolean;
70
+ /** null only when the SDK answered without the service and had nothing cached. */
71
+ type: FeatureType | null;
72
+ balance: number | null;
73
+ included: number | null;
74
+ usage: number | null;
75
+ unlimited: boolean;
76
+ resets_at: string | null;
77
+ plan: string | null;
78
+ plan_source: PlanSource;
79
+ reason: FeatureReason;
80
+ required_balance?: number;
81
+ source: EntitlementSource;
82
+ error?: string;
83
+ /** Since 0.6.0, only when credits / grants / overage / rollover are in play: grants (and an unwritten rollover) left. */
84
+ granted?: number;
85
+ overage_allowed?: boolean;
86
+ /** Overage units this period. */
87
+ overage_units?: number;
88
+ /** Since 0.6.0, a feature drawing from a credit pool: balances are in the pool's credits. */
89
+ credit_feature_id?: string;
90
+ credit_rate?: number;
91
+ }
92
+ /** POST /v1/track through the SDK (since 0.5.0). Never thrown. */
93
+ export interface TrackResult extends CheckResult {
94
+ value: number;
95
+ /** The usage was deducted and recorded. */
96
+ applied: boolean;
97
+ /** An earlier request with the same idempotency key was applied; nothing counted twice. */
98
+ replayed: boolean;
99
+ event_id: string | null;
100
+ check_and_track?: boolean;
101
+ /** The service was unreachable: the event waits in the SDK's retry buffer (allowed, reason 'unverified'). */
102
+ queued?: boolean;
103
+ /** Since 0.6.0, only when the draw went to overage or past the spend cap (pool units). */
104
+ drawn?: {
105
+ balance: number;
106
+ overage: number;
107
+ capped: number;
108
+ };
109
+ }
110
+ /** A one-time grant of balance (0.6.0). */
111
+ export interface Grant {
112
+ id: string;
113
+ feature_id: string;
114
+ source: 'grant' | 'pack' | 'topup' | 'rollover';
115
+ amount: number;
116
+ remaining: number;
117
+ expires_at: string | null;
118
+ reason: string | null;
119
+ created_at: string | null;
120
+ }
121
+ /** POST /v1/balances/lock and /finalize (0.6.0). */
122
+ export interface Lock {
123
+ lock_id: string | null;
124
+ allowed: boolean;
125
+ feature_id?: string;
126
+ pool_feature_id?: string;
127
+ amount: number;
128
+ pool_amount?: number;
129
+ status?: 'held' | 'finalized' | 'expired';
130
+ used?: number | null;
131
+ expires_at?: string | null;
132
+ released?: number;
133
+ replayed?: boolean;
134
+ balance: number | null;
135
+ reason?: FeatureReason;
136
+ }
137
+ export interface TopupRule {
138
+ feature_id: string;
139
+ threshold: number;
140
+ /** A one_time pack of the app that grants this feature. */
141
+ product: string;
142
+ /** The account's opt-in to off-session charges of its saved card. */
143
+ auto: boolean;
144
+ max_per_month: number;
145
+ }
146
+ /** GET /v1/accounts/:id/balances (0.6.0). */
147
+ export interface Balances {
148
+ account_id: string;
149
+ plan: string | null;
150
+ plan_source: PlanSource;
151
+ features: Record<string, {
152
+ type: FeatureType;
153
+ balance: number | null;
154
+ included: number | null;
155
+ usage: number | null;
156
+ unlimited: boolean;
157
+ periodic_remaining: number | null;
158
+ granted: number;
159
+ overage_allowed: boolean;
160
+ overage_units: number;
161
+ overage_amount: number;
162
+ overage_currency: string | null;
163
+ resets_at: string | null;
164
+ reason: FeatureReason;
165
+ drawn_by: Array<{
166
+ feature_id: string;
167
+ credit_rate: number;
168
+ }>;
169
+ }>;
170
+ grants: Grant[];
171
+ locks: Lock[];
172
+ spend_cap: {
173
+ amount: number;
174
+ currency: string;
175
+ } | null;
176
+ auto_topups: Array<TopupRule & {
177
+ last: Record<string, unknown> | null;
178
+ }>;
179
+ }
180
+ /** PUT /v1/accounts/:id/usage-settings (0.6.0). Omitted fields keep their value. */
181
+ export interface UsageSettingsInput {
182
+ /** Minor units per period across overage features; null removes the cap. */
183
+ spendCap?: {
184
+ amount: number;
185
+ currency: string;
186
+ } | null;
187
+ autoTopups?: Array<{
188
+ featureId: string;
189
+ threshold: number;
190
+ product: string;
191
+ auto?: boolean;
192
+ maxPerMonth?: number;
193
+ }>;
194
+ }
195
+ /** The typed events the service sends besides entitlement.changed (0.6.0); dedupe on `id`. */
196
+ export interface UsageEvent {
197
+ id: string;
198
+ /** 0.6 usage events, and (since 0.7.0, only the types the app chose in event_types) lifecycle events. */
199
+ type: 'usage.threshold_reached' | 'balance.low' | 'topup.succeeded' | 'topup.failed' | 'subscription.created' | 'subscription.updated' | 'subscription.canceled' | 'subscription.plan_changed' | 'trial.will_end' | 'invoice.paid' | 'invoice.payment_failed';
200
+ created: string;
201
+ app_id: string;
202
+ account_id: string;
203
+ attempt?: number;
204
+ data: Record<string, unknown>;
205
+ }
206
+ export type BillingEvent = EntitlementChangedEvent | UsageEvent;
207
+ /** POST /v1/subscriptions/change (since 0.7.0): what happened to the plan. */
208
+ export interface PlanChange {
209
+ status: 'applied' | 'scheduled' | 'requires_action';
210
+ plan: string;
211
+ from_plan: string | null;
212
+ direction: 'upgrade' | 'downgrade' | 'interval';
213
+ effective_at: string | null;
214
+ /** requires_action: the invoice page where the customer completes 3DS / pays. */
215
+ action_url: string | null;
216
+ amount_due_now?: number | null;
217
+ }
218
+ /** POST /v1/subscriptions/change/preview (since 0.7.0). Amounts in minor units. */
219
+ export interface ChangePreview {
220
+ plan: string;
221
+ from_plan: string | null;
222
+ direction: 'upgrade' | 'downgrade' | 'interval';
223
+ when: 'now' | 'period_end';
224
+ proration: 'create_prorations' | 'always_invoice' | 'none';
225
+ currency: string | null;
226
+ /** Pass back to changePlan to be charged exactly this preview. */
227
+ proration_date: number;
228
+ amount_due_now: number;
229
+ next_invoice_amount: number;
230
+ effective_at: string | null;
231
+ lines: Array<{
232
+ description: string | null;
233
+ amount: number;
234
+ proration: boolean;
235
+ }>;
236
+ }
237
+ /** GET /v1/plans (since 0.7.0): the app's public plans; never a custom or hidden one. */
238
+ export interface PublicPlan {
239
+ plan: string;
240
+ kind: 'free' | 'subscription' | 'add_on' | 'pack' | 'lifetime';
241
+ price: {
242
+ id: string;
243
+ unit_amount: number | null;
244
+ currency: string | null;
245
+ interval: string | null;
246
+ interval_count: number | null;
247
+ } | null;
248
+ items?: Array<Record<string, unknown>>;
249
+ grants?: Array<{
250
+ feature_id: string;
251
+ amount: number;
252
+ expires_in_days?: number;
253
+ }>;
254
+ }
255
+ /**
256
+ * Where an answer came from:
257
+ * - live: fetched from the service just now
258
+ * - cache: cached and younger than ttlSeconds
259
+ * - stale: cached and older (served while refreshing in the background,
260
+ * or because the service is failing)
261
+ * - fail_open: service unreachable, nothing cached, allowed anyway (failOpen: true)
262
+ * - error: service unreachable, nothing cached, denied (failOpen: false)
263
+ */
264
+ export type EntitlementSource = 'live' | 'cache' | 'stale' | 'fail_open' | 'error';
265
+ export interface EntitlementResult extends Entitlement {
266
+ source: EntitlementSource;
267
+ /** Error code when the answer is not from the service (source fail_open / error). */
268
+ error?: string;
269
+ }
270
+ export interface SubscriptionView {
271
+ id: string;
272
+ plan: string | null;
273
+ quantity: number;
274
+ status: string;
275
+ auto_renew: boolean;
276
+ cancel_at_period_end: boolean;
277
+ cancel_at: string | null;
278
+ current_period_start: string | null;
279
+ current_period_end: string | null;
280
+ /** When the card is next charged; null when it will not renew. */
281
+ next_billing_date: string | null;
282
+ paid_through: string | null;
283
+ started_at: string | null;
284
+ canceled_at: string | null;
285
+ ended_at: string | null;
286
+ price_id?: string | null;
287
+ payment_failed_at?: string | null;
288
+ /** Access was ended early (full refund, dispute, immediate cancel, duplicate). */
289
+ revoked_at?: string | null;
290
+ revoke_reason?: string | null;
291
+ /** Needs the owner: unknown_price | duplicate_refund_failed | disputed | cancel_failed | create_failed | requires_action … */
292
+ flag?: string | null;
293
+ /** The account this subscription pays for; null = its owner. Since 0.4.0 (G2). */
294
+ covers_account_id?: string | null;
295
+ /** The customer must complete a payment (3DS / declined first payment) at `action_url`. Since 0.4.0 (G3). */
296
+ requires_action?: boolean;
297
+ action_url?: string | null;
298
+ }
299
+ /** A subscription ANOTHER account holds for this one (read-only here; only the payer manages it). Since 0.4.0. */
300
+ export interface PaidBy {
301
+ account_id: string;
302
+ subscription_id: string;
303
+ plan: string | null;
304
+ status: string;
305
+ auto_renew: boolean;
306
+ current_period_end: string | null;
307
+ next_billing_date: string | null;
308
+ paid_through: string | null;
309
+ requires_action: boolean;
310
+ }
311
+ /** What happened to each subscription an auto-renew / cancel targeted. Since 0.4.0. */
312
+ export interface SubscriptionResult {
313
+ subscription_id: string;
314
+ covers_account_id: string | null;
315
+ ok: boolean;
316
+ error?: string;
317
+ message?: string;
318
+ }
319
+ /** GET /v1/accounts/:id — everything a billing page needs. */
320
+ export interface AccountStatus {
321
+ account_id: string;
322
+ entitlement: Omit<Entitlement, 'account_id'>;
323
+ has_subscription: boolean;
324
+ has_billing_customer: boolean;
325
+ /** True when this account owns a subscription it can manage (portal, auto-renew). */
326
+ can_manage: boolean;
327
+ plan: string | null;
328
+ quantity: number | null;
329
+ auto_renew: boolean;
330
+ next_billing_date: string | null;
331
+ current_period_end: string | null;
332
+ subscription: SubscriptionView | null;
333
+ subscriptions: SubscriptionView[];
334
+ exempt: boolean;
335
+ trial_ends_at: string | null;
336
+ covered_by_account_id: string | null;
337
+ email: string | null;
338
+ /** A trial was granted at some point (never reset). Since 0.2.0. */
339
+ trial_used?: boolean;
340
+ /** POST /v1/accounts/:id/trial would succeed ('explicit' trial mode only). Since 0.2.0. */
341
+ trial_available?: boolean;
342
+ trial_mode?: 'on_first_seen' | 'explicit';
343
+ /** Subscriptions other accounts hold for this one (G2). Since 0.4.0. */
344
+ paid_by?: PaidBy[];
345
+ /** Exempt by its own flag or its policy parent's (G7). Since 0.4.0. */
346
+ exempt_source?: 'own' | 'parent' | null;
347
+ /** Where trial_ends_at comes from. Since 0.4.0. */
348
+ trial_source?: 'stamped' | 'own' | 'parent' | 'computed' | null;
349
+ parent_account_id?: string | null;
350
+ role?: 'payer' | null;
351
+ /** The account's creation date in the app, as supplied (the trial anchor). Since 0.4.0. */
352
+ created_at?: string | null;
353
+ /** Only on auto-renew / cancel answers. Since 0.4.0. */
354
+ results?: SubscriptionResult[];
355
+ }
356
+ /** PUT /v1/accounts/:id and POST /v1/accounts/upsert. A field left out is left alone; null clears it. Since 0.4.0. */
357
+ export interface AccountInput {
358
+ /** The account's creation date in the app (the account_created / app_launch trial anchor). */
359
+ createdAt?: string | number | Date | null;
360
+ /** A POLICY parent (one level): exempt, trial override and createdAt are inherited when the account has none. */
361
+ parentAccountId?: string | null;
362
+ /** 'payer': pays for others only; no trial clock. */
363
+ role?: 'payer' | null;
364
+ email?: string;
365
+ }
366
+ export interface UpsertResult {
367
+ results: Array<{
368
+ account_id: string;
369
+ action: 'created' | 'updated' | 'unchanged';
370
+ }>;
371
+ errors: Array<{
372
+ account_id: string;
373
+ error: string;
374
+ message: string;
375
+ }>;
376
+ }
377
+ /** The body the billing service POSTs to the app's webhook_url. */
378
+ export interface EntitlementChangedEvent {
379
+ id: string;
380
+ type: 'entitlement.changed';
381
+ created: string;
382
+ app_id: string;
383
+ account_id: string;
384
+ /** Delivery attempt (1, 2, …); `id` stays the same across retries — dedupe on it. Since 0.2.0. */
385
+ attempt?: number;
386
+ entitlement: Omit<Entitlement, 'account_id'>;
387
+ }
388
+ /** Error codes the API returns (stable; branch on these, not on messages). */
389
+ export type BillingErrorCode = 'missing_credentials' | 'invalid_credentials' | 'app_disabled'
390
+ /** 0.7 security: the service is locked down (only the owner key works). */
391
+ | 'service_locked_down' | 'ip_not_allowed' | 'rate_limited' | 'too_many_auth_failures' | 'invalid_json' | 'invalid_account_id' | 'invalid_field' | 'invalid_email' | 'invalid_url' | 'origin_not_allowed' | 'unknown_plan' | 'price_not_found' | 'exempt' | 'covered_by_account' | 'already_subscribed' | 'no_billing_customer' | 'no_subscription' | 'coverage_self' | 'coverage_chain' | 'trial_used' | 'trial_unavailable' | 'cancel_failed' | 'account_not_found' | 'portal_not_configured' | 'covers_self' | 'too_many_covers' | 'covered_elsewhere' | 'accounts_not_eligible' | 'not_launched' | 'promotion_code_not_supported' | 'parent_chain' | 'parent_self' | 'too_many_ids' | 'key_scope_denied' | 'invoice_not_found' | 'invoice_not_paid' | 'nothing_refundable' | 'over_refundable' | 'bad_amount' | 'no_charge' | 'feature_not_found' | 'feature_not_metered' | 'invalid_feature_id' | 'too_many_events' | 'plan_not_purchasable' | 'lock_not_found' | 'lock_not_held' | 'already_lifetime' | 'covers_not_supported' | 'resume_failed' | 'same_plan' | 'add_on_requires_base' | 'not_an_add_on' | 'add_on_not_found' | 'already_entitled' | 'currency_mismatch' | 'pack_too_small'
392
+ /** 0.7 review / prerelease: codes the service answers that earlier unions missed. */
393
+ | 'price_not_owned' | 'reason_required' | 'prune_refused' | 'storage_unavailable' | 'invalid_admin_key' | 'app_not_found' | 'not_found' | 'forbidden' | 'misconfigured' | 'stripe_not_configured' | 'stripe_permission' | 'stripe_key_unreadable' | 'no_stripe_key' | 'invalid_config' | 'invalid_items' | 'invalid_plans' | 'invalid_origin' | 'invalid_event' | 'invalid_signature' | 'invalid_app_id' | 'confirm_required' | 'feature_exists' | 'feature_in_use' | 'too_many_features' | 'plan_exists' | 'plan_not_found' | 'version_not_found' | 'key_not_found' | 'too_many_keys' | 'has_live_subscriptions' | 'mark_key_in_use' | 'no_accounts' | 'no_customer' | 'no_payment_method' | 'no_pending_setup' | 'no_subscription_item' | 'price_unreadable' | 'customer_owned_by_another_account' | 'different_customer_already_linked' | 'subscription_customer_mismatch' | 'subscription_missing_in_stripe' | 'subscription_owned_by_another_account' | 'webhook_not_found' | 'no_webhook_url' | 'no_webhook_secret' | 'invalid_webhook_secret' | 'invalid_stripe_key' | 'stripe_mode_mismatch' | 'endpoint_exists' | 'unsupported_media_type' | 'stripe_error' | 'internal' | 'network_error' | 'timeout' | (string & {});
package/dist/types.js ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Wire types shared by the SDK's entry points. Type-only: importing this file
3
+ * pulls no code into a bundle, so the browser-side `react` entry can use it.
4
+ */
5
+ export {};
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Verifies the `entitlement.changed` POSTs the billing service sends to the app.
3
+ *
4
+ * Billing-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(webhook_secret, `${t}.${rawBody}`)>
5
+ *
6
+ * The same construction as Stripe's, verified with WebCrypto (Workers, Node
7
+ * >= 20, browsers). The timestamp is the replay protection: a captured
8
+ * request replayed after `toleranceSeconds` is refused even though its HMAC
9
+ * is valid. (The service's test suite checks this file against the service's
10
+ * signer, so the two cannot drift.)
11
+ */
12
+ import type { BillingEvent, EntitlementChangedEvent } from './types.js';
13
+ export declare const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
14
+ export type BillingWebhookErrorCode = 'missing_signature' | 'malformed_signature' | 'timestamp_out_of_tolerance' | 'signature_mismatch' | 'invalid_payload';
15
+ export declare class BillingWebhookError extends Error {
16
+ readonly code: BillingWebhookErrorCode;
17
+ constructor(code: BillingWebhookErrorCode, message?: string);
18
+ }
19
+ /** Anything with an `invalidate(accountId)` — normally the client from createBilling(). */
20
+ export interface Invalidates {
21
+ invalidate(accountId: string): Promise<void>;
22
+ }
23
+ export interface VerifyOptions {
24
+ toleranceSeconds?: number;
25
+ /** Pass the billing client to drop the cached entitlement for the account. */
26
+ billing?: Invalidates;
27
+ /** Clock override, epoch ms (tests). */
28
+ now?: number;
29
+ }
30
+ /**
31
+ * Verifies and parses an incoming entitlement.changed. Throws
32
+ * BillingWebhookError (answer 400) on anything wrong.
33
+ *
34
+ * Accepts the Request itself (its body is consumed) or, for frameworks that
35
+ * already read the body, `{ body, signature }` with the RAW body text.
36
+ */
37
+ export declare function verifyBillingWebhook(input: Request | {
38
+ body: string;
39
+ signature: string | null | undefined;
40
+ },
41
+ /** The webhook secret, or several during the app's own rotation (any one may match). */
42
+ secret: string | string[], opts?: VerifyOptions): Promise<EntitlementChangedEvent>;
43
+ /**
44
+ * Since 0.5.0 of the SDK / 0.6.0 of the service: verifies ANY signed event the service sends —
45
+ * entitlement.changed, usage.threshold_reached, balance.low, topup.succeeded, topup.failed — and
46
+ * returns it (switch on `type`; answer 2xx to types you do not handle). Same signature rules as
47
+ * verifyBillingWebhook. With `billing`, entitlement.changed and topup.* drop the account's cache entry.
48
+ */
49
+ export declare function verifyBillingEvent(input: Request | {
50
+ body: string;
51
+ signature: string | null | undefined;
52
+ }, secret: string | string[], opts?: VerifyOptions): Promise<BillingEvent>;
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Verifies the `entitlement.changed` POSTs the billing service sends to the app.
3
+ *
4
+ * Billing-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(webhook_secret, `${t}.${rawBody}`)>
5
+ *
6
+ * The same construction as Stripe's, verified with WebCrypto (Workers, Node
7
+ * >= 20, browsers). The timestamp is the replay protection: a captured
8
+ * request replayed after `toleranceSeconds` is refused even though its HMAC
9
+ * is valid. (The service's test suite checks this file against the service's
10
+ * signer, so the two cannot drift.)
11
+ */
12
+ export const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
13
+ export class BillingWebhookError extends Error {
14
+ code;
15
+ constructor(code, message) {
16
+ super(message ?? code);
17
+ this.name = 'BillingWebhookError';
18
+ this.code = code;
19
+ }
20
+ }
21
+ const enc = new TextEncoder();
22
+ async function hmacHex(key, msg) {
23
+ const k = await crypto.subtle.importKey('raw', enc.encode(key), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
24
+ const sig = new Uint8Array(await crypto.subtle.sign('HMAC', k, enc.encode(msg)));
25
+ return Array.from(sig, (b) => b.toString(16).padStart(2, '0')).join('');
26
+ }
27
+ function constantTimeEqual(a, b) {
28
+ let diff = a.length ^ b.length;
29
+ for (let i = 0; i < Math.max(a.length, b.length); i++)
30
+ diff |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0);
31
+ return diff === 0;
32
+ }
33
+ /**
34
+ * Verifies and parses an incoming entitlement.changed. Throws
35
+ * BillingWebhookError (answer 400) on anything wrong.
36
+ *
37
+ * Accepts the Request itself (its body is consumed) or, for frameworks that
38
+ * already read the body, `{ body, signature }` with the RAW body text.
39
+ */
40
+ export async function verifyBillingWebhook(input,
41
+ /** The webhook secret, or several during the app's own rotation (any one may match). */
42
+ secret, opts = {}) {
43
+ const event = await verifyBillingEvent(input, secret, { ...opts, billing: undefined });
44
+ if (event.type !== 'entitlement.changed' || !event.entitlement)
45
+ throw new BillingWebhookError('invalid_payload', 'Not an entitlement.changed event');
46
+ // Invalidate rather than store the pushed value: notifications are
47
+ // best-effort and may arrive out of order; the next read fetches the truth.
48
+ if (opts.billing)
49
+ await opts.billing.invalidate(event.account_id);
50
+ return event;
51
+ }
52
+ /**
53
+ * Since 0.5.0 of the SDK / 0.6.0 of the service: verifies ANY signed event the service sends —
54
+ * entitlement.changed, usage.threshold_reached, balance.low, topup.succeeded, topup.failed — and
55
+ * returns it (switch on `type`; answer 2xx to types you do not handle). Same signature rules as
56
+ * verifyBillingWebhook. With `billing`, entitlement.changed and topup.* drop the account's cache entry.
57
+ */
58
+ export async function verifyBillingEvent(input, secret, opts = {}) {
59
+ const body = input instanceof Request ? await input.text() : input.body;
60
+ const header = input instanceof Request ? input.headers.get('Billing-Signature') : input.signature;
61
+ if (!header)
62
+ throw new BillingWebhookError('missing_signature');
63
+ let t = NaN;
64
+ const sigs = [];
65
+ for (const part of header.split(',')) {
66
+ const [k, v] = part.split('=', 2).map((s) => s.trim());
67
+ if (k === 't')
68
+ t = Number(v);
69
+ else if (k === 'v1' && v && /^[0-9a-f]{64}$/i.test(v))
70
+ sigs.push(v.toLowerCase());
71
+ }
72
+ if (!Number.isInteger(t) || sigs.length === 0)
73
+ throw new BillingWebhookError('malformed_signature');
74
+ const tolerance = opts.toleranceSeconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS;
75
+ const nowSec = Math.floor((opts.now ?? Date.now()) / 1000);
76
+ if (Math.abs(nowSec - t) > tolerance)
77
+ throw new BillingWebhookError('timestamp_out_of_tolerance');
78
+ let ok = false;
79
+ for (const sec of (Array.isArray(secret) ? secret : [secret]).filter(Boolean)) {
80
+ const expected = await hmacHex(sec, `${t}.${body}`);
81
+ for (const s of sigs)
82
+ ok = constantTimeEqual(s, expected) || ok;
83
+ }
84
+ if (!ok)
85
+ throw new BillingWebhookError('signature_mismatch');
86
+ let event;
87
+ try {
88
+ event = JSON.parse(body);
89
+ }
90
+ catch {
91
+ throw new BillingWebhookError('invalid_payload', 'Body is not JSON');
92
+ }
93
+ if (typeof event?.type !== 'string' || typeof event.account_id !== 'string' || typeof event.id !== 'string')
94
+ throw new BillingWebhookError('invalid_payload', 'Not a billing event');
95
+ if (opts.billing && (event.type === 'entitlement.changed' || event.type.startsWith('topup.')))
96
+ await opts.billing.invalidate(event.account_id);
97
+ return event;
98
+ }
package/package.json CHANGED
@@ -1,6 +1,77 @@
1
1
  {
2
2
  "name": "@hjam91/billing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.7.0",
4
+ "description": "Zero-dependency client for a billing-kit service: cached, fail-open entitlement and feature checks, usage tracking, Stripe Checkout / portal, signed webhook verification, a Hono gate and an optional React billing card.",
5
+ "keywords": [
6
+ "billing",
7
+ "subscriptions",
8
+ "stripe",
9
+ "entitlements",
10
+ "feature-flags",
11
+ "usage-based-billing",
12
+ "paywall",
13
+ "hono",
14
+ "react",
15
+ "cloudflare-workers"
16
+ ],
17
+ "license": "MIT",
18
+ "type": "module",
19
+ "sideEffects": false,
20
+ "engines": {
21
+ "node": ">=20"
22
+ },
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js",
29
+ "default": "./dist/index.js"
30
+ },
31
+ "./kv": {
32
+ "types": "./dist/kv.d.ts",
33
+ "import": "./dist/kv.js",
34
+ "default": "./dist/kv.js"
35
+ },
36
+ "./hono": {
37
+ "types": "./dist/hono.d.ts",
38
+ "import": "./dist/hono.js",
39
+ "default": "./dist/hono.js"
40
+ },
41
+ "./react": {
42
+ "types": "./dist/react.d.ts",
43
+ "import": "./dist/react.js",
44
+ "default": "./dist/react.js"
45
+ },
46
+ "./config": {
47
+ "types": "./dist/config.d.ts",
48
+ "import": "./dist/config.js",
49
+ "default": "./dist/config.js"
50
+ },
51
+ "./package.json": "./package.json"
52
+ },
53
+ "bin": {
54
+ "billing-cli": "dist/cli.mjs"
55
+ },
56
+ "files": [
57
+ "dist",
58
+ "README.md",
59
+ "LICENSE"
60
+ ],
61
+ "publishConfig": {
62
+ "access": "public",
63
+ "provenance": false
64
+ },
65
+ "peerDependencies": {
66
+ "hono": ">=4",
67
+ "react": ">=18"
68
+ },
69
+ "peerDependenciesMeta": {
70
+ "hono": {
71
+ "optional": true
72
+ },
73
+ "react": {
74
+ "optional": true
75
+ }
76
+ }
77
+ }