anhedral 0.12.0 → 0.13.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.
Files changed (73) hide show
  1. package/README.md +99 -39
  2. package/dist/capabilities.d.ts +3 -3
  3. package/dist/capability-contract.js +12 -1
  4. package/dist/command-schema.js +8 -2
  5. package/dist/command.js +9 -11
  6. package/dist/delivery.js +3 -1
  7. package/dist/dependencies.d.ts +6 -1
  8. package/dist/dependencies.js +13 -1
  9. package/dist/index.d.ts +1 -0
  10. package/dist/index.js +1 -0
  11. package/dist/platforms/mobile.d.ts +1 -1
  12. package/dist/platforms/mobile.js +44 -3
  13. package/dist/project-state.js +4 -1
  14. package/dist/provider-auth.js +6 -0
  15. package/dist/providers/adapters.js +9 -3
  16. package/dist/providers/runtime.js +11 -0
  17. package/dist/readiness.js +4 -2
  18. package/dist/registry/add.js +40 -7
  19. package/dist/registry/options.js +12 -0
  20. package/dist/registry/presets.d.ts +4 -0
  21. package/dist/registry/presets.js +41 -0
  22. package/dist/registry/resolve.d.ts +3 -1
  23. package/dist/registry/resolve.js +40 -14
  24. package/dist/registry/types.d.ts +1 -0
  25. package/dist/registry/usage.js +1 -1
  26. package/dist/runtime-policy.js +4 -1
  27. package/dist/scaffold/api.js +10 -2
  28. package/dist/scaffold/auth.d.ts +1 -1
  29. package/dist/scaffold/auth.js +22 -6
  30. package/dist/scaffold/backend.d.ts +6 -0
  31. package/dist/scaffold/backend.js +224 -0
  32. package/dist/scaffold/billing-config.d.ts +1 -0
  33. package/dist/scaffold/billing-config.js +73 -0
  34. package/dist/scaffold/billing-contracts.d.ts +2 -0
  35. package/dist/scaffold/billing-contracts.js +48 -0
  36. package/dist/scaffold/billing-providers.d.ts +1 -0
  37. package/dist/scaffold/billing-providers.js +249 -0
  38. package/dist/scaffold/billing-schema.d.ts +1 -0
  39. package/dist/scaffold/billing-schema.js +34 -0
  40. package/dist/scaffold/billing-security.d.ts +1 -0
  41. package/dist/scaffold/billing-security.js +46 -0
  42. package/dist/scaffold/billing-server.d.ts +1 -0
  43. package/dist/scaffold/billing-server.js +139 -0
  44. package/dist/scaffold/billing-store.d.ts +1 -0
  45. package/dist/scaffold/billing-store.js +72 -0
  46. package/dist/scaffold/billing.d.ts +2 -0
  47. package/dist/scaffold/billing.js +216 -0
  48. package/dist/scaffold/cloudflare-services.d.ts +8 -0
  49. package/dist/scaffold/cloudflare-services.js +198 -0
  50. package/dist/scaffold/compose.js +2 -0
  51. package/dist/scaffold/database.js +19 -2
  52. package/dist/scaffold/documentation.js +10 -6
  53. package/dist/scaffold/expo-auth.d.ts +3 -0
  54. package/dist/scaffold/expo-auth.js +192 -0
  55. package/dist/scaffold/expo-billing.d.ts +3 -0
  56. package/dist/scaffold/expo-billing.js +292 -0
  57. package/dist/scaffold/expo-runtime.d.ts +3 -0
  58. package/dist/scaffold/expo-runtime.js +134 -0
  59. package/dist/scaffold/integrations.d.ts +2 -1
  60. package/dist/scaffold/integrations.js +7 -2
  61. package/dist/scaffold/void.js +13 -5
  62. package/dist/scaffold/web.js +2 -0
  63. package/dist/scaffold/workspace.js +6 -1
  64. package/dist/ship.js +3 -1
  65. package/dist/stack-registry.d.ts +11 -2
  66. package/dist/stack-registry.js +136 -16
  67. package/dist/version.d.ts +1 -1
  68. package/dist/version.js +1 -1
  69. package/docs/anhedral-stack.md +122 -0
  70. package/docs/software-factory.md +67 -8
  71. package/docs/stack-standard.md +126 -57
  72. package/docs/verification.md +113 -0
  73. package/package.json +7 -4
@@ -0,0 +1,224 @@
1
+ import { existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { resourceName } from '../render.js';
4
+ import { STACK_DEPENDENCIES } from '../dependencies.js';
5
+ import { json, patchPackage, put, readJson, sharedPackage } from './files.js';
6
+ import { writeEnvironmentFile } from './environment.js';
7
+ /** Public contracts never import a framework, database or auth server. */
8
+ export function scaffoldContracts(root) {
9
+ sharedPackage(root, 'contracts', `import { z } from 'zod';
10
+ import { createHttpClient, type HttpOptions } from './http';
11
+
12
+ export const healthSchema = z.object({ ok: z.literal(true) });
13
+ export const sessionSchema = z.object({ user: z.object({ id: z.string(), name: z.string(), email: z.email() }) });
14
+ export type Session = z.infer<typeof sessionSchema>;
15
+
16
+ export function createApiClient(baseURL = '/api', options: HttpOptions = {}) {
17
+ const request = createHttpClient(baseURL, options);
18
+ return {
19
+ health: (init?: RequestInit) => request('/health', healthSchema, init),
20
+ session: (init?: RequestInit) => request('/session', sessionSchema, init),
21
+ };
22
+ }
23
+ `, { zod: STACK_DEPENDENCIES.zod });
24
+ put(root, 'packages/contracts/src/http.ts', `import type { z } from 'zod';
25
+
26
+ export interface HttpOptions {
27
+ headers?: () => HeadersInit | Promise<HeadersInit>;
28
+ credentials?: 'omit' | 'same-origin' | 'include';
29
+ }
30
+ export function createHttpClient(baseURL: string, options: HttpOptions = {}) {
31
+ return async function request<T>(route: string, schema: z.ZodType<T>, init: RequestInit = {}): Promise<T> {
32
+ const headers = new Headers(await options.headers?.());
33
+ new Headers(init.headers).forEach((value, name) => headers.set(name, value));
34
+ headers.set('accept', 'application/json');
35
+ // Worker fetch types omit the browser credentials member.
36
+ const settings: RequestInit & { credentials: 'omit' | 'same-origin' | 'include' } = { ...init, credentials: options.credentials ?? 'same-origin', headers };
37
+ const response = await fetch(baseURL.replace(/\\/$/, '') + route, settings);
38
+ if (!response.ok) throw new Error('API request failed (' + response.status + ').');
39
+ return schema.parse(await response.json());
40
+ };
41
+ }
42
+ `);
43
+ }
44
+ /** A single trusted upstream; never forward provider/edge identity headers from browsers. */
45
+ export function scaffoldWebBackend({ root, options, has }) {
46
+ if (!has('hono'))
47
+ return;
48
+ if (has('better-auth')) {
49
+ patchPackage(root, 'apps/web/package.json', {
50
+ dependencies: { '@workspace/contracts': 'workspace:*' },
51
+ });
52
+ put(root, 'apps/web/lib/api-client.ts', `import { createApiClient } from '@workspace/contracts';
53
+ export const api = createApiClient();
54
+ `);
55
+ }
56
+ put(root, 'apps/web/lib/api-proxy.ts', `type Transport = (request: Request) => Promise<Response>;
57
+ const forwardedHeaders = ['accept', 'content-type', 'cookie', 'origin', 'authorization', 'expo-origin', 'sec-fetch-site', 'idempotency-key'];
58
+ const removedHeaders = ['connection', 'transfer-encoding', 'access-control-allow-origin', 'access-control-allow-credentials'];
59
+ function isLocal(url: URL) {
60
+ return url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
61
+ }
62
+ function trustedOrigin(origin: string) {
63
+ const url = new URL(origin);
64
+ if (url.protocol !== 'https:' && !isLocal(url)) throw new Error('Configure a trusted HTTPS API origin (HTTP is local-only).');
65
+ if ([url.username, url.password, url.pathname.replace('/', ''), url.search, url.hash].some(Boolean)) {
66
+ throw new Error('Configure a trusted HTTPS API origin without credentials or a path.');
67
+ }
68
+ return url;
69
+ }
70
+ function requestHeaders(request: Request) {
71
+ const headers = new Headers();
72
+ for (const name of forwardedHeaders) {
73
+ const value = request.headers.get(name);
74
+ if (value) headers.set(name, value);
75
+ }
76
+ return headers;
77
+ }
78
+ function privateResponse(response: Response) {
79
+ const headers = new Headers(response.headers);
80
+ for (const name of removedHeaders) headers.delete(name);
81
+ headers.set('cache-control', 'private, no-store');
82
+ return new Response(response.body, { status: response.status, headers });
83
+ }
84
+ export function createApiProxy(send: Transport, origin: string) {
85
+ const upstream = trustedOrigin(origin);
86
+ return async function proxy(request: Request): Promise<Response> {
87
+ const path = new URL(request.url);
88
+ if (!path.pathname.startsWith('/api/')) return new Response(null, { status: 404 });
89
+ const target = new URL(upstream);
90
+ target.pathname = path.pathname;
91
+ target.search = path.search;
92
+ try {
93
+ const forwarded = new Request(new Request(target, request), {
94
+ headers: requestHeaders(request), redirect: 'manual',
95
+ signal: AbortSignal.any([request.signal, AbortSignal.timeout(15000)]),
96
+ });
97
+ return privateResponse(await send(forwarded));
98
+ } catch {
99
+ return Response.json({ error: 'API unavailable' }, { status: 503, headers: { 'cache-control': 'private, no-store' } });
100
+ }
101
+ };
102
+ }
103
+ `);
104
+ const cloudflare = options.hosting === 'cloudflare';
105
+ const binding = has('vinext')
106
+ ? "import { env } from 'cloudflare:workers';"
107
+ : "import { getCloudflareContext } from '@opennextjs/cloudflare';";
108
+ const transport = cloudflare
109
+ ? `${binding}
110
+ import { createApiProxy } from '@/lib/api-proxy';
111
+ async function handler(request: Request) {
112
+ const bindings = ${has('vinext') ? 'env' : '(await getCloudflareContext({ async: true })).env'} as unknown as { API: { fetch(request: Request): Promise<Response> } };
113
+ return createApiProxy((upstream) => bindings.API.fetch(upstream), 'https://localhost')(request);
114
+ }`
115
+ : `import { apiTransport } from '@/lib/api-transport';
116
+ import { createApiProxy } from '@/lib/api-proxy';
117
+ async function handler(request: Request) {
118
+ const origin = process.env.API_URL;
119
+ if (!origin) return Response.json({ error: 'Configure API_URL' }, { status: 503 });
120
+ return createApiProxy(apiTransport, origin)(request);
121
+ }`;
122
+ put(root, 'apps/web/app/api/[...path]/route.ts', `${transport}
123
+ export { handler as GET, handler as POST, handler as PUT, handler as PATCH, handler as DELETE, handler as OPTIONS, handler as HEAD };
124
+ `);
125
+ if (cloudflare) {
126
+ const configFile = existsSync(path.join(root, 'apps/web/wrangler.jsonc'))
127
+ ? 'apps/web/wrangler.jsonc'
128
+ : 'apps/web/anhedral.cloudflare.json';
129
+ const config = readJson(root, configFile);
130
+ const services = (config.services ?? []);
131
+ json(root, configFile, {
132
+ ...config,
133
+ services: [
134
+ ...services.filter((service) => service.binding !== 'API'),
135
+ { binding: 'API', service: resourceName(options.name, 'api') },
136
+ ],
137
+ });
138
+ }
139
+ else {
140
+ put(root, 'apps/web/lib/api-transport.ts', `// Service credentials are server-only; never forward browser-supplied Access identity.
141
+ export function apiTransport(request: Request) {
142
+ const id = process.env.API_ACCESS_CLIENT_ID;
143
+ const secret = process.env.API_ACCESS_CLIENT_SECRET;
144
+ if (Boolean(id) !== Boolean(secret)) throw new Error('Configure both API Access credentials.');
145
+ const headers = new Headers(request.headers);
146
+ if (id && secret) {
147
+ headers.set('CF-Access-Client-Id', id);
148
+ headers.set('CF-Access-Client-Secret', secret);
149
+ }
150
+ return fetch(request, { headers, redirect: 'manual' });
151
+ }
152
+ `);
153
+ writeEnvironmentFile(root, 'apps/web/.env.example', {
154
+ API_URL: 'http://127.0.0.1:8787',
155
+ API_ACCESS_CLIENT_ID: '',
156
+ API_ACCESS_CLIENT_SECRET: '',
157
+ });
158
+ }
159
+ }
160
+ export function scaffoldWebAuth(root) {
161
+ patchPackage(root, 'apps/web/package.json', {
162
+ dependencies: { 'better-auth': STACK_DEPENDENCIES['better-auth'] },
163
+ });
164
+ put(root, 'apps/web/lib/auth-client.ts', `import { createAuthClient } from 'better-auth/react';
165
+ export const authClient = createAuthClient();
166
+ `);
167
+ put(root, 'apps/web/app/sign-in/page.tsx', `'use client';
168
+
169
+ import { useState } from 'react';
170
+ import { Button } from '@workspace/ui/components/button';
171
+ import { api } from '@/lib/api-client';
172
+ import { authClient } from '@/lib/auth-client';
173
+
174
+ const modes = {
175
+ signIn: { title: 'Sign in', password: 'current-password', name: false, next: 'signUp', toggle: 'Create an account' },
176
+ signUp: { title: 'Create account', password: 'new-password', name: true, next: 'signIn', toggle: 'Use an existing account' },
177
+ } as const;
178
+ type Mode = keyof typeof modes;
179
+ function authenticate(mode: Mode, form: FormData) {
180
+ const credentials = { email: String(form.get('email')), password: String(form.get('password')) };
181
+ if (mode === 'signUp') return authClient.signUp.email({ ...credentials, name: String(form.get('name')) });
182
+ return authClient.signIn.email(credentials);
183
+ }
184
+ function AuthForm({ refresh }: { refresh: () => Promise<unknown> }) {
185
+ const [mode, setMode] = useState<Mode>('signIn');
186
+ const [pending, setPending] = useState(false);
187
+ const [message, setMessage] = useState('');
188
+ const fields = modes[mode];
189
+ async function submit(event: React.SyntheticEvent<HTMLFormElement>) {
190
+ event.preventDefault();
191
+ const form = new FormData(event.currentTarget);
192
+ setPending(true);
193
+ setMessage('');
194
+ try {
195
+ const result = await authenticate(mode, form);
196
+ if (result.error) { setMessage(result.error.message ?? 'Sign in failed.'); return; }
197
+ await api.session();
198
+ await refresh();
199
+ } catch { setMessage('Unable to reach the API.'); }
200
+ finally { setPending(false); }
201
+ }
202
+ return <main className="mx-auto grid max-w-sm gap-4 p-6">
203
+ <h1 className="text-xl font-medium">{fields.title}</h1>
204
+ <form onSubmit={submit} className="grid gap-3">
205
+ {fields.name && <label>Name<input className="block w-full rounded border p-2" name="name" autoComplete="name" required /></label>}
206
+ <label>Email<input className="block w-full rounded border p-2" type="email" name="email" autoComplete="email" required /></label>
207
+ <label>Password<input className="block w-full rounded border p-2" type="password" name="password" autoComplete={fields.password} minLength={8} required /></label>
208
+ <Button type="submit" disabled={pending}>{pending ? 'Working…' : fields.title}</Button>
209
+ </form>
210
+ <p role="status">{message}</p>
211
+ <Button variant="ghost" disabled={pending} onClick={() => { setMode(fields.next); setMessage(''); }}>{fields.toggle}</Button>
212
+ </main>;
213
+ }
214
+ export default function SignInPage() {
215
+ const { data: session, refetch } = authClient.useSession();
216
+ if (!session) return <AuthForm refresh={refetch} />;
217
+ return <main className="mx-auto grid max-w-sm gap-4 p-6">
218
+ <h1 className="text-xl font-medium">Account</h1>
219
+ <p>{session.user.email}</p>
220
+ <Button onClick={async () => { await authClient.signOut(); await refetch(); }}>Sign out</Button>
221
+ </main>;
222
+ }
223
+ `);
224
+ }
@@ -0,0 +1 @@
1
+ export declare const BILLING_CONFIG = "import { z } from 'zod';\n\nexport interface BillingEnv {\n BILLING_ORIGIN: string;\n BILLING_ENVIRONMENT: string;\n BILLING_PLANS_JSON?: string;\n BILLING_ENTITLEMENTS_JSON: string;\n BILLING_PREMIUM_ENTITLEMENT?: string;\n STRIPE_SECRET_KEY?: string;\n STRIPE_WEBHOOK_SECRET?: string;\n REVENUECAT_SECRET_KEY?: string;\n REVENUECAT_WEBHOOK_AUTHORIZATION?: string;\n REVENUECAT_WEBHOOK_SIGNING_SECRET?: string;\n REVENUECAT_APP_IDS_JSON?: string;\n REVENUECAT_PROJECT_ID?: string;\n}\nconst key = z.string().regex(/^[a-zA-Z0-9_.-]{1,100}$/);\nconst planSchema = z.object({ label: z.string().min(1).max(100), stripePriceId: z.string().regex(/^price_[a-zA-Z0-9]+$/), entitlement: key }).strict();\nconst plansSchema = z.record(key, planSchema);\nexport type Plan = z.infer<typeof planSchema>;\nexport interface Config {\n origin: string;\n environment: 'sandbox' | 'production';\n plans: Record<string, Plan>;\n entitlements: string[];\n appIds: string[];\n projectId: string;\n demoEntitlement: string;\n}\nfunction json(value: string | undefined, fallback: string): unknown {\n return JSON.parse(value ?? fallback);\n}\nfunction protocolAllowed(url: URL, environment: 'sandbox' | 'production'): boolean {\n if (url.protocol === 'https:') return true;\n if (environment !== 'sandbox') return false;\n return url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);\n}\nfunction origin(value: string, environment: 'sandbox' | 'production'): string {\n const url = new URL(value);\n if (!protocolAllowed(url, environment)) throw new Error('Billing requires HTTPS; sandbox HTTP is loopback-only.');\n if ([url.username, url.password, url.pathname !== '/', url.search, url.hash].some(Boolean)) throw new Error('Billing requires an origin without credentials or a path.');\n return url.origin;\n}\nexport function billingConfig(env: BillingEnv): Config {\n const environment = z.enum(['sandbox', 'production']).parse(env.BILLING_ENVIRONMENT);\n const plans = plansSchema.parse(json(env.BILLING_PLANS_JSON, '{}'));\n const entitlements = z.array(key).min(1).max(100).parse(json(env.BILLING_ENTITLEMENTS_JSON, '[]'));\n if (Object.values(plans).some((plan) => !entitlements.includes(plan.entitlement))) throw new Error('Every billing plan needs an allowed entitlement.');\n return {\n origin: origin(env.BILLING_ORIGIN, environment),\n environment,\n plans, entitlements,\n appIds: z.array(z.string().regex(/^app[a-zA-Z0-9_]+$/)).max(50).parse(json(env.REVENUECAT_APP_IDS_JSON, '[]')),\n projectId: env.REVENUECAT_PROJECT_ID ?? '',\n demoEntitlement: key.parse(env.BILLING_PREMIUM_ENTITLEMENT ?? 'premium'),\n };\n}\nexport function requireValue(value: string | undefined): string {\n if (!value?.trim()) throw new Error('Billing provider configuration is incomplete.');\n return value;\n}\nexport async function digest(value: string): Promise<string> {\n const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));\n return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, '0')).join('');\n}\nexport async function equalSecret(actual: string, expected: string): Promise<boolean> {\n // Fixed-length digests make comparison independent of secret length.\n const values = await Promise.all([digest(actual), digest(expected)]);\n let difference = 0;\n for (let index = 0; index < values[0].length; index++) difference |= values[0].charCodeAt(index) ^ values[1].charCodeAt(index);\n return difference === 0;\n}\n";
@@ -0,0 +1,73 @@
1
+ export const BILLING_CONFIG = `import { z } from 'zod';
2
+
3
+ export interface BillingEnv {
4
+ BILLING_ORIGIN: string;
5
+ BILLING_ENVIRONMENT: string;
6
+ BILLING_PLANS_JSON?: string;
7
+ BILLING_ENTITLEMENTS_JSON: string;
8
+ BILLING_PREMIUM_ENTITLEMENT?: string;
9
+ STRIPE_SECRET_KEY?: string;
10
+ STRIPE_WEBHOOK_SECRET?: string;
11
+ REVENUECAT_SECRET_KEY?: string;
12
+ REVENUECAT_WEBHOOK_AUTHORIZATION?: string;
13
+ REVENUECAT_WEBHOOK_SIGNING_SECRET?: string;
14
+ REVENUECAT_APP_IDS_JSON?: string;
15
+ REVENUECAT_PROJECT_ID?: string;
16
+ }
17
+ const key = z.string().regex(/^[a-zA-Z0-9_.-]{1,100}$/);
18
+ const planSchema = z.object({ label: z.string().min(1).max(100), stripePriceId: z.string().regex(/^price_[a-zA-Z0-9]+$/), entitlement: key }).strict();
19
+ const plansSchema = z.record(key, planSchema);
20
+ export type Plan = z.infer<typeof planSchema>;
21
+ export interface Config {
22
+ origin: string;
23
+ environment: 'sandbox' | 'production';
24
+ plans: Record<string, Plan>;
25
+ entitlements: string[];
26
+ appIds: string[];
27
+ projectId: string;
28
+ demoEntitlement: string;
29
+ }
30
+ function json(value: string | undefined, fallback: string): unknown {
31
+ return JSON.parse(value ?? fallback);
32
+ }
33
+ function protocolAllowed(url: URL, environment: 'sandbox' | 'production'): boolean {
34
+ if (url.protocol === 'https:') return true;
35
+ if (environment !== 'sandbox') return false;
36
+ return url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
37
+ }
38
+ function origin(value: string, environment: 'sandbox' | 'production'): string {
39
+ const url = new URL(value);
40
+ if (!protocolAllowed(url, environment)) throw new Error('Billing requires HTTPS; sandbox HTTP is loopback-only.');
41
+ if ([url.username, url.password, url.pathname !== '/', url.search, url.hash].some(Boolean)) throw new Error('Billing requires an origin without credentials or a path.');
42
+ return url.origin;
43
+ }
44
+ export function billingConfig(env: BillingEnv): Config {
45
+ const environment = z.enum(['sandbox', 'production']).parse(env.BILLING_ENVIRONMENT);
46
+ const plans = plansSchema.parse(json(env.BILLING_PLANS_JSON, '{}'));
47
+ const entitlements = z.array(key).min(1).max(100).parse(json(env.BILLING_ENTITLEMENTS_JSON, '[]'));
48
+ if (Object.values(plans).some((plan) => !entitlements.includes(plan.entitlement))) throw new Error('Every billing plan needs an allowed entitlement.');
49
+ return {
50
+ origin: origin(env.BILLING_ORIGIN, environment),
51
+ environment,
52
+ plans, entitlements,
53
+ appIds: z.array(z.string().regex(/^app[a-zA-Z0-9_]+$/)).max(50).parse(json(env.REVENUECAT_APP_IDS_JSON, '[]')),
54
+ projectId: env.REVENUECAT_PROJECT_ID ?? '',
55
+ demoEntitlement: key.parse(env.BILLING_PREMIUM_ENTITLEMENT ?? 'premium'),
56
+ };
57
+ }
58
+ export function requireValue(value: string | undefined): string {
59
+ if (!value?.trim()) throw new Error('Billing provider configuration is incomplete.');
60
+ return value;
61
+ }
62
+ export async function digest(value: string): Promise<string> {
63
+ const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
64
+ return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, '0')).join('');
65
+ }
66
+ export async function equalSecret(actual: string, expected: string): Promise<boolean> {
67
+ // Fixed-length digests make comparison independent of secret length.
68
+ const values = await Promise.all([digest(actual), digest(expected)]);
69
+ let difference = 0;
70
+ for (let index = 0; index < values[0].length; index++) difference |= values[0].charCodeAt(index) ^ values[1].charCodeAt(index);
71
+ return difference === 0;
72
+ }
73
+ `;
@@ -0,0 +1,2 @@
1
+ /** Public billing transport exposes verified identity and entitlements, never provider secrets. */
2
+ export declare function scaffoldBillingContracts(root: string): void;
@@ -0,0 +1,48 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { scaffoldContracts } from './backend.js';
3
+ import path from 'node:path';
4
+ import { put } from './files.js';
5
+ /** Public billing transport exposes verified identity and entitlements, never provider secrets. */
6
+ export function scaffoldBillingContracts(root) {
7
+ if (!existsSync(path.join(root, 'packages/contracts/src/http.ts')))
8
+ scaffoldContracts(root);
9
+ put(root, 'packages/contracts/src/billing.ts', `import { z } from 'zod';
10
+ import { createHttpClient, type HttpOptions } from './http';
11
+
12
+ export const billingIdentitySchema = z.object({
13
+ appUserId: z.string(),
14
+ providers: z.object({ stripe: z.boolean(), revenuecat: z.boolean() }),
15
+ plans: z.array(z.object({ id: z.string(), label: z.string() })),
16
+ });
17
+ export const billingEntitlementsSchema = z.object({
18
+ entitlements: z.array(z.object({ key: z.string(), active: z.boolean(), expiresAt: z.string().nullable(), sources: z.array(z.enum(['stripe', 'revenuecat'])) })),
19
+ checkedAt: z.string(),
20
+ });
21
+ export const billingUrlSchema = z.object({ url: z.url().refine((value) => new URL(value).protocol === 'https:', 'Billing navigation requires HTTPS.') });
22
+ export type BillingIdentity = z.infer<typeof billingIdentitySchema>;
23
+ export type BillingEntitlements = z.infer<typeof billingEntitlementsSchema>;
24
+ export function createBillingClient(baseURL = '/api/billing', options: HttpOptions = {}) {
25
+ const request = createHttpClient(baseURL, options);
26
+ function post<T>(route: string, schema: z.ZodType<T>, body: unknown, headers: HeadersInit = {}) {
27
+ const combined = new Headers(headers);
28
+ combined.set('content-type', 'application/json');
29
+ return request(route, schema, { method: 'POST', body: JSON.stringify(body), headers: combined });
30
+ }
31
+ return {
32
+ identity: () => request('/identity', billingIdentitySchema),
33
+ entitlements: () => request('/entitlements', billingEntitlementsSchema),
34
+ refresh: () => post('/refresh', billingEntitlementsSchema, {}),
35
+ checkout: (plan: string, idempotencyKey: string) => {
36
+ const body = z.strictObject({ plan: z.string().min(1) }).parse({ plan });
37
+ const key = z.uuid().parse(idempotencyKey);
38
+ return post('/checkout', billingUrlSchema, body, { 'idempotency-key': key });
39
+ },
40
+ portal: () => post('/portal', billingUrlSchema, {}),
41
+ };
42
+ }
43
+ `);
44
+ const file = 'packages/contracts/src/index.ts';
45
+ const source = readFileSync(path.join(root, file), 'utf8');
46
+ if (!source.includes("export * from './billing'"))
47
+ put(root, file, source + "\nexport * from './billing';\n");
48
+ }
@@ -0,0 +1 @@
1
+ export declare const BILLING_PROVIDERS = "import Stripe from 'stripe';\nimport { z } from 'zod';\nimport { digest, requireValue, type BillingEnv, type Config, type Plan } from './config';\nimport type { Account, Store } from './store';\n\nexport interface Grant { key: string; expiresAt: number | null; source: 'stripe' | 'revenuecat' }\nexport class BillingConflict extends Error {}\nconst timeout = 15_000;\nexport function stripeClient(env: BillingEnv) {\n return new Stripe(requireValue(env.STRIPE_SECRET_KEY), { httpClient: Stripe.createFetchHttpClient(), maxNetworkRetries: 1, timeout });\n}\nexport function verifyMode(livemode: boolean, config: Config): void {\n if (livemode !== (config.environment === 'production')) throw new Error('Unexpected billing environment.');\n}\nfunction objectId(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n return z.object({ id: z.string() }).safeParse(value).data?.id;\n}\nasync function verifyCustomer(stripe: Stripe, customerId: string, userId: string, config: Config) {\n const customer = await stripe.customers.retrieve(customerId);\n if (customer.deleted) throw new Error('Billing customer no longer exists.');\n verifyMode(customer.livemode, config);\n if (customer.metadata.app_user_id !== userId) throw new Error('Billing customer ownership mismatch.');\n return customer;\n}\nasync function stripeCustomer(stripe: Stripe, account: Account, store: Store, config: Config): Promise<string> {\n if (account.stripeCustomerId) {\n await verifyCustomer(stripe, account.stripeCustomerId, account.userId, config);\n return account.stripeCustomerId;\n }\n const idempotencyKey = 'anhedral-customer-' + await digest(account.userId);\n const customer = await stripe.customers.create({ metadata: { app_user_id: account.userId } }, { idempotencyKey });\n verifyMode(customer.livemode, config);\n await store.customer(account, customer.id);\n return customer.id;\n}\nfunction activeSubscription(subscription: Stripe.Subscription): boolean {\n return ['active', 'trialing'].includes(subscription.status);\n}\nfunction planForPrice(price: string, config: Config): Plan | undefined {\n return Object.values(config.plans).find((plan) => plan.stripePriceId === price);\n}\nasync function soundCharge(stripe: Stripe, payment: Stripe.InvoicePayment, customerId: string, config: Config): Promise<boolean> {\n const intentId = objectId(payment.payment.payment_intent);\n if (!intentId) return false;\n const intent = await stripe.paymentIntents.retrieve(intentId, { expand: ['latest_charge'] });\n verifyMode(intent.livemode, config);\n if (objectId(intent.customer) !== customerId) throw new Error('Payment ownership mismatch.');\n const charge = intent.latest_charge;\n if (!expandedCharge(charge)) return false;\n return validCharge(charge, customerId, config);\n}\nfunction expandedCharge(value: Stripe.Charge | string | null): value is Stripe.Charge {\n return value !== null && typeof value !== 'string';\n}\nfunction validCharge(charge: Stripe.Charge, customerId: string, config: Config): boolean {\n verifyMode(charge.livemode, config);\n if (objectId(charge.customer) !== customerId) throw new Error('Charge ownership mismatch.');\n return [charge.paid, !charge.disputed, charge.amount_refunded === 0].every(Boolean);\n}\nasync function paidInvoice(stripe: Stripe, subscription: Stripe.Subscription, customerId: string, config: Config): Promise<boolean> {\n if (subscription.status === 'trialing') return true;\n const invoiceId = objectId(subscription.latest_invoice);\n if (!invoiceId) return false;\n const invoice = await stripe.invoices.retrieve(invoiceId);\n verifyMode(invoice.livemode, config);\n if (objectId(invoice.customer) !== customerId) throw new Error('Invoice ownership mismatch.');\n return invoicePayment(stripe, invoice, customerId, config);\n}\nasync function invoicePayment(stripe: Stripe, invoice: Stripe.Invoice, customerId: string, config: Config): Promise<boolean> {\n if (invoice.status !== 'paid') return false;\n if (invoice.amount_paid === 0) return true;\n const payments = await stripe.invoicePayments.list({ invoice: invoice.id, status: 'paid', limit: 100 });\n requireCompletePayments(payments);\n if (!payments.data.length) return false;\n const sound = await Promise.all(payments.data.map((payment) => soundCharge(stripe, payment, customerId, config)));\n return sound.every(Boolean);\n}\nfunction requireCompletePayments(payments: Stripe.ApiList<Stripe.InvoicePayment>): void {\n if (payments.has_more) throw new Error('Billing payment pagination requires reconciliation.');\n}\nfunction subscriptionGrants(subscription: Stripe.Subscription, config: Config): Grant[] {\n return subscription.items.data.flatMap((item): Grant[] => {\n const plan = planForPrice(item.price.id, config);\n if (!plan || item.current_period_end * 1000 <= Date.now()) return [];\n return [{ key: plan.entitlement, expiresAt: item.current_period_end * 1000, source: 'stripe' }];\n });\n}\nasync function grantsForSubscription(stripe: Stripe, subscription: Stripe.Subscription, account: Account, config: Config): Promise<Grant[]> {\n verifyMode(subscription.livemode, config);\n if (objectId(subscription.customer) !== account.stripeCustomerId) throw new Error('Subscription ownership mismatch.');\n if (!ownedActiveSubscription(subscription, account.userId)) return [];\n if (!await paidInvoice(stripe, subscription, account.stripeCustomerId!, config)) return [];\n return subscriptionGrants(subscription, config);\n}\nfunction ownedActiveSubscription(subscription: Stripe.Subscription, userId: string): boolean {\n return subscription.metadata.app_user_id === userId && activeSubscription(subscription);\n}\nasync function customerSubscriptions(stripe: Stripe, account: Account, config: Config): Promise<Stripe.Subscription[]> {\n if (!account.stripeCustomerId) return [];\n await verifyCustomer(stripe, account.stripeCustomerId, account.userId, config);\n const subscriptions = await stripe.subscriptions.list({ customer: account.stripeCustomerId, status: 'all', limit: 100 });\n if (subscriptions.has_more) throw new Error('Billing subscription pagination requires reconciliation.');\n return subscriptions.data;\n}\nexport async function stripeGrants(stripe: Stripe, account: Account, config: Config): Promise<Grant[]> {\n const subscriptions = await customerSubscriptions(stripe, account, config);\n const values = await Promise.all(subscriptions.map((subscription) => grantsForSubscription(stripe, subscription, account, config)));\n return values.flat();\n}\nfunction configuredSubscription(subscription: Stripe.Subscription, account: Account, config: Config): boolean {\n verifyMode(subscription.livemode, config);\n if (objectId(subscription.customer) !== account.stripeCustomerId) throw new Error('Subscription ownership mismatch.');\n if (['canceled', 'incomplete_expired'].includes(subscription.status)) return false;\n // A nonterminal configured subscription still needs management when its payment\n // failed or was refunded. Absence of an access grant never authorizes another sale.\n return subscription.items.data.some((item) => Boolean(planForPrice(item.price.id, config)));\n}\nasync function requireNewSubscription(stripe: Stripe, account: Account, config: Config): Promise<void> {\n const subscriptions = await customerSubscriptions(stripe, account, config);\n if (subscriptions.some((subscription) => configuredSubscription(subscription, account, config))) throw new BillingConflict('Manage the existing subscription in its billing portal.');\n}\nfunction verifyOpenSession(session: Stripe.Checkout.Session, account: Account, config: Config): string {\n verifyMode(session.livemode, config);\n if (objectId(session.customer) !== account.stripeCustomerId) throw new Error('Checkout ownership mismatch.');\n if (session.metadata?.app_user_id !== account.userId) throw new Error('Checkout identity mismatch.');\n return configuredSessionPlan(session, config);\n}\nfunction configuredSessionPlan(session: Stripe.Checkout.Session, config: Config): string {\n verifySessionKind(session);\n const plan = sessionPlanId(session);\n if (!plan) throw new Error('Checkout plan is missing.');\n if (!Object.hasOwn(config.plans, plan)) throw new Error('Unexpected checkout plan.');\n return plan;\n}\nfunction verifySessionKind(session: Stripe.Checkout.Session): void {\n if (session.mode !== 'subscription') throw new Error('Unexpected checkout mode.');\n if (session.status !== 'open') throw new Error('Unexpected checkout state.');\n}\nfunction sessionPlanId(session: Stripe.Checkout.Session): string | undefined { return session.metadata?.plan_id; }\nasync function pendingCheckout(stripe: Stripe, account: Account, planId: string, config: Config): Promise<string | undefined> {\n const sessions = await stripe.checkout.sessions.list({ customer: account.stripeCustomerId!, status: 'open', limit: 100 });\n if (sessions.has_more) throw new Error('Checkout pagination requires reconciliation.');\n const plans = sessions.data.map((session) => verifyOpenSession(session, account, config));\n if (plans.some((plan) => plan !== planId)) throw new BillingConflict('Finish the existing checkout before choosing another plan.');\n return openSessionURL(sessions.data);\n}\nfunction openSessionURL(sessions: Stripe.Checkout.Session[]): string | undefined {\n if (!sessions.length) return undefined;\n const session = sessions[0];\n verifySessionExpiration(session);\n return providerURL(requireValue(session.url ?? undefined), 'checkout.stripe.com');\n}\nfunction verifySessionExpiration(session: Stripe.Checkout.Session): void {\n if (!Number.isSafeInteger(session.expires_at)) throw new Error('Invalid checkout expiration.');\n if (session.expires_at * 1000 <= Date.now()) throw new BillingConflict('The existing checkout is expiring. Try again shortly.');\n}\nexport async function createCheckout(stripe: Stripe, account: Account, planId: string, idempotencyKey: string, store: Store, config: Config): Promise<string> {\n const plan = config.plans[planId];\n if (!plan) throw new Error('Unknown billing plan.');\n const customer = await stripeCustomer(stripe, account, store, config);\n const owner = { ...account, stripeCustomerId: customer };\n await requireNewSubscription(stripe, owner, config);\n const pending = await pendingCheckout(stripe, owner, planId, config);\n if (pending) return pending;\n const operation = await digest(account.userId + ':' + idempotencyKey);\n const result = await stripe.checkout.sessions.create({\n mode: 'subscription', customer,\n line_items: [{ price: plan.stripePriceId, quantity: 1 }],\n client_reference_id: account.userId,\n metadata: { app_user_id: account.userId, plan_id: planId },\n subscription_data: { metadata: { app_user_id: account.userId, plan_id: planId } },\n success_url: config.origin + '/billing?result=success',\n cancel_url: config.origin + '/billing?result=cancelled',\n integration_identifier: 'anhedral_' + operation.slice(0, 8).split('').map((character) => String.fromCharCode(97 + Number.parseInt(character, 16))).join(''),\n }, { idempotencyKey: 'anhedral-checkout-' + operation });\n return providerURL(requireValue(result.url ?? undefined), 'checkout.stripe.com');\n}\nfunction providerURL(value: string, hostname: string): string {\n const url = new URL(value);\n if ([url.protocol !== 'https:', url.hostname !== hostname, url.username, url.password].some(Boolean)) throw new Error('Unexpected billing provider URL.');\n return url.href;\n}\nexport async function createPortal(stripe: Stripe, account: Account, config: Config): Promise<string> {\n if (!account.stripeCustomerId) throw new Error('No web billing subscription for this account.');\n await verifyCustomer(stripe, account.stripeCustomerId, account.userId, config);\n const portal = await stripe.billingPortal.sessions.create({ customer: account.stripeCustomerId, return_url: config.origin + '/billing' });\n return providerURL(portal.url, 'billing.stripe.com');\n}\nexport async function stripeEventCustomer(stripe: Stripe, event: Stripe.Event): Promise<string | undefined> {\n const object = event.data.object as unknown as Record<string, unknown>;\n const customer = objectId(object.customer);\n if (customer) return customer;\n const charge = objectId(object.charge);\n if (!charge) return undefined;\n return objectId((await stripe.charges.retrieve(charge)).customer);\n}\n\nconst purchase = z.object({ is_sandbox: z.boolean(), store: z.string(), expires_date: z.string().nullable().optional(), grace_period_expires_date: z.string().nullable().optional() });\nconst rcSchema = z.object({ subscriber: z.object({\n entitlements: z.record(z.string(), z.object({ product_identifier: z.string(), expires_date: z.string().nullable(), grace_period_expires_date: z.string().nullable().optional() })),\n subscriptions: z.record(z.string(), purchase),\n non_subscriptions: z.record(z.string(), z.array(purchase)).optional(),\n}) });\ntype Subscriber = z.infer<typeof rcSchema>['subscriber'];\ntype Purchase = z.infer<typeof purchase>;\nfunction matchesPurchase(value: Purchase, config: Config, stripeEnabled: boolean): boolean {\n if (value.is_sandbox !== (config.environment === 'sandbox')) return false;\n return !(stripeEnabled && value.store === 'stripe');\n}\nfunction receiptForProduct(subscriber: Subscriber, productId: string, config: Config, stripeEnabled: boolean): Purchase | undefined {\n const candidates = [subscriber.subscriptions[productId], ...(subscriber.non_subscriptions?.[productId] ?? [])].filter((value): value is Purchase => Boolean(value));\n return candidates.find((value) => matchesPurchase(value, config, stripeEnabled));\n}\nfunction expires(value: string | null | undefined): number | null {\n if (value === null) return null;\n const parsed = Date.parse(value ?? '');\n if (!Number.isFinite(parsed)) throw new Error('Invalid provider entitlement expiry.');\n return parsed;\n}\nfunction revenueCatGrant(key: string, subscriber: Subscriber, config: Config, stripeEnabled: boolean): Grant[] {\n const entitlement = subscriber.entitlements[key];\n if (!entitlement) return [];\n const receipt = receiptForProduct(subscriber, entitlement.product_identifier, config, stripeEnabled);\n if (!receipt) return [];\n const expiry = entitlementExpiry(entitlement);\n if (!validExpiry(expiry)) return [];\n return [{ key, expiresAt: expiry, source: 'revenuecat' }];\n}\nfunction entitlementExpiry(entitlement: { expires_date: string | null; grace_period_expires_date?: string | null }): number | null {\n return expires(entitlement.grace_period_expires_date ?? entitlement.expires_date);\n}\nfunction validExpiry(expiry: number | null): boolean { return expiry === null || expiry > Date.now(); }\nfunction requireRevenueCatScope(config: Config): void {\n if (!config.projectId) throw new Error('Configure the RevenueCat project.');\n if (!config.appIds.length) throw new Error('Configure the RevenueCat app allowlist.');\n}\nexport async function revenueCatGrants(userId: string, env: BillingEnv, config: Config, stripeEnabled: boolean): Promise<Grant[]> {\n requireRevenueCatScope(config);\n const response = await fetch('https://api.revenuecat.com/v1/subscribers/' + encodeURIComponent(userId), {\n headers: { authorization: 'Bearer ' + requireValue(env.REVENUECAT_SECRET_KEY), accept: 'application/json' },\n signal: AbortSignal.timeout(timeout), redirect: 'error',\n });\n if (response.status === 404) return [];\n if (!response.ok) throw new Error('RevenueCat reconciliation failed.');\n const { subscriber } = rcSchema.parse(await response.json());\n return config.entitlements.flatMap((key) => revenueCatGrant(key, subscriber, config, stripeEnabled));\n}\n";
@@ -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
+ `;