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.
Files changed (246) hide show
  1. package/README.md +82 -34
  2. package/assets/stack/ai-schema.ts.txt +5 -0
  3. package/assets/stack/ai.ts.txt +30 -0
  4. package/assets/stack/api-index.ts.txt +15 -0
  5. package/assets/stack/auth-features.ts.txt +4 -0
  6. package/assets/stack/auth-journal.json.txt +13 -0
  7. package/assets/stack/auth-migration.sql.txt +53 -0
  8. package/assets/stack/auth-routes.ts.txt +11 -0
  9. package/assets/stack/auth-schema.ts.txt +64 -0
  10. package/assets/stack/auth-snapshot.json.txt +346 -0
  11. package/assets/stack/auth.ts.txt +32 -0
  12. package/assets/stack/billing-mode.ts.txt +8 -0
  13. package/assets/stack/billing-schema.ts.txt +11 -0
  14. package/assets/stack/desktop.rs.txt +21 -0
  15. package/assets/stack/entitlement-guard.ts.txt +32 -0
  16. package/assets/stack/entitlements.ts.txt +8 -0
  17. package/assets/stack/events-schema.ts.txt +12 -0
  18. package/assets/stack/events.ts.txt +59 -0
  19. package/assets/stack/mobile-auth.ts.txt +25 -0
  20. package/assets/stack/mobile-billing.tsx.txt +63 -0
  21. package/assets/stack/mobile-session.tsx.txt +83 -0
  22. package/assets/stack/native-button.tsx.txt +108 -0
  23. package/assets/stack/native-global.css.txt +4 -0
  24. package/assets/stack/native-lib-utils.ts.txt +5 -0
  25. package/assets/stack/native-metro.config.js.txt +6 -0
  26. package/assets/stack/native-nativewind-env.d.ts.txt +1 -0
  27. package/assets/stack/native-tailwind.config.js.txt +73 -0
  28. package/assets/stack/native-text.tsx.txt +89 -0
  29. package/assets/stack/purchases.ts.txt +65 -0
  30. package/assets/stack/revenuecat.ts.txt +88 -0
  31. package/assets/stack/rtc-schema.ts.txt +10 -0
  32. package/assets/stack/rtc.ts.txt +122 -0
  33. package/assets/stack/security.ts.txt +31 -0
  34. package/assets/stack/storage.ts.txt +36 -0
  35. package/assets/stack/stripe.ts.txt +126 -0
  36. package/assets/stack/web-sign-in.tsx.txt +51 -0
  37. package/assets/ui/LICENSE.react-native-reusables +21 -0
  38. package/assets/ui/UPSTREAM.json +0 -11
  39. package/assets/ui/catalog.json +891 -0
  40. package/assets/ui/extensions/registry.json +6 -0
  41. package/dist/bin.js +7 -12
  42. package/dist/capabilities.d.ts +4 -33
  43. package/dist/capabilities.js +2 -66
  44. package/dist/capability-catalog.d.ts +83 -0
  45. package/dist/capability-catalog.js +121 -0
  46. package/dist/capability-command.d.ts +3 -0
  47. package/dist/capability-command.js +188 -0
  48. package/dist/capability-editor.d.ts +17 -0
  49. package/dist/capability-editor.js +97 -0
  50. package/dist/capability-recipes.d.ts +4 -0
  51. package/dist/capability-recipes.js +520 -0
  52. package/dist/capability-references.d.ts +4 -0
  53. package/dist/capability-references.js +7 -0
  54. package/dist/cli-commands.d.ts +1 -2
  55. package/dist/cli-commands.js +10 -104
  56. package/dist/cli-output.d.ts +1 -2
  57. package/dist/cli-output.js +6 -251
  58. package/dist/command-schema.js +39 -322
  59. package/dist/dependencies.d.ts +29 -9
  60. package/dist/dependencies.js +57 -64
  61. package/dist/index.d.ts +1 -42
  62. package/dist/index.js +1 -27
  63. package/dist/platforms/web.d.ts +1 -1
  64. package/dist/platforms/web.js +27 -75
  65. package/dist/project-config.d.ts +2 -13
  66. package/dist/project-config.js +10 -82
  67. package/dist/registry/options.js +1 -5
  68. package/dist/registry/resolve.d.ts +1 -1
  69. package/dist/registry/resolve.js +4 -10
  70. package/dist/registry/usage.js +3 -9
  71. package/dist/scaffold/backend.js +0 -3
  72. package/dist/scaffold/database.js +2 -1
  73. package/dist/scaffold/documentation.js +56 -25
  74. package/dist/scaffold/stack-documentation.js +1 -1
  75. package/dist/scaffold/storage.d.ts +2 -0
  76. package/dist/scaffold/storage.js +21 -0
  77. package/dist/scaffold/workspace.js +21 -22
  78. package/dist/stack-registry.d.ts +2 -10
  79. package/dist/stack-registry.js +12 -98
  80. package/dist/standard.js +1 -11
  81. package/dist/ui-catalog.d.ts +26 -0
  82. package/dist/ui-catalog.js +31 -0
  83. package/dist/ui-command.d.ts +3 -0
  84. package/dist/ui-command.js +219 -0
  85. package/dist/ui-project.d.ts +22 -0
  86. package/dist/ui-project.js +110 -0
  87. package/dist/version.d.ts +1 -1
  88. package/dist/version.js +1 -1
  89. package/docs/anhedral-stack.md +12 -23
  90. package/docs/assets/anhedral-stack-light.png +0 -0
  91. package/docs/assets/anhedral-stack.png +0 -0
  92. package/docs/capabilities.md +110 -0
  93. package/docs/native-ui.md +47 -0
  94. package/docs/software-factory.md +35 -50
  95. package/docs/stack-standard.md +19 -70
  96. package/docs/ui.md +33 -0
  97. package/docs/verification.md +6 -876
  98. package/package.json +21 -16
  99. package/assets/ui/native/button.tsx +0 -85
  100. package/assets/ui/native/card.tsx +0 -33
  101. package/assets/ui/native/dialog.tsx +0 -75
  102. package/assets/ui/native/input.tsx +0 -27
  103. package/assets/ui/native/label.tsx +0 -4
  104. package/assets/ui/native/layout.tsx +0 -26
  105. package/assets/ui/native/text.tsx +0 -20
  106. package/assets/ui/native/theme-switcher.tsx +0 -22
  107. package/assets/ui/theme-storage.ts +0 -25
  108. package/assets/ui/theme.tsx +0 -66
  109. package/dist/access.d.ts +0 -10
  110. package/dist/access.js +0 -93
  111. package/dist/auth-schema-snapshot.d.ts +0 -346
  112. package/dist/auth-schema-snapshot.js +0 -347
  113. package/dist/auth-schema.d.ts +0 -1
  114. package/dist/auth-schema.js +0 -57
  115. package/dist/capability-contract.d.ts +0 -47
  116. package/dist/capability-contract.js +0 -129
  117. package/dist/catalog-model.d.ts +0 -24
  118. package/dist/catalog-model.js +0 -1
  119. package/dist/catalog-registration.d.ts +0 -16
  120. package/dist/catalog-registration.js +0 -22
  121. package/dist/catalog-snapshot.d.ts +0 -5
  122. package/dist/catalog-snapshot.js +0 -97
  123. package/dist/cli-delivery.d.ts +0 -3
  124. package/dist/cli-delivery.js +0 -112
  125. package/dist/cloudflare.d.ts +0 -25
  126. package/dist/cloudflare.js +0 -226
  127. package/dist/delivery-evidence.d.ts +0 -62
  128. package/dist/delivery-evidence.js +0 -157
  129. package/dist/delivery.d.ts +0 -82
  130. package/dist/delivery.js +0 -489
  131. package/dist/inspector-model.d.ts +0 -123
  132. package/dist/inspector-model.js +0 -1
  133. package/dist/integration-service-readers.d.ts +0 -12
  134. package/dist/integration-service-readers.js +0 -92
  135. package/dist/lifecycle-model.d.ts +0 -15
  136. package/dist/lifecycle-model.js +0 -20
  137. package/dist/lifecycle.d.ts +0 -11
  138. package/dist/lifecycle.js +0 -91
  139. package/dist/management.d.ts +0 -3
  140. package/dist/management.js +0 -47
  141. package/dist/mobile-delivery.d.ts +0 -77
  142. package/dist/mobile-delivery.js +0 -370
  143. package/dist/platforms/mobile.d.ts +0 -2
  144. package/dist/platforms/mobile.js +0 -156
  145. package/dist/project-catalog.d.ts +0 -41
  146. package/dist/project-catalog.js +0 -288
  147. package/dist/project-inspector.d.ts +0 -4
  148. package/dist/project-inspector.js +0 -671
  149. package/dist/project-lifecycle.d.ts +0 -25
  150. package/dist/project-lifecycle.js +0 -57
  151. package/dist/project-state.d.ts +0 -47
  152. package/dist/project-state.js +0 -480
  153. package/dist/provider-auth.d.ts +0 -41
  154. package/dist/provider-auth.js +0 -180
  155. package/dist/provider-readiness.d.ts +0 -30
  156. package/dist/provider-readiness.js +0 -85
  157. package/dist/providers/adapters.d.ts +0 -17
  158. package/dist/providers/adapters.js +0 -103
  159. package/dist/providers/api.d.ts +0 -29
  160. package/dist/providers/api.js +0 -253
  161. package/dist/providers/config.d.ts +0 -15
  162. package/dist/providers/config.js +0 -136
  163. package/dist/providers/definitions.d.ts +0 -115
  164. package/dist/providers/definitions.js +0 -42
  165. package/dist/providers/provision.d.ts +0 -24
  166. package/dist/providers/provision.js +0 -76
  167. package/dist/providers/receipts.d.ts +0 -20
  168. package/dist/providers/receipts.js +0 -56
  169. package/dist/providers/recovery-verification.d.ts +0 -7
  170. package/dist/providers/recovery-verification.js +0 -52
  171. package/dist/providers/recovery.d.ts +0 -30
  172. package/dist/providers/recovery.js +0 -34
  173. package/dist/providers/runtime.d.ts +0 -10
  174. package/dist/providers/runtime.js +0 -234
  175. package/dist/providers/schema.d.ts +0 -28
  176. package/dist/providers/schema.js +0 -49
  177. package/dist/providers/state.d.ts +0 -55
  178. package/dist/providers/state.js +0 -283
  179. package/dist/provision.d.ts +0 -47
  180. package/dist/provision.js +0 -208
  181. package/dist/r2-service-data.d.ts +0 -2
  182. package/dist/r2-service-data.js +0 -136
  183. package/dist/readiness.d.ts +0 -23
  184. package/dist/readiness.js +0 -117
  185. package/dist/registry/add.d.ts +0 -24
  186. package/dist/registry/add.js +0 -210
  187. package/dist/registry/bootstrap.d.ts +0 -3
  188. package/dist/registry/bootstrap.js +0 -5
  189. package/dist/registry/commands.d.ts +0 -3
  190. package/dist/registry/commands.js +0 -83
  191. package/dist/registry/preview.d.ts +0 -11
  192. package/dist/registry/preview.js +0 -91
  193. package/dist/registry/receipt.d.ts +0 -3
  194. package/dist/registry/receipt.js +0 -68
  195. package/dist/repository.d.ts +0 -24
  196. package/dist/repository.js +0 -96
  197. package/dist/scaffold/auth.d.ts +0 -2
  198. package/dist/scaffold/auth.js +0 -76
  199. package/dist/scaffold/billing-config.d.ts +0 -1
  200. package/dist/scaffold/billing-config.js +0 -73
  201. package/dist/scaffold/billing-contracts.d.ts +0 -2
  202. package/dist/scaffold/billing-contracts.js +0 -48
  203. package/dist/scaffold/billing-providers.d.ts +0 -1
  204. package/dist/scaffold/billing-providers.js +0 -249
  205. package/dist/scaffold/billing-schema.d.ts +0 -1
  206. package/dist/scaffold/billing-schema.js +0 -34
  207. package/dist/scaffold/billing-security.d.ts +0 -1
  208. package/dist/scaffold/billing-security.js +0 -46
  209. package/dist/scaffold/billing-server.d.ts +0 -1
  210. package/dist/scaffold/billing-server.js +0 -139
  211. package/dist/scaffold/billing-store.d.ts +0 -1
  212. package/dist/scaffold/billing-store.js +0 -72
  213. package/dist/scaffold/billing.d.ts +0 -2
  214. package/dist/scaffold/billing.js +0 -208
  215. package/dist/scaffold/expo-auth.d.ts +0 -3
  216. package/dist/scaffold/expo-auth.js +0 -203
  217. package/dist/scaffold/expo-billing.d.ts +0 -3
  218. package/dist/scaffold/expo-billing.js +0 -257
  219. package/dist/scaffold/expo-runtime.d.ts +0 -3
  220. package/dist/scaffold/expo-runtime.js +0 -43
  221. package/dist/scaffold/integrations.d.ts +0 -2
  222. package/dist/scaffold/integrations.js +0 -11
  223. package/dist/scaffold/managed-email.d.ts +0 -3
  224. package/dist/scaffold/managed-email.js +0 -47
  225. package/dist/scaffold/native-ui.d.ts +0 -2
  226. package/dist/scaffold/native-ui.js +0 -69
  227. package/dist/scaffold/password-reset.d.ts +0 -1
  228. package/dist/scaffold/password-reset.js +0 -99
  229. package/dist/scaffold/private-files.d.ts +0 -2
  230. package/dist/scaffold/private-files.js +0 -78
  231. package/dist/scaffold/web-billing.d.ts +0 -2
  232. package/dist/scaffold/web-billing.js +0 -48
  233. package/dist/service-deletion.d.ts +0 -29
  234. package/dist/service-deletion.js +0 -195
  235. package/dist/service-descriptor.d.ts +0 -10
  236. package/dist/service-descriptor.js +0 -71
  237. package/dist/service-model.d.ts +0 -49
  238. package/dist/service-model.js +0 -8
  239. package/dist/service-operations.d.ts +0 -29
  240. package/dist/service-operations.js +0 -48
  241. package/dist/service-readers.d.ts +0 -8
  242. package/dist/service-readers.js +0 -216
  243. package/dist/services-command.d.ts +0 -39
  244. package/dist/services-command.js +0 -96
  245. package/dist/ship.d.ts +0 -35
  246. package/dist/ship.js +0 -107
@@ -1,257 +0,0 @@
1
- import { writeEnvironmentFile } from './environment.js';
2
- import { readFileSync } from 'node:fs';
3
- import path from 'node:path';
4
- import { STACK_DEPENDENCIES } from '../dependencies.js';
5
- import { patchPackage, put } from './files.js';
6
- /** Native store purchases and web Stripe checkout share only server-verified entitlements. */
7
- export function scaffoldExpoBilling({ root, has }) {
8
- const directory = 'apps/mobile';
9
- put(root, `${directory}/lib/billing-types.ts`, 'export interface StoreOffer { id: string; label: string; price: string }\n');
10
- if (has('revenuecat')) {
11
- writeEnvironmentFile(root, `${directory}/.env.example`, {
12
- EXPO_PUBLIC_REVENUECAT_IOS_API_KEY: '',
13
- EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEY: '',
14
- });
15
- patchPackage(root, `${directory}/package.json`, {
16
- dependencies: { 'react-native-purchases': STACK_DEPENDENCIES['react-native-purchases'] },
17
- });
18
- }
19
- put(root, `${directory}/lib/billing-api.ts`, `export { billingApi } from './billing-api.native';\n`);
20
- put(root, `${directory}/lib/billing-api.native.ts`, `import { createBillingClient } from '@workspace/contracts';
21
- import { nativeApiOrigin } from './api-client';
22
- import { getAuthClient } from './auth-client.native';
23
-
24
- function client() {
25
- return createBillingClient(nativeApiOrigin() + '/api/billing', {
26
- credentials: 'omit', headers: async () => {
27
- const headers = new Headers();
28
- headers.set('cookie', await getAuthClient().getCookie());
29
- return headers;
30
- },
31
- });
32
- }
33
- export const billingApi = {
34
- identity: () => client().identity(), entitlements: () => client().entitlements(),
35
- refresh: () => client().refresh(), checkout: (plan: string, key: string) => client().checkout(plan, key),
36
- portal: () => client().portal(),
37
- };
38
- `);
39
- put(root, `${directory}/lib/billing-platform.ts`, `export type { StoreOffer } from './billing-types';
40
- export * from './billing-platform.native';
41
- `);
42
- if (has('revenuecat'))
43
- put(root, `${directory}/lib/billing-platform.native.ts`, nativeStoreSource());
44
- else
45
- put(root, `${directory}/lib/billing-platform.native.ts`, `export type { StoreOffer } from './billing-types';
46
- export async function connectStore(_userId: string): Promise<void> {}
47
- export async function disconnectStore(): Promise<void> {}
48
- export async function storeOffers(): Promise<import('./billing-types').StoreOffer[]> { return []; }
49
- export async function purchaseStoreOffer(_id: string): Promise<void> { throw new Error('RevenueCat is not selected.'); }
50
- export async function restoreStorePurchases(): Promise<void> { throw new Error('RevenueCat is not selected.'); }
51
- export async function manageStorePurchases(): Promise<void> { throw new Error('RevenueCat is not selected.'); }
52
- `);
53
- put(root, `${directory}/app/billing.tsx`, billingScreenSource());
54
- const account = `${directory}/app/account.tsx`;
55
- const source = readFileSync(path.join(root, account), 'utf8');
56
- const linked = source.includes('href="/billing"')
57
- ? source
58
- : source.replace('<Link href="/">Home</Link>', '<Link href="/billing">Subscription and entitlements</Link>\n <Link href="/">Home</Link>');
59
- if (linked.includes('await disconnectStore();'))
60
- return;
61
- put(root, account, "import { disconnectStore } from '@/lib/billing-platform';\n" +
62
- linked.replace('const result = await getAuthClient().signOut();', 'await disconnectStore();\n const result = await getAuthClient().signOut();'));
63
- }
64
- function nativeStoreSource() {
65
- return `import Purchases from 'react-native-purchases';
66
- import { Linking, Platform } from 'react-native';
67
- import type { StoreOffer } from './billing-types';
68
- let generation = 0;
69
- let account: string | null = null;
70
- let queue: Promise<void> = Promise.resolve();
71
-
72
- function serial<T>(action: () => Promise<T>): Promise<T> {
73
- const next = queue.then(action, action);
74
- queue = next.then(() => undefined, () => undefined);
75
- return next;
76
- }
77
- function platformKey(): string {
78
- const keys: Partial<Record<string, string>> = {
79
- ios: process.env.EXPO_PUBLIC_REVENUECAT_IOS_API_KEY,
80
- android: process.env.EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEY,
81
- };
82
- return keys[Platform.OS] ?? '';
83
- }
84
- function assertIdentity(token: number): void {
85
- if (token !== generation) throw new Error('The signed-in account changed. Refresh subscriptions.');
86
- if (!account) throw new Error('Sign in before using purchases.');
87
- }
88
- async function assertStoreIdentity(token: number): Promise<void> {
89
- assertIdentity(token);
90
- if (await Purchases.getAppUserID() !== account) throw new Error('The store account differs from the verified application account.');
91
- assertIdentity(token);
92
- }
93
- export async function connectStore(userId: string): Promise<void> {
94
- const token = ++generation;
95
- account = null;
96
- await serial(async () => {
97
- await configureIdentity(userId);
98
- if (token === generation) account = userId;
99
- });
100
- }
101
- async function configureIdentity(userId: string): Promise<void> {
102
- const apiKey = platformKey();
103
- if (!apiKey) throw new Error('Configure the platform public RevenueCat SDK key and rebuild the native app.');
104
- if (await Purchases.isConfigured()) await Purchases.logIn(userId);
105
- else Purchases.configure({ apiKey, appUserID: userId });
106
- await verifyConfiguredIdentity(userId);
107
- }
108
- async function verifyConfiguredIdentity(userId: string): Promise<void> {
109
- if (await Purchases.getAppUserID() !== userId) throw new Error('Store identity synchronization failed.');
110
- }
111
- export async function disconnectStore(): Promise<void> {
112
- ++generation; account = null;
113
- const operation = serial(async () => {
114
- if (!(await Purchases.isConfigured())) return;
115
- if (!(await Purchases.isAnonymous())) await Purchases.logOut();
116
- });
117
- await bestEffortLogout(operation);
118
- }
119
- async function bestEffortLogout(operation: Promise<void>): Promise<void> {
120
- let timer: ReturnType<typeof setTimeout> | undefined;
121
- try {
122
- await Promise.race([operation.catch(() => undefined), new Promise<void>((resolve) => { timer = setTimeout(resolve, 5000); })]);
123
- } finally { clearTimeout(timer); }
124
- }
125
- async function availablePackages() {
126
- const offerings = await Purchases.getOfferings();
127
- return offerings.current?.availablePackages ?? [];
128
- }
129
- export async function storeOffers(): Promise<StoreOffer[]> {
130
- const token = generation;
131
- return serial(async () => {
132
- await assertStoreIdentity(token);
133
- const items = await availablePackages();
134
- await assertStoreIdentity(token);
135
- return items.map((item) => ({ id: item.identifier, label: item.product.title, price: item.product.priceString }));
136
- });
137
- }
138
- export async function purchaseStoreOffer(id: string): Promise<void> {
139
- const token = generation;
140
- await serial(async () => {
141
- await assertStoreIdentity(token);
142
- const item = (await availablePackages()).find((entry) => entry.identifier === id);
143
- if (!item) throw new Error('This offering is no longer available. Refresh subscriptions.');
144
- await assertStoreIdentity(token);
145
- await Purchases.purchasePackage(item);
146
- await assertStoreIdentity(token);
147
- });
148
- }
149
- export async function restoreStorePurchases(): Promise<void> {
150
- const token = generation;
151
- await serial(async () => { await assertStoreIdentity(token); await Purchases.restorePurchases(); await assertStoreIdentity(token); });
152
- }
153
- export async function manageStorePurchases(): Promise<void> {
154
- const token = generation;
155
- await serial(async () => {
156
- await assertStoreIdentity(token);
157
- const info = await Purchases.getCustomerInfo();
158
- await assertStoreIdentity(token);
159
- if (!info.managementURL) throw new Error('No store subscription management link is available.');
160
- const url = new URL(info.managementURL);
161
- if (url.protocol !== 'https:') throw new Error('Store management requires HTTPS.');
162
- await Linking.openURL(url.href);
163
- });
164
- }
165
- `;
166
- }
167
- function billingScreenSource() {
168
- return `import { useCallback, useEffect, useRef, useState } from 'react';
169
- import { Redirect } from 'expo-router';
170
- import { View } from 'react-native';
171
- import { Screen, Text } from '@workspace/native-ui';
172
- import type { BillingIdentity, BillingEntitlements } from '@workspace/contracts';
173
- import { AuthConfiguration } from '@/components/auth-configuration';
174
- import { Button } from '@/components/ui/button';
175
- import { getAuthClient } from '@/lib/auth-client';
176
- import { billingApi } from '@/lib/billing-api';
177
- import { connectStore, disconnectStore, manageStorePurchases, purchaseStoreOffer, restoreStorePurchases, storeOffers, type StoreOffer } from '@/lib/billing-platform';
178
-
179
- export default function BillingRoute() { return <AuthConfiguration><Billing /></AuthConfiguration>; }
180
- type Data = { identity: BillingIdentity; state: BillingEntitlements; offers: StoreOffer[] };
181
- function billingError(error: unknown): string {
182
- const message = error instanceof Error ? error.message : 'Billing is unavailable. Try again later.';
183
- if (message === 'API request failed (409).') return 'A checkout, subscription, or billing update already exists. Retry shortly, continue your checkout, or manage your current subscription.';
184
- return message;
185
- }
186
- function assertAccount(identity: BillingIdentity, userId: string, isCurrent: () => boolean) {
187
- if (!isCurrent()) throw new Error('The signed-in account changed.');
188
- if (identity.appUserId !== userId) throw new Error('The signed-in billing account changed.');
189
- }
190
- async function connectIdentity(identity: BillingIdentity, userId: string, isCurrent: () => boolean) {
191
- assertAccount(identity, userId, isCurrent);
192
- if (identity.providers.revenuecat) await connectStore(identity.appUserId);
193
- assertAccount(identity, userId, isCurrent);
194
- }
195
- async function loadBilling(userId: string, isCurrent: () => boolean): Promise<Data> {
196
- const identity = await billingApi.identity();
197
- await connectIdentity(identity, userId, isCurrent);
198
- const state = await billingApi.entitlements();
199
- const offers = identity.providers.revenuecat ? await storeOffers() : [];
200
- return { identity, state, offers };
201
- }
202
- function Billing() {
203
- const { data: session, isPending } = getAuthClient().useSession();
204
- const userId = session?.user.id;
205
- const [data, setData] = useState<Data | null>(null);
206
- const [message, setMessage] = useState('');
207
- const [pending, setPending] = useState(false);
208
- const [reload, setReload] = useState(0);
209
- const generation = useRef(0);
210
- const invalidate = useCallback(() => { ++generation.current; void disconnectStore(); }, []);
211
- useEffect(() => {
212
- const token = ++generation.current;
213
- if (userId) void loadBilling(userId, () => token === generation.current).then(
214
- (current) => { if (token === generation.current) setData(current); },
215
- (error) => { if (token === generation.current) setMessage(billingError(error)); },
216
- );
217
- return invalidate;
218
- }, [userId, reload, invalidate]);
219
- function updateCurrent(token: number, action: () => void) { if (token === generation.current) action(); }
220
- async function run(action: () => Promise<void>) {
221
- const token = generation.current;
222
- setPending(true); setMessage('');
223
- try {
224
- await action();
225
- const state = await billingApi.refresh();
226
- updateCurrent(token, () => setData((previous) => previous && { ...previous, state }));
227
- } catch (error) { updateCurrent(token, () => setMessage(billingError(error))); }
228
- finally { updateCurrent(token, () => setPending(false)); }
229
- }
230
- if (isPending) return <Text>Restoring session…</Text>;
231
- if (!session) return <Redirect href="/sign-in" />;
232
- return <SessionBilling userId={session.user.id} data={data} message={message} pending={pending} run={run} retry={() => setReload((value) => value + 1)} />;
233
- }
234
- function SessionBilling({ userId, data, message, pending, run, retry }: Actions & { userId: string; data: Data | null; message: string; retry: () => void }) {
235
- if (data?.identity.appUserId !== userId) return <View style={{ padding: 24, gap: 12 }}><Text>{message || 'Loading subscriptions…'}</Text><Button onPress={retry}>Retry subscriptions</Button></View>;
236
- return <BillingContent data={data} message={message} pending={pending} run={run} />;
237
- }
238
- function Entitlements({ state }: { state: BillingEntitlements }) {
239
- return <View><Text accessibilityRole="header">Last server-verified access</Text>{state.entitlements.map((item) => <Text key={item.key}>{item.key}: {item.active ? 'Active' : 'Inactive'}</Text>)}<Text>Checked: {state.checkedAt}</Text></View>;
240
- }
241
- type Actions = { pending: boolean; run: (action: () => Promise<void>) => Promise<void> };
242
- function NativePlans({ data, pending, run }: Actions & { data: Data }) {
243
- if (!data.identity.providers.revenuecat) return <Text>Native store purchases are not selected.</Text>;
244
- return <View style={{ gap: 12 }}>{data.offers.map((offer) => <Button key={offer.id} disabled={pending} onPress={() => void run(() => purchaseStoreOffer(offer.id))}>{offer.label + ' — ' + offer.price}</Button>)}<Button disabled={pending} onPress={() => void run(restoreStorePurchases)}>Restore purchases</Button><Button disabled={pending} onPress={() => void run(manageStorePurchases)}>Manage store subscription</Button></View>;
245
- }
246
- function BillingContent({ data, message, pending, run }: Actions & { data: Data; message: string }) {
247
- return <Screen>
248
- <Text accessibilityRole="header">Subscriptions</Text>
249
- <Entitlements state={data.state} />
250
- <NativePlans data={data} pending={pending} run={run} />
251
- <Button disabled={pending} onPress={() => void run(async () => undefined)}>Refresh server access</Button>
252
- <Text accessibilityLiveRegion="polite">{message}</Text>
253
- <Text>Purchases grant access only after server verification. Store account transfers follow the configured provider policy.</Text>
254
- </Screen>;
255
- }
256
- `;
257
- }
@@ -1,3 +0,0 @@
1
- import type { RecipeContext } from '../registry/types.js';
2
- /** Native uses the public product origin; all browser transport belongs to Next. */
3
- export declare function scaffoldExpoRuntime({ root }: RecipeContext): void;
@@ -1,43 +0,0 @@
1
- import { writeEnvironmentFile } from './environment.js';
2
- import { patchPackage, put } from './files.js';
3
- /** Native uses the public product origin; all browser transport belongs to Next. */
4
- export function scaffoldExpoRuntime({ root }) {
5
- const directory = 'apps/mobile';
6
- patchPackage(root, `${directory}/package.json`, {
7
- dependencies: { '@workspace/contracts': 'workspace:*' },
8
- });
9
- put(root, `${directory}/lib/api-client.ts`, `import { createApiClient } from '@workspace/contracts';
10
-
11
- type Options = NonNullable<Parameters<typeof createApiClient>[1]>;
12
-
13
- function validProtocol(url: URL): boolean {
14
- return url.protocol === 'https:' || (__DEV__ && url.protocol === 'http:');
15
- }
16
- export function nativeApiOrigin(): string {
17
- const configured = process.env.EXPO_PUBLIC_API_URL;
18
- if (!configured) throw new Error('Configure EXPO_PUBLIC_API_URL with the product origin reachable from this device.');
19
- const origin = new URL(configured);
20
- if (!validProtocol(origin)) throw new Error('EXPO_PUBLIC_API_URL requires HTTPS outside development.');
21
- if ([origin.username, origin.password, origin.pathname !== '/', origin.search, origin.hash].some(Boolean))
22
- throw new Error('EXPO_PUBLIC_API_URL must be an origin without credentials, path, query or fragment.');
23
- return origin.origin;
24
- }
25
- function apiBaseURL(): string {
26
- return nativeApiOrigin() + '/api';
27
- }
28
-
29
- // A native auth adapter can provide its own session headers. No server secret belongs here.
30
- export function createApplicationApiClient(options: Options = {}) {
31
- const client = () => createApiClient(apiBaseURL(), {
32
- ...options, credentials: 'omit',
33
- });
34
- return {
35
- health: (init?: RequestInit) => client().health(init),
36
- session: (init?: RequestInit) => client().session(init),
37
- };
38
- }
39
-
40
- export const api = createApplicationApiClient();
41
- `);
42
- writeEnvironmentFile(root, `${directory}/.env.example`, { EXPO_PUBLIC_API_URL: '' });
43
- }
@@ -1,2 +0,0 @@
1
- import type { RecipeContext } from '../registry/types.js';
2
- export declare function scaffoldPrivateFiles({ root }: RecipeContext): void;
@@ -1,11 +0,0 @@
1
- import { readFileSync } from 'node:fs';
2
- import path from 'node:path';
3
- import { put } from './files.js';
4
- import { PRIVATE_FILES_SOURCE } from './private-files.js';
5
- export function scaffoldPrivateFiles({ root }) {
6
- put(root, 'apps/api/src/private-files.ts', PRIVATE_FILES_SOURCE);
7
- const file = 'apps/api/src/index.ts';
8
- const source = readFileSync(path.join(root, file), 'utf8');
9
- put(root, file, "import { privateFileRoutes } from './private-files';\n" +
10
- source.replace('export default app;', "app.route('/api/files', privateFileRoutes);\nexport default app;"));
11
- }
@@ -1,3 +0,0 @@
1
- /** Generated apps receive a scoped capability, never the broker's provider credentials. */
2
- export declare function scaffoldManagedEmail(root: string): void;
3
- export declare const MANAGED_EMAIL_SOURCE = "export type EmailTemplate = 'verify-email' | 'reset-password';\nexport interface EmailEnvironment {\n ANHEDRAL_EMAIL?: { fetch(request: Request): Promise<Response> };\n ANHEDRAL_EMAIL_SCOPE?: string;\n ANHEDRAL_EMAIL_CAPABILITY?: string;\n}\nfunction validConfiguration(env: EmailEnvironment): boolean {\n return [typeof env.ANHEDRAL_EMAIL?.fetch === 'function', /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(env.ANHEDRAL_EMAIL_SCOPE ?? ''), /^[a-f0-9]{72}$/.test(env.ANHEDRAL_EMAIL_CAPABILITY ?? '')].every(Boolean);\n}\nexport function createManagedEmail(env: EmailEnvironment) {\n const { ANHEDRAL_EMAIL: binding, ANHEDRAL_EMAIL_SCOPE: scope, ANHEDRAL_EMAIL_CAPABILITY: capability } = env;\n if (![binding, scope, capability].some(Boolean)) return undefined;\n if (!validConfiguration(env))\n throw new Error('Managed email configuration is incomplete.');\n return async (template: EmailTemplate, to: string, url: string) => {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify([template, to, url])));\n const id = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('');\n try {\n const response = await binding!.fetch(new Request('https://email.internal/scopes/' + encodeURIComponent(scope!) + '/send', {\n method: 'POST', redirect: 'error',\n headers: { authorization: 'Bearer ' + capability, 'content-type': 'application/json' },\n body: JSON.stringify({ id, template, to, url }), signal: AbortSignal.timeout(15000),\n }));\n if (!response.ok) throw new Error('Email rejected');\n } catch { throw new Error('Application email could not be accepted. Please try again.'); }\n };\n}\n";
@@ -1,47 +0,0 @@
1
- import { put, sharedPackage } from './files.js';
2
- /** Generated apps receive a scoped capability, never the broker's provider credentials. */
3
- export function scaffoldManagedEmail(root) {
4
- sharedPackage(root, 'managed-email', MANAGED_EMAIL_SOURCE, {});
5
- put(root, 'packages/managed-email/README.md', `# Managed authentication email
6
-
7
- Anhedral provisions the ANHEDRAL_EMAIL service binding, ANHEDRAL_EMAIL_SCOPE and
8
- ANHEDRAL_EMAIL_CAPABILITY in the API Worker only. No provider keys belong in clients.
9
- The broker owns sender/provider configuration, scope/origin checks, quotas and receipts.
10
- Configure the scope with this app's public Better Auth origin and exact native URL scheme.
11
-
12
- With no binding or scope/capability, standalone email/password sessions keep their
13
- existing behavior. Any partial configuration fails closed. A complete configuration
14
- requires verified email and enables password reset with session revocation. Do not
15
- remove configuration to bypass verification. Use a local mail sink in tests; never
16
- log token URLs or use a production capability in fixtures. Request acceptance does
17
- not establish inbox delivery. Initialization never provisions the broker or sends mail.
18
- `);
19
- }
20
- export const MANAGED_EMAIL_SOURCE = `export type EmailTemplate = 'verify-email' | 'reset-password';
21
- export interface EmailEnvironment {
22
- ANHEDRAL_EMAIL?: { fetch(request: Request): Promise<Response> };
23
- ANHEDRAL_EMAIL_SCOPE?: string;
24
- ANHEDRAL_EMAIL_CAPABILITY?: string;
25
- }
26
- function validConfiguration(env: EmailEnvironment): boolean {
27
- return [typeof env.ANHEDRAL_EMAIL?.fetch === 'function', /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(env.ANHEDRAL_EMAIL_SCOPE ?? ''), /^[a-f0-9]{72}$/.test(env.ANHEDRAL_EMAIL_CAPABILITY ?? '')].every(Boolean);
28
- }
29
- export function createManagedEmail(env: EmailEnvironment) {
30
- const { ANHEDRAL_EMAIL: binding, ANHEDRAL_EMAIL_SCOPE: scope, ANHEDRAL_EMAIL_CAPABILITY: capability } = env;
31
- if (![binding, scope, capability].some(Boolean)) return undefined;
32
- if (!validConfiguration(env))
33
- throw new Error('Managed email configuration is incomplete.');
34
- return async (template: EmailTemplate, to: string, url: string) => {
35
- const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify([template, to, url])));
36
- const id = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('');
37
- try {
38
- const response = await binding!.fetch(new Request('https://email.internal/scopes/' + encodeURIComponent(scope!) + '/send', {
39
- method: 'POST', redirect: 'error',
40
- headers: { authorization: 'Bearer ' + capability, 'content-type': 'application/json' },
41
- body: JSON.stringify({ id, template, to, url }), signal: AbortSignal.timeout(15000),
42
- }));
43
- if (!response.ok) throw new Error('Email rejected');
44
- } catch { throw new Error('Application email could not be accepted. Please try again.'); }
45
- };
46
- }
47
- `;
@@ -1,2 +0,0 @@
1
- /** Anhedral-maintained native shadcn port. Never imported by the DOM application. */
2
- export declare function scaffoldNativeUI(root: string): void;
@@ -1,69 +0,0 @@
1
- import { readFileSync } from 'node:fs';
2
- import { fileURLToPath } from 'node:url';
3
- import { NATIVE_ESLINT_VERSION, NATIVE_UI_DEPENDENCIES, MOBILE_APP_DEPENDENCIES, } from '../dependencies.js';
4
- import { json, put } from './files.js';
5
- import { writeReactLintConfig } from '../platforms/lint.js';
6
- /** Anhedral-maintained native shadcn port. Never imported by the DOM application. */
7
- export function scaffoldNativeUI(root) {
8
- const components = [
9
- 'button',
10
- 'card',
11
- 'dialog',
12
- 'input',
13
- 'label',
14
- 'layout',
15
- 'text',
16
- 'theme-switcher',
17
- ];
18
- for (const file of [
19
- 'theme.tsx',
20
- 'theme-storage.ts',
21
- 'LICENSE.shadcn',
22
- 'UPSTREAM.json',
23
- ...components.map((name) => `native/${name}.tsx`),
24
- ]) {
25
- const source = readFileSync(fileURLToPath(new URL(`../../assets/ui/${file}`, import.meta.url)), 'utf8');
26
- put(root, `packages/native-ui/${file.endsWith('.tsx') || file.endsWith('.ts') ? 'src/' : ''}${file}`, source);
27
- }
28
- put(root, 'packages/native-ui/src/index.ts', `export * from './theme';\n` +
29
- components.map((name) => `export * from './native/${name}';\n`).join(''));
30
- json(root, 'packages/native-ui/package.json', {
31
- name: '@workspace/native-ui',
32
- private: true,
33
- type: 'module',
34
- exports: { '.': './src/index.ts' },
35
- scripts: { typecheck: 'tsc --noEmit', lint: 'eslint . --max-warnings 0' },
36
- dependencies: {
37
- ...NATIVE_UI_DEPENDENCIES.dependencies,
38
- 'react-native-safe-area-context': MOBILE_APP_DEPENDENCIES.dependencies['react-native-safe-area-context'],
39
- '@workspace/styling': 'workspace:*',
40
- },
41
- peerDependencies: {
42
- react: MOBILE_APP_DEPENDENCIES.dependencies.react,
43
- 'react-native': MOBILE_APP_DEPENDENCIES.dependencies['react-native'],
44
- },
45
- devDependencies: {
46
- typescript: MOBILE_APP_DEPENDENCIES.devDependencies.typescript,
47
- '@types/react': MOBILE_APP_DEPENDENCIES.devDependencies['@types/react'],
48
- react: MOBILE_APP_DEPENDENCIES.dependencies.react,
49
- 'react-native': MOBILE_APP_DEPENDENCIES.dependencies['react-native'],
50
- '@workspace/eslint-config': 'workspace:*',
51
- eslint: NATIVE_ESLINT_VERSION,
52
- },
53
- });
54
- json(root, 'packages/native-ui/tsconfig.json', {
55
- compilerOptions: {
56
- target: 'ES2022',
57
- lib: ['ES2022'],
58
- module: 'ESNext',
59
- moduleResolution: 'Bundler',
60
- strict: true,
61
- jsx: 'react-jsx',
62
- noEmit: true,
63
- skipLibCheck: true,
64
- esModuleInterop: true,
65
- },
66
- include: ['src/**/*.ts', 'src/**/*.tsx'],
67
- });
68
- writeReactLintConfig(root + '/packages/native-ui');
69
- }
@@ -1 +0,0 @@
1
- export declare function scaffoldPasswordReset(root: string): void;
@@ -1,99 +0,0 @@
1
- import { readFileSync } from 'node:fs';
2
- import path from 'node:path';
3
- import { put } from './files.js';
4
- export function scaffoldPasswordReset(root) {
5
- put(root, 'packages/contracts/src/password-reset.ts', PASSWORD_RESET_CLIENT);
6
- const contracts = readFileSync(path.join(root, 'packages/contracts/src/index.ts'), 'utf8');
7
- put(root, 'packages/contracts/src/index.ts', contracts + "\nexport { submitPasswordReset, passwordResetLabel } from './password-reset';\n");
8
- put(root, 'apps/web/app/reset-password/page.tsx', `import { PasswordReset } from '@/components/password-reset';
9
- export default async function Page({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
10
- const params = await searchParams;
11
- return <PasswordReset key={JSON.stringify([params.token, params.error])} token={typeof params.token === 'string' ? params.token : undefined} invalid={Boolean(params.error)} />;
12
- }
13
- `);
14
- put(root, 'apps/web/components/password-reset.tsx', WEB_PASSWORD_RESET);
15
- put(root, 'apps/mobile/app/reset-password.tsx', NATIVE_PASSWORD_RESET);
16
- }
17
- const WEB_PASSWORD_RESET = `'use client';
18
- import { useState, type FormEvent } from 'react';
19
- import Link from 'next/link';
20
- import { authClient } from '@/lib/auth-client';
21
- import { Button } from '@/components/ui/button';
22
- import { Input } from '@/components/ui/input';
23
- import { Label } from '@/components/ui/label';
24
- import { submitPasswordReset, passwordResetLabel } from '@workspace/contracts';
25
- function ResetFields({ token }: { token?: string }) {
26
- return token ? <Label>New password<Input name="password" type="password" autoComplete="new-password" minLength={8} required /></Label> : <Label>Email<Input name="email" type="email" autoComplete="email" required /></Label>;
27
- }
28
- export function PasswordReset({ token, invalid }: { token?: string; invalid: boolean }) {
29
- const [pending, setPending] = useState(false);
30
- const [complete, setComplete] = useState(false);
31
- const [message, setMessage] = useState(invalid ? 'This link is invalid or expired. Request a new one.' : '');
32
- async function submit(event: FormEvent<HTMLFormElement>) {
33
- event.preventDefault(); if (pending) return;
34
- const form = event.currentTarget; const data = new FormData(form);
35
- setPending(true); setMessage('');
36
- try {
37
- const message = await submitPasswordReset(authClient, { token, email: String(data.get('email')), password: String(data.get('password')) }, new URL('/reset-password', window.location.origin).href);
38
- form.reset(); setComplete(Boolean(token)); setMessage(message);
39
- } catch { setMessage('Unable to complete this request. Try again or request a new link.'); }
40
- finally { setPending(false); }
41
- }
42
- return <section className="stack"><h1>Reset password</h1>{!complete && <form onSubmit={submit}>
43
- <ResetFields token={token} />
44
- <Button disabled={pending} type="submit">{passwordResetLabel(pending, token)}</Button>
45
- </form>}<p role="status">{message}</p><Link href="/reset-password">Request a new link</Link><Link href="/sign-in">Back to sign in</Link></section>;
46
- }
47
- `;
48
- const NATIVE_PASSWORD_RESET = `import { useState } from 'react';
49
- import { Link, useLocalSearchParams } from 'expo-router';
50
- import * as Linking from 'expo-linking';
51
- import { Screen, Text, Input } from '@workspace/native-ui';
52
- import { Button } from '@/components/ui/button';
53
- import { getAuthClient } from '@/lib/auth-client';
54
- import { AuthConfiguration } from '@/components/auth-configuration';
55
- import { submitPasswordReset, passwordResetLabel } from '@workspace/contracts';
56
- function disabled(pending: boolean, token: string | undefined, password: string, email: string): boolean { return pending || (token ? password.length < 8 : !email); }
57
- function ResetFields({ token, password, setPassword, email, setEmail }: { token?: string; password: string; setPassword: (value: string) => void; email: string; setEmail: (value: string) => void }) {
58
- return token ? <Input accessibilityLabel="New password" value={password} onChangeText={setPassword} secureTextEntry autoComplete="new-password" /> : <Input accessibilityLabel="Email" value={email} onChangeText={setEmail} keyboardType="email-address" autoCapitalize="none" autoComplete="email" />;
59
- }
60
- export default function ResetPasswordRoute() {
61
- const params = useLocalSearchParams<{ token?: string; error?: string }>();
62
- return <AuthConfiguration><ResetPassword key={JSON.stringify([params.token, params.error])} /></AuthConfiguration>;
63
- }
64
- function ResetPassword() {
65
- const params = useLocalSearchParams<{ token?: string; error?: string }>();
66
- const token = typeof params.token === 'string' ? params.token : undefined;
67
- const [email, setEmail] = useState(''); const [password, setPassword] = useState('');
68
- const [message, setMessage] = useState(params.error ? 'This link is invalid or expired. Request a new one.' : '');
69
- const [complete, setComplete] = useState(false); const [pending, setPending] = useState(false);
70
- async function submit() {
71
- if (pending) return; setPending(true); setMessage('');
72
- try {
73
- const message = await submitPasswordReset(getAuthClient(), { token, email, password }, Linking.createURL('reset-password'));
74
- setPassword(''); setComplete(Boolean(token)); setMessage(message);
75
- } catch { setMessage('Unable to complete this request. Try again or request a new link.'); }
76
- finally { setPending(false); }
77
- }
78
- return <Screen><Text accessibilityRole="header">Reset password</Text>{!complete && <>
79
- <ResetFields token={token} password={password} setPassword={setPassword} email={email} setEmail={setEmail} />
80
- <Button disabled={disabled(pending, token, password, email)} onPress={() => void submit()}>{passwordResetLabel(pending, token)}</Button>
81
- </>}<Text accessibilityLiveRegion="polite">{message}</Text><Link href="/reset-password">Request a new link</Link><Link href="/sign-in">Back to sign in</Link></Screen>;
82
- }
83
- `;
84
- const PASSWORD_RESET_CLIENT = `interface PasswordResetClient {
85
- resetPassword(input: { token: string; newPassword: string }): Promise<{ error: unknown }>;
86
- requestPasswordReset(input: { email: string; redirectTo: string }): Promise<{ error: unknown }>;
87
- }
88
- export async function submitPasswordReset(client: PasswordResetClient, values: { token?: string; email: string; password: string }, redirectTo: string): Promise<string> {
89
- const result = values.token
90
- ? await client.resetPassword({ token: values.token, newPassword: values.password })
91
- : await client.requestPasswordReset({ email: values.email, redirectTo });
92
- if (result.error) throw Error('Reset unavailable');
93
- return values.token ? 'Password updated. Sign in again.' : 'If an account exists, check your email for the reset link.';
94
- }
95
- export function passwordResetLabel(pending: boolean, token?: string): string {
96
- if (pending) return 'Working…';
97
- return token ? 'Update password' : 'Send reset link';
98
- }
99
- `;
@@ -1,2 +0,0 @@
1
- /** Generated server code: the caller never selects the owner's R2 namespace. */
2
- export declare const PRIVATE_FILES_SOURCE = "import { Hono } from 'hono';\nimport { createAuth } from '@workspace/auth';\nimport { createDatabase } from '@workspace/db';\n\nconst MAX_FILE_BYTES = 1024 * 1024;\ntype Identity = (request: Request, env: Env) => Promise<string | null>;\nasync function authenticate(request: Request, env: Env): Promise<string | null> {\n const session = await createAuth(createDatabase(env.DB), env.BETTER_AUTH_SECRET, env.BETTER_AUTH_URL, env).api.getSession({ headers: request.headers });\n return session?.user.id ?? null;\n}\nasync function readFileBody(request: Request): Promise<Uint8Array | null> {\n if (!request.body) return new Uint8Array();\n return readFileStream(request.body);\n}\nasync function readFileStream(body: ReadableStream<Uint8Array>): Promise<Uint8Array | null> {\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > MAX_FILE_BYTES) { await reader.cancel(); return null; }\n chunks.push(value);\n }\n } finally { reader.releaseLock(); }\n return combineChunks(chunks, size);\n}\nfunction combineChunks(chunks: Uint8Array[], size: number): Uint8Array {\n const result = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.byteLength; }\n return result;\n}\nfunction trustedMutation(request: Request, baseURL: string): boolean {\n if (request.headers.get('sec-fetch-site') === 'cross-site') return false;\n const origin = request.headers.get('origin');\n return !origin || origin === new URL(baseURL).origin;\n}\nfunction createPrivateFileRoutes(identity: Identity = authenticate) {\n const routes = new Hono<{ Bindings: Env; Variables: { fileOwner: string } }>();\n routes.use('*', async (c, next) => {\n c.header('cache-control', 'private, no-store');\n const userId = await identity(c.req.raw, c.env);\n if (!userId) return c.json({ error: 'Unauthorized' }, 401);\n c.set('fileOwner', encodeURIComponent(userId));\n const mutation = !['GET', 'HEAD'].includes(c.req.method);\n if (mutation && !trustedMutation(c.req.raw, c.env.BETTER_AUTH_URL)) return c.json({ error: 'Unexpected request origin' }, 403);\n await next();\n });\n routes.post('/', async (c) => {\n // Raw bytes keep upload memory bounded. Only the server creates keys.\n const bytes = await readFileBody(c.req.raw);\n if (!bytes) return c.json({ error: 'File exceeds 1 MiB' }, 413);\n if (!bytes.byteLength) return c.json({ error: 'An empty file is not allowed' }, 400);\n const id = crypto.randomUUID();\n await c.env.FILES.put(c.get('fileOwner') + '/' + id, bytes, { httpMetadata: { contentType: 'application/octet-stream' } });\n return c.json({ id, size: bytes.byteLength }, 201);\n });\n routes.use('/:id', async (c, next) => {\n if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c.req.param('id') ?? '')) return c.json({ error: 'Not found' }, 404);\n await next();\n });\n routes.get('/:id', async (c) => {\n const object = await c.env.FILES.get(c.get('fileOwner') + '/' + c.req.param('id'));\n if (!object) return c.json({ error: 'Not found' }, 404);\n return new Response(object.body, { headers: { 'content-type': 'application/octet-stream', 'content-disposition': 'attachment; filename=\"download\"', 'x-content-type-options': 'nosniff', 'cache-control': 'private, no-store' } });\n });\n routes.delete('/:id', async (c) => {\n await c.env.FILES.delete(c.get('fileOwner') + '/' + c.req.param('id'));\n return c.body(null, 204);\n });\n return routes;\n}\nexport const privateFileRoutes = createPrivateFileRoutes();\n";
@@ -1,78 +0,0 @@
1
- /** Generated server code: the caller never selects the owner's R2 namespace. */
2
- export const PRIVATE_FILES_SOURCE = `import { Hono } from 'hono';
3
- import { createAuth } from '@workspace/auth';
4
- import { createDatabase } from '@workspace/db';
5
-
6
- const MAX_FILE_BYTES = 1024 * 1024;
7
- type Identity = (request: Request, env: Env) => Promise<string | null>;
8
- async function authenticate(request: Request, env: Env): Promise<string | null> {
9
- const session = await createAuth(createDatabase(env.DB), env.BETTER_AUTH_SECRET, env.BETTER_AUTH_URL, env).api.getSession({ headers: request.headers });
10
- return session?.user.id ?? null;
11
- }
12
- async function readFileBody(request: Request): Promise<Uint8Array | null> {
13
- if (!request.body) return new Uint8Array();
14
- return readFileStream(request.body);
15
- }
16
- async function readFileStream(body: ReadableStream<Uint8Array>): Promise<Uint8Array | null> {
17
- const reader = body.getReader();
18
- const chunks: Uint8Array[] = [];
19
- let size = 0;
20
- try {
21
- while (true) {
22
- const { done, value } = await reader.read();
23
- if (done) break;
24
- size += value.byteLength;
25
- if (size > MAX_FILE_BYTES) { await reader.cancel(); return null; }
26
- chunks.push(value);
27
- }
28
- } finally { reader.releaseLock(); }
29
- return combineChunks(chunks, size);
30
- }
31
- function combineChunks(chunks: Uint8Array[], size: number): Uint8Array {
32
- const result = new Uint8Array(size);
33
- let offset = 0;
34
- for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.byteLength; }
35
- return result;
36
- }
37
- function trustedMutation(request: Request, baseURL: string): boolean {
38
- if (request.headers.get('sec-fetch-site') === 'cross-site') return false;
39
- const origin = request.headers.get('origin');
40
- return !origin || origin === new URL(baseURL).origin;
41
- }
42
- function createPrivateFileRoutes(identity: Identity = authenticate) {
43
- const routes = new Hono<{ Bindings: Env; Variables: { fileOwner: string } }>();
44
- routes.use('*', async (c, next) => {
45
- c.header('cache-control', 'private, no-store');
46
- const userId = await identity(c.req.raw, c.env);
47
- if (!userId) return c.json({ error: 'Unauthorized' }, 401);
48
- c.set('fileOwner', encodeURIComponent(userId));
49
- const mutation = !['GET', 'HEAD'].includes(c.req.method);
50
- if (mutation && !trustedMutation(c.req.raw, c.env.BETTER_AUTH_URL)) return c.json({ error: 'Unexpected request origin' }, 403);
51
- await next();
52
- });
53
- routes.post('/', async (c) => {
54
- // Raw bytes keep upload memory bounded. Only the server creates keys.
55
- const bytes = await readFileBody(c.req.raw);
56
- if (!bytes) return c.json({ error: 'File exceeds 1 MiB' }, 413);
57
- if (!bytes.byteLength) return c.json({ error: 'An empty file is not allowed' }, 400);
58
- const id = crypto.randomUUID();
59
- await c.env.FILES.put(c.get('fileOwner') + '/' + id, bytes, { httpMetadata: { contentType: 'application/octet-stream' } });
60
- return c.json({ id, size: bytes.byteLength }, 201);
61
- });
62
- routes.use('/:id', async (c, next) => {
63
- if (!/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c.req.param('id') ?? '')) return c.json({ error: 'Not found' }, 404);
64
- await next();
65
- });
66
- routes.get('/:id', async (c) => {
67
- const object = await c.env.FILES.get(c.get('fileOwner') + '/' + c.req.param('id'));
68
- if (!object) return c.json({ error: 'Not found' }, 404);
69
- return new Response(object.body, { headers: { 'content-type': 'application/octet-stream', 'content-disposition': 'attachment; filename="download"', 'x-content-type-options': 'nosniff', 'cache-control': 'private, no-store' } });
70
- });
71
- routes.delete('/:id', async (c) => {
72
- await c.env.FILES.delete(c.get('fileOwner') + '/' + c.req.param('id'));
73
- return c.body(null, 204);
74
- });
75
- return routes;
76
- }
77
- export const privateFileRoutes = createPrivateFileRoutes();
78
- `;