@hjam91/billing 0.0.0-stage → 0.7.1
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/LICENSE +21 -0
- package/README.md +145 -2
- package/dist/admin.d.ts +186 -0
- package/dist/admin.js +88 -0
- package/dist/cache.d.ts +26 -0
- package/dist/cache.js +36 -0
- package/dist/cli.mjs +82 -0
- package/dist/config.d.ts +90 -0
- package/dist/config.js +31 -0
- package/dist/errors.d.ts +17 -0
- package/dist/errors.js +32 -0
- package/dist/hono.d.ts +85 -0
- package/dist/hono.js +208 -0
- package/dist/index.d.ts +334 -0
- package/dist/index.js +563 -0
- package/dist/kv.d.ts +25 -0
- package/dist/kv.js +29 -0
- package/dist/react.d.ts +119 -0
- package/dist/react.js +211 -0
- package/dist/types.d.ts +393 -0
- package/dist/types.js +5 -0
- package/dist/webhook.d.ts +52 -0
- package/dist/webhook.js +98 -0
- package/package.json +75 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,563 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @hjam91/billing — the app side of billing-kit. SERVER-SIDE ONLY: it holds
|
|
3
|
+
* the app's secret. (The browser uses `@hjam91/billing/react`, which talks to
|
|
4
|
+
* the app's own backend, never to the billing service.)
|
|
5
|
+
*
|
|
6
|
+
* const billing = createBilling({ baseUrl, appId, secret });
|
|
7
|
+
* const ent = await billing.getEntitlement(orgId);
|
|
8
|
+
* if (!ent.active) return paymentRequired();
|
|
9
|
+
*
|
|
10
|
+
* Entitlement checks are cached and FAIL OPEN on an OUTAGE: if the billing
|
|
11
|
+
* service is slow, down or answering 5xx, the last known answer is used; with
|
|
12
|
+
* no cached answer the account is allowed and the failure is logged. A billing
|
|
13
|
+
* outage must never lock out a paying customer.
|
|
14
|
+
*
|
|
15
|
+
* A 401/403/404 is NOT an outage: it means this app's configuration is wrong
|
|
16
|
+
* (secret, app id, rotated key, disabled app). Since 0.2.0 those DENY
|
|
17
|
+
* (reason 'unverified', source 'error'), log at ERROR and call `onError`, so a
|
|
18
|
+
* misconfiguration or a disabled tenant can never mean free access forever.
|
|
19
|
+
* Set `failOpenOnAuthError: true` to restore the 0.1 behaviour.
|
|
20
|
+
*
|
|
21
|
+
* Actions (checkout, portal, auto-renew, trial, delete) never fail open —
|
|
22
|
+
* they throw BillingError, because there is nothing safe to pretend.
|
|
23
|
+
*
|
|
24
|
+
* WHO MAY ACT FOR AN ACCOUNT IS THE APP'S DECISION. The service checks that
|
|
25
|
+
* the app is who it says it is and that an account only manages what it owns;
|
|
26
|
+
* it cannot know whether the signed-in user is an admin of `accountId`. Check
|
|
27
|
+
* that in the app before calling checkout/portal/setAutoRenew.
|
|
28
|
+
*/
|
|
29
|
+
import { memoryStore } from "./cache.js";
|
|
30
|
+
export * from "./types.js";
|
|
31
|
+
export { BillingError, isOutage, killSignal } from "./errors.js";
|
|
32
|
+
import { BillingError, isOutage, killSignal } from "./errors.js";
|
|
33
|
+
export { defineConfig, formatChanges } from "./config.js";
|
|
34
|
+
export { createBillingAdmin } from "./admin.js";
|
|
35
|
+
export { memoryStore } from "./cache.js";
|
|
36
|
+
export { BillingWebhookError, verifyBillingEvent, verifyBillingWebhook } from "./webhook.js";
|
|
37
|
+
const selectorBody = (s = {}) => ({
|
|
38
|
+
...(s.subscriptionId ? { subscription_id: s.subscriptionId } : {}),
|
|
39
|
+
...(s.coversAccountId ? { covers_account_id: s.coversAccountId } : {}),
|
|
40
|
+
...(s.all ? { all: true } : {}),
|
|
41
|
+
});
|
|
42
|
+
const dateish = (v) => v === undefined ? undefined : v === null ? null : v instanceof Date ? v.toISOString() : v;
|
|
43
|
+
/** The wire form of an AccountInput (snake_case; left-out fields stay out). */
|
|
44
|
+
export function accountInputBody(input) {
|
|
45
|
+
const out = {};
|
|
46
|
+
if (input.createdAt !== undefined)
|
|
47
|
+
out.created_at = dateish(input.createdAt);
|
|
48
|
+
if (input.parentAccountId !== undefined)
|
|
49
|
+
out.parent_account_id = input.parentAccountId;
|
|
50
|
+
if (input.role !== undefined)
|
|
51
|
+
out.role = input.role;
|
|
52
|
+
if (input.email !== undefined)
|
|
53
|
+
out.email = input.email;
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
/** The service's batch limit (POST /v1/accounts/batch and /upsert). */
|
|
57
|
+
export const BATCH_LIMIT = 200;
|
|
58
|
+
const changeBody = (accountId, plan, o = {}) => ({
|
|
59
|
+
account_id: accountId,
|
|
60
|
+
plan,
|
|
61
|
+
...(o.when ? { when: o.when } : {}),
|
|
62
|
+
...(o.proration ? { proration: o.proration } : {}),
|
|
63
|
+
...(o.prorationDate !== undefined ? { proration_date: o.prorationDate } : {}),
|
|
64
|
+
...(o.subscriptionId ? { subscription_id: o.subscriptionId } : {}),
|
|
65
|
+
...(o.coversAccountId ? { covers_account_id: o.coversAccountId } : {}),
|
|
66
|
+
});
|
|
67
|
+
export function createBilling(opts) {
|
|
68
|
+
const base = opts.baseUrl.replace(/\/+$/, '');
|
|
69
|
+
const cache = opts.cache ?? memoryStore();
|
|
70
|
+
const ttlMs = (opts.ttlSeconds ?? 60) * 1000;
|
|
71
|
+
const failOpen = opts.failOpen ?? true;
|
|
72
|
+
const failOpenOnAuth = opts.failOpenOnAuthError ?? false;
|
|
73
|
+
const killDeny = opts.onKill === 'deny';
|
|
74
|
+
const maxStaleMs = (opts.maxStaleSeconds ?? 7 * 86_400) * 1000;
|
|
75
|
+
const doFetch = opts.fetch ?? ((input, init) => fetch(input, init));
|
|
76
|
+
const timeoutMs = opts.timeoutMs ?? 3000;
|
|
77
|
+
const log = opts.logger ?? console;
|
|
78
|
+
const now = opts.now ?? Date.now;
|
|
79
|
+
const key = (accountId) => `${opts.appId}:${accountId}`;
|
|
80
|
+
const inflight = new Map();
|
|
81
|
+
async function call(method, path, body, extraHeaders = {}) {
|
|
82
|
+
let res;
|
|
83
|
+
try {
|
|
84
|
+
res = await doFetch(`${base}${path}`, {
|
|
85
|
+
method,
|
|
86
|
+
headers: {
|
|
87
|
+
Authorization: `Bearer ${opts.secret}`,
|
|
88
|
+
'X-Billing-App': opts.appId,
|
|
89
|
+
...(body !== undefined ? { 'Content-Type': 'application/json' } : {}),
|
|
90
|
+
...extraHeaders,
|
|
91
|
+
},
|
|
92
|
+
body: body !== undefined ? JSON.stringify(body) : undefined,
|
|
93
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
const name = err?.name;
|
|
98
|
+
if (name === 'TimeoutError' || name === 'AbortError')
|
|
99
|
+
throw new BillingError(0, 'timeout', `Billing service did not answer within ${timeoutMs} ms`);
|
|
100
|
+
throw new BillingError(0, 'network_error', `Billing service unreachable: ${err?.message ?? err}`);
|
|
101
|
+
}
|
|
102
|
+
const data = (await res.json().catch(() => null));
|
|
103
|
+
if (!res.ok) {
|
|
104
|
+
throw new BillingError(res.status, data?.error ?? 'internal', data?.message ?? `Billing service answered HTTP ${res.status}`, (data ?? {}));
|
|
105
|
+
}
|
|
106
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) {
|
|
107
|
+
throw new BillingError(502, 'invalid_response', 'Billing service returned an invalid JSON object');
|
|
108
|
+
}
|
|
109
|
+
return data;
|
|
110
|
+
}
|
|
111
|
+
function validateEntitlement(value) {
|
|
112
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || typeof value.active !== 'boolean' || typeof value.reason !== 'string') {
|
|
113
|
+
throw new BillingError(502, 'invalid_response', 'Billing service returned an invalid entitlement');
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const enc = encodeURIComponent;
|
|
117
|
+
/** One network fetch per account at a time; concurrent callers share it. */
|
|
118
|
+
function refresh(accountId) {
|
|
119
|
+
const existing = inflight.get(accountId);
|
|
120
|
+
if (existing)
|
|
121
|
+
return existing;
|
|
122
|
+
const p = call('GET', `/v1/accounts/${enc(accountId)}/entitlement`)
|
|
123
|
+
.then(async (value) => {
|
|
124
|
+
validateEntitlement(value);
|
|
125
|
+
await cache.set(key(accountId), { value, fetchedAt: now() }).catch((e) => log.warn('[billing] cache write failed', e));
|
|
126
|
+
return value;
|
|
127
|
+
})
|
|
128
|
+
.finally(() => inflight.delete(accountId));
|
|
129
|
+
inflight.set(accountId, p);
|
|
130
|
+
return p;
|
|
131
|
+
}
|
|
132
|
+
function reportFailure(accountId, err, served, as) {
|
|
133
|
+
const e = err;
|
|
134
|
+
const kill = killSignal(e);
|
|
135
|
+
// 5xx / network: the service is having a bad day. 4xx: OUR config is wrong (secret, app id) — louder.
|
|
136
|
+
const outage = !kill && isOutage(e);
|
|
137
|
+
if (kill)
|
|
138
|
+
log.error(`[billing] !!! KILL SWITCH: billing-kit refused this app (${kill}: ${e?.message ?? ''}). Entitlement for ${accountId}: serving ${served} (onKill: ${killDeny ? 'deny' : 'fail_open'}). ` +
|
|
139
|
+
'The owner disabled this app or locked the service down — usually because a credential was stolen. Rotate BILLING_SECRET and ask the owner to re-enable.');
|
|
140
|
+
else
|
|
141
|
+
(outage ? log.warn : log.error).call(log, `[billing] entitlement check for ${accountId} failed (${e?.code ?? 'error'}: ${e?.message ?? err}); serving ${served}${outage ? '' : ' — CHECK BILLING_SECRET / BILLING_APP_ID / app status'}`);
|
|
142
|
+
try {
|
|
143
|
+
opts.onError?.({ accountId, status: e?.status ?? 0, code: String(e?.code ?? 'error'), kind: kill ? 'killed' : outage ? 'outage' : 'misconfigured', served: as });
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
/* a metrics hook must never break an entitlement check */
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const unverified = (accountId, active, source, error) => ({
|
|
150
|
+
account_id: accountId,
|
|
151
|
+
active,
|
|
152
|
+
reason: 'unverified',
|
|
153
|
+
plan: null,
|
|
154
|
+
quantity: null,
|
|
155
|
+
trial_ends_at: null,
|
|
156
|
+
current_period_end: null,
|
|
157
|
+
renews: false,
|
|
158
|
+
grace_ends_at: null,
|
|
159
|
+
covered_by_account_id: null,
|
|
160
|
+
subscription_status: null,
|
|
161
|
+
payment_failed: false,
|
|
162
|
+
computed_at: new Date(now()).toISOString(),
|
|
163
|
+
source,
|
|
164
|
+
...(error ? { error } : {}),
|
|
165
|
+
});
|
|
166
|
+
/** The answer for a failed check: stale value during an outage, deny on misconfiguration, else the failOpen rule. */
|
|
167
|
+
async function onFailure(accountId, err, entry) {
|
|
168
|
+
const code = String(err?.code ?? 'error');
|
|
169
|
+
if (killSignal(err)) {
|
|
170
|
+
// The owner's kill switch: onKill decides, not the outage / auth rules.
|
|
171
|
+
if (killDeny) {
|
|
172
|
+
await cache.delete(key(accountId)).catch(() => undefined);
|
|
173
|
+
reportFailure(accountId, err, 'DENY', 'deny');
|
|
174
|
+
return unverified(accountId, false, 'error', code);
|
|
175
|
+
}
|
|
176
|
+
if (entry && now() - entry.fetchedAt < maxStaleMs) {
|
|
177
|
+
reportFailure(accountId, err, 'the last known entitlement', 'stale');
|
|
178
|
+
return { ...entry.value, source: 'stale' };
|
|
179
|
+
}
|
|
180
|
+
// Nothing cached (a never-seen account): the kill does not widen access — the app's failOpen rule applies.
|
|
181
|
+
reportFailure(accountId, err, failOpen ? 'ALLOW (nothing cached; failOpen)' : 'DENY (nothing cached; failOpen: false)', failOpen ? 'fail_open' : 'deny');
|
|
182
|
+
return unverified(accountId, failOpen, failOpen ? 'fail_open' : 'error', code);
|
|
183
|
+
}
|
|
184
|
+
if (!isOutage(err) && !failOpenOnAuth) {
|
|
185
|
+
// Misconfiguration: never serve a cached "active" forever. Drop it so the next read asks again.
|
|
186
|
+
await cache.delete(key(accountId)).catch(() => undefined);
|
|
187
|
+
reportFailure(accountId, err, 'DENY (misconfigured: auth/app error is not an outage)', 'deny');
|
|
188
|
+
return unverified(accountId, false, 'error', code);
|
|
189
|
+
}
|
|
190
|
+
if (entry && now() - entry.fetchedAt < maxStaleMs) {
|
|
191
|
+
reportFailure(accountId, err, 'the last known entitlement', 'stale');
|
|
192
|
+
return { ...entry.value, source: 'stale' };
|
|
193
|
+
}
|
|
194
|
+
reportFailure(accountId, err, failOpen ? 'ALLOW (fail-open, nothing cached)' : 'DENY (failOpen: false)', failOpen ? 'fail_open' : 'deny');
|
|
195
|
+
return unverified(accountId, failOpen, failOpen ? 'fail_open' : 'error', code);
|
|
196
|
+
}
|
|
197
|
+
// ---------------------------------------------------------------- features (0.5.0)
|
|
198
|
+
const bufferSize = opts.usageBufferSize ?? 1000;
|
|
199
|
+
const maxAttempts = opts.usageMaxAttempts ?? 5;
|
|
200
|
+
const usageBuffer = [];
|
|
201
|
+
let flushing = null;
|
|
202
|
+
const randomKey = () => `sdk-${globalThis.crypto?.randomUUID?.() ?? `${now()}-${Math.random().toString(36).slice(2)}`}`;
|
|
203
|
+
const unverifiedCheck = (accountId, featureId, allowed, source, error) => ({
|
|
204
|
+
account_id: accountId,
|
|
205
|
+
feature_id: featureId,
|
|
206
|
+
allowed,
|
|
207
|
+
type: null,
|
|
208
|
+
balance: null,
|
|
209
|
+
included: null,
|
|
210
|
+
usage: null,
|
|
211
|
+
unlimited: false,
|
|
212
|
+
resets_at: null,
|
|
213
|
+
plan: null,
|
|
214
|
+
plan_source: null,
|
|
215
|
+
reason: 'unverified',
|
|
216
|
+
source,
|
|
217
|
+
...(error ? { error } : {}),
|
|
218
|
+
});
|
|
219
|
+
/** A cached entitlement's view of one feature, as a check answer. */
|
|
220
|
+
const fromEntry = (accountId, featureId, value, required, source) => {
|
|
221
|
+
const f = value.features?.[featureId];
|
|
222
|
+
if (!f)
|
|
223
|
+
return null;
|
|
224
|
+
const allowed = f.allowed && (f.balance == null || f.balance >= required);
|
|
225
|
+
return { account_id: accountId, feature_id: featureId, ...f, allowed, reason: allowed ? f.reason : f.reason === 'ok' ? 'insufficient_balance' : f.reason, plan: value.plan, plan_source: null, source };
|
|
226
|
+
};
|
|
227
|
+
function reportUsage(what, err) {
|
|
228
|
+
const e = err;
|
|
229
|
+
(isOutage(e) ? log.warn : log.error).call(log, `[billing] ${what} (${e?.code ?? 'error'}: ${e?.message ?? err})`);
|
|
230
|
+
}
|
|
231
|
+
function enqueue(body) {
|
|
232
|
+
usageBuffer.push({ body, attempts: 1 });
|
|
233
|
+
while (usageBuffer.length > bufferSize) {
|
|
234
|
+
const lost = usageBuffer.shift();
|
|
235
|
+
log.error(`[billing] usage buffer full (${bufferSize}): dropped ${lost.body.feature_id} for ${lost.body.account_id}`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
async function flushUsage() {
|
|
239
|
+
if (flushing)
|
|
240
|
+
return flushing;
|
|
241
|
+
flushing = (async () => {
|
|
242
|
+
let sent = 0;
|
|
243
|
+
let dropped = 0;
|
|
244
|
+
while (usageBuffer.length) {
|
|
245
|
+
const chunk = usageBuffer.slice(0, 1000);
|
|
246
|
+
try {
|
|
247
|
+
await call('POST', '/v1/track/batch', { events: chunk.map((x) => x.body) });
|
|
248
|
+
usageBuffer.splice(0, chunk.length);
|
|
249
|
+
sent += chunk.length;
|
|
250
|
+
}
|
|
251
|
+
catch (err) {
|
|
252
|
+
if (!isOutage(err) && !(killSignal(err) && !killDeny)) {
|
|
253
|
+
// The service refused the batch itself (auth / config): retrying cannot help.
|
|
254
|
+
usageBuffer.splice(0, chunk.length);
|
|
255
|
+
dropped += chunk.length;
|
|
256
|
+
reportUsage(`dropped ${chunk.length} buffered usage event(s): the service refused them`, err);
|
|
257
|
+
break;
|
|
258
|
+
}
|
|
259
|
+
for (const x of chunk)
|
|
260
|
+
x.attempts++;
|
|
261
|
+
const dead = usageBuffer.filter((x) => x.attempts >= maxAttempts);
|
|
262
|
+
if (dead.length) {
|
|
263
|
+
for (const x of dead)
|
|
264
|
+
usageBuffer.splice(usageBuffer.indexOf(x), 1);
|
|
265
|
+
dropped += dead.length;
|
|
266
|
+
log.error(`[billing] dropped ${dead.length} usage event(s) after ${maxAttempts} attempts (${err?.code ?? 'error'}): usage is never fatal, but it is lost`);
|
|
267
|
+
}
|
|
268
|
+
break;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return { sent, dropped, pending: usageBuffer.length };
|
|
272
|
+
})().finally(() => {
|
|
273
|
+
flushing = null;
|
|
274
|
+
});
|
|
275
|
+
return flushing;
|
|
276
|
+
}
|
|
277
|
+
/** Sends what is buffered behind a successful call (the service is evidently up). */
|
|
278
|
+
const flushBehind = (waitUntil) => {
|
|
279
|
+
if (!usageBuffer.length || flushing)
|
|
280
|
+
return;
|
|
281
|
+
const p = flushUsage().catch(() => undefined);
|
|
282
|
+
(waitUntil ?? opts.waitUntil)?.(p);
|
|
283
|
+
};
|
|
284
|
+
const self = {
|
|
285
|
+
async check(accountId, featureId, o = {}) {
|
|
286
|
+
const required = o.requiredBalance ?? 1;
|
|
287
|
+
const entry = await cache.get(key(accountId)).catch(() => undefined);
|
|
288
|
+
if (entry && !o.fresh && now() - entry.fetchedAt < ttlMs && entry.value.features?.[featureId]?.type === 'boolean') {
|
|
289
|
+
return fromEntry(accountId, featureId, entry.value, required, 'cache');
|
|
290
|
+
}
|
|
291
|
+
try {
|
|
292
|
+
const r = await call('POST', '/v1/check', { account_id: accountId, feature_id: featureId, required_balance: required });
|
|
293
|
+
flushBehind();
|
|
294
|
+
return { ...r, source: 'live' };
|
|
295
|
+
}
|
|
296
|
+
catch (err) {
|
|
297
|
+
const code = String(err?.code ?? 'error');
|
|
298
|
+
const kill = killSignal(err);
|
|
299
|
+
if (kill && killDeny) {
|
|
300
|
+
await cache.delete(key(accountId)).catch(() => undefined);
|
|
301
|
+
reportFailure(accountId, err, `DENY feature ${featureId}`, 'deny');
|
|
302
|
+
return unverifiedCheck(accountId, featureId, false, 'error', code);
|
|
303
|
+
}
|
|
304
|
+
if (!kill && !isOutage(err) && !failOpenOnAuth) {
|
|
305
|
+
await cache.delete(key(accountId)).catch(() => undefined);
|
|
306
|
+
reportFailure(accountId, err, `DENY for feature ${featureId} (misconfigured: auth/app/feature error is not an outage)`, 'deny');
|
|
307
|
+
return unverifiedCheck(accountId, featureId, false, 'error', code);
|
|
308
|
+
}
|
|
309
|
+
if (entry && now() - entry.fetchedAt < maxStaleMs) {
|
|
310
|
+
const stale = fromEntry(accountId, featureId, entry.value, required, 'stale');
|
|
311
|
+
if (stale) {
|
|
312
|
+
reportFailure(accountId, err, `the last known value of feature ${featureId}`, 'stale');
|
|
313
|
+
return stale;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
// Kill or outage: the cached value above, else the app's failOpen rule (never wider for a kill).
|
|
317
|
+
const allow = failOpen;
|
|
318
|
+
reportFailure(accountId, err, allow ? `ALLOW feature ${featureId} (fail-open, nothing cached)` : `DENY feature ${featureId} (failOpen: false)`, allow ? 'fail_open' : 'deny');
|
|
319
|
+
return unverifiedCheck(accountId, featureId, allow, allow ? 'fail_open' : 'error', code);
|
|
320
|
+
}
|
|
321
|
+
},
|
|
322
|
+
async track(accountId, featureId, value = 1, o = {}) {
|
|
323
|
+
const body = {
|
|
324
|
+
account_id: accountId,
|
|
325
|
+
feature_id: featureId,
|
|
326
|
+
value,
|
|
327
|
+
idempotency_key: o.idempotencyKey ?? randomKey(),
|
|
328
|
+
...(o.eventName ? { event_name: o.eventName } : {}),
|
|
329
|
+
...(o.properties ? { properties: o.properties } : {}),
|
|
330
|
+
...(o.checkAndTrack ? { check_and_track: true } : {}),
|
|
331
|
+
};
|
|
332
|
+
try {
|
|
333
|
+
const r = await call('POST', '/v1/track', body);
|
|
334
|
+
flushBehind(o.waitUntil);
|
|
335
|
+
return { ...r, source: 'live' };
|
|
336
|
+
}
|
|
337
|
+
catch (err) {
|
|
338
|
+
const code = String(err?.code ?? 'error');
|
|
339
|
+
const kill = killSignal(err);
|
|
340
|
+
if (kill && !killDeny) {
|
|
341
|
+
// Kill switch, fail_open: the usage is kept for a retry once the app is re-enabled (bounded buffer).
|
|
342
|
+
enqueue(body);
|
|
343
|
+
log.error(`[billing] !!! KILL SWITCH (${kill}): track ${featureId} for ${accountId} queued (onKill: fail_open)`);
|
|
344
|
+
return { ...unverifiedCheck(accountId, featureId, failOpen, failOpen ? 'fail_open' : 'error', code), value, applied: false, replayed: false, event_id: null, queued: true };
|
|
345
|
+
}
|
|
346
|
+
if (kill || !isOutage(err)) {
|
|
347
|
+
reportUsage(`track ${featureId} for ${accountId} refused`, err);
|
|
348
|
+
return { ...unverifiedCheck(accountId, featureId, false, 'error', code), value, applied: false, replayed: false, event_id: null };
|
|
349
|
+
}
|
|
350
|
+
enqueue(body);
|
|
351
|
+
reportUsage(`track ${featureId} for ${accountId} queued for a retry (${usageBuffer.length} waiting)`, err);
|
|
352
|
+
return { ...unverifiedCheck(accountId, featureId, true, 'fail_open', code), value, applied: false, replayed: false, event_id: null, queued: true };
|
|
353
|
+
}
|
|
354
|
+
},
|
|
355
|
+
async setUsage(accountId, featureId, value) {
|
|
356
|
+
const r = await call('POST', '/v1/usage', { account_id: accountId, feature_id: featureId, value });
|
|
357
|
+
return { ...r, source: 'live' };
|
|
358
|
+
},
|
|
359
|
+
flushUsage,
|
|
360
|
+
async getEntitlement(accountId, callOpts = {}) {
|
|
361
|
+
const entry = await cache.get(key(accountId)).catch((e) => {
|
|
362
|
+
log.warn('[billing] cache read failed', e);
|
|
363
|
+
return undefined;
|
|
364
|
+
});
|
|
365
|
+
if (entry && !callOpts.fresh && now() - entry.fetchedAt < maxStaleMs) {
|
|
366
|
+
if (now() - entry.fetchedAt < ttlMs)
|
|
367
|
+
return { ...entry.value, source: 'cache' };
|
|
368
|
+
// Stale-while-revalidate: answer now from the last known value, refresh behind it.
|
|
369
|
+
const bg = refresh(accountId).catch(async (err) => {
|
|
370
|
+
if (killSignal(err) ? killDeny : !isOutage(err) && !failOpenOnAuth) {
|
|
371
|
+
await cache.delete(key(accountId)).catch(() => undefined);
|
|
372
|
+
reportFailure(accountId, err, 'the last known entitlement once more; the cache entry is dropped', 'stale');
|
|
373
|
+
}
|
|
374
|
+
else
|
|
375
|
+
reportFailure(accountId, err, 'the last known entitlement', 'stale');
|
|
376
|
+
});
|
|
377
|
+
(callOpts.waitUntil ?? opts.waitUntil)?.(bg);
|
|
378
|
+
return { ...entry.value, source: 'stale' };
|
|
379
|
+
}
|
|
380
|
+
try {
|
|
381
|
+
return { ...(await refresh(accountId)), source: 'live' };
|
|
382
|
+
}
|
|
383
|
+
catch (err) {
|
|
384
|
+
return onFailure(accountId, err, entry);
|
|
385
|
+
}
|
|
386
|
+
},
|
|
387
|
+
async invalidate(accountId) {
|
|
388
|
+
await cache.delete(key(accountId));
|
|
389
|
+
},
|
|
390
|
+
async checkout(p) {
|
|
391
|
+
const r = await call('POST', '/v1/checkout', {
|
|
392
|
+
account_id: p.accountId,
|
|
393
|
+
plan: p.plan,
|
|
394
|
+
quantity: p.quantity,
|
|
395
|
+
success_url: p.successUrl,
|
|
396
|
+
cancel_url: p.cancelUrl,
|
|
397
|
+
email: p.email,
|
|
398
|
+
covers: p.covers,
|
|
399
|
+
promotion_code: p.promotionCode,
|
|
400
|
+
customer_name: p.customerName,
|
|
401
|
+
});
|
|
402
|
+
return {
|
|
403
|
+
url: r.url,
|
|
404
|
+
sessionId: r.session_id,
|
|
405
|
+
trialEnd: r.trial_end,
|
|
406
|
+
reused: r.reused === true,
|
|
407
|
+
mode: r.mode ?? 'subscription',
|
|
408
|
+
covers: r.covers ?? [],
|
|
409
|
+
trialEnds: r.trial_ends ?? {},
|
|
410
|
+
...(r.purchase_id ? { purchaseId: r.purchase_id } : {}),
|
|
411
|
+
};
|
|
412
|
+
},
|
|
413
|
+
async balances(accountId) {
|
|
414
|
+
return call('GET', `/v1/accounts/${enc(accountId)}/balances`);
|
|
415
|
+
},
|
|
416
|
+
async lock(accountId, featureId, amount, o = {}) {
|
|
417
|
+
return call('POST', '/v1/balances/lock', {
|
|
418
|
+
account_id: accountId,
|
|
419
|
+
feature_id: featureId,
|
|
420
|
+
amount,
|
|
421
|
+
...(o.ttlSeconds !== undefined ? { ttl_seconds: o.ttlSeconds } : {}),
|
|
422
|
+
...(o.idempotencyKey ? { idempotency_key: o.idempotencyKey } : {}),
|
|
423
|
+
});
|
|
424
|
+
},
|
|
425
|
+
async finalize(lockId, used) {
|
|
426
|
+
return call('POST', `/v1/balances/lock/${enc(lockId)}/finalize`, { used });
|
|
427
|
+
},
|
|
428
|
+
async topUp(p) {
|
|
429
|
+
return self.checkout({ accountId: p.accountId, plan: p.product, quantity: p.quantity, successUrl: p.successUrl, cancelUrl: p.cancelUrl, email: p.email });
|
|
430
|
+
},
|
|
431
|
+
async changePlan(accountId, plan, o) {
|
|
432
|
+
const r = await call('POST', '/v1/subscriptions/change', changeBody(accountId, plan, o));
|
|
433
|
+
await cache.delete(key(accountId)).catch(() => undefined);
|
|
434
|
+
return r;
|
|
435
|
+
},
|
|
436
|
+
previewChange: (accountId, plan, o) => call('POST', '/v1/subscriptions/change/preview', changeBody(accountId, plan, o)),
|
|
437
|
+
async attachAddOn(accountId, plan, o = {}) {
|
|
438
|
+
const r = await call('POST', '/v1/subscriptions/add-ons', { account_id: accountId, plan, ...(o.quantity ? { quantity: o.quantity } : {}), ...(o.subscriptionId ? { subscription_id: o.subscriptionId } : {}) });
|
|
439
|
+
await cache.delete(key(accountId)).catch(() => undefined);
|
|
440
|
+
return r;
|
|
441
|
+
},
|
|
442
|
+
async detachAddOn(accountId, plan) {
|
|
443
|
+
const r = await call('DELETE', `/v1/subscriptions/add-ons/${enc(plan)}?account_id=${enc(accountId)}`);
|
|
444
|
+
await cache.delete(key(accountId)).catch(() => undefined);
|
|
445
|
+
return r;
|
|
446
|
+
},
|
|
447
|
+
plans: () => call('GET', '/v1/plans'),
|
|
448
|
+
async setUsageSettings(accountId, st) {
|
|
449
|
+
const body = {};
|
|
450
|
+
if (st.spendCap !== undefined)
|
|
451
|
+
body.spend_cap = st.spendCap;
|
|
452
|
+
if (st.autoTopups !== undefined)
|
|
453
|
+
body.auto_topups = st.autoTopups.map((t) => ({ feature_id: t.featureId, threshold: t.threshold, product: t.product, auto: t.auto === true, ...(t.maxPerMonth !== undefined ? { max_per_month: t.maxPerMonth } : {}) }));
|
|
454
|
+
return call('PUT', `/v1/accounts/${enc(accountId)}/usage-settings`, body);
|
|
455
|
+
},
|
|
456
|
+
async startTrial(accountId, o = {}) {
|
|
457
|
+
const s = await call('POST', `/v1/accounts/${enc(accountId)}/trial`, { email: o.email });
|
|
458
|
+
await cache.set(key(accountId), { value: { account_id: accountId, ...s.entitlement }, fetchedAt: now() }).catch(() => undefined);
|
|
459
|
+
return s;
|
|
460
|
+
},
|
|
461
|
+
async deleteAccount(accountId, o = {}) {
|
|
462
|
+
const q = new URLSearchParams();
|
|
463
|
+
if (o.cancel)
|
|
464
|
+
q.set('cancel', o.cancel);
|
|
465
|
+
if (o.deleteCustomer)
|
|
466
|
+
q.set('delete_customer', '1');
|
|
467
|
+
const r = await call('DELETE', `/v1/accounts/${enc(accountId)}${q.size ? `?${q}` : ''}`);
|
|
468
|
+
await cache.delete(key(accountId)).catch(() => undefined);
|
|
469
|
+
return r;
|
|
470
|
+
},
|
|
471
|
+
exportAccount: (accountId) => call('GET', `/v1/accounts/${enc(accountId)}/export`),
|
|
472
|
+
summary: () => call('GET', '/v1/summary'),
|
|
473
|
+
portal: (p) => call('POST', '/v1/portal', { account_id: p.accountId, return_url: p.returnUrl, ...(p.subscriptionId ? { subscription_id: p.subscriptionId } : {}) }),
|
|
474
|
+
async setAutoRenew(accountId, on, select) {
|
|
475
|
+
const s = await call('POST', '/v1/autorenew', { account_id: accountId, auto_renew: on, ...selectorBody(select) });
|
|
476
|
+
await cache.delete(key(accountId)).catch(() => undefined);
|
|
477
|
+
// The covered accounts whose subscription changed read fresh next time too.
|
|
478
|
+
for (const r of s.results ?? [])
|
|
479
|
+
if (r.covers_account_id)
|
|
480
|
+
await cache.delete(key(r.covers_account_id)).catch(() => undefined);
|
|
481
|
+
return s;
|
|
482
|
+
},
|
|
483
|
+
async getEntitlements(accountIds, o = {}) {
|
|
484
|
+
const ids = [...new Set(accountIds)];
|
|
485
|
+
const out = {};
|
|
486
|
+
const misses = [];
|
|
487
|
+
const entries = new Map();
|
|
488
|
+
for (const id of ids) {
|
|
489
|
+
const entry = await cache.get(key(id)).catch(() => undefined);
|
|
490
|
+
entries.set(id, entry);
|
|
491
|
+
if (entry && !o.fresh && now() - entry.fetchedAt < ttlMs)
|
|
492
|
+
out[id] = { ...entry.value, source: 'cache' };
|
|
493
|
+
else
|
|
494
|
+
misses.push(id);
|
|
495
|
+
}
|
|
496
|
+
for (let i = 0; i < misses.length; i += BATCH_LIMIT) {
|
|
497
|
+
const chunk = misses.slice(i, i + BATCH_LIMIT);
|
|
498
|
+
try {
|
|
499
|
+
const r = await call('POST', '/v1/accounts/batch', { ids: chunk, create: o.create === true });
|
|
500
|
+
for (const id of chunk) {
|
|
501
|
+
const value = r.accounts[id];
|
|
502
|
+
if (!value) {
|
|
503
|
+
out[id] = null;
|
|
504
|
+
continue;
|
|
505
|
+
}
|
|
506
|
+
await cache.set(key(id), { value, fetchedAt: now() }).catch((e) => log.warn('[billing] cache write failed', e));
|
|
507
|
+
out[id] = { ...value, source: 'live' };
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
catch (err) {
|
|
511
|
+
// Fail open PER ID: the last known value during an outage, else the failOpen rule (or deny on misconfiguration).
|
|
512
|
+
for (const id of chunk)
|
|
513
|
+
out[id] = await onFailure(id, err, entries.get(id));
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
return out;
|
|
517
|
+
},
|
|
518
|
+
async statuses(accountIds, o = {}) {
|
|
519
|
+
const ids = [...new Set(accountIds)];
|
|
520
|
+
const out = {};
|
|
521
|
+
for (let i = 0; i < ids.length; i += BATCH_LIMIT) {
|
|
522
|
+
const chunk = ids.slice(i, i + BATCH_LIMIT);
|
|
523
|
+
const r = await call('POST', '/v1/accounts/batch', { ids: chunk, include: 'status', create: o.create === true });
|
|
524
|
+
for (const id of chunk) {
|
|
525
|
+
const s = r.accounts[id] ?? null;
|
|
526
|
+
out[id] = s;
|
|
527
|
+
if (s)
|
|
528
|
+
await cache.set(key(id), { value: { account_id: id, ...s.entitlement }, fetchedAt: now() }).catch(() => undefined);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
return out;
|
|
532
|
+
},
|
|
533
|
+
async upsertAccount(accountId, input) {
|
|
534
|
+
const s = await call('PUT', `/v1/accounts/${enc(accountId)}`, accountInputBody(input));
|
|
535
|
+
await cache.set(key(accountId), { value: { account_id: accountId, ...s.entitlement }, fetchedAt: now() }).catch(() => undefined);
|
|
536
|
+
return s;
|
|
537
|
+
},
|
|
538
|
+
async upsertAccounts(accounts) {
|
|
539
|
+
const all = { results: [], errors: [] };
|
|
540
|
+
for (let i = 0; i < accounts.length; i += BATCH_LIMIT) {
|
|
541
|
+
const chunk = accounts.slice(i, i + BATCH_LIMIT);
|
|
542
|
+
const r = await call('POST', '/v1/accounts/upsert', { accounts: chunk.map((a) => ({ account_id: a.accountId, ...accountInputBody(a) })) });
|
|
543
|
+
all.results.push(...r.results);
|
|
544
|
+
all.errors.push(...r.errors);
|
|
545
|
+
for (const a of chunk)
|
|
546
|
+
await cache.delete(key(a.accountId)).catch(() => undefined);
|
|
547
|
+
}
|
|
548
|
+
return all;
|
|
549
|
+
},
|
|
550
|
+
async status(accountId, o = {}) {
|
|
551
|
+
const s = await call('GET', `/v1/accounts/${enc(accountId)}`, undefined, o.email ? { 'X-Billing-Email': o.email } : {});
|
|
552
|
+
validateEntitlement(s.entitlement);
|
|
553
|
+
await cache.set(key(accountId), { value: { account_id: accountId, ...s.entitlement }, fetchedAt: now() }).catch(() => undefined);
|
|
554
|
+
return s;
|
|
555
|
+
},
|
|
556
|
+
async setCoverage(accountId, coveredBy) {
|
|
557
|
+
const s = await call('PUT', `/v1/accounts/${enc(accountId)}/coverage`, { covered_by_account_id: coveredBy });
|
|
558
|
+
await cache.delete(key(accountId)).catch(() => undefined);
|
|
559
|
+
return s;
|
|
560
|
+
},
|
|
561
|
+
};
|
|
562
|
+
return self;
|
|
563
|
+
}
|
package/dist/kv.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cloudflare KV adapter for the entitlement cache.
|
|
3
|
+
*
|
|
4
|
+
* import { kvStore } from '@hjam91/billing/kv';
|
|
5
|
+
* createBilling({ ..., cache: kvStore(env.BILLING_CACHE) });
|
|
6
|
+
*
|
|
7
|
+
* Shared by every isolate and colo, so one webhook invalidation reaches them
|
|
8
|
+
* all — eventually: KV is eventually consistent (a delete can take up to ~60 s
|
|
9
|
+
* to be seen everywhere). Entries expire after `expirationTtlSeconds`
|
|
10
|
+
* (default 7 days); until then a stale entry is still served when the billing
|
|
11
|
+
* service is down.
|
|
12
|
+
*/
|
|
13
|
+
import type { CacheStore } from './cache.js';
|
|
14
|
+
/** The subset of KVNamespace used here (structural, so no workers-types dependency). */
|
|
15
|
+
export interface KVNamespaceLike {
|
|
16
|
+
get(key: string, type: 'json'): Promise<unknown>;
|
|
17
|
+
put(key: string, value: string, options?: {
|
|
18
|
+
expirationTtl?: number;
|
|
19
|
+
}): Promise<void>;
|
|
20
|
+
delete(key: string): Promise<void>;
|
|
21
|
+
}
|
|
22
|
+
export declare function kvStore(kv: KVNamespaceLike, opts?: {
|
|
23
|
+
prefix?: string;
|
|
24
|
+
expirationTtlSeconds?: number;
|
|
25
|
+
}): CacheStore;
|
package/dist/kv.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cloudflare KV adapter for the entitlement cache.
|
|
3
|
+
*
|
|
4
|
+
* import { kvStore } from '@hjam91/billing/kv';
|
|
5
|
+
* createBilling({ ..., cache: kvStore(env.BILLING_CACHE) });
|
|
6
|
+
*
|
|
7
|
+
* Shared by every isolate and colo, so one webhook invalidation reaches them
|
|
8
|
+
* all — eventually: KV is eventually consistent (a delete can take up to ~60 s
|
|
9
|
+
* to be seen everywhere). Entries expire after `expirationTtlSeconds`
|
|
10
|
+
* (default 7 days); until then a stale entry is still served when the billing
|
|
11
|
+
* service is down.
|
|
12
|
+
*/
|
|
13
|
+
export function kvStore(kv, opts = {}) {
|
|
14
|
+
const prefix = opts.prefix ?? 'billing:ent:';
|
|
15
|
+
// KV refuses an expirationTtl under 60 seconds.
|
|
16
|
+
const ttl = Math.max(60, opts.expirationTtlSeconds ?? 7 * 86_400);
|
|
17
|
+
return {
|
|
18
|
+
async get(key) {
|
|
19
|
+
const v = (await kv.get(prefix + key, 'json'));
|
|
20
|
+
return v && typeof v === 'object' && 'value' in v && typeof v.fetchedAt === 'number' ? v : undefined;
|
|
21
|
+
},
|
|
22
|
+
async set(key, entry) {
|
|
23
|
+
await kv.put(prefix + key, JSON.stringify(entry), { expirationTtl: ttl });
|
|
24
|
+
},
|
|
25
|
+
async delete(key) {
|
|
26
|
+
await kv.delete(prefix + key);
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
}
|