anhedral 0.15.0 → 0.16.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 (308) hide show
  1. package/README.md +29 -38
  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 +7 -1
  39. package/assets/ui/catalog.json +891 -0
  40. package/assets/ui/extensions/registry.json +6 -0
  41. package/assets/ui/native/_controls.tsx +521 -0
  42. package/assets/ui/native/_core.tsx +118 -0
  43. package/assets/ui/native/_data.tsx +200 -0
  44. package/assets/ui/native/_display.tsx +453 -0
  45. package/assets/ui/native/_feedback.tsx +242 -0
  46. package/assets/ui/native/_legacy-dialog.tsx +38 -0
  47. package/assets/ui/native/_motion.tsx +520 -0
  48. package/assets/ui/native/_overlay.tsx +402 -0
  49. package/assets/ui/native/_selection.tsx +366 -0
  50. package/assets/ui/native/accordion.tsx +1 -0
  51. package/assets/ui/native/alert-dialog.tsx +11 -0
  52. package/assets/ui/native/alert.tsx +1 -0
  53. package/assets/ui/native/aspect-ratio.tsx +1 -0
  54. package/assets/ui/native/attachment.tsx +8 -0
  55. package/assets/ui/native/avatar.tsx +8 -0
  56. package/assets/ui/native/badge.tsx +1 -0
  57. package/assets/ui/native/breadcrumb.tsx +9 -0
  58. package/assets/ui/native/bubble.tsx +1 -0
  59. package/assets/ui/native/button-group.tsx +1 -0
  60. package/assets/ui/native/button.tsx +2 -1
  61. package/assets/ui/native/calendar.tsx +170 -0
  62. package/assets/ui/native/card.tsx +16 -5
  63. package/assets/ui/native/carousel.tsx +1 -0
  64. package/assets/ui/native/chart.tsx +193 -0
  65. package/assets/ui/native/checkbox.tsx +1 -0
  66. package/assets/ui/native/code-block.tsx +137 -0
  67. package/assets/ui/native/collapsible.tsx +1 -0
  68. package/assets/ui/native/combobox.tsx +1 -0
  69. package/assets/ui/native/command.tsx +11 -0
  70. package/assets/ui/native/context-menu.tsx +16 -0
  71. package/assets/ui/native/data-table.tsx +1 -0
  72. package/assets/ui/native/date-picker.tsx +43 -0
  73. package/assets/ui/native/dialog.tsx +14 -74
  74. package/assets/ui/native/direction.tsx +1 -0
  75. package/assets/ui/native/drawer.tsx +10 -0
  76. package/assets/ui/native/dropdown-menu.tsx +16 -0
  77. package/assets/ui/native/empty.tsx +8 -0
  78. package/assets/ui/native/field.tsx +13 -0
  79. package/assets/ui/native/hover-card.tsx +1 -0
  80. package/assets/ui/native/input-group.tsx +8 -0
  81. package/assets/ui/native/input-otp.tsx +1 -0
  82. package/assets/ui/native/input.tsx +2 -1
  83. package/assets/ui/native/item.tsx +12 -0
  84. package/assets/ui/native/kbd.tsx +1 -0
  85. package/assets/ui/native/marker.tsx +1 -0
  86. package/assets/ui/native/menubar.tsx +17 -0
  87. package/assets/ui/native/message-scroller.tsx +6 -0
  88. package/assets/ui/native/message.tsx +10 -0
  89. package/assets/ui/native/native-select.tsx +1 -0
  90. package/assets/ui/native/navigation-menu.tsx +10 -0
  91. package/assets/ui/native/pagination.tsx +9 -0
  92. package/assets/ui/native/popover.tsx +1 -0
  93. package/assets/ui/native/progress.tsx +1 -0
  94. package/assets/ui/native/questionnaire.tsx +130 -0
  95. package/assets/ui/native/radio-group.tsx +1 -0
  96. package/assets/ui/native/registry.json +1103 -0
  97. package/assets/ui/native/resizable.tsx +1 -0
  98. package/assets/ui/native/scroll-area.tsx +1 -0
  99. package/assets/ui/native/select.tsx +11 -0
  100. package/assets/ui/native/separator.tsx +1 -0
  101. package/assets/ui/native/sheet.tsx +10 -0
  102. package/assets/ui/native/sidebar.tsx +22 -0
  103. package/assets/ui/native/skeleton.tsx +1 -0
  104. package/assets/ui/native/slider.tsx +1 -0
  105. package/assets/ui/native/spinner.tsx +1 -0
  106. package/assets/ui/native/switch.tsx +1 -0
  107. package/assets/ui/native/table.tsx +10 -0
  108. package/assets/ui/native/tabs.tsx +1 -0
  109. package/assets/ui/native/textarea.tsx +1 -0
  110. package/assets/ui/native/toast.tsx +11 -0
  111. package/assets/ui/native/toggle-group.tsx +1 -0
  112. package/assets/ui/native/toggle.tsx +1 -0
  113. package/assets/ui/native/tooltip.tsx +1 -0
  114. package/assets/ui/native/trace.tsx +20 -0
  115. package/assets/ui/native/typography.tsx +15 -0
  116. package/dist/bin.js +7 -12
  117. package/dist/capabilities.d.ts +4 -33
  118. package/dist/capabilities.js +2 -66
  119. package/dist/capability-catalog.d.ts +83 -0
  120. package/dist/capability-catalog.js +121 -0
  121. package/dist/capability-command.d.ts +3 -0
  122. package/dist/capability-command.js +188 -0
  123. package/dist/capability-editor.d.ts +17 -0
  124. package/dist/capability-editor.js +97 -0
  125. package/dist/capability-recipes.d.ts +4 -0
  126. package/dist/capability-recipes.js +520 -0
  127. package/dist/capability-references.d.ts +4 -0
  128. package/dist/capability-references.js +7 -0
  129. package/dist/cli-commands.d.ts +1 -2
  130. package/dist/cli-commands.js +10 -104
  131. package/dist/cli-output.d.ts +1 -2
  132. package/dist/cli-output.js +6 -251
  133. package/dist/command-schema.js +39 -322
  134. package/dist/dependencies.d.ts +29 -6
  135. package/dist/dependencies.js +61 -14
  136. package/dist/index.d.ts +1 -42
  137. package/dist/index.js +1 -27
  138. package/dist/platforms/mobile.js +1 -20
  139. package/dist/platforms/web.d.ts +1 -1
  140. package/dist/platforms/web.js +27 -75
  141. package/dist/project-config.d.ts +2 -13
  142. package/dist/project-config.js +10 -82
  143. package/dist/registry/options.js +1 -5
  144. package/dist/registry/resolve.d.ts +1 -1
  145. package/dist/registry/resolve.js +2 -10
  146. package/dist/registry/usage.js +3 -9
  147. package/dist/scaffold/backend.js +0 -3
  148. package/dist/scaffold/database.js +2 -1
  149. package/dist/scaffold/documentation.js +82 -20
  150. package/dist/scaffold/expo-runtime.js +3 -4
  151. package/dist/scaffold/native-ui.js +12 -7
  152. package/dist/scaffold/stack-documentation.js +1 -1
  153. package/dist/scaffold/storage.d.ts +2 -0
  154. package/dist/scaffold/storage.js +21 -0
  155. package/dist/scaffold/workspace.js +26 -21
  156. package/dist/stack-registry.d.ts +2 -8
  157. package/dist/stack-registry.js +11 -87
  158. package/dist/standard.js +1 -11
  159. package/dist/ui-catalog.d.ts +26 -0
  160. package/dist/ui-catalog.js +31 -0
  161. package/dist/ui-command.d.ts +3 -0
  162. package/dist/ui-command.js +219 -0
  163. package/dist/ui-project.d.ts +22 -0
  164. package/dist/ui-project.js +110 -0
  165. package/dist/version.d.ts +1 -1
  166. package/dist/version.js +1 -1
  167. package/docs/anhedral-stack.md +4 -20
  168. package/docs/capabilities.md +110 -0
  169. package/docs/native-ui.md +102 -0
  170. package/docs/software-factory.md +16 -44
  171. package/docs/stack-standard.md +11 -60
  172. package/docs/ui.md +33 -0
  173. package/docs/verification.md +191 -0
  174. package/package.json +19 -18
  175. package/dist/access.d.ts +0 -10
  176. package/dist/access.js +0 -93
  177. package/dist/auth-schema-snapshot.d.ts +0 -346
  178. package/dist/auth-schema-snapshot.js +0 -347
  179. package/dist/auth-schema.d.ts +0 -1
  180. package/dist/auth-schema.js +0 -57
  181. package/dist/capability-contract.d.ts +0 -47
  182. package/dist/capability-contract.js +0 -129
  183. package/dist/catalog-model.d.ts +0 -24
  184. package/dist/catalog-model.js +0 -1
  185. package/dist/catalog-registration.d.ts +0 -16
  186. package/dist/catalog-registration.js +0 -22
  187. package/dist/catalog-snapshot.d.ts +0 -5
  188. package/dist/catalog-snapshot.js +0 -97
  189. package/dist/cli-delivery.d.ts +0 -3
  190. package/dist/cli-delivery.js +0 -112
  191. package/dist/cloudflare.d.ts +0 -25
  192. package/dist/cloudflare.js +0 -226
  193. package/dist/delivery-evidence.d.ts +0 -62
  194. package/dist/delivery-evidence.js +0 -157
  195. package/dist/delivery.d.ts +0 -82
  196. package/dist/delivery.js +0 -489
  197. package/dist/inspector-model.d.ts +0 -123
  198. package/dist/inspector-model.js +0 -1
  199. package/dist/integration-service-readers.d.ts +0 -12
  200. package/dist/integration-service-readers.js +0 -92
  201. package/dist/lifecycle-model.d.ts +0 -15
  202. package/dist/lifecycle-model.js +0 -20
  203. package/dist/lifecycle.d.ts +0 -11
  204. package/dist/lifecycle.js +0 -91
  205. package/dist/management.d.ts +0 -3
  206. package/dist/management.js +0 -47
  207. package/dist/mobile-delivery.d.ts +0 -77
  208. package/dist/mobile-delivery.js +0 -370
  209. package/dist/project-catalog.d.ts +0 -41
  210. package/dist/project-catalog.js +0 -288
  211. package/dist/project-inspector.d.ts +0 -4
  212. package/dist/project-inspector.js +0 -671
  213. package/dist/project-lifecycle.d.ts +0 -25
  214. package/dist/project-lifecycle.js +0 -57
  215. package/dist/project-state.d.ts +0 -47
  216. package/dist/project-state.js +0 -480
  217. package/dist/provider-auth.d.ts +0 -41
  218. package/dist/provider-auth.js +0 -180
  219. package/dist/provider-readiness.d.ts +0 -30
  220. package/dist/provider-readiness.js +0 -85
  221. package/dist/providers/adapters.d.ts +0 -17
  222. package/dist/providers/adapters.js +0 -103
  223. package/dist/providers/api.d.ts +0 -29
  224. package/dist/providers/api.js +0 -253
  225. package/dist/providers/config.d.ts +0 -15
  226. package/dist/providers/config.js +0 -136
  227. package/dist/providers/definitions.d.ts +0 -115
  228. package/dist/providers/definitions.js +0 -42
  229. package/dist/providers/provision.d.ts +0 -24
  230. package/dist/providers/provision.js +0 -76
  231. package/dist/providers/receipts.d.ts +0 -20
  232. package/dist/providers/receipts.js +0 -56
  233. package/dist/providers/recovery-verification.d.ts +0 -7
  234. package/dist/providers/recovery-verification.js +0 -52
  235. package/dist/providers/recovery.d.ts +0 -30
  236. package/dist/providers/recovery.js +0 -34
  237. package/dist/providers/runtime.d.ts +0 -10
  238. package/dist/providers/runtime.js +0 -234
  239. package/dist/providers/schema.d.ts +0 -28
  240. package/dist/providers/schema.js +0 -49
  241. package/dist/providers/state.d.ts +0 -55
  242. package/dist/providers/state.js +0 -283
  243. package/dist/provision.d.ts +0 -47
  244. package/dist/provision.js +0 -208
  245. package/dist/r2-service-data.d.ts +0 -2
  246. package/dist/r2-service-data.js +0 -136
  247. package/dist/readiness.d.ts +0 -23
  248. package/dist/readiness.js +0 -117
  249. package/dist/registry/add.d.ts +0 -24
  250. package/dist/registry/add.js +0 -210
  251. package/dist/registry/bootstrap.d.ts +0 -3
  252. package/dist/registry/bootstrap.js +0 -5
  253. package/dist/registry/commands.d.ts +0 -3
  254. package/dist/registry/commands.js +0 -83
  255. package/dist/registry/preview.d.ts +0 -11
  256. package/dist/registry/preview.js +0 -91
  257. package/dist/registry/receipt.d.ts +0 -3
  258. package/dist/registry/receipt.js +0 -68
  259. package/dist/repository.d.ts +0 -24
  260. package/dist/repository.js +0 -96
  261. package/dist/scaffold/auth.d.ts +0 -2
  262. package/dist/scaffold/auth.js +0 -76
  263. package/dist/scaffold/billing-config.d.ts +0 -1
  264. package/dist/scaffold/billing-config.js +0 -73
  265. package/dist/scaffold/billing-contracts.d.ts +0 -2
  266. package/dist/scaffold/billing-contracts.js +0 -48
  267. package/dist/scaffold/billing-providers.d.ts +0 -1
  268. package/dist/scaffold/billing-providers.js +0 -249
  269. package/dist/scaffold/billing-schema.d.ts +0 -1
  270. package/dist/scaffold/billing-schema.js +0 -34
  271. package/dist/scaffold/billing-security.d.ts +0 -1
  272. package/dist/scaffold/billing-security.js +0 -46
  273. package/dist/scaffold/billing-server.d.ts +0 -1
  274. package/dist/scaffold/billing-server.js +0 -139
  275. package/dist/scaffold/billing-store.d.ts +0 -1
  276. package/dist/scaffold/billing-store.js +0 -72
  277. package/dist/scaffold/billing.d.ts +0 -2
  278. package/dist/scaffold/billing.js +0 -208
  279. package/dist/scaffold/expo-auth.d.ts +0 -3
  280. package/dist/scaffold/expo-auth.js +0 -203
  281. package/dist/scaffold/expo-billing.d.ts +0 -3
  282. package/dist/scaffold/expo-billing.js +0 -257
  283. package/dist/scaffold/integrations.d.ts +0 -2
  284. package/dist/scaffold/integrations.js +0 -11
  285. package/dist/scaffold/managed-email.d.ts +0 -3
  286. package/dist/scaffold/managed-email.js +0 -47
  287. package/dist/scaffold/password-reset.d.ts +0 -1
  288. package/dist/scaffold/password-reset.js +0 -99
  289. package/dist/scaffold/private-files.d.ts +0 -2
  290. package/dist/scaffold/private-files.js +0 -78
  291. package/dist/scaffold/web-billing.d.ts +0 -2
  292. package/dist/scaffold/web-billing.js +0 -48
  293. package/dist/service-deletion.d.ts +0 -29
  294. package/dist/service-deletion.js +0 -195
  295. package/dist/service-descriptor.d.ts +0 -10
  296. package/dist/service-descriptor.js +0 -71
  297. package/dist/service-model.d.ts +0 -49
  298. package/dist/service-model.js +0 -8
  299. package/dist/service-operations.d.ts +0 -29
  300. package/dist/service-operations.js +0 -48
  301. package/dist/service-readers.d.ts +0 -8
  302. package/dist/service-readers.js +0 -216
  303. package/dist/services-command.d.ts +0 -39
  304. package/dist/services-command.js +0 -96
  305. package/dist/ship.d.ts +0 -35
  306. package/dist/ship.js +0 -107
  307. package/docs/assets/anhedral-stack-light.png +0 -0
  308. package/docs/assets/anhedral-stack.png +0 -0
@@ -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,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 +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
- `;
@@ -1,2 +0,0 @@
1
- import type { RecipeContext } from '../registry/types.js';
2
- export declare function scaffoldWebBilling({ root }: RecipeContext): void;
@@ -1,48 +0,0 @@
1
- import { put } from './files.js';
2
- export function scaffoldWebBilling({ root }) {
3
- put(root, 'apps/web/components/billing.tsx', WEB_BILLING);
4
- put(root, 'apps/web/app/account/page.tsx', `import { headers } from 'next/headers';
5
- import { redirect } from 'next/navigation';
6
- import { sessionSchema } from '@workspace/contracts';
7
- import { apiRequest } from '@/lib/server-api';
8
- import { SignOut } from '@/components/sign-out';
9
- import { Billing } from '@/components/billing';
10
- export default async function Account() {
11
- const incoming = await headers();
12
- const response = await apiRequest(new Request('https://app.internal/api/session', { headers: { cookie: incoming.get('cookie') ?? '' } }));
13
- if (response.status === 401) redirect('/sign-in');
14
- if (!response.ok) throw Error('Session verification is unavailable.');
15
- const { user } = sessionSchema.parse(await response.json());
16
- return <section className="stack"><h1>Account</h1><p>{user.email}</p><Billing key={user.id} /><SignOut /></section>;
17
- }
18
- `);
19
- }
20
- const WEB_BILLING = `'use client';
21
- import { useEffect, useRef, useState } from 'react';
22
- import { createBillingClient, type BillingIdentity, type BillingEntitlements } from '@workspace/contracts';
23
- import { Button } from '@/components/ui/button';
24
- const api = createBillingClient();
25
- function navigate(value: string) {
26
- const url = new URL(value);
27
- const invalid = [url.protocol !== 'https:', !['checkout.stripe.com', 'billing.stripe.com'].includes(url.hostname), url.username, url.password];
28
- if (invalid.some(Boolean)) throw Error('Unrecognized billing destination.');
29
- window.location.assign(url.href);
30
- }
31
- export function Billing() {
32
- const [identity, setIdentity] = useState<BillingIdentity | null>(null);
33
- const [entitlements, setEntitlements] = useState<BillingEntitlements | null>(null);
34
- const [pending, setPending] = useState(false); const [error, setError] = useState('');
35
- const intents = useRef(new Map<string, string>());
36
- useEffect(() => { let active = true; void Promise.all([api.identity(), api.entitlements()]).then(([user, access]) => { if (active) { setIdentity(user); setEntitlements(access); } }).catch(() => { if (active) setError('Unable to verify subscriptions.'); }); return () => { active = false; }; }, []);
37
- function checkoutIntent(plan: string) { const key = intents.current.get(plan) ?? crypto.randomUUID(); intents.current.set(plan, key); return key; }
38
- async function checkout(plan: string) {
39
- if (pending || !identity) return;
40
- setPending(true); setError('');
41
- // Keep one intent through uncertain retries. The server controls customer, price and return URL.
42
- const key = checkoutIntent(plan);
43
- try { navigate((await api.checkout(plan, key)).url); } catch { setError('Checkout is unavailable. Retry to resume the same checkout.'); } finally { setPending(false); }
44
- }
45
- async function portal() { if (pending || !identity) return; setPending(true); setError(''); try { navigate((await api.portal()).url); } catch { setError('Billing management is unavailable.'); } finally { setPending(false); } }
46
- return <section className="stack" aria-label="Subscription"><h2>Subscription</h2><p>{entitlements?.entitlements.some((grant) => grant.active) ? 'Active access' : 'No verified subscription'}</p>{identity?.providers.stripe && <>{identity.plans.map((plan) => <Button key={plan.id} disabled={pending} onClick={() => void checkout(plan.id)}>{plan.label}</Button>)}<Button disabled={pending} onClick={() => void portal()}>Manage web subscription</Button></>}<p role="status">{error}</p></section>;
47
- }
48
- `;
@@ -1,29 +0,0 @@
1
- import type { CloudflareRequest } from './cloudflare.js';
2
- export interface DeletionPlan {
3
- token: string;
4
- name: string;
5
- accountId: string;
6
- resourceId: string;
7
- kind: string;
8
- applications: string[];
9
- expiresAt: string;
10
- impact: string;
11
- }
12
- export declare class ServiceDeletionStore {
13
- readonly directory: string;
14
- constructor(directory: string);
15
- plan(root: string, key: string, request: CloudflareRequest): Promise<DeletionPlan>;
16
- execute(root: string, key: string, token: string, typedName: string, request: CloudflareRequest): Promise<{
17
- state: "deleted";
18
- resourceId: string;
19
- message: string;
20
- } | {
21
- state: "uncertain";
22
- resourceId: string;
23
- message: string;
24
- }>;
25
- }
26
- export declare function assertNoDeletedServices(root: string, resources: {
27
- kind: string;
28
- name: string;
29
- }[]): void;