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
@@ -0,0 +1,65 @@
1
+ import Purchases, { type PurchasesPackage } from 'react-native-purchases';
2
+ import { Platform } from 'react-native';
3
+ import { authClient } from './auth-client';
4
+ let initialized = false;
5
+ let pending: Promise<unknown> = Promise.resolve();
6
+ function serial<T>(work: () => Promise<T>) {
7
+ const result = pending.then(work, work);
8
+ pending = result.then(
9
+ () => undefined,
10
+ () => undefined,
11
+ );
12
+ return result;
13
+ }
14
+ async function subject() {
15
+ const session = await authClient.getSession();
16
+ if (!session.data) throw Error('Sign in before using purchases');
17
+ return session.data.user.id;
18
+ }
19
+ function publicKey() {
20
+ return Platform.OS === 'ios'
21
+ ? process.env.EXPO_PUBLIC_REVENUECAT_IOS_KEY
22
+ : process.env.EXPO_PUBLIC_REVENUECAT_ANDROID_KEY;
23
+ }
24
+ function requiredKey() {
25
+ const value = publicKey();
26
+ if (!value) throw Error('Configure the platform public SDK key');
27
+ return value;
28
+ }
29
+ async function connect() {
30
+ const appUserID = await subject();
31
+ const apiKey = requiredKey();
32
+ if (!initialized) {
33
+ Purchases.configure({ apiKey, appUserID });
34
+ initialized = true;
35
+ } else await Purchases.logIn(appUserID);
36
+ return Purchases.getOfferings();
37
+ }
38
+ export function connectPurchases() {
39
+ return serial(connect);
40
+ }
41
+ export function purchase(value: PurchasesPackage) {
42
+ return serial(async () => {
43
+ await connect();
44
+ return Purchases.purchasePackage(value);
45
+ });
46
+ }
47
+ export function restorePurchases() {
48
+ return serial(async () => {
49
+ await connect();
50
+ return Purchases.restorePurchases();
51
+ });
52
+ }
53
+ export function manageSubscriptions() {
54
+ return serial(async () => {
55
+ await connect();
56
+ return Purchases.showManageSubscriptions();
57
+ });
58
+ }
59
+ export function disconnectPurchases() {
60
+ return serial(async () => {
61
+ if (initialized) await Purchases.logOut();
62
+ });
63
+ }
64
+ // SDK identity transitions are serialized. Callbacks update presentation only;
65
+ // Hono's canonical provider reconciliation owns all application access decisions.
@@ -0,0 +1,88 @@
1
+ import { Hono } from 'hono';
2
+ import { z } from 'zod';
3
+ import { timingSafeEqual } from 'node:crypto';
4
+ import { requireSession } from '../security';
5
+ import { billingEnvironment } from '../billing-mode';
6
+ import type { AppEnv } from '../environment';
7
+ export const revenuecatRoutes = new Hono<AppEnv>();
8
+ const hookConfig = z.object({
9
+ REVENUECAT_WEBHOOK_AUTH: z.string().min(1),
10
+ REVENUECAT_APP_ID: z.string().min(1),
11
+ });
12
+ function authorized(actual: string | undefined, expected: string) {
13
+ const a = new TextEncoder().encode(actual);
14
+ const b = new TextEncoder().encode(expected);
15
+ if (a.byteLength !== b.byteLength) return false;
16
+ return timingSafeEqual(a, b);
17
+ }
18
+ revenuecatRoutes.post('/webhooks/revenuecat', async (c) => {
19
+ const config = hookConfig.safeParse(c.env);
20
+ if (!config.success) return c.json({ error: 'Webhook needs configuration' }, 503);
21
+ if (!authorized(c.req.header('authorization'), config.data.REVENUECAT_WEBHOOK_AUTH))
22
+ return c.json({ error: 'Unauthorized' }, 401);
23
+ const schema = z.object({
24
+ event: z.object({
25
+ id: z.string().min(1).max(512),
26
+ environment: z.literal({ sandbox: 'SANDBOX', live: 'PRODUCTION' }[billingEnvironment(c.env)]),
27
+ app_id: z.literal(config.data.REVENUECAT_APP_ID),
28
+ }),
29
+ });
30
+ const body = schema.safeParse(await c.req.json().catch(() => null));
31
+ if (!body.success) return c.json({ error: 'Invalid webhook or scope' }, 400);
32
+ await c.env.DB.prepare(
33
+ 'INSERT OR IGNORE INTO billing_receipt(provider,event_id,received_at) VALUES (?,?,?)',
34
+ )
35
+ .bind('revenuecat', body.data.event.id, Date.now())
36
+ .run();
37
+ return c.json({ received: true });
38
+ });
39
+ const statusConfig = z.object({
40
+ REVENUECAT_SECRET_KEY: z.string().min(1),
41
+ REVENUECAT_ENTITLEMENT: z.string().min(1),
42
+ });
43
+ const subscriberSchema = z.object({
44
+ subscriber: z.object({
45
+ entitlements: z.record(
46
+ z.string(),
47
+ z.object({ expires_date: z.string().nullable(), product_identifier: z.string() }),
48
+ ),
49
+ subscriptions: z.record(z.string(), z.object({ is_sandbox: z.boolean() })),
50
+ }),
51
+ });
52
+ type Subscriber = z.infer<typeof subscriberSchema>['subscriber'];
53
+ const current = (expires: string | null) => expires === null || Date.parse(expires) > Date.now();
54
+ function entitled(subscriber: Subscriber, key: string, sandbox: boolean) {
55
+ const item = subscriber.entitlements[key];
56
+ if (!item) return false;
57
+ const product = subscriber.subscriptions[item.product_identifier];
58
+ if (!product) return false;
59
+ return product.is_sandbox === sandbox && current(item.expires_date);
60
+ }
61
+ export async function revenuecatEntitled(env: AppEnv['Bindings'], userId: string) {
62
+ const config = statusConfig.parse(env);
63
+ const response = await fetch(
64
+ 'https://api.revenuecat.com/v1/subscribers/' + encodeURIComponent(userId),
65
+ {
66
+ headers: { Authorization: 'Bearer ' + config.REVENUECAT_SECRET_KEY },
67
+ signal: AbortSignal.timeout(10000),
68
+ },
69
+ );
70
+ if (!response.ok) throw Error('RevenueCat unavailable');
71
+ const data = subscriberSchema.parse(await response.json());
72
+ return entitled(
73
+ data.subscriber,
74
+ config.REVENUECAT_ENTITLEMENT,
75
+ billingEnvironment(env) === 'sandbox',
76
+ );
77
+ }
78
+ revenuecatRoutes.get('/billing/mobile-status', requireSession, async (c) => {
79
+ try {
80
+ return c.json({
81
+ entitled: await revenuecatEntitled(c.env, c.get('userId')),
82
+ provider: 'revenuecat',
83
+ environment: billingEnvironment(c.env),
84
+ });
85
+ } catch {
86
+ return c.json({ error: 'Billing needs configuration or is temporarily unavailable' }, 503);
87
+ }
88
+ });
@@ -0,0 +1,10 @@
1
+ import { sqliteTable, text, integer, index } from 'drizzle-orm/sqlite-core';
2
+ export const rtcSession = sqliteTable(
3
+ 'rtc_session',
4
+ {
5
+ id: text('id').primaryKey(),
6
+ userId: text('user_id').notNull(),
7
+ createdAt: integer('created_at').notNull(),
8
+ },
9
+ (t) => [index('rtc_session_user_time').on(t.userId, t.createdAt)],
10
+ );
@@ -0,0 +1,122 @@
1
+ import { Hono, type Context } from 'hono';
2
+ import { z } from 'zod';
3
+ import { requireSession } from '../security';
4
+ import type { AppEnv } from '../environment';
5
+ export const rtcRoutes = new Hono<AppEnv>();
6
+ const identifier = z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/);
7
+ const configuration = z.object({ RTC_APP_ID: identifier, RTC_APP_SECRET: z.string().min(1) });
8
+ const description = z.object({
9
+ type: z.enum(['offer', 'answer']),
10
+ sdp: z.string().min(1).max(128000),
11
+ });
12
+ const track = z.discriminatedUnion('location', [
13
+ z.object({ location: z.literal('local'), mid: identifier.optional(), trackName: identifier }),
14
+ z.object({ location: z.literal('remote'), sessionId: identifier, trackName: identifier }),
15
+ ]);
16
+ const trackRequest = z.object({
17
+ sessionDescription: description.optional(),
18
+ tracks: z.array(track).min(1).max(10),
19
+ });
20
+ const closeRequest = z
21
+ .object({
22
+ force: z.boolean().default(false),
23
+ sessionDescription: description.optional(),
24
+ tracks: z
25
+ .array(z.object({ mid: identifier }))
26
+ .min(1)
27
+ .max(10),
28
+ })
29
+ .refine((value) => value.force || !!value.sessionDescription);
30
+ const renegotiateRequest = z.object({
31
+ sessionDescription: description.extend({ type: z.literal('answer') }),
32
+ });
33
+ async function provider(env: AppEnv['Bindings'], path: string, body?: unknown, method = 'POST') {
34
+ return fetch(
35
+ 'https://rtc.live.cloudflare.com/v1/apps/' + encodeURIComponent(env.RTC_APP_ID!) + path,
36
+ {
37
+ method,
38
+ headers: {
39
+ Authorization: 'Bearer ' + env.RTC_APP_SECRET,
40
+ 'Content-Type': 'application/json',
41
+ },
42
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
43
+ signal: AbortSignal.timeout(10000),
44
+ },
45
+ );
46
+ }
47
+ async function owns(c: Context<AppEnv>, id: string) {
48
+ return !!(await c.env.DB.prepare('SELECT id FROM rtc_session WHERE id = ? AND user_id = ?')
49
+ .bind(id, c.get('userId'))
50
+ .first());
51
+ }
52
+ rtcRoutes.use('/rtc/*', requireSession);
53
+ rtcRoutes.use('/rtc/*', async (c, next) => {
54
+ if (!configuration.safeParse(c.env).success)
55
+ return c.json({ error: 'Configure Cloudflare Realtime SFU first' }, 503);
56
+ await next();
57
+ });
58
+ rtcRoutes.use('/rtc/session/:id/*', async (c, next) => {
59
+ const id = identifier.safeParse(c.req.param('id'));
60
+ if (!id.success) return c.json({ error: 'Invalid session' }, 400);
61
+ if (!(await owns(c, id.data))) return c.json({ error: 'Not found' }, 404);
62
+ await next();
63
+ });
64
+ async function allocate(c: Context<AppEnv>, reservation: string) {
65
+ return c.env.DB.prepare(
66
+ 'INSERT INTO rtc_session(id,user_id,created_at) SELECT ?,?,? WHERE (SELECT COUNT(*) FROM rtc_session WHERE user_id = ? AND created_at > ?) < 10',
67
+ )
68
+ .bind(reservation, c.get('userId'), Date.now(), c.get('userId'), Date.now() - 3600000)
69
+ .run();
70
+ }
71
+ async function createProviderSession(c: Context<AppEnv>) {
72
+ const response = await provider(c.env, '/sessions/new');
73
+ if (!response.ok) return null;
74
+ const body = (await response.json()) as { sessionId?: unknown };
75
+ const result = identifier.safeParse(body.sessionId);
76
+ return result.success ? result.data : null;
77
+ }
78
+ rtcRoutes.post('/rtc/session', async (c) => {
79
+ const reservation = crypto.randomUUID();
80
+ const quota = await allocate(c, reservation);
81
+ if (!quota.meta.changes) return c.json({ error: 'RTC session limit reached' }, 429);
82
+ // Uncertain provider failures retain the reservation for the bounded hour.
83
+ const sessionId = await createProviderSession(c);
84
+ if (!sessionId) return c.json({ error: 'RTC provider unavailable' }, 503);
85
+ await c.env.DB.prepare('UPDATE rtc_session SET id = ? WHERE id = ? AND user_id = ?')
86
+ .bind(sessionId, reservation, c.get('userId'))
87
+ .run();
88
+ return c.json({ sessionId }, 201);
89
+ });
90
+ async function operation(c: Context<AppEnv>, endpoint: string, body: unknown, method: string) {
91
+ const response = await provider(
92
+ c.env,
93
+ '/sessions/' + encodeURIComponent(c.req.param('id')!) + endpoint,
94
+ body,
95
+ method,
96
+ );
97
+ if (!response.ok) return c.json({ error: 'RTC operation rejected' }, 502);
98
+ return c.json(await response.json());
99
+ }
100
+ async function permitted(c: Context<AppEnv>, value: z.infer<typeof track>) {
101
+ if (value.location === 'local') return true;
102
+ // A multi-user product replaces this with reviewed room/membership rules.
103
+ return owns(c, value.sessionId);
104
+ }
105
+ rtcRoutes.post('/rtc/session/:id/tracks', async (c) => {
106
+ const body = trackRequest.safeParse(await c.req.json().catch(() => null));
107
+ if (!body.success) return c.json({ error: 'Invalid tracks' }, 400);
108
+ for (const value of body.data.tracks) {
109
+ if (!(await permitted(c, value))) return c.json({ error: 'Remote session forbidden' }, 403);
110
+ }
111
+ return operation(c, '/tracks/new', body.data, 'POST');
112
+ });
113
+ rtcRoutes.post('/rtc/session/:id/close', async (c) => {
114
+ const body = closeRequest.safeParse(await c.req.json().catch(() => null));
115
+ if (!body.success) return c.json({ error: 'Invalid close request' }, 400);
116
+ return operation(c, '/tracks/close', body.data, 'PUT');
117
+ });
118
+ rtcRoutes.post('/rtc/session/:id/renegotiate', async (c) => {
119
+ const body = renegotiateRequest.safeParse(await c.req.json().catch(() => null));
120
+ if (!body.success) return c.json({ error: 'Invalid SDP' }, 400);
121
+ return operation(c, '/renegotiate', body.data, 'PUT');
122
+ });
@@ -0,0 +1,31 @@
1
+ import type { MiddlewareHandler } from 'hono';
2
+ import { createAuth, authConfiguration } from './auth';
3
+ import type { AppEnv } from './environment';
4
+ const bearer = (headers: Headers) => (headers.get('authorization') ?? '').startsWith('Bearer ');
5
+ function sessionHeaders(request: Request) {
6
+ const headers = new Headers(request.headers);
7
+ if (bearer(headers)) headers.delete('cookie');
8
+ return headers;
9
+ }
10
+ function nativeOrigin(request: Request, env: AppEnv['Bindings']) {
11
+ const origins = (env.AUTH_TRUSTED_ORIGINS ?? '').split(',').map((value) => value.trim());
12
+ const claimed = request.headers.get('expo-origin') ?? '';
13
+ return claimed.length > 0 && origins.includes(claimed);
14
+ }
15
+ function trustedMutation(request: Request, env: AppEnv['Bindings']) {
16
+ if (['GET', 'HEAD', 'OPTIONS'].includes(request.method)) return true;
17
+ if (bearer(request.headers)) return true;
18
+ const origin = request.headers.get('origin');
19
+ if (origin !== null) return origin === new URL(env.PUBLIC_APP_URL!).origin;
20
+ // A browser-supplied Origin is never bypassed by an expo-origin header.
21
+ return nativeOrigin(request, env);
22
+ }
23
+ export const requireSession: MiddlewareHandler<AppEnv> = async (c, next) => {
24
+ if (!authConfiguration.safeParse(c.env).success)
25
+ return c.json({ error: 'Authentication needs configuration' }, 503);
26
+ const session = await createAuth(c.env).api.getSession({ headers: sessionHeaders(c.req.raw) });
27
+ if (!session) return c.json({ error: 'Unauthorized' }, 401);
28
+ if (!trustedMutation(c.req.raw, c.env)) return c.json({ error: 'Origin rejected' }, 403);
29
+ c.set('userId', session.user.id);
30
+ await next();
31
+ };
@@ -0,0 +1,36 @@
1
+ import { Hono } from 'hono';
2
+ import { requireSession } from '../security';
3
+ import type { AppEnv } from '../environment';
4
+ export const storageRoutes = new Hono<AppEnv>();
5
+ storageRoutes.use('/files/*', requireSession);
6
+ storageRoutes.use('/files/:name', async (c, next) => {
7
+ const name = c.req.param('name');
8
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(name))
9
+ return c.json({ error: 'Invalid filename' }, 400);
10
+ c.set('fileKey', encodeURIComponent(c.get('userId')) + '/' + name);
11
+ await next();
12
+ });
13
+ storageRoutes.get('/files/:name', async (c) => {
14
+ const object = await c.env.FILES.get(c.get('fileKey'));
15
+ if (!object) return c.json({ error: 'Not found' }, 404);
16
+ return new Response(object.body, {
17
+ headers: {
18
+ 'Content-Type': 'application/octet-stream',
19
+ 'Content-Disposition': 'attachment; filename="' + c.req.param('name') + '"',
20
+ 'X-Content-Type-Options': 'nosniff',
21
+ 'Cache-Control': 'private, no-store',
22
+ },
23
+ });
24
+ });
25
+ storageRoutes.put('/files/:name', async (c) => {
26
+ const bytes = await c.req.arrayBuffer();
27
+ if (bytes.byteLength > 1024 * 1024) return c.json({ error: 'File too large' }, 413);
28
+ await c.env.FILES.put(c.get('fileKey'), bytes, {
29
+ httpMetadata: { contentType: 'application/octet-stream' },
30
+ });
31
+ return c.json({ stored: true }, 201);
32
+ });
33
+ storageRoutes.delete('/files/:name', async (c) => {
34
+ await c.env.FILES.delete(c.get('fileKey'));
35
+ return c.body(null, 204);
36
+ });
@@ -0,0 +1,126 @@
1
+ import { Hono } from 'hono';
2
+ import { z } from 'zod';
3
+ import Stripe from 'stripe';
4
+ import { requireSession } from '../security';
5
+ import { billingEnvironment } from '../billing-mode';
6
+ import type { AppEnv } from '../environment';
7
+ export const stripeRoutes = new Hono<AppEnv>();
8
+ const client = (key: string) =>
9
+ new Stripe(key, {
10
+ httpClient: Stripe.createFetchHttpClient(),
11
+ timeout: 5000,
12
+ maxNetworkRetries: 0,
13
+ });
14
+ const settings = z.object({
15
+ STRIPE_SECRET_KEY: z.string().min(1),
16
+ STRIPE_PRICE_ID: z.string().startsWith('price_'),
17
+ PUBLIC_APP_URL: z.url(),
18
+ });
19
+ const webhookSettings = z.object({
20
+ STRIPE_SECRET_KEY: z.string().min(1),
21
+ STRIPE_WEBHOOK_SECRET: z.string().min(1),
22
+ });
23
+ const idempotencyKey = z.string().regex(/^[a-zA-Z0-9_-]{8,100}$/);
24
+ stripeRoutes.post('/billing/checkout', requireSession, async (c) => {
25
+ const config = settings.safeParse(c.env);
26
+ if (!config.success) return c.json({ error: 'Configure Stripe test mode first' }, 503);
27
+ const key = idempotencyKey.safeParse(c.req.header('idempotency-key'));
28
+ if (!key.success) return c.json({ error: 'Provide an idempotency-key' }, 400);
29
+ const env = config.data;
30
+ requireMatchingKey(c.env, env.STRIPE_SECRET_KEY);
31
+ const userId = c.get('userId');
32
+ const result = await client(env.STRIPE_SECRET_KEY).checkout.sessions.create(
33
+ {
34
+ mode: 'subscription',
35
+ client_reference_id: userId,
36
+ line_items: [{ price: env.STRIPE_PRICE_ID, quantity: 1 }],
37
+ subscription_data: { metadata: { userId } },
38
+ success_url: new URL('/?checkout=success', env.PUBLIC_APP_URL).href,
39
+ cancel_url: new URL('/?checkout=cancelled', env.PUBLIC_APP_URL).href,
40
+ },
41
+ { idempotencyKey: 'checkout:' + userId + ':' + key.data },
42
+ );
43
+ return c.json({ url: result.url });
44
+ });
45
+ async function verifiedEvent(
46
+ key: string,
47
+ secret: string,
48
+ signature: string | undefined,
49
+ body: string,
50
+ live: boolean,
51
+ ) {
52
+ if (!signature) return null;
53
+ try {
54
+ const event = await client(key).webhooks.constructEventAsync(
55
+ body,
56
+ signature,
57
+ secret,
58
+ undefined,
59
+ Stripe.createSubtleCryptoProvider(),
60
+ );
61
+ return event.livemode === live ? event : null;
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+ stripeRoutes.post('/webhooks/stripe', async (c) => {
67
+ const config = webhookSettings.safeParse(c.env);
68
+ if (!config.success) return c.json({ error: 'Webhook needs configuration' }, 503);
69
+ requireMatchingKey(c.env, config.data.STRIPE_SECRET_KEY);
70
+ const event = await verifiedEvent(
71
+ config.data.STRIPE_SECRET_KEY,
72
+ config.data.STRIPE_WEBHOOK_SECRET,
73
+ c.req.header('stripe-signature'),
74
+ await c.req.text(),
75
+ billingEnvironment(c.env) === 'live',
76
+ );
77
+ if (!event) return c.json({ error: 'Invalid signature or billing environment' }, 400);
78
+ // Receipts deduplicate delivery, but never grant an entitlement by event order.
79
+ await c.env.DB.prepare(
80
+ 'INSERT OR IGNORE INTO billing_receipt(provider,event_id,received_at) VALUES (?,?,?)',
81
+ )
82
+ .bind('stripe', event.id, Date.now())
83
+ .run();
84
+ return c.json({ received: true });
85
+ });
86
+ function activePrice(subscription: Stripe.Subscription, price: string) {
87
+ if (!['active', 'trialing'].includes(subscription.status)) return false;
88
+ return subscription.items.data.some(
89
+ (item) => item.price.id === price && item.current_period_end * 1000 > Date.now(),
90
+ );
91
+ }
92
+ function requireMatchingKey(env: AppEnv['Bindings'], key: string) {
93
+ const prefix = { sandbox: 'sk_test_', live: 'sk_live_' }[billingEnvironment(env)];
94
+ if (!key.startsWith(prefix))
95
+ throw Error('Stripe key does not match the configured billing environment');
96
+ }
97
+ export async function stripeEntitled(env: AppEnv['Bindings'], userId: string) {
98
+ const config = settings.parse(env);
99
+ requireMatchingKey(env, config.STRIPE_SECRET_KEY);
100
+ const stripe = client(config.STRIPE_SECRET_KEY);
101
+ const subject = userId.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
102
+ const found = await stripe.subscriptions.search({
103
+ query: "metadata['userId']:'" + subject + "'",
104
+ limit: 100,
105
+ });
106
+ const canonical = await Promise.all(
107
+ found.data.map((value) => stripe.subscriptions.retrieve(value.id)),
108
+ );
109
+ return canonical.some(
110
+ (value) =>
111
+ value.metadata.userId === userId &&
112
+ value.livemode === (billingEnvironment(env) === 'live') &&
113
+ activePrice(value, config.STRIPE_PRICE_ID),
114
+ );
115
+ }
116
+ stripeRoutes.get('/billing/status', requireSession, async (c) => {
117
+ try {
118
+ return c.json({
119
+ entitled: await stripeEntitled(c.env, c.get('userId')),
120
+ provider: 'stripe',
121
+ environment: billingEnvironment(c.env),
122
+ });
123
+ } catch {
124
+ return c.json({ error: 'Billing needs configuration or is temporarily unavailable' }, 503);
125
+ }
126
+ });
@@ -0,0 +1,51 @@
1
+ 'use client';
2
+ import { useState } from 'react';
3
+ import { authClient } from '@/lib/auth-client';
4
+ import { Button } from '@/components/ui/button';
5
+ import { Input } from '@/components/ui/input';
6
+ import { Label } from '@/components/ui/label';
7
+ export default function SignIn() {
8
+ const [email, setEmail] = useState('');
9
+ const [password, setPassword] = useState('');
10
+ const [message, setMessage] = useState('');
11
+ const [busy, setBusy] = useState(false);
12
+ async function submit(event: React.FormEvent<HTMLFormElement>) {
13
+ event.preventDefault();
14
+ setBusy(true);
15
+ try {
16
+ const result = await authClient.signIn.email({ email, password });
17
+ setMessage(result.error?.message ?? 'Signed in');
18
+ } catch {
19
+ setMessage('Unable to sign in');
20
+ } finally {
21
+ setBusy(false);
22
+ }
23
+ }
24
+ return (
25
+ <form onSubmit={submit} className="stack">
26
+ <h1>Sign in</h1>
27
+ <Label htmlFor="email">Email</Label>
28
+ <Input
29
+ id="email"
30
+ type="email"
31
+ autoComplete="email"
32
+ required
33
+ value={email}
34
+ onChange={(event) => setEmail(event.target.value)}
35
+ />
36
+ <Label htmlFor="password">Password</Label>
37
+ <Input
38
+ id="password"
39
+ type="password"
40
+ autoComplete="current-password"
41
+ required
42
+ value={password}
43
+ onChange={(event) => setPassword(event.target.value)}
44
+ />
45
+ <Button type="submit" disabled={busy}>
46
+ Sign in
47
+ </Button>
48
+ <p role="status">{message}</p>
49
+ </form>
50
+ );
51
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Founded Labs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -29,5 +29,11 @@
29
29
  "Native themes derive their colors from the generated shared semantic tokens; no separate native palette is installed.",
30
30
  "Native Dialog restores focus to its actionable trigger on both iOS dismissal and Android close transitions.",
31
31
  "Recovered Input and Label use the local cn utility; Input delegates keyboard focus styling to the existing shared global focus rule."
32
- ]
32
+ ],
33
+ "native": {
34
+ "catalog": "native/registry.json",
35
+ "baseline": "https://ui.shadcn.com/docs/components",
36
+ "retrieved": "2026-10-24",
37
+ "implementation": "Anhedral-owned React Native semantic adaptations. Native APIs replace browser-only DOM and interaction APIs; device acceptance is tracked separately."
38
+ }
33
39
  }