anhedral 0.15.0 → 0.17.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 +82 -34
- package/assets/stack/ai-schema.ts.txt +5 -0
- package/assets/stack/ai.ts.txt +30 -0
- package/assets/stack/api-index.ts.txt +15 -0
- package/assets/stack/auth-features.ts.txt +4 -0
- package/assets/stack/auth-journal.json.txt +13 -0
- package/assets/stack/auth-migration.sql.txt +53 -0
- package/assets/stack/auth-routes.ts.txt +11 -0
- package/assets/stack/auth-schema.ts.txt +64 -0
- package/assets/stack/auth-snapshot.json.txt +346 -0
- package/assets/stack/auth.ts.txt +32 -0
- package/assets/stack/billing-mode.ts.txt +8 -0
- package/assets/stack/billing-schema.ts.txt +11 -0
- package/assets/stack/desktop.rs.txt +21 -0
- package/assets/stack/entitlement-guard.ts.txt +32 -0
- package/assets/stack/entitlements.ts.txt +8 -0
- package/assets/stack/events-schema.ts.txt +12 -0
- package/assets/stack/events.ts.txt +59 -0
- package/assets/stack/mobile-auth.ts.txt +25 -0
- package/assets/stack/mobile-billing.tsx.txt +63 -0
- package/assets/stack/mobile-session.tsx.txt +83 -0
- package/assets/stack/native-button.tsx.txt +108 -0
- package/assets/stack/native-global.css.txt +4 -0
- package/assets/stack/native-lib-utils.ts.txt +5 -0
- package/assets/stack/native-metro.config.js.txt +6 -0
- package/assets/stack/native-nativewind-env.d.ts.txt +1 -0
- package/assets/stack/native-tailwind.config.js.txt +73 -0
- package/assets/stack/native-text.tsx.txt +89 -0
- package/assets/stack/purchases.ts.txt +65 -0
- package/assets/stack/revenuecat.ts.txt +88 -0
- package/assets/stack/rtc-schema.ts.txt +10 -0
- package/assets/stack/rtc.ts.txt +122 -0
- package/assets/stack/security.ts.txt +31 -0
- package/assets/stack/storage.ts.txt +36 -0
- package/assets/stack/stripe.ts.txt +126 -0
- package/assets/stack/web-sign-in.tsx.txt +51 -0
- package/assets/ui/LICENSE.react-native-reusables +21 -0
- package/assets/ui/UPSTREAM.json +0 -11
- package/assets/ui/catalog.json +891 -0
- package/assets/ui/extensions/registry.json +6 -0
- package/dist/bin.js +7 -12
- package/dist/capabilities.d.ts +4 -33
- package/dist/capabilities.js +2 -66
- package/dist/capability-catalog.d.ts +83 -0
- package/dist/capability-catalog.js +121 -0
- package/dist/capability-command.d.ts +3 -0
- package/dist/capability-command.js +188 -0
- package/dist/capability-editor.d.ts +17 -0
- package/dist/capability-editor.js +97 -0
- package/dist/capability-recipes.d.ts +4 -0
- package/dist/capability-recipes.js +520 -0
- package/dist/capability-references.d.ts +4 -0
- package/dist/capability-references.js +7 -0
- package/dist/cli-commands.d.ts +1 -2
- package/dist/cli-commands.js +10 -104
- package/dist/cli-output.d.ts +1 -2
- package/dist/cli-output.js +6 -251
- package/dist/command-schema.js +39 -322
- package/dist/dependencies.d.ts +29 -9
- package/dist/dependencies.js +57 -64
- package/dist/index.d.ts +1 -42
- package/dist/index.js +1 -27
- package/dist/platforms/web.d.ts +1 -1
- package/dist/platforms/web.js +27 -75
- package/dist/project-config.d.ts +2 -13
- package/dist/project-config.js +10 -82
- package/dist/registry/options.js +1 -5
- package/dist/registry/resolve.d.ts +1 -1
- package/dist/registry/resolve.js +4 -10
- package/dist/registry/usage.js +3 -9
- package/dist/scaffold/backend.js +0 -3
- package/dist/scaffold/database.js +2 -1
- package/dist/scaffold/documentation.js +56 -25
- package/dist/scaffold/stack-documentation.js +1 -1
- package/dist/scaffold/storage.d.ts +2 -0
- package/dist/scaffold/storage.js +21 -0
- package/dist/scaffold/workspace.js +21 -22
- package/dist/stack-registry.d.ts +2 -10
- package/dist/stack-registry.js +12 -98
- package/dist/standard.js +1 -11
- package/dist/ui-catalog.d.ts +26 -0
- package/dist/ui-catalog.js +31 -0
- package/dist/ui-command.d.ts +3 -0
- package/dist/ui-command.js +219 -0
- package/dist/ui-project.d.ts +22 -0
- package/dist/ui-project.js +110 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/docs/anhedral-stack.md +12 -23
- package/docs/assets/anhedral-stack-light.png +0 -0
- package/docs/assets/anhedral-stack.png +0 -0
- package/docs/capabilities.md +110 -0
- package/docs/native-ui.md +47 -0
- package/docs/software-factory.md +35 -50
- package/docs/stack-standard.md +19 -70
- package/docs/ui.md +33 -0
- package/docs/verification.md +6 -876
- package/package.json +21 -16
- package/assets/ui/native/button.tsx +0 -85
- package/assets/ui/native/card.tsx +0 -33
- package/assets/ui/native/dialog.tsx +0 -75
- package/assets/ui/native/input.tsx +0 -27
- package/assets/ui/native/label.tsx +0 -4
- package/assets/ui/native/layout.tsx +0 -26
- package/assets/ui/native/text.tsx +0 -20
- package/assets/ui/native/theme-switcher.tsx +0 -22
- package/assets/ui/theme-storage.ts +0 -25
- package/assets/ui/theme.tsx +0 -66
- package/dist/access.d.ts +0 -10
- package/dist/access.js +0 -93
- package/dist/auth-schema-snapshot.d.ts +0 -346
- package/dist/auth-schema-snapshot.js +0 -347
- package/dist/auth-schema.d.ts +0 -1
- package/dist/auth-schema.js +0 -57
- package/dist/capability-contract.d.ts +0 -47
- package/dist/capability-contract.js +0 -129
- package/dist/catalog-model.d.ts +0 -24
- package/dist/catalog-model.js +0 -1
- package/dist/catalog-registration.d.ts +0 -16
- package/dist/catalog-registration.js +0 -22
- package/dist/catalog-snapshot.d.ts +0 -5
- package/dist/catalog-snapshot.js +0 -97
- package/dist/cli-delivery.d.ts +0 -3
- package/dist/cli-delivery.js +0 -112
- package/dist/cloudflare.d.ts +0 -25
- package/dist/cloudflare.js +0 -226
- package/dist/delivery-evidence.d.ts +0 -62
- package/dist/delivery-evidence.js +0 -157
- package/dist/delivery.d.ts +0 -82
- package/dist/delivery.js +0 -489
- package/dist/inspector-model.d.ts +0 -123
- package/dist/inspector-model.js +0 -1
- package/dist/integration-service-readers.d.ts +0 -12
- package/dist/integration-service-readers.js +0 -92
- package/dist/lifecycle-model.d.ts +0 -15
- package/dist/lifecycle-model.js +0 -20
- package/dist/lifecycle.d.ts +0 -11
- package/dist/lifecycle.js +0 -91
- package/dist/management.d.ts +0 -3
- package/dist/management.js +0 -47
- package/dist/mobile-delivery.d.ts +0 -77
- package/dist/mobile-delivery.js +0 -370
- package/dist/platforms/mobile.d.ts +0 -2
- package/dist/platforms/mobile.js +0 -156
- package/dist/project-catalog.d.ts +0 -41
- package/dist/project-catalog.js +0 -288
- package/dist/project-inspector.d.ts +0 -4
- package/dist/project-inspector.js +0 -671
- package/dist/project-lifecycle.d.ts +0 -25
- package/dist/project-lifecycle.js +0 -57
- package/dist/project-state.d.ts +0 -47
- package/dist/project-state.js +0 -480
- package/dist/provider-auth.d.ts +0 -41
- package/dist/provider-auth.js +0 -180
- package/dist/provider-readiness.d.ts +0 -30
- package/dist/provider-readiness.js +0 -85
- package/dist/providers/adapters.d.ts +0 -17
- package/dist/providers/adapters.js +0 -103
- package/dist/providers/api.d.ts +0 -29
- package/dist/providers/api.js +0 -253
- package/dist/providers/config.d.ts +0 -15
- package/dist/providers/config.js +0 -136
- package/dist/providers/definitions.d.ts +0 -115
- package/dist/providers/definitions.js +0 -42
- package/dist/providers/provision.d.ts +0 -24
- package/dist/providers/provision.js +0 -76
- package/dist/providers/receipts.d.ts +0 -20
- package/dist/providers/receipts.js +0 -56
- package/dist/providers/recovery-verification.d.ts +0 -7
- package/dist/providers/recovery-verification.js +0 -52
- package/dist/providers/recovery.d.ts +0 -30
- package/dist/providers/recovery.js +0 -34
- package/dist/providers/runtime.d.ts +0 -10
- package/dist/providers/runtime.js +0 -234
- package/dist/providers/schema.d.ts +0 -28
- package/dist/providers/schema.js +0 -49
- package/dist/providers/state.d.ts +0 -55
- package/dist/providers/state.js +0 -283
- package/dist/provision.d.ts +0 -47
- package/dist/provision.js +0 -208
- package/dist/r2-service-data.d.ts +0 -2
- package/dist/r2-service-data.js +0 -136
- package/dist/readiness.d.ts +0 -23
- package/dist/readiness.js +0 -117
- package/dist/registry/add.d.ts +0 -24
- package/dist/registry/add.js +0 -210
- package/dist/registry/bootstrap.d.ts +0 -3
- package/dist/registry/bootstrap.js +0 -5
- package/dist/registry/commands.d.ts +0 -3
- package/dist/registry/commands.js +0 -83
- package/dist/registry/preview.d.ts +0 -11
- package/dist/registry/preview.js +0 -91
- package/dist/registry/receipt.d.ts +0 -3
- package/dist/registry/receipt.js +0 -68
- package/dist/repository.d.ts +0 -24
- package/dist/repository.js +0 -96
- package/dist/scaffold/auth.d.ts +0 -2
- package/dist/scaffold/auth.js +0 -76
- package/dist/scaffold/billing-config.d.ts +0 -1
- package/dist/scaffold/billing-config.js +0 -73
- package/dist/scaffold/billing-contracts.d.ts +0 -2
- package/dist/scaffold/billing-contracts.js +0 -48
- package/dist/scaffold/billing-providers.d.ts +0 -1
- package/dist/scaffold/billing-providers.js +0 -249
- package/dist/scaffold/billing-schema.d.ts +0 -1
- package/dist/scaffold/billing-schema.js +0 -34
- package/dist/scaffold/billing-security.d.ts +0 -1
- package/dist/scaffold/billing-security.js +0 -46
- package/dist/scaffold/billing-server.d.ts +0 -1
- package/dist/scaffold/billing-server.js +0 -139
- package/dist/scaffold/billing-store.d.ts +0 -1
- package/dist/scaffold/billing-store.js +0 -72
- package/dist/scaffold/billing.d.ts +0 -2
- package/dist/scaffold/billing.js +0 -208
- package/dist/scaffold/expo-auth.d.ts +0 -3
- package/dist/scaffold/expo-auth.js +0 -203
- package/dist/scaffold/expo-billing.d.ts +0 -3
- package/dist/scaffold/expo-billing.js +0 -257
- package/dist/scaffold/expo-runtime.d.ts +0 -3
- package/dist/scaffold/expo-runtime.js +0 -43
- package/dist/scaffold/integrations.d.ts +0 -2
- package/dist/scaffold/integrations.js +0 -11
- package/dist/scaffold/managed-email.d.ts +0 -3
- package/dist/scaffold/managed-email.js +0 -47
- package/dist/scaffold/native-ui.d.ts +0 -2
- package/dist/scaffold/native-ui.js +0 -69
- package/dist/scaffold/password-reset.d.ts +0 -1
- package/dist/scaffold/password-reset.js +0 -99
- package/dist/scaffold/private-files.d.ts +0 -2
- package/dist/scaffold/private-files.js +0 -78
- package/dist/scaffold/web-billing.d.ts +0 -2
- package/dist/scaffold/web-billing.js +0 -48
- package/dist/service-deletion.d.ts +0 -29
- package/dist/service-deletion.js +0 -195
- package/dist/service-descriptor.d.ts +0 -10
- package/dist/service-descriptor.js +0 -71
- package/dist/service-model.d.ts +0 -49
- package/dist/service-model.js +0 -8
- package/dist/service-operations.d.ts +0 -29
- package/dist/service-operations.js +0 -48
- package/dist/service-readers.d.ts +0 -8
- package/dist/service-readers.js +0 -216
- package/dist/services-command.d.ts +0 -39
- package/dist/services-command.js +0 -96
- package/dist/ship.d.ts +0 -35
- package/dist/ship.js +0 -107
package/dist/scaffold/billing.js
DELETED
|
@@ -1,208 +0,0 @@
|
|
|
1
|
-
import { readFileSync } from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
4
|
-
import { scaffoldBillingContracts } from './billing-contracts.js';
|
|
5
|
-
import { scaffoldWebBilling } from './web-billing.js';
|
|
6
|
-
import { scaffoldExpoBilling } from './expo-billing.js';
|
|
7
|
-
import { scaffoldBillingSchema } from './billing-schema.js';
|
|
8
|
-
import { BILLING_CONFIG } from './billing-config.js';
|
|
9
|
-
import { BILLING_SECURITY } from './billing-security.js';
|
|
10
|
-
import { BILLING_STORE } from './billing-store.js';
|
|
11
|
-
import { BILLING_PROVIDERS } from './billing-providers.js';
|
|
12
|
-
import { BILLING_SERVER } from './billing-server.js';
|
|
13
|
-
import { writeEnvironmentFile } from './environment.js';
|
|
14
|
-
import { json, patchPackage, put, readJson, sharedPackage } from './files.js';
|
|
15
|
-
function applicationBilling(context) {
|
|
16
|
-
const { has } = context;
|
|
17
|
-
const database = 'env.DB';
|
|
18
|
-
const authenticate = `const session = await createAuth(createDatabase(env.DB), env.BETTER_AUTH_SECRET, env.BETTER_AUTH_URL, env).api.getSession({ headers: request.headers });
|
|
19
|
-
if (!session) throw new BillingError(401, 'Sign in to access billing.');
|
|
20
|
-
return session.user.id;`;
|
|
21
|
-
return `import { Hono, type Context } from 'hono';
|
|
22
|
-
import { z } from 'zod';
|
|
23
|
-
import { createDatabase } from '@workspace/db';
|
|
24
|
-
import { createAuth } from '@workspace/auth';
|
|
25
|
-
import { createBilling, BillingError, type Billing } from '@workspace/billing/server';
|
|
26
|
-
|
|
27
|
-
type BillingContext = Context<{ Bindings: Env }>;
|
|
28
|
-
function billing(env: Env): Billing {
|
|
29
|
-
return createBilling({ database: createDatabase(${database}), env, stripeEnabled: ${has('stripe')}, revenueCatEnabled: ${has('revenuecat')} });
|
|
30
|
-
}
|
|
31
|
-
async function subject(request: Request, env: Env): Promise<string> {
|
|
32
|
-
${authenticate}
|
|
33
|
-
}
|
|
34
|
-
function originAllowed(request: Request, env: Env): void {
|
|
35
|
-
if (!trustedOrigin(request, env)) throw new BillingError(403, 'Unexpected billing request origin.');
|
|
36
|
-
if (request.headers.get('sec-fetch-site') === 'cross-site') throw new BillingError(403, 'Cross-site billing requests are denied.');
|
|
37
|
-
if (!jsonRequest(request)) throw new BillingError(400, 'A JSON request is required.');
|
|
38
|
-
}
|
|
39
|
-
function jsonRequest(request: Request): boolean {
|
|
40
|
-
const contentType = request.headers.get('content-type') ?? '';
|
|
41
|
-
return contentType.split(';')[0].trim() === 'application/json';
|
|
42
|
-
}
|
|
43
|
-
function trustedOrigin(request: Request, env: Env): boolean {
|
|
44
|
-
const origin = request.headers.get('origin');
|
|
45
|
-
return !origin || origin === new URL(env.BILLING_ORIGIN).origin;
|
|
46
|
-
}
|
|
47
|
-
function handle(action: (context: BillingContext) => Promise<unknown>) {
|
|
48
|
-
return async (context: BillingContext) => {
|
|
49
|
-
context.header('cache-control', 'private, no-store');
|
|
50
|
-
try { return context.body(JSON.stringify(await action(context)), 200, { 'content-type': 'application/json' }); }
|
|
51
|
-
catch (error) {
|
|
52
|
-
if (error instanceof BillingError) return context.json({ error: error.message }, error.status);
|
|
53
|
-
if (error instanceof z.ZodError) return context.json({ error: 'Invalid billing request or configuration.' }, 400);
|
|
54
|
-
return context.json({ error: 'Billing is temporarily unavailable.' }, 503);
|
|
55
|
-
}
|
|
56
|
-
};
|
|
57
|
-
}
|
|
58
|
-
async function signedIn(context: BillingContext) {
|
|
59
|
-
const userId = await subject(context.req.raw, context.env);
|
|
60
|
-
return { userId, service: billing(context.env) };
|
|
61
|
-
}
|
|
62
|
-
async function mutation(context: BillingContext) {
|
|
63
|
-
originAllowed(context.req.raw, context.env);
|
|
64
|
-
return signedIn(context);
|
|
65
|
-
}
|
|
66
|
-
export const billingRoutes = new Hono<{ Bindings: Env }>();
|
|
67
|
-
billingRoutes.get('/billing/identity', handle(async (context) => {
|
|
68
|
-
const { service, userId } = await signedIn(context);
|
|
69
|
-
return service.identity(userId);
|
|
70
|
-
}));
|
|
71
|
-
billingRoutes.get('/billing/entitlements', handle(async (context) => {
|
|
72
|
-
const { service, userId } = await signedIn(context);
|
|
73
|
-
return service.entitlements(userId);
|
|
74
|
-
}));
|
|
75
|
-
billingRoutes.post('/billing/refresh', handle(async (context) => {
|
|
76
|
-
const { service, userId } = await mutation(context);
|
|
77
|
-
z.object({}).strict().parse(await context.req.json());
|
|
78
|
-
return service.entitlements(userId, true);
|
|
79
|
-
}));
|
|
80
|
-
billingRoutes.post('/billing/checkout', handle(async (context) => {
|
|
81
|
-
const { service, userId } = await mutation(context);
|
|
82
|
-
const { plan } = z.object({ plan: z.string().min(1).max(100) }).strict().parse(await context.req.json());
|
|
83
|
-
return service.checkout(userId, plan, context.req.header('idempotency-key') ?? '');
|
|
84
|
-
}));
|
|
85
|
-
billingRoutes.post('/billing/portal', handle(async (context) => {
|
|
86
|
-
const { service, userId } = await mutation(context);
|
|
87
|
-
z.object({}).strict().parse(await context.req.json());
|
|
88
|
-
return service.portal(userId);
|
|
89
|
-
}));
|
|
90
|
-
billingRoutes.get('/billing/premium', handle(async (context) => {
|
|
91
|
-
const { service, userId } = await signedIn(context);
|
|
92
|
-
await service.assertEntitled(userId, service.config.demoEntitlement);
|
|
93
|
-
return { ok: true, entitlement: service.config.demoEntitlement };
|
|
94
|
-
}));
|
|
95
|
-
billingRoutes.post('/webhooks/stripe', handle(async (context) => {
|
|
96
|
-
await billing(context.env).stripeWebhook(await context.req.text(), context.req.raw.headers);
|
|
97
|
-
return { received: true };
|
|
98
|
-
}));
|
|
99
|
-
billingRoutes.post('/webhooks/revenuecat', handle(async (context) => {
|
|
100
|
-
await billing(context.env).revenueCatWebhook(await context.req.text(), context.req.raw.headers);
|
|
101
|
-
return { received: true };
|
|
102
|
-
}));
|
|
103
|
-
export async function drainBilling(env: Env): Promise<void> {
|
|
104
|
-
try { await billing(env).drainPending(); }
|
|
105
|
-
catch { /* Missing configuration or provider outage grants nothing; inbox stays durable. */ }
|
|
106
|
-
}
|
|
107
|
-
`;
|
|
108
|
-
}
|
|
109
|
-
function connectApi(context) {
|
|
110
|
-
const { root } = context;
|
|
111
|
-
put(root, 'apps/api/src/billing.ts', applicationBilling(context));
|
|
112
|
-
put(root, 'apps/api/src/billing-env.d.ts', `import type { BillingEnv } from '@workspace/billing/config';
|
|
113
|
-
// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Merge billing bindings with Wrangler's generated Env.
|
|
114
|
-
declare global { interface Env extends BillingEnv {} }
|
|
115
|
-
export {};
|
|
116
|
-
`);
|
|
117
|
-
patchPackage(root, 'apps/api/package.json', {
|
|
118
|
-
dependencies: { '@workspace/billing': 'workspace:*', zod: STACK_DEPENDENCIES.zod },
|
|
119
|
-
});
|
|
120
|
-
const file = 'apps/api/src/index.ts';
|
|
121
|
-
const source = readFileSync(path.join(root, file), 'utf8');
|
|
122
|
-
if (!source.includes('import { billingRoutes, drainBilling }'))
|
|
123
|
-
put(root, file, "import { billingRoutes, drainBilling } from './billing';\n" +
|
|
124
|
-
source.replace('export default app;', `app.route('/api', billingRoutes);
|
|
125
|
-
// Retry a bounded batch of durable webhook records independently of client activity.
|
|
126
|
-
export default {
|
|
127
|
-
fetch: app.fetch,
|
|
128
|
-
scheduled(_event: ScheduledController, env: Env, context: ExecutionContext) {
|
|
129
|
-
context.waitUntil(drainBilling(env));
|
|
130
|
-
},
|
|
131
|
-
};`));
|
|
132
|
-
const configuration = 'apps/api/wrangler.jsonc';
|
|
133
|
-
const config = readJson(root, configuration);
|
|
134
|
-
const triggers = (config.triggers ?? {});
|
|
135
|
-
config.triggers = {
|
|
136
|
-
...triggers,
|
|
137
|
-
crons: [...new Set([...(triggers.crons ?? []), '*/5 * * * *'])],
|
|
138
|
-
};
|
|
139
|
-
json(root, configuration, config);
|
|
140
|
-
}
|
|
141
|
-
export function scaffoldBilling(context) {
|
|
142
|
-
const { root, has } = context;
|
|
143
|
-
if (!has('hono'))
|
|
144
|
-
throw new Error('Billing requires the shared Hono runtime.');
|
|
145
|
-
if (!has('d1'))
|
|
146
|
-
throw new Error('Billing requires the core D1 database.');
|
|
147
|
-
scaffoldBillingContracts(root);
|
|
148
|
-
scaffoldBillingSchema(root);
|
|
149
|
-
sharedPackage(root, 'billing', "export { createBilling, BillingError } from './server';\n", {
|
|
150
|
-
'@workspace/contracts': 'workspace:*',
|
|
151
|
-
'@workspace/db': 'workspace:*',
|
|
152
|
-
stripe: STACK_DEPENDENCIES.stripe,
|
|
153
|
-
zod: STACK_DEPENDENCIES.zod,
|
|
154
|
-
'drizzle-orm': STACK_DEPENDENCIES['drizzle-orm'],
|
|
155
|
-
});
|
|
156
|
-
patchPackage(root, 'packages/billing/package.json', {
|
|
157
|
-
exports: {
|
|
158
|
-
'.': './src/index.ts',
|
|
159
|
-
'./server': './src/server.ts',
|
|
160
|
-
'./config': './src/config.ts',
|
|
161
|
-
},
|
|
162
|
-
});
|
|
163
|
-
for (const [name, source] of Object.entries({
|
|
164
|
-
config: BILLING_CONFIG,
|
|
165
|
-
security: BILLING_SECURITY,
|
|
166
|
-
store: BILLING_STORE,
|
|
167
|
-
providers: BILLING_PROVIDERS,
|
|
168
|
-
server: BILLING_SERVER,
|
|
169
|
-
}))
|
|
170
|
-
put(root, `packages/billing/src/${name}.ts`, source);
|
|
171
|
-
connectApi(context);
|
|
172
|
-
writeEnvironmentFile(root, 'apps/api/.dev.vars.example', {
|
|
173
|
-
BILLING_ORIGIN: '',
|
|
174
|
-
BILLING_ENVIRONMENT: 'sandbox',
|
|
175
|
-
BILLING_PLANS_JSON: '{}',
|
|
176
|
-
BILLING_ENTITLEMENTS_JSON: '["premium"]',
|
|
177
|
-
BILLING_PREMIUM_ENTITLEMENT: 'premium',
|
|
178
|
-
...(has('stripe') ? { STRIPE_SECRET_KEY: '', STRIPE_WEBHOOK_SECRET: '' } : {}),
|
|
179
|
-
...(has('revenuecat')
|
|
180
|
-
? {
|
|
181
|
-
REVENUECAT_SECRET_KEY: '',
|
|
182
|
-
REVENUECAT_WEBHOOK_AUTHORIZATION: '',
|
|
183
|
-
REVENUECAT_WEBHOOK_SIGNING_SECRET: '',
|
|
184
|
-
REVENUECAT_APP_IDS_JSON: '[]',
|
|
185
|
-
REVENUECAT_PROJECT_ID: '',
|
|
186
|
-
}
|
|
187
|
-
: {}),
|
|
188
|
-
});
|
|
189
|
-
scaffoldExpoBilling(context);
|
|
190
|
-
scaffoldWebBilling(context);
|
|
191
|
-
put(root, 'packages/billing/README.md', BILLING_README);
|
|
192
|
-
}
|
|
193
|
-
const BILLING_README = `# Shared billing
|
|
194
|
-
|
|
195
|
-
Hono owns authenticated Checkout, customer portal and entitlement decisions. Clients use the public contracts and never select a user/customer ID, raw Stripe price or return URL. Stripe web subscriptions and RevenueCat native subscriptions are independent provider projections; Hono unions their allowed entitlements. When both are enabled, RevenueCat Stripe receipts do not grant access, preventing stale Stripe mirrors from restoring a revoked web grant. Web purchases are not automatically imported into RevenueCat. Native clients query Hono for unified product access.
|
|
196
|
-
|
|
197
|
-
Generate and review SQL from packages/db/src/billing-schema.ts with pnpm db:generate, then migrate the selected development database explicitly. Builds and checks never migrate configured data. Billing accounts intentionally do not foreign-key a provider-specific user table. Use the verified auth subject as RevenueCat appUserID everywhere; identify through /api/billing/identity before purchasing. Account changes must switch RevenueCat identity and clear client entitlement state. Unknown webhook users are ignored; email never links accounts.
|
|
198
|
-
|
|
199
|
-
Set BILLING_ORIGIN to the exact product origin. HTTPS is required in production; sandbox development also permits HTTP on localhost, 127.0.0.1 or [::1] only. LAN HTTP is denied; physical devices require a reachable HTTPS origin. BILLING_PLANS_JSON maps a public plan ID to {label,stripePriceId,entitlement}; BILLING_ENTITLEMENTS_JSON lists allowed entitlement keys. Example: {"monthly":{"label":"Monthly","stripePriceId":"price_example","entitlement":"premium"}}. Return paths are /billing?result=success and /billing?result=cancelled; portal returns /billing. Configure the Stripe Customer Portal and required Stripe webhook event types from src/security.ts. POST Checkout requires a UUID Idempotency-Key; preserve the same UUID for retries of one intent. Under the account lease, an existing open checkout for the same configured plan is reused even for a distinct intent UUID. Another pending configured plan returns HTTP 409: finish that checkout before choosing another plan, or have the owner expire it in Stripe. Sessions use Stripe's default expiration; no retry-dependent expires_at parameter is sent. Nonterminal configured subscriptions, including payment failures and refunded active subscriptions, must be managed in the portal and cannot start a duplicate subscription. No access is granted by the return URL. Successful active or trial subscriptions grant until the verified item period ends; past_due is denied. Paid invoices with partial/full refunds or disputes deny web access. This conservative policy excludes out-of-band positive-value invoices without verified payment-intent charges.
|
|
200
|
-
|
|
201
|
-
Select BILLING_ENVIRONMENT explicitly for the intended sandbox/production backend. Keep Stripe test/live keys and webhook signing secrets isolated. Configure a dedicated RevenueCat project and allowed app IDs using REVENUECAT_PROJECT_ID and REVENUECAT_APP_IDS_JSON. RevenueCat webhook payloads normally omit project_id: the dedicated server API key and project-scoped webhook integration establish that boundary; a present mismatching project_id is rejected. REVENUECAT_SECRET_KEY is a server API v1 key, distinct from CLI management credentials. Require the configured Authorization header and enable HMAC signing with REVENUECAT_WEBHOOK_SIGNING_SECRET when available. Production never honors sandbox receipts, even when client keys or webhook payloads claim otherwise. Use separate RevenueCat projects for staging and production.
|
|
202
|
-
|
|
203
|
-
Webhook metadata is durably inserted before processing, with a unique provider/environment/event ID. Retries reconcile canonical provider state rather than replaying entitlement deltas. Per-account leases fence stale concurrent writes. Cached access lasts at most sixty seconds and never past a grant's expiry; an outage after that window fails closed. Failed records remain pending; the API's five-minute scheduled handler retries at most ten records per invocation. Inspect pending state/attempts operationally and repair configuration/provider access before retries. Code rollback does not reverse billing events or database migrations. Prune completed event records only under a reviewed retention policy long enough for provider replay windows.
|
|
204
|
-
|
|
205
|
-
GET /api/billing/premium demonstrates server enforcement through assertEntitled. It is a product example, not a substitute for placing guards on every actual paid operation. Review cross-account restore/transfer behavior and reconcile both source/destination accounts. Public SDK CustomerInfo is display state, never a server authorization claim. Digital consumables/credit balances, metered billing, tax registrations, refunds initiation and store publication are outside this subscription foundation.
|
|
206
|
-
|
|
207
|
-
Validate signup/session isolation, purchase/restore, renewal, failed payment, refund/dispute, cancellation versus expiry, duplicate/out-of-order webhooks, concurrent refresh, cross-user denial, environment isolation, invalid signatures and provider outage recovery. Local mocks/builds do not establish store purchases, configured provider acceptance or production billing. No services or payments are activated during generation.
|
|
208
|
-
`;
|
|
@@ -1,203 +0,0 @@
|
|
|
1
|
-
import { readFileSync } from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
4
|
-
import { jsString } from '../render.js';
|
|
5
|
-
import { json, patchPackage, put, readJson } from './files.js';
|
|
6
|
-
export function expoAuthScheme(root) {
|
|
7
|
-
const config = readJson(root, 'apps/mobile/app.json');
|
|
8
|
-
const scheme = config.expo?.scheme;
|
|
9
|
-
if (typeof scheme !== 'string' || !/^[a-z][a-z0-9+.-]*$/i.test(scheme))
|
|
10
|
-
throw new Error('Expo authentication requires one explicit valid app.json URL scheme.');
|
|
11
|
-
return scheme;
|
|
12
|
-
}
|
|
13
|
-
/** Platform resolution keeps SecureStore and the native plugin out of the browser bundle. */
|
|
14
|
-
export function scaffoldExpoAuth(root, scheme, linkHome = true) {
|
|
15
|
-
const directory = 'apps/mobile';
|
|
16
|
-
patchPackage(root, `${directory}/package.json`, {
|
|
17
|
-
dependencies: {
|
|
18
|
-
'better-auth': STACK_DEPENDENCIES['better-auth'],
|
|
19
|
-
'@better-auth/expo': STACK_DEPENDENCIES['@better-auth/expo'],
|
|
20
|
-
'expo-secure-store': STACK_DEPENDENCIES['expo-secure-store'],
|
|
21
|
-
'expo-network': STACK_DEPENDENCIES['expo-network'],
|
|
22
|
-
},
|
|
23
|
-
});
|
|
24
|
-
const config = readJson(root, `${directory}/app.json`);
|
|
25
|
-
const expo = config.expo;
|
|
26
|
-
const plugins = expo.plugins ?? [];
|
|
27
|
-
if (!plugins.some((plugin) => (Array.isArray(plugin) ? plugin[0] : plugin) === 'expo-secure-store'))
|
|
28
|
-
expo.plugins = [...plugins, 'expo-secure-store'];
|
|
29
|
-
json(root, `${directory}/app.json`, config);
|
|
30
|
-
put(root, `${directory}/lib/auth-client.ts`, `export { getAuthClient, authConfigurationError } from './auth-client.native';\n`);
|
|
31
|
-
put(root, `${directory}/lib/auth-client.native.ts`, `import { createAuthClient } from 'better-auth/react';
|
|
32
|
-
import { expoClient } from '@better-auth/expo/client';
|
|
33
|
-
import * as SecureStore from 'expo-secure-store';
|
|
34
|
-
import { nativeApiOrigin } from './api-client';
|
|
35
|
-
|
|
36
|
-
export function authConfigurationError(): string | null {
|
|
37
|
-
try { nativeApiOrigin(); return null; }
|
|
38
|
-
catch (error) { return error instanceof Error ? error.message : 'Invalid product API origin.'; }
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
function createNativeClient() {
|
|
42
|
-
return createAuthClient({
|
|
43
|
-
baseURL: nativeApiOrigin(),
|
|
44
|
-
plugins: [expoClient({ scheme: ${jsString(scheme)}, storagePrefix: ${jsString(scheme)}, storage: SecureStore })],
|
|
45
|
-
});
|
|
46
|
-
}
|
|
47
|
-
let client: ReturnType<typeof createNativeClient> | undefined;
|
|
48
|
-
export function getAuthClient() { return client ??= createNativeClient(); }
|
|
49
|
-
`);
|
|
50
|
-
put(root, `${directory}/lib/session-api.ts`, `export { sessionApi } from './session-api.native';\n`);
|
|
51
|
-
put(root, `${directory}/lib/session-api.native.ts`, `import { createApplicationApiClient } from './api-client';
|
|
52
|
-
import { getAuthClient } from './auth-client.native';
|
|
53
|
-
|
|
54
|
-
export const sessionApi = createApplicationApiClient({ headers: async () => {
|
|
55
|
-
const cookie = await getAuthClient().getCookie();
|
|
56
|
-
const headers = new Headers();
|
|
57
|
-
if (cookie) headers.set('cookie', cookie);
|
|
58
|
-
return headers;
|
|
59
|
-
} });
|
|
60
|
-
`);
|
|
61
|
-
put(root, `${directory}/components/auth-configuration.tsx`, `import { Text, Screen } from '@workspace/native-ui';
|
|
62
|
-
import { authConfigurationError } from '@/lib/auth-client';
|
|
63
|
-
|
|
64
|
-
export function AuthConfiguration({ children }: { children: React.ReactNode }) {
|
|
65
|
-
const error = authConfigurationError();
|
|
66
|
-
if (error) return <Screen><Text accessibilityRole="header">Configure the product API</Text><Text selectable>{error}</Text></Screen>;
|
|
67
|
-
return <>{children}</>;
|
|
68
|
-
}
|
|
69
|
-
`);
|
|
70
|
-
put(root, `${directory}/app/sign-in.tsx`, `import { useState } from 'react';
|
|
71
|
-
import { Link, router } from 'expo-router';
|
|
72
|
-
import * as Linking from 'expo-linking';
|
|
73
|
-
import { Screen, Text, Input as TextInput } from '@workspace/native-ui';
|
|
74
|
-
import { Button } from '@/components/ui/button';
|
|
75
|
-
import { AuthConfiguration } from '@/components/auth-configuration';
|
|
76
|
-
import { getAuthClient } from '@/lib/auth-client';
|
|
77
|
-
import { sessionApi } from '@/lib/session-api';
|
|
78
|
-
|
|
79
|
-
export default function SignInRoute() { return <AuthConfiguration><SignIn /></AuthConfiguration>; }
|
|
80
|
-
|
|
81
|
-
function verificationPending(create: boolean, signedIn: boolean): boolean { return create && !signedIn; }
|
|
82
|
-
function modeLabel(create: boolean): string { return create ? 'Create account' : 'Sign in'; }
|
|
83
|
-
function submitLabel(pending: boolean, create: boolean): string { return pending ? 'Working…' : modeLabel(create); }
|
|
84
|
-
function switchLabel(create: boolean): string { return create ? 'Use an existing account' : 'Create an account'; }
|
|
85
|
-
function authenticationError(error: unknown): string {
|
|
86
|
-
return error instanceof Error ? error.message : 'Unable to verify the session. Check the connection and try again.';
|
|
87
|
-
}
|
|
88
|
-
async function authenticate(values: { create: boolean; name: string; email: string; password: string }) {
|
|
89
|
-
const auth = getAuthClient();
|
|
90
|
-
const result = values.create ? await auth.signUp.email({ ...values, callbackURL: Linking.createURL('sign-in') }) : await auth.signIn.email(values);
|
|
91
|
-
if (result.error) throw new Error('Sign in failed. Verify your email or check your details.');
|
|
92
|
-
return Boolean(result.data?.token);
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
function SignIn() {
|
|
96
|
-
const { refetch } = getAuthClient().useSession();
|
|
97
|
-
const [create, setCreate] = useState(false);
|
|
98
|
-
const [name, setName] = useState('');
|
|
99
|
-
const [email, setEmail] = useState('');
|
|
100
|
-
const [password, setPassword] = useState('');
|
|
101
|
-
const [pending, setPending] = useState(false);
|
|
102
|
-
const [message, setMessage] = useState('');
|
|
103
|
-
async function submit() {
|
|
104
|
-
if (pending) return;
|
|
105
|
-
setPending(true); setMessage('');
|
|
106
|
-
try {
|
|
107
|
-
const signedIn = await authenticate({ create, name, email, password });
|
|
108
|
-
if (verificationPending(create, signedIn)) { setPassword(''); setMessage('Check your email to verify your account, then sign in.'); setCreate(false); return; }
|
|
109
|
-
await sessionApi.session();
|
|
110
|
-
await refetch();
|
|
111
|
-
setPassword('');
|
|
112
|
-
router.replace('/account');
|
|
113
|
-
} catch (error) { setMessage(authenticationError(error)); }
|
|
114
|
-
finally { setPending(false); }
|
|
115
|
-
}
|
|
116
|
-
async function resend() {
|
|
117
|
-
if (pending) return; setPending(true); setMessage('');
|
|
118
|
-
try {
|
|
119
|
-
const result = await getAuthClient().sendVerificationEmail({ email, callbackURL: Linking.createURL('sign-in') });
|
|
120
|
-
if (result.error) throw Error('Verification unavailable');
|
|
121
|
-
setMessage('If verification is needed, check your email for the link.');
|
|
122
|
-
} catch { setMessage('Unable to request verification. Please retry.'); }
|
|
123
|
-
finally { setPending(false); }
|
|
124
|
-
}
|
|
125
|
-
return <Screen>
|
|
126
|
-
<Text accessibilityRole="header">{modeLabel(create)}</Text>
|
|
127
|
-
{create && <TextInput accessibilityLabel="Name" placeholder="Name" value={name} onChangeText={setName} autoComplete="name" />}
|
|
128
|
-
<TextInput accessibilityLabel="Email" placeholder="Email" value={email} onChangeText={setEmail} keyboardType="email-address" autoCapitalize="none" autoComplete="email" />
|
|
129
|
-
<TextInput accessibilityLabel="Password" placeholder="Password" value={password} onChangeText={setPassword} secureTextEntry autoComplete={create ? 'new-password' : 'current-password'} />
|
|
130
|
-
<Button disabled={pending} onPress={() => void submit()}>{submitLabel(pending, create)}</Button>
|
|
131
|
-
<Text accessibilityLiveRegion="polite">{message}</Text>
|
|
132
|
-
<Link href="/reset-password">Forgot your password?</Link>
|
|
133
|
-
<Button disabled={pending || !email} onPress={() => void resend()}>Resend verification email</Button>
|
|
134
|
-
<Button disabled={pending} onPress={() => { setCreate(!create); setMessage(''); }}>{switchLabel(create)}</Button>
|
|
135
|
-
</Screen>;
|
|
136
|
-
}
|
|
137
|
-
`);
|
|
138
|
-
put(root, `${directory}/app/account.tsx`, `import { useEffect, useState } from 'react';
|
|
139
|
-
import { Link, Redirect, router } from 'expo-router';
|
|
140
|
-
import { Text, Screen } from '@workspace/native-ui';
|
|
141
|
-
import type { Session } from '@workspace/contracts';
|
|
142
|
-
import { Button } from '@/components/ui/button';
|
|
143
|
-
import { AuthConfiguration } from '@/components/auth-configuration';
|
|
144
|
-
import { getAuthClient } from '@/lib/auth-client';
|
|
145
|
-
import { sessionApi } from '@/lib/session-api';
|
|
146
|
-
|
|
147
|
-
export default function AccountRoute() { return <AuthConfiguration><Account /></AuthConfiguration>; }
|
|
148
|
-
|
|
149
|
-
function Account() {
|
|
150
|
-
const { data: session, isPending, refetch } = getAuthClient().useSession();
|
|
151
|
-
const userId = session?.user.id;
|
|
152
|
-
const [verified, setVerified] = useState<Session['user'] | null>(null);
|
|
153
|
-
const [message, setMessage] = useState('');
|
|
154
|
-
const [pending, setPending] = useState(false);
|
|
155
|
-
useEffect(() => {
|
|
156
|
-
let active = true;
|
|
157
|
-
if (userId) void sessionApi.session().then(
|
|
158
|
-
(current) => { if (active) { setVerified(current.user); setMessage(''); } },
|
|
159
|
-
() => { if (active) { setVerified(null); setMessage('The server could not verify this session. Sign in again or retry when connected.'); } },
|
|
160
|
-
);
|
|
161
|
-
return () => { active = false; };
|
|
162
|
-
}, [userId]);
|
|
163
|
-
async function signOut() {
|
|
164
|
-
setVerified(null); setPending(true); setMessage('');
|
|
165
|
-
try {
|
|
166
|
-
const result = await getAuthClient().signOut();
|
|
167
|
-
if (result.error) { setMessage(result.error.message ?? 'Sign out failed.'); return; }
|
|
168
|
-
await refetch(); router.replace('/sign-in');
|
|
169
|
-
} catch { setMessage('Unable to sign out. Check the connection and retry.'); }
|
|
170
|
-
finally { setPending(false); }
|
|
171
|
-
}
|
|
172
|
-
if (isPending) return <Screen><Text>Restoring session…</Text></Screen>;
|
|
173
|
-
if (!session) return <Redirect href="/sign-in" />;
|
|
174
|
-
return <AccountContent userId={session.user.id} verified={verified} message={message} pending={pending} signOut={signOut} />;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
function accountMessage(userId: string, verified: Session['user'] | null, message: string): string {
|
|
178
|
-
if (verified?.id === userId) return verified.email;
|
|
179
|
-
return message || 'Verifying with the API…';
|
|
180
|
-
}
|
|
181
|
-
function AccountContent({ userId, verified, message, pending, signOut }: {
|
|
182
|
-
userId: string; verified: Session['user'] | null; message: string; pending: boolean; signOut: () => Promise<void>;
|
|
183
|
-
}) {
|
|
184
|
-
return <Screen>
|
|
185
|
-
<Text accessibilityRole="header">Account</Text>
|
|
186
|
-
<Text>{accountMessage(userId, verified, message)}</Text>
|
|
187
|
-
<Text accessibilityLiveRegion="polite">{message}</Text>
|
|
188
|
-
<Button disabled={pending} onPress={() => void signOut()}>{pending ? 'Signing out…' : 'Sign out'}</Button>
|
|
189
|
-
<Link href="/sign-in">Sign in again</Link>
|
|
190
|
-
<Link href="/">Home</Link>
|
|
191
|
-
</Screen>;
|
|
192
|
-
}
|
|
193
|
-
`);
|
|
194
|
-
// Additions expose /account and /sign-in without rewriting existing product screens.
|
|
195
|
-
if (!linkHome)
|
|
196
|
-
return;
|
|
197
|
-
const home = `${directory}/app/index.tsx`;
|
|
198
|
-
const source = readFileSync(path.join(root, home), 'utf8');
|
|
199
|
-
if (source.includes('<Link href="/account">'))
|
|
200
|
-
return;
|
|
201
|
-
put(root, home, "import { Link } from 'expo-router';\n" +
|
|
202
|
-
source.replace("<Button onPress={() => void Linking.openURL('https://docs.expo.dev')}>Learn more</Button>", '<Link href="/account">Account and sign in</Link>\n <Button onPress={() => void Linking.openURL(\'https://docs.expo.dev\')}>Learn more</Button>'));
|
|
203
|
-
}
|