anhedral 0.12.0 → 0.15.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 +35 -172
- package/assets/patches/audit-deps.mjs +12 -2
- package/assets/ui/LICENSE.shadcn +21 -0
- package/assets/ui/UPSTREAM.json +33 -0
- package/assets/ui/native/button.tsx +85 -0
- package/assets/ui/native/card.tsx +33 -0
- package/assets/ui/native/dialog.tsx +75 -0
- package/assets/ui/native/input.tsx +27 -0
- package/assets/ui/native/label.tsx +4 -0
- package/assets/ui/native/layout.tsx +26 -0
- package/assets/ui/native/text.tsx +20 -0
- package/assets/ui/native/theme-switcher.tsx +22 -0
- package/assets/ui/theme-storage.ts +25 -0
- package/assets/ui/theme.tsx +66 -0
- package/assets/ui/web/button.tsx +59 -0
- package/assets/ui/web/input.tsx +21 -0
- package/assets/ui/web/label.tsx +19 -0
- package/dist/capabilities.d.ts +5 -5
- package/dist/capabilities.js +3 -21
- package/dist/capability-contract.d.ts +3 -3
- package/dist/capability-contract.js +11 -39
- package/dist/cli-delivery.d.ts +1 -1
- package/dist/cli-delivery.js +5 -65
- package/dist/cli-output.js +3 -3
- package/dist/command-schema.js +35 -80
- package/dist/command.js +9 -11
- package/dist/delivery-evidence.d.ts +1 -1
- package/dist/delivery-evidence.js +7 -36
- package/dist/delivery.d.ts +2 -8
- package/dist/delivery.js +23 -102
- package/dist/dependencies.d.ts +12 -58
- package/dist/dependencies.js +67 -189
- package/dist/index.d.ts +1 -3
- package/dist/index.js +1 -3
- package/dist/inspector-model.d.ts +2 -2
- package/dist/integration-service-readers.d.ts +1 -2
- package/dist/integration-service-readers.js +3 -84
- package/dist/lifecycle-model.d.ts +1 -1
- package/dist/lifecycle-model.js +1 -1
- package/dist/mobile-delivery.d.ts +1 -1
- package/dist/mobile-delivery.js +4 -0
- package/dist/platforms/mobile.d.ts +1 -1
- package/dist/platforms/mobile.js +64 -114
- package/dist/platforms/web.d.ts +3 -0
- package/dist/platforms/web.js +299 -0
- package/dist/project-config.d.ts +1 -1
- package/dist/project-config.js +0 -1
- package/dist/project-inspector.js +5 -36
- package/dist/project-state.d.ts +1 -3
- package/dist/project-state.js +6 -86
- package/dist/provider-auth.js +3 -32
- package/dist/provider-readiness.d.ts +1 -1
- package/dist/provider-readiness.js +5 -24
- package/dist/providers/adapters.js +9 -178
- package/dist/providers/api.d.ts +1 -1
- package/dist/providers/api.js +3 -3
- package/dist/providers/config.js +2 -48
- package/dist/providers/definitions.d.ts +1 -204
- package/dist/providers/definitions.js +0 -85
- package/dist/providers/provision.d.ts +1 -1
- package/dist/providers/receipts.js +1 -11
- package/dist/providers/recovery-verification.js +1 -61
- package/dist/providers/runtime.js +15 -35
- package/dist/providers/state.js +1 -7
- package/dist/provision.d.ts +5 -13
- package/dist/provision.js +4 -80
- package/dist/readiness.d.ts +1 -1
- package/dist/readiness.js +3 -6
- package/dist/registry/add.js +11 -38
- package/dist/registry/bootstrap.d.ts +3 -2
- package/dist/registry/bootstrap.js +4 -13
- package/dist/registry/commands.js +8 -10
- package/dist/registry/context.js +0 -1
- package/dist/registry/options.js +8 -26
- package/dist/registry/resolve.d.ts +3 -2
- package/dist/registry/resolve.js +26 -82
- package/dist/registry/types.d.ts +2 -7
- package/dist/registry/usage.js +2 -2
- package/dist/runtime-policy.d.ts +0 -2
- package/dist/runtime-policy.js +0 -13
- package/dist/scaffold/api.js +10 -2
- package/dist/scaffold/auth.d.ts +1 -2
- package/dist/scaffold/auth.js +57 -116
- package/dist/scaffold/backend.d.ts +2 -0
- package/dist/scaffold/backend.js +39 -0
- package/dist/scaffold/billing-config.d.ts +1 -0
- package/dist/scaffold/billing-config.js +73 -0
- package/dist/scaffold/billing-contracts.d.ts +2 -0
- package/dist/scaffold/billing-contracts.js +48 -0
- package/dist/scaffold/billing-providers.d.ts +1 -0
- package/dist/scaffold/billing-providers.js +249 -0
- package/dist/scaffold/billing-schema.d.ts +1 -0
- package/dist/scaffold/billing-schema.js +34 -0
- package/dist/scaffold/billing-security.d.ts +1 -0
- package/dist/scaffold/billing-security.js +46 -0
- package/dist/scaffold/billing-server.d.ts +1 -0
- package/dist/scaffold/billing-server.js +139 -0
- package/dist/scaffold/billing-store.d.ts +1 -0
- package/dist/scaffold/billing-store.js +72 -0
- package/dist/scaffold/billing.d.ts +2 -0
- package/dist/scaffold/billing.js +208 -0
- package/dist/scaffold/bootstrap.d.ts +2 -3
- package/dist/scaffold/bootstrap.js +37 -43
- package/dist/scaffold/compose.js +2 -12
- package/dist/scaffold/database.d.ts +1 -1
- package/dist/scaffold/database.js +20 -111
- package/dist/scaffold/documentation.d.ts +0 -1
- package/dist/scaffold/documentation.js +22 -82
- package/dist/scaffold/expo-auth.d.ts +3 -0
- package/dist/scaffold/expo-auth.js +203 -0
- package/dist/scaffold/expo-billing.d.ts +3 -0
- package/dist/scaffold/expo-billing.js +257 -0
- package/dist/scaffold/expo-runtime.d.ts +3 -0
- package/dist/scaffold/expo-runtime.js +43 -0
- package/dist/scaffold/integrations.d.ts +1 -2
- package/dist/scaffold/integrations.js +9 -5
- package/dist/scaffold/managed-email.d.ts +3 -0
- package/dist/scaffold/managed-email.js +47 -0
- package/dist/scaffold/native-ui.d.ts +2 -0
- package/dist/scaffold/native-ui.js +69 -0
- package/dist/scaffold/password-reset.d.ts +1 -0
- package/dist/scaffold/password-reset.js +99 -0
- package/dist/scaffold/private-files.d.ts +2 -0
- package/dist/scaffold/private-files.js +78 -0
- package/dist/scaffold/stack-documentation.d.ts +0 -1
- package/dist/scaffold/stack-documentation.js +3 -49
- package/dist/scaffold/styling.d.ts +1 -1
- package/dist/scaffold/styling.js +20 -28
- package/dist/scaffold/web-billing.d.ts +2 -0
- package/dist/scaffold/web-billing.js +48 -0
- package/dist/scaffold/workspace.js +53 -189
- package/dist/service-deletion.js +1 -1
- package/dist/service-descriptor.js +5 -12
- package/dist/service-model.d.ts +1 -1
- package/dist/service-operations.js +2 -32
- package/dist/service-readers.js +1 -32
- package/dist/services-command.d.ts +1 -1
- package/dist/services-command.js +3 -9
- package/dist/ship.d.ts +3 -316
- package/dist/ship.js +13 -143
- package/dist/stack-registry.d.ts +2 -43
- package/dist/stack-registry.js +80 -308
- package/dist/standard.js +7 -14
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/docs/anhedral-stack.md +23 -0
- package/docs/assets/anhedral-stack-light.png +0 -0
- package/docs/assets/anhedral-stack.png +0 -0
- package/docs/software-factory.md +25 -499
- package/docs/stack-standard.md +48 -226
- package/docs/verification.md +433 -0
- package/package.json +22 -21
- package/dist/neon-service-data.d.ts +0 -8
- package/dist/neon-service-data.js +0 -117
- package/dist/platforms/desktop.d.ts +0 -2
- package/dist/platforms/desktop.js +0 -415
- package/dist/platforms/extension.d.ts +0 -2
- package/dist/platforms/extension.js +0 -328
- package/dist/scaffold/lint.d.ts +0 -4
- package/dist/scaffold/lint.js +0 -56
- package/dist/scaffold/neon-realtime.d.ts +0 -2
- package/dist/scaffold/neon-realtime.js +0 -97
- package/dist/scaffold/services.d.ts +0 -5
- package/dist/scaffold/services.js +0 -108
- package/dist/scaffold/stream.d.ts +0 -2
- package/dist/scaffold/stream.js +0 -114
- package/dist/scaffold/void.d.ts +0 -4
- package/dist/scaffold/void.js +0 -256
- package/dist/scaffold/web.d.ts +0 -2
- package/dist/scaffold/web.js +0 -128
- package/dist/vercel-project.d.ts +0 -101
- package/dist/vercel-project.js +0 -305
- package/dist/vercel.d.ts +0 -67
- package/dist/vercel.js +0 -581
- package/dist/vinext.d.ts +0 -2
- package/dist/vinext.js +0 -86
- package/dist/void-execution.d.ts +0 -10
- package/dist/void-execution.js +0 -94
- package/dist/void-migrations.d.ts +0 -6
- package/dist/void-migrations.js +0 -110
- package/dist/void-state.d.ts +0 -16
- package/dist/void-state.js +0 -65
- package/dist/void.d.ts +0 -3
- package/dist/void.js +0 -5
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
export const BILLING_PROVIDERS = `import Stripe from 'stripe';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { digest, requireValue, type BillingEnv, type Config, type Plan } from './config';
|
|
4
|
+
import type { Account, Store } from './store';
|
|
5
|
+
|
|
6
|
+
export interface Grant { key: string; expiresAt: number | null; source: 'stripe' | 'revenuecat' }
|
|
7
|
+
export class BillingConflict extends Error {}
|
|
8
|
+
const timeout = 15_000;
|
|
9
|
+
export function stripeClient(env: BillingEnv) {
|
|
10
|
+
return new Stripe(requireValue(env.STRIPE_SECRET_KEY), { httpClient: Stripe.createFetchHttpClient(), maxNetworkRetries: 1, timeout });
|
|
11
|
+
}
|
|
12
|
+
export function verifyMode(livemode: boolean, config: Config): void {
|
|
13
|
+
if (livemode !== (config.environment === 'production')) throw new Error('Unexpected billing environment.');
|
|
14
|
+
}
|
|
15
|
+
function objectId(value: unknown): string | undefined {
|
|
16
|
+
if (typeof value === 'string') return value;
|
|
17
|
+
return z.object({ id: z.string() }).safeParse(value).data?.id;
|
|
18
|
+
}
|
|
19
|
+
async function verifyCustomer(stripe: Stripe, customerId: string, userId: string, config: Config) {
|
|
20
|
+
const customer = await stripe.customers.retrieve(customerId);
|
|
21
|
+
if (customer.deleted) throw new Error('Billing customer no longer exists.');
|
|
22
|
+
verifyMode(customer.livemode, config);
|
|
23
|
+
if (customer.metadata.app_user_id !== userId) throw new Error('Billing customer ownership mismatch.');
|
|
24
|
+
return customer;
|
|
25
|
+
}
|
|
26
|
+
async function stripeCustomer(stripe: Stripe, account: Account, store: Store, config: Config): Promise<string> {
|
|
27
|
+
if (account.stripeCustomerId) {
|
|
28
|
+
await verifyCustomer(stripe, account.stripeCustomerId, account.userId, config);
|
|
29
|
+
return account.stripeCustomerId;
|
|
30
|
+
}
|
|
31
|
+
const idempotencyKey = 'anhedral-customer-' + await digest(account.userId);
|
|
32
|
+
const customer = await stripe.customers.create({ metadata: { app_user_id: account.userId } }, { idempotencyKey });
|
|
33
|
+
verifyMode(customer.livemode, config);
|
|
34
|
+
await store.customer(account, customer.id);
|
|
35
|
+
return customer.id;
|
|
36
|
+
}
|
|
37
|
+
function activeSubscription(subscription: Stripe.Subscription): boolean {
|
|
38
|
+
return ['active', 'trialing'].includes(subscription.status);
|
|
39
|
+
}
|
|
40
|
+
function planForPrice(price: string, config: Config): Plan | undefined {
|
|
41
|
+
return Object.values(config.plans).find((plan) => plan.stripePriceId === price);
|
|
42
|
+
}
|
|
43
|
+
async function soundCharge(stripe: Stripe, payment: Stripe.InvoicePayment, customerId: string, config: Config): Promise<boolean> {
|
|
44
|
+
const intentId = objectId(payment.payment.payment_intent);
|
|
45
|
+
if (!intentId) return false;
|
|
46
|
+
const intent = await stripe.paymentIntents.retrieve(intentId, { expand: ['latest_charge'] });
|
|
47
|
+
verifyMode(intent.livemode, config);
|
|
48
|
+
if (objectId(intent.customer) !== customerId) throw new Error('Payment ownership mismatch.');
|
|
49
|
+
const charge = intent.latest_charge;
|
|
50
|
+
if (!expandedCharge(charge)) return false;
|
|
51
|
+
return validCharge(charge, customerId, config);
|
|
52
|
+
}
|
|
53
|
+
function expandedCharge(value: Stripe.Charge | string | null): value is Stripe.Charge {
|
|
54
|
+
return value !== null && typeof value !== 'string';
|
|
55
|
+
}
|
|
56
|
+
function validCharge(charge: Stripe.Charge, customerId: string, config: Config): boolean {
|
|
57
|
+
verifyMode(charge.livemode, config);
|
|
58
|
+
if (objectId(charge.customer) !== customerId) throw new Error('Charge ownership mismatch.');
|
|
59
|
+
return [charge.paid, !charge.disputed, charge.amount_refunded === 0].every(Boolean);
|
|
60
|
+
}
|
|
61
|
+
async function paidInvoice(stripe: Stripe, subscription: Stripe.Subscription, customerId: string, config: Config): Promise<boolean> {
|
|
62
|
+
if (subscription.status === 'trialing') return true;
|
|
63
|
+
const invoiceId = objectId(subscription.latest_invoice);
|
|
64
|
+
if (!invoiceId) return false;
|
|
65
|
+
const invoice = await stripe.invoices.retrieve(invoiceId);
|
|
66
|
+
verifyMode(invoice.livemode, config);
|
|
67
|
+
if (objectId(invoice.customer) !== customerId) throw new Error('Invoice ownership mismatch.');
|
|
68
|
+
return invoicePayment(stripe, invoice, customerId, config);
|
|
69
|
+
}
|
|
70
|
+
async function invoicePayment(stripe: Stripe, invoice: Stripe.Invoice, customerId: string, config: Config): Promise<boolean> {
|
|
71
|
+
if (invoice.status !== 'paid') return false;
|
|
72
|
+
if (invoice.amount_paid === 0) return true;
|
|
73
|
+
const payments = await stripe.invoicePayments.list({ invoice: invoice.id, status: 'paid', limit: 100 });
|
|
74
|
+
requireCompletePayments(payments);
|
|
75
|
+
if (!payments.data.length) return false;
|
|
76
|
+
const sound = await Promise.all(payments.data.map((payment) => soundCharge(stripe, payment, customerId, config)));
|
|
77
|
+
return sound.every(Boolean);
|
|
78
|
+
}
|
|
79
|
+
function requireCompletePayments(payments: Stripe.ApiList<Stripe.InvoicePayment>): void {
|
|
80
|
+
if (payments.has_more) throw new Error('Billing payment pagination requires reconciliation.');
|
|
81
|
+
}
|
|
82
|
+
function subscriptionGrants(subscription: Stripe.Subscription, config: Config): Grant[] {
|
|
83
|
+
return subscription.items.data.flatMap((item): Grant[] => {
|
|
84
|
+
const plan = planForPrice(item.price.id, config);
|
|
85
|
+
if (!plan || item.current_period_end * 1000 <= Date.now()) return [];
|
|
86
|
+
return [{ key: plan.entitlement, expiresAt: item.current_period_end * 1000, source: 'stripe' }];
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
async function grantsForSubscription(stripe: Stripe, subscription: Stripe.Subscription, account: Account, config: Config): Promise<Grant[]> {
|
|
90
|
+
verifyMode(subscription.livemode, config);
|
|
91
|
+
if (objectId(subscription.customer) !== account.stripeCustomerId) throw new Error('Subscription ownership mismatch.');
|
|
92
|
+
if (!ownedActiveSubscription(subscription, account.userId)) return [];
|
|
93
|
+
if (!await paidInvoice(stripe, subscription, account.stripeCustomerId!, config)) return [];
|
|
94
|
+
return subscriptionGrants(subscription, config);
|
|
95
|
+
}
|
|
96
|
+
function ownedActiveSubscription(subscription: Stripe.Subscription, userId: string): boolean {
|
|
97
|
+
return subscription.metadata.app_user_id === userId && activeSubscription(subscription);
|
|
98
|
+
}
|
|
99
|
+
async function customerSubscriptions(stripe: Stripe, account: Account, config: Config): Promise<Stripe.Subscription[]> {
|
|
100
|
+
if (!account.stripeCustomerId) return [];
|
|
101
|
+
await verifyCustomer(stripe, account.stripeCustomerId, account.userId, config);
|
|
102
|
+
const subscriptions = await stripe.subscriptions.list({ customer: account.stripeCustomerId, status: 'all', limit: 100 });
|
|
103
|
+
if (subscriptions.has_more) throw new Error('Billing subscription pagination requires reconciliation.');
|
|
104
|
+
return subscriptions.data;
|
|
105
|
+
}
|
|
106
|
+
export async function stripeGrants(stripe: Stripe, account: Account, config: Config): Promise<Grant[]> {
|
|
107
|
+
const subscriptions = await customerSubscriptions(stripe, account, config);
|
|
108
|
+
const values = await Promise.all(subscriptions.map((subscription) => grantsForSubscription(stripe, subscription, account, config)));
|
|
109
|
+
return values.flat();
|
|
110
|
+
}
|
|
111
|
+
function configuredSubscription(subscription: Stripe.Subscription, account: Account, config: Config): boolean {
|
|
112
|
+
verifyMode(subscription.livemode, config);
|
|
113
|
+
if (objectId(subscription.customer) !== account.stripeCustomerId) throw new Error('Subscription ownership mismatch.');
|
|
114
|
+
if (['canceled', 'incomplete_expired'].includes(subscription.status)) return false;
|
|
115
|
+
// A nonterminal configured subscription still needs management when its payment
|
|
116
|
+
// failed or was refunded. Absence of an access grant never authorizes another sale.
|
|
117
|
+
return subscription.items.data.some((item) => Boolean(planForPrice(item.price.id, config)));
|
|
118
|
+
}
|
|
119
|
+
async function requireNewSubscription(stripe: Stripe, account: Account, config: Config): Promise<void> {
|
|
120
|
+
const subscriptions = await customerSubscriptions(stripe, account, config);
|
|
121
|
+
if (subscriptions.some((subscription) => configuredSubscription(subscription, account, config))) throw new BillingConflict('Manage the existing subscription in its billing portal.');
|
|
122
|
+
}
|
|
123
|
+
function verifyOpenSession(session: Stripe.Checkout.Session, account: Account, config: Config): string {
|
|
124
|
+
verifyMode(session.livemode, config);
|
|
125
|
+
if (objectId(session.customer) !== account.stripeCustomerId) throw new Error('Checkout ownership mismatch.');
|
|
126
|
+
if (session.metadata?.app_user_id !== account.userId) throw new Error('Checkout identity mismatch.');
|
|
127
|
+
return configuredSessionPlan(session, config);
|
|
128
|
+
}
|
|
129
|
+
function configuredSessionPlan(session: Stripe.Checkout.Session, config: Config): string {
|
|
130
|
+
verifySessionKind(session);
|
|
131
|
+
const plan = sessionPlanId(session);
|
|
132
|
+
if (!plan) throw new Error('Checkout plan is missing.');
|
|
133
|
+
if (!Object.hasOwn(config.plans, plan)) throw new Error('Unexpected checkout plan.');
|
|
134
|
+
return plan;
|
|
135
|
+
}
|
|
136
|
+
function verifySessionKind(session: Stripe.Checkout.Session): void {
|
|
137
|
+
if (session.mode !== 'subscription') throw new Error('Unexpected checkout mode.');
|
|
138
|
+
if (session.status !== 'open') throw new Error('Unexpected checkout state.');
|
|
139
|
+
}
|
|
140
|
+
function sessionPlanId(session: Stripe.Checkout.Session): string | undefined { return session.metadata?.plan_id; }
|
|
141
|
+
async function pendingCheckout(stripe: Stripe, account: Account, planId: string, config: Config): Promise<string | undefined> {
|
|
142
|
+
const sessions = await stripe.checkout.sessions.list({ customer: account.stripeCustomerId!, status: 'open', limit: 100 });
|
|
143
|
+
if (sessions.has_more) throw new Error('Checkout pagination requires reconciliation.');
|
|
144
|
+
const plans = sessions.data.map((session) => verifyOpenSession(session, account, config));
|
|
145
|
+
if (plans.some((plan) => plan !== planId)) throw new BillingConflict('Finish the existing checkout before choosing another plan.');
|
|
146
|
+
return openSessionURL(sessions.data);
|
|
147
|
+
}
|
|
148
|
+
function openSessionURL(sessions: Stripe.Checkout.Session[]): string | undefined {
|
|
149
|
+
if (!sessions.length) return undefined;
|
|
150
|
+
const session = sessions[0];
|
|
151
|
+
verifySessionExpiration(session);
|
|
152
|
+
return providerURL(requireValue(session.url ?? undefined), 'checkout.stripe.com');
|
|
153
|
+
}
|
|
154
|
+
function verifySessionExpiration(session: Stripe.Checkout.Session): void {
|
|
155
|
+
if (!Number.isSafeInteger(session.expires_at)) throw new Error('Invalid checkout expiration.');
|
|
156
|
+
if (session.expires_at * 1000 <= Date.now()) throw new BillingConflict('The existing checkout is expiring. Try again shortly.');
|
|
157
|
+
}
|
|
158
|
+
export async function createCheckout(stripe: Stripe, account: Account, planId: string, idempotencyKey: string, store: Store, config: Config): Promise<string> {
|
|
159
|
+
const plan = config.plans[planId];
|
|
160
|
+
if (!plan) throw new Error('Unknown billing plan.');
|
|
161
|
+
const customer = await stripeCustomer(stripe, account, store, config);
|
|
162
|
+
const owner = { ...account, stripeCustomerId: customer };
|
|
163
|
+
await requireNewSubscription(stripe, owner, config);
|
|
164
|
+
const pending = await pendingCheckout(stripe, owner, planId, config);
|
|
165
|
+
if (pending) return pending;
|
|
166
|
+
const operation = await digest(account.userId + ':' + idempotencyKey);
|
|
167
|
+
const result = await stripe.checkout.sessions.create({
|
|
168
|
+
mode: 'subscription', customer,
|
|
169
|
+
line_items: [{ price: plan.stripePriceId, quantity: 1 }],
|
|
170
|
+
client_reference_id: account.userId,
|
|
171
|
+
metadata: { app_user_id: account.userId, plan_id: planId },
|
|
172
|
+
subscription_data: { metadata: { app_user_id: account.userId, plan_id: planId } },
|
|
173
|
+
success_url: config.origin + '/billing?result=success',
|
|
174
|
+
cancel_url: config.origin + '/billing?result=cancelled',
|
|
175
|
+
integration_identifier: 'anhedral_' + operation.slice(0, 8).split('').map((character) => String.fromCharCode(97 + Number.parseInt(character, 16))).join(''),
|
|
176
|
+
}, { idempotencyKey: 'anhedral-checkout-' + operation });
|
|
177
|
+
return providerURL(requireValue(result.url ?? undefined), 'checkout.stripe.com');
|
|
178
|
+
}
|
|
179
|
+
function providerURL(value: string, hostname: string): string {
|
|
180
|
+
const url = new URL(value);
|
|
181
|
+
if ([url.protocol !== 'https:', url.hostname !== hostname, url.username, url.password].some(Boolean)) throw new Error('Unexpected billing provider URL.');
|
|
182
|
+
return url.href;
|
|
183
|
+
}
|
|
184
|
+
export async function createPortal(stripe: Stripe, account: Account, config: Config): Promise<string> {
|
|
185
|
+
if (!account.stripeCustomerId) throw new Error('No web billing subscription for this account.');
|
|
186
|
+
await verifyCustomer(stripe, account.stripeCustomerId, account.userId, config);
|
|
187
|
+
const portal = await stripe.billingPortal.sessions.create({ customer: account.stripeCustomerId, return_url: config.origin + '/billing' });
|
|
188
|
+
return providerURL(portal.url, 'billing.stripe.com');
|
|
189
|
+
}
|
|
190
|
+
export async function stripeEventCustomer(stripe: Stripe, event: Stripe.Event): Promise<string | undefined> {
|
|
191
|
+
const object = event.data.object as unknown as Record<string, unknown>;
|
|
192
|
+
const customer = objectId(object.customer);
|
|
193
|
+
if (customer) return customer;
|
|
194
|
+
const charge = objectId(object.charge);
|
|
195
|
+
if (!charge) return undefined;
|
|
196
|
+
return objectId((await stripe.charges.retrieve(charge)).customer);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const purchase = z.object({ is_sandbox: z.boolean(), store: z.string(), expires_date: z.string().nullable().optional(), grace_period_expires_date: z.string().nullable().optional() });
|
|
200
|
+
const rcSchema = z.object({ subscriber: z.object({
|
|
201
|
+
entitlements: z.record(z.string(), z.object({ product_identifier: z.string(), expires_date: z.string().nullable(), grace_period_expires_date: z.string().nullable().optional() })),
|
|
202
|
+
subscriptions: z.record(z.string(), purchase),
|
|
203
|
+
non_subscriptions: z.record(z.string(), z.array(purchase)).optional(),
|
|
204
|
+
}) });
|
|
205
|
+
type Subscriber = z.infer<typeof rcSchema>['subscriber'];
|
|
206
|
+
type Purchase = z.infer<typeof purchase>;
|
|
207
|
+
function matchesPurchase(value: Purchase, config: Config, stripeEnabled: boolean): boolean {
|
|
208
|
+
if (value.is_sandbox !== (config.environment === 'sandbox')) return false;
|
|
209
|
+
return !(stripeEnabled && value.store === 'stripe');
|
|
210
|
+
}
|
|
211
|
+
function receiptForProduct(subscriber: Subscriber, productId: string, config: Config, stripeEnabled: boolean): Purchase | undefined {
|
|
212
|
+
const candidates = [subscriber.subscriptions[productId], ...(subscriber.non_subscriptions?.[productId] ?? [])].filter((value): value is Purchase => Boolean(value));
|
|
213
|
+
return candidates.find((value) => matchesPurchase(value, config, stripeEnabled));
|
|
214
|
+
}
|
|
215
|
+
function expires(value: string | null | undefined): number | null {
|
|
216
|
+
if (value === null) return null;
|
|
217
|
+
const parsed = Date.parse(value ?? '');
|
|
218
|
+
if (!Number.isFinite(parsed)) throw new Error('Invalid provider entitlement expiry.');
|
|
219
|
+
return parsed;
|
|
220
|
+
}
|
|
221
|
+
function revenueCatGrant(key: string, subscriber: Subscriber, config: Config, stripeEnabled: boolean): Grant[] {
|
|
222
|
+
const entitlement = subscriber.entitlements[key];
|
|
223
|
+
if (!entitlement) return [];
|
|
224
|
+
const receipt = receiptForProduct(subscriber, entitlement.product_identifier, config, stripeEnabled);
|
|
225
|
+
if (!receipt) return [];
|
|
226
|
+
const expiry = entitlementExpiry(entitlement);
|
|
227
|
+
if (!validExpiry(expiry)) return [];
|
|
228
|
+
return [{ key, expiresAt: expiry, source: 'revenuecat' }];
|
|
229
|
+
}
|
|
230
|
+
function entitlementExpiry(entitlement: { expires_date: string | null; grace_period_expires_date?: string | null }): number | null {
|
|
231
|
+
return expires(entitlement.grace_period_expires_date ?? entitlement.expires_date);
|
|
232
|
+
}
|
|
233
|
+
function validExpiry(expiry: number | null): boolean { return expiry === null || expiry > Date.now(); }
|
|
234
|
+
function requireRevenueCatScope(config: Config): void {
|
|
235
|
+
if (!config.projectId) throw new Error('Configure the RevenueCat project.');
|
|
236
|
+
if (!config.appIds.length) throw new Error('Configure the RevenueCat app allowlist.');
|
|
237
|
+
}
|
|
238
|
+
export async function revenueCatGrants(userId: string, env: BillingEnv, config: Config, stripeEnabled: boolean): Promise<Grant[]> {
|
|
239
|
+
requireRevenueCatScope(config);
|
|
240
|
+
const response = await fetch('https://api.revenuecat.com/v1/subscribers/' + encodeURIComponent(userId), {
|
|
241
|
+
headers: { authorization: 'Bearer ' + requireValue(env.REVENUECAT_SECRET_KEY), accept: 'application/json' },
|
|
242
|
+
signal: AbortSignal.timeout(timeout), redirect: 'error',
|
|
243
|
+
});
|
|
244
|
+
if (response.status === 404) return [];
|
|
245
|
+
if (!response.ok) throw new Error('RevenueCat reconciliation failed.');
|
|
246
|
+
const { subscriber } = rcSchema.parse(await response.json());
|
|
247
|
+
return config.entitlements.flatMap((key) => revenueCatGrant(key, subscriber, config, stripeEnabled));
|
|
248
|
+
}
|
|
249
|
+
`;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function scaffoldBillingSchema(root: string): void;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { put } from './files.js';
|
|
4
|
+
export function scaffoldBillingSchema(root) {
|
|
5
|
+
const table = 'sqliteTable';
|
|
6
|
+
const integer = 'integer(name)';
|
|
7
|
+
put(root, 'packages/db/src/billing-schema.ts', `import { ${table}, text, integer, index } from 'drizzle-orm/sqlite-core';
|
|
8
|
+
const number = (name: string) => ${integer};
|
|
9
|
+
|
|
10
|
+
// Billing IDs are verified auth subjects, including external identity providers.
|
|
11
|
+
// They are never inferred from email addresses or client purchase claims.
|
|
12
|
+
export const billingAccounts = ${table}('billing_accounts', {
|
|
13
|
+
userId: text('user_id').primaryKey(),
|
|
14
|
+
stripeCustomerId: text('stripe_customer_id').unique(),
|
|
15
|
+
leaseToken: text('lease_token'),
|
|
16
|
+
leaseUntil: number('lease_until').notNull().default(0),
|
|
17
|
+
snapshot: text('snapshot').notNull().default('{}'),
|
|
18
|
+
checkedAt: number('checked_at').notNull().default(0),
|
|
19
|
+
});
|
|
20
|
+
export const billingEvents = ${table}('billing_events', {
|
|
21
|
+
id: text('id').primaryKey(),
|
|
22
|
+
provider: text('provider').notNull(),
|
|
23
|
+
users: text('users').notNull(),
|
|
24
|
+
state: text('state').notNull().default('pending'),
|
|
25
|
+
attempts: number('attempts').notNull().default(0),
|
|
26
|
+
nextAttemptAt: number('next_attempt_at').notNull().default(0),
|
|
27
|
+
createdAt: number('created_at').notNull(),
|
|
28
|
+
}, (table) => [index('billing_events_pending_idx').on(table.state, table.nextAttemptAt)]);
|
|
29
|
+
`);
|
|
30
|
+
const file = 'packages/db/src/schema.ts';
|
|
31
|
+
const source = readFileSync(path.join(root, file), 'utf8');
|
|
32
|
+
if (!source.includes("export * from './billing-schema'"))
|
|
33
|
+
put(root, file, source + "\nexport * from './billing-schema';\n");
|
|
34
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const BILLING_SECURITY = "import { z } from 'zod';\nimport { equalSecret, requireValue, type BillingEnv, type Config } from './config';\n\nexport const stripeEventTypes = new Set(['checkout.session.completed', 'checkout.session.async_payment_succeeded', 'customer.subscription.created', 'customer.subscription.updated', 'customer.subscription.deleted', 'invoice.paid', 'invoice.payment_failed', 'charge.refunded', 'charge.dispute.created']);\nexport const rcEventSchema = z.object({ event: z.object({\n id: z.string().min(1).max(200),\n app_id: z.string(), environment: z.enum(['SANDBOX', 'PRODUCTION']),\n project_id: z.string().optional(),\n app_user_id: z.string().max(1500).optional(),\n original_app_user_id: z.string().max(1500).optional(),\n aliases: z.array(z.string().max(1500)).max(50).optional(),\n transferred_from: z.array(z.string().max(1500)).max(50).optional(),\n transferred_to: z.array(z.string().max(1500)).max(50).optional(),\n}) });\nexport type RevenueCatEvent = z.infer<typeof rcEventSchema>['event'];\n\nfunction verifyRevenueCatApp(event: RevenueCatEvent, config: Config): void {\n if (!config.projectId) throw new Error('Configure the RevenueCat project.');\n if (!config.appIds.includes(event.app_id)) throw new Error('Unexpected RevenueCat app.');\n}\nexport function verifyRevenueCatScope(event: RevenueCatEvent, config: Config): void {\n verifyRevenueCatApp(event, config);\n if (event.project_id && event.project_id !== config.projectId) throw new Error('Unexpected RevenueCat project.');\n if (event.environment.toLowerCase() !== config.environment) throw new Error('Unexpected billing environment.');\n}\nexport function revenueCatUsers(event: RevenueCatEvent): string[] {\n return [event.app_user_id, event.original_app_user_id, ...(event.aliases ?? []), ...(event.transferred_from ?? []), ...(event.transferred_to ?? [])].filter((value): value is string => typeof value === 'string').slice(0, 50);\n}\nasync function verifyHmac(raw: string, header: string, secret: string): Promise<boolean> {\n const match = /^t=([0-9]+),v1=([a-f0-9]{64})$/.exec(header);\n if (!match) return false;\n if (Math.abs(Date.now() / 1000 - Number(match[1])) > 300) return false;\n const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);\n const signature = Uint8Array.from(match[2].match(/../g)!, (value) => Number.parseInt(value, 16));\n return crypto.subtle.verify('HMAC', key, signature, new TextEncoder().encode(match[1] + '.' + raw));\n}\nasync function verifyAuthorization(headers: Headers, env: BillingEnv): Promise<void> {\n const expected = requireValue(env.REVENUECAT_WEBHOOK_AUTHORIZATION);\n if (!await equalSecret(headers.get('authorization') ?? '', expected)) throw new Error('Invalid RevenueCat authorization.');\n}\nexport async function verifyRevenueCat(raw: string, headers: Headers, env: BillingEnv): Promise<void> {\n await verifyAuthorization(headers, env);\n if (!env.REVENUECAT_WEBHOOK_SIGNING_SECRET) return;\n if (!await verifyHmac(raw, headers.get('X-RevenueCat-Webhook-Signature') ?? '', env.REVENUECAT_WEBHOOK_SIGNING_SECRET)) throw new Error('Invalid RevenueCat signature.');\n}\n";
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
export const BILLING_SECURITY = `import { z } from 'zod';
|
|
2
|
+
import { equalSecret, requireValue, type BillingEnv, type Config } from './config';
|
|
3
|
+
|
|
4
|
+
export const stripeEventTypes = new Set(['checkout.session.completed', 'checkout.session.async_payment_succeeded', 'customer.subscription.created', 'customer.subscription.updated', 'customer.subscription.deleted', 'invoice.paid', 'invoice.payment_failed', 'charge.refunded', 'charge.dispute.created']);
|
|
5
|
+
export const rcEventSchema = z.object({ event: z.object({
|
|
6
|
+
id: z.string().min(1).max(200),
|
|
7
|
+
app_id: z.string(), environment: z.enum(['SANDBOX', 'PRODUCTION']),
|
|
8
|
+
project_id: z.string().optional(),
|
|
9
|
+
app_user_id: z.string().max(1500).optional(),
|
|
10
|
+
original_app_user_id: z.string().max(1500).optional(),
|
|
11
|
+
aliases: z.array(z.string().max(1500)).max(50).optional(),
|
|
12
|
+
transferred_from: z.array(z.string().max(1500)).max(50).optional(),
|
|
13
|
+
transferred_to: z.array(z.string().max(1500)).max(50).optional(),
|
|
14
|
+
}) });
|
|
15
|
+
export type RevenueCatEvent = z.infer<typeof rcEventSchema>['event'];
|
|
16
|
+
|
|
17
|
+
function verifyRevenueCatApp(event: RevenueCatEvent, config: Config): void {
|
|
18
|
+
if (!config.projectId) throw new Error('Configure the RevenueCat project.');
|
|
19
|
+
if (!config.appIds.includes(event.app_id)) throw new Error('Unexpected RevenueCat app.');
|
|
20
|
+
}
|
|
21
|
+
export function verifyRevenueCatScope(event: RevenueCatEvent, config: Config): void {
|
|
22
|
+
verifyRevenueCatApp(event, config);
|
|
23
|
+
if (event.project_id && event.project_id !== config.projectId) throw new Error('Unexpected RevenueCat project.');
|
|
24
|
+
if (event.environment.toLowerCase() !== config.environment) throw new Error('Unexpected billing environment.');
|
|
25
|
+
}
|
|
26
|
+
export function revenueCatUsers(event: RevenueCatEvent): string[] {
|
|
27
|
+
return [event.app_user_id, event.original_app_user_id, ...(event.aliases ?? []), ...(event.transferred_from ?? []), ...(event.transferred_to ?? [])].filter((value): value is string => typeof value === 'string').slice(0, 50);
|
|
28
|
+
}
|
|
29
|
+
async function verifyHmac(raw: string, header: string, secret: string): Promise<boolean> {
|
|
30
|
+
const match = /^t=([0-9]+),v1=([a-f0-9]{64})$/.exec(header);
|
|
31
|
+
if (!match) return false;
|
|
32
|
+
if (Math.abs(Date.now() / 1000 - Number(match[1])) > 300) return false;
|
|
33
|
+
const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']);
|
|
34
|
+
const signature = Uint8Array.from(match[2].match(/../g)!, (value) => Number.parseInt(value, 16));
|
|
35
|
+
return crypto.subtle.verify('HMAC', key, signature, new TextEncoder().encode(match[1] + '.' + raw));
|
|
36
|
+
}
|
|
37
|
+
async function verifyAuthorization(headers: Headers, env: BillingEnv): Promise<void> {
|
|
38
|
+
const expected = requireValue(env.REVENUECAT_WEBHOOK_AUTHORIZATION);
|
|
39
|
+
if (!await equalSecret(headers.get('authorization') ?? '', expected)) throw new Error('Invalid RevenueCat authorization.');
|
|
40
|
+
}
|
|
41
|
+
export async function verifyRevenueCat(raw: string, headers: Headers, env: BillingEnv): Promise<void> {
|
|
42
|
+
await verifyAuthorization(headers, env);
|
|
43
|
+
if (!env.REVENUECAT_WEBHOOK_SIGNING_SECRET) return;
|
|
44
|
+
if (!await verifyHmac(raw, headers.get('X-RevenueCat-Webhook-Signature') ?? '', env.REVENUECAT_WEBHOOK_SIGNING_SECRET)) throw new Error('Invalid RevenueCat signature.');
|
|
45
|
+
}
|
|
46
|
+
`;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const BILLING_SERVER = "import { z } from 'zod';\nimport Stripe from 'stripe';\nimport { billingEntitlementsSchema } from '@workspace/contracts';\nimport { billingConfig, requireValue, type BillingEnv } from './config';\nimport { createStore, type Account, type Database, type InboxEvent } from './store';\nimport { BillingConflict, createCheckout, createPortal, revenueCatGrants, stripeClient, stripeEventCustomer, stripeGrants, verifyMode, type Grant } from './providers';\nimport { rcEventSchema, revenueCatUsers, stripeEventTypes, verifyRevenueCat, verifyRevenueCatScope } from './security';\n\nexport class BillingError extends Error {\n constructor(public status: 400 | 401 | 403 | 409 | 503, message: string) { super(message); }\n}\nconst freshFor = 60_000;\nconst grantsSchema = z.array(z.object({ key: z.string(), expiresAt: z.number().nullable(), source: z.enum(['stripe', 'revenuecat']) })).max(1000);\nfunction future(grant: Grant): boolean { return grant.expiresAt === null || grant.expiresAt > Date.now(); }\nfunction longest(grants: Grant[]): number | null {\n if (grants.some((grant) => grant.expiresAt === null)) return null;\n return Math.max(...grants.map((grant) => grant.expiresAt!));\n}\nfunction summary(key: string, grants: Grant[]) {\n const matches = grants.filter((grant) => grant.key === key).filter(future);\n return { key, active: matches.length > 0, expiresAt: matches.length ? date(longest(matches)) : null, sources: [...new Set(matches.map((grant) => grant.source))] };\n}\nfunction date(value: number | null): string | null { return value === null ? null : new Date(value).toISOString(); }\nfunction fresh(account: Account): boolean {\n const age = Date.now() - account.checkedAt;\n return account.checkedAt > 0 && age >= 0 && age < freshFor;\n}\nfunction idempotency(value: string): string {\n const result = z.uuid().safeParse(value);\n if (!result.success) throw new BillingError(400, 'A UUID Idempotency-Key is required.');\n return result.data;\n}\n\nexport function createBilling(options: { database: Database; env: BillingEnv; stripeEnabled: boolean; revenueCatEnabled: boolean }) {\n const { env, stripeEnabled, revenueCatEnabled } = options;\n const config = billingConfig(env);\n const store = createStore(options.database);\n const stripe = stripeEnabled ? stripeClient(env) : undefined;\n\n function report(account: Account) {\n const grants = grantsSchema.parse(JSON.parse(account.snapshot));\n return billingEntitlementsSchema.parse({ entitlements: config.entitlements.map((key) => summary(key, grants)), checkedAt: new Date(account.checkedAt).toISOString() });\n }\n async function canonical(account: Account): Promise<Grant[]> {\n const web = stripe ? await stripeGrants(stripe, account, config) : [];\n const native = revenueCatEnabled ? await revenueCatGrants(account.userId, env, config, stripeEnabled) : [];\n return [...web, ...native];\n }\n async function withLease<T>(userId: string, action: (account: Account) => Promise<T>): Promise<T> {\n const account = await store.acquire(userId);\n if (!account) throw new BillingError(409, 'Billing reconciliation is already running. Retry shortly.');\n try { return await action(account); }\n finally { await store.release(account); }\n }\n async function reconcile(userId: string) {\n return withLease(userId, async (account) => {\n const grants = await canonical(account);\n const checkedAt = Date.now();\n await store.commit(account, JSON.stringify(grants), checkedAt);\n return report({ ...account, snapshot: JSON.stringify(grants), checkedAt });\n });\n }\n async function entitlements(userId: string, force = false) {\n const account = await store.ensure(userId);\n if (!force && fresh(account)) return report(account);\n // No provider response means no new grant; expired projections fail closed.\n return reconcile(userId);\n }\n async function identity(userId: string) {\n await store.ensure(userId);\n return { appUserId: userId, providers: { stripe: stripeEnabled, revenuecat: revenueCatEnabled }, plans: Object.entries(config.plans).map(([id, plan]) => ({ id, label: plan.label })) };\n }\n async function checkout(userId: string, plan: string, requestId: string) {\n if (!stripe) throw new BillingError(400, 'Web checkout is unavailable.');\n if (!Object.hasOwn(config.plans, plan)) throw new BillingError(400, 'Unknown billing plan.');\n const key = idempotency(requestId);\n return withLease(userId, async (account) => {\n try { return { url: await createCheckout(stripe, account, plan, key, store, config) }; }\n catch (error) {\n if (error instanceof BillingConflict) throw new BillingError(409, error.message);\n throw error;\n }\n });\n }\n async function portal(userId: string) {\n if (!stripe) throw new BillingError(400, 'Web billing portal is unavailable.');\n return withLease(userId, async (account) => ({ url: await createPortal(stripe, account, config) }));\n }\n async function assertEntitled(userId: string, key: string): Promise<void> {\n const state = await entitlements(userId);\n if (!state.entitlements.some((value) => value.key === key && value.active)) throw new BillingError(403, 'An active entitlement is required.');\n }\n async function process(event: InboxEvent): Promise<void> {\n if (event.state === 'done') return;\n const users = z.array(z.string()).max(50).parse(JSON.parse(event.users));\n try {\n for (const user of users) await reconcile(user);\n await store.complete(event.id);\n } catch {\n await store.failed(event.id);\n throw new BillingError(503, 'Billing reconciliation pending.');\n }\n }\n async function stripeEvent(raw: string, headers: Headers) {\n if (!stripe) throw new BillingError(400, 'Stripe is not selected.');\n let event: Stripe.Event;\n try {\n event = await stripe.webhooks.constructEventAsync(raw, headers.get('stripe-signature') ?? '', requireValue(env.STRIPE_WEBHOOK_SECRET), 300, Stripe.createSubtleCryptoProvider());\n } catch { throw new BillingError(401, 'Invalid Stripe webhook.'); }\n verifyMode(event.livemode, config);\n return event;\n }\n async function stripeWebhook(raw: string, headers: Headers): Promise<void> {\n const event = await stripeEvent(raw, headers);\n if (!stripeEventTypes.has(event.type)) return;\n const customerId = await stripeEventCustomer(stripe!, event);\n const owner = customerId ? await store.customerOwner(customerId) : undefined;\n const users = owner ? [owner.userId] : [];\n await process(await store.inbox('stripe:' + config.environment, event.id, users));\n }\n async function revenueCatWebhook(raw: string, headers: Headers): Promise<void> {\n if (!revenueCatEnabled) throw new BillingError(400, 'RevenueCat is not selected.');\n try { await verifyRevenueCat(raw, headers, env); }\n catch { throw new BillingError(401, 'Invalid RevenueCat webhook.'); }\n const { event } = rcEventSchema.parse(JSON.parse(raw));\n verifyRevenueCatScope(event, config);\n const users = await store.known(revenueCatUsers(event));\n await process(await store.inbox('revenuecat:' + config.environment, event.id, users));\n }\n async function drainPending(): Promise<void> {\n for (const event of await store.pending()) {\n try { await process(event); }\n catch { /* Persisted retry remains pending; never log provider bodies or secrets. */ }\n }\n }\n return { identity, entitlements, checkout, portal, assertEntitled, stripeWebhook, revenueCatWebhook, drainPending, config };\n}\nexport type Billing = ReturnType<typeof createBilling>;\n";
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
export const BILLING_SERVER = `import { z } from 'zod';
|
|
2
|
+
import Stripe from 'stripe';
|
|
3
|
+
import { billingEntitlementsSchema } from '@workspace/contracts';
|
|
4
|
+
import { billingConfig, requireValue, type BillingEnv } from './config';
|
|
5
|
+
import { createStore, type Account, type Database, type InboxEvent } from './store';
|
|
6
|
+
import { BillingConflict, createCheckout, createPortal, revenueCatGrants, stripeClient, stripeEventCustomer, stripeGrants, verifyMode, type Grant } from './providers';
|
|
7
|
+
import { rcEventSchema, revenueCatUsers, stripeEventTypes, verifyRevenueCat, verifyRevenueCatScope } from './security';
|
|
8
|
+
|
|
9
|
+
export class BillingError extends Error {
|
|
10
|
+
constructor(public status: 400 | 401 | 403 | 409 | 503, message: string) { super(message); }
|
|
11
|
+
}
|
|
12
|
+
const freshFor = 60_000;
|
|
13
|
+
const grantsSchema = z.array(z.object({ key: z.string(), expiresAt: z.number().nullable(), source: z.enum(['stripe', 'revenuecat']) })).max(1000);
|
|
14
|
+
function future(grant: Grant): boolean { return grant.expiresAt === null || grant.expiresAt > Date.now(); }
|
|
15
|
+
function longest(grants: Grant[]): number | null {
|
|
16
|
+
if (grants.some((grant) => grant.expiresAt === null)) return null;
|
|
17
|
+
return Math.max(...grants.map((grant) => grant.expiresAt!));
|
|
18
|
+
}
|
|
19
|
+
function summary(key: string, grants: Grant[]) {
|
|
20
|
+
const matches = grants.filter((grant) => grant.key === key).filter(future);
|
|
21
|
+
return { key, active: matches.length > 0, expiresAt: matches.length ? date(longest(matches)) : null, sources: [...new Set(matches.map((grant) => grant.source))] };
|
|
22
|
+
}
|
|
23
|
+
function date(value: number | null): string | null { return value === null ? null : new Date(value).toISOString(); }
|
|
24
|
+
function fresh(account: Account): boolean {
|
|
25
|
+
const age = Date.now() - account.checkedAt;
|
|
26
|
+
return account.checkedAt > 0 && age >= 0 && age < freshFor;
|
|
27
|
+
}
|
|
28
|
+
function idempotency(value: string): string {
|
|
29
|
+
const result = z.uuid().safeParse(value);
|
|
30
|
+
if (!result.success) throw new BillingError(400, 'A UUID Idempotency-Key is required.');
|
|
31
|
+
return result.data;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function createBilling(options: { database: Database; env: BillingEnv; stripeEnabled: boolean; revenueCatEnabled: boolean }) {
|
|
35
|
+
const { env, stripeEnabled, revenueCatEnabled } = options;
|
|
36
|
+
const config = billingConfig(env);
|
|
37
|
+
const store = createStore(options.database);
|
|
38
|
+
const stripe = stripeEnabled ? stripeClient(env) : undefined;
|
|
39
|
+
|
|
40
|
+
function report(account: Account) {
|
|
41
|
+
const grants = grantsSchema.parse(JSON.parse(account.snapshot));
|
|
42
|
+
return billingEntitlementsSchema.parse({ entitlements: config.entitlements.map((key) => summary(key, grants)), checkedAt: new Date(account.checkedAt).toISOString() });
|
|
43
|
+
}
|
|
44
|
+
async function canonical(account: Account): Promise<Grant[]> {
|
|
45
|
+
const web = stripe ? await stripeGrants(stripe, account, config) : [];
|
|
46
|
+
const native = revenueCatEnabled ? await revenueCatGrants(account.userId, env, config, stripeEnabled) : [];
|
|
47
|
+
return [...web, ...native];
|
|
48
|
+
}
|
|
49
|
+
async function withLease<T>(userId: string, action: (account: Account) => Promise<T>): Promise<T> {
|
|
50
|
+
const account = await store.acquire(userId);
|
|
51
|
+
if (!account) throw new BillingError(409, 'Billing reconciliation is already running. Retry shortly.');
|
|
52
|
+
try { return await action(account); }
|
|
53
|
+
finally { await store.release(account); }
|
|
54
|
+
}
|
|
55
|
+
async function reconcile(userId: string) {
|
|
56
|
+
return withLease(userId, async (account) => {
|
|
57
|
+
const grants = await canonical(account);
|
|
58
|
+
const checkedAt = Date.now();
|
|
59
|
+
await store.commit(account, JSON.stringify(grants), checkedAt);
|
|
60
|
+
return report({ ...account, snapshot: JSON.stringify(grants), checkedAt });
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
async function entitlements(userId: string, force = false) {
|
|
64
|
+
const account = await store.ensure(userId);
|
|
65
|
+
if (!force && fresh(account)) return report(account);
|
|
66
|
+
// No provider response means no new grant; expired projections fail closed.
|
|
67
|
+
return reconcile(userId);
|
|
68
|
+
}
|
|
69
|
+
async function identity(userId: string) {
|
|
70
|
+
await store.ensure(userId);
|
|
71
|
+
return { appUserId: userId, providers: { stripe: stripeEnabled, revenuecat: revenueCatEnabled }, plans: Object.entries(config.plans).map(([id, plan]) => ({ id, label: plan.label })) };
|
|
72
|
+
}
|
|
73
|
+
async function checkout(userId: string, plan: string, requestId: string) {
|
|
74
|
+
if (!stripe) throw new BillingError(400, 'Web checkout is unavailable.');
|
|
75
|
+
if (!Object.hasOwn(config.plans, plan)) throw new BillingError(400, 'Unknown billing plan.');
|
|
76
|
+
const key = idempotency(requestId);
|
|
77
|
+
return withLease(userId, async (account) => {
|
|
78
|
+
try { return { url: await createCheckout(stripe, account, plan, key, store, config) }; }
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (error instanceof BillingConflict) throw new BillingError(409, error.message);
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
async function portal(userId: string) {
|
|
86
|
+
if (!stripe) throw new BillingError(400, 'Web billing portal is unavailable.');
|
|
87
|
+
return withLease(userId, async (account) => ({ url: await createPortal(stripe, account, config) }));
|
|
88
|
+
}
|
|
89
|
+
async function assertEntitled(userId: string, key: string): Promise<void> {
|
|
90
|
+
const state = await entitlements(userId);
|
|
91
|
+
if (!state.entitlements.some((value) => value.key === key && value.active)) throw new BillingError(403, 'An active entitlement is required.');
|
|
92
|
+
}
|
|
93
|
+
async function process(event: InboxEvent): Promise<void> {
|
|
94
|
+
if (event.state === 'done') return;
|
|
95
|
+
const users = z.array(z.string()).max(50).parse(JSON.parse(event.users));
|
|
96
|
+
try {
|
|
97
|
+
for (const user of users) await reconcile(user);
|
|
98
|
+
await store.complete(event.id);
|
|
99
|
+
} catch {
|
|
100
|
+
await store.failed(event.id);
|
|
101
|
+
throw new BillingError(503, 'Billing reconciliation pending.');
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async function stripeEvent(raw: string, headers: Headers) {
|
|
105
|
+
if (!stripe) throw new BillingError(400, 'Stripe is not selected.');
|
|
106
|
+
let event: Stripe.Event;
|
|
107
|
+
try {
|
|
108
|
+
event = await stripe.webhooks.constructEventAsync(raw, headers.get('stripe-signature') ?? '', requireValue(env.STRIPE_WEBHOOK_SECRET), 300, Stripe.createSubtleCryptoProvider());
|
|
109
|
+
} catch { throw new BillingError(401, 'Invalid Stripe webhook.'); }
|
|
110
|
+
verifyMode(event.livemode, config);
|
|
111
|
+
return event;
|
|
112
|
+
}
|
|
113
|
+
async function stripeWebhook(raw: string, headers: Headers): Promise<void> {
|
|
114
|
+
const event = await stripeEvent(raw, headers);
|
|
115
|
+
if (!stripeEventTypes.has(event.type)) return;
|
|
116
|
+
const customerId = await stripeEventCustomer(stripe!, event);
|
|
117
|
+
const owner = customerId ? await store.customerOwner(customerId) : undefined;
|
|
118
|
+
const users = owner ? [owner.userId] : [];
|
|
119
|
+
await process(await store.inbox('stripe:' + config.environment, event.id, users));
|
|
120
|
+
}
|
|
121
|
+
async function revenueCatWebhook(raw: string, headers: Headers): Promise<void> {
|
|
122
|
+
if (!revenueCatEnabled) throw new BillingError(400, 'RevenueCat is not selected.');
|
|
123
|
+
try { await verifyRevenueCat(raw, headers, env); }
|
|
124
|
+
catch { throw new BillingError(401, 'Invalid RevenueCat webhook.'); }
|
|
125
|
+
const { event } = rcEventSchema.parse(JSON.parse(raw));
|
|
126
|
+
verifyRevenueCatScope(event, config);
|
|
127
|
+
const users = await store.known(revenueCatUsers(event));
|
|
128
|
+
await process(await store.inbox('revenuecat:' + config.environment, event.id, users));
|
|
129
|
+
}
|
|
130
|
+
async function drainPending(): Promise<void> {
|
|
131
|
+
for (const event of await store.pending()) {
|
|
132
|
+
try { await process(event); }
|
|
133
|
+
catch { /* Persisted retry remains pending; never log provider bodies or secrets. */ }
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return { identity, entitlements, checkout, portal, assertEntitled, stripeWebhook, revenueCatWebhook, drainPending, config };
|
|
137
|
+
}
|
|
138
|
+
export type Billing = ReturnType<typeof createBilling>;
|
|
139
|
+
`;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const BILLING_STORE = "import { and, eq, lt, gt, sql } from 'drizzle-orm';\nimport type { createDatabase } from '@workspace/db';\nimport { billingAccounts, billingEvents } from '@workspace/db/schema';\n\nexport type Database = ReturnType<typeof createDatabase>;\nexport type Account = typeof billingAccounts.$inferSelect;\nexport type InboxEvent = typeof billingEvents.$inferSelect;\nconst leaseDuration = 90_000;\n\nexport function createStore(db: Database) {\n async function account(userId: string): Promise<Account | undefined> {\n return (await db.select().from(billingAccounts).where(eq(billingAccounts.userId, userId)).limit(1))[0];\n }\n async function ensure(userId: string): Promise<Account> {\n await db.insert(billingAccounts).values({ userId }).onConflictDoNothing();\n const value = await account(userId);\n if (!value) throw new Error('Billing account unavailable.');\n return value;\n }\n async function acquire(userId: string): Promise<Account | undefined> {\n await ensure(userId);\n return (await db.update(billingAccounts).set({ leaseToken: crypto.randomUUID(), leaseUntil: Date.now() + leaseDuration })\n .where(and(eq(billingAccounts.userId, userId), lt(billingAccounts.leaseUntil, Date.now())))\n .returning())[0];\n }\n function owned(value: Account) {\n if (!value.leaseToken) throw new Error('Billing lease required.');\n return and(eq(billingAccounts.userId, value.userId), eq(billingAccounts.leaseToken, value.leaseToken), gt(billingAccounts.leaseUntil, Date.now()));\n }\n async function customer(value: Account, customerId: string): Promise<void> {\n const saved = await db.update(billingAccounts).set({ stripeCustomerId: customerId }).where(owned(value)).returning();\n if (!saved.length) throw new Error('Billing lease expired.');\n }\n async function commit(value: Account, snapshot: string, checkedAt: number): Promise<void> {\n const saved = await db.update(billingAccounts).set({ snapshot, checkedAt, leaseToken: null, leaseUntil: 0 }).where(owned(value)).returning();\n if (!saved.length) throw new Error('Billing lease expired.');\n }\n async function release(value: Account): Promise<void> {\n if (!value.leaseToken) return;\n await db.update(billingAccounts).set({ leaseToken: null, leaseUntil: 0 })\n .where(and(eq(billingAccounts.userId, value.userId), eq(billingAccounts.leaseToken, value.leaseToken)));\n }\n async function known(userIds: string[]): Promise<string[]> {\n const result: string[] = [];\n for (const userId of [...new Set(userIds)].slice(0, 50)) {\n if (await account(userId)) result.push(userId);\n }\n return result;\n }\n async function customerOwner(customerId: string): Promise<Account | undefined> {\n return (await db.select().from(billingAccounts).where(eq(billingAccounts.stripeCustomerId, customerId)).limit(1))[0];\n }\n async function inbox(provider: string, eventId: string, userIds: string[]): Promise<InboxEvent> {\n const id = provider + ':' + eventId;\n await db.insert(billingEvents).values({ id, provider, users: JSON.stringify(userIds), createdAt: Date.now() }).onConflictDoNothing();\n const result = (await db.select().from(billingEvents).where(eq(billingEvents.id, id)).limit(1))[0];\n if (!result) throw new Error('Billing inbox unavailable.');\n return result;\n }\n async function complete(id: string): Promise<void> {\n await db.update(billingEvents).set({ state: 'done' }).where(eq(billingEvents.id, id));\n }\n async function failed(id: string): Promise<void> {\n await db.update(billingEvents).set({ attempts: sql`${billingEvents.attempts} + 1`, nextAttemptAt: Date.now() + 60_000 }).where(eq(billingEvents.id, id));\n }\n async function pending(): Promise<InboxEvent[]> {\n return db.select().from(billingEvents).where(and(eq(billingEvents.state, 'pending'), lt(billingEvents.nextAttemptAt, Date.now()))).limit(10);\n }\n return { account, ensure, acquire, customer, commit, release, known, customerOwner, inbox, complete, failed, pending };\n}\nexport type Store = ReturnType<typeof createStore>;\n";
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
export const BILLING_STORE = `import { and, eq, lt, gt, sql } from 'drizzle-orm';
|
|
2
|
+
import type { createDatabase } from '@workspace/db';
|
|
3
|
+
import { billingAccounts, billingEvents } from '@workspace/db/schema';
|
|
4
|
+
|
|
5
|
+
export type Database = ReturnType<typeof createDatabase>;
|
|
6
|
+
export type Account = typeof billingAccounts.$inferSelect;
|
|
7
|
+
export type InboxEvent = typeof billingEvents.$inferSelect;
|
|
8
|
+
const leaseDuration = 90_000;
|
|
9
|
+
|
|
10
|
+
export function createStore(db: Database) {
|
|
11
|
+
async function account(userId: string): Promise<Account | undefined> {
|
|
12
|
+
return (await db.select().from(billingAccounts).where(eq(billingAccounts.userId, userId)).limit(1))[0];
|
|
13
|
+
}
|
|
14
|
+
async function ensure(userId: string): Promise<Account> {
|
|
15
|
+
await db.insert(billingAccounts).values({ userId }).onConflictDoNothing();
|
|
16
|
+
const value = await account(userId);
|
|
17
|
+
if (!value) throw new Error('Billing account unavailable.');
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
async function acquire(userId: string): Promise<Account | undefined> {
|
|
21
|
+
await ensure(userId);
|
|
22
|
+
return (await db.update(billingAccounts).set({ leaseToken: crypto.randomUUID(), leaseUntil: Date.now() + leaseDuration })
|
|
23
|
+
.where(and(eq(billingAccounts.userId, userId), lt(billingAccounts.leaseUntil, Date.now())))
|
|
24
|
+
.returning())[0];
|
|
25
|
+
}
|
|
26
|
+
function owned(value: Account) {
|
|
27
|
+
if (!value.leaseToken) throw new Error('Billing lease required.');
|
|
28
|
+
return and(eq(billingAccounts.userId, value.userId), eq(billingAccounts.leaseToken, value.leaseToken), gt(billingAccounts.leaseUntil, Date.now()));
|
|
29
|
+
}
|
|
30
|
+
async function customer(value: Account, customerId: string): Promise<void> {
|
|
31
|
+
const saved = await db.update(billingAccounts).set({ stripeCustomerId: customerId }).where(owned(value)).returning();
|
|
32
|
+
if (!saved.length) throw new Error('Billing lease expired.');
|
|
33
|
+
}
|
|
34
|
+
async function commit(value: Account, snapshot: string, checkedAt: number): Promise<void> {
|
|
35
|
+
const saved = await db.update(billingAccounts).set({ snapshot, checkedAt, leaseToken: null, leaseUntil: 0 }).where(owned(value)).returning();
|
|
36
|
+
if (!saved.length) throw new Error('Billing lease expired.');
|
|
37
|
+
}
|
|
38
|
+
async function release(value: Account): Promise<void> {
|
|
39
|
+
if (!value.leaseToken) return;
|
|
40
|
+
await db.update(billingAccounts).set({ leaseToken: null, leaseUntil: 0 })
|
|
41
|
+
.where(and(eq(billingAccounts.userId, value.userId), eq(billingAccounts.leaseToken, value.leaseToken)));
|
|
42
|
+
}
|
|
43
|
+
async function known(userIds: string[]): Promise<string[]> {
|
|
44
|
+
const result: string[] = [];
|
|
45
|
+
for (const userId of [...new Set(userIds)].slice(0, 50)) {
|
|
46
|
+
if (await account(userId)) result.push(userId);
|
|
47
|
+
}
|
|
48
|
+
return result;
|
|
49
|
+
}
|
|
50
|
+
async function customerOwner(customerId: string): Promise<Account | undefined> {
|
|
51
|
+
return (await db.select().from(billingAccounts).where(eq(billingAccounts.stripeCustomerId, customerId)).limit(1))[0];
|
|
52
|
+
}
|
|
53
|
+
async function inbox(provider: string, eventId: string, userIds: string[]): Promise<InboxEvent> {
|
|
54
|
+
const id = provider + ':' + eventId;
|
|
55
|
+
await db.insert(billingEvents).values({ id, provider, users: JSON.stringify(userIds), createdAt: Date.now() }).onConflictDoNothing();
|
|
56
|
+
const result = (await db.select().from(billingEvents).where(eq(billingEvents.id, id)).limit(1))[0];
|
|
57
|
+
if (!result) throw new Error('Billing inbox unavailable.');
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
async function complete(id: string): Promise<void> {
|
|
61
|
+
await db.update(billingEvents).set({ state: 'done' }).where(eq(billingEvents.id, id));
|
|
62
|
+
}
|
|
63
|
+
async function failed(id: string): Promise<void> {
|
|
64
|
+
await db.update(billingEvents).set({ attempts: sql\`\${billingEvents.attempts} + 1\`, nextAttemptAt: Date.now() + 60_000 }).where(eq(billingEvents.id, id));
|
|
65
|
+
}
|
|
66
|
+
async function pending(): Promise<InboxEvent[]> {
|
|
67
|
+
return db.select().from(billingEvents).where(and(eq(billingEvents.state, 'pending'), lt(billingEvents.nextAttemptAt, Date.now()))).limit(10);
|
|
68
|
+
}
|
|
69
|
+
return { account, ensure, acquire, customer, commit, release, known, customerOwner, inbox, complete, failed, pending };
|
|
70
|
+
}
|
|
71
|
+
export type Store = ReturnType<typeof createStore>;
|
|
72
|
+
`;
|