Skip to content

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 readiness check, the timeouts and a recovery runbook

spacesdrivefb177312bf36
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 962fde7..f96bd90 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -23,6 +23,8 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- Public replies: a rule can also post a public reply under the comment, or only that, with up to five wordings that rotate per comment; the private and public replies have their own status, limits, cooldown and retry, and one failing never sends the other again (#107, ADR-044)
- A public reply whose answer was lost is looked for among the comment's replies and posted again once only when it is not there; `AUTOMATION_PUBLIC_ACCOUNT_HOURLY_LIMIT` (default 60) paces public replies, and each person gets at most one per post a day (#107)
- New table `automation_public_replies` and new columns and functions; existing instances run `npm run db:push` before deploying (#107)
+- `GET /api/health/ready`, a readiness check for monitors: it confirms the Supabase secrets are set and the database answers, and reports how long the database took (#110)
+- A recovery runbook, `docs/workflows/RECOVERY.md`: finding a failed request, pausing automation, rolling back, and backing up and restoring the database (#114)
### Changed
@@ -30,12 +32,15 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- The Worker's publishing cron runs every 5 minutes instead of 15; posts still publish on the quarter hour, and the other runs check the reply queue (#89, #100)
- The reply queue sends up to 10 replies a minute instead of 10 every five minutes, accounts take turns so one busy reel cannot hold back another account, and paused, cooling or limited accounts are no longer claimed and put back on every run (#99)
- The daily retention deletes old comments in batches of 1,000 instead of one statement (#101)
+- A database call that does not answer within 15 seconds now fails as a database error, so a hung query can no longer hold a request until its deadline (#112)
+- Error and log text also hides Bearer tokens and token-like parameters, not only URLs (#113)
### Fixed
- The sign-in page opens the dashboard when you are already signed in, so the public site's Sign in and Get started buttons no longer ask you to sign in again (#94)
- The public site's home page opens the dashboard when you are signed in to the app; the docs stay readable (#96)
- Runs claiming replies at the same moment no longer leave each other with nothing to send while jobs wait (#99)
+- A missing `SUPABASE_URL`, `SUPABASE_SERVICE_KEY` or `SUPABASE_ANON_KEY` now answers 503 naming the secret instead of an internal error, and a cron run logs it and stops (#111)
---
diff --git a/claude.md b/claude.md
index 1f41f10..6f0c5f5 100644
--- a/claude.md
+++ b/claude.md
@@ -144,6 +144,7 @@ docs/
TESTING.md Test types, commands, pass criteria
GIT.md Commit format, branch rules, changelog
DEPLOYMENT.md Backend deploy, frontend deploy, verification
+ RECOVERY.md Incidents: find the failure, stop the damage, roll back, back up and restore
SCHEDULING_SETUP.md Five-step GitHub Actions scheduling setup for self-hosters
features/
NEW_ANALYTICS_PAGE.md Add analytics view for a new platform
diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.md
index b096e16..2b75a2b 100644
--- a/docs/architecture/OVERVIEW.md
+++ b/docs/architecture/OVERVIEW.md
@@ -24,7 +24,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/health/ready, │
+│ │ GET /api/auth/instagram/callback, │
│ │ POST /api/auth/email-hook (signed by Supabase Auth), │
│ │ GET/POST /api/webhooks/instagram (signed by Meta) │
│ ├── Protected (/api/*): requireAuth -> rate limits │
diff --git a/docs/architecture/backend/MIDDLEWARE.md b/docs/architecture/backend/MIDDLEWARE.md
index adbaeaa..4dff545 100644
--- a/docs/architecture/backend/MIDDLEWARE.md
+++ b/docs/architecture/backend/MIDDLEWARE.md
@@ -69,10 +69,13 @@ The API only answers JSON and redirects, so nothing it returns may be framed, sn
**Source:** `backend/middleware/clients.ts` (`injectClients`)
**Applied to:** Every request
-Creates per-request Supabase and Redis client instances and sets them on the Hono context. The clients are stateless HTTP clients, so creating them per request is cheap and safe.
+Creates per-request Supabase and Redis client instances and sets them on the Hono context. The clients are stateless HTTP clients, so creating them per request is cheap and safe. It first checks the core secrets with `missingCoreSecrets(env)` (`lib/config.ts`): when `SUPABASE_URL` (or a URL that is not a web address), `SUPABASE_SERVICE_KEY` or `SUPABASE_ANON_KEY` is missing, it throws `NotConfiguredError` naming them, so every request answers 503 with a message that says what to set instead of an internal error.
```ts
export async function injectClients(c: AppContext, next: Next): Promise<void> {
+ const missing = missingCoreSecrets(c.env);
+ if (missing.length > 0) throw new NotConfiguredError(coreSecretsMessage(missing));
+
c.set('supabase', getSupabase(c.env));
c.set('redis', getRedis(c.env));
c.set('rateLimitRedis', getRateLimitRedis(c.env));
@@ -80,7 +83,7 @@ export async function injectClients(c: AppContext, next: Next): Promise<void> {
}
```
-**`getSupabase(env)`** (`database/supabase.ts`) - a Supabase client with the service-role key, used by every repository.
+**`getSupabase(env)`** (`database/supabase.ts`) - a Supabase client with the service-role key, used by every repository. Every query has a 15 second timeout (`DB_TIMEOUT_MS`).
**`getRedis(env)`** (`database/redis.ts`) - an Upstash Redis client if `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` are set, otherwise `null`. `analyticsCacheRepository` treats `null` as a cache that is always empty.
**`getRateLimitRedis(env)`** (`database/redis.ts`) - a second Upstash client for the rate limiter, with retries off and a 1 second timeout, so a Redis outage cannot slow every request. `null` without credentials.
diff --git a/docs/architecture/backend/REQUEST_PIPELINE.md b/docs/architecture/backend/REQUEST_PIPELINE.md
index a1bff6a..519de4d 100644
--- a/docs/architecture/backend/REQUEST_PIPELINE.md
+++ b/docs/architecture/backend/REQUEST_PIPELINE.md
@@ -23,9 +23,9 @@ Request
2. Request context hono/request-id + middleware/requestContext.ts
request id (X-Request-Id), deadline signal, one access log line
3. Security headers middleware/securityHeaders.ts deny-all CSP, no framing, no-referrer, nosniff, HSTS
- 4. Clients middleware/clients.ts per-request Supabase and Redis clients
+ 4. Clients middleware/clients.ts per-request Supabase and Redis clients; 503 naming a missing Supabase secret
5. 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/health/ready, /api/auth/instagram/callback (with its own oauth limit),
/api/auth/email-hook (middleware/authHook.ts checks Supabase's signature),
/api/webhooks/instagram (middleware/metaWebhook.ts checks Meta's signature)
6. Authentication middleware/auth.ts verifies the JWT and sets userId; 401 otherwise
@@ -77,9 +77,9 @@ Services and repositories throw typed errors from `lib/errors.ts`. An error carr
| `ConflictError` | `CONFLICT` | 409 | The account is already added |
| `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 |
+| `NotConfiguredError` | `NOT_CONFIGURED` | 503 | A Worker secret the request needs is not set; `injectClients` throws it for every request when `SUPABASE_URL`, `SUPABASE_SERVICE_KEY` or `SUPABASE_ANON_KEY` is missing |
| `UpstreamTimeoutError` | `UPSTREAM_TIMEOUT` | 504 | A platform call was cancelled or timed out |
-| `DatabaseError` | `DATABASE_ERROR` | 500 | A Supabase query failed; the client gets a plain message, the log gets the driver's |
+| `DatabaseError` | `DATABASE_ERROR` | 500 | A Supabase query failed or did not answer within 15 seconds; the client gets a plain message, the log gets the driver's |
| anything else | `INTERNAL_ERROR` | 500 | A bug; the client gets a message asking it to quote the request id |
Errors of status 500 and above are logged at `error` level with the request id; 4xx errors at `warn`. The frontend's `request()` shows the message and adds the request id to 5xx messages.
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index 1d1e10c..fea3ee2 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -34,7 +34,8 @@ Registered on `publicRoutes` in `routes/index.ts`.
| Method | Path | Controller | Purpose |
|---|---|---|---|
-| GET | `/api/health` | `healthController.getHealth` | Returns `{ status: 'ok', timestamp }` |
+| GET | `/api/health` | `healthController.getHealth` | Liveness: returns `{ status: 'ok', timestamp }` without touching the database |
+| GET | `/api/health/ready` | `healthController.getReadiness` | Readiness: the Supabase secrets are set and one database read succeeds; returns `{ status: 'ready', databaseMs, timestamp }`, or `503 NOT_CONFIGURED` naming a missing secret, or `500 DATABASE_ERROR` |
| GET | `/api/auth/instagram/callback` | `instagramAuthController.handleInstagramCallback` | OAuth code exchange; always redirects the browser back to the accounts page with `ig_connected=true`, `ig_connected=reconnected` (the account was already connected and its token was renewed) 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 `{}` |
| GET | `/api/webhooks/instagram` | `instagramWebhookController.verifyInstagramWebhook` (`routes/instagramWebhookRoutes.ts`) | Meta's webhook check: answers the bare `hub.challenge` as text when `hub.mode=subscribe` and `hub.verify_token` matches `INSTAGRAM_WEBHOOK_VERIFY_TOKEN`; 403 otherwise, 503 when the token is not set |
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index 4c2d03f..6809e14 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -49,6 +49,7 @@ A service receives only what it uses: repositories, the cleaned `AppConfig` from
| `automationPublicReplies` | `automationPublicReplyProcessor.ts` | public replies | `run({ ids?, subrequests?, timeBudgetMs? })` (post due public replies under their comments; webhook, public reply retry route and every minute cron) |
| `automationReconciler` | `automationReconciler.ts` | comments, public replies | `run()` (expire overdue replies, follow-ups and public replies, look for lost replies on Instagram, log the queue's health; five minute cron, never sends or posts) |
| `retention` | `retentionService.ts` | comments, audit | `purge(now?, { commentBatches? })` (daily cron; comments in batches of 1,000) |
+| `health` | `healthService.ts` | health | `readiness()` (`GET /api/health/ready`: one database read, timed; returns no data) |
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`, `tokenRefresh`, `automationWebhook`, `automationProcessor`, `automationFollowups`, `automationPublicReplies`, `automationReconciler` and `retention` are the only services that use the cross-user repository methods (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `claim`, and the automation queue, follow-up, review, intake and retention methods).
diff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.md
index 3bd9b9f..6e3c338 100644
--- a/docs/architecture/database/SECURITY.md
+++ b/docs/architecture/database/SECURITY.md
@@ -8,7 +8,7 @@ The backend uses the **service-role key** for all database operations. This key
2. Controllers pass that `userId` to services, and every user-scoped repository method (named `...ForUser`) appends `.eq('user_id', userId)` using this verified value
3. `userId` is never accepted from request body, query params, or any other user-controlled input
-**This means a missing `.eq('user_id', userId)` call is a security bug.** The centralization of all queries in `backend/repositories/` makes this auditable: a method that takes a `userId` ends in `ForUser`, and the few that reach every user (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `claim`, and for comment automation `listEnabledForInstagramUser`, `insertMany`, the queue methods `claim`, `reserve`, `finish`, `release` and `returnUnstarted` on comments and follow-ups, `insertForMessages`, `expireDue`, `reviewCandidates`, `recordReview`, `health` and the retention `purgeCreatedBefore`) are used only by the cron services, the Instagram webhook and the reply and follow-up processors. Because ownership is a query filter, another user's record is simply not found (404).
+**This means a missing `.eq('user_id', userId)` call is a security bug.** The centralization of all queries in `backend/repositories/` makes this auditable: a method that takes a `userId` ends in `ForUser`, and the few that reach every user (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `claim`, and for comment automation `listEnabledForInstagramUser`, `insertMany`, the queue methods `claim`, `reserve`, `finish`, `release` and `returnUnstarted` on comments and follow-ups, `insertForMessages`, `expireDue`, `reviewCandidates`, `recordReview`, `health` and the retention `purgeCreatedBefore`) are used only by the cron services, the Instagram webhook and the reply and follow-up processors. `healthRepository.ping` reads one `accounts` id for the public readiness check and returns nothing from it. Because ownership is a query filter, another user's record is simply not found (404).
The merge functions follow the same rule: the `...ForUser` repository methods pass the verified `userId` as `p_user_id`, and only `updateById` passes `null`, the cron form that reaches any user's row.
@@ -83,7 +83,7 @@ The Instagram `accessToken` stored in `accounts.data.accessToken` is a long-live
- Graph API calls: `services/instagram/instagramApi.ts`, `instagramMedia.ts` and `instagramPublishing.ts` (the token is passed in as `access_token`)
- Obtaining and storing tokens: `services/instagram/instagramTokens.ts` (long-lived exchange and refresh), `services/instagram/instagramOAuth.ts` (OAuth code exchange), `services/instagramConnectService.ts` (OAuth connect), `services/accountService.ts` and `services/accountFactory.ts` (pasted tokens and new account rows)
- Reading the stored token: `services/publishingService.ts` and `services/scheduledPublisher.ts` (publishing), `services/instagramAnalyticsService.ts` (Instagram analytics and media), `services/accountService.ts` (profile and token refresh), `services/tokenRefreshService.ts` (daily refresh), `services/overviewService.ts` (overview cache warm-up), `services/automationService.ts` (webhook subscription) and `services/automationProcessor.ts` (private replies, through `services/instagram/instagramMessaging.ts`, which sends it as a Bearer header)
- - `claim_automation_comments`, `claim_automation_followups`, `claim_automation_public_replies`, `automation_review_candidates` and `automation_public_review_candidates` return the token to the Worker with each job; the functions are granted only to the service role. The public reply, the follow check, the conversation read and the comment replies read send it as a Bearer header or a query parameter of a Graph API call, and error messages pass through `redactUrls` before they are stored or logged
+ - `claim_automation_comments`, `claim_automation_followups`, `claim_automation_public_replies`, `automation_review_candidates` and `automation_public_review_candidates` return the token to the Worker with each job; the functions are granted only to the service role. The public reply, the follow check, the conversation read and the comment replies read send it as a Bearer header or a query parameter of a Graph API call, and error messages pass through `redactSecrets` before they are stored or logged
4. The `GET /api/accounts` endpoint passes all accounts through `safeAccount()` before returning
**If you add a route that returns account data, you must call `safeAccount()`.** Repositories return full accounts and there is no automatic stripping - it is an explicit step in controllers (and in the services that embed an account in a larger result).
@@ -104,7 +104,7 @@ The Instagram `accessToken` stored in `accounts.data.accessToken` is a long-live
When 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` (or passes it as `p_user_id` to a merge function); the methods without a `userId` are used only by `scheduledPublisher.ts`, `tokenRefreshService.ts`, `automationWebhookService.ts`, `automationProcessor.ts`, `automationFollowupProcessor.ts`, `automationPublicReplyProcessor.ts`, `automationReconciler.ts` and `retentionService.ts`. `automationPublicReplyRepository.ts` follows the same split: `requeueForUser` and `releaseHeldForAccount` take the verified user, the claim, reservation, finish and review methods serve the dispatch and the reconcile. `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/repositories/` - every user-scoped method ends in `ForUser` and filters by `user_id` (or passes it as `p_user_id` to a merge function); the methods without a `userId` are used only by `scheduledPublisher.ts`, `tokenRefreshService.ts`, `automationWebhookService.ts`, `automationProcessor.ts`, `automationFollowupProcessor.ts`, `automationPublicReplyProcessor.ts`, `automationReconciler.ts` and `retentionService.ts`. `automationPublicReplyRepository.ts` follows the same split: `requeueForUser` and `releaseHeldForAccount` take the verified user, the claim, reservation, finish and review methods serve the dispatch and the reconcile. `emailQuotaRepository.ts` is not user-scoped: it keeps instance-wide Redis counters for the Send Email hook, keyed by a hash of the address. `healthRepository.ts` is not user-scoped either: its one read proves the database answers and its result is discarded
- `backend/middleware/authHook.ts` and `backend/lib/webhookSignature.ts` - the only thing that authenticates the public Send Email hook
- `backend/middleware/metaWebhook.ts` and `backend/lib/metaWebhookSignature.ts` - the only thing that authenticates the public Instagram webhook
- `backend/controllers/` and `backend/services/` - the `userId` passed to a repository always comes from `c.get('userId')`, never from the body or query
diff --git a/docs/guidelines/ERROR_HANDLING.md b/docs/guidelines/ERROR_HANDLING.md
index 10332af..090aace 100644
--- a/docs/guidelines/ERROR_HANDLING.md
+++ b/docs/guidelines/ERROR_HANDLING.md
@@ -13,9 +13,9 @@ Every backend failure is a typed error thrown where the problem is found and for
| `ConflictError` | `CONFLICT` | 409 | The account is already added |
| `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 |
+| `NotConfiguredError` | `NOT_CONFIGURED` | 503 | A Worker secret the request needs is not set, or a core Supabase secret is missing (thrown by `injectClients` for every request) |
| `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`) |
+| `DatabaseError` | `DATABASE_ERROR` | 500 | A Supabase query failed or passed the 15 second database timeout (thrown by `repositories/query.ts`) |
An error carries a code, not a status; `middleware/errorHandler.ts` maps the code to the status. Anything that is not an `AppError` becomes `INTERNAL_ERROR` (500).
@@ -32,7 +32,7 @@ if (data.error) {
}
```
-`UpstreamError` removes URLs from its message, because a platform error can echo the request URL with the API key or token in it. Cast the parsed JSON once to an interface that covers the fields the module reads (see `docs/guidelines/TYPESCRIPT.md`).
+`UpstreamError` passes its message through `redactSecrets` (`lib/redact.ts`), which removes URLs, `Bearer` tokens and token-like `name=value` pairs and JSON fields, because a platform error can echo the request URL, a header or the form body with the API key or token in it. Cast the parsed JSON once to an interface that covers the fields the module reads (see `docs/guidelines/TYPESCRIPT.md`).
Pass the request's `AbortSignal` to every `fetch`. A cancelled or timed out call becomes an `UpstreamTimeoutError`; a network failure an `UpstreamError`:
@@ -53,7 +53,7 @@ Run every query through `execute`, `rows` or `maybeRow` in `repositories/query.t
const found = await rows<AccountRow>('accounts.listForUser', () => db.from('accounts').select(COLUMNS).eq('user_id', userId));
```
-The client gets a plain message (`The database request failed. Try again in a moment.`); the driver's message, which can name tables and constraints, goes to the log only. A query that finds nothing is not an error: `maybeRow` returns `null` and the service decides whether that is a `NotFoundError`.
+The client gets a plain message (`The database request failed. Try again in a moment.`); the driver's message, which can name tables and constraints, goes to the log only. Every Supabase call has a 15 second timeout (`DB_TIMEOUT_MS` in `database/supabase.ts`, the client's `db.timeout`), so a query that hangs becomes a `DatabaseError` well inside the 30 second request deadline instead of holding the request. A query that finds nothing is not an error: `maybeRow` returns `null` and the service decides whether that is a `NotFoundError`.
### Cache Operations (`repositories/analyticsCacheRepository.ts`)
@@ -138,9 +138,13 @@ Log through `lib/logger.ts`: services use `context.log`, middleware and controll
log.error('scheduled post failed', { postId: post.id, ...errorFields(err) });
```
-`errorFields(err)` adds the error's message and cause with URLs removed, never the stack. The error handler already logs every failed request (500 and above at `error`, 4xx at `warn`), and `requestContext` writes one access line per request, so do not log an error you are about to throw. Never call `console` directly.
+`errorFields(err)` adds the error's message and cause through `redactSecrets` (URLs, `Bearer` tokens and token-like parameters removed), never the stack. The error handler already logs every failed request (500 and above at `error`, 4xx at `warn`), and `requestContext` writes one access line per request, so do not log an error you are about to throw. Never call `console` directly.
-Do not log sensitive values: access tokens, API keys, cookies, user emails, Supabase URLs.
+Do not log sensitive values: access tokens, API keys, cookies, user emails, Supabase URLs. Redaction is a safety net for text you do not control, such as a platform's error message; it is not a reason to pass a secret to the logger.
+
+## Detecting and Recovering
+
+`GET /api/health` is the liveness check (the Worker answers) and `GET /api/health/ready` the readiness check (the Supabase secrets are set and the database answers, with `databaseMs`). A missing core secret is a `NOT_CONFIGURED` 503 that names it, for requests, and a `cron run skipped` log line, for cron runs. `docs/workflows/RECOVERY.md` lists what to do when production breaks: find the failing request by its id, pause automation, roll back, and back up the data.
## User-Facing Error Messages
diff --git a/docs/workflows/DEPLOYMENT.md b/docs/workflows/DEPLOYMENT.md
index f760a4b..f11fd45 100644
--- a/docs/workflows/DEPLOYMENT.md
+++ b/docs/workflows/DEPLOYMENT.md
@@ -111,7 +111,7 @@ The CLI has no down migrations. To undo one change on a remote database:
2. Open the matching file in `supabase/rollbacks/` (same name as the migration) and run it in the Supabase SQL editor.
3. Mark the migration as not applied: `npx supabase migration repair --status reverted <version>`, where `<version>` is the 14 digit prefix of the file name.
-Roll back in reverse order when several changes are involved. The four baseline migrations have no rollback, because undoing them would drop tables with data.
+Roll back in reverse order when several changes are involved. `docs/workflows/RECOVERY.md` covers the rest of an incident: finding the failing request, pausing automation, rolling back the Worker and taking backups. The four baseline migrations have no rollback, because undoing them would drop tables with data.
### Existing instances
@@ -191,6 +191,9 @@ Required for `deploy-frontend.yml`, `deploy-backend.yml`, `deploy-site.yml` and
curl -i https://twiligent.ujjwalkrai.workers.dev/api/health
# Expected: 200 with {"status":"ok","timestamp":"2025-..."} and an X-Request-Id header
+curl -i https://twiligent.ujjwalkrai.workers.dev/api/health/ready
+# Expected: 200 with {"status":"ready","databaseMs":...}; 503 NOT_CONFIGURED names a missing Supabase secret
+
curl -i -H "Origin: https://app.twiligent.ujjwal.fyi" https://twiligent.ujjwalkrai.workers.dev/api/health
# Expected: Access-Control-Allow-Origin: https://app.twiligent.ujjwal.fyi (the FRONTEND_URL origin)
```
@@ -253,7 +256,7 @@ For a fresh deployment from this repo:
8. Set all GitHub Actions secrets (see above)
9. Link the Supabase CLI (`npx supabase login`, then `npx supabase link --project-ref <ref>`) and run `npm run db:push` to create the tables, constraints, functions and indexes from `supabase/migrations/`
10. `npm run typecheck`, then `cd backend && npx wrangler deploy` (first manual deploy)
-11. Verify health endpoint
+11. Verify `/api/health` and `/api/health/ready`
12. `npm run build` at the root, then `cd frontend && npx wrangler pages deploy dist --project-name=twiligent`
13. Verify frontend loads
14. Add a YouTube channel via AccountManager to verify the full flow
diff --git a/docs/workflows/RECOVERY.md b/docs/workflows/RECOVERY.md
new file mode 100644
index 0000000..d1de876
--- /dev/null
+++ b/docs/workflows/RECOVERY.md
@@ -0,0 +1,44 @@
+# Recovery
+
+What to do when something breaks in production. Each section names the check that shows the problem and the steps that limit the damage. Try a procedure on a development instance before you need it in production.
+
+## 1. Find out what is failing
+
+| Check | What it tells you |
+|---|---|
+| `curl -i <backend-url>/api/health` | The Worker answers. It never touches the database |
+| `curl -i <backend-url>/api/health/ready` | The Supabase secrets are set and the database answers; `databaseMs` shows how long the database took. A `503 NOT_CONFIGURED` names the missing secret, a `500 DATABASE_ERROR` means the database did not answer |
+| `npx wrangler tail` (from `backend/`) | The Worker's log lines as they happen: one access line per request, every failure with its request id, and the cron runs (`scheduled publish run`, `automation dispatch`, `automation reconcile`, `cron run skipped`) |
+
+A person who reports an error can quote the request id at the end of the error message. Search the tail output for it. Logs are streamed, not stored: turn on Workers Logs for the Worker in the Cloudflare dashboard to keep them.
+
+## 2. Stop the damage
+
+| Problem | Step | Effect |
+|---|---|---|
+| Comment replies go out wrong or too fast | `npx wrangler secret put AUTOMATION_PAUSED` with the value `true` | Every reply is held; comments are still recorded and wait. Remove the secret, or set `false`, to resume |
+| One Instagram account replies badly | Pause the account on the Automations page | Only that account stops |
+| A scheduled post keeps failing | Read its reason in the scheduled posts list on the Publish page | A temporary failure is tried up to three times and a permanent one once; the post is then marked Failed with the reason and is not tried again |
+| A secret leaked | Set a new value with `npx wrangler secret put <NAME>` and revoke the old one where it was issued (Meta, Google, Resend, Supabase) | The Worker uses the new value on its next request |
+
+## 3. Undo a change
+
+| What changed | How to undo it |
+|---|---|
+| The Worker or the app (a merged pull request) | Revert the pull request on GitHub and merge the revert; merging deploys both apps again. For an immediate fix while the revert waits for CI, `npx wrangler rollback` (from `backend/`) puts the previous Worker version live, and the Pages project's deployments list in the Cloudflare dashboard can roll the app back the same way |
+| A database migration | Follow "Rolling Back a Database Change" in `docs/workflows/DEPLOYMENT.md`: code first, then the matching file in `supabase/rollbacks/`, then `npx supabase migration repair` |
+
+A Worker rollback does not change the database. If the newer version applied a migration the older code cannot read, roll the migration back too.
+
+## 4. Back up the data
+
+Supabase backs up projects on paid plans daily. On the Free plan there are no automatic backups, so take your own with the Supabase CLI. It needs Docker running and the project linked (`npx supabase link --project-ref <ref>`):
+
+```bash
+npx supabase db dump --linked -f backup-schema.sql
+npx supabase db dump --linked --data-only --use-copy -f backup-data.sql
+```
+
+Keep the files off this repository: it is public, and the data holds account tokens and personal data. Store them encrypted and outside the machine that runs the project.
+
+A backup only counts once a restore has worked. Load both files into a local database (`npx supabase start`, then `psql` with the connection string it prints) and check the tables hold the rows you expect before you rely on it.
diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.md
index 8b72c9d..f494219 100644
--- a/docs/workflows/TESTING.md
+++ b/docs/workflows/TESTING.md
@@ -32,6 +32,10 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that
| `backend/services/tokenRefreshService.ts` | `backend/tests/services/tokenRefreshService.test.ts` |
| `backend/repositories/accountRepository.ts` | `backend/tests/repositories/accountRepository.test.ts` |
| `backend/middleware/errorHandler.ts` | `backend/tests/middleware/errorHandler.test.ts` |
+| `backend/middleware/clients.ts` | `backend/tests/middleware/clients.test.ts` |
+| `backend/routes/index.ts` (health checks) | `backend/tests/routes/healthRoutes.test.ts` |
+| `backend/database/supabase.ts` | `backend/tests/database/supabase.test.ts` |
+| `backend/lib/redact.ts` | `backend/tests/lib/redact.test.ts` |
| `backend/validators/fields.ts` | `backend/tests/validators/fields.test.ts` |
| `supabase/migrations/*.sql` and `supabase/rollbacks/*.sql` | `backend/tests/database/migrations.test.ts` |
| `frontend/src/lib/accounts.ts` | `frontend/tests/lib/accounts.test.ts` |
@@ -77,7 +81,7 @@ Site tests are in `site/tests/docs/` and `site/tests/lib/`. `chart.test.ts` chec
Test files import the code under test the same way, by relative path with the `.ts` extension (`../../src/lib/accounts.ts`). Type test fakes narrowly: cast a fake once to the interface it stands in for, rather than using `any`, which is a lint error.
-The error contract has its own tests: `tests/middleware/errorHandler.test.ts` (the status and body for each error code, platform messages without URLs, database and unexpected errors hidden from the client, validation and malformed JSON, and unknown routes) and, on the frontend, `tests/lib/apiErrors.test.ts` (the message `request()` throws, with the request id on 5xx). Repository tests (`tests/repositories/*.test.ts`) check the user filter, the `data` merge and the `DatabaseError` for a failed query against the fake Supabase client, and `analyticsCacheRepository.test.ts` the cache keys, versions and failure cooldown. Validator tests (`tests/validators/*.test.ts`) check the field helpers and their messages.
+The error contract has its own tests: `tests/middleware/errorHandler.test.ts` (the status and body for each error code, platform messages without URLs, database and unexpected errors hidden from the client, validation and malformed JSON, and unknown routes) and, on the frontend, `tests/lib/apiErrors.test.ts` (the message `request()` throws, with the request id on 5xx). Repository tests (`tests/repositories/*.test.ts`) check the user filter, the `data` merge and the `DatabaseError` for a failed query against the fake Supabase client, and `analyticsCacheRepository.test.ts` the cache keys, versions and failure cooldown. Validator tests (`tests/validators/*.test.ts`) check the field helpers and their messages. The failure paths around them have tests too: `tests/middleware/clients.test.ts` (a missing Supabase secret answers `NOT_CONFIGURED` naming it), `tests/lib/config.test.ts` (which secrets count as missing), `tests/jobs/scheduled.test.ts` (a cron run without them logs and stops), `tests/database/supabase.test.ts` (a query that never answers is cut off at the timeout, with mocked timers), `tests/routes/healthRoutes.test.ts` (liveness without the database, readiness, and a database failure hidden from the client) and `tests/lib/redact.test.ts` (URLs, Bearer tokens and token parameters removed, ordinary messages unchanged).
Rate limiting has its own tests: `tests/lib/rateLimit/algorithms.test.ts` (each algorithm's decisions, retry and reset times), `tests/lib/rateLimit/limiter.test.ts` (Redis path, memory fallback, circuit breaker, deny cache, eviction) and `tests/middleware/rateLimit.test.ts` (headers, the 429 body, route filters, IPv6 keys). The Lua scripts in `lib/rateLimit/scripts.ts` cannot run in Node; when you change one, change the twin function in `algorithms.ts` the same way and check both against each other in a Lua VM (see `docs/architecture/backend/RATE_LIMITING.md`).
@@ -141,6 +145,9 @@ For any backend change, verify the affected routes directly:
# Health check (should always work); the response carries an X-Request-Id header
curl -i https://twiligent.ujjwalkrai.workers.dev/api/health
+# Readiness: 200 with { "status": "ready", "databaseMs": ..., "timestamp": ... } when the secrets are set and the database answers
+curl -i https://twiligent.ujjwalkrai.workers.dev/api/health/ready
+
# Authenticated route (replace TOKEN with a real Supabase JWT)
curl -H "Authorization: Bearer TOKEN" https://twiligent.ujjwalkrai.workers.dev/api/accounts
@@ -194,6 +201,7 @@ Open the app in a browser. For each changed area, test:
- [ ] With the Worker on `localhost`, the Vite dev server on port 5173 can call it
- [ ] A failing request returns `{ success: false, code, message, requestId }` with the status for its code, and `npx wrangler tail` shows a JSON log line with the same request id
- [ ] A 5xx error toast in the app ends with `(request <id>)`
+- [ ] `.../api/health/ready` answers 200 with `databaseMs`; on a local Worker with `SUPABASE_SERVICE_KEY` removed from `.dev.vars`, every route answers `503 NOT_CONFIGURED` naming the secret
**Rate limiting (if changed):**
- [ ] `curl -i -H "CF-Connecting-IP: 203.0.113.1" http://localhost:8787/api/health` shows `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset`
diff --git a/site/content/docs/self-host/checklist.mdx b/site/content/docs/self-host/checklist.mdx
index b831151..f6a5d21 100644
--- a/site/content/docs/self-host/checklist.mdx
+++ b/site/content/docs/self-host/checklist.mdx
@@ -3,6 +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. |
+| Backend is ready | `/api/health/ready` returns status ready. If it names a missing secret, set it and deploy again. |
| 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. |
diff --git a/site/content/docs/self-host/deploy-backend.mdx b/site/content/docs/self-host/deploy-backend.mdx
index bd78cf7..673e3d6 100644
--- a/site/content/docs/self-host/deploy-backend.mdx
+++ b/site/content/docs/self-host/deploy-backend.mdx
@@ -47,7 +47,7 @@ If you use Redis, also add `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKE
</Step>
<Step title="Check it is running">
-Open `https://your-backend-url/api/health`. It should return `{"status":"ok"}` with a timestamp. Every response also carries an `X-Request-Id` header; server error messages in the app show the same id, and you can find its log line with `npx wrangler tail`.
+Open `https://your-backend-url/api/health`. It should return `{"status":"ok"}` with a timestamp. Then open `/api/health/ready`, which also checks the database: it should return `{"status":"ready"}`. If a Supabase secret is missing, it names the secret to set. Every response also carries an `X-Request-Id` header; server error messages in the app show the same id, and you can find its log line with `npx wrangler tail`.
</Step>
</Steps>