Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
docs: describe the code sign-in and the new sign-in page
spacesdrive23d561345aa2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ee5ac13..4f4f78c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -56,9 +56,16 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).**Docs and app addresses**- The docs moved from the app to the public site; links in the app (sign-in page, user menu, command palette, Settings) open `https://twiligent.ujjwal.fyi/docs`, and old `/docs/...` links in the app redirect to the same page there- The app moves to `https://app.twiligent.ujjwal.fyi`. The app's old paths on `twiligent.ujjwal.fyi` (such as `/login` and `/settings`) redirect to the new address. The Worker's `FRONTEND_URL` and `ALLOWED_ORIGINS`, the Supabase Auth URLs and the Google sign-in origins must name the new address-- The sign-in page opens on the sign-up form when the link ends in `?mode=signup`+- The sign-in page shows the sign-up headline and Sign up with Google when the link ends in `?mode=signup`- `npm run build`, `npm test` and `npm run typecheck` at the root now cover the site as well+**Sign-in page**+- The sign-in page follows the Activepieces layout in the Twiligent brand: one centred card, styled like the app's dialogs, over a blurred picture of the dashboard. The split layout and its brand panel are gone (ADR-036)+- Signing in starts with Continue with Google or an email address: Twiligent emails a 6-digit code that signs you in, and creates the account the first time an address is used. Use password opens email and password sign-in, Forgot your password? and Create one with a password+- A password sign-in for an address that was never confirmed sends a sign-in code instead of failing+- Each code sign-in is one email against the daily cap; when the cap is reached, the sign-in page shows that email codes are paused until tomorrow and points to Google or the password+- Without the Send Email hook, Supabase's own Magic Link email signs people in with a link; the self-hosting docs explain how to add the code to it+**Protected main branch**- `main` only accepts pull requests whose CI check passed on an up-to-date branch, merged with rebase; force pushes and deleting the branch are blocked for everyone (ADR-034)@@ -122,6 +129,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).- The Reddit "Upvoted" column is now "Upvote rate", with an explanation of what it measures and why some rows show a dash- README: `VITE_API_URL` example now ends in `/api`; the setup SQL now creates `tracked_posts` and turns on row level security for all four tables- Buttons rendered as links no longer log a Base UI native-button warning+- In dark mode, Continue with Google showed the G on a white square; the app now draws the button in its own outline style, with Google's button over it handling the sign-in### Removeddiff --git a/DECISIONS.md b/DECISIONS.mdindex 3edbff2..b5d68a3 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -745,3 +745,26 @@ Records every significant architectural decision, the alternatives considered, a- The search index is rebuilt on every site build and downloaded only when someone searches, so it adds nothing to the first load.- Self-hosters do not need the site: they deploy only the app and the Worker, and read the docs on the project's site.- The site follows the brand kit in `frontend/public/` but keeps its own copy of the tokens in `site/src/index.css` (see `docs/brand-notes.md`), so a token change must be made in both places.++---++## ADR-036: Sign in with an emailed code first, in the Activepieces layout++**Date:** 2026-10-15+**Status:** Accepted++**Decision:** The app's sign-in page follows the Activepieces sign-in layout in Twiligent's brand and the dashboard's style: one centred card in the app's dialog styling (`rounded-dialog`, `border-line`, `bg-popover`, `shadow-lg`) over a blurred picture of the dashboard (`pages/LoginBackdrop.tsx`, built from the shared components with sample figures, `aria-hidden`, loaded with `React.lazy`). The first view offers Continue with Google, then one email field that sends a 6-digit sign-in code (`supabase.auth.signInWithOtp` with `shouldCreateUser: true`, checked with `verifyOtp` type `email`), then a quiet Use password link. The code signs the person in and creates the account the first time an address is used, so Google and an emailed code are the default ways to join. Password sign-in, password sign-up (with its confirmation code when **Confirm email** is on) and the reset-by-code flow stay behind the password view. A password sign-in that fails with `email_not_confirmed` sends a sign-in code instead. `GoogleSignInButton` draws an outline button in the app's style and lays Google's real button over it, nearly transparent. The split layout with its brand panel (`LoginForm.tsx`, `LoginBrandPanel.tsx`) is removed.++**Context:** The owner asked for the Activepieces sign-in exactly, in the Twiligent brand and the dashboard's style. The previous page put a password form first in a split layout beside a brand panel. Google's own button cannot be styled and in dark mode shows the G on a white square.++**Alternatives considered:**+- Password first with the same look. It matches the old behaviour, but Activepieces asks for the email first, and a code needs no password to remember or reset.+- Keeping the split layout with the brand panel. It does not match the requested reference, and the panel duplicated a picture of the app in a second style.+- Rendering Google's button alone. It keeps the white square in dark mode and a different shape and type from the rest of the card.++**Trade-offs:**+- Every code sign-in is one email (`magiclink` for an existing user, `signup` for a new one) and counts against `EMAIL_DAILY_LIMIT` (100 a day by default). When the cap is reached, the first view shows a warning and points to Google or the password; members who sign in often should use one of those.+- Password sign-up stays for instances that do not email codes, so the page keeps seven views instead of three.+- Google's button is drawn by the app with Google's real button over it at near-zero opacity. Clicks, keyboard focus and the sign-in stay Google's, but the visible label must follow Google's text options (`googleButtonLabel()`), and the button still only works on origins listed in the OAuth client.+- Self-hosters without the Send Email hook get Supabase's own Magic Link email, which holds a link rather than a code unless they add `{{ .Token }}` to its template, and is limited to a few emails an hour.+- With signups turned off in Supabase, the code is refused for unknown addresses, which keeps private instances private without a separate setting.diff --git a/README.md b/README.mdindex 9083142..d78b35e 100644--- a/README.md+++ b/README.md@@ -68,7 +68,7 @@ The project's own public site and documentation are at [twiligent.ujjwal.fyi](ht| **Bulk upload** | Upload multiple files at once, assign captions individually or apply a shared caption, schedule them with configurable intervals || **Cloudinary CDN** | Upload media directly from the dashboard; Instagram requires public URLs before publishing || **Token auto-refresh** | Instagram long-lived tokens renew automatically every 24 hours via a daily Worker cron so analytics never break |-| **Authentication** | Supabase Auth with email and password or Google; optional 6-digit email verification codes sent through Resend with a daily cap; each user's accounts and posts are fully isolated |+| **Authentication** | Supabase Auth: Google, a 6-digit code emailed to the address (which also creates the account), or email and password; codes sent through Resend with a daily cap; each user's accounts and posts are fully isolated || **Dark and light mode** | Toggle between themes from the header |---@@ -238,7 +238,7 @@ alter table scheduled_posts enable row level security;alter table tracked_posts enable row level security;```-If you created the tables from an earlier version of this README, run the `tracked_posts` and `alter table` statements above as well. Then, in Supabase Authentication, turn off **Confirm email** unless you have set up email verification codes ([docs](https://twiligent.ujjwal.fyi/docs/self-host/email-codes)), and turn off new signups once your team has accounts if the instance is private.+If you created the tables from an earlier version of this README, run the `tracked_posts` and `alter table` statements above as well. Then, in Supabase Authentication, turn off **Confirm email** unless you have set up email verification codes ([docs](https://twiligent.ujjwal.fyi/docs/self-host/email-codes)), and turn off new signups once your team has accounts if the instance is private. The sign-in page's email field sends a sign-in code; without the email codes setup, Supabase sends its own rate-limited Magic Link email, which holds a link (add `{{ .Token }}` to its template in Authentication, Emails to show the code too).**4. Configure credentials**@@ -341,7 +341,7 @@ npx wrangler secret put EMAIL_FROM # optionalnpx wrangler secret put EMAIL_DAILY_LIMIT # optional; defaults to 100```-The four email secrets turn on 6-digit verification codes for email sign-ups, sent free through Resend (100 a day). Supabase Auth hands each email to the Worker through its Send Email hook (`POST /api/auth/email-hook`). Past the daily limit, the sign-up page asks people to sign in with Google instead. Setup steps are in the [docs](https://twiligent.ujjwal.fyi/docs/self-host/email-codes).+The four email secrets turn on the 6-digit codes that sign people in and confirm password sign-ups, sent free through Resend (100 a day). Supabase Auth hands each email to the Worker through its Send Email hook (`POST /api/auth/email-hook`); every code sign-in is one email. Past the daily limit, the sign-in page pauses email codes and points people to Google or their password. Setup steps are in the [docs](https://twiligent.ujjwal.fyi/docs/self-host/email-codes).### Getting API credentialsdiff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.mdindex 582065c..a67da78 100644--- a/docs/architecture/backend/ROUTES.md+++ b/docs/architecture/backend/ROUTES.md@@ -44,7 +44,7 @@ Supabase Auth calls this route, not a browser, so it has its own rules:- **Authentication.** `middleware/authHook.ts` (`verifyAuthHook`) checks the Standard Webhooks signature (`webhook-id`, `webhook-timestamp`, `webhook-signature`) against `SEND_EMAIL_HOOK_SECRET` and rejects a timestamp more than five minutes from now. There is no JWT.- **Error body.** Supabase reads hook failures as `{ "error": { "http_code": 429, "message": "..." } }` and passes the message to the client, so the route table sets `authHookErrorHandler` instead of the usual body. The statuses are the same.-- **Statuses.** `200 {}` when the emails were sent, or when a notice was skipped at a cap. `400` for a payload without a user email or email action. `401` for a missing, wrong or expired signature. `429` when the day's emails (`EMAIL_DAILY_LIMIT`, 100 by default) or this address's 5 emails a day are used up, or Resend reports its own quota is used up; the message points to Google sign-in. `502` when Resend refuses the email, `503` when the hook secret, `RESEND_API_KEY` or `EMAIL_FROM` is not set, `504` when Resend does not answer within 4 seconds (Supabase gives the whole call 5).+- **Statuses.** `200 {}` when the emails were sent, or when a notice was skipped at a cap. `400` for a payload without a user email or email action. `401` for a missing, wrong or expired signature. `429` when the day's emails (`EMAIL_DAILY_LIMIT`, 100 by default) or this address's 5 emails a day are used up, or Resend reports its own quota is used up; the message points to Google sign-in, and the sign-in page recognises the daily cap and shows its own warning offering Google or the password. `502` when Resend refuses the email, `503` when the hook secret, `RESEND_API_KEY` or `EMAIL_FROM` is not set, `504` when Resend does not answer within 4 seconds (Supabase gives the whole call 5).- **Retries.** The `webhook-id` is sent to Resend as the idempotency key, so a repeated call does not send the email twice.See `docs/architecture/data-flows/AUTHENTICATION.md` for the whole flow.diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.mdindex 1029cbb..fe5680c 100644--- a/docs/architecture/backend/SERVICES.md+++ b/docs/architecture/backend/SERVICES.md@@ -73,7 +73,7 @@ Every user-scoped method takes the verified `userId` as its first argument. Meth`composeAuthEmails(hook, supabaseUrl)` in `email/authEmails.ts` turns one hook call into the emails to send, each with a plain text and an HTML body:-- `signup`, `recovery`, `magiclink`, `email`, `invite`: the 6-digit code and a link to Supabase Auth's `/auth/v1/verify` endpoint, which does the same. The recovery email asks for the code on the sign-in page with the new password; its link signs the person in on Settings, where the Password section sets one.+- `signup`, `recovery`, `magiclink`, `email`, `invite`: the 6-digit code and a link to Supabase Auth's `/auth/v1/verify` endpoint, which does the same. The recovery email asks for the code on the sign-in page with the new password; its link signs the person in on Settings, where the Password section sets one. A code sign-in sends `magiclink` for an existing user and `signup` for a new one.- `reauthentication`: the code only.- `email_change`: with Secure Email Change, one code to each address. Supabase names the hashes the other way round: the current address gets `token` with `token_hash_new`, the new one `token_new` with `token_hash`. Without it, one email to the new address.- `*_notification`: a notice of a change already made, with no code (`notice: true`).@@ -83,7 +83,7 @@ Values from the payload are HTML-escaped.`AuthEmailService.send` throws `NotConfiguredError` (503) without `RESEND_API_KEY` and `EMAIL_FROM`. For each email it:-1. Claims a send from `emailQuotaRepository` for the UTC day: at most `EMAIL_DAILY_LIMIT` (100 by default) in total, and `RECIPIENT_DAILY_LIMIT` (5) to one address. Past either cap it throws `RateLimitedError` (429). The daily cap's message tells the person to sign in with Google.+1. Claims a send from `emailQuotaRepository` for the UTC day: at most `EMAIL_DAILY_LIMIT` (100 by default) in total, and `RECIPIENT_DAILY_LIMIT` (5) to one address. Past either cap it throws `RateLimitedError` (429). The daily cap's message tells the person to sign in with Google; the sign-in page recognises it (`emailErrorNotice` in `frontend/src/lib/authErrors.ts`) and shows its own wording, which also offers the password.2. Sends it with `email/resendApi.ts` `sendEmail()`. The idempotency key is `<webhook-id>-<index>`. The call is abandoned after 4 seconds, inside Supabase's 5 second budget for the whole hook call.3. Treats Resend's `daily_quota_exceeded` and `monthly_quota_exceeded` answers like the daily cap. Other Resend errors are `UpstreamError` (502), and a timeout is `UpstreamTimeoutError` (504).diff --git a/docs/architecture/cloudflare/WORKERS.md b/docs/architecture/cloudflare/WORKERS.mdindex 41704d7..8c3886f 100644--- a/docs/architecture/cloudflare/WORKERS.md+++ b/docs/architecture/cloudflare/WORKERS.md@@ -55,7 +55,7 @@ All secrets are set via `npx wrangler secret put <NAME>`, run from `backend/`. T| `SEND_EMAIL_HOOK_SECRET` | Optional | The Send Email hook secret from Supabase (`v1,whsec_...`); verifies that `POST /api/auth/email-hook` was called by your Supabase Auth. Without it the hook answers 503 || `RESEND_API_KEY` | Optional | Resend API key with sending access; sends the auth emails (verification codes) || `EMAIL_FROM` | Optional | Sender of the auth emails on a domain verified in Resend, such as `Twiligent <[email protected]>` |-| `EMAIL_DAILY_LIMIT` | Optional | Auth emails a day across all users before sign-up points to Google; defaults to `100`, Resend's free daily quota |+| `EMAIL_DAILY_LIMIT` | Optional | Auth emails a day across all users (each code sign-in is one) before the sign-in page pauses email codes and points to Google or a password; defaults to `100`, Resend's free daily quota |### Setting secretsdiff --git a/docs/architecture/data-flows/AUTHENTICATION.md b/docs/architecture/data-flows/AUTHENTICATION.mdindex a215db2..11af96e 100644--- a/docs/architecture/data-flows/AUTHENTICATION.md+++ b/docs/architecture/data-flows/AUTHENTICATION.md@@ -1,6 +1,21 @@# Data Flow - Authentication-## Login Flow+## The Sign-in Page++`/login` (`pages/Login.tsx`) is one card over a blurred picture of the dashboard (`LoginBackdrop.tsx`, lazy-loaded so it never delays the card). The card shows one view at a time (`LoginView` in `pages/loginCopy.ts`):++| View | Shows | Back goes to |+|---|---|---|+| `start` | Continue with Google, "or", one email field with the Continue arrow inside it (`LoginEmailStart.tsx`), a Use password link and the privacy note | - |+| `code` | "Check your email": the 6-digit sign-in code (`LoginCodeForm.tsx`), Send a new code after 60 seconds | `start` |+| `password` | Email, Password with Forgot your password?, Sign in, and No account yet? Create one with a password (`LoginPasswordForm.tsx`) | `start` |+| `signup` | The same form, creating a password account | `start` |+| `verify` | The code that confirms a password sign-up when **Confirm email** is on | `start` |+| `forgot`, `reset` | The reset-by-code flow below | `password` |++`?mode=signup` (the public site's Get started buttons) keeps the `start` view but shows the headline "Create your Twiligent account" and Google's "Sign up with Google". The default ways to join are Google and an emailed code, both of which create the account on first use; the password sign-up stays behind the password view for instances that do not email codes.++## Login Flow (Emailed Code, the Default)```User visits the app@@ -9,12 +24,19 @@ User visits the appReact Router: no session -> ProtectedRoute redirects to /login│▼-Login.tsx renders email/password form+Login.tsx start view: the user types an address (looksLikeEmail() in lib/emailAddress.ts enables the arrow)│▼-User submits -> AuthContext.signIn(email, password)- -> supabase.auth.signInWithPassword({ email, password })- -> Supabase validates credentials+AuthContext.sendSignInCode(email)+ -> supabase.auth.signInWithOtp({ email, options: { shouldCreateUser: true } })+ -> Supabase creates the user if the address is new, makes a 6-digit code and calls the Send Email hook+ email_action_type 'magiclink' for an existing user, 'signup' for a new one; both emails carry the code+ -> the Worker sends it through Resend, counted against the daily cap (see the sign-up section below)+ │+ ▼+Login.tsx code view ("Check your email", LoginCodeForm)+ -> the user types or pastes the code (non-digits are dropped)+ -> AuthContext.verifySignInCode(email, code) -> supabase.auth.verifyOtp({ email, token, type: 'email' })-> Returns { session: { access_token, user: { id, email } } }-> AuthProvider.setSession(session)-> onAuthStateChange fires, React re-renders@@ -31,12 +53,28 @@ AppProvider mounts -> loadAccounts() firesUser sees Overview dashboard```-## Sign-up with an Email Code+Send a new code calls `sendSignInCode` again and then waits 60 seconds. Each code sign-in is one email, so it counts against `EMAIL_DAILY_LIMIT`; when the cap is reached the start view shows the warning described below and Google and the password remain. With **Allow new users to sign up** off in Supabase, a code is refused for an address with no account.++### Without the Send Email Hook-Used when **Confirm email** is on in Supabase and the Send Email hook points at the Worker. With **Confirm email** off, `signUp` returns a session and the page signs the user straight in.+Self-hosters who skip the email codes setup get Supabase's own **Magic Link** email for a code sign-in. By default it holds a link rather than a code; the link still signs the person in. Adding `{{ .Token }}` to the Magic Link template (Supabase, Authentication, Emails) shows the code too. Supabase's built-in email sends only a few messages an hour, so those instances should set up the hook or rely on Google and password accounts.+## Password Sign-in++```+Login.tsx: Use password -> password view (LoginPasswordForm)+ -> AuthContext.signIn(email, password) -> supabase.auth.signInWithPassword({ email, password })+ -> session issued; same lifecycle as the code sign-in above+ -> email_not_confirmed (a password account that never confirmed):+ AuthContext.sendSignInCode(email), then the code view; the sign-in code also confirms the address```-Login.tsx (sign-up mode) -> AuthContext.signUp(email, password)++## Password Sign-up with a Confirmation Code++The password view's Create one with a password link opens the `signup` view. A confirmation code is used when **Confirm email** is on in Supabase and the Send Email hook points at the Worker. With **Confirm email** off, `signUp` returns a session and the page signs the user straight in.++```+Login.tsx (signup view) -> AuthContext.signUp(email, password)-> supabase.auth.signUp({ email, password })-> Supabase Auth creates the unconfirmed user and a 6-digit code, then calls the Send Email hook:POST https://<worker>/api/auth/email-hook (webhook-id, webhook-timestamp, webhook-signature headers)@@ -51,24 +89,24 @@ Login.tsx (sign-up mode) -> AuthContext.signUp(email, password)-> signUp resolves with a user and no session│▼-Login.tsx opens the code step (LoginCodeForm)+Login.tsx opens the verify view (LoginCodeForm)-> the user types or pastes the code (non-digits are dropped)-> AuthContext.verifySignUpCode(email, code) -> supabase.auth.verifyOtp({ email, token, type: 'signup' })- -> session issued; same lifecycle as password sign-in below+ -> session issued; same lifecycle as the code sign-in above```-Other cases on the login page:+The same hook, caps and errors apply to the sign-in code. Other cases on the sign-in page:| Case | What happens ||---|---|-| The hook answers 429 for the daily cap, or Supabase's own email limit (`over_email_send_rate_limit`) is hit | `signUp` or `resend` fails with status 429. `lib/authErrors.ts` (`emailErrorNotice`) recognises it, and the page shows a warning above the Google button instead of a toast. On the code step the Google button appears too. |+| The hook answers 429 for the daily cap, or Supabase's own email limit (`over_email_send_rate_limit`) is hit | `signInWithOtp`, `signUp`, `resend` or `resetPasswordForEmail` fails with status 429. `lib/authErrors.ts` (`emailErrorNotice`) recognises it, and the page returns to the start view with the warning "Email codes are paused until tomorrow" above the Google button instead of a toast: "Twiligent has sent all the codes it can email today. Continue with Google or use your password instead, or try again tomorrow." (without Google: "Use your password instead, or try again tomorrow.") || The per-address cap (5 a day) or Supabase's one-code-a-minute wait | Status 429, but the message already says what to do, so it is shown as a toast and Google is not suggested || Wrong or expired code (`otp_expired`) | "The code is wrong or has expired. Check it, or send a new one." |-| Send a new code | `AuthContext.resendSignUpCode(email)` -> `supabase.auth.resend({ type: 'signup', email })`; the button then waits 60 seconds |-| Signing in before confirming (`email_not_confirmed`) | The page opens the code step with the resend button ready |+| Send a new code | On the verify view, `AuthContext.resendSignUpCode(email)` -> `supabase.auth.resend({ type: 'signup', email })`; on the code view, `sendSignInCode(email)` again; the button then waits 60 seconds |+| Signing in with a password before confirming (`email_not_confirmed`) | The page sends a sign-in code and opens the code view; the code signs the person in and confirms the address || Sign-up for an address that already has an account | Supabase returns a user with no identities and sends nothing; the page says to sign in instead |-If the sign-up email cannot be sent, Supabase does not create the user, so the person can try again later or use Google. Password reset, magic link, invite, email change and security notice emails go through the same hook. Notices that hit a cap are skipped instead of failing the change they report. See `docs/architecture/backend/ROUTES.md` (Send Email hook) and `SERVICES.md` (Auth emails).+If the sign-up email cannot be sent, Supabase does not create the user, so the person can try again later or use Google. Sign-in code (magic link), password reset, invite, email change and security notice emails go through the same hook. Notices that hit a cap are skipped instead of failing the change they report. See `docs/architecture/backend/ROUTES.md` (Send Email hook) and `SERVICES.md` (Auth emails).## Setting a Password from Settings@@ -85,45 +123,49 @@ Supabase keeps one user per email address, so for an account that only used Goog## Resetting a Forgotten Password```-Login.tsx: Forgot password? (sign-in form) -> mode 'forgot' (LoginEmailForm)+Login.tsx: Forgot your password? (password view) -> view 'forgot' (LoginEmailForm)-> AuthContext.sendPasswordReset(email) -> supabase.auth.resetPasswordForEmail(email, { redirectTo: <origin>/settings })-> Supabase calls the Send Email hook with email_action_type 'recovery'-> the Worker emails the 6-digit code and a link, counted against the daily cap like every auth email-> "If an account uses <email>, a code is on its way." (Supabase answers the same for unknown addresses)│▼-mode 'reset' (LoginCodeForm with a PasswordInput for the new password)+view 'reset' (LoginCodeForm with a PasswordInput for the new password)-> AuthContext.verifyPasswordResetCode(email, code) -> supabase.auth.verifyOtp({ email, token, type: 'recovery' })the code signs the user in-> AuthContext.updatePassword(password)-> "Password saved" and the Overview; if the password is refused, the user is already signed in and is sent to Settings```-The email's link does the same as the code: Supabase verifies it, signs the user in and opens Settings, where the Password section sets the new password. Send a new code, the 60 second wait and the daily-limit warning with the Google button work as on the sign-up code step. A Google-only account can use this flow to get a password.+The email's link does the same as the code: Supabase verifies it, signs the user in and opens Settings, where the Password section sets the new password. Send a new code, the 60 second wait and the daily-limit warning work as on the other code views. Back from `forgot` and `reset` returns to the password view. A Google-only account can use this flow to get a password.## Sign in with GoogleOptional; enabled when `VITE_GOOGLE_CLIENT_ID` is set and the Google provider is on in Supabase.```-Login.tsx renders GoogleSignInButton+Login.tsx start view renders GoogleSignInButton (text 'continue_with', or 'signup_with' for ?mode=signup)-> lib/googleIdentity.ts loads https://accounts.google.com/gsi/client once-> createNonce(): raw random nonce + its SHA-256 hex-> google.accounts.id.initialize({ client_id, nonce: hashed, callback })-> google.accounts.id.renderButton(...) (Google's own button, popup or FedCM)+ laid nearly transparent over an outline button the app draws (the G from public/icons/google-g.svg,+ the label from googleButtonLabel()), so clicks and keyboard focus still reach Google's buttonUser picks a Google account-> callback receives an ID token (JWT signed by Google, contains the hashed nonce)-> supabase.auth.signInWithIdToken({ provider: 'google', token, nonce: raw })-> Supabase checks the signature, audience (client ID) and sha256(raw) == token nonce- -> session issued; same lifecycle as password sign-in below+ -> session issued; same lifecycle as the code sign-in above```+Google's button is an iframe that cannot be styled, and in dark mode it puts the G on a white square; drawing the app's own button underneath keeps it in the outline style in both themes while the sign-in stays Google's. Google only renders the button on origins listed in the OAuth client's **Authorized JavaScript origins**, so on an unlisted origin (such as a local dev server that was not added) the button does nothing.+No OAuth redirect is involved, so the Google client has JavaScript origins only and no redirect URI on `supabase.co`. Every domain Google sees is the frontend's own domain, which is what allows brand verification (name and logo on the consent screen). A Google sign-in with the same verified email as an existing password account opens that account.## Session Lifecycle```-Session created (on signIn)+Session created (on any sign-in)│▼Supabase JWT stored in browser (localStorage by default)diff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.mdindex 98fbae1..7188c4b 100644--- a/docs/architecture/database/SECURITY.md+++ b/docs/architecture/database/SECURITY.md@@ -41,9 +41,9 @@ This denies the anon and authenticated roles everything, while the service-role## Signups-Supabase Auth accepts signups from anyone who knows the project URL and anon key. Private instances should turn off new signups in Supabase Authentication settings once their members have accounts.+Supabase Auth accepts signups from anyone who knows the project URL and anon key. The sign-in page creates an account the first time an address enters a correct emailed sign-in code (`signInWithOtp` with `shouldCreateUser: true`), as well as through Google and the password sign-up form. Private instances should turn off new signups in Supabase Authentication settings once their members have accounts; a sign-in code is then refused for an address with no account.-With **Confirm email** on and the Send Email hook set up, an email account cannot sign in until its owner enters the 6-digit code sent to the address. The Worker sends those emails through Resend and caps them at `EMAIL_DAILY_LIMIT` a day (100 by default) and 5 a day per address; see `docs/architecture/data-flows/AUTHENTICATION.md`.+A code sign-in proves the person owns the address. With **Confirm email** on, a password account cannot sign in until its owner enters a 6-digit code sent to the address. With the Send Email hook set up, the Worker sends every auth email through Resend and caps them at `EMAIL_DAILY_LIMIT` a day (100 by default) and 5 a day per address, so each code sign-in counts against the cap; see `docs/architecture/data-flows/AUTHENTICATION.md`.**The service-role key must never appear in:**- Frontend codediff --git a/docs/architecture/frontend/CONTEXTS.md b/docs/architecture/frontend/CONTEXTS.mdindex bc61df9..c9828da 100644--- a/docs/architecture/frontend/CONTEXTS.md+++ b/docs/architecture/frontend/CONTEXTS.md@@ -8,8 +8,8 @@ Wraps Supabase Auth state and exposes it to the entire app.```tsconst {- session, user, signIn, signUp, verifySignUpCode, resendSignUpCode, sendPasswordReset, verifyPasswordResetCode, updatePassword,- signInWithGoogle, signOut,+ session, user, signIn, signUp, verifySignUpCode, resendSignUpCode, sendSignInCode, verifySignInCode, sendPasswordReset,+ verifyPasswordResetCode, updatePassword, signInWithGoogle, signOut,} = useAuth();```@@ -20,9 +20,11 @@ The value is typed as `AuthContextValue`, exported from `AuthContext.tsx`.| `session` | `Session \| null \| undefined` | Current Supabase session; `undefined` until the first `getSession()` resolves, `null` if not logged in || `user` | `User \| null` | `session.user` shorthand || `signIn(email, password)` | async function | Calls `supabase.auth.signInWithPassword()` |-| `signUp(email, password)` | async function | Calls `supabase.auth.signUp()`. With **Confirm email** on it resolves with a user and no session, and the login page asks for the emailed code |+| `signUp(email, password)` | async function | Calls `supabase.auth.signUp()` to create a password account, for instances that do not email sign-in codes. With **Confirm email** on it resolves with a user and no session, and the login page asks for the emailed code || `verifySignUpCode(email, code)` | async function | Calls `supabase.auth.verifyOtp({ email, token: code, type: 'signup' })`; a correct code confirms the address and signs the user in || `resendSignUpCode(email)` | async function | Calls `supabase.auth.resend({ type: 'signup', email })` to email a new code |+| `sendSignInCode(email)` | async function | Calls `supabase.auth.signInWithOtp({ email, options: { shouldCreateUser: true } })`; emails a 6-digit code that signs the user in, creating the account the first time an address is used |+| `verifySignInCode(email, code)` | async function | Calls `supabase.auth.verifyOtp({ email, token: code, type: 'email' })`; a correct code signs the user in, and also confirms an address that signed up with a password and never confirmed it || `sendPasswordReset(email)` | async function | Calls `supabase.auth.resetPasswordForEmail(email, { redirectTo: <origin>/settings })`; the email carries a recovery code and a link || `verifyPasswordResetCode(email, code)` | async function | Calls `supabase.auth.verifyOtp({ email, token: code, type: 'recovery' })`; a correct code signs the user in || `updatePassword(password)` | async function | Calls `supabase.auth.updateUser({ password })`; sets or changes the password, including for an account that only used Google |@@ -48,7 +50,7 @@ useEffect(() => {### Where to use it- `ProtectedRoute` - reads `session` to decide whether to redirect to `/login`-- `Login.tsx` - calls `signIn()`, `signUp()`, `verifySignUpCode()`, `resendSignUpCode()`, `sendPasswordReset()`, `verifyPasswordResetCode()`, `updatePassword()` and `signInWithGoogle()`+- `Login.tsx` - calls `sendSignInCode()` and `verifySignInCode()` (the default email sign-in), `signIn()`, `signUp()`, `verifySignUpCode()`, `resendSignUpCode()`, `sendPasswordReset()`, `verifyPasswordResetCode()`, `updatePassword()` and `signInWithGoogle()`- `features/settings/PasswordSection.tsx` - calls `updatePassword()` and reads `user.email` for password managers- `Header.tsx` - calls `signOut()`, shows `user.email`- Do **not** use in page/feature components - they should never need auth state directlydiff --git a/docs/architecture/frontend/DESIGN_SYSTEM.md b/docs/architecture/frontend/DESIGN_SYSTEM.mdindex 8c100c3..cfb76f3 100644--- a/docs/architecture/frontend/DESIGN_SYSTEM.md+++ b/docs/architecture/frontend/DESIGN_SYSTEM.md@@ -48,6 +48,7 @@ Shared components live in `frontend/src/components/`. Reach for these before wri| `EmptyState`, `ErrorState`, `LoadingState`, `PageSkeleton` | Every data view needs all of these || `AccountAvatar`, `PlatformBadge`, `PlatformIcon` | Account and platform identity, never by colour alone || `brand/Logo` | The theme-aware lockup, or the mark when the sidebar is collapsed |+| `GoogleSignInButton` | Continue with Google. Google's own button cannot be styled (in dark mode it puts the G on a white square), so this draws an outline button with the coloured G (`public/icons/google-g.svg`) and lays Google's real button over it, nearly transparent; clicks, keyboard focus and the sign-in stay Google's |## Page patterns@@ -59,6 +60,7 @@ Shared components live in `frontend/src/components/`. Reach for these before wri| Create | Accounts (add flow) | Choice cards, then a form step, then review before commit || Working surface | Publish | Main editor on the left, sticky `DetailPanel` with settings and the primary action on the right || Settings | Settings | Sections with a label column and content column |+| Sign-in | Login | One centred card in the dialog styling (`rounded-dialog`, `border-line`, `bg-popover`, `shadow-lg`) over a blurred picture of the dashboard (`LoginBackdrop`, the shared components with sample figures under a `bg-surface/70` blur); logo, Back link when not on the first view, one headline, then the view's form |## Rulesdiff --git a/docs/architecture/frontend/REACT_ARCHITECTURE.md b/docs/architecture/frontend/REACT_ARCHITECTURE.mdindex 5780daf..5edb487 100644--- a/docs/architecture/frontend/REACT_ARCHITECTURE.md+++ b/docs/architecture/frontend/REACT_ARCHITECTURE.md@@ -48,7 +48,7 @@ ReactDOM.createRoot(document.getElementById('root')!).render(Defines the router, provider tree, and lazy-loaded page imports.-**Lazy loading:** All pages except `Login` are wrapped in `React.lazy()`. This means pages are code-split into separate chunks and loaded on first navigation. The `<Suspense fallback={null}>` wrapper renders nothing while the chunk loads.+**Lazy loading:** All pages except `Login` are wrapped in `React.lazy()`. This means pages are code-split into separate chunks and loaded on first navigation. The `<Suspense fallback={null}>` wrapper renders nothing while the chunk loads. `Login` lazy-loads only its decorative `LoginBackdrop`, so the sign-in card never waits for it.**Router:** Uses `createBrowserRouter` (React Router v7 data router). This enables nested layouts via `<Outlet />` in `MainLayout`.@@ -94,7 +94,7 @@ frontend/src/services/api.ts All backend HTTP callscontext/- AuthContext.tsx Session, signIn, signUp, signOut+ AuthContext.tsx Session, sign-in code, password sign-in and sign-up, Google, reset, signOutAppContext.tsx Accounts list, loading, showToastutils/formatters.ts fmtNum, fmtDate, fmtDuration, normalizeAccount, etc.@@ -116,14 +116,17 @@ frontend/src/brand/ Logo and platform iconsui/ shadcn generated components, restyled onto the tokenspages/- Login.tsx Auth page (not lazy-loaded, always small); owns mode (sign in, sign up, code), fields, the password toggle and the resend wait- LoginForm.tsx Email and password form- LoginCodeForm.tsx The 6-digit email code step (sign-up confirmation, and password reset with a new-password field), with Send a new code+ Login.tsx Auth page (not lazy-loaded, always small): one card over the dashboard picture; owns the view+ (start, code, password, signup, verify, forgot, reset), fields, the password toggle and the resend wait+ LoginBackdrop.tsx Blurred picture of the dashboard behind the card, built from the shared components with sample+ figures; aria-hidden and loaded with React.lazy so it never delays the card+ LoginEmailStart.tsx The first view's email field, with a mail icon and the Continue arrow inside it+ LoginPasswordForm.tsx Email and password form, for signing in and for creating a password account+ LoginCodeForm.tsx The 6-digit email code step (code sign-in, sign-up confirmation, and password reset with a new-password field), with Send a new codeLoginEmailForm.tsx The email-only Forgot password stepPasswordInput.tsx Password field with its show or hide button, used by the sign-in, sign-up and reset formsuseCountdown.ts Seconds until another email code may be sent- LoginBrandPanel.tsx Decorative product preview beside the form- loginCopy.ts Sign-in and sign-up text, privacy link+ loginCopy.ts LoginView, the title and button text for each view, the sign-up title, privacy linkfeatures/analytics/overview/ Overview.tsx - all-accounts dashboard (page; tabs, hooks and helpers beside it)diff --git a/docs/architecture/frontend/ROUTING.md b/docs/architecture/frontend/ROUTING.mdindex 41b2863..ee05fdd 100644--- a/docs/architecture/frontend/ROUTING.md+++ b/docs/architecture/frontend/ROUTING.md@@ -8,7 +8,7 @@ The app uses React Router v6 in `frontend/src/App.tsx`. The router uses `Browser| Path | Component | Notes ||---|---|---|-| `/login` | `Login.tsx` | Public - redirects to `/` if already authenticated. `?mode=signup` opens the sign-up form (the public site's Get started buttons link to `https://app.twiligent.ujjwal.fyi/login?mode=signup`) |+| `/login` | `Login.tsx` | Public - redirects to `/` if already authenticated. Opens on the start view: Continue with Google, an email field that sends a sign-in code, and a Use password link. `?mode=signup` keeps the same view with the headline "Create your Twiligent account" and Google's "Sign up with Google"; the emailed code creates the account the first time an address is used (the public site's Get started buttons link to `https://app.twiligent.ujjwal.fyi/login?mode=signup`) || `/docs/*` | `components/DocsRedirect.tsx` | Public. The docs live on the public site; this route replaces the location with the same path and hash under `https://twiligent.ujjwal.fyi/docs` (`docsUrl()` in `lib/docs.ts`), so old links keep working || `/` (layout) | `AppLayout` (inline) | Protected - redirects to `/login` if unauthenticated || `/` (index) | `Overview.tsx` | Default page after login |diff --git a/docs/architecture/site/SITE.md b/docs/architecture/site/SITE.mdindex 78c4766..5220067 100644--- a/docs/architecture/site/SITE.md+++ b/docs/architecture/site/SITE.md@@ -89,7 +89,7 @@ site/Fallback: the build has no top-level `404.html`, so Cloudflare Pages serves `index.html` for any path that is not a file, and the router decides. A docs path with no content file shows a docs 404 inside the docs frame.-Links to the app use the constants in `src/lib/links.ts`: `SIGN_IN_URL` (`https://app.twiligent.ujjwal.fyi/login`) and `SIGN_UP_URL` (the same with `?mode=signup`, which opens the app's sign-up form). Sign-up and sign-in only exist in the app.+Links to the app use the constants in `src/lib/links.ts`: `SIGN_IN_URL` (`https://app.twiligent.ujjwal.fyi/login`) and `SIGN_UP_URL` (the same with `?mode=signup`, which shows the app's sign-up headline and Sign up with Google; an emailed code creates the account). Sign-up and sign-in only exist in the app.## Docs Pipelinediff --git a/docs/guidelines/ERROR_HANDLING.md b/docs/guidelines/ERROR_HANDLING.mdindex dcecf54..10332af 100644--- a/docs/guidelines/ERROR_HANDLING.md+++ b/docs/guidelines/ERROR_HANDLING.md@@ -105,7 +105,7 @@ Registered with `app.onError(errorHandler)` and `app.notFound(notFoundHandler)`.It also maps Hono's own `HTTPException` (such as a malformed JSON body) by status, and answers anything else with `INTERNAL_ERROR` and a message asking the user to quote the request id. The rate limiter builds its 429 body with the same `errorBody()` helper, plus `retryAfter`.-`authHookErrorHandler`, in the same file, is used only by `routes/authHookRoutes.ts` (`router.onError`). It logs and maps statuses exactly like `errorHandler`, but writes the body Supabase Auth reads from a hook, `{ "error": { "http_code": 429, "message": "..." } }`; Supabase passes the message to the sign-up form, so it is written for the person signing up.+`authHookErrorHandler`, in the same file, is used only by `routes/authHookRoutes.ts` (`router.onError`). It logs and maps statuses exactly like `errorHandler`, but writes the body Supabase Auth reads from a hook, `{ "error": { "http_code": 429, "message": "..." } }`; Supabase passes the message to the sign-in page, so it is written for the person signing in or up; for the daily cap the page shows its own wording (`emailErrorNotice` in `frontend/src/lib/authErrors.ts`).### Frontend API Callsdiff --git a/docs/guidelines/SUPABASE.md b/docs/guidelines/SUPABASE.mdindex d379cd6..9130316 100644--- a/docs/guidelines/SUPABASE.md+++ b/docs/guidelines/SUPABASE.md@@ -114,8 +114,11 @@ export function getSupabase(env: Env): SupabaseClient {## Frontend - No DB AccessThe frontend's Supabase client (`frontend/src/lib/supabase.ts`) is used only for:+- `supabase.auth.signInWithOtp()` and `supabase.auth.verifyOtp()` (the emailed sign-in code, sign-up confirmation and password reset codes)- `supabase.auth.signInWithPassword()`-- `supabase.auth.signUp()`+- `supabase.auth.signUp()` and `supabase.auth.resend()`+- `supabase.auth.resetPasswordForEmail()` and `supabase.auth.updateUser()`+- `supabase.auth.signInWithIdToken()` (Google)- `supabase.auth.signOut()`- `supabase.auth.getSession()`- `supabase.auth.onAuthStateChange()`diff --git a/docs/workflows/DEPLOYMENT.md b/docs/workflows/DEPLOYMENT.mdindex a67756f..c7aff03 100644--- a/docs/workflows/DEPLOYMENT.md+++ b/docs/workflows/DEPLOYMENT.md@@ -140,7 +140,7 @@ curl -i -H "Origin: https://app.twiligent.ujjwal.fyi" https://twiligent.ujjwalkrA request with any other `Origin` gets no `Access-Control-Allow-Origin` header. The Worker writes one JSON log line per request with its request id; use `npx wrangler tail` from `backend/` to watch them, and search for the id a user quotes from an error message.**Frontend (the app):**-Open `https://app.twiligent.ujjwal.fyi` (custom domain on the `twiligent` Pages project) -> verify login page loads -> sign in -> verify accounts load. Open `https://app.twiligent.ujjwal.fyi/login?mode=signup` -> verify the sign-up form opens. Open `https://app.twiligent.ujjwal.fyi/docs/use/publishing` -> verify it lands on the same page of the public docs.+Open `https://app.twiligent.ujjwal.fyi` (custom domain on the `twiligent` Pages project) -> verify login page loads -> sign in -> verify accounts load. Open `https://app.twiligent.ujjwal.fyi/login?mode=signup` -> verify the headline reads "Create your Twiligent account". Open `https://app.twiligent.ujjwal.fyi/docs/use/publishing` -> verify it lands on the same page of the public docs.**Public site:**Open `https://twiligent.ujjwal.fyi` (custom domain on the `twiligent-site` Pages project; `twiligent.spacesdrive.cc` 301-redirects here) -> verify the home page renders in light and dark (the theme toggle in the navbar) -> open `/docs`, press Ctrl K and search for `redis` -> open a result. Check that `/sitemap.xml` and `/llms.txt` load and that `https://twiligent.ujjwal.fyi/settings` redirects to `https://app.twiligent.ujjwal.fyi/settings`.diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.mdindex 49bc11e..756986f 100644--- a/docs/workflows/TESTING.md+++ b/docs/workflows/TESTING.md@@ -37,6 +37,8 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that| `backend/services/authEmailService.ts` | `backend/tests/services/authEmailService.test.ts` || `frontend/src/lib/authErrors.ts` | `frontend/tests/lib/authErrors.test.ts` || `frontend/src/lib/passwords.ts` | `frontend/tests/lib/passwords.test.ts` |+| `frontend/src/lib/emailAddress.ts` | `frontend/tests/lib/emailAddress.test.ts` |+| `frontend/src/lib/googleIdentity.ts` | `frontend/tests/lib/googleIdentity.test.ts` || `frontend/src/features/analytics/overview/overviewStats.ts` | `frontend/tests/features/analytics/overview/overviewStats.test.ts` || `site/src/docs/searchShared.ts` | `site/tests/docs/searchShared.test.ts` || `site/content/docs/**/*.mdx` and `site/src/docs/nav.ts` | `site/tests/docs/content.test.ts` |@@ -57,7 +59,7 @@ Rate limiting has its own tests: `tests/lib/rateLimit/algorithms.test.ts` (eachBackend route and cron service tests (`tests/routes/*Routes.test.ts`, `tests/services/scheduledPublisher.test.ts`, `tests/services/tokenRefreshService.test.ts`) run the real code against `tests/fixtures/fakeSupabase.ts` and a scripted `fetch`, then compare responses, queries and outgoing requests with the `tests/fixtures/*.golden.json` snapshots. Route tests mount a route table with `mountWithContext()` from `tests/fixtures/routeHarness.ts`, which installs the real error handler and not-found handler and sets the request id (`req-test`), the signal and the context values the pipeline would set, so error responses are checked with their real `{ success: false, code, message, requestId }` body and status. Rows tagged with `tableRow(name, row)` are only visible to that table; untagged rows are visible to every table. A refactor must leave the snapshots unchanged. Prettier ignores the snapshots (`.prettierignore`), because the tests compare them byte for byte.-The Send Email hook has its own tests: `tests/lib/webhookSignature.test.ts` (valid, tampered, wrong-key, multi-signature and replayed requests), `tests/validators/authHookValidators.test.ts`, `tests/services/email/authEmails.test.ts` (the email for each action, the verify links, HTML escaping and the two Secure Email Change emails), `tests/repositories/emailQuotaRepository.test.ts` (daily and per-address caps, hashed keys, Redis failures), `tests/services/authEmailService.test.ts` (Resend requests, idempotency keys, the caps and Resend's own quota errors, skipped notices) and `tests/routes/authHookRoutes.test.ts` (the hook error shape, and the route answering unsigned calls with 401 in the full app). `tests/fixtures/authHook.ts` signs requests the way Supabase Auth does. The Lua claim script cannot run in Node; the repository test runs the same rules in memory. On the frontend, `tests/lib/authErrors.test.ts` covers when the login page points to Google.+The Send Email hook has its own tests: `tests/lib/webhookSignature.test.ts` (valid, tampered, wrong-key, multi-signature and replayed requests), `tests/validators/authHookValidators.test.ts`, `tests/services/email/authEmails.test.ts` (the email for each action, the verify links, HTML escaping and the two Secure Email Change emails), `tests/repositories/emailQuotaRepository.test.ts` (daily and per-address caps, hashed keys, Redis failures), `tests/services/authEmailService.test.ts` (Resend requests, idempotency keys, the caps and Resend's own quota errors, skipped notices) and `tests/routes/authHookRoutes.test.ts` (the hook error shape, and the route answering unsigned calls with 401 in the full app). `tests/fixtures/authHook.ts` signs requests the way Supabase Auth does. The Lua claim script cannot run in Node; the repository test runs the same rules in memory. On the frontend, `tests/lib/authErrors.test.ts` covers when the sign-in page shows the daily cap warning and whether it offers Google, `tests/lib/emailAddress.test.ts` when an address looks complete enough to enable the Continue arrow, and `tests/lib/googleIdentity.test.ts` the label drawn on the Google button for each text option.The testing workflow documented here describes what should run before shipping any change.@@ -126,23 +128,31 @@ npm run dev:backend # from the repository root; wrangler dev on port 8787Open the app in a browser. For each changed area, test:-**Authentication:**-- [ ] Login with valid credentials -> lands on Overview-- [ ] Login with invalid credentials -> error message shown+**Authentication (if the sign-in page, AuthContext or the Google button changed):**+- [ ] `/login` shows one card over a blurred dashboard picture, in light and dark mode, and the card appears before the picture+- [ ] Code sign-in: type an address you own -> the Continue arrow enables once it looks complete -> "Check your email" -> the 6-digit code lands on Overview; an address with no account gets one the same way+- [ ] Use password -> Email and Password with Forgot your password? -> valid credentials land on Overview; wrong ones show an error toast+- [ ] No account yet? Create one with a password -> with Confirm email on, the code step opens and the code lands on Overview; with it off, the account opens at once+- [ ] A password sign-in for an address that never confirmed -> a sign-in code is sent and the code view opens+- [ ] Back returns to the first view, and from Reset your password to the password view+- [ ] Continue with Google signs in (only on an origin listed in the OAuth client's Authorized JavaScript origins); in dark mode the button is the app's outline button with no white square behind the G, and Tab focus shows its ring+- [ ] `/login?mode=signup` shows "Create your Twiligent account" and "Sign up with Google"+- [ ] With the daily cap reached, Continue shows the warning "Email codes are paused until tomorrow" above Google, offering Google or the password- [ ] Sign out -> redirects to login**Email verification codes (if the hook, its secrets or the login page changed):**-- [ ] Create an account with an address you own -> the code arrives from `EMAIL_FROM`, the page shows the code step, and entering the code lands on Overview+- [ ] Code sign-in with an address you own -> the code arrives from `EMAIL_FROM` ("Your Twiligent sign-in code" for an existing account, the verification code email for a new one), and entering it lands on Overview- [ ] A wrong code -> "The code is wrong or has expired"; Send a new code -> a new email, then a 60 second wait-- [ ] Sign in with an unconfirmed address -> the code step opens+- [ ] Create an account with a password (Use password, Create one with a password) -> the confirmation code arrives and entering it lands on Overview+- [ ] Sign in with a password for an unconfirmed address -> a sign-in code is sent and the code step opens- [ ] An unsigned call, `curl -i -X POST -H "Content-Type: application/json" -d '{}' .../api/auth/email-hook` -> 401 with `{ "error": { "http_code": 401, ... } }` and no email sent- [ ] `npx wrangler tail` shows `auth email sent` for each code, and no code in any log line-- [ ] To check the daily cap without spending the quota, run the Worker locally with `EMAIL_DAILY_LIMIT=1` and no Redis, and send signed requests (see `tests/fixtures/authHook.ts` for the signing) -> the second one answers 429 with the Google message+- [ ] To check the daily cap without spending the quota, run the Worker locally with `EMAIL_DAILY_LIMIT=1` and no Redis, and send signed requests (see `tests/fixtures/authHook.ts` for the signing) -> the second one answers 429 with the Google message, which the sign-in page shows as the daily cap warning**Passwords (if the Password section, the reset steps or the recovery email changed):**- [ ] Settings, Password: mismatched fields -> "The two passwords do not match"; a valid password -> saved, and signing out and in with it works- [ ] An account created with Google sets a password in Settings, then signs in with email and that password and sees the same accounts-- [ ] Sign-in page, Forgot password? -> the email step -> a recovery code arrives -> a wrong code shows "The code is wrong or has expired" -> the right code and a new password land on Overview+- [ ] Sign-in page, Use password, Forgot your password? -> the email step -> a recovery code arrives -> a wrong code shows "The code is wrong or has expired" -> the right code and a new password land on Overview- [ ] The link in the recovery email opens Settings signed in**Request pipeline (if middleware, CORS or error handling changed):**@@ -192,7 +202,7 @@ Run `npm run dev:site`, or `npm run build --workspace site` and `npm run preview- [ ] Code blocks are highlighted in both themes- [ ] After a build, `site/dist/sitemap.xml` and `site/dist/llms.txt` list every docs page- [ ] In the app, `/docs/self-host/github` (or any `/docs/...` path) lands on the same page of the public docs, and the Documentation item in the user menu opens the docs in a new tab-- [ ] The app's `/login?mode=signup` opens the sign-up form+- [ ] The app's `/login?mode=signup` shows "Create your Twiligent account"- [ ] The product previews play while on screen: the cursor in Publish clicks the upload, caption, time and Schedule post, the Analytics cursor reads the chart and opens Shorts and regular, and each bento card fills its panel down to the lower edge- [ ] With reduced motion on (DevTools, Rendering, prefers-reduced-motion), every preview shows its finished state and no cursor appearsdiff --git a/site/content/docs/concepts.mdx b/site/content/docs/concepts.mdxindex 55fed4f..0285eb8 100644--- a/site/content/docs/concepts.mdx+++ b/site/content/docs/concepts.mdx@@ -4,7 +4,7 @@ export const meta = { title: 'Members and administrators', description: 'Who set### Member-A member signs in to an existing instance with an email and password. Members connect their own YouTube, Instagram and Reddit accounts, read their analytics, publish and schedule posts, and track content. A member never needs a server, a database, API keys or GitHub.+A member signs in to an existing instance with Google, a code emailed to their address, or an email and password. Members connect their own YouTube, Instagram and Reddit accounts, read their analytics, publish and schedule posts, and track content. A member never needs a server, a database, API keys or GitHub.### Administratordiff --git a/site/content/docs/reference/environment.mdx b/site/content/docs/reference/environment.mdxindex fc4a1e3..d5d1e3d 100644--- a/site/content/docs/reference/environment.mdx+++ b/site/content/docs/reference/environment.mdx@@ -28,9 +28,9 @@ The backend only answers browsers on `FRONTEND_URL` and the addresses in `ALLOWE| `UPSTASH_REDIS_REST_URL` | <Badge tone="optional">Optional</Badge> | Upstash database, REST API | Cache address. || `UPSTASH_REDIS_REST_TOKEN` <Badge tone="secret">Secret</Badge> | <Badge tone="optional">Optional</Badge> | Upstash database, REST API | Cache password. || `SEND_EMAIL_HOOK_SECRET` <Badge tone="secret">Secret</Badge> | <Badge tone="optional">Optional</Badge> | Supabase, Authentication, Auth Hooks, Send Email hook | Proves an email request came from your Supabase project. |-| `RESEND_API_KEY` <Badge tone="secret">Secret</Badge> | <Badge tone="optional">Optional</Badge> | Resend, API Keys (sending access) | Sends verification codes and other sign-in emails. |+| `RESEND_API_KEY` <Badge tone="secret">Secret</Badge> | <Badge tone="optional">Optional</Badge> | Resend, API Keys (sending access) | Sends sign-in and verification codes and other auth emails. || `EMAIL_FROM` | <Badge tone="optional">Optional</Badge> | A sender on a domain verified in Resend, for example {'Twiligent <[email protected]>'} | The sender of those emails. |-| `EMAIL_DAILY_LIMIT` | <Badge tone="optional">Optional</Badge> | A whole number; 100 when not set | Emails a day before sign-up points people to Google. |+| `EMAIL_DAILY_LIMIT` | <Badge tone="optional">Optional</Badge> | A whole number; 100 when not set | Emails a day before the sign-in page pauses email codes and points people to Google or a password. |Platform keys are shared by every member of the instance. Missing ones only switch off that platform: Settings shows which are set, and members see a clear message instead of an error.diff --git a/site/content/docs/self-host/checklist.mdx b/site/content/docs/self-host/checklist.mdxindex 37e89bb..2912b9e 100644--- a/site/content/docs/self-host/checklist.mdx+++ b/site/content/docs/self-host/checklist.mdx@@ -3,7 +3,7 @@ export const meta = { title: 'Launch checklist', description: 'Confirm everythin| Check | How || --- | --- || Backend is up | `/api/health` on your backend URL returns status ok. |-| Sign-in works | Create an account on the site and sign in. |+| Sign-in works | On the site, sign in with an emailed code (or Use password, then Create one with a password), and with Continue with Google if you set it up. || Keys are detected | Settings, Server API keys shows YouTube, Instagram and Cloudinary as set. || YouTube works | Add any public channel in Accounts. || Instagram works | Connect your own tester account in Accounts. |diff --git a/site/content/docs/self-host/email-codes.mdx b/site/content/docs/self-host/email-codes.mdxindex e3dd828..1cea784 100644--- a/site/content/docs/self-host/email-codes.mdx+++ b/site/content/docs/self-host/email-codes.mdx@@ -1,8 +1,8 @@-export const meta = { title: 'Email verification codes (optional)', description: 'Confirm each new email account with a 6-digit code, sent free through Resend, with a daily cap.' }+export const meta = { title: 'Email verification codes (optional)', description: 'Email the 6-digit codes that sign members in and confirm new accounts, sent free through Resend, with a daily cap.' }<Callout type="note" title="How it works">-Supabase Auth hands every sign-up, password reset and sign-in email to your backend instead of sending it. The backend checks that the request came from your Supabase project, counts the day's emails, and sends the code through Resend. Resend's free plan sends 100 emails a day, so the backend stops at 100. After that, the sign-up page tells people to sign in with Google instead, and email codes start again at midnight UTC.+The sign-in page's email field signs people in with a 6-digit code, and creates their account the first time an address is used. Supabase Auth hands that email, and every sign-up, password reset and other auth email, to your backend instead of sending it. The backend checks that the request came from your Supabase project, counts the day's emails, and sends the code through Resend. Every code sign-in is one email. Resend's free plan sends 100 emails a day, so the backend stops at 100. After that, the sign-in page shows that email codes are paused until tomorrow and points people to Google or their password, and email codes start again at midnight UTC.</Callout>@@ -44,7 +44,7 @@ Paste the secret exactly as Supabase shows it, starting with `v1,whsec_`.</Step><Step title="Turn on email confirmation">-Open **Sign In / Providers**, **Email**. Turn on **Confirm email** and keep the email OTP length at 6. New members then enter the code on the sign-up page before they can sign in.+Open **Sign In / Providers**, **Email**. Turn on **Confirm email** and keep the email OTP length at 6. Members who create an account with a password then enter a code before they can sign in. Code sign-in confirms the address by itself, so it works either way.</Step><Step title="Slow down bursts">@@ -54,13 +54,13 @@ Open **Rate Limits** and set **Rate limit for sending emails** to about 30 an ho</Step><Step title="Test it">-Create an account with an address you own. The code should arrive within a minute, from your `EMAIL_FROM` address. If it does not, run `npx wrangler tail` in `backend/` while you sign up: a `request failed` line explains why, for example an unverified domain.+On the sign-in page, type an address you own and press the arrow. The code should arrive within a minute, from your `EMAIL_FROM` address, and entering it signs you in. If it does not arrive, run `npx wrangler tail` in `backend/` while you try again: a `request failed` line explains why, for example an unverified domain.</Step></Steps><Callout type="warning" title="Every email counts">-Password resets, email changes and security notices go through the same hook and count towards the 100. When the cap is reached, notices are skipped rather than blocking the change they report. Without Redis, the backend cannot count, and Resend's own daily quota is the only limit; the message people see is the same.+Code sign-ins, password resets, email changes and security notices go through the same hook and count towards the 100. If many members sign in with a code each day, ask them to use Google or add a password in Settings. When the cap is reached, notices are skipped rather than blocking the change they report. Without Redis, the backend cannot count, and Resend's own daily quota is the only limit; the message people see is the same.</Callout>diff --git a/site/content/docs/self-host/google-sign-in.mdx b/site/content/docs/self-host/google-sign-in.mdxindex 0887fab..45d8b62 100644--- a/site/content/docs/self-host/google-sign-in.mdx+++ b/site/content/docs/self-host/google-sign-in.mdx@@ -2,7 +2,7 @@ export const meta = { title: 'Sign in with Google (optional)', description: 'Let<Callout type="note" title="How it works">-Twiligent shows Google's own sign-in button. Google returns a signed ID token to the browser, and Supabase verifies it directly. Nothing redirects through your Supabase address, so every domain Google sees is one you own, which is what lets Google approve your logo.+Twiligent uses Google's own sign-in button, laid over a button drawn in Twiligent's style so it matches the page in both themes. Google returns a signed ID token to the browser, and Supabase verifies it directly. Nothing redirects through your Supabase address, so every domain Google sees is one you own, which is what lets Google approve your logo.</Callout>@@ -24,7 +24,7 @@ Under **Audience**, pick **External** and publish the app to production. Under *</Step><Step title="Create the client">-Under **Clients**, create a **Web application**. Add your Twiligent address as an authorized JavaScript origin, plus `http://localhost:5173` for development. No redirect URI is needed. Copy the client ID.+Under **Clients**, create a **Web application**. Add your Twiligent address as an authorized JavaScript origin, plus `http://localhost:5173` for development. Google only shows its button on the origins listed here, so on any other address the Continue with Google button does nothing. No redirect URI is needed. Copy the client ID.</Step><Step title="Turn on Google in Supabase">diff --git a/site/content/docs/self-host/index.mdx b/site/content/docs/self-host/index.mdxindex 150c36d..c538e38 100644--- a/site/content/docs/self-host/index.mdx+++ b/site/content/docs/self-host/index.mdx@@ -22,7 +22,7 @@ The repository has a third folder, `site`, which is the project's own public web| Meta for Developers | Connecting Instagram and publishing | <Badge tone="optional">For Instagram</Badge> | Free || Cloudinary | Hosting media before Instagram fetches it | <Badge tone="optional">For publishing</Badge> | Free plan is enough || Upstash | Caching to save API quota and speed pages up | <Badge tone="optional">Optional</Badge> | Free plan is enough |-| Resend | Emailing verification codes to new members | <Badge tone="optional">Optional</Badge> | Free, 100 emails a day |+| Resend | Emailing sign-in and verification codes to members | <Badge tone="optional">Optional</Badge> | Free, 100 emails a day || GitHub | Deploy on every push, and a backup scheduler | <Badge tone="optional">Optional</Badge> | Free |Reddit needs no key. Each member pastes their own Reddit session cookie when they connect an account.diff --git a/site/content/docs/self-host/supabase.mdx b/site/content/docs/self-host/supabase.mdxindex 69b4731..ac1ffa5 100644--- a/site/content/docs/self-host/supabase.mdx+++ b/site/content/docs/self-host/supabase.mdx@@ -61,8 +61,10 @@ alter table tracked_posts enable row level security;Open **Authentication**, then **Sign In / Providers**, then **Email**.-- Turn off **Confirm email** unless you set up [email verification codes](/docs/self-host/email-codes). Otherwise new members never receive a code and cannot sign in.-- To keep the instance private, turn off **Allow new users to sign up** after you and your team have created accounts. You can also add members yourself under **Authentication**, **Users**, **Add user**.+- Turn off **Confirm email** unless you set up [email verification codes](/docs/self-host/email-codes). Otherwise members who create an account with a password wait for a confirmation code that Supabase's own email does not contain.+- To keep the instance private, turn off **Allow new users to sign up** after you and your team have created accounts. Google and emailed codes then only sign in existing members. You can also add members yourself under **Authentication**, **Users**, **Add user**.++The sign-in page's email field sends a 6-digit sign-in code. Without [email verification codes](/docs/self-host/email-codes), Supabase sends its own **Magic Link** email instead, which by default holds a link rather than a code; the link still signs the person in. To show the code as well, open **Authentication**, **Emails**, **Magic Link** and add `{{ .Token }}` to the template. Supabase's built-in email only sends a few messages an hour, so set up email verification codes, or have members use Google or a password.</Step><Step title="Copy the project URL">diff --git a/site/content/docs/use/getting-started.mdx b/site/content/docs/use/getting-started.mdxindex a0bc4f8..dbc245d 100644--- a/site/content/docs/use/getting-started.mdx+++ b/site/content/docs/use/getting-started.mdx@@ -7,9 +7,17 @@ You are a member if someone gave you a Twiligent link to sign in to. The server,</Callout><Steps>-<Step title="Create your account">+<Step title="Sign in">-Open your instance's link and choose **Continue with Google**, if your instance offers it. Otherwise choose **Create an account** and use your email and a password of at least 6 characters, then enter the 6-digit code we email you. If you sign in with Google using the same email as an existing account, both open the same account. If you joined with Google and also want a password, set one in **Settings**, **Password**. Forgot it? Choose **Forgot password?** on the sign-in page and enter the 6-digit code we email you with a new password.+Open your instance's link. The first time you continue with Google or an emailed code, Twiligent creates your account, so there is no separate sign-up step.++- **Continue with Google**, if your instance offers it.+- Or type your email and press the arrow. Enter the 6-digit code we email you on the **Check your email** screen. A new code can be sent after a minute.+- Or choose **Use password** to sign in with your email and a password. **No account yet? Create one with a password** makes a password account; if your instance asks you to confirm your email, enter the code we send.++Google, an emailed code and a password all open the same account when they use the same email. To add a password to an account you opened another way, set one in **Settings**, **Password**. Forgot it? Choose **Use password**, then **Forgot your password?**, and enter the 6-digit code we email you with a new password.++If the sign-in page says email codes are paused until tomorrow, your instance has sent all the emails it can today. Continue with Google or use your password instead.</Step><Step title="Connect an account">