anhedral 0.11.2 → 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.
- package/README.md +171 -18
- package/dist/bin.js +48 -493
- package/dist/capabilities.d.ts +3 -3
- package/dist/capability-contract.js +16 -1
- package/dist/cli-arguments.d.ts +8 -0
- package/dist/cli-arguments.js +32 -0
- package/dist/cli-commands.d.ts +3 -0
- package/dist/cli-commands.js +114 -0
- package/dist/cli-delivery.d.ts +3 -0
- package/dist/cli-delivery.js +172 -0
- package/dist/cli-output.js +231 -205
- package/dist/command-schema.js +8 -2
- package/dist/command.js +9 -11
- package/dist/delivery-evidence.d.ts +62 -0
- package/dist/delivery-evidence.js +186 -0
- package/dist/delivery.d.ts +3 -40
- package/dist/delivery.js +7 -182
- package/dist/dependencies.d.ts +7 -1
- package/dist/dependencies.js +15 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/mobile-delivery.d.ts +21 -44
- package/dist/mobile-delivery.js +127 -80
- package/dist/platforms/mobile.d.ts +1 -1
- package/dist/platforms/mobile.js +44 -3
- package/dist/project-state.js +4 -1
- package/dist/provider-auth.js +9 -3
- package/dist/providers/adapters.js +9 -3
- package/dist/providers/runtime.js +11 -0
- package/dist/readiness.js +4 -2
- package/dist/registry/add.js +40 -7
- package/dist/registry/options.js +12 -0
- package/dist/registry/presets.d.ts +4 -0
- package/dist/registry/presets.js +41 -0
- package/dist/registry/resolve.d.ts +3 -1
- package/dist/registry/resolve.js +40 -14
- package/dist/registry/types.d.ts +1 -0
- package/dist/registry/usage.js +1 -1
- package/dist/runtime-policy.js +4 -1
- package/dist/scaffold/api.js +10 -2
- package/dist/scaffold/auth.d.ts +1 -1
- package/dist/scaffold/auth.js +22 -6
- package/dist/scaffold/backend.d.ts +6 -0
- package/dist/scaffold/backend.js +224 -0
- package/dist/scaffold/billing-config.d.ts +1 -0
- package/dist/scaffold/billing-config.js +73 -0
- package/dist/scaffold/billing-contracts.d.ts +2 -0
- package/dist/scaffold/billing-contracts.js +48 -0
- package/dist/scaffold/billing-providers.d.ts +1 -0
- package/dist/scaffold/billing-providers.js +249 -0
- package/dist/scaffold/billing-schema.d.ts +1 -0
- package/dist/scaffold/billing-schema.js +34 -0
- package/dist/scaffold/billing-security.d.ts +1 -0
- package/dist/scaffold/billing-security.js +46 -0
- package/dist/scaffold/billing-server.d.ts +1 -0
- package/dist/scaffold/billing-server.js +139 -0
- package/dist/scaffold/billing-store.d.ts +1 -0
- package/dist/scaffold/billing-store.js +72 -0
- package/dist/scaffold/billing.d.ts +2 -0
- package/dist/scaffold/billing.js +216 -0
- package/dist/scaffold/cloudflare-services.d.ts +8 -0
- package/dist/scaffold/cloudflare-services.js +198 -0
- package/dist/scaffold/compose.js +2 -0
- package/dist/scaffold/database.js +19 -2
- package/dist/scaffold/documentation.js +11 -6
- package/dist/scaffold/expo-auth.d.ts +3 -0
- package/dist/scaffold/expo-auth.js +192 -0
- package/dist/scaffold/expo-billing.d.ts +3 -0
- package/dist/scaffold/expo-billing.js +292 -0
- package/dist/scaffold/expo-runtime.d.ts +3 -0
- package/dist/scaffold/expo-runtime.js +134 -0
- package/dist/scaffold/integrations.d.ts +2 -1
- package/dist/scaffold/integrations.js +7 -2
- package/dist/scaffold/stream.d.ts +2 -0
- package/dist/scaffold/stream.js +114 -0
- package/dist/scaffold/void.js +13 -5
- package/dist/scaffold/web.js +2 -0
- package/dist/scaffold/workspace.js +6 -1
- package/dist/service-readers.js +1 -1
- package/dist/services-command.js +8 -6
- package/dist/ship.d.ts +15 -15
- package/dist/ship.js +3 -1
- package/dist/stack-registry.d.ts +13 -2
- package/dist/stack-registry.js +152 -16
- package/dist/transaction-lock.d.ts +15 -0
- package/dist/transaction-lock.js +227 -0
- package/dist/transaction.js +2 -208
- package/dist/vercel-project.d.ts +101 -0
- package/dist/vercel-project.js +305 -0
- package/dist/vercel.d.ts +3 -36
- package/dist/vercel.js +3 -300
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/docs/anhedral-stack.md +122 -0
- package/docs/software-factory.md +402 -7
- package/docs/stack-standard.md +226 -49
- package/docs/verification.md +557 -0
- package/package.json +7 -7
- package/docs/cli-design.md +0 -67
- package/docs/plugin-ui.md +0 -102
- package/docs/provider-configuration.md +0 -116
- package/docs/void-verification.md +0 -185
package/dist/registry/options.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { applyPreset } from './presets.js';
|
|
1
2
|
import { resolveStandardProducts } from './resolve.js';
|
|
2
3
|
import path from 'node:path';
|
|
3
4
|
import { packageNameFromText } from '../render.js';
|
|
@@ -20,6 +21,7 @@ function parseStandardFlags(remaining) {
|
|
|
20
21
|
let hosting = 'cloudflare';
|
|
21
22
|
let hostingSpecified = false;
|
|
22
23
|
let gitSpecified;
|
|
24
|
+
let preset;
|
|
23
25
|
for (let index = 0; index < remaining.length; index++) {
|
|
24
26
|
const token = remaining[index];
|
|
25
27
|
if (['--skip-install', '--dry-run', '--json', '--verbose'].includes(token))
|
|
@@ -28,6 +30,14 @@ function parseStandardFlags(remaining) {
|
|
|
28
30
|
gitSpecified = readGitFlag(token, gitSpecified);
|
|
29
31
|
continue;
|
|
30
32
|
}
|
|
33
|
+
if (token === '--preset' || token.startsWith('--preset=')) {
|
|
34
|
+
if (preset !== undefined)
|
|
35
|
+
throw new Error('Specify --preset once.');
|
|
36
|
+
preset = token === '--preset' ? remaining[++index] : token.slice('--preset='.length);
|
|
37
|
+
if (!preset || preset.startsWith('-'))
|
|
38
|
+
throw new Error('Supply a value for --preset.');
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
31
41
|
if (token === '--hosting' || token.startsWith('--hosting=')) {
|
|
32
42
|
const value = token === '--hosting' ? remaining[++index] : token.slice('--hosting='.length);
|
|
33
43
|
hosting = readHostingFlag(value, hosting, hostingSpecified);
|
|
@@ -40,6 +50,8 @@ function parseStandardFlags(remaining) {
|
|
|
40
50
|
}
|
|
41
51
|
products.add(value);
|
|
42
52
|
}
|
|
53
|
+
if (preset)
|
|
54
|
+
applyPreset(preset, products);
|
|
43
55
|
if (!hostingSpecified && products.has('next'))
|
|
44
56
|
hosting = 'vercel';
|
|
45
57
|
return { products, hosting, hostingSpecified, gitSpecified };
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { StandardProduct } from './types.js';
|
|
2
|
+
/** A compatible product selection, not mutually exclusive catalog alternatives. */
|
|
3
|
+
export declare const FULL_PRODUCT: readonly StandardProduct[];
|
|
4
|
+
export declare function applyPreset(name: string, selected: Set<StandardProduct>): void;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** A compatible product selection, not mutually exclusive catalog alternatives. */
|
|
2
|
+
export const FULL_PRODUCT = Object.freeze([
|
|
3
|
+
'expo',
|
|
4
|
+
'hono',
|
|
5
|
+
'wxt',
|
|
6
|
+
'd1',
|
|
7
|
+
'better-auth',
|
|
8
|
+
'r2',
|
|
9
|
+
'kv',
|
|
10
|
+
'stripe',
|
|
11
|
+
'revenuecat',
|
|
12
|
+
'workers-ai',
|
|
13
|
+
'analytics-engine',
|
|
14
|
+
'basin',
|
|
15
|
+
'realtime',
|
|
16
|
+
'realtimekit',
|
|
17
|
+
'images',
|
|
18
|
+
'stream',
|
|
19
|
+
'video',
|
|
20
|
+
'queues',
|
|
21
|
+
'cron',
|
|
22
|
+
'workflows',
|
|
23
|
+
'resend',
|
|
24
|
+
'sentry',
|
|
25
|
+
]);
|
|
26
|
+
export function applyPreset(name, selected) {
|
|
27
|
+
if (!['minimal', 'full-product'].includes(name))
|
|
28
|
+
throw new Error('preset must be minimal or full-product.');
|
|
29
|
+
if (name === 'minimal')
|
|
30
|
+
return;
|
|
31
|
+
// Explicit provider/frontend choices replace the preset's corresponding default.
|
|
32
|
+
for (const id of FULL_PRODUCT) {
|
|
33
|
+
if (id === 'expo' && (selected.has('next') || selected.has('vinext')))
|
|
34
|
+
continue;
|
|
35
|
+
if (id === 'd1' && (selected.has('neon') || selected.has('neon-realtime')))
|
|
36
|
+
continue;
|
|
37
|
+
if (id === 'better-auth' && selected.has('clerk'))
|
|
38
|
+
continue;
|
|
39
|
+
selected.add(id);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { Hosting, StandardOptions, StandardProduct, StackRegistryItem } from './types.js';
|
|
2
|
+
/** Explicit billing selection needs an authenticated server and durable state. */
|
|
3
|
+
export declare function resolveBillingProducts(selected: Set<StandardProduct>): void;
|
|
2
4
|
/** Apply default selections once. All callers then use the same strict graph resolver. */
|
|
3
|
-
export declare function resolveStandardProducts(selected: Set<StandardProduct>, hosting: Hosting, hostingSpecified: boolean): void;
|
|
5
|
+
export declare function resolveStandardProducts(selected: Set<StandardProduct>, hosting: Hosting, hostingSpecified: boolean, initializing?: boolean): void;
|
|
4
6
|
export interface ResolvedStackRegistry {
|
|
5
7
|
schemaVersion: number;
|
|
6
8
|
name: string;
|
package/dist/registry/resolve.js
CHANGED
|
@@ -9,6 +9,14 @@ function needsWorker(name, context) {
|
|
|
9
9
|
return (definition.runtime === 'worker' ||
|
|
10
10
|
(definition.runtime === 'optional-worker' && hasServer(context)));
|
|
11
11
|
}
|
|
12
|
+
/** Explicit billing selection needs an authenticated server and durable state. */
|
|
13
|
+
export function resolveBillingProducts(selected) {
|
|
14
|
+
selected.add('hono');
|
|
15
|
+
if (!selected.has('clerk'))
|
|
16
|
+
selected.add('better-auth');
|
|
17
|
+
if (!selected.has('neon') && !selected.has('d1'))
|
|
18
|
+
selected.add(selected.has('neon-realtime') ? 'neon' : 'd1');
|
|
19
|
+
}
|
|
12
20
|
function validateProducts(selected, hosting) {
|
|
13
21
|
if (!['cloudflare', 'vercel'].includes(hosting))
|
|
14
22
|
throw new Error('hosting must be cloudflare or vercel.');
|
|
@@ -29,28 +37,46 @@ function validateProducts(selected, hosting) {
|
|
|
29
37
|
throw new Error('Vinext requires Cloudflare hosting; select --next for Vercel.');
|
|
30
38
|
}
|
|
31
39
|
/** Apply default selections once. All callers then use the same strict graph resolver. */
|
|
32
|
-
export function resolveStandardProducts(selected, hosting, hostingSpecified) {
|
|
40
|
+
export function resolveStandardProducts(selected, hosting, hostingSpecified, initializing = true) {
|
|
33
41
|
for (const id of selected)
|
|
34
42
|
getStackDefinition(id);
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
//
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
const
|
|
44
|
-
if (
|
|
45
|
-
|
|
46
|
-
|
|
43
|
+
const applications = [...selected].filter((id) => getStackDefinition(id).type === 'application');
|
|
44
|
+
if (!applications.length)
|
|
45
|
+
selected.add(hosting === 'vercel' ? 'next' : 'expo');
|
|
46
|
+
// Resolve to a fixed point: an addition may introduce another dependency.
|
|
47
|
+
// Readiness/add callers preserve an existing web-owned backend; new profiles
|
|
48
|
+
// use Hono whenever privileged server behavior is selected.
|
|
49
|
+
let changed = true;
|
|
50
|
+
while (changed) {
|
|
51
|
+
const before = selected.size;
|
|
52
|
+
if (selected.has('stripe') || selected.has('revenuecat'))
|
|
53
|
+
resolveBillingProducts(selected);
|
|
54
|
+
const defaults = [...selected].sort((left, right) => (getStackDefinition(left).selection.requiresAny?.length ?? 0) -
|
|
55
|
+
(getStackDefinition(right).selection.requiresAny?.length ?? 0) ||
|
|
56
|
+
left.localeCompare(right));
|
|
57
|
+
for (const id of defaults) {
|
|
58
|
+
const definition = getStackDefinition(id);
|
|
59
|
+
const alternatives = definition.selection.requiresAny ?? [];
|
|
60
|
+
if (definition.fallbackDependency &&
|
|
61
|
+
!alternatives.some((other) => selected.has(other)))
|
|
62
|
+
selected.add(definition.fallbackDependency);
|
|
63
|
+
for (const dependency of definition.selection.requiresAll ?? [])
|
|
64
|
+
selected.add(dependency);
|
|
65
|
+
const serverCapability = Boolean(definition.runtime);
|
|
66
|
+
if (serverCapability &&
|
|
67
|
+
(initializing || !hasServer(createResolutionContext({ products: [...selected], hosting }))))
|
|
68
|
+
selected.add('hono');
|
|
69
|
+
}
|
|
70
|
+
changed = selected.size !== before;
|
|
47
71
|
}
|
|
48
72
|
const context = createResolutionContext({ products: [...selected], hosting });
|
|
49
73
|
if (context.has('next') &&
|
|
50
74
|
hosting === 'vercel' &&
|
|
51
75
|
[...selected].some((id) => needsWorker(id, context)))
|
|
52
76
|
selected.add('hono');
|
|
53
|
-
if (
|
|
77
|
+
if (selected.has('expo') && hosting === 'vercel' && !selected.has('next'))
|
|
78
|
+
throw new Error('Expo web uses Cloudflare hosting; select --next for a Vercel web application.');
|
|
79
|
+
if (hostingSpecified && !selected.has('next') && !selected.has('vinext') && !selected.has('expo'))
|
|
54
80
|
throw new Error('--hosting applies to the web application.');
|
|
55
81
|
resolveStackRegistry({ products: [...selected], hosting });
|
|
56
82
|
}
|
package/dist/registry/types.d.ts
CHANGED
package/dist/registry/usage.js
CHANGED
|
@@ -15,4 +15,4 @@ export function commandHelp(command) {
|
|
|
15
15
|
export const STANDARD_USAGE = `Anhedral\nScaffold source, authenticate your providers, and ship your selected stack.\n\nUsage: anhedral <command> [options]\n\nStart here:\n${primary.map((name) => ` ${name.padEnd(12)}${COMMAND_HELP[name].description}`).join('\n')}\n\nDelivery tools:\n${Object.entries(COMMAND_HELP)
|
|
16
16
|
.filter(([name]) => !primary.includes(name))
|
|
17
17
|
.map(([name, entry]) => ` ${name.padEnd(12)}${entry.description}`)
|
|
18
|
-
.join('\n')}\n\nDefault:
|
|
18
|
+
.join('\n')}\n\nDefault: minimal Expo web, iOS and Android app in a pnpm/Turborepo workspace. Add API, identity, data and services when needed; --preset full-product selects the complete compatible stack.\nExamples:\n anhedral init client-app\n anhedral auth client-app\n anhedral ship client-app --dry-run\n\nUse anhedral <command> --help for options and examples.\nUse anhedral help <command> for the same focused help.\nGlobal options:\n${common.map((option) => ` ${option}`).join('\n')}\n -v, --version Show the CLI version.\n`;
|
package/dist/runtime-policy.js
CHANGED
|
@@ -14,8 +14,11 @@ export function supportsVoidRuntime(version) {
|
|
|
14
14
|
return major > 24 || (major === 24 && minor >= 21);
|
|
15
15
|
}
|
|
16
16
|
export function usesVoidSelection(products, hosting) {
|
|
17
|
-
return (!
|
|
17
|
+
return (!products.includes('expo') &&
|
|
18
|
+
!(products.includes('next') && hosting === 'cloudflare') &&
|
|
18
19
|
!products.includes('queues') &&
|
|
19
20
|
!products.includes('basin') &&
|
|
21
|
+
!products.includes('images') &&
|
|
22
|
+
!products.includes('analytics-engine') &&
|
|
20
23
|
products.some((product) => ['vinext', 'hono', 'realtime', 'cron', 'workflows'].includes(product)));
|
|
21
24
|
}
|
package/dist/scaffold/api.js
CHANGED
|
@@ -1,22 +1,29 @@
|
|
|
1
|
+
import { scaffoldContracts } from './backend.js';
|
|
1
2
|
import { resourceName, jsString } from '../render.js';
|
|
2
3
|
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
3
4
|
import { workerConfig, worker } from './files.js';
|
|
4
5
|
export function scaffoldApi({ root, options, bindings }) {
|
|
5
|
-
|
|
6
|
+
scaffoldContracts(root);
|
|
7
|
+
worker(root, 'api', { ...workerConfig(resourceName(options.name, 'api')), ...bindings }, `import { OpenAPIHono, createRoute } from '@hono/zod-openapi';
|
|
8
|
+
|
|
9
|
+
import { healthSchema } from '@workspace/contracts';
|
|
10
|
+
import { bodyLimit } from 'hono/body-limit';
|
|
6
11
|
|
|
7
12
|
const app = new OpenAPIHono<{ Bindings: Env }>();
|
|
13
|
+
app.use('/api/*', bodyLimit({ maxSize: 1024 * 1024 }));
|
|
8
14
|
const health = createRoute({
|
|
9
15
|
method: 'get',
|
|
10
16
|
path: '/health',
|
|
11
17
|
responses: {
|
|
12
18
|
200: {
|
|
13
19
|
description: 'Healthy',
|
|
14
|
-
content: { 'application/json': { schema:
|
|
20
|
+
content: { 'application/json': { schema: healthSchema } },
|
|
15
21
|
},
|
|
16
22
|
},
|
|
17
23
|
});
|
|
18
24
|
|
|
19
25
|
app.openapi(health, (c) => c.json({ ok: true as const }, 200));
|
|
26
|
+
app.get('/api/health', (c) => c.json(healthSchema.parse({ ok: true })));
|
|
20
27
|
app.doc('/openapi.json', {
|
|
21
28
|
openapi: '3.0.0',
|
|
22
29
|
info: { title: ${jsString(options.name)}, version: '1.0.0' },
|
|
@@ -24,6 +31,7 @@ app.doc('/openapi.json', {
|
|
|
24
31
|
|
|
25
32
|
export default app;
|
|
26
33
|
`, {
|
|
34
|
+
'@workspace/contracts': 'workspace:*',
|
|
27
35
|
hono: STACK_DEPENDENCIES['hono'],
|
|
28
36
|
'@hono/zod-openapi': STACK_DEPENDENCIES['@hono/zod-openapi'],
|
|
29
37
|
});
|
package/dist/scaffold/auth.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import type { RecipeContext } from '../registry/types.js';
|
|
2
|
-
export declare function scaffoldBetterAuth({ root, options, runtimeApp, has }: RecipeContext): void;
|
|
2
|
+
export declare function scaffoldBetterAuth({ root, options, runtimeApp, has, updating, }: RecipeContext): void;
|
|
3
3
|
export declare function scaffoldClerk({ root, has }: RecipeContext): void;
|
package/dist/scaffold/auth.js
CHANGED
|
@@ -1,24 +1,31 @@
|
|
|
1
|
+
import { scaffoldContracts, scaffoldWebAuth } from './backend.js';
|
|
2
|
+
import { expoAuthScheme, scaffoldExpoAuth } from './expo-auth.js';
|
|
3
|
+
import { jsString } from '../render.js';
|
|
1
4
|
import { writeEnvironmentFile } from './environment.js';
|
|
2
5
|
import { STACK_DEPENDENCIES } from '../dependencies.js';
|
|
3
6
|
import { existsSync, readFileSync } from 'node:fs';
|
|
4
7
|
import path from 'node:path';
|
|
5
8
|
import { writeBetterAuthSchema } from '../auth-schema.js';
|
|
6
9
|
import { put, patchPackage, sharedPackage } from './files.js';
|
|
7
|
-
export function scaffoldBetterAuth({ root, options, runtimeApp, has }) {
|
|
10
|
+
export function scaffoldBetterAuth({ root, options, runtimeApp, has, updating, }) {
|
|
11
|
+
const scheme = has('expo') ? expoAuthScheme(root) : undefined;
|
|
8
12
|
writeBetterAuthSchema(root, has('neon'));
|
|
9
|
-
sharedPackage(root, 'auth',
|
|
13
|
+
sharedPackage(root, 'auth', `${scheme ? "import { expo } from '@better-auth/expo';\n" : ''}import { betterAuth } from 'better-auth';
|
|
10
14
|
import { drizzleAdapter } from '@better-auth/drizzle-adapter';
|
|
11
15
|
import type { createDatabase } from '@workspace/db';
|
|
12
|
-
export function createAuth(db: ReturnType<typeof createDatabase>, secret: string, baseURL: string) {
|
|
16
|
+
export function createAuth(db: ReturnType<typeof createDatabase>, secret: string, baseURL: string, trustedOrigins: string[] = [new URL(baseURL).origin${scheme ? `, ${jsString(scheme + '://')}` : ''}]) {
|
|
13
17
|
return betterAuth({
|
|
14
18
|
database: drizzleAdapter(db, { provider: '${has('neon') ? 'pg' : 'sqlite'}', transaction: false }),
|
|
15
19
|
secret,
|
|
16
20
|
baseURL,
|
|
21
|
+
trustedOrigins,
|
|
22
|
+
${scheme ? 'plugins: [expo()],' : ''}
|
|
17
23
|
emailAndPassword: { enabled: true },
|
|
18
24
|
});
|
|
19
25
|
}
|
|
20
26
|
`, {
|
|
21
27
|
'better-auth': STACK_DEPENDENCIES['better-auth'],
|
|
28
|
+
...(scheme ? { '@better-auth/expo': STACK_DEPENDENCIES['@better-auth/expo'] } : {}),
|
|
22
29
|
'@better-auth/drizzle-adapter': STACK_DEPENDENCIES['@better-auth/drizzle-adapter'],
|
|
23
30
|
'@workspace/db': 'workspace:*',
|
|
24
31
|
});
|
|
@@ -27,9 +34,14 @@ export function createAuth(db: ReturnType<typeof createDatabase>, secret: string
|
|
|
27
34
|
});
|
|
28
35
|
const connection = has('neon') ? 'createDatabase(env.DATABASE_URL)' : 'createDatabase(env.DB)';
|
|
29
36
|
if (has('hono')) {
|
|
37
|
+
if (!existsSync(path.join(root, 'packages/contracts/package.json')))
|
|
38
|
+
scaffoldContracts(root);
|
|
39
|
+
patchPackage(root, 'apps/api/package.json', {
|
|
40
|
+
dependencies: { '@workspace/contracts': 'workspace:*' },
|
|
41
|
+
});
|
|
30
42
|
const source = readFileSync(path.join(root, 'apps/api/src/index.ts'), 'utf8');
|
|
31
|
-
put(root, 'apps/api/src/index.ts', `import { createAuth } from '@workspace/auth';\
|
|
32
|
-
source.replace('export default app;', `app.on(['GET', 'POST'], '/api/auth/*', async (c) => {\n const env = c.env;\n const database = ${connection};\n return await createAuth(database, env.BETTER_AUTH_SECRET, env.BETTER_AUTH_URL).handler(c.req.raw);\n});\nexport default app;`));
|
|
43
|
+
put(root, 'apps/api/src/index.ts', `import { createAuth } from '@workspace/auth';\n${source.includes("import { createDatabase } from '@workspace/db'") ? '' : "import { createDatabase } from '@workspace/db';\n"}import { sessionSchema } from '@workspace/contracts';\n` +
|
|
44
|
+
source.replace('export default app;', `app.get('/api/session', async (c) => {\n const env = c.env;\n const session = await createAuth(${connection}, env.BETTER_AUTH_SECRET, env.BETTER_AUTH_URL).api.getSession({ headers: c.req.raw.headers });\n c.header('cache-control', 'private, no-store');\n if (!session) return c.json({ error: 'Unauthorized' }, 401);\n return c.json(sessionSchema.parse({ user: session.user }));\n});\napp.on(['GET', 'POST'], '/api/auth/*', async (c) => {\n const env = c.env;\n const database = ${connection};\n return await createAuth(database, env.BETTER_AUTH_SECRET, env.BETTER_AUTH_URL).handler(c.req.raw);\n});\nexport default app;`));
|
|
33
45
|
}
|
|
34
46
|
else {
|
|
35
47
|
put(root, 'apps/web/app/api/auth/[...all]/route.ts', `${has('vinext') ? "import { env } from 'cloudflare:workers';" : options.hosting === 'cloudflare' ? "import { getCloudflareContext } from '@opennextjs/cloudflare';" : ''}
|
|
@@ -54,8 +66,12 @@ export { handler as GET, handler as POST };
|
|
|
54
66
|
writeEnvironmentFile(root, `apps/${runtimeApp}/${runtimeApp === 'web' && options.hosting === 'vercel' ? '.env.example' : '.dev.vars.example'}`, {
|
|
55
67
|
...(has('neon') ? { DATABASE_URL: '' } : {}),
|
|
56
68
|
BETTER_AUTH_SECRET: '',
|
|
57
|
-
BETTER_AUTH_URL: `http://localhost:${
|
|
69
|
+
BETTER_AUTH_URL: `http://localhost:${has('vinext') || has('next') || has('expo') ? '3000' : '8787'}`,
|
|
58
70
|
});
|
|
71
|
+
if (has('hono') && (has('vinext') || has('next')))
|
|
72
|
+
scaffoldWebAuth(root);
|
|
73
|
+
if (scheme)
|
|
74
|
+
scaffoldExpoAuth(root, scheme, !updating);
|
|
59
75
|
if (has('hono'))
|
|
60
76
|
put(root, 'apps/api/src/secrets.d.ts', 'interface Env { BETTER_AUTH_SECRET: string; BETTER_AUTH_URL: string }\n');
|
|
61
77
|
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { RecipeContext } from '../registry/types.js';
|
|
2
|
+
/** Public contracts never import a framework, database or auth server. */
|
|
3
|
+
export declare function scaffoldContracts(root: string): void;
|
|
4
|
+
/** A single trusted upstream; never forward provider/edge identity headers from browsers. */
|
|
5
|
+
export declare function scaffoldWebBackend({ root, options, has }: RecipeContext): void;
|
|
6
|
+
export declare function scaffoldWebAuth(root: string): void;
|
|
@@ -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
|
+
`;
|