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 email verification codes and their setup
spacesdrivef707ad173e97
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ed4ac87..10ae2f0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,12 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).- Issue templates, a pull request template and `docs/workflows/ISSUES.md` describe the lifecycle, labels and `gh` commands- `ROADMAP.md` now starts with the project goals and links in-progress items to their issues+**Email verification codes**+- New email accounts are confirmed with a 6-digit code: after sign-up the page asks for the code, with a button to send a new one (once a minute), and signing in with an unconfirmed address opens the same step+- Supabase Auth hands its emails to the backend through the Send Email hook (`POST /api/auth/email-hook`), which checks Supabase's signature and sends them for free through Resend+- At most 100 emails a day (`EMAIL_DAILY_LIMIT`) and 5 a day to one address; past the daily limit, the sign-up page says so and points to Continue with Google+- New optional Worker secrets `SEND_EMAIL_HOOK_SECRET`, `RESEND_API_KEY`, `EMAIL_FROM` and `EMAIL_DAILY_LIMIT`, and a setup guide at `/docs/self-host/email-codes` (ADR-033)+**Sign in with Google**- Continue with Google on the sign-in page, using Google's own button and a nonce-checked ID token sent to Supabase; shown only when `VITE_GOOGLE_CLIENT_ID` is set- Docs page for administrators: branding, audience, scopes, client, Supabase provider and brand verificationdiff --git a/DECISIONS.md b/DECISIONS.mdindex 1e5d847..bc521a4 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -674,3 +674,28 @@ Records every significant architectural decision, the alternatives considered, a- Building every service per request costs a few object allocations; nothing is cached across requests.- A browser on an origin that is not `FRONTEND_URL` or listed in `ALLOWED_ORIGINS` can no longer call the API. A local Worker also allows the Vite dev server.- The request deadline (30 seconds) and the warm-up deadline (25 seconds) abandon slow platform calls instead of waiting indefinitely.++---++## ADR-033: Auth emails through a Supabase Send Email hook on the Worker, sent with Resend and capped per day++**Date:** 2026-10-14+**Status:** Accepted++**Decision:** Email accounts are confirmed with a 6-digit code. Supabase Auth hands every auth email to the Worker through its Send Email hook (`POST /api/auth/email-hook`, public, authenticated by the Standard Webhooks signature with `SEND_EMAIL_HOOK_SECRET`). The Worker sends it through Resend's REST API (`RESEND_API_KEY`, `EMAIL_FROM`), with no npm package. Before each send, one atomic Redis script checks and increments two counters for the UTC day: all emails (`EMAIL_DAILY_LIMIT`, 100 by default) and emails to one address (5), keyed by a hash of the address. Past a cap, or when Resend reports its own quota is used up, the hook answers 429 in Supabase's hook error shape. Supabase passes the message to the sign-up form, which points the person to Google sign-in.++**Alternatives considered:**+- Resend as Supabase's custom SMTP server, with Supabase's email rate limit as the cap. No code, but the limit is per hour, not per day, and the error is a generic "email rate limit exceeded".+- Supabase's built-in email service. It sends only a few emails an hour and is meant for testing.+- Brevo (300 a day, but every email carries its branding), SMTP2GO (200 a day but 1,000 a month) and Amazon SES (free only for a limited time). Resend's free plan (100 a day, 3,000 a month) matches the target exactly and needs only a verified domain.+- A Supabase Edge Function for the hook. It would put a second runtime and deploy step next to the Worker.++**Context:** Email sign-ups were never confirmed, because the built-in email service cannot send enough emails. The goal was a free provider, at least 100 codes a day, and a clear way in when that runs out.++**Trade-offs:**+- Every auth email goes through the Worker: if it is down or misconfigured while the hook is on, sign-up and password reset fail. The 503 and 502 messages say which secret or provider setting is wrong.+- Supabase gives the hook 5 seconds in total, so Resend calls time out after 4 seconds and the counters use the fail-fast Redis client.+- A claimed send that Resend then refuses still counts towards the day, so the count can run slightly ahead of Resend's.+- Without Redis there is no count, and Resend's own daily quota (on the free plan) is the cap. A paid Resend plan has no daily quota, so `EMAIL_DAILY_LIMIT` is then the only one.+- Supabase calls the hook from its own servers, so the per-IP rate limit cannot tell people apart. The per-address cap, Supabase's email rate limit and optional CAPTCHA protect the daily allowance from one person.+- Security notices that hit a cap are skipped instead of failing the change they report.diff --git a/README.md b/README.mdindex 144c7ca..aa6ade8 100644--- a/README.md+++ b/README.md@@ -66,7 +66,7 @@ You deploy one Cloudflare Worker and one Cloudflare Pages site using your own AP| **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; each user's accounts and posts are fully isolated |+| **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 || **Dark and light mode** | Toggle between themes from the header |---@@ -236,7 +236,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 an email provider, 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/self-host/email-codes`), and turn off new signups once your team has accounts if the instance is private.**4. Configure credentials**@@ -332,8 +332,14 @@ npx wrangler secret put FRONTEND_URLnpx wrangler secret put ALLOWED_ORIGINS # optionalnpx wrangler secret put UPSTASH_REDIS_REST_URL # optionalnpx wrangler secret put UPSTASH_REDIS_REST_TOKEN # optional+npx wrangler secret put SEND_EMAIL_HOOK_SECRET # optional; email verification codes+npx wrangler secret put RESEND_API_KEY # optional+npx wrangler secret put EMAIL_FROM # optional+npx 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 app at `/docs/self-host/email-codes`.+### Getting API credentials**YouTube Data API v3**diff --git a/ROADMAP.md b/ROADMAP.mdindex 945b3dd..1546bef 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -30,7 +30,8 @@ What Twiligent is for, and what every change should move forward.## In Progress-1. **Backend request pipeline in layers** ([#20](https://github.com/spacesdrive/twiligent/issues/20)) - split the Worker into middleware, route tables, controllers, services and repositories, with a request context (request id, user id, cancellation), security headers, input validation and one error handler.+1. **Email verification codes** ([#29](https://github.com/spacesdrive/twiligent/issues/29)) - confirm new email accounts with a 6-digit code sent through Resend from a Supabase Send Email hook on the Worker, capped at 100 emails a day, with Google sign-in offered once the day's emails run out.+2. **Backend request pipeline in layers** ([#20](https://github.com/spacesdrive/twiligent/issues/20)) - split the Worker into middleware, route tables, controllers, services and repositories, with a request context (request id, user id, cancellation), security headers, input validation and one error handler.---diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.mdindex 3035b7c..0bb4611 100644--- a/docs/architecture/OVERVIEW.md+++ b/docs/architecture/OVERVIEW.md@@ -17,7 +17,8 @@│ Hono v4 app (backend/app.ts) ││ ├── Middleware: CORS, request id, security headers, clients, ││ │ per-IP rate limit │-│ ├── Public: GET /api/health, GET /api/auth/instagram/callback │+│ ├── Public: GET /api/health, GET /api/auth/instagram/callback, │+│ │ POST /api/auth/email-hook (signed by Supabase Auth) ││ ├── Protected (/api/*): requireAuth -> rate limits ││ │ -> route table -> controller -> service -> repository ││ └── Errors: errorHandler -> { success, code, message, ... } │@@ -33,7 +34,9 @@│ Postgres │ │ Redis │ │ ├── YouTube Data API v3 ││ │ │ (cache, │ │ ├── Instagram Graph API v25 ││ tables: │ │ rate │ │ ├── Reddit Public JSON API │-│ accounts │ │ limits)│ │ └── Cloudinary Upload API │+│ accounts │ │ limits,│ │ ├── Cloudinary Upload API │+│ │ │ email │ │ └── Resend Email API (auth emails) │+│ │ │ counts)│ │ ││ settings │ │ │ └──────────────────────────────────────┘│ sched_ │ │ keys: ││ posts │ │ videos: │@@ -54,6 +57,7 @@| Database + Auth | Supabase | `nheuatbcevaxgxyvahtr.supabase.co` || Media cache | Upstash Redis | Configured via `UPSTASH_REDIS_REST_URL` || Media hosting | Cloudinary | `CLOUDINARY_CLOUD_NAME` |+| Auth emails | Resend, through Supabase's Send Email hook | `RESEND_API_KEY`, `EMAIL_FROM` || CI/CD | GitHub Actions | `spacesdrive/twiligent` |## Request Lifecycle (Protected Route)@@ -113,6 +117,7 @@ Cloudflare scheduler fires cron trigger| User settings (GitHub repository) | `settings` table, `value` jsonb | Generic key-value per user || Scheduled posts | `scheduled_posts` table | Queryable by status + scheduled_at || Video/media analytics | Upstash Redis (`videos:` / `ig:` keys) | Avoids repeated heavy API calls |+| Auth email counts | Upstash Redis (`email:day:` / `email:to:` keys, addresses hashed) | Caps verification emails at the provider's free daily quota || Media files (for publishing) | Cloudinary CDN | Instagram requires public URL || Tracked Reddit post images | Cloudinary CDN | Reddit's public JSON API carries no usable thumbnail || API secrets | Cloudflare Worker secrets | Encrypted at rest, never in responses |@@ -129,9 +134,9 @@ The SPA also serves public documentation at `/docs` (no sign-in, no API calls).1. **The Worker never receives binary file uploads.** Cloudinary handles file ingestion directly from the browser. The Worker only receives Cloudinary URLs.-2. **Redis is always optional.** Every cache call goes through `analyticsCacheRepository`, which catches Redis failures, so a miss falls back to live APIs, and rate limits fall back to per-isolate memory. Removing Upstash credentials degrades performance and loosens rate limits but never breaks functionality.+2. **Redis is always optional.** Every cache call goes through `analyticsCacheRepository`, which catches Redis failures, so a miss falls back to live APIs, and rate limits fall back to per-isolate memory. The email counters in `emailQuotaRepository` fall back to Resend's own daily quota. Removing Upstash credentials degrades performance and loosens rate limits but never breaks functionality.-3. **The service-role key is never used on the frontend.** The frontend uses only the anon key (for Supabase Auth client-side). The service-role key is a Worker secret.+3. **The service-role key is never used on the frontend.** The frontend uses only the anon key (for Supabase Auth client-side). The service-role key is a Worker secret. Sign-up and sign-in go from the browser to Supabase Auth directly; the Worker only sends the emails Supabase hands it through the signed Send Email hook (see `docs/architecture/data-flows/AUTHENTICATION.md`).4. **`safeAccount()` is the only place access tokens are stripped.** Repositories return full accounts; every account in a response passes through this function first.diff --git a/docs/architecture/backend/CACHING.md b/docs/architecture/backend/CACHING.mdindex 6c4ab24..3ae2f97 100644--- a/docs/architecture/backend/CACHING.md+++ b/docs/architecture/backend/CACHING.md@@ -57,6 +57,15 @@ The rate limiter uses its own client with a 1 second timeout and no retries; seeRate limit state also lives in Redis under `twiligent:ratelimit:{rule}:{identifier}` keys (hashes or sorted sets, each with its own expiry). They are written only by the Lua scripts in `lib/rateLimit/scripts.ts` through a separate fast-fail client; see `RATE_LIMITING.md`.+The auth email counters are not cache either. `repositories/emailQuotaRepository.ts` writes them through the same fast-fail client, so a slow Redis cannot use up the Send Email hook's 5 second budget:++| Key pattern | Content | Set when | Expires |+|---|---|---|---|+| `email:day:{YYYY-MM-DD}` | Emails sent on that UTC day, all users together | Each email the hook sends | 2 days after the last write |+| `email:to:{sha256 of the lowercased address}:{YYYY-MM-DD}` | Emails sent to one address that day; the key holds a hash, never the address | Each email the hook sends | 2 days after the last write |++One Lua script reads both counters and increments both only when neither cap is reached, so two calls at once cannot both take the last email, and a refused send counts nothing. When Redis is missing or fails, the repository answers `unknown` and the email is sent; Resend's own daily quota is then the cap.+**Note:** Instagram OAuth state is an HMAC-signed token and does not use Redis.## Cache Versioningdiff --git a/docs/architecture/backend/HONO.md b/docs/architecture/backend/HONO.mdindex 4c4bc08..13a71f7 100644--- a/docs/architecture/backend/HONO.md+++ b/docs/architecture/backend/HONO.md@@ -25,16 +25,16 @@ The backend is split into layers, each with one job. `REQUEST_PIPELINE.md` is th| `app.ts` | `createApp()`: the ordered middleware pipeline and the two route groups || `server.ts` | The Worker export: `fetch` and `scheduled` || `container.ts` | The composition root: `createServices(clients, config, context)` wires repositories into services |-| `middleware/` | `cors.ts`, `requestContext.ts`, `securityHeaders.ts`, `clients.ts`, `rateLimit.ts`, `auth.ts`, `validate.ts`, `errorHandler.ts` (see `MIDDLEWARE.md`) |+| `middleware/` | `cors.ts`, `requestContext.ts`, `securityHeaders.ts`, `clients.ts`, `rateLimit.ts`, `auth.ts`, `authHook.ts`, `validate.ts`, `errorHandler.ts` (see `MIDDLEWARE.md`) || `routes/` | One route table per feature (`<feature>Routes.ts`) and `index.ts`, which groups them into `publicRoutes` and `protectedRoutes` || `controllers/` | One controller file per feature (`<feature>Controller.ts`) and `http.ts` with `controller`, `servicesFor(c)` and `pathParam(c, name)` || `validators/` | Request body and query parsers (`<feature>Validators.ts`) and the field helpers in `fields.ts` |-| `services/` | Feature services (`<feature>Service.ts`, `scheduledPublisher.ts`) and the platform modules in `youtube/`, `instagram/` and `reddit/` (see `SERVICES.md`) |+| `services/` | Feature services (`<feature>Service.ts`, `scheduledPublisher.ts`) the platform modules in `youtube/`, `instagram/` and `reddit/`, and the auth email modules in `email/` (see `SERVICES.md`) || `repositories/` | Data access, one repository per table or cache (`<table>Repository.ts`), and the query helpers in `query.ts` || `database/` | `supabase.ts` (`getSupabase`, `getSupabaseAuth`) and `redis.ts` (`getRedis`, `getRateLimitRedis`) || `jobs/` | `scheduled.ts`: the cron entry point, `runScheduledJob(cron, env)` |-| `lib/` | Helpers with no HTTP or database code: `errors.ts`, `logger.ts`, `config.ts`, `redact.ts`, `safeAccount.ts`, `oauthState.ts`, `analyticsMath.ts`, `rateLimit/` |-| `types/` | `env.ts` (`Env`), `app.ts` (`AppEnv`, `AppVariables`, `AppContext`), `context.ts` (`RequestContext`) |+| `lib/` | Helpers with no HTTP or database code: `errors.ts`, `logger.ts`, `config.ts`, `redact.ts`, `safeAccount.ts`, `oauthState.ts`, `webhookSignature.ts`, `analyticsMath.ts`, `rateLimit/` |+| `types/` | `env.ts` (`Env`), `app.ts` (`AppEnv`, `AppVariables`, `AppContext`), `context.ts` (`RequestContext`), `authHook.ts` (the Send Email hook payload and error body) |## Application Structure@@ -53,7 +53,7 @@ export function createApp(): Hono<AppEnv> {app.use('*', injectClients); // 4. Supabase and Redis clientsapp.use('/api/*', rateLimit(RATE_LIMIT_RULES.ip, clientIp)); // 5. limit by IP- app.route('/api', publicRoutes); // health check and the OAuth callback+ app.route('/api', publicRoutes); // health check, OAuth callback, email hookconst api = new Hono<AppEnv>();api.use('*', requireAuth); // 6. authentication@@ -66,7 +66,7 @@ export function createApp(): Hono<AppEnv> {}```-`routes/index.ts` registers the public routes on `publicRoutes` (`GET /health`, and `GET /auth/instagram/callback` with the `oauth` rate limit) and mounts every feature route table on `protectedRoutes`. The public group is registered before the protected one, so those two paths answer without a token.+`routes/index.ts` registers the public routes on `publicRoutes` (`GET /health`, `GET /auth/instagram/callback` with the `oauth` rate limit, and the `routes/authHookRoutes.ts` table with `POST /auth/email-hook` behind `verifyAuthHook`) and mounts every feature route table on `protectedRoutes`. The public group is registered before the protected one, so those paths answer without a token.See `REQUEST_PIPELINE.md` for what each step does and `RATE_LIMITING.md` for the rate limit rules.@@ -159,7 +159,7 @@ Controllers do not catch errors. Services, repositories, validators and middlewaAn unknown route gets the same body with `NOT_FOUND` from `notFoundHandler`. An error that is not an `AppError` is a bug: it is logged at `error` level and the client gets `INTERNAL_ERROR` with a message asking it to quote the request id. The status for each code is in `REQUEST_PIPELINE.md`.-The one exception is the Instagram OAuth callback, which catches its own errors so the browser is always redirected back to the app.+The one exception is the Instagram OAuth callback, which catches its own errors so the browser is always redirected back to the app. The Send Email hook does not catch errors either, but its route table sets `router.onError(authHookErrorHandler)`, which answers in the `{ error: { http_code, message } }` shape Supabase Auth reads.## Loggingdiff --git a/docs/architecture/backend/MIDDLEWARE.md b/docs/architecture/backend/MIDDLEWARE.mdindex a883dee..be090d3 100644--- a/docs/architecture/backend/MIDDLEWARE.md+++ b/docs/architecture/backend/MIDDLEWARE.md@@ -12,7 +12,8 @@ Request arrives3. securityHeaders app.use('*', securityHeaders) middleware/securityHeaders.ts4. injectClients app.use('*', injectClients) middleware/clients.ts5. rateLimit(ip) app.use('/api/*', rateLimit(RATE_LIMIT_RULES.ip, clientIp)) middleware/rateLimit.ts- public routes app.route('/api', publicRoutes) health check, OAuth callback (+ rateLimit(oauth))+ public routes app.route('/api', publicRoutes) health check, OAuth callback (+ rateLimit(oauth)),+ email hook (+ verifyAuthHook) middleware/authHook.ts6. requireAuth api.use('*', requireAuth) middleware/auth.ts <- protected routes only7. rateLimit(user, quota, publish) middleware/rateLimit.ts <- protected routes only8. route table api.route('/', protectedRoutes)@@ -158,6 +159,24 @@ Every error thrown by a middleware, controller, service or repository ends here.Failures with status 500 and above are logged at `error` level, 4xx failures at `warn`. `notFoundHandler` answers an unknown route with `NOT_FOUND`. The code to status table is in `REQUEST_PIPELINE.md`.+`authHookErrorHandler` does the same logging and status mapping but answers in the shape Supabase Auth reads from a hook, `{ "error": { "http_code": 429, "message": "..." } }`. Only `routes/authHookRoutes.ts` sets it, with `router.onError`; Hono applies a route table's own error handler to that table's routes.++---++## Auth Hook Signature++**Source:** `backend/middleware/authHook.ts` (`verifyAuthHook`), with `lib/webhookSignature.ts`+**Applied to:** `POST /api/auth/email-hook` only, before its validator++The hook route is public, so the signature is the only proof that a request came from this project's Supabase Auth. `verifyAuthHook`:++1. Throws `NotConfiguredError` (503) when `SEND_EMAIL_HOOK_SECRET` is not set.+2. Reads the raw body with `c.req.text()`. Hono caches it, so the JSON validator after it parses the same text.+3. Checks the Standard Webhooks headers: HMAC-SHA256 over `webhook-id.webhook-timestamp.body` with the base64 key from the `v1,whsec_<base64>` secret, compared with `crypto.subtle.verify` (constant time). Any one `v1,` entry in `webhook-signature` may match.+4. Rejects a timestamp more than five minutes from now, so a captured request cannot be replayed later.++A failure throws `UnauthorizedError` (401).+---## Adding New Middlewarediff --git a/docs/architecture/backend/RATE_LIMITING.md b/docs/architecture/backend/RATE_LIMITING.mdindex 3c0328d..aa27507 100644--- a/docs/architecture/backend/RATE_LIMITING.md+++ b/docs/architecture/backend/RATE_LIMITING.md@@ -37,6 +37,8 @@ Defined in `backend/lib/rateLimit/rules.ts`.| `publish` | `POST /accounts/:id/ig-media-publish`, `/accounts/:id/ig-publish` | User id | Leaking bucket | 50 deep, drains 1 every 15 seconds || `oauth` | `GET /auth/instagram/callback` | Client IP | Fixed window counter | 10 per 10 minutes |+Auth emails have their own daily caps, which are not rate limit rules: the Send Email hook allows `EMAIL_DAILY_LIMIT` emails a day in total (100 by default) and 5 a day to one address, counted per UTC day by `repositories/emailQuotaRepository.ts`. See `docs/architecture/backend/CACHING.md` for the counters and `SERVICES.md` for the rules. Supabase calls the hook from its own servers, so the `ip` rule above counts Supabase, not the person signing up; the per-address cap and Supabase's own email rate limit are what slow down one person.+The limits are sized for the dashboard: an Overview load sends about 20 requests, Instagram container polling sends one every 3 seconds, and bulk publishing sends two Instagram calls per file. Lowering them can block normal use; test the Overview, bulk publishing and tracked content refresh after any change.The client IP comes from `CF-Connecting-IP`, which Cloudflare always sets and which a client cannot override. Locally, `wrangler dev` does not set it, so the IP rule only applies when a test sends the header. IPv4-mapped IPv6 addresses (`::ffff:203.0.113.7`) are limited as the IPv4 address.diff --git a/docs/architecture/backend/REQUEST_PIPELINE.md b/docs/architecture/backend/REQUEST_PIPELINE.mdindex 70b2878..573fd1b 100644--- a/docs/architecture/backend/REQUEST_PIPELINE.md+++ b/docs/architecture/backend/REQUEST_PIPELINE.md@@ -8,7 +8,7 @@ Every API request passes through the same layers, and each layer has one job:| Route table | `backend/routes/` | Maps a method and path to its middleware and controller | HTTP || Controller | `backend/controllers/` | Reads validated input and the user id, calls one service method, picks the status and builds the response | HTTP || Service | `backend/services/` | Business rules and orchestration: what should happen | Application data only |-| Repository | `backend/repositories/` | Data access: one method per query on a Supabase table or the Redis cache | The database |+| Repository | `backend/repositories/` | Data access: one method per query on a Supabase table, the Redis cache or the Redis email counters (`emailQuotaRepository`) | The database || Request context | `types/context.ts`, `AppVariables` | Request-scoped metadata: request id, user id, cancellation signal, logger | Nothing else |The rule of thumb: HTTP concerns stay in middleware and controllers, business concerns in services, database concerns in repositories, cross-cutting work in middleware and request metadata in the request context.@@ -25,7 +25,8 @@ Request3. Security headers middleware/securityHeaders.ts deny-all CSP, no framing, no-referrer, nosniff, HSTS4. Clients middleware/clients.ts per-request Supabase and Redis clients5. Rate limit by IP middleware/rateLimit.ts before authentication, so bad tokens never reach Supabase Auth- Public routes routes/index.ts /api/health, /api/auth/instagram/callback (with its own oauth limit)+ Public routes routes/index.ts /api/health, /api/auth/instagram/callback (with its own oauth limit),+ /api/auth/email-hook (middleware/authHook.ts checks Supabase's signature)6. Authentication middleware/auth.ts verifies the JWT and sets userId; 401 otherwise7. Per-user limits middleware/rateLimit.ts user, quota and publish rules8. Route table routes/<feature>Routes.ts@@ -36,7 +37,7 @@ RequestResponse, or a thrown error -> middleware/errorHandler.ts```-Authorization is ownership: every user-scoped repository method filters by the verified user id, so another user's row is simply not found (404). There are no roles.+Authorization is ownership: every user-scoped repository method filters by the verified user id, so another user's row is simply not found (404). There are no roles. The Send Email hook has no user: Supabase Auth calls it, and the webhook signature takes the place of the JWT.## Request context@@ -73,7 +74,7 @@ Services and repositories throw typed errors from `lib/errors.ts`. An error carr| `ForbiddenError` | `FORBIDDEN` | 403 | Reserved; ownership failures are 404 || `NotFoundError` | `NOT_FOUND` | 404 | The resource does not exist for this user, or the route does not exist || `ConflictError` | `CONFLICT` | 409 | The account is already added |-| (rate limiter) | `RATE_LIMITED` | 429 | A rate limit rule is exceeded; the body adds `retryAfter` |+| `RateLimitedError`, or the rate limiter | `RATE_LIMITED` | 429 | A daily allowance is used up (the auth email caps), or a rate limit rule is exceeded; the rate limiter's body adds `retryAfter` || `UpstreamError` | `UPSTREAM_ERROR` | 502 | YouTube, Instagram or Reddit answered with an error; its message is kept, URLs are removed || `NotConfiguredError` | `NOT_CONFIGURED` | 503 | A Worker secret the request needs is not set || `UpstreamTimeoutError` | `UPSTREAM_TIMEOUT` | 504 | A platform call was cancelled or timed out |@@ -84,6 +85,8 @@ Errors of status 500 and above are logged at `error` level with the request id;Controllers do not catch errors to format them. The one exception is the Instagram OAuth callback, which must redirect the browser back to the app whatever happens.+The Send Email hook is called by Supabase Auth, which reads failures as `{ "error": { "http_code": 429, "message": "..." } }`. Its route table, `routes/authHookRoutes.ts`, sets `router.onError(authHookErrorHandler)`; the status mapping and logging are the same as `errorHandler`'s, only the body differs.+## ValidationHono's `validator` runs before the controller. `middleware/validate.ts` wraps it as `jsonBody(parse)` and `queryParams(parse)`; each parser in `backend/validators/` reads fields with the helpers in `validators/fields.ts` (trimming strings, checking types, applying required-field messages) and throws `ValidationError`. A malformed JSON body is a 400 from Hono's own check. The controller reads the result with `c.req.valid('json')` or `c.req.valid('query')`, so services always receive clean input.diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.mdindex 79e6fc9..582065c 100644--- a/docs/architecture/backend/ROUTES.md+++ b/docs/architecture/backend/ROUTES.md@@ -22,10 +22,10 @@ These statuses apply to every route below and are not repeated in the tables:| 401 | `UNAUTHORIZED` | Protected route without a valid token || 404 | `NOT_FOUND` | The account, post or item does not exist for this user, is on the wrong platform, or the route does not exist || 409 | `CONFLICT` | The account is already added |-| 429 | `RATE_LIMITED` | A rate limit rule is exceeded; the body adds `retryAfter` (seconds) |+| 429 | `RATE_LIMITED` | A rate limit rule is exceeded; the body adds `retryAfter` (seconds). The email hook also answers 429 when the day's emails are used up || 500 | `DATABASE_ERROR`, `INTERNAL_ERROR` | A Supabase query failed, or a bug || 502 | `UPSTREAM_ERROR` | YouTube, Instagram or Reddit answered with an error; the platform's message is kept with URLs removed |-| 503 | `NOT_CONFIGURED` | A Worker secret the route needs (YouTube key, Instagram app, Cloudinary) is not set |+| 503 | `NOT_CONFIGURED` | A Worker secret the route needs (YouTube key, Instagram app, Cloudinary, the email hook secrets) is not set || 504 | `UPSTREAM_TIMEOUT` | A platform call was cancelled or timed out |## Public Routes@@ -36,6 +36,18 @@ Registered on `publicRoutes` in `routes/index.ts`.|---|---|---|---|| GET | `/api/health` | `healthController.getHealth` | Returns `{ status: 'ok', timestamp }` || GET | `/api/auth/instagram/callback` | `instagramAuthController.handleInstagramCallback` | OAuth code exchange; always redirects the browser back to the accounts page with `ig_connected=true` or `ig_error=<reason>`, never a JSON error |+| POST | `/api/auth/email-hook` | `authHookController.sendAuthEmail` (`routes/authHookRoutes.ts`) | Supabase Auth's Send Email hook: sends sign-up, password reset and other auth emails through Resend. Answers `{}` |++### Send Email hook++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).+- **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.## Protected Routes (require `Authorization: Bearer <jwt>`)diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.mdindex 72847e7..9959059 100644--- a/docs/architecture/backend/SERVICES.md+++ b/docs/architecture/backend/SERVICES.md@@ -41,6 +41,7 @@ A service receives only what it uses: repositories, the cleaned `AppConfig` from| `overview` | `overviewService.ts` | accounts, tracked posts, cache | `summary` || `settings` | `settingsService.ts` | settings | `githubSettings`, `saveGithubSettings`, `serverKeyStatus` || `instagramConnect` | `instagramConnectService.ts` | accounts | `authorizationUrl`, `userIdFromState`, `connect`, plus `configured` and `accountsPageUrl` |+| `authEmail` | `authEmailService.ts` | email quota (Redis, the fail-fast client) | `send(hook, webhookId)` (Supabase Auth's Send Email hook; no user) |Every user-scoped method takes the verified `userId` as its first argument. Methods that need one of the user's records load it with a `...ForUser` repository method and throw `NotFoundError` when it is missing or on the wrong platform, so another user's record is never found. `scheduledPublisher` and `tokenRefresh` are the only services that use the cross-user repository methods (`listAll`, `findById`, `updateById`, `listDue`, `claim`).@@ -68,6 +69,26 @@ Every user-scoped method takes the verified `userId` as its first argument. Meth`readInstagramOAuthConfig(env)` in `lib/config.ts` strips a leading byte order mark and whitespace from the app id, secret and URLs, drops a trailing slash from `BACKEND_URL`, and falls back to `http://localhost:8787` and `http://localhost:5173`. `authorizationUrl` throws `NotConfiguredError` (503) without the app credentials, and `buildAuthorizationUrl` signs the state with the app secret (`lib/oauthState.ts`). `connect` exchanges the code (stripping a trailing `#_`), upgrades to a long-lived token when Instagram allows it (otherwise keeps the short-lived token with no expiry), fetches the profile and returns `'already_added'` or `'connected'`. The callback controller turns those into the `ig_error` and `ig_connected` redirects.+### Auth emails (`authEmailService.ts`, `email/authEmails.ts`, `email/resendApi.ts`)++`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.+- `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`).+- Any other action: nothing, and the service logs it.++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.+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).++A notice that hits a cap is skipped with a warning instead of failing, because the change it reports has already happened. Without Redis the claim is `unknown`, the email is sent anyway and a warning is logged; Resend's own quota is then the only cap.+### Publishing (`publishingService.ts`, `scheduledPublisher.ts`)`publishableAccount(account)` in `publishingService.ts` is the one check both publishers use: the account must be Instagram (`NotFoundError` otherwise) and have an `igUserId` and token (`ValidationError` otherwise). `cloudinaryConfig()` throws `NotConfiguredError` (503) when the Worker has no Cloudinary settings.diff --git a/docs/architecture/cloudflare/CI_CD.md b/docs/architecture/cloudflare/CI_CD.mdindex e93c95f..d56f8b6 100644--- a/docs/architecture/cloudflare/CI_CD.md+++ b/docs/architecture/cloudflare/CI_CD.md@@ -47,7 +47,7 @@ A type error or failing test stops the run before the deploy step.- `CLOUDFLARE_API_TOKEN` - API token with Worker deploy permission- `CLOUDFLARE_ACCOUNT_ID` - your Cloudflare account ID-The workflow does not set the Worker's own secrets (`SUPABASE_*`, `FRONTEND_URL`, the optional `ALLOWED_ORIGINS` and the rest). They are set once with `npx wrangler secret put` and kept across deploys; see `WORKERS.md`.+The workflow does not set the Worker's own secrets (`SUPABASE_*`, `FRONTEND_URL`, the optional `ALLOWED_ORIGINS`, the optional email secrets `SEND_EMAIL_HOOK_SECRET`, `RESEND_API_KEY`, `EMAIL_FROM` and `EMAIL_DAILY_LIMIT`, and the rest). They are set once with `npx wrangler secret put` and kept across deploys; see `WORKERS.md`.**Does not** redeploy on frontend-only changes, documentation changes, or script changes.diff --git a/docs/architecture/cloudflare/WORKERS.md b/docs/architecture/cloudflare/WORKERS.mdindex 578a7b5..41704d7 100644--- a/docs/architecture/cloudflare/WORKERS.md+++ b/docs/architecture/cloudflare/WORKERS.md@@ -52,6 +52,10 @@ All secrets are set via `npx wrangler secret put <NAME>`, run from `backend/`. T| `ALLOWED_ORIGINS` | Optional | Comma-separated extra browser origins CORS allows besides `FRONTEND_URL`, such as a second domain (`https://a.example.com,https://b.example.com`). Set it with `wrangler secret put` like the others, so the next `wrangler deploy` keeps it (a plain variable added in the dashboard can be replaced on deploy) || `UPSTASH_REDIS_REST_URL` | Optional | Upstash Redis endpoint; caching disabled if absent || `UPSTASH_REDIS_REST_TOKEN` | Optional | Upstash auth token |+| `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 |### Setting secrets@@ -80,6 +84,10 @@ FRONTEND_URL=http://localhost:5173# ALLOWED_ORIGINS=https://another-domain.example.comUPSTASH_REDIS_REST_URL=https://...UPSTASH_REDIS_REST_TOKEN=...+# only to test the Send Email hook locally; Supabase cannot reach localhost, so sign request bodies yourself+# SEND_EMAIL_HOOK_SECRET=v1,whsec_...+# RESEND_API_KEY=re_...+# EMAIL_FROM=Twiligent <[email protected]>```Run locally from the repository root: `npm run dev:backend` (Worker only, port 8787) or `npm run dev` (Worker and Vite together). Both run `wrangler dev` in `backend/`, which reloads on save.diff --git a/docs/architecture/data-flows/AUTHENTICATION.md b/docs/architecture/data-flows/AUTHENTICATION.mdindex c8be34a..28512c2 100644--- a/docs/architecture/data-flows/AUTHENTICATION.md+++ b/docs/architecture/data-flows/AUTHENTICATION.md@@ -31,6 +31,45 @@ AppProvider mounts -> loadAccounts() firesUser sees Overview dashboard```+## Sign-up with an Email Code++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 (sign-up mode) -> 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)+ -> verifyAuthHook: Standard Webhooks HMAC with SEND_EMAIL_HOOK_SECRET, timestamp within 5 minutes; 401 otherwise+ -> parseAuthEmailHook: user.email, email_data.email_action_type, token, token_hash, ...+ -> authEmail.send(hook, webhookId)+ -> composeAuthEmails: subject, code and a /auth/v1/verify link+ -> emailQuotaRepository.claim: today's count < EMAIL_DAILY_LIMIT (100) and this address < 5 today+ past a cap -> 429 { error: { http_code: 429, message } }+ -> Resend POST /emails (Idempotency-Key: webhook-id); Resend's daily_quota_exceeded -> the same 429+ -> 200 {}+ -> signUp resolves with a user and no session+ │+ ▼+Login.tsx opens the code step (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+```++Other cases on the login 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 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 |+| 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).+## Sign in with GoogleOptional; enabled when `VITE_GOOGLE_CLIENT_ID` is set and the Google provider is on in Supabase.diff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.mdindex 43da13e..6ae410b 100644--- a/docs/architecture/database/SECURITY.md+++ b/docs/architecture/database/SECURITY.md@@ -43,6 +43,8 @@ This denies the anon and authenticated roles everything, while the service-roleSupabase 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.+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`.+**The service-role key must never appear in:**- Frontend code- API responses@@ -73,7 +75,8 @@ The Instagram `accessToken` stored in `accounts.data.accessToken` is a long-liveWhen reviewing security, check these files:- `backend/middleware/auth.ts` - JWT verification-- `backend/repositories/` - every user-scoped method ends in `ForUser` and filters by `user_id`; the methods without a `userId` are used only by `scheduledPublisher.ts` and `tokenRefreshService.ts`+- `backend/repositories/` - every user-scoped method ends in `ForUser` and filters by `user_id`; the methods without a `userId` are used only by `scheduledPublisher.ts` and `tokenRefreshService.ts`. `emailQuotaRepository.ts` is not user-scoped: it keeps instance-wide Redis counters for the Send Email hook, keyed by a hash of the address+- `backend/middleware/authHook.ts` and `backend/lib/webhookSignature.ts` - the only thing that authenticates the public Send Email hook- `backend/controllers/` and `backend/services/` - the `userId` passed to a repository always comes from `c.get('userId')`, never from the body or query- `backend/lib/safeAccount.ts` - `safeAccount()` definition; it strips every stored credential for all platforms- All controllers in `backend/controllers/` - verify `safeAccount()` is called on every account responsediff --git a/docs/architecture/frontend/CONTEXTS.md b/docs/architecture/frontend/CONTEXTS.mdindex b160ce7..0f2c139 100644--- a/docs/architecture/frontend/CONTEXTS.md+++ b/docs/architecture/frontend/CONTEXTS.md@@ -7,7 +7,7 @@ Wraps Supabase Auth state and exposes it to the entire app.### What it provides```ts-const { session, user, signIn, signUp, signInWithGoogle, signOut } = useAuth();+const { session, user, signIn, signUp, verifySignUpCode, resendSignUpCode, signInWithGoogle, signOut } = useAuth();```The value is typed as `AuthContextValue`, exported from `AuthContext.tsx`.@@ -17,7 +17,9 @@ 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()` |+| `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 |+| `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 || `signInWithGoogle(idToken, nonce)` | async function | Calls `supabase.auth.signInWithIdToken({ provider: 'google', token, nonce })` with the ID token from Google's button and the raw nonce || `signOut()` | async function | Calls `supabase.auth.signOut()` |@@ -40,7 +42,7 @@ useEffect(() => {### Where to use it- `ProtectedRoute` - reads `session` to decide whether to redirect to `/login`-- `Login.tsx` - calls `signIn()`, `signUp()` and `signInWithGoogle()`+- `Login.tsx` - calls `signIn()`, `signUp()`, `verifySignUpCode()`, `resendSignUpCode()` and `signInWithGoogle()`- `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/REACT_ARCHITECTURE.md b/docs/architecture/frontend/REACT_ARCHITECTURE.mdindex 8393e80..46ff3ee 100644--- a/docs/architecture/frontend/REACT_ARCHITECTURE.md+++ b/docs/architecture/frontend/REACT_ARCHITECTURE.md@@ -111,8 +111,9 @@ 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, fields and the password toggle+ Login.tsx Auth page (not lazy-loaded, always small); owns mode (sign in, sign up, code), fields, the password toggle and the resend waitLoginForm.tsx Email and password form+ LoginCodeForm.tsx The 6-digit email code step after sign-up, with Send a new codeLoginBrandPanel.tsx Decorative product preview beside the formloginCopy.ts Sign-in and sign-up text, privacy linkfeatures/diff --git a/docs/guidelines/API_CONVENTIONS.md b/docs/guidelines/API_CONVENTIONS.mdindex b348248..4fc2ce9 100644--- a/docs/guidelines/API_CONVENTIONS.md+++ b/docs/guidelines/API_CONVENTIONS.md@@ -33,6 +33,8 @@ Every failure has a 4xx or 5xx status and one body, the `ApiFailure` type in `sh`code` is one of the `ApiErrorCode` values and decides the status. `message` is written for the user. `requestId` matches the `X-Request-Id` header and the Worker's log lines. Only a 429 adds `retryAfter`. There is no other error shape: never return `{ error }`, and never send `success: false` with a 2xx status.+The one route that answers differently is `POST /api/auth/email-hook`, which Supabase Auth calls: its failures are `{ "error": { "http_code": 429, "message": "..." } }` with the same statuses, written by `authHookErrorHandler`, because that is the shape Supabase reads.+Controllers never build these bodies; services, repositories, validators and middleware throw the typed errors in `backend/lib/errors.ts`. The `request()` function in `frontend/src/services/api.ts` throws an `Error` with the body's `message` (plus the request id on a 5xx) when the status is not 2xx, so a 2xx response is always a success.## Status Codes@@ -46,9 +48,9 @@ Controllers never build these bodies; services, repositories, validators and mid| `403` | `FORBIDDEN` - reserved; a record that belongs to another user is a 404 || `404` | `NOT_FOUND` - resource not found for this user, or no such route || `409` | `CONFLICT` - the resource already exists (an account that is already added) |-| `429` | `RATE_LIMITED` - returned by the `rateLimit` middleware only, with `Retry-After` and `retryAfter` in the body (see `docs/architecture/backend/RATE_LIMITING.md`) |+| `429` | `RATE_LIMITED` - returned by the `rateLimit` middleware, with `Retry-After` and `retryAfter` in the body (see `docs/architecture/backend/RATE_LIMITING.md`), and by the Send Email hook when the day's emails are used up (`RateLimitedError`, no `retryAfter`) || `500` | `DATABASE_ERROR` or `INTERNAL_ERROR` - a failed query or an unexpected error |-| `502` | `UPSTREAM_ERROR` - YouTube, Instagram or Reddit answered with an error |+| `502` | `UPSTREAM_ERROR` - YouTube, Instagram, Reddit or Resend answered with an error || `503` | `NOT_CONFIGURED` - a Worker secret the request needs is not set || `504` | `UPSTREAM_TIMEOUT` - a platform call was cancelled or timed out |diff --git a/docs/guidelines/ERROR_HANDLING.md b/docs/guidelines/ERROR_HANDLING.mdindex 5087189..dcecf54 100644--- a/docs/guidelines/ERROR_HANDLING.md+++ b/docs/guidelines/ERROR_HANDLING.md@@ -7,11 +7,12 @@ Every backend failure is a typed error thrown where the problem is found and for| Error | Code | Status | Throw when ||---|---|---|---|| `ValidationError` | `VALIDATION_ERROR` | 400 | Input is missing or malformed, or a stored field the request needs is missing |-| `UnauthorizedError` | `UNAUTHORIZED` | 401 | No token, or an invalid or expired one (thrown by `requireAuth` only) |+| `UnauthorizedError` | `UNAUTHORIZED` | 401 | No token, or an invalid or expired one (thrown by `requireAuth`), or a Send Email hook call without a valid signature (thrown by `verifyAuthHook`) || `ForbiddenError` | `FORBIDDEN` | 403 | Reserved; another user's record is a `NotFoundError` || `NotFoundError` | `NOT_FOUND` | 404 | The record does not exist for this user, or is on the wrong platform || `ConflictError` | `CONFLICT` | 409 | The account is already added |-| `UpstreamError` | `UPSTREAM_ERROR` | 502 | YouTube, Instagram or Reddit answered with an error |+| `RateLimitedError` | `RATE_LIMITED` | 429 | A daily allowance is used up: the auth email caps in `authEmailService.ts`. Per-request limits are the rate limiter's job, not this error |+| `UpstreamError` | `UPSTREAM_ERROR` | 502 | YouTube, Instagram, Reddit or Resend answered with an error || `NotConfiguredError` | `NOT_CONFIGURED` | 503 | A Worker secret the request needs is not set || `UpstreamTimeoutError` | `UPSTREAM_TIMEOUT` | 504 | A platform call was cancelled or timed out || `DatabaseError` | `DATABASE_ERROR` | 500 | A Supabase query failed (thrown by `repositories/query.ts`) |@@ -104,6 +105,8 @@ 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.+### Frontend API CallsCatch in the component or handler, show a toast, and handle loading state:diff --git a/docs/philosophy/SECURITY.md b/docs/philosophy/SECURITY.mdindex 70d9b21..0b7f6c2 100644--- a/docs/philosophy/SECURITY.md+++ b/docs/philosophy/SECURITY.md@@ -10,6 +10,8 @@| Instagram App Secret | Worker secret | Worker only | **Never** || YouTube API key | Worker secret | Worker only | **Never** || Cloudinary credentials | Worker secrets | Worker only | **Never** |+| Send Email hook secret (`SEND_EMAIL_HOOK_SECRET`) | Worker secret, and Supabase's hook settings | Worker (verifies) and Supabase Auth (signs) | **Never** |+| Resend API key | Worker secret | Worker only | **Never** || User's Instagram access token | `accounts.data.accessToken` in DB | Worker only | **Never** || Supabase JWT secret | Supabase (internal) | Supabase JWT verification | **Never** |@@ -66,6 +68,18 @@ The Instagram OAuth flow uses a self-verifying HMAC state token to prevent CSRF:If the HMAC check fails, the callback discards the code and redirects the browser back to the accounts page with `ig_error=invalid_state`. An attacker cannot forge a valid state without the `INSTAGRAM_APP_SECRET`.+## Auth Email Hook++`POST /api/auth/email-hook` is public because Supabase Auth, not a browser, calls it. Its only proof of origin is the Standard Webhooks signature made with `SEND_EMAIL_HOOK_SECRET`:++1. The Worker recomputes HMAC-SHA256 over `webhook-id.webhook-timestamp.body` and compares it in constant time (`crypto.subtle.verify`).+2. A timestamp more than five minutes from now is refused, so a captured request cannot be replayed later.+3. Without the secret the route answers 503 instead of sending anything.++Without a valid signature nobody can make the Worker send email or read the codes. The codes travel only from Supabase to the Worker to Resend; they are never logged. The daily counters in Redis are keyed by a SHA-256 hash of the address, never the address.++The caps also protect the free email quota. There are 100 emails a day by default and 5 a day to one address, and a refused send counts nothing, so repeated requests for one address cannot use up the day. Supabase's own email rate limit and CAPTCHA add protection against many addresses at once (see the self-hosting page `self-host/email-codes`).+## Rate LimitingEvery `/api` request is rate limited per client IP before authentication, so a flood of invalid tokens never reaches Supabase Auth. Protected requests are also limited per user, and routes that spend the shared YouTube quota or the Instagram and Reddit limits have a tighter per-user rule. Limits are counted atomically in Redis (one Lua script per check) and fall back to per-isolate memory when Redis is absent or failing, so they never fail open entirely and never fail a request. See `docs/architecture/backend/RATE_LIMITING.md`.@@ -101,6 +115,7 @@ If a credential is compromised:2. GitHub Actions secrets: update in repository Settings -> Secrets3. Instagram App Secret: rotate in Meta Developer dashboard, then update Worker secret4. Supabase service role key: rotate in Supabase project Settings -> API-5. User Instagram tokens: user must reconnect their account via the OAuth flow+5. Send Email hook secret: generate a new one in Supabase Authentication -> Auth Hooks, then `wrangler secret put SEND_EMAIL_HOOK_SECRET`; Resend API key: create a new key in Resend, update the Worker secret, then delete the old key+6. User Instagram tokens: user must reconnect their account via the OAuth flowThere is no automated secrets rotation. This is a known gap.diff --git a/docs/workflows/DEPLOYMENT.md b/docs/workflows/DEPLOYMENT.mdindex 0730f0b..8561e84 100644--- a/docs/workflows/DEPLOYMENT.md+++ b/docs/workflows/DEPLOYMENT.md@@ -72,12 +72,18 @@ npx wrangler secret put FRONTEND_URLnpx wrangler secret put ALLOWED_ORIGINS # optional; extra browser origins, comma-separatednpx wrangler secret put UPSTASH_REDIS_REST_URL # optionalnpx wrangler secret put UPSTASH_REDIS_REST_TOKEN # optional+npx wrangler secret put SEND_EMAIL_HOOK_SECRET # optional; email verification codes (with the three below)+npx wrangler secret put RESEND_API_KEY # optional+npx wrangler secret put EMAIL_FROM # optional+npx wrangler secret put EMAIL_DAILY_LIMIT # optional; defaults to 100```Each command prompts for the value (no echo - the value is not shown).`FRONTEND_URL` is also the browser origin the API accepts: CORS answers only `FRONTEND_URL` and the origins listed in `ALLOWED_ORIGINS`. Set `ALLOWED_ORIGINS` when the app is served from more than one address (for example a custom domain and the `pages.dev` address), and update `FRONTEND_URL` when the domain changes, or the browser blocks every API call.+The email secrets only matter once Supabase's Send Email hook points at `https://<worker>/api/auth/email-hook`. Set them before turning the hook on: while the hook is on and the secrets are missing, every sign-up and password reset fails with a 503. The full setup (Resend domain, hook, **Confirm email**, rate limit) is in the in-app guide at `/docs/self-host/email-codes`. To check the hook after a deploy, sign up with an address you own and watch `npx wrangler tail` for the `auth email sent` line.+## Setting GitHub Actions SecretsRequired for `deploy-frontend.yml` and `publish-scheduled.yml`:diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.mdindex e294ea7..9a2226d 100644--- a/docs/workflows/TESTING.md+++ b/docs/workflows/TESTING.md@@ -32,6 +32,9 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that| `backend/validators/fields.ts` | `backend/tests/validators/fields.test.ts` || `frontend/src/lib/accounts.ts` | `frontend/tests/lib/accounts.test.ts` || `frontend/src/lib/apiErrors.ts` | `frontend/tests/lib/apiErrors.test.ts` |+| `backend/routes/authHookRoutes.ts` | `backend/tests/routes/authHookRoutes.test.ts` |+| `backend/services/authEmailService.ts` | `backend/tests/services/authEmailService.test.ts` |+| `frontend/src/lib/authErrors.ts` | `frontend/tests/lib/authErrors.test.ts` || `frontend/src/features/analytics/overview/overviewStats.ts` | `frontend/tests/features/analytics/overview/overviewStats.test.ts` || `frontend/src/docs/nav.ts` | `frontend/tests/docs/nav.test.ts` |@@ -47,6 +50,8 @@ 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 testing workflow documented here describes what should run before shipping any change.## Pre-Deployment Checklist@@ -118,6 +123,14 @@ Open the app in a browser. For each changed area, test:- [ ] Login with invalid credentials -> error message shown- [ ] 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+- [ ] 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+- [ ] 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+**Request pipeline (if middleware, CORS or error handling changed):**- [ ] Every response, including errors, has an `X-Request-Id` header and the security headers (`Content-Security-Policy`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, `X-Content-Type-Options: nosniff`)- [ ] `curl -i -H "Origin: <FRONTEND_URL>" .../api/health` returns `Access-Control-Allow-Origin` with that origindiff --git a/frontend/src/docs/nav.ts b/frontend/src/docs/nav.tsindex 1ca1b45..9cafb7f 100644--- a/frontend/src/docs/nav.ts+++ b/frontend/src/docs/nav.ts@@ -84,6 +84,7 @@ export const DOC_TABS: DocTab[] = [pages: [{ slug: 'self-host/supabase', title: 'Supabase', keywords: ['database', 'auth', 'sql', 'rls', 'keys'] },{ slug: 'self-host/google-sign-in', title: 'Sign in with Google (optional)', keywords: ['google', 'oauth', 'login', 'branding', 'logo', 'verification'] },+ { slug: 'self-host/email-codes', title: 'Email verification codes (optional)', keywords: ['email', 'resend', 'smtp', 'confirm', 'otp', 'code', 'sign up', 'hook'] },{ slug: 'self-host/youtube', title: 'YouTube API key', keywords: ['google cloud', 'data api'] },{ slug: 'self-host/instagram', title: 'Instagram app', keywords: ['meta', 'facebook', 'oauth', 'redirect', 'tester', 'app review'] },{ slug: 'self-host/cloudinary', title: 'Cloudinary', keywords: ['media', 'upload preset', 'cdn'] },diff --git a/frontend/src/docs/pages/SelfHost.tsx b/frontend/src/docs/pages/SelfHost.tsxindex c637409..d76a1da 100644--- a/frontend/src/docs/pages/SelfHost.tsx+++ b/frontend/src/docs/pages/SelfHost.tsx@@ -3,6 +3,7 @@ export { SCHEMA_SQL } from './selfHost/selfHostSql';export { default as Overview } from './selfHost/Overview';export { default as Supabase } from './selfHost/Supabase';export { default as GoogleSignIn } from './selfHost/GoogleSignIn';+export { default as EmailCodes } from './selfHost/EmailCodes';export { default as YouTube } from './selfHost/YouTube';export { default as Instagram } from './selfHost/Instagram';export { default as Cloudinary } from './selfHost/Cloudinary';diff --git a/frontend/src/docs/pages/reference/Environment.tsx b/frontend/src/docs/pages/reference/Environment.tsxindex e69d104..5b10c02 100644--- a/frontend/src/docs/pages/reference/Environment.tsx+++ b/frontend/src/docs/pages/reference/Environment.tsx@@ -17,6 +17,10 @@ const BACKEND_VARS: [string, Need, boolean, string, string][] = [['ALLOWED_ORIGINS', 'optional', false, 'Other addresses the site is served from, comma-separated, for example https://twiligent.pages.dev', 'Lets the site call the backend from more than one address.'],['UPSTASH_REDIS_REST_URL', 'optional', false, 'Upstash database, REST API', 'Cache address.'],['UPSTASH_REDIS_REST_TOKEN', 'optional', true, 'Upstash database, REST API', 'Cache password.'],+ ['SEND_EMAIL_HOOK_SECRET', 'optional', true, 'Supabase, Authentication, Auth Hooks, Send Email hook', 'Proves an email request came from your Supabase project.'],+ ['RESEND_API_KEY', 'optional', true, 'Resend, API Keys (sending access)', 'Sends verification codes and other sign-in emails.'],+ ['EMAIL_FROM', 'optional', false, 'A sender on a domain verified in Resend, for example Twiligent <[email protected]>', 'The sender of those emails.'],+ ['EMAIL_DAILY_LIMIT', 'optional', false, 'A whole number; 100 when not set', 'Emails a day before sign-up points people to Google.'],];const FRONTEND_VARS: [string, Need, string][] = [diff --git a/frontend/src/docs/pages/selfHost/DeployBackend.tsx b/frontend/src/docs/pages/selfHost/DeployBackend.tsxindex ce0fbcc..05ff3ae 100644--- a/frontend/src/docs/pages/selfHost/DeployBackend.tsx+++ b/frontend/src/docs/pages/selfHost/DeployBackend.tsx@@ -1,5 +1,5 @@import React from 'react';-import { DocTitle, H2, P, Code, CodeBlock, Steps, Step, Table } from '../../components';+import { DocTitle, H2, P, A, Code, CodeBlock, Steps, Step, Table } from '../../components';export default function DeployBackend() {return (@@ -34,7 +34,7 @@ npx wrangler secret put CLOUDINARY_UPLOAD_PRESETnpx wrangler secret put BACKEND_URLnpx wrangler secret put FRONTEND_URL`}</CodeBlock>- <P>If you use Redis, also add <Code>UPSTASH_REDIS_REST_URL</Code> and <Code>UPSTASH_REDIS_REST_TOKEN</Code>. Skip any platform you do not use. <Code>FRONTEND_URL</Code> is the address of the site from the next page; you can set it after deploying the frontend, but the site cannot reach the backend until you do. If the site is served from more than one address, list the others in <Code>ALLOWED_ORIGINS</Code>, separated by commas.</P>+ <P>If you use Redis, also add <Code>UPSTASH_REDIS_REST_URL</Code> and <Code>UPSTASH_REDIS_REST_TOKEN</Code>. Skip any platform you do not use. <Code>FRONTEND_URL</Code> is the address of the site from the next page; you can set it after deploying the frontend, but the site cannot reach the backend until you do. If the site is served from more than one address, list the others in <Code>ALLOWED_ORIGINS</Code>, separated by commas. To email verification codes, add the secrets in <A to="/docs/self-host/email-codes">Email verification codes</A>.</P></Step><Step title="Check it is running"><P>Open <Code>{'https://your-backend-url/api/health'}</Code>. It should return <Code>{'{"status":"ok"}'}</Code> with a timestamp. Every response also carries an <Code>X-Request-Id</Code> header; server error messages in the app show the same id, and you can find its log line with <Code>npx wrangler tail</Code>.</P>diff --git a/frontend/src/docs/pages/selfHost/EmailCodes.tsx b/frontend/src/docs/pages/selfHost/EmailCodes.tsxnew file mode 100644index 0000000..4cbb9ce--- /dev/null+++ b/frontend/src/docs/pages/selfHost/EmailCodes.tsx@@ -0,0 +1,47 @@+import React from 'react';+import { DocTitle, P, A, Code, CodeBlock, Callout, Steps, Step } from '../../components';++export default function EmailCodes() {+ return (+ <>+ <DocTitle title="Email verification codes (optional)" lead="Confirm each new email account with a 6-digit code, sent free through Resend, with a daily cap." />++ <Callout type="note" title="How it works">+ <p>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.</p>+ </Callout>++ <Steps>+ <Step title="Create a Resend account and verify your domain">+ <P>Sign up at <A href="https://resend.com">resend.com</A>. Under <strong>Domains</strong>, add the domain you will send from, such as <Code>example.com</Code>, and add the DNS records Resend shows. Emails from an unverified domain are refused. The free plan allows one domain.</P>+ </Step>+ <Step title="Create an API key">+ <P>Under <strong>API Keys</strong>, create a key with <strong>Sending access</strong> for that domain. Copy it; Resend shows it once.</P>+ </Step>+ <Step title="Add the email secrets to the backend">+ <P>In <Code>backend/</Code>, run:</P>+ <CodeBlock>{`npx wrangler secret put RESEND_API_KEY+npx wrangler secret put EMAIL_FROM`}</CodeBlock>+ <P><Code>EMAIL_FROM</Code> is the sender people see, on your verified domain, for example <Code>{'Twiligent <[email protected]>'}</Code>. If you pay for a Resend plan without a daily quota, also set <Code>EMAIL_DAILY_LIMIT</Code> to the number of emails a day you allow.</P>+ </Step>+ <Step title="Point Supabase at the backend">+ <P>In Supabase, open <strong>Authentication</strong>, <strong>Auth Hooks</strong>, and add a <strong>Send Email</strong> hook of type <strong>HTTPS</strong>. The URL is your backend address followed by <Code>/api/auth/email-hook</Code>, for example <Code>https://twiligent-api.example.workers.dev/api/auth/email-hook</Code>. Generate a secret, copy it, and save the hook.</P>+ <CodeBlock>{`npx wrangler secret put SEND_EMAIL_HOOK_SECRET`}</CodeBlock>+ <P>Paste the secret exactly as Supabase shows it, starting with <Code>v1,whsec_</Code>.</P>+ </Step>+ <Step title="Turn on email confirmation">+ <P>Open <strong>Sign In / Providers</strong>, <strong>Email</strong>. Turn on <strong>Confirm email</strong> and keep the email OTP length at 6. New members then enter the code on the sign-up page before they can sign in.</P>+ </Step>+ <Step title="Slow down bursts">+ <P>Open <strong>Rate Limits</strong> and set <strong>Rate limit for sending emails</strong> to about 30 an hour, so a burst of sign-ups cannot use the whole day at once. The backend also allows at most 5 emails a day to any one address. To stop automated sign-ups, turn on CAPTCHA under <strong>Attack Protection</strong>.</P>+ </Step>+ <Step title="Test it">+ <P>Create an account with an address you own. The code should arrive within a minute, from your <Code>EMAIL_FROM</Code> address. If it does not, run <Code>npx wrangler tail</Code> in <Code>backend/</Code> while you sign up: a <Code>request failed</Code> line explains why, for example an unverified domain.</P>+ </Step>+ </Steps>++ <Callout type="warning" title="Every email counts">+ <p>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.</p>+ </Callout>+ </>+ );+}diff --git a/frontend/src/docs/pages/selfHost/Overview.tsx b/frontend/src/docs/pages/selfHost/Overview.tsxindex c9157d3..a112942 100644--- a/frontend/src/docs/pages/selfHost/Overview.tsx+++ b/frontend/src/docs/pages/selfHost/Overview.tsx@@ -23,6 +23,7 @@ export default function Overview() {['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'],['GitHub', 'Deploy on every push, and a backup scheduler', <Badge tone="optional">Optional</Badge>, 'Free'],]}/>diff --git a/frontend/src/docs/pages/selfHost/Supabase.tsx b/frontend/src/docs/pages/selfHost/Supabase.tsxindex 2238cf6..659dfee 100644--- a/frontend/src/docs/pages/selfHost/Supabase.tsx+++ b/frontend/src/docs/pages/selfHost/Supabase.tsx@@ -18,7 +18,7 @@ export default function Supabase() {<Step title="Configure sign-in"><P>Open <strong>Authentication</strong>, then <strong>Sign In / Providers</strong>, then <strong>Email</strong>.</P><UL>- <li>Turn off <strong>Confirm email</strong> unless you have set up an email provider. Otherwise new members never receive the confirmation and cannot sign in.</li>+ <li>Turn off <strong>Confirm email</strong> unless you set up <A to="/docs/self-host/email-codes">email verification codes</A>. Otherwise new members never receive a code and cannot sign in.</li><li>To keep the instance private, turn off <strong>Allow new users to sign up</strong> after you and your team have created accounts. You can also add members yourself under <strong>Authentication</strong>, <strong>Users</strong>, <strong>Add user</strong>.</li></UL></Step>diff --git a/frontend/src/docs/routes.ts b/frontend/src/docs/routes.tsindex a8057d5..d63b915 100644--- a/frontend/src/docs/routes.ts+++ b/frontend/src/docs/routes.ts@@ -32,6 +32,7 @@ const PAGES: Record<string, DocPageComponent> = {'self-host': page('selfHost', 'Overview'),'self-host/supabase': page('selfHost', 'Supabase'),'self-host/google-sign-in': page('selfHost', 'GoogleSignIn'),+ 'self-host/email-codes': page('selfHost', 'EmailCodes'),'self-host/youtube': page('selfHost', 'YouTube'),'self-host/instagram': page('selfHost', 'Instagram'),'self-host/cloudinary': page('selfHost', 'Cloudinary'),