@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.
package/dist/config.js ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Config-as-code (since 0.7.0): the document `billing-cli push | pull | diff` syncs with the service
3
+ * (POST/GET /admin/apps/:app/config). Type-only plus defineConfig(): safe to import anywhere.
4
+ *
5
+ * // billing.config.ts
6
+ * import { defineConfig } from '@hjam91/billing/config';
7
+ * export default defineConfig({
8
+ * features: [{ id: 'credits', type: 'credit_system' }, { id: 'images', type: 'metered', credit_feature: 'credits', credit_rate: 5 }],
9
+ * plans: {
10
+ * free: { free: true, items: { credits: { included: 10, reset: 'month' } } },
11
+ * pro: { price: { amount: 1900, currency: 'usd', interval: 'month' }, items: { credits: { included: 500, reset: 'month' } } },
12
+ * boost: { add_on: true, price: { amount: 500, currency: 'usd', interval: 'month' }, items: { credits: { included: 200, reset: 'month' } } },
13
+ * },
14
+ * default_plan: 'free',
15
+ * });
16
+ *
17
+ * A price given as {amount, currency, interval} is created once by the service (Stripe product per plan,
18
+ * deterministic lookup key); the same document pushed again creates nothing. Plans and features missing
19
+ * from the document are kept unless `--prune`.
20
+ */
21
+ /** Identity, for type checking a config file. */
22
+ export function defineConfig(config) {
23
+ return config;
24
+ }
25
+ /** One line per change, for the CLI's diff. */
26
+ export function formatChanges(changes) {
27
+ if (!changes.length)
28
+ return 'No changes.';
29
+ const sign = { create: '+', update: '~', delete: '-' };
30
+ return changes.map((c) => `${sign[c.op]} ${c.kind} ${c.id}${c.detail !== undefined ? ` ${JSON.stringify(c.detail)}` : ''}`).join('\n');
31
+ }
@@ -0,0 +1,17 @@
1
+ /** The error every SDK action throws (shared by createBilling and createBillingAdmin). Zero dependencies. */
2
+ import type { BillingErrorCode } from './types.js';
3
+ export declare class BillingError extends Error {
4
+ /** HTTP status from the service; 0 for network errors and timeouts. */
5
+ readonly status: number;
6
+ readonly code: BillingErrorCode;
7
+ /** The full error body (e.g. `portal_url` and `subscription_status` on 409 already_subscribed). */
8
+ readonly details: Record<string, unknown>;
9
+ constructor(status: number, code: BillingErrorCode, message: string, details?: Record<string, unknown>);
10
+ }
11
+ /** True for failures that mean "the service is having a bad day" (fail open), not "we are misconfigured". */
12
+ export declare function isOutage(err: unknown): boolean;
13
+ /**
14
+ * The owner's kill switch (0.7): 403 app_disabled (this app was switched off) or 503 service_locked_down (the
15
+ * whole service). What the SDK serves then is `onKill` (default 'fail_open'), never the outage or auth rules.
16
+ */
17
+ export declare function killSignal(err: unknown): 'app_disabled' | 'service_locked_down' | null;
package/dist/errors.js ADDED
@@ -0,0 +1,32 @@
1
+ /** The error every SDK action throws (shared by createBilling and createBillingAdmin). Zero dependencies. */
2
+ export class BillingError extends Error {
3
+ /** HTTP status from the service; 0 for network errors and timeouts. */
4
+ status;
5
+ code;
6
+ /** The full error body (e.g. `portal_url` and `subscription_status` on 409 already_subscribed). */
7
+ details;
8
+ constructor(status, code, message, details = {}) {
9
+ super(message);
10
+ this.name = 'BillingError';
11
+ this.status = status;
12
+ this.code = code;
13
+ this.details = details;
14
+ }
15
+ }
16
+ /** True for failures that mean "the service is having a bad day" (fail open), not "we are misconfigured". */
17
+ export function isOutage(err) {
18
+ const s = err?.status;
19
+ return typeof s !== 'number' || s === 0 || s >= 500 || s === 408 || s === 429;
20
+ }
21
+ /**
22
+ * The owner's kill switch (0.7): 403 app_disabled (this app was switched off) or 503 service_locked_down (the
23
+ * whole service). What the SDK serves then is `onKill` (default 'fail_open'), never the outage or auth rules.
24
+ */
25
+ export function killSignal(err) {
26
+ const e = err;
27
+ if (e?.status === 403 && e.code === 'app_disabled')
28
+ return 'app_disabled';
29
+ if (e?.status === 503 && e.code === 'service_locked_down')
30
+ return 'service_locked_down';
31
+ return null;
32
+ }
package/dist/hono.d.ts ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Hono helpers for the app's backend (hono is an optional peer dependency;
3
+ * the core SDK has none).
4
+ *
5
+ * app.use('/api/premium/*', requireEntitlement(billing, (c) => c.get('user')?.orgId));
6
+ * app.route('/api/billing', billingRoutes(billing, { getAccountId, canManage, webhookSecret, returnUrl }));
7
+ */
8
+ import { Hono, type Context, type MiddlewareHandler } from 'hono';
9
+ import type { Billing } from './index.js';
10
+ import type { CheckResult, EntitlementChangedEvent, EntitlementResult, UsageEvent } from './types.js';
11
+ /** Stable error codes the gate answers with. Clients branch on these. */
12
+ export declare const BILLING_INACTIVE = "billing_inactive";
13
+ export declare const BILLING_UNAVAILABLE = "billing_unavailable";
14
+ export declare const BILLING_ACCOUNT_REQUIRED = "billing_account_required";
15
+ /** The account's plan does not include the feature, or its balance is used up (since 0.5.0). */
16
+ export declare const FEATURE_UNAVAILABLE = "feature_unavailable";
17
+ type Maybe<T> = T | null | undefined;
18
+ type GetAccountId = (c: Context<any>) => Maybe<string> | Promise<Maybe<string>>;
19
+ export interface RequireEntitlementOptions {
20
+ /** Custom response when the account is not entitled (default: 402 JSON). */
21
+ onDenied?: (c: Context<any>, entitlement: EntitlementResult) => Response | Promise<Response>;
22
+ }
23
+ /**
24
+ * Lets the request through only if the account is entitled. Sets
25
+ * `c.get('entitlement')` for handlers. Answers:
26
+ * 401 {error: 'billing_account_required'} getAccountId returned nothing
27
+ * 402 {error: 'billing_inactive', reason, trial_ends_at, grace_ends_at}
28
+ * 503 {error: 'billing_unavailable'} only with failOpen: false and the service down
29
+ * With the default failOpen: true a billing outage never produces 402/503.
30
+ */
31
+ export declare function requireEntitlement(billing: Billing, getAccountId: GetAccountId, opts?: RequireEntitlementOptions): MiddlewareHandler<any>;
32
+ export interface RequireFeatureOptions {
33
+ /** How much the request needs (default 1). */
34
+ requiredBalance?: number | ((c: Context<any>) => number | Promise<number>);
35
+ /** Custom response when not allowed (default: 402 JSON). */
36
+ onDenied?: (c: Context<any>, check: CheckResult) => Response | Promise<Response>;
37
+ }
38
+ /**
39
+ * Lets the request through only if the account may use `featureId` (since 0.5.0). Sets
40
+ * `c.get('feature')` (the CheckResult) for handlers. It CHECKS only: record usage with
41
+ * billing.track() once the work is done (or use check_and_track there). Answers:
42
+ * 401 {error: 'billing_account_required'}
43
+ * 402 {error: 'feature_unavailable', feature_id, reason, balance, included, resets_at, plan}
44
+ * 503 {error: 'billing_unavailable'} only with failOpen: false and the service down
45
+ * A billing outage never denies with the default failOpen: true (reason 'unverified').
46
+ */
47
+ export declare function requireFeature(billing: Billing, featureId: string, getAccountId: GetAccountId, opts?: RequireFeatureOptions): MiddlewareHandler<any>;
48
+ export interface BillingRoutesOptions {
49
+ /** The billing account of the signed-in user (e.g. their org id). */
50
+ getAccountId: GetAccountId;
51
+ /**
52
+ * May this user manage billing for this account? THE APP DECIDES: e.g.
53
+ * "is an admin of the org", never "is a member". The service only ensures an
54
+ * account manages what it owns; it cannot know your roles.
55
+ */
56
+ canManage: (c: Context<any>, accountId: string) => boolean | Promise<boolean>;
57
+ /** The app's webhook_secret from registration (for POST /webhook). */
58
+ /** One secret, or several during a rotation. */
59
+ webhookSecret?: string | string[];
60
+ /** Where Stripe sends the user back (Checkout success/cancel, portal return). Must be an allowed origin. */
61
+ returnUrl: string | ((c: Context<any>) => string);
62
+ /** Optional email for a new Stripe customer (receipts). */
63
+ getEmail?: (c: Context<any>) => Maybe<string> | Promise<Maybe<string>>;
64
+ /** Plans the browser may ask for. Default: any (the service still rejects unknown plans). */
65
+ plans?: string[];
66
+ /** Called after a verified entitlement.changed (cache already invalidated). */
67
+ onEntitlementChanged?: (event: EntitlementChangedEvent) => void | Promise<void>;
68
+ /**
69
+ * Since 0.6.0: called after a verified usage.threshold_reached / balance.low / topup.succeeded / topup.failed.
70
+ * Without it those are acknowledged (200) and ignored.
71
+ */
72
+ onUsageEvent?: (event: UsageEvent) => void | Promise<void>;
73
+ }
74
+ /**
75
+ * The app's billing routes, ready to mount (e.g. at /api/billing):
76
+ *
77
+ * GET / billing status for the signed-in user's account
78
+ * GET /check?feature_id=…&required_balance=… may the signed-in user's account use a feature (0.5.0; read-only)
79
+ * POST /:action checkout {plan, quantity?} | portal | autorenew {auto_renew} | trial
80
+ * POST /webhook entitlement.changed from the billing service (signature-checked)
81
+ *
82
+ * The browser (sdk/react) calls these; the secret never leaves the server.
83
+ */
84
+ export declare function billingRoutes(billing: Billing, opts: BillingRoutesOptions): Hono<any>;
85
+ export {};
package/dist/hono.js ADDED
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Hono helpers for the app's backend (hono is an optional peer dependency;
3
+ * the core SDK has none).
4
+ *
5
+ * app.use('/api/premium/*', requireEntitlement(billing, (c) => c.get('user')?.orgId));
6
+ * app.route('/api/billing', billingRoutes(billing, { getAccountId, canManage, webhookSecret, returnUrl }));
7
+ */
8
+ import { Hono } from 'hono';
9
+ import { BillingWebhookError, verifyBillingEvent } from "./webhook.js";
10
+ /** Stable error codes the gate answers with. Clients branch on these. */
11
+ export const BILLING_INACTIVE = 'billing_inactive';
12
+ export const BILLING_UNAVAILABLE = 'billing_unavailable';
13
+ export const BILLING_ACCOUNT_REQUIRED = 'billing_account_required';
14
+ /** The account's plan does not include the feature, or its balance is used up (since 0.5.0). */
15
+ export const FEATURE_UNAVAILABLE = 'feature_unavailable';
16
+ const waitUntilOf = (c) => {
17
+ try {
18
+ const ctx = c.executionCtx;
19
+ return ctx.waitUntil.bind(ctx);
20
+ }
21
+ catch {
22
+ return undefined; // Node / tests: no ExecutionContext
23
+ }
24
+ };
25
+ /**
26
+ * Lets the request through only if the account is entitled. Sets
27
+ * `c.get('entitlement')` for handlers. Answers:
28
+ * 401 {error: 'billing_account_required'} getAccountId returned nothing
29
+ * 402 {error: 'billing_inactive', reason, trial_ends_at, grace_ends_at}
30
+ * 503 {error: 'billing_unavailable'} only with failOpen: false and the service down
31
+ * With the default failOpen: true a billing outage never produces 402/503.
32
+ */
33
+ export function requireEntitlement(billing, getAccountId, opts = {}) {
34
+ return async (c, next) => {
35
+ const accountId = await getAccountId(c);
36
+ if (!accountId)
37
+ return c.json({ error: BILLING_ACCOUNT_REQUIRED, message: 'No billing account for this request' }, 401);
38
+ const ent = await billing.getEntitlement(accountId, { waitUntil: waitUntilOf(c) });
39
+ c.set('entitlement', ent);
40
+ if (ent.active)
41
+ return next();
42
+ if (opts.onDenied)
43
+ return opts.onDenied(c, ent);
44
+ if (ent.source === 'error')
45
+ return c.json({ error: BILLING_UNAVAILABLE, message: 'Billing could not be verified' }, 503);
46
+ return c.json({
47
+ error: BILLING_INACTIVE,
48
+ message: 'A subscription is required',
49
+ reason: ent.reason,
50
+ trial_ends_at: ent.trial_ends_at,
51
+ grace_ends_at: ent.grace_ends_at,
52
+ }, 402);
53
+ };
54
+ }
55
+ /**
56
+ * Lets the request through only if the account may use `featureId` (since 0.5.0). Sets
57
+ * `c.get('feature')` (the CheckResult) for handlers. It CHECKS only: record usage with
58
+ * billing.track() once the work is done (or use check_and_track there). Answers:
59
+ * 401 {error: 'billing_account_required'}
60
+ * 402 {error: 'feature_unavailable', feature_id, reason, balance, included, resets_at, plan}
61
+ * 503 {error: 'billing_unavailable'} only with failOpen: false and the service down
62
+ * A billing outage never denies with the default failOpen: true (reason 'unverified').
63
+ */
64
+ export function requireFeature(billing, featureId, getAccountId, opts = {}) {
65
+ return async (c, next) => {
66
+ const accountId = await getAccountId(c);
67
+ if (!accountId)
68
+ return c.json({ error: BILLING_ACCOUNT_REQUIRED, message: 'No billing account for this request' }, 401);
69
+ const required = typeof opts.requiredBalance === 'function' ? await opts.requiredBalance(c) : opts.requiredBalance;
70
+ const check = await billing.check(accountId, featureId, required !== undefined ? { requiredBalance: required } : {});
71
+ c.set('feature', check);
72
+ if (check.allowed)
73
+ return next();
74
+ if (opts.onDenied)
75
+ return opts.onDenied(c, check);
76
+ if (check.source === 'error' && check.reason === 'unverified' && check.error !== 'feature_not_found')
77
+ return c.json({ error: BILLING_UNAVAILABLE, message: 'Billing could not be verified' }, 503);
78
+ return c.json({
79
+ error: FEATURE_UNAVAILABLE,
80
+ message: check.reason === 'insufficient_balance' ? `No ${featureId} left` : `${featureId} is not included in this plan`,
81
+ feature_id: featureId,
82
+ reason: check.reason,
83
+ balance: check.balance,
84
+ included: check.included,
85
+ resets_at: check.resets_at,
86
+ plan: check.plan,
87
+ }, 402);
88
+ };
89
+ }
90
+ /**
91
+ * The app's billing routes, ready to mount (e.g. at /api/billing):
92
+ *
93
+ * GET / billing status for the signed-in user's account
94
+ * GET /check?feature_id=…&required_balance=… may the signed-in user's account use a feature (0.5.0; read-only)
95
+ * POST /:action checkout {plan, quantity?} | portal | autorenew {auto_renew} | trial
96
+ * POST /webhook entitlement.changed from the billing service (signature-checked)
97
+ *
98
+ * The browser (sdk/react) calls these; the secret never leaves the server.
99
+ */
100
+ export function billingRoutes(billing, opts) {
101
+ const r = new Hono();
102
+ const resolveReturn = (c) => (typeof opts.returnUrl === 'function' ? opts.returnUrl(c) : opts.returnUrl);
103
+ const asError = (c, err) => {
104
+ const e = err;
105
+ // Pass through the user-meaningful ones; anything else (incl. a 401 about
106
+ // OUR app secret) is the backend's problem, not the browser's.
107
+ const status = e.status === 400 || e.status === 404 || e.status === 409 ? e.status : 502;
108
+ return c.json({ error: e.code ?? 'billing_error', message: e.message ?? 'Billing request failed' }, status);
109
+ };
110
+ // Registered before /:action so "webhook" is never treated as an action.
111
+ r.post('/webhook', async (c) => {
112
+ if (!opts.webhookSecret)
113
+ return c.json({ error: 'not_configured' }, 404);
114
+ try {
115
+ const event = await verifyBillingEvent(c.req.raw, opts.webhookSecret, { billing });
116
+ if (event.type === 'entitlement.changed')
117
+ await opts.onEntitlementChanged?.(event);
118
+ else
119
+ await opts.onUsageEvent?.(event);
120
+ return c.json({ received: true });
121
+ }
122
+ catch (err) {
123
+ if (err instanceof BillingWebhookError)
124
+ return c.json({ error: err.code }, 400);
125
+ throw err;
126
+ }
127
+ });
128
+ r.get('/', async (c) => {
129
+ const accountId = await opts.getAccountId(c);
130
+ if (!accountId)
131
+ return c.json({ error: BILLING_ACCOUNT_REQUIRED }, 401);
132
+ try {
133
+ const status = await billing.status(accountId);
134
+ // Tell the browser whether to show the manage controls at all.
135
+ return c.json({ ...status, viewer_can_manage: await opts.canManage(c, accountId) });
136
+ }
137
+ catch (err) {
138
+ return asError(c, err);
139
+ }
140
+ });
141
+ // 0.5.0: the browser's feature gate (sdk/react useFeature / <Gate>). Read-only, the viewer's own
142
+ // account, no canManage. The server still enforces with requireFeature / track.
143
+ r.get('/check', async (c) => {
144
+ const accountId = await opts.getAccountId(c);
145
+ if (!accountId)
146
+ return c.json({ error: BILLING_ACCOUNT_REQUIRED }, 401);
147
+ const featureId = c.req.query('feature_id') ?? '';
148
+ if (!/^[a-z0-9][a-z0-9_.:-]{0,63}$/.test(featureId))
149
+ return c.json({ error: 'invalid_feature_id' }, 400);
150
+ const rb = c.req.query('required_balance');
151
+ const required = rb === undefined ? undefined : Number(rb);
152
+ if (required !== undefined && (!Number.isFinite(required) || required < 0))
153
+ return c.json({ error: 'invalid_field', message: 'required_balance must be a number >= 0' }, 400);
154
+ const r = await billing.check(accountId, featureId, required !== undefined ? { requiredBalance: required } : {});
155
+ return c.json({
156
+ feature_id: featureId,
157
+ allowed: r.allowed,
158
+ type: r.type,
159
+ balance: r.balance,
160
+ included: r.included,
161
+ usage: r.usage,
162
+ unlimited: r.unlimited,
163
+ resets_at: r.resets_at,
164
+ plan: r.plan,
165
+ reason: r.reason,
166
+ ...(r.granted !== undefined ? { granted: r.granted } : {}),
167
+ ...(r.credit_feature_id ? { credit_feature_id: r.credit_feature_id, credit_rate: r.credit_rate } : {}),
168
+ });
169
+ });
170
+ r.post('/:action', async (c) => {
171
+ const accountId = await opts.getAccountId(c);
172
+ if (!accountId)
173
+ return c.json({ error: BILLING_ACCOUNT_REQUIRED }, 401);
174
+ if (!(await opts.canManage(c, accountId)))
175
+ return c.json({ error: 'forbidden', message: 'You cannot manage billing for this account' }, 403);
176
+ const body = (await c.req.json().catch(() => ({})));
177
+ try {
178
+ switch (c.req.param('action')) {
179
+ case 'checkout': {
180
+ const plan = typeof body.plan === 'string' ? body.plan : '';
181
+ if (!plan || (opts.plans && !opts.plans.includes(plan)))
182
+ return c.json({ error: 'unknown_plan' }, 400);
183
+ const quantity = typeof body.quantity === 'number' ? body.quantity : undefined;
184
+ const url = resolveReturn(c);
185
+ const email = (await opts.getEmail?.(c)) ?? undefined;
186
+ const res = await billing.checkout({ accountId, plan, quantity, successUrl: url, cancelUrl: url, email });
187
+ return c.json({ url: res.url });
188
+ }
189
+ case 'portal':
190
+ return c.json(await billing.portal({ accountId, returnUrl: resolveReturn(c) }));
191
+ case 'trial': {
192
+ const email = (await opts.getEmail?.(c)) ?? undefined;
193
+ return c.json({ ...(await billing.startTrial(accountId, { email })), viewer_can_manage: true });
194
+ }
195
+ case 'autorenew':
196
+ if (typeof body.auto_renew !== 'boolean')
197
+ return c.json({ error: 'invalid_field', message: 'auto_renew must be boolean' }, 400);
198
+ return c.json({ ...(await billing.setAutoRenew(accountId, body.auto_renew)), viewer_can_manage: true });
199
+ default:
200
+ return c.json({ error: 'not_found' }, 404);
201
+ }
202
+ }
203
+ catch (err) {
204
+ return asError(c, err);
205
+ }
206
+ });
207
+ return r;
208
+ }