usebecky 0.0.0-stage → 0.2.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 (135) hide show
  1. package/README.md +701 -2
  2. package/dist/analytics/client.d.ts +219 -0
  3. package/dist/analytics/client.js +923 -0
  4. package/dist/analytics/cmp.d.ts +20 -0
  5. package/dist/analytics/cmp.js +166 -0
  6. package/dist/analytics/context.d.ts +29 -0
  7. package/dist/analytics/context.js +97 -0
  8. package/dist/auth/client.d.ts +401 -0
  9. package/dist/auth/client.js +1081 -0
  10. package/dist/auth/webauthn.d.ts +18 -0
  11. package/dist/auth/webauthn.js +138 -0
  12. package/dist/cli/ai.d.ts +54 -0
  13. package/dist/cli/ai.js +202 -0
  14. package/dist/cli/analytics.d.ts +53 -0
  15. package/dist/cli/analytics.js +357 -0
  16. package/dist/cli/config.d.ts +75 -0
  17. package/dist/cli/config.js +718 -0
  18. package/dist/cli/db.d.ts +48 -0
  19. package/dist/cli/db.js +215 -0
  20. package/dist/cli/deploy-api.d.ts +168 -0
  21. package/dist/cli/deploy-api.js +177 -0
  22. package/dist/cli/deploy-ci.d.ts +15 -0
  23. package/dist/cli/deploy-ci.js +54 -0
  24. package/dist/cli/deploy-detect.d.ts +64 -0
  25. package/dist/cli/deploy-detect.js +249 -0
  26. package/dist/cli/deploy-files.d.ts +112 -0
  27. package/dist/cli/deploy-files.js +778 -0
  28. package/dist/cli/deploy.d.ts +10 -0
  29. package/dist/cli/deploy.js +430 -0
  30. package/dist/cli/emails.d.ts +29 -0
  31. package/dist/cli/emails.js +122 -0
  32. package/dist/cli/framework.d.ts +135 -0
  33. package/dist/cli/framework.js +459 -0
  34. package/dist/cli/functions.d.ts +59 -0
  35. package/dist/cli/functions.js +426 -0
  36. package/dist/cli/hosting.d.ts +4 -0
  37. package/dist/cli/hosting.js +532 -0
  38. package/dist/cli/index.d.ts +2 -0
  39. package/dist/cli/index.js +9 -0
  40. package/dist/cli/payments.d.ts +35 -0
  41. package/dist/cli/payments.js +176 -0
  42. package/dist/cli/push.d.ts +36 -0
  43. package/dist/cli/push.js +172 -0
  44. package/dist/cli/run.d.ts +65 -0
  45. package/dist/cli/run.js +850 -0
  46. package/dist/cli/social.d.ts +52 -0
  47. package/dist/cli/social.js +532 -0
  48. package/dist/cli/tokens.d.ts +28 -0
  49. package/dist/cli/tokens.js +114 -0
  50. package/dist/cli/ui.d.ts +38 -0
  51. package/dist/cli/ui.js +140 -0
  52. package/dist/client.d.ts +94 -0
  53. package/dist/client.js +156 -0
  54. package/dist/db/query.d.ts +162 -0
  55. package/dist/db/query.js +336 -0
  56. package/dist/db/types.d.ts +93 -0
  57. package/dist/db/types.js +4 -0
  58. package/dist/forms/client.d.ts +65 -0
  59. package/dist/forms/client.js +106 -0
  60. package/dist/functions/client.d.ts +37 -0
  61. package/dist/functions/client.js +76 -0
  62. package/dist/index.d.ts +17 -0
  63. package/dist/index.js +16 -0
  64. package/dist/lib/dashboard-paths.d.ts +4 -0
  65. package/dist/lib/dashboard-paths.js +8 -0
  66. package/dist/lib/env.d.ts +9 -0
  67. package/dist/lib/env.js +55 -0
  68. package/dist/lib/errors.d.ts +22 -0
  69. package/dist/lib/errors.js +90 -0
  70. package/dist/lib/hosted.d.ts +2 -0
  71. package/dist/lib/hosted.js +7 -0
  72. package/dist/lib/http.d.ts +59 -0
  73. package/dist/lib/http.js +172 -0
  74. package/dist/lib/jwt.d.ts +1 -0
  75. package/dist/lib/jwt.js +31 -0
  76. package/dist/lib/locale.d.ts +12 -0
  77. package/dist/lib/locale.js +51 -0
  78. package/dist/lib/pkce.d.ts +20 -0
  79. package/dist/lib/pkce.js +124 -0
  80. package/dist/lib/storage-adapter.d.ts +15 -0
  81. package/dist/lib/storage-adapter.js +91 -0
  82. package/dist/lib/types.d.ts +339 -0
  83. package/dist/lib/types.js +1 -0
  84. package/dist/newsletter/client.d.ts +140 -0
  85. package/dist/newsletter/client.js +85 -0
  86. package/dist/payments/client.d.ts +352 -0
  87. package/dist/payments/client.js +323 -0
  88. package/dist/push/client.d.ts +110 -0
  89. package/dist/push/client.js +179 -0
  90. package/dist/realtime/client.d.ts +131 -0
  91. package/dist/realtime/client.js +513 -0
  92. package/dist/server/analytics.d.ts +176 -0
  93. package/dist/server/analytics.js +49 -0
  94. package/dist/server/cache.d.ts +74 -0
  95. package/dist/server/cache.js +154 -0
  96. package/dist/server/emails.d.ts +142 -0
  97. package/dist/server/emails.js +123 -0
  98. package/dist/server/events.d.ts +357 -0
  99. package/dist/server/events.js +219 -0
  100. package/dist/server/functions.d.ts +40 -0
  101. package/dist/server/functions.js +1 -0
  102. package/dist/server/http-utils.d.ts +10 -0
  103. package/dist/server/http-utils.js +115 -0
  104. package/dist/server/index.d.ts +195 -0
  105. package/dist/server/index.js +314 -0
  106. package/dist/server/payments.d.ts +218 -0
  107. package/dist/server/payments.js +150 -0
  108. package/dist/server/push.d.ts +85 -0
  109. package/dist/server/push.js +37 -0
  110. package/dist/server/usage.d.ts +43 -0
  111. package/dist/server/usage.js +8 -0
  112. package/dist/storage/client.d.ts +143 -0
  113. package/dist/storage/client.js +224 -0
  114. package/package.json +52 -4
  115. package/skill/usebecky/SKILL.md +339 -0
  116. package/skill/usebecky/references/access-rules.md +307 -0
  117. package/skill/usebecky/references/addons.md +68 -0
  118. package/skill/usebecky/references/analytics.md +166 -0
  119. package/skill/usebecky/references/android.md +434 -0
  120. package/skill/usebecky/references/auth.md +379 -0
  121. package/skill/usebecky/references/cache.md +51 -0
  122. package/skill/usebecky/references/components.md +127 -0
  123. package/skill/usebecky/references/emails.md +105 -0
  124. package/skill/usebecky/references/expo.md +147 -0
  125. package/skill/usebecky/references/functions.md +99 -0
  126. package/skill/usebecky/references/hosting.md +119 -0
  127. package/skill/usebecky/references/http-api.md +233 -0
  128. package/skill/usebecky/references/ios.md +355 -0
  129. package/skill/usebecky/references/payments.md +493 -0
  130. package/skill/usebecky/references/realtime.md +143 -0
  131. package/skill/usebecky/references/scheduled-jobs.md +82 -0
  132. package/skill/usebecky/references/sdk.md +838 -0
  133. package/skill/usebecky/references/storage.md +210 -0
  134. package/skill/usebecky/references/templates.md +191 -0
  135. package/skill/usebecky/references/wordpress.md +87 -0
@@ -0,0 +1,379 @@
1
+ # Auth
2
+
3
+ Users live in `auth.users` in the project database. Reference them from your tables with `user_id uuid references auth.users (id) on delete cascade` and check them in policies with `auth.uid()`. The REST API cannot read `auth.users`; keep public profile data in your own `profiles` table.
4
+
5
+ ## Project settings (dashboard)
6
+
7
+ Defaults: email + password on, email confirmation off, magic link on, sign-ups on, TOTP MFA on, access tokens valid 3600 s, `site_url` `http://localhost:3000`, redirect URLs `http://localhost:*`. Google is ON in a new project when the server has a managed Google app ("Managed by usebecky", `use_dev_credentials: true`: no keys, works on localhost and on the live domain; Google's screen shows "usebecky"). GitHub can use the managed app too but is off until enabled (one click, Dashboard → Auth → Sign-in methods → Turn on); Apple needs your own keys. Never ask the developer to create Google OAuth credentials unless they want their own name on the consent screen or need native Android Credential Manager.
8
+
9
+ Check what is on before building a login screen:
10
+
11
+ ```ts
12
+ // inside an async function:
13
+ const { data: settings } = await baas.auth.settings()
14
+ // { signup_enabled: true, email_password: true, magic_link: true, providers: { google: true, github: false, apple: false, microsoft: false, discord: false, gitlab: false, linkedin: false, slack: false, x: false },
15
+ // mfa_totp: true, site_url: 'http://localhost:3000', passkeys: false, phone: false, anonymous: false, sso: false }
16
+ ```
17
+
18
+ Redirect safety: `redirectTo` must start with `site_url` or match a redirect URL (wildcards like `http://localhost:*`, app schemes like `com.example.mynotes://**`); otherwise email links land on `site_url`, and social sign-in (`/auth/v1/authorize`) shows a 400 HTML page naming the address to add. Add production URLs and mobile deep links (`com.example.mynotes://auth`) to `auth.redirect_urls` in `usebecky/config.json` and run `npx usebecky config push` (or Dashboard → Auth → Settings). Providers too: `"providers": {"github": {"enabled": true, "use_dev_credentials": true}, "google": {"enabled": true, "client_id": "…", "client_secret": "${GOOGLE_CLIENT_SECRET}"}}`, email confirmation: `"email_password": {"confirm_email": false}`. For apps, use your app's bundle ID (iOS) / application ID (Android) as the scheme: it is unique to your app, so another app can't register the same scheme and catch the sign-in. Replace `com.example.mynotes` with your own bundle ID / application ID.
19
+
20
+ ## Email and password
21
+
22
+ ```ts
23
+ // src/auth.ts: each function returns the message to show
24
+ import { baas } from './lib/usebecky'
25
+
26
+ export async function signUp(email: string, password: string): Promise<string> {
27
+ const { data, error } = await baas.auth.signUp({ email, password, data: { name: 'Ada' } })
28
+ if (error) return error.message // user_already_exists (409), weak_password (400, min 6 chars), signup_disabled (403)
29
+ if (!data.session) return 'Check your email to confirm your account.' // email confirmation is on
30
+ return 'Account created.'
31
+ }
32
+
33
+ export async function signIn(email: string, password: string): Promise<string> {
34
+ const { data, error } = await baas.auth.signIn({ email, password })
35
+ if (error) return error.message // invalid_credentials (400), email_not_confirmed (403), rate_limited (429)
36
+ if (data.mfaRequired) return 'Enter the code from your authenticator app.' // then baas.auth.mfa.verify(factorId, code), see MFA below
37
+ return `Signed in as ${data.user.email}`
38
+ }
39
+ ```
40
+
41
+ `data` passed to `signUp` becomes `user.user_metadata`. Profile triggers in project templates read `name` (or `full_name`) and `avatar_url` from it.
42
+
43
+ ## Social sign-in (Google, GitHub, Apple, Microsoft, Discord, GitLab, LinkedIn, Slack, X)
44
+
45
+ ```ts
46
+ // inside an async function:
47
+ await baas.auth.signInWith('google', { redirectTo: `${location.origin}/dashboard` }) // or 'github' | 'apple' | 'microsoft' | 'discord' | 'gitlab' | 'linkedin' | 'slack' | 'x'; options: skipBrowserRedirect, flowType: 'pkce' (default) | 'implicit'
48
+ ```
49
+
50
+ In a browser this navigates away. PKCE is on by default: the client sends a code challenge and keeps the verifier; when the user returns with a one-time `?code=`, it swaps the code for the session (`baas.auth.exchangeCodeForSession(code)` does the same by hand), stores it, cleans the URL and fires `SIGNED_IN`. Redirects in the older form (`#access_token=...`) still work. Errors come back as `?error=...&error_code=...&error_description=...` (or in the `#fragment`) and show up in `baas.auth.getSession().error` plus a console warning. A disabled provider shows a JSON `provider_disabled` error page instead of redirecting.
51
+
52
+ React Native / Expo (no browser URL; more in `expo.md`):
53
+
54
+ ```ts
55
+ // lib/signInWithGoogle.ts (Expo; the client is lib/usebecky.ts)
56
+ import * as Linking from 'expo-linking'
57
+ import * as WebBrowser from 'expo-web-browser'
58
+ import { baas } from './usebecky'
59
+
60
+ export async function signInWithGoogle() {
61
+ const redirectTo = Linking.createURL('auth') // com.example.mynotes://auth in a build (app.json "scheme"), exp://<computer>/--/auth in Expo Go
62
+ const { data, error } = await baas.auth.signInWith('google', { redirectTo, skipBrowserRedirect: true }) // URL with the PKCE challenge
63
+ if (error) return error
64
+ const result = await WebBrowser.openAuthSessionAsync(data.url, redirectTo)
65
+ if (result.type !== 'success') return null // canceled
66
+ return (await baas.auth.setSessionFromUrl(result.url)).error // swaps ?code= for the session; null on success
67
+ }
68
+ ```
69
+
70
+ Native apps: Swift `signIn(with:redirectTo:)` and Kotlin `signInWithUrl` + `handleRedirect` do the same PKCE exchange (`ios.md`, `android.md`). Offer Sign in with Apple (iOS) or Credential Manager (Android) first: no redirect at all.
71
+
72
+ ## Native ID-token sign-in (Sign in with Apple, Google Sign-In / Credential Manager)
73
+
74
+ ```ts
75
+ // lib/signInWithApple.ts (Expo on iOS: expo-apple-authentication + expo-crypto)
76
+ import * as AppleAuthentication from 'expo-apple-authentication'
77
+ import * as Crypto from 'expo-crypto'
78
+ import { baas } from './usebecky'
79
+
80
+ export async function signInWithApple() {
81
+ const rawNonce = Crypto.randomUUID()
82
+ const hashedNonce = await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, rawNonce) // Apple gets SHA-256(raw) in hex
83
+ const credential = await AppleAuthentication.signInAsync({
84
+ requestedScopes: [AppleAuthentication.AppleAuthenticationScope.FULL_NAME, AppleAuthentication.AppleAuthenticationScope.EMAIL],
85
+ nonce: hashedNonce,
86
+ })
87
+ if (!credential.identityToken) return null
88
+ return baas.auth.signInWithIdToken({ provider: 'apple', token: credential.identityToken, nonce: rawNonce }) // { data: { user, session } }
89
+ }
90
+ // HTTP: POST /auth/v1/token?grant_type=id_token {"provider": "apple" | "google", "id_token": "...", "nonce": "<raw>"}
91
+ ```
92
+
93
+ - Swift: `try await baas.auth.signInWithApple()` (native sheet + nonce, all in one) or `signIn(withIdToken:provider:nonce:)`. Kotlin: `baas.auth.signInWithIdToken("google", idToken, rawNonce)` after Credential Manager (`ios.md`, `android.md`).
94
+ - Dashboard → Auth → Sign-in methods → Apple / Google: turn on, and add the token audience under "iOS bundle ID / Android client IDs (for native sign-in)" (config `providers.<p>.native_client_ids`): the iOS bundle ID for Apple, the iOS client ID for Google Sign-In on iOS. The provider's `client_id` (Google web client ID, used by Android Credential Manager's `setServerClientId`) is accepted too.
95
+ - Nonce: send the raw nonce. Apple's request gets SHA-256(raw) in hex; Google gets the raw nonce or its SHA-256. A token with a nonce is refused without the matching raw one.
96
+ - The server verifies signature (provider JWKS, cached), `iss`, `exp`, `aud`, nonce; then finds/creates the user like social sign-in (verified email links to an existing account; `user.created` / `user.updated` + `user.signed_in`). New users count against the monthly active users quota (`402 quota_exceeded`).
97
+
98
+ ## Passkeys
99
+
100
+ Turn on: Dashboard → Auth → Sign-in methods → Passkeys. Relying party = the site URL's domain (`localhost` locally). The user adds a passkey while signed in, then signs in without an email:
101
+
102
+ ```ts
103
+ // inside an async function:
104
+ await baas.auth.passkeys.register({ friendlyName: 'My laptop' }) // signed in; guest → permanent user
105
+ const { data, error } = await baas.auth.signInWithPasskey() // { data: { user, session } }; aal2 when Face ID / fingerprint / PIN was used
106
+ await baas.auth.passkeys.list() // { data: { passkeys } }; also rename(id, name), remove(id) (last sign-in method → last_sign_in_method)
107
+ ```
108
+
109
+ Passkey autofill: `autocomplete="username webauthn"` on the email input + `signInWithPasskey({ autofill: true })` on page load. React Native: pass `{ create }` / `{ get }` (options JSON in, credential JSON out, e.g. react-native-passkey). iOS: Associated Domains `webcredentials:<domain>` + apple-app-site-association; Android: add `android:apk-key-hash:...` in the dashboard (Passkeys → Settings) + `/.well-known/assetlinks.json`. Errors: `passkeys_disabled`, `passkey_cancelled`, `passkeys_unsupported`, `passkey_not_found`, `passkey_origin_not_allowed`, `invalid_challenge`.
110
+
111
+ ## Phone sign-in (SMS codes)
112
+
113
+ Turn on: Dashboard → Auth → Sign-in methods → Phone. Text messages: Pro 50/month, Business 1,000; Free only reaches the **test numbers** set in the dashboard (fixed codes, never a text). Default countries: EU/EEA, CH, UK, US, CA.
114
+
115
+ ```ts
116
+ // inside an async function:
117
+ await baas.auth.signInWithPhone('+49 170 1234567') // { data: {} } always; createUser: false = existing users only
118
+ const { data } = await baas.auth.verifyPhone('+49 170 1234567', '482913') // { data: { user, session } }; user.phone = '+491701234567'
119
+ await baas.auth.updatePhone('+44 7700 900123') // signed in; then verifyPhone(phone, code, { type: 'phone_change' })
120
+ ```
121
+
122
+ Limits: 5 codes per number per hour, 10 per IP per hour, 5 tries per code, 10 minutes. Errors: `invalid_phone`, `country_not_allowed`, `sms_rate_limited` (429), `quota_exceeded` (402, `sms_per_month`), `otp_expired`, `phone_exists`. Bot protection feature `phone` needs `captchaToken`.
123
+
124
+ ## Guests (anonymous users) and linking
125
+
126
+ Turn on: Dashboard → Auth → Sign-in methods → Guests. A guest is a real user (`is_anonymous: true`, no email); access rules use `auth.uid()` as usual (`auth.jwt()->>'is_anonymous'` tells guests apart). Linking keeps the user id and data:
127
+
128
+ ```ts
129
+ // inside an async function:
130
+ await baas.auth.signInAnonymously()
131
+ await baas.auth.linkEmail({ email: 'ada@example.com', password: 'a-long-password' }) // or:
132
+ await baas.auth.linkIdentity('google') // redirect + PKCE; applied when this client, signed in as this user, swaps the code
133
+ // also passkeys.register(), updatePhone() + verifyPhone(..., { type: 'phone_change' }), linkIdToken({ provider: 'apple', token })
134
+ ```
135
+
136
+ Errors: `anonymous_disabled`, `identity_already_exists` (that social account belongs to another user: sign in to it instead), `email_exists`. Guests inactive for 30 days (configurable) are deleted; they count toward monthly active users.
137
+
138
+ ## Single sign-on for companies (SAML, Business)
139
+
140
+ Dashboard → Auth → Single sign-on → Add a company (name + email domains → give the ACS URL / Entity ID / Metadata URL to their IT team → paste their metadata). In the app:
141
+
142
+ ```ts
143
+ // inside an async function:
144
+ await baas.auth.signInWithSSO({ domain: 'ada@acme.com' }) // work email or domain; or { providerId }; redirect + PKCE like signInWith()
145
+ ```
146
+
147
+ `settings().sso` is true when a company is set up. Errors: `sso_provider_not_found` (404), `plan_required` (402).
148
+
149
+ ## Magic link and 6-digit code
150
+
151
+ ```ts
152
+ // inside an async function:
153
+ const email = 'ada@example.com'
154
+ await baas.auth.sendMagicLink(email, { redirectTo: `${location.origin}/app`, createUser: true }) // data: {} (also for unknown emails); errors: rate_limited, magic_link_disabled, invalid email
155
+ // The email has a link (signs in on click) and a 6-digit code the user can type instead:
156
+ const code = '123456'
157
+ const { data, error } = await baas.auth.verifyCode(email, code) // data: { user, session }; otp_expired (400) for a wrong, used or expired code
158
+ ```
159
+
160
+ Without `createUser: true` unknown addresses get no email and no error. Each code works once; 5 attempts per code; 5 auth emails per address per 5 minutes.
161
+
162
+ ## Password reset
163
+
164
+ ```ts
165
+ // inside an async function:
166
+ await baas.auth.resetPassword('ada@example.com', { redirectTo: `${location.origin}/reset` }) // data: {} (never reveals if the email exists)
167
+ ```
168
+
169
+ ```ts
170
+ // src/reset.ts, loaded on /reset: the client finishes the redirect and fires PASSWORD_RECOVERY
171
+ import { baas } from './lib/usebecky'
172
+
173
+ baas.auth.onAuthStateChange(async (event) => {
174
+ if (event !== 'PASSWORD_RECOVERY') return
175
+ const newPassword = prompt('Choose a new password') ?? '' // or your own form
176
+ const { error } = await baas.auth.updateUser({ password: newPassword }) // signs out other devices
177
+ if (error) alert(error.message)
178
+ })
179
+ // Or with the emailed code: await baas.auth.verifyCode(email, code, 'recovery'), then updateUser({ password })
180
+ ```
181
+
182
+ ## Session and state
183
+
184
+ ```ts
185
+ // inside an async function:
186
+ const session = baas.auth.getSession().data.session // sync; null when signed out
187
+ const { data, error } = await baas.auth.getUser() // data: { user: User | null }, fresh from the server
188
+ const user = data?.user ?? null
189
+ await baas.auth.ready // stored session loaded (async storage, redirects)
190
+ const stop = baas.auth.onAuthStateChange((event, session) => {
191
+ // INITIAL_SESSION (once, after load) | SIGNED_IN | SIGNED_OUT | TOKEN_REFRESHED | USER_UPDATED | PASSWORD_RECOVERY | MFA_CHALLENGE_VERIFIED
192
+ })
193
+ await baas.auth.signOut() // this device
194
+ await baas.auth.signOut({ everywhere: true }) // all devices
195
+ ```
196
+
197
+ - Sessions persist in `localStorage` (browsers) or the `storage` option (pass AsyncStorage in React Native). Without either, sessions live in memory.
198
+ - Access tokens refresh automatically before they expire, once across tabs. Refresh tokens are single use; a reused one revokes the session (`refresh_token_already_used`, then `SIGNED_OUT`). Never store or refresh sessions yourself.
199
+ - Tabs stay in sync: signing out in one tab fires `SIGNED_OUT` in the others.
200
+ - Gate UI on `INITIAL_SESSION` to avoid flashing the signed-out view.
201
+
202
+ ```ts
203
+ // src/useSession.ts: React hook
204
+ import { useEffect, useState } from 'react'
205
+ import type { Session } from 'usebecky'
206
+ import { baas } from './lib/usebecky'
207
+
208
+ export function useSession() {
209
+ const [session, setSession] = useState<Session | null>(baas.auth.getSession().data.session)
210
+ const [loading, setLoading] = useState(true)
211
+ useEffect(() => baas.auth.onAuthStateChange((_e, s) => { setSession(s); setLoading(false) }), [])
212
+ return { session, user: session?.user ?? null, loading }
213
+ }
214
+ ```
215
+
216
+ ## Updating the user
217
+
218
+ ```ts
219
+ // inside an async function:
220
+ await baas.auth.updateUser({ data: { name: 'Ada L.' } }) // merged into user_metadata; fires USER_UPDATED
221
+ await baas.auth.updateUser({ email: 'new@example.com' }) // confirmation sent to the new address; email_exists (409)
222
+ await baas.auth.updateUser({ password: 'new-password' }) // aal2_required (403) for users with verified MFA
223
+ ```
224
+
225
+ ## MFA (authenticator apps, TOTP)
226
+
227
+ ```ts
228
+ // inside an async function:
229
+ // Enroll (signed in)
230
+ const { data: factor, error } = await baas.auth.mfa.enroll({ friendlyName: 'Phone' }) // data: { id, type: 'totp', secret, uri }
231
+ if (error) return alert(error.message)
232
+ // render factor.uri as a QR code, then verify the code the authenticator app shows:
233
+ await baas.auth.mfa.verify(factor.id, '123456') // session becomes aal2
234
+
235
+ // At sign-in
236
+ const { data } = await baas.auth.signIn({ email: 'ada@example.com', password: 'a-long-password' })
237
+ if (data?.mfaRequired) {
238
+ const { data: factors } = await baas.auth.mfa.listFactors() // data: { all, totp } (totp = verified factors)
239
+ await baas.auth.mfa.verify(factors!.totp[0].id, '654321') // invalid_mfa_code
240
+ }
241
+ baas.auth.mfa.getAssuranceLevel() // { currentLevel: 'aal1', nextLevel: 'aal2' } → still needs a code
242
+ await baas.auth.mfa.unenroll(factor.id) // data: { id }
243
+ ```
244
+
245
+ Require it in data with a policy: `(auth.jwt() ->> 'aal') = 'aal2'`.
246
+
247
+ ## Server side
248
+
249
+ The browser client mirrors the access token into the `ub-access-token` cookie (`SameSite=Lax`, path `/`, expires with the token). `baas.auth.getUser()` from `usebecky/server` reads `Authorization: Bearer <token>` first, then that cookie, verifies the token with usebecky and caches the result ~30 s.
250
+
251
+ All three are server code (secret key):
252
+
253
+ ```tsx
254
+ // app/notes/page.tsx (Next.js App Router, server component)
255
+ import { cookies } from 'next/headers'
256
+ import { redirect } from 'next/navigation'
257
+ import { baas } from 'usebecky/server'
258
+
259
+ export default async function NotesPage() {
260
+ const jar = await cookies()
261
+ const user = await baas.auth.getUser(jar) // User | null
262
+ if (!user) redirect('/login')
263
+ const { data } = await baas.as(jar).from('notes').select()
264
+ return <pre>{JSON.stringify(data, null, 2)}</pre>
265
+ }
266
+ ```
267
+
268
+ ```ts
269
+ // app/api/me/route.ts (Next.js route handler; a Remix loader, Hono, Bun or Deno handler gets a Request too)
270
+ import { baas } from 'usebecky/server'
271
+
272
+ export async function GET(request: Request) {
273
+ const user = await baas.auth.getUser(request) // User | null
274
+ if (!user) return Response.json({ error: { code: 'not_signed_in', message: 'Sign in first.' } }, { status: 401 })
275
+ return Response.json({ user })
276
+ }
277
+ ```
278
+
279
+ ```ts
280
+ // server.ts (Express)
281
+ import express from 'express'
282
+ import { baas } from 'usebecky/server'
283
+
284
+ const app = express()
285
+ app.use(baas.auth.middleware()) // req.user = User | null
286
+ app.get('/api/me', baas.auth.requireUser(), (req, res) => res.json({ user: req.user }))
287
+ app.listen(3000)
288
+ ```
289
+
290
+ Any other caller (mobile app, CLI) sends the access token: `Authorization: Bearer <session.access_token>`.
291
+
292
+ `baas.as(input)` accepts the same inputs plus `req.user`, and runs queries as that user. `usebecky/server` imports `node:crypto`: use it in Node runtimes (route handlers, server components, server actions, API servers), not in Edge runtimes.
293
+
294
+ ## Admin user management (server, secret key)
295
+
296
+ ```ts
297
+ // scripts/users.ts: server only (secret key)
298
+ import { baas } from 'usebecky/server'
299
+
300
+ const { data: page } = await baas.auth.admin.listUsers({ page: 1, perPage: 50, q: '@example.com' }) // data: { users, total, page, perPage }
301
+ const { data: user, error } = await baas.auth.admin.createUser({ email: 'grace@example.com', password: 'a-long-password', emailConfirm: true, userMetadata: { name: 'Grace' }, appMetadata: { role: 'admin' } }) // data: User
302
+ if (error) throw error
303
+ await baas.auth.admin.getUserById(user.id)
304
+ await baas.auth.admin.updateUser(user.id, { ban: '24h' }) // 'none' | '24h' | 'forever' | '<n>h'; banning signs the user out
305
+ await baas.auth.admin.updateUser(user.id, { appMetadata: { role: 'admin' } })
306
+ await baas.auth.admin.inviteUser('alan@example.com', { redirectTo: 'https://app.example.com/welcome' }) // data: User (invite email sent)
307
+ await baas.auth.admin.signOutUser(user.id) // data: { ok: true }
308
+ await baas.auth.admin.createSession(user.id) // data: Session (access + refresh token). For automated tests: no password, code or captcha; aal1; on the activity log
309
+ await baas.auth.admin.deleteUser(user.id) // data: { id }; user_has_data (409) while your tables still reference the user
310
+ ```
311
+
312
+ ## Emails
313
+
314
+ Auth email templates, sender, SMTP, the welcome email and sending your own emails (`baas.emails.send`, server only): `emails.md`.
315
+
316
+ ## Bot protection (captcha)
317
+
318
+ Optional, per project: Dashboard → Settings → Bot protection (Cloudflare Turnstile or hCaptcha; site key + secret key). When on, these calls need the widget's token as `captchaToken` (sent as `captcha_token`); forms and newsletter sign-ups only when ticked there:
319
+
320
+ ```ts
321
+ // inside an async function:
322
+ const email = 'ada@example.com'
323
+ const password = 'a-long-password'
324
+ const captchaToken = '<token from the Turnstile or hCaptcha widget>' // e.g. turnstile.getResponse()
325
+ const { data: s } = await baas.auth.settings() // s.captcha: { provider: 'turnstile' | 'hcaptcha', site_key, features: ['signup', 'signin', 'magic_link', 'recover', ...] } | null
326
+ await baas.auth.signUp({ email, password, captchaToken })
327
+ await baas.auth.signIn({ email, password, captchaToken })
328
+ await baas.auth.sendMagicLink(email, { captchaToken })
329
+ await baas.auth.resetPassword(email, { captchaToken })
330
+ await baas.forms.submit('contact', { name: 'Ada', email, message: 'Hello!' }, { captchaToken })
331
+ await baas.newsletter.subscribe(email, { captchaToken })
332
+ ```
333
+
334
+ Swift and Kotlin take an optional `captchaToken` as the last parameter of `signUp`, `signIn(email:password:)`, `sendMagicLink` and `resetPassword` (`ios.md`, `android.md`). If you turn on Bot protection for sign-in, your app must show a captcha. Native apps can't do that easily yet; keep sign-in protection off for apps, and protect forms instead.
335
+
336
+ Render the widget with `s.captcha.site_key` (Turnstile: `<div class="cf-turnstile" data-sitekey="...">` + `https://challenges.cloudflare.com/turnstile/v0/api.js`; hCaptcha: `<div class="h-captcha" data-sitekey="...">` + `https://js.hcaptcha.com/1/api.js`). A token works once: reset the widget after each attempt. Plain HTML forms need no code (the widget's `cf-turnstile-response` / `h-captcha-response` field is read and never stored). Secret-key (server) calls never need a token. Turnstile test keys that always pass: site `1x00000000000000000000AA`, secret `1x0000000000000000000000000000000AA`.
337
+
338
+ ## Profiles on sign-up
339
+
340
+ The SQL editor cannot add triggers on `auth.users`. Choose one:
341
+
342
+ 1. Client: after `SIGNED_IN`, `baas.from('profiles').upsert({ id: session.user.id, display_name: session.user.user_metadata.name ?? null }, { onConflict: 'id', ignoreDuplicates: true })` (needs an insert policy `with check (id = auth.uid())`).
343
+ 2. Server: a `user.created` webhook that inserts with `baas.admin.from('profiles').upsert(...)`.
344
+ 3. Most project templates (`saas`, `downloads`, `mobile`, `blog`, `team`, `community`, `bookings`) already include `profiles` filled by a trigger at sign-up (`templates.md`).
345
+
346
+ ## Auth error codes
347
+
348
+ | Code | Status | Meaning |
349
+ |---|---|---|
350
+ | `invalid_credentials` | 400 | Wrong email or password |
351
+ | `email_not_confirmed` | 403 | Confirmation required; offer `resend(email, 'signup')` |
352
+ | `user_already_exists` | 409 | Sign-up with a taken email |
353
+ | `email_exists` | 409 | Email change to a taken address |
354
+ | `weak_password` | 400 | Shorter than 6 characters |
355
+ | `signup_disabled`, `email_password_disabled`, `magic_link_disabled` | 403 | Turned off in settings |
356
+ | `provider_disabled`, `provider_not_configured` | 400 | Social provider off or missing credentials (native: no bundle / client ID) |
357
+ | `invalid_id_token`, `id_token_expired`, `invalid_nonce` | 400 | Native ID token refused (wrong audience: the message names it and what to add) |
358
+ | `provider_not_supported` | 400 | `grant_type=id_token` with a provider other than `apple` / `google` |
359
+ | `quota_exceeded` | 402 | New sign-up past the plan's monthly active users, counted for the whole team (existing users still sign in) |
360
+ | `otp_expired` | 400 | Code or link wrong, used or expired |
361
+ | `invalid_auth_code`, `invalid_code_verifier`, `auth_code_required` | 400 | PKCE exchange failed: the one-time `?code=` was used, expired (5 minutes) or doesn't match the verifier; start the sign-in again |
362
+ | `invalid_code_challenge`, `invalid_code_challenge_method` | 400 | `/authorize` got a malformed PKCE challenge or a method other than `S256` |
363
+ | `invalid_mfa_code` | 400 | Wrong authenticator code |
364
+ | `aal2_required` | 403 | Verify MFA before changing email or password |
365
+ | `user_banned` | 403 | Banned by an admin |
366
+ | `rate_limited` | 429 | Too many attempts or emails |
367
+ | `captcha_required` | 400 | Bot protection is on and no `captchaToken` was sent: show the widget |
368
+ | `captcha_failed` | 400 | Token wrong, reused, expired, or the check timed out: reset the widget and retry |
369
+ | `not_signed_in` | 401 | Needs a session (`updateUser`, `mfa.*`, `passkeys.*`, `link*`, `updatePhone`) |
370
+ | `passkeys_disabled`, `phone_disabled`, `anonymous_disabled` | 403 | Turned off in Sign-in methods |
371
+ | `passkey_cancelled`, `passkeys_unsupported` | 0 | Person closed the passkey sheet / no WebAuthn here (SDK only) |
372
+ | `passkey_not_found`, `passkey_verification_failed`, `passkey_origin_not_allowed`, `invalid_challenge` | 400 | Passkey refused (deleted, wrong page domain, expired request) |
373
+ | `last_sign_in_method` | 409 | Removing the user's only way to sign in |
374
+ | `invalid_phone`, `country_not_allowed` | 400 / 403 | Phone number malformed / country not allowed by the project |
375
+ | `sms_rate_limited` | 429 | Too many codes for this number, network or project |
376
+ | `identity_already_exists` | 409 | Linking a social account that belongs to another user |
377
+ | `sso_provider_not_found` | 404 | No single sign-on connection for that email domain |
378
+ | `invalid_refresh_token`, `refresh_token_already_used`, `session_expired` | 401 | Session ended; the SDK fires `SIGNED_OUT` |
379
+ | `token_expired`, `invalid_token` | 401 | Access token expired or invalid; the SDK refreshes and retries once |
@@ -0,0 +1,51 @@
1
+ # Cache (Business plan)
2
+
3
+ Built into usebecky for **Business** projects; on Free and Pro every call finds nothing (`get` → `null`) and the dashboard shows an upgrade card. Tell the user to upgrade instead of working around it. Three parts:
4
+
5
+ 1. **Faster reads** for tables: no code. The user switches a table on in Dashboard → Cache. REST/SDK reads of it are cached, every committed change (any source: app, SQL editor, Functions, triggers) clears them within milliseconds, the app always reads its own writes, and access rules still apply (copies are shared only when the rules don't depend on the user; per user when they use `auth.uid()`/`auth.jwt()`; never when a rule uses a subquery, `now()` or a custom function). Responses carry `X-UseBecky-Cache: hit | miss | bypass`. To make a per-team table cacheable, prefer a rule on the row itself (`team_id = (auth.jwt() -> 'app_metadata' ->> 'team_id')::uuid`) over a subquery.
6
+ 2. **`baas.cache`** in server code (`usebecky/server`, secret key) and in Functions (`ctx.baas.cache`). Never in browser or app code: the publishable key gets `403 secret_key_required`.
7
+ 3. **Public files from the edge**: pass the upload's `version` to `getPublicUrl` (below). Links without a version keep the file's own Cache-Control (1 hour by default) and may show an old file that long after a replace.
8
+ 4. Reads whose filters contain `now`, `today`, `tomorrow` or `yesterday` are never cached.
9
+
10
+ ```ts
11
+ // server.ts (server only)
12
+ import { baas } from 'usebecky/server'
13
+
14
+ export async function homeStats() {
15
+ // Saved value, or compute + save for 5 minutes. null/undefined results aren't saved.
16
+ return baas.cache.getOrSet('home:stats', async () => ({ users: 1240, orders: 87 }), { ttl: '5m' })
17
+ }
18
+
19
+ export async function cacheBasics() {
20
+ await baas.cache.set('weather:berlin', { temp: 7.4 }, { ttl: '10m' }) // ttl: seconds or '30s' | '10m' | '2h' | '7d' (max 30 days, default 1 h); any JSON ≤ 1 MB
21
+ const w = await baas.cache.get<{ temp: number }>('weather:berlin') // value or null
22
+ await baas.cache.delete('weather:berlin') // true when removed
23
+ return w
24
+ }
25
+
26
+ export async function allowSignup(ip: string) {
27
+ // At most 5 tries per hour per IP; the window starts with the first try; refused tries don't count.
28
+ const { allowed, retryAfter } = await baas.cache.limit(`signup:${ip}`, 5, '1h') // also: limit, remaining, resetAt, error? (see onError below)
29
+ return allowed ? { ok: true } : { ok: false, retryAfter }
30
+ }
31
+ ```
32
+
33
+ ```ts
34
+ // src/logo.ts
35
+ import { baas } from './lib/usebecky'
36
+
37
+ export async function uploadLogo(file: File) {
38
+ const { data, error } = await baas.storage.from('public').upload('logo.png', file, { upsert: true })
39
+ if (error) throw error
40
+ // ?v=<version>: kept at Cloudflare's edge, a new upload gives a new link (never stale).
41
+ return baas.storage.from('public').getPublicUrl('logo.png', { version: data.version }).data.publicUrl
42
+ }
43
+ ```
44
+
45
+ Rules:
46
+ - `get`/`set`/`delete` fail open: an outage or a non-Business project makes `get` return `null` and `set`/`delete` return `false`, plus one console warning a minute. Code must work with an empty cache (values can also vanish when the cache server restarts).
47
+ - `limit` when the cache can't be asked (`error` set): by default the try goes through on an outage (a 5xx other than 507, or the network), so users are never locked out, and is refused on everything else (429 requests used up, 507 cache full, 400/401/403 wrong key). `{ onError: 'refuse' }` refuses on every error (use it for sign-in tries), `{ onError: 'allow' }` lets every try through (low-risk forms). A non-Business project (`plan_required`) is always let through. `max` 1–1,000,000. Only wrong arguments throw.
48
+ - Keys: 1–512 bytes, no control characters; use `thing:id` patterns and one key per rate-limit rule.
49
+ - Memory: 512 MB per project, shared with the Redis add-on. Full → `set` returns `false` (API `507 cache_full`).
50
+ - Don't build your own invalidation for tables with faster reads: changes clear them. Don't cache table reads in `baas.cache` too.
51
+ - For lists, sorted sets, pub/sub or queues use the Redis add-on (`addons.md`).
@@ -0,0 +1,127 @@
1
+ # Ready-made UI components (`@usebecky/ui`)
2
+
3
+ Finished, accessible, themable UI for usebecky: sign-in, user menu, contact form, newsletter, waitlist, pricing table, checkout, embedded payment form, customer portal, paywall and file upload. React components, plus Web Components (`<ub-...>`) for any website.
4
+
5
+ ## When to use them
6
+
7
+ - Prefer a component over a hand-rolled form whenever the user asks for one of these screens ("add a login page", "contact form", "pricing page", "let users upload an avatar"). They already handle validation, loading, errors, success states, spam protection, MFA, trials, 3-D Secure, accessibility, mobile and dark mode.
8
+ - Write custom code with the `usebecky` SDK instead when the user explicitly asks for their own UI, needs a flow the props can't express, or the app is not React and not a web page (React Native, Swift, Kotlin: components are web only).
9
+ - Never mix: do not wrap a component's behavior in your own `onSubmit` logic; use its callbacks (`onSignedIn`, `onSuccess`, ...).
10
+
11
+ ## Install (React: Next.js, Vite, Remix)
12
+
13
+ ```bash
14
+ npm install @usebecky/ui usebecky
15
+ ```
16
+
17
+ ```tsx
18
+ // src/main.tsx (Vite). Next.js: put the provider in a 'use client' app/providers.tsx used by app/layout.tsx.
19
+ import { createRoot } from 'react-dom/client'
20
+ import { UseBeckyProvider, SignedIn, SignedOut, SignIn, UserButton } from '@usebecky/ui'
21
+ import '@usebecky/ui/styles.css'
22
+ import { baas } from './lib/usebecky' // the app's existing client
23
+
24
+ function App() {
25
+ return (
26
+ <>
27
+ <SignedOut><SignIn /></SignedOut>
28
+ <SignedIn><UserButton /></SignedIn>
29
+ </>
30
+ )
31
+ }
32
+
33
+ createRoot(document.getElementById('root')!).render(
34
+ <UseBeckyProvider client={baas}>
35
+ <App />
36
+ </UseBeckyProvider>,
37
+ )
38
+ ```
39
+
40
+ - Reuse the app's existing `baas` client (`lib/usebecky.ts`); never create a second browser client.
41
+ - Import `@usebecky/ui/styles.css` once (root layout or entry). Components inject their CSS if it's missing, with a console note.
42
+ - Components ship with `'use client'`; they can be rendered from Next.js server components.
43
+ - Without a provider, components call `createClient()` (reads `NEXT_PUBLIC_USEBECKY_URL` / `NEXT_PUBLIC_USEBECKY_PUBLISHABLE_KEY`, `EXPO_PUBLIC_*`, `USEBECKY_*`). Vite needs the provider. `<UseBeckyProvider url="..." publishableKey="ub_pk_...">` also works.
44
+ - Hooks: `useBecky()` (client), `useUser()` / `useSession()` (`undefined` while loading, then value or `null`), `useAccess('pro')` (`undefined` while checking, then boolean).
45
+
46
+ ## Install (any website: HTML, Wix, Squarespace, WordPress, Webflow)
47
+
48
+ ```html
49
+ <script src="https://cdn.jsdelivr.net/npm/@usebecky/ui@0/dist/usebecky-ui.js" defer></script>
50
+ <ub-config url="https://api.usebecky.com" key="ub_pk_..."></ub-config>
51
+ <ub-sign-in redirect-to="/dashboard"></ub-sign-in>
52
+ ```
53
+
54
+ - One self-contained IIFE bundle (Preact + SDK + CSS, ~62 KB gzip). The API also serves it at `https://api.usebecky.com/ui/v1/usebecky-ui.js`: use that address until the npm package (and so the jsDelivr link) is published.
55
+ - Every element renders in Shadow DOM: site CSS can't break it (even `* { all: unset }`).
56
+ - `url` + `key` can also go on each element. Attributes are kebab-case versions of the React props; arrays are comma lists (`providers="google,github"`); objects are JSON in single quotes (`features='{"pro":["A","B"]}'`).
57
+ - Callbacks become bubbling DOM events with `detail`: `ub-signed-in`, `ub-signed-out`, `ub-success`, `ub-error`, `ub-subscribed`, `ub-joined`, `ub-uploaded`.
58
+ - `el.setProps({ ... })` sets any prop from JS (functions too). `UseBeckyUI.configure({ url, key, theme, appearance, labels })` and `UseBeckyUI.getClient()` are global.
59
+ - Wix "Embed HTML" is an iframe: fine for forms, newsletter, waitlist, pricing; not for OAuth sign-in.
60
+
61
+ ## Components
62
+
63
+ | React | HTML | One line |
64
+ |---|---|---|
65
+ | `<SignIn />`, `<SignUp />`, `<Auth />` (tabs) | `<ub-sign-in>`, `<ub-sign-up>`, `<ub-auth>` | Email + password, 6-digit email code, enabled social providers, forgot password (code), confirm email, TOTP MFA |
66
+ | `<UserButton />` | `<ub-user-button>` | Avatar menu (account, billing, sign out); signed out: "Sign in" button opening a sign-in dialog |
67
+ | `<SignedIn>`, `<SignedOut>` | `<ub-signed-in>`, `<ub-signed-out>` | Show children only when signed in / out (HTML: light DOM, page-styled) |
68
+ | `<ContactForm form="f_..." />` | `<ub-contact-form form="f_...">` | Fields from the form definition (`baas.forms.get`), client validation, honeypot `_gotcha` + `_t`, success message |
69
+ | `<NewsletterSignup list="weekly" />` | `<ub-newsletter list="weekly">` | `variant="card"` or `"inline"`; explains double opt-in ("Check your inbox") |
70
+ | `<Waitlist />` | `<ub-waitlist>` | Inserts `{ email }` into `waitlist`, counter from `rpc('waitlist_count')`, `referrals` share links |
71
+ | `<PricingTable />` | `<ub-pricing-table>` | `payments.products()`, monthly/yearly toggle, trial badges, highlight, "Current plan"/"Manage" via `payments.me()`, `mode="hosted"` or `"embedded"` |
72
+ | `<CheckoutButton price="pro_monthly" />` | `<ub-checkout-button price="pro_monthly">` | Hosted Stripe Checkout (signs the visitor in first if needed) |
73
+ | `<PaymentForm price="pro_monthly" />` | `<ub-payment-form price="pro_monthly">` | Embedded Stripe Payment Element + order summary; `createPayment` → `confirmPayment`/`confirmSetup` (`redirect: 'if_required'`) → `waitForAccess` |
74
+ | `<CustomerPortalButton />` | `<ub-portal-button>` | `payments.portal()`; hidden when signed out |
75
+ | `<Paywall feature="pro" fallback={...}>` | `<ub-paywall feature="pro">` | Children only with access; default fallback = pricing table of products granting the feature (HTML fallback: child with `slot="fallback"`) |
76
+ | `<FileUpload bucket="avatars" />` | `<ub-file-upload bucket="avatars">` | Drag and drop, type/size checks, progress, image preview, path `<user id>/<time>-<name>`, `onUploaded(path, info)` |
77
+
78
+ Main props (HTML attribute in parentheses when the name differs):
79
+
80
+ - Auth: `redirectTo` (`redirect-to`), `providers`, `methods` (`['password','code']`), `collectName`, `logo`, `title`/`subtitle` (`heading`/`subheading`), `signUpUrl`, `signInUrl`, `defaultTab` (Auth), `onSignedIn(user, session)`.
81
+ - UserButton: `accountUrl`, `showBilling`, `afterSignOutUrl`, `signInUrl`, `menuItems` (React), `onSignedOut`.
82
+ - ContactForm: `form` (id `f_...` or key), `title` (`heading`; React `title` alone = form name), `description`, `submitLabel`, `defaultValues`, `onSuccess({ message, values })`, `onError`.
83
+ - NewsletterSignup: `list`, `variant`, `tags`, `title`, `description`, `buttonLabel`, `finePrint`, `collectName`, `onSubscribed({ email, status })`.
84
+ - Waitlist: `table` (`waitlist`), `countFunction` (`waitlist_count`, `false` hides), `referrals`, `onJoined({ email, referralCode })`.
85
+ - PricingTable: `mode`, `products` (keys, order), `features` (`{ [productKey]: string[] }`; default bullets = description lines starting with `- ` plus non-slug feature names), `highlight` (key or `false`), `defaultInterval`, `freePlan` (`{ name, description, features, buttonLabel, href }`), `feature`, `successUrl`, `cancelUrl`, `signInUrl`, `onSuccess`.
86
+ - CheckoutButton: `price`, children = label, `quantity`, `successUrl`, `cancelUrl`, `promotionCodes`, `variant`, `block`, `signInUrl`.
87
+ - PaymentForm: `price`, `coupon` (promotion code), `quantity`, `feature`, `successUrl`, `hideSummary`, `onSuccess({ mode, product, price, subscriptionId, hasAccess })`, `onError`.
88
+ - FileUpload: `bucket`, `accept`, `maxSize` (`"5MB"`), `multiple`, `folder`, `path(file, user)` (React), `upsert`, `hidePreview`, `onUploaded(path, { path, bucket, publicUrl, file })`, `onError`.
89
+
90
+ Every component also takes `theme` (`light` | `dark` | `auto`), `appearance`, `labels`, `className`, `style` (HTML: `theme`, `accent`, `radius`, `font`, `appearance`, `labels`).
91
+
92
+ ## What the project needs (tell the user)
93
+
94
+ - Sign-in: methods and providers turned on in Dashboard → Auth → Sign-in methods; the site's URL in Settings → General → Your app’s addresses (for social sign-in and email links).
95
+ - ContactForm: a form in Dashboard → Forms (its id is `f_...`).
96
+ - NewsletterSignup: nothing (default list); other lists in Newsletter → Settings → Lists.
97
+ - Waitlist: the `waitlist` table and `waitlist_count()` (Waitlist template, or the same SQL).
98
+ - Payments: Stripe connected, products created; customer portal saved once in Stripe. If embedded forms answer `stripe_elements_not_configured`, payment forms are temporarily unavailable; hosted checkout keeps working.
99
+ - FileUpload: the bucket plus the "Users manage their own folder" policy preset (or matching `storage.objects` policies).
100
+ - Bot protection (optional): Dashboard → Settings → Bot protection (Turnstile or hCaptcha keys, which actions). Nothing to change in code; see below.
101
+
102
+ ## Bot protection (captcha)
103
+
104
+ - Automatic once enabled in Dashboard → Settings → Bot protection. No props or attributes: `SignIn`/`SignUp`/`Auth` read `auth.settings().captcha`, `ContactForm` reads `forms.get(id).captcha`, `NewsletterSignup` checks `auth.settings().captcha.features` for `'newsletter'` (`Waitlist` never needs one).
105
+ - Per action (`features`): `signup`, `signin` (password), `magic_link` (email code request; on the code screen only after "Send a new code"), `recover` (forgot password), `forms`, `newsletter`. The widget renders above the submit button, which stays disabled until there is a token; the token goes as `captchaToken`; the widget resets after every attempt (tokens are single-use) and on `captcha_required` / `captcha_failed` (friendly text: labels `captchaRequired`, `captchaFailed`, `captchaLoadFailed`, `captchaResendHint`).
106
+ - Scripts load lazily, once, from the providers' CDNs (`https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit`, `https://js.hcaptcha.com/1/api.js?render=explicit`); a strict CSP must allow them (script, frame). The widget follows the component theme and renders inside the Web Components' Shadow DOM.
107
+ - Custom React forms: `<CaptchaWidget provider siteKey onToken onExpire ref={ref} />` (`ref.current.reset()` after each attempt) with the SDK's `captchaToken` option. Don't add a widget next to a ready-made component: it already has one.
108
+
109
+ ## Theming and text
110
+
111
+ ```css
112
+ :root { --ub-accent: #e11d48; --ub-radius: 10px; --ub-font: "Inter", system-ui, sans-serif; }
113
+ ```
114
+
115
+ - Variables: `--ub-accent`, `--ub-accent-text` (auto black/white by default), `--ub-radius`, `--ub-font`, `--ub-font-size`, `--ub-background`, `--ub-text`, `--ub-muted`, `--ub-border`, `--ub-danger`, `--ub-success`; dark-only overrides `--ub-dark-*`. They pierce Shadow DOM.
116
+ - React: `appearance={{ accent, radius, font, dark: { accent }, bare: true }}` on a component or the provider (`bare` removes the card chrome).
117
+ - `labels={{ signInTitle: 'Willkommen zurück' }}` on a component, the provider or `<ub-config labels='{...}'>`; defaults in `defaultLabels`.
118
+ - Stable classes `.ub-*` (React) and `::part(card|title|button|button-primary|input|label|alert|plan|plan-highlight|dropzone|avatar|menu|modal)` (Web Components).
119
+
120
+ ## Gotchas
121
+
122
+ - Hiding is not security: `Paywall`, `SignedIn` and `ub-paywall` only change what renders. Protect data with RLS (`billing.has_access('pro')`).
123
+ - Components show developer-facing setup notes (grey, dashed) for misconfiguration (missing client, unknown form id, no products, Stripe not set up) and log details to the console; read them before debugging.
124
+ - `PricingTable` and `CheckoutButton` open a sign-in dialog for signed-out visitors before checkout; pass `signInUrl` to use the app's own page instead.
125
+ - Hosted checkout returns to the current page with `?checkout=success` unless `successUrl` or dashboard defaults say otherwise; `PricingTable` shows a thank-you notice and refreshes the plan.
126
+ - Stripe.js is loaded on demand from `https://js.stripe.com/v3`; a strict Content-Security-Policy must allow `js.stripe.com` (script, frame) for `PaymentForm`.
127
+ - A `captcha_required` error from a ready-made component means bot protection was turned on after the page loaded: it reloads the settings (ContactForm: the form) and shows the check by itself.