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 layered backend everywhere
spacesdrive00f59e964453
diff --git a/README.md b/README.mdindex 991fb43..144c7ca 100644--- a/README.md+++ b/README.md@@ -271,7 +271,7 @@ Add a dependency to the app that uses it: `npm install <package> --workspace bacThe whole project is TypeScript in `strict` mode. Nothing is compiled ahead of time: Wrangler and Vite strip the types while bundling, and Node strips them when it runs the tests and `scripts/publish-scheduled.ts`. None of them checks types, so run `npm run typecheck` before you commit; CI runs it on every pull request and before every deploy. The API request and response types live once in `shared/types/` and are used by both the backend and the frontend. See `docs/guidelines/TYPESCRIPT.md`.-Tests live outside the source folders, in `backend/tests/` and `frontend/tests/`, and mirror the source tree: the test for `backend/services/youtube.ts` is `backend/tests/services/youtube.test.ts`, and the test for `frontend/src/lib/accounts.ts` is `frontend/tests/lib/accounts.test.ts`. Backend fixtures and golden snapshots are in `backend/tests/fixtures/`.+Tests live outside the source folders, in `backend/tests/` and `frontend/tests/`, and mirror the source tree: the test for `backend/services/youtube/youtubeChannels.ts` is `backend/tests/services/youtube/youtubeChannels.test.ts`, and the test for `frontend/src/lib/accounts.ts` is `frontend/tests/lib/accounts.test.ts`. Backend fixtures and golden snapshots are in `backend/tests/fixtures/`.ESLint (with `typescript-eslint`), Prettier and EditorConfig are configured once at the root, and the shared compiler settings are in `tsconfig.base.json`. The existing code has not been reformatted in bulk, so run `npm run format` only when you mean to reformat.@@ -300,6 +300,8 @@ UPSTASH_REDIS_REST_TOKEN=...`UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` are optional. The app works without Redis - analytics are fetched live on every request with caching disabled.+`FRONTEND_URL` is also the only browser origin the API accepts. To serve the app from more than one address, list the others in the optional `ALLOWED_ORIGINS` (comma-separated, for example `ALLOWED_ORIGINS=https://twiligent.pages.dev`). A Worker running on `localhost` also accepts the Vite dev server on port 5173.+### Frontend environment variables (`frontend/.env.local`)```@@ -327,8 +329,9 @@ npx wrangler secret put CLOUDINARY_CLOUD_NAMEnpx wrangler secret put CLOUDINARY_UPLOAD_PRESETnpx wrangler secret put BACKEND_URLnpx wrangler secret put FRONTEND_URL-npx wrangler secret put UPSTASH_REDIS_REST_URL-npx wrangler secret put UPSTASH_REDIS_REST_TOKEN+npx wrangler secret put ALLOWED_ORIGINS # optional+npx wrangler secret put UPSTASH_REDIS_REST_URL # optional+npx wrangler secret put UPSTASH_REDIS_REST_TOKEN # optional```### Getting API credentials@@ -411,10 +414,10 @@ flowchart TD**Request lifecycle:**1. The browser sends a request with a Supabase JWT in the `Authorization: Bearer` header-2. The Cloudflare Worker verifies the JWT and extracts the user ID-3. Route handlers query Supabase using the verified user ID as an isolation filter+2. The Cloudflare Worker checks the origin (CORS), gives the request an id, applies rate limits and verifies the JWT to get the user ID+3. A route table hands the request to a controller, which calls a service; the service reads and writes Supabase through repositories that filter by the verified user ID4. Frequently accessed data (analytics) is read from Upstash Redis if available; otherwise fetched live from the platform APIs and cached-5. Responses are returned as JSON; access tokens are always stripped before leaving the Worker+5. Responses are returned as JSON with an `X-Request-Id` header; access tokens are always stripped before leaving the Worker, and every failure has the same body: `{ success: false, code, message, requestId }`**Cron lifecycle:**@@ -437,32 +440,36 @@ twiligent/│ └── publish-scheduled.yml # Scheduled post fallback (every 15 minutes, Node 24)│├── backend/+│ ├── app.ts # createApp(): the ordered middleware pipeline and route groups+│ ├── server.ts # Worker export (fetch + scheduled)+│ ├── container.ts # Composition root: builds repositories and services per request+│ ├── middleware/ # cors, requestContext, securityHeaders, clients, rateLimit, auth, validate, errorHandler+│ ├── routes/ # One route table per feature (<feature>Routes.ts) and index.ts (public and protected)+│ ├── controllers/ # HTTP only: read input, call one service method, build the response+│ ├── validators/ # Request body and query parsers+│ ├── services/+│ │ ├── *Service.ts # Feature services: business rules, no Hono types+│ │ ├── scheduledPublisher.ts # Publishes due scheduled posts (cron and manual trigger)+│ │ ├── youtube/ # YouTube Data API v3 client and analytics+│ │ ├── instagram/ # Instagram Graph API client, OAuth, publishing and analytics+│ │ └── reddit/ # Reddit public JSON API client and analytics+│ ├── repositories/ # All Supabase queries and the Redis analytics cache+│ ├── database/ # Supabase and Upstash Redis client factories+│ ├── jobs/+│ │ └── scheduled.ts # Cron entry point: publish due posts, refresh Instagram tokens│ ├── lib/-│ │ ├── db.ts # All Supabase query functions (single source)-│ │ ├── cache.ts # Redis cache helpers (silent fail on error)-│ │ ├── redis.ts # Upstash Redis client factory+│ │ ├── errors.ts # Typed errors; the error handler maps each code to a status+│ │ ├── logger.ts # Structured JSON log lines+│ │ ├── config.ts # Cleaned Worker settings and allowed CORS origins│ │ ├── safeAccount.ts # Strips tokens and cookies from accounts in responses-│ │ ├── rateLimit/ # Rate limit rules, algorithms and Lua scripts-│ │ └── supabase.ts # Supabase client factory-│ ├── middleware/-│ │ ├── auth.ts # requireAuth: JWT verification, sets userId-│ │ └── rateLimit.ts # Per-IP and per-user rate limits-│ ├── routes/-│ │ ├── accounts.ts # Add, remove, and refresh accounts-│ │ ├── analytics.ts # YouTube and Instagram analytics-│ │ ├── publishing.ts # Instagram Graph API publish flow-│ │ ├── scheduledPosts.ts # CRUD for scheduled post queue-│ │ ├── instagramAuth.ts # Instagram OAuth flow-│ │ ├── settings.ts # User settings (GitHub repository for setup links)-│ │ └── keys.ts # API key presence check-│ ├── services/-│ │ ├── youtube.ts # YouTube Data API v3 client-│ │ └── instagram.ts # Instagram Graph API client+│ │ ├── oauthState.ts # HMAC-signed Instagram OAuth state+│ │ ├── analyticsMath.ts # Shared analytics formulas+│ │ └── rateLimit/ # Rate limit rules, algorithms and Lua scripts│ ├── types/│ │ ├── env.ts # Env: Worker secrets and bindings-│ │ └── app.ts # AppEnv, AppContext: Hono context typing-│ ├── tests/ # Node tests (*.test.ts) mirroring lib/, middleware/, routes/, services/, utils/; fixtures/ holds fakes and golden snapshots-│ ├── server.ts # Hono app + Worker export (fetch + scheduled)+│ │ ├── app.ts # AppEnv, AppContext: Hono context typing+│ │ └── context.ts # RequestContext: request id, signal and logger for services+│ ├── tests/ # Node tests (*.test.ts) mirroring lib/, middleware/, repositories/, routes/, services/, validators/; fixtures/ holds fakes and golden snapshots│ ├── wrangler.toml # Cloudflare Worker config (main = "server.ts") and cron triggers│ ├── tsconfig.json # Worker type check (Workers types, no DOM or Node)│ └── package.json # Backend workspace: hono, supabase-js, upstash redis, wrangler, workers-typesdiff --git a/ROADMAP.md b/ROADMAP.mdindex 3176b46..945b3dd 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -106,7 +106,7 @@ YouTube's upload API requires OAuth with the `youtube.upload` scope. The archite### Multi-User Teams-Each Supabase auth user is completely isolated. A team feature would let several users share the same accounts. Requires a `teams` table, a `team_members` join table, and query changes across `lib/db`.+Each Supabase auth user is completely isolated. A team feature would let several users share the same accounts. Requires a `teams` table, a `team_members` join table, and query changes across the repositories in `backend/repositories/`.### Mobile App@@ -117,7 +117,7 @@ React Native app using the same Cloudflare Worker backend.## Known Issues / Tech Debt- `wrangler.toml` has no `vars` section for non-secret configuration - any non-sensitive config currently requires a redeploy to change.-- The scheduled publishers (`backend/utils/scheduler` and `scripts/publish-scheduled`) publish due posts one after another in a single run. A large batch due at the same moment can exceed the Worker's or the Actions job's time limit; the rest wait for the next run.+- The scheduled publishers (`backend/services/scheduledPublisher` and `scripts/publish-scheduled`) publish due posts one after another in a single run. A large batch due at the same moment can exceed the Worker's or the Actions job's time limit; the rest wait for the next run.- Rate limits are counted per Worker isolate when Redis is not configured, which is looser than one global count (see `docs/architecture/backend/RATE_LIMITING.md`).- The project stays on TypeScript 6.0 until `typescript-eslint` supports TypeScript 7.- No end-to-end tests; see `docs/workflows/TESTING.md` for the planned Playwright coverage.diff --git a/backend/.env.example b/backend/.env.exampleindex c4b1db5..d95f7d1 100644--- a/backend/.env.example+++ b/backend/.env.example@@ -28,6 +28,9 @@ INSTAGRAM_APP_ID=your-instagram-app-idINSTAGRAM_APP_SECRET=your-instagram-app-secret# ── URLs ──────────────────────────────────────────────────────────────────────-# Used for Instagram OAuth redirect. Update these for production.+# Used for the Instagram OAuth redirect and as the allowed CORS origin. Update these for production.BACKEND_URL=http://localhost:8787FRONTEND_URL=http://localhost:5173+# Browser origins allowed to call the API (CORS): FRONTEND_URL plus this optional comma-separated list.+# A Worker running on localhost also allows the Vite dev server.+# ALLOWED_ORIGINS=https://preview.example.pages.devdiff --git a/backend/database/redis.ts b/backend/database/redis.tsindex a7b1b46..2d476c5 100644--- a/backend/database/redis.ts+++ b/backend/database/redis.ts@@ -11,7 +11,7 @@ function credentials(env: Env): { url: string; token: string } | null {return { url, token };}-// one quick retry instead of the default five (about 4 seconds); lib/cache.ts then skips Redis for a while+// one quick retry instead of the default five (about 4 seconds); the cache repository then skips Redis for a whileexport function getRedis(env: Env): Redis | null {const config = credentials(env);if (!config) return null;diff --git a/claude.md b/claude.mdindex b2c30ac..a6c236a 100644--- a/claude.md+++ b/claude.md@@ -48,7 +48,7 @@ scripts/ publish-scheduled.ts, run by GitHub Actions with no depend- `npm install` at the root installs both apps. Never run `npm install` inside `backend/` or `frontend/`, and never commit a lockfile there.- `npm run dev` starts the Worker (port 8787) and Vite (port 5173) together; `npm run typecheck`, `npm test`, `npm run lint` and `npm run build` cover the whole repo.- Add a dependency to the app that uses it: `npm install <pkg> --workspace backend` or `--workspace frontend`. Only shared dev tooling belongs in the root `package.json`.-- Tests never live next to source files. A test for `backend/services/youtube.ts` is `backend/tests/services/youtube.test.ts`; a test for `frontend/src/lib/accounts.ts` is `frontend/tests/lib/accounts.test.ts`.+- Tests never live next to source files. A test for `backend/services/accountService.ts` is `backend/tests/services/accountService.test.ts`; a test for `frontend/src/lib/accounts.ts` is `frontend/tests/lib/accounts.test.ts`.---diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.mdindex b7bec44..3035b7c 100644--- a/docs/architecture/OVERVIEW.md+++ b/docs/architecture/OVERVIEW.md@@ -4,38 +4,42 @@```┌─────────────────────────────────────────────────────────────────┐-│ Browser (User) │+│ Browser (User) ││ React SPA - Cloudflare Pages │-│ https://twiligent.ujjwal.fyi │+│ https://twiligent.ujjwal.fyi │└────────────────────────┬────────────────────────────────────────┘│ HTTPS + Bearer JWT▼┌─────────────────────────────────────────────────────────────────┐-│ Cloudflare Worker - "twiligent" │+│ Cloudflare Worker - "twiligent" ││ https://twiligent.ujjwalkrai.workers.dev/api │-│ │-│ Hono v4 app │-│ ├── Global middleware: CORS, clients, per-IP rate limit │-│ ├── Public: GET /api/health, GET /api/auth/instagram/callback │-│ └── Protected (/api/*): requireAuth -> rate limits -> routes │-│ │-│ Cron handlers (wrangler.toml triggers): │-│ ├── */15 * * * * -> processScheduledPosts() │-│ └── 0 0 * * * -> autoRefreshInstagramTokens() │+│ │+│ 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 │+│ ├── Protected (/api/*): requireAuth -> rate limits │+│ │ -> route table -> controller -> service -> repository │+│ └── Errors: errorHandler -> { success, code, message, ... } │+│ │+│ Cron handlers (wrangler.toml triggers, jobs/scheduled.ts): │+│ ├── */15 * * * * -> scheduledPublisher.publishDue() │+│ └── 0 0 * * * -> tokenRefresh.refreshExpiringInstagram... │└──────┬──────────┬──────────────┬────────────────────────────────┘│ │ │▼ ▼ ▼┌──────────┐ ┌─────────┐ ┌──────────────────────────────────────┐-│ Supabase │ │ Upstash │ │ External APIs │-│ Postgres │ │ Redis │ │ ├── YouTube Data API v3 │-│ │ │ (cache) │ │ ├── Instagram Graph API v25 │-│ │ │ (cache) │ │ ├── Reddit Public JSON API │-│ tables: │ │ │ │ └── Cloudinary Upload API │-│ accounts │ │ keys: │ └──────────────────────────────────────┘-│ settings │ │ videos: │-│ sched_ │ │ {u}:{a} │-│ posts │ │ ig:{u}: │-│ │ │ {a} │+│ Supabase │ │ Upstash │ │ External APIs │+│ Postgres │ │ Redis │ │ ├── YouTube Data API v3 │+│ │ │ (cache, │ │ ├── Instagram Graph API v25 │+│ tables: │ │ rate │ │ ├── Reddit Public JSON API │+│ accounts │ │ limits)│ │ └── Cloudinary Upload API │+│ settings │ │ │ └──────────────────────────────────────┘+│ sched_ │ │ keys: │+│ posts │ │ videos: │+│ tracked_ │ │ ig: │+│ posts │ │ reddit: │+│ │ │ ││ auth: │ │ ││ users │ │ optional│└──────────┘ └─────────┘@@ -54,24 +58,31 @@## Request Lifecycle (Protected Route)+The full pipeline, with the job of each layer, is in `docs/architecture/backend/REQUEST_PIPELINE.md`.+```Browser-> fetch(`${VITE_API_URL}/accounts`, { Authorization: Bearer <jwt> })↓Cloudflare Worker edge node (nearest to user)- -> CORS middleware (checks origin)- -> Client injection middleware (creates Supabase + Redis clients from env)+ -> CORS middleware (allows FRONTEND_URL and ALLOWED_ORIGINS only)+ -> request id (X-Request-Id), cancellation signal, access log line+ -> security headers+ -> client injection middleware (creates Supabase + Redis clients from env)-> rateLimit(ip) middleware (per client IP; 429 when over the limit)-> requireAuth middleware-> extracts Bearer token from Authorization header-> supabaseAuth.auth.getUser(token) -> Supabase validates JWT- -> sets c.userId, c.userEmail on Hono context+ -> sets userId, userEmail on the Hono context (401 otherwise)-> rateLimit(user), and rateLimit(quota) or rateLimit(publish) on the routes they cover- -> route handler (e.g., accounts router)- -> db.getAccounts(supabase, userId) [lib/db.ts]- -> supabase.from('accounts').select(...).eq('user_id', userId)- -> normalizes rows+ -> route table (routes/accountRoutes.ts) -> validator, if the route takes input+ -> controller (accountController.listAccounts)+ -> servicesFor(c).accounts.list(userId) [services/accountService.ts]+ -> accounts.listForUser(userId) [repositories/accountRepository.ts]+ -> supabase.from('accounts').select(...).eq('user_id', userId)+ -> safeAccount() on every account-> returns JSON response+ -> a thrown error at any step -> errorHandler -> { success: false, code, message, requestId }```## Cron Lifecycle@@ -79,17 +90,18 @@ Cloudflare Worker edge node (nearest to user)```Cloudflare scheduler fires cron trigger-> Worker.scheduled(event, env, ctx)- -> getSupabase(env) [creates service-role client]- -> if event.cron === '*/15 * * * *':- ctx.waitUntil(processScheduledPosts(supabase))- -> db.getDuePosts(supabase) [no userId filter - scans all users]- -> for each post: publishToInstagram(post, account)- -> db.updatePost(supabase, id, { status: 'published' })- -> if event.cron === '0 0 * * *':- ctx.waitUntil(autoRefreshInstagramTokens(supabase))- -> db.getAccounts(supabase) [all users, platform='instagram']- -> for each expiring token: igFetch refresh endpoint- -> db.updateAccount(supabase, id, { accessToken: newToken })+ -> ctx.waitUntil(runScheduledJob(event.cron, env)) [jobs/scheduled.ts]+ -> createServices(service-role Supabase, Redis, config, cron context)+ -> if cron === '*/15 * * * *':+ scheduledPublisher.publishDue()+ -> posts.listDue() [no userId filter - scans all users]+ -> for each post: posts.claim(id), then create, wait for and publish the container+ -> posts.updateById(id, { status: 'published' })+ -> if cron === '0 0 * * *':+ tokenRefresh.refreshExpiringInstagramTokens()+ -> accounts.listAll() [all users, Instagram accounts with a token]+ -> for each expiring token: refreshLongLivedToken()+ -> accounts.updateById(id, { accessToken, tokenExpiresAt })```## Data Storage Strategy@@ -117,16 +129,18 @@ 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 is wrapped in try/catch and 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. 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.-4. **`safeAccount()` is the only place access tokens are stripped.** Any route that returns account data must pass through this function before responding.+4. **`safeAccount()` is the only place access tokens are stripped.** Repositories return full accounts; every account in a response passes through this function first.-5. **`db.ts` is the only file that contains Supabase queries.** Route handlers import and call db functions - they never call `supabase.from()` directly.+5. **Repositories are the only files that contain Supabase queries.** Each table has one repository in `backend/repositories/`; services call its methods and never call `supabase.from()` directly. User-scoped methods end in `ForUser` and always filter by the verified user id.6. **Every `/api` request is rate limited.** Per IP before authentication, per user after it, and tighter on routes that spend platform API quota. See `docs/architecture/backend/RATE_LIMITING.md`.7. **`api.ts` is the only file that calls `fetch()` in the frontend.** Components call `api.methodName()` - they never construct fetch calls.-8. **The API contract is typed once, in `shared/types/`.** Routes check every response against it with `satisfies`, and `api.ts` methods return the same types, so `npm run typecheck` catches a shape change on both sides. CI runs the type check before every deploy, because Wrangler and Vite strip types without checking them. See `docs/guidelines/TYPESCRIPT.md`.+8. **The API contract is typed once, in `shared/types/`.** Controllers check every response against it with `satisfies`, and `api.ts` methods return the same types, so `npm run typecheck` catches a shape change on both sides. CI runs the type check before every deploy, because Wrangler and Vite strip types without checking them. See `docs/guidelines/TYPESCRIPT.md`.++9. **Every failure has one shape.** Services throw typed errors from `backend/lib/errors.ts`, and `middleware/errorHandler.ts` answers each with a 4xx or 5xx status and `{ success: false, code, message, requestId }`. A 2xx response is always a success. See `docs/architecture/backend/REQUEST_PIPELINE.md`.diff --git a/docs/architecture/backend/CACHING.md b/docs/architecture/backend/CACHING.mdindex 7dedd88..6c4ab24 100644--- a/docs/architecture/backend/CACHING.md+++ b/docs/architecture/backend/CACHING.md@@ -2,40 +2,46 @@## Overview-Caching is implemented via Upstash Redis (REST API) using the `@upstash/redis` SDK. It is **entirely optional** - if `UPSTASH_REDIS_REST_URL` is not set, `getRedis()` returns `null` and all cache functions in `lib/cache.ts` silently no-op.+Caching is implemented via Upstash Redis (REST API) using the `@upstash/redis` SDK. It is **entirely optional** - if `UPSTASH_REDIS_REST_URL` is not set, `getRedis()` in `database/redis.ts` returns `null` and every method of the analytics cache repository silently no-ops.-## Cache Layer: `backend/lib/cache.ts`+## Cache Layer: `backend/repositories/analyticsCacheRepository.ts`-All cache operations follow this contract:-- Accept `redis` (`Redis | null`) as the first argument-- If `redis` is `null`, return immediately (no-op)-- Wrap all `redis` calls in `try/catch` - a Redis failure must never break the main request-- Return the cached shape from `shared/types` (`VideosCacheData`, `IGCacheData`, `RedditCacheData`), or `null` on a miss+The cache is a repository like the database tables. `createAnalyticsCacheRepository(redis)` is built in `container.ts` and handed to the services that read or warm analytics (`accounts`, `youtubeAnalytics`, `instagramAnalytics`, `redditAnalytics`, `overview`). No other code touches Redis keys for analytics.-The private helpers `readKey<T>()`, `writeKey()` and `deleteKey()` implement the null check, the `try/catch` and the TTL once; every exported function goes through them:+The repository follows this contract:+- Every method is a no-op without Redis: reads return `null`, writes and deletes return+- Every Redis call is wrapped in `try/catch` - a Redis failure must never break the main request+- Reads return the cached shape from `shared/types` (`VideosCacheData`, `IGCacheData`, `RedditCacheData`), or `null` on a miss+- `enabled` is `false` without Redis, so the Overview knows not to start warming++The private helpers `readKey<T>()`, `writeKey()` and `deleteKey()` implement the availability check, the `try/catch` and the TTL once; every method goes through them:```ts-async function readKey<T>(redis: Redis | null, key: string): Promise<T | null> {- if (!redis) return null;+async function readKey<T>(key: string): Promise<T | null> {+ if (!redis || !available()) return null;try {return await redis.get<T>(key);} catch {// a cache miss falls back to the live api+ markDown();return null;}}--export async function getRedditCache(redis: Redis | null, userId: string, accountId: string): Promise<RedditCacheData | null> {- return (await readKey<RedditCacheData>(redis, `reddit:${userId}:${accountId}`)) || null;-}```+| Method | Key |+|---|---|+| `getVideos(userId, accountId)`, `setVideos(userId, accountId, data)` | `videos:{userId}:{accountId}` |+| `getInstagramMedia(userId, accountId)`, `setInstagramMedia(userId, accountId, data)` | `ig:{userId}:{accountId}` |+| `getReddit(userId, accountId)`, `setReddit(userId, accountId, data)` | `reddit:{userId}:{accountId}` |+| `deleteAllForAccount(userId, accountId)` | All three keys for the account |+## When Redis FailsA Redis outage must make the app slower to refresh, never slower to respond:-- **Short timeout.** `getRedis()` in `lib/redis.ts` gives every call a 3 second timeout and one retry after 100 ms, instead of the SDK default of five retries with backoff (about 4 seconds per call).-- **Cooldown.** When a read, write or delete fails, `lib/cache.ts` skips Redis in that isolate for 30 seconds (`CACHE_COOLDOWN_MS`): reads return a miss and writes are dropped. An outage therefore costs one timeout per isolate every 30 seconds, not one per cache call. `resetCacheState()` clears the cooldown in tests.+- **Short timeout.** `getRedis()` in `database/redis.ts` gives every call a 3 second timeout and one retry after 100 ms, instead of the SDK default of five retries with backoff (about 4 seconds per call).+- **Cooldown.** When a read, write or delete fails, `analyticsCacheRepository.ts` skips Redis in that isolate for 30 seconds (`CACHE_COOLDOWN_MS`): reads return a miss and writes are dropped. An outage therefore costs one timeout per isolate every 30 seconds, not one per cache call. `resetCacheState()` clears the cooldown in tests.The rate limiter uses its own client with a 1 second timeout and no retries; see `RATE_LIMITING.md`.@@ -45,61 +51,58 @@ The rate limiter uses its own client with a 1 second timeout and no retries; see| Key pattern | Content | Set when | Invalidated when ||---|---|---|---|-| `videos:{userId}:{accountId}` | Array of YouTube video objects with stats | `GET /api/accounts/:id/analytics` succeeds | `DELETE /api/accounts/:id` |+| `videos:{userId}:{accountId}` | `{ videos, fetchedAt, version }` - YouTube video objects with stats | `GET /api/accounts/:id/analytics` succeeds, `GET /api/accounts/:id/videos` fetches live on a miss, or the Overview warms it | `DELETE /api/accounts/:id`, or a `version` mismatch || `ig:{userId}:{accountId}` | `{ media, fetchedAt, version }` - normalized Instagram media (see `normalizeInstagramMedia()`) | `GET /api/accounts/:id/ig-analytics` or `ig-media` succeeds, or the Overview warms it | `DELETE /api/accounts/:id`, or a `version` mismatch |-| `reddit:{userId}:{accountId}` | Object `{ profile, analytics, posts }` for Reddit account | `GET /api/accounts/:id/reddit-analytics` succeeds | `DELETE /api/accounts/:id` |+| `reddit:{userId}:{accountId}` | Object `{ profile, analytics, posts }` for Reddit account | `GET /api/accounts/:id/reddit-analytics` succeeds, or the Overview warms it | `DELETE /api/accounts/:id` |Rate 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`.-**Note:** Instagram OAuth state is an HMAC-signed token and does not use Redis. The unused Redis-backed `oauth_ig:` helpers were removed.+**Note:** Instagram OAuth state is an HMAC-signed token and does not use Redis.## Cache Versioning-`ig:` entries carry a `version` field written by `setIGCache()`. `getIGCache()` treats an entry whose `version` differs from `IG_CACHE_VERSION` in `lib/cache.ts` as a miss, so the next request refetches from Instagram and overwrites it. Bump `IG_CACHE_VERSION` whenever the cached media shape changes. Version 2 added `contentType` and `viewCount`.+`ig:` entries carry a `version` field written by `setInstagramMedia()`. `getInstagramMedia()` treats an entry whose `version` differs from `IG_CACHE_VERSION` in `analyticsCacheRepository.ts` as a miss, so the next request refetches from Instagram and overwrites it. Bump `IG_CACHE_VERSION` whenever the cached media shape changes. Version 2 added `contentType` and `viewCount`.## Cache TTL-`videos:`, `ig:` and `reddit:` keys expire after 6 hours (`ANALYTICS_TTL_SECONDS` in `lib/cache.ts`), so counts refetch rather than going stale. They are also removed when the account is deleted.+`videos:`, `ig:` and `reddit:` keys expire after 6 hours (`ANALYTICS_TTL_SECONDS` in `analyticsCacheRepository.ts`), so counts refetch rather than going stale. They are also removed when the account is deleted.`videos:` entries carry a `version` field like `ig:` entries (`VIDEOS_CACHE_VERSION`). Version 2 stores `likeCount` and `commentCount` as `null` when YouTube hides them (the owner hid likes, or comments are off), instead of `0`; the UI shows those as "Hidden".## Overview warming-`GET /api/overview` returns `{ cacheWarmed, syncing }` per account. When an account has no cache entry it starts a background fetch with `waitUntil` (YouTube, Instagram and Reddit) and returns `syncing: true` only if that fetch actually started. Without Redis, an API key, a token or a cookie it returns `syncing: false`, so the client never waits on something that cannot load. While any account is syncing the client polls again up to three times. Each poll waits 4, 8 and then 16 seconds after the previous response (about 4, 12 and 28 seconds after the first load), then polling stops.+`GET /api/overview` returns `{ cacheWarmed, syncing }` per account. When an account has no cache entry, `overviewService.summary()` starts a background fetch (YouTube, Instagram and Reddit) and the controller keeps it alive with `waitUntil`; the response says `syncing: true` only if that fetch actually started. Without Redis, an API key, a token or a cookie it returns `syncing: false`, so the client never waits on something that cannot load. While any account is syncing the client polls again up to three times. Each poll waits 4, 8 and then 16 seconds after the previous response (about 4, 12 and 28 seconds after the first load), then polling stops.-## Cache Usage in Routes+## Cache Usage in Services-The analytics routes use this pattern:+Services read the cache first and fall back to the live API on a miss, then write what they fetched:```ts-// GET /api/accounts/:id/analytics-const cached = await getVideosCache(redis, userId, accountId);-if (cached) return c.json(cached);--// fetch fresh data from YouTube API...-const result = { /* computed analytics */ };--await setVideosCache(redis, userId, accountId, result);-return c.json(result);+// YouTubeAnalyticsService.channelVideos: served from the cache when it has the channel, without spending quota+async channelVideos(userId, accountId) {+ const cached = await cache.getVideos(userId, accountId);+ if (cached?.videos) return { videos: cached.videos, fetchedAt: cached.fetchedAt };+ const apiKey = youtubeKey();+ const account = await findChannel(userId, accountId);+ return fetchAndCacheVideos(userId, accountId, account.uploadsPlaylistId, apiKey);+},```## Adding New Cache Keys-1. Add getter, setter, and deleter functions to `backend/lib/cache.ts`+1. Add the getter and setter to `AnalyticsCacheRepository` in `backend/repositories/analyticsCacheRepository.ts`, built on `readKey`, `writeKey` and `deleteKey`2. Follow the existing naming convention: `{entity}:{userId}:{accountId}`-3. Always guard with `if (!redis) return null/undefined`-4. Always wrap in `try/catch`-5. Call the deleter in the account deletion handler if the cache is account-specific+3. Never call Redis outside those helpers, so the availability check, the `try/catch` and the cooldown always apply+4. Add the key to `deleteAllForAccount()` if the cache is account-specific+5. Add a test to `backend/tests/repositories/analyticsCacheRepository.test.ts`6. Update this document## HMAC OAuth State (Not Redis)-The `createOAuthState()` and `verifyOAuthState()` functions live in `lib/oauthState.ts`; `services/instagramOAuth.ts` and `routes/instagramAuth.ts` import them from there directly, and `cache.ts` still re-exports them. They are **not** Redis-based. They use `crypto.subtle.sign()` (native Web Crypto API in Workers) to create self-verifying state tokens. Redis is not involved.+The `createOAuthState()` and `verifyOAuthState()` functions live in `lib/oauthState.ts`; `services/instagram/instagramOAuth.ts` and `services/instagramConnectService.ts` import them. They are **not** Redis-based. They use `crypto.subtle.sign()` (native Web Crypto API in Workers) to create self-verifying state tokens.```State format: base64url(userId:timestamp).base64url(HMAC-SHA256-signature)Expiry: 10 minutes (checked by comparing embedded timestamp to Date.now())Secret: INSTAGRAM_APP_SECRET```--They started in `cache.ts` as Redis-backed helpers and were migrated to HMAC, then moved to their own module. `cache.ts` still re-exports them, but new code imports them from `lib/oauthState.ts`.diff --git a/docs/architecture/backend/CRON.md b/docs/architecture/backend/CRON.mdindex 3ba978b..b1478f3 100644--- a/docs/architecture/backend/CRON.md+++ b/docs/architecture/backend/CRON.md@@ -7,38 +7,63 @@crons = ["*/15 * * * *", "0 0 * * *"]```-Both cron triggers invoke the `scheduled` export from `backend/server.ts`.+Both cron triggers invoke the `scheduled` export from `backend/server.ts`, which hands the cron expression to `runScheduledJob(cron, env)` in `backend/jobs/scheduled.ts`. The expressions are constants there (`PUBLISH_DUE_POSTS_CRON`, `REFRESH_TOKENS_CRON`) and must match `wrangler.toml` character for character.++## The Cron Entry Point (`backend/jobs/scheduled.ts`)++A cron run uses the same services as the API, built from the Worker env instead of a request:++```ts+export async function runScheduledJob(cron: string, env: Env): Promise<void> {+ const context = cronContext(cron);+ const services = createServices({ supabase: getSupabase(env), redis: getRedis(env) }, readConfig(env), context);++ if (cron === PUBLISH_DUE_POSTS_CRON) {+ const run = await services.scheduledPublisher.publishDue();+ context.log.info('scheduled publish run', { processed: run.processed, failed: run.errors.length });+ } else if (cron === REFRESH_TOKENS_CRON) {+ await services.tokenRefresh.refreshExpiringInstagramTokens();+ } else {+ context.log.warn('no job for this cron', { cron });+ }+}+```++`cronContext(cron)` builds the `RequestContext` a request would have: a `cron-<uuid>` request id, a 14 minute deadline signal (under the Worker's 15 minute limit for scheduled events) and a logger bound to the request id and the cron expression. Every log line of the run carries that id.## Cron Handlers### `*/15 * * * *` - Instagram Scheduled Post Publisher-**Function:** `processScheduledPosts(supabase)` in `backend/utils/scheduler.ts`+**Function:** `scheduledPublisher.publishDue()` in `backend/services/scheduledPublisher.ts`**What it does:**-1. Queries `scheduled_posts` where `status = 'pending'` and `scheduled_at <= now()`+1. Lists due posts with `scheduledPostRepository.listDue()` (`status = 'pending'` and `scheduled_at <= now()`)2. For each due post:- - Claims it with `claimPost()` (pending to `'publishing'`); a post another scheduler already claimed is skipped- - Fetches the associated account from `accounts` table and builds the container parameters with `buildMediaParams()`+ - Claims it with `scheduledPostRepository.claim()` (pending to `'publishing'`); a post another scheduler already claimed is skipped+ - Loads the account with `accountRepository.findById()`, checks it with `publishableAccount()` and builds the container parameters with `buildMediaParams()`- Creates the Graph API container, waits for it (Reels and Stories poll the status every 3 seconds, up to 60 times; other media wait 2 seconds), then publishes it- On success: sets status to `'published'`, stores `publishedMediaId` and `publishedAt` in `data`- - On failure: sets status to `'failed'`, stores `error` message in `data`+ - On failure: sets status to `'failed'`, stores `error` message in `data`, and logs the failure with the post id+3. Returns `{ processed, errors }`; the job logs the totals-`backend/tests/utils/scheduler.test.ts` pins this sequence, the log lines and the stored results against a fake Supabase client and Graph API (fixtures and golden snapshots in `backend/tests/fixtures/`).+`backend/tests/services/scheduledPublisher.test.ts` pins this sequence, the log lines and the stored results against a fake Supabase client and Graph API (fixtures and golden snapshots in `backend/tests/fixtures/`).-**No userId filter** - the scheduler operates across all users. It uses the service-role Supabase client.+**No userId filter** - the publisher operates across all users through the cron-only repository methods (`listDue`, `claim`, `findById`, `updateById`). It uses the service-role Supabase client. The manual trigger (`GET` or `POST /api/process-scheduled`) runs the same `publishDue()`.**Concurrency safety:** The `'publishing'` status acts as a mutex. If the Worker cron and GitHub Actions cron overlap, the second one to claim a post will find it already in `'publishing'` state and skip it (it won't appear in the `status=pending` query).### `0 0 * * *` - Instagram Token Auto-Refresh-**`autoRefreshInstagramTokens(supabase)` in `backend/services/instagram.ts`**+**Function:** `tokenRefresh.refreshExpiringInstagramTokens()` in `backend/services/tokenRefreshService.ts`**What it does:**-1. Queries all accounts with `platform = 'instagram'`+1. Lists every account with `accountRepository.listAll()` and keeps the Instagram accounts with a token and an expiry2. For each account, checks if the Instagram long-lived token expires within 15 days-3. If expiring soon: calls `GET https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=<token>`-4. Updates the account's `accessToken` in Supabase+3. If expiring soon: calls `refreshLongLivedToken()` (`GET https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=<token>`)+4. Updates the account's `accessToken` and `tokenExpiresAt` with `accountRepository.updateById()`++One failed account is logged and skipped; it never stops the others. `backend/tests/services/tokenRefreshService.test.ts` covers the selection and the updates.**Token lifecycle:**- Instagram issues long-lived tokens valid for 60 days@@ -50,18 +75,15 @@ Reddit sessions are not refreshed on a schedule. Reddit accounts are added with## The `ctx.waitUntil()` Pattern-Cron handlers use `ctx.waitUntil()` to run work after the handler returns:+The `scheduled` handler passes the job to `ctx.waitUntil()`:```tsasync scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {- const supabase = getSupabase(env);- if (event.cron === '*/15 * * * *') {- ctx.waitUntil(processScheduledPosts(supabase));- }-}+ ctx.waitUntil(runScheduledJob(event.cron, env));+},```-This is required because Workers have a request deadline. `ctx.waitUntil()` tells the Workers runtime to keep the isolate alive until the promise resolves, even after the handler returns.+`ctx.waitUntil()` tells the Workers runtime to keep the isolate alive until the promise resolves, even after the handler returns.## Dual-Scheduler (GitHub Actions Fallback)@@ -74,14 +96,16 @@ The same `*/15` publishing logic also runs via `scripts/publish-scheduled.ts` incrons = ["*/15 * * * *", "0 0 * * *", "0 12 * * 1"]```-2. Add a handler branch in `server.ts`:+2. Add a constant and a branch in `backend/jobs/scheduled.ts`:```ts- } else if (event.cron === '0 12 * * 1') {- ctx.waitUntil(myWeeklyJob(supabase));+ export const WEEKLY_REPORT_CRON = '0 12 * * 1';+ // ...+ } else if (cron === WEEKLY_REPORT_CRON) {+ await services.weeklyReport.run();}```-3. Implement `myWeeklyJob(supabase: SupabaseClient): Promise<void>` in the appropriate service or utils file, and run `npm run typecheck`+3. Implement the job as a service method (a new service is wired in `backend/container.ts`). It receives repositories and the cron's `RequestContext`, logs through `context.log`, and catches per-item failures so one bad record does not stop the run. Add a test in `backend/tests/services/` and run `npm run typecheck`4. Update `docs/architecture/backend/CRON.md` (this file)diff --git a/docs/architecture/backend/HONO.md b/docs/architecture/backend/HONO.mdindex 35df99f..4c4bc08 100644--- a/docs/architecture/backend/HONO.md+++ b/docs/architecture/backend/HONO.md@@ -2,163 +2,184 @@## Entry Point: `backend/server.ts`-The entire backend is a single Hono application exported as a Cloudflare Workers module. `backend/wrangler.toml` points at it with `main = "server.ts"`; Wrangler bundles it and strips the types, and `npm run typecheck` checks them.+The backend is a single Hono application exported as a Cloudflare Workers module. `backend/wrangler.toml` points at it with `main = "server.ts"`; Wrangler bundles it and strips the types, and `npm run typecheck` checks them.```ts-// The two exports Cloudflare Workers looks for:+// the Worker's two entry points: HTTP requests go through the pipeline in app.ts, cron triggers to jobs/export default {- fetch: app.fetch, // handles all HTTP requests- async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) { ... } // handles cron triggers+ fetch: app.fetch,+ async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {+ ctx.waitUntil(runScheduledJob(event.cron, env));+ },} satisfies ExportedHandler<Env>;```+`server.ts` holds nothing else. The application is built by `createApp()` in `backend/app.ts`, and cron work starts in `backend/jobs/scheduled.ts` (see `CRON.md`).++## Folder Layout++The backend is split into layers, each with one job. `REQUEST_PIPELINE.md` is the reference for the layers, their order and the error model; this table is the map of where files live.++| Path | Contents |+|---|---|+| `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`) |+| `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`) |+| `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`) |+## Application Structure+`backend/app.ts` builds the pipeline. Each numbered step can answer early, so the cheap checks come first:+```ts-const app = new Hono<AppEnv>(); // root application--// Global middleware (runs on every request)-app.use('*', cors({ exposeHeaders: RATE_LIMIT_HEADERS }));-app.use('*', async (c, next) => { /* sets supabase, redis, rateLimitRedis */ await next(); });-app.use('/api/*', rateLimit(RATE_LIMIT_RULES.ip, clientIp));--// Public routes-app.get('/api/health', ...);-app.get('/api/auth/instagram/callback', rateLimit(RATE_LIMIT_RULES.oauth, clientIp), callbackHandler);--// Protected sub-application-const api = new Hono<AppEnv>();-api.use('*', requireAuth); // JWT verification on all /api/* routes-api.use('*', rateLimit(RATE_LIMIT_RULES.user, userKey));-// plus the quota and publish limits for the routes listed in lib/rateLimit/rules.ts-api.route('/', keysRouter);-api.route('/', accountsRouter);-api.route('/', analyticsRouter);-api.route('/', publishingRouter);-api.route('/', scheduledPostsRouter);-api.route('/', settingsRouter);-api.route('/', redditRouter);-api.route('/', trackedContentRouter);-api.route('/', overviewRouter);-api.get('/auth/instagram/url', urlHandler);--app.route('/api', api); // mount protected sub-app under /api+export function createApp(): Hono<AppEnv> {+ const app = new Hono<AppEnv>();+ app.onError(errorHandler);+ app.notFound(notFoundHandler);++ app.use('*', apiCors); // 1. CORS+ app.use('*', requestId()); // 2. request id+ app.use('*', requestContext); // signal and access log line+ app.use('*', securityHeaders); // 3. security headers+ app.use('*', injectClients); // 4. Supabase and Redis clients+ app.use('/api/*', rateLimit(RATE_LIMIT_RULES.ip, clientIp)); // 5. limit by IP++ app.route('/api', publicRoutes); // health check and the OAuth callback++ const api = new Hono<AppEnv>();+ api.use('*', requireAuth); // 6. authentication+ api.use('*', rateLimit(RATE_LIMIT_RULES.user, userKey)); // 7. per-user limits+ // plus the quota and publish limits for the routes listed in lib/rateLimit/rules.ts+ api.route('/', protectedRoutes); // 8. route tables+ app.route('/api', api);++ return app;+}```-See `docs/architecture/backend/RATE_LIMITING.md` for the rate limit rules.+`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.++See `REQUEST_PIPELINE.md` for what each step does and `RATE_LIMITING.md` for the rate limit rules.## Types| Type | File | Purpose ||---|---|---|-| `Env` | `backend/types/env.ts` | Worker secrets and bindings, read through `c.env` or the `env` argument of `scheduled()` |+| `Env` | `backend/types/env.ts` | Worker secrets and variables, read through `c.env` or the `env` argument of `scheduled()`; `lib/config.ts` turns them into a cleaned `AppConfig` || `AppVariables` | `backend/types/app.ts` | The keys set with `c.set()` and read with `c.get()` || `AppEnv` | `backend/types/app.ts` | `{ Bindings: Env; Variables: AppVariables }`, the type argument of every `new Hono<AppEnv>()` |-| `AppContext` | `backend/types/app.ts` | `Context<AppEnv>`, for middleware and handlers declared outside a router |-| Request and response shapes | `shared/types/*.ts` | Shared with the frontend; routes check responses with `satisfies` |+| `AppContext` | `backend/types/app.ts` | `Context<AppEnv>`, for middleware and helpers declared outside a router |+| `RequestContext` | `backend/types/context.ts` | `requestId`, `signal` and `log`: the request metadata services receive, free of Hono types |+| `Services` | `backend/container.ts` | Every service for one request or cron run, returned by `createServices()` |+| Request and response shapes | `shared/types/*.ts` | Shared with the frontend; controllers check responses with `satisfies` |`ScheduledController`, `ExecutionContext` and `ExportedHandler` are global types from `@cloudflare/workers-types`.## Context Values-These are set on the Hono context (`c`) and available in all route handlers:+The Hono context carries only small request-scoped values:| Key | Type | Set by | Available after ||---|---|---|---|-| `supabase` | `SupabaseClient` (service-role) | global middleware | All routes |-| `redis` | `Redis \| null` | global middleware | All routes |-| `rateLimitRedis` | `Redis \| null` (no retries, 1 second timeout) | global middleware | All routes; used only by `rateLimit` |+| `requestId` | `string` | `hono/request-id` | All routes; returned in the `X-Request-Id` header |+| `signal` | `AbortSignal` | `requestContext` | All routes; aborts on client disconnect or after 30 seconds |+| `supabase` | `SupabaseClient` (service-role) | `injectClients` | All routes |+| `redis` | `Redis \| null` | `injectClients` | All routes |+| `rateLimitRedis` | `Redis \| null` (no retries, 1 second timeout) | `injectClients` | All routes; used only by `rateLimit` || `userId` | `string` (UUID) | `requireAuth` | Protected routes only || `userEmail` | `string \| undefined` | `requireAuth` | Protected routes only |The keys and their types are declared in `AppVariables`, so `c.get('redis')` is typed `Redis | null` without a cast. Add a key there before setting a new one.-**Accessing context values in a handler declared outside a router:**+Controllers read `userId` with `c.get('userId')` and pass it to a service method. They never hand the clients to a service directly: `servicesFor(c)` in `controllers/http.ts` builds the request's services from the clients, the cleaned config and the request context.+```ts-export async function myHandler(c: AppContext) {- const supabase = c.get('supabase');- const redis = c.get('redis');- const userId = c.get('userId');- // ...-}+export const listAccounts = controller.createHandlers(async c => {+ const accounts = await servicesFor(c).accounts.list(c.get('userId'));+ return c.json(accounts.map(safeAccount) satisfies AccountListResponse);+});```-## Route File Pattern+## Route Table and Controller Pattern-Every route file follows this structure:+A feature has a route table in `routes/` and a controller in `controllers/`. The route table only maps a method and path to a controller:```ts-// backend/routes/myFeature.ts+// backend/routes/trackedContentRoutes.tsimport { Hono } from 'hono';-import { getMyData, createMyData } from '../lib/db.ts';+import {+ listTrackedContent, addTrackedContent, updateTrackedContent, deleteTrackedContent, refreshTrackedContent,+} from '../controllers/trackedContentController.ts';import type { AppEnv } from '../types/app.ts';-import type { MyData, MyDataRequest } from '../../shared/types/domain.ts';const router = new Hono<AppEnv>();-router.get('/my-resource', async (c) => {- const userId = c.get('userId');- const supabase = c.get('supabase');- try {- const data = await getMyData(supabase, userId);- return c.json(data satisfies MyData[]);- } catch (err) {- console.error('GET /my-resource:', (err as Error).message);- return c.json({ error: (err as Error).message }, 500);- }-});--router.post('/my-resource', async (c) => {- const userId = c.get('userId');- const supabase = c.get('supabase');- const body = await c.req.json() as MyDataRequest;- // validate body...- try {- await createMyData(supabase, body, userId);- return c.json({ success: true }, 201);- } catch (err) {- console.error('POST /my-resource:', (err as Error).message);- return c.json({ error: (err as Error).message }, 500);- }-});+router.get('/tracked-content', ...listTrackedContent);+router.post('/tracked-content', ...addTrackedContent);+router.put('/tracked-content/:id', ...updateTrackedContent);+router.delete('/tracked-content/:id', ...deleteTrackedContent);+router.post('/tracked-content/:id/refresh', ...refreshTrackedContent);export default router;```-Then in `server.ts`:+Each controller is built with `controller.createHandlers(...)` from `controllers/http.ts`. A validator from `middleware/validate.ts` comes first, so `c.req.valid('json')` is typed inside the handler:+```ts-import myFeatureRouter from './routes/myFeature.ts';-// ...-api.route('/', myFeatureRouter);+// backend/controllers/trackedContentController.ts+export const addTrackedContent = controller.createHandlers(jsonBody(parseNewTrackedContent), async c => {+ const item = await servicesFor(c).trackedContent.add(c.get('userId'), c.req.valid('json'));+ return c.json(item, 201);+});++export const deleteTrackedContent = controller.createHandlers(async c => {+ await servicesFor(c).trackedContent.remove(c.get('userId'), pathParam(c, 'id'));+ return c.json({ success: true } satisfies SuccessResponse);+});```+`pathParam(c, name)` reads a path parameter, because Hono cannot type the parameters of a controller declared apart from its route. A new route table is added to the list in `routes/index.ts`. See `docs/features/NEW_API_ENDPOINT.md` for the full walkthrough.+## Error Handling-The global error handler catches uncaught errors (Hono types `err` as `Error` here):-```ts-app.onError((err, c) => {- console.error('Worker error:', err.message);- return c.json({ error: 'Internal server error' }, 500);-});+Controllers do not catch errors. Services, repositories, validators and middleware throw the typed errors in `lib/errors.ts` (`ValidationError`, `NotFoundError`, `ConflictError`, `UpstreamError`, `NotConfiguredError` and the rest), and `middleware/errorHandler.ts`, registered with `app.onError`, maps each error's code to a status and writes one body:++```json+{ "success": false, "code": "NOT_FOUND", "message": "Account not found", "requestId": "3f2a..." }```-Route handlers should catch their own errors and return descriptive messages. Do not throw from route handlers - catch and return JSON error responses with appropriate status codes.+An 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.++## Logging++`lib/logger.ts` writes one JSON object per line (`level`, `message`, the request id, the user id and any extra fields), which Workers Logs indexes field by field. `requestContext` writes one access line per request with the method, path, status and duration, and the error handler logs each failure with its code. Services log through `context.log`; no other code calls `console` directly. `errorFields(err)` adds an error's message and cause to a log line with URLs removed, never the stack.## Environment Access-Worker environment variables are accessed via `c.env` in middleware and handlers, or via the `env` parameter in the `scheduled` handler:+Worker variables are declared in `Env` and reach the code through `lib/config.ts`. `readConfig(env)` returns an `AppConfig` with every value trimmed (pasted secrets can carry a byte order mark): the YouTube key, the Instagram OAuth settings, the Cloudinary settings (or `null`) and the allowed CORS origins. Services receive the config from `createServices()`, and a service that needs a missing value throws `NotConfiguredError` (503).```ts-// In middleware or handler:-const apiKey = c.env.YOUTUBE_API_KEY; // string | undefined, declared in Env+// in a service+if (!config.youtubeApiKey) throw new NotConfiguredError(NO_YOUTUBE_KEY_MESSAGE);-// In cron handler:-async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {- const supabase = getSupabase(env);-}+// in the cron entry point, jobs/scheduled.ts+const services = createServices({ supabase: getSupabase(env), redis: getRedis(env) }, readConfig(env), context);```-**Never hardcode secrets.** All secrets must come from `c.env` (Worker secrets set via `wrangler secret put`).+The Supabase and Redis credentials are read by `database/supabase.ts` and `database/redis.ts`.++**Never hardcode secrets.** All secrets must come from the Worker environment (Worker secrets set via `wrangler secret put`).## Packages and Toolingdiff --git a/docs/architecture/backend/MIDDLEWARE.md b/docs/architecture/backend/MIDDLEWARE.mdindex a75273f..a883dee 100644--- a/docs/architecture/backend/MIDDLEWARE.md+++ b/docs/architecture/backend/MIDDLEWARE.md@@ -1,78 +1,117 @@# Backend Middleware+Every file in `backend/middleware/` does one piece of work that many requests need. `backend/app.ts` applies them in a fixed order; `REQUEST_PIPELINE.md` explains why the order matters.+## Middleware Stack (in execution order)```Request arrives- │- ▼-1. CORS middleware app.use('*', cors({ exposeHeaders }))- │- ▼-2. Client injection app.use('*', clientInjectionMiddleware)- │- ▼-3. rateLimit(ip) app.use('/api/*', rateLimit(RATE_LIMIT_RULES.ip, clientIp))- │- ▼-4. requireAuth api.use('*', requireAuth) <- protected routes only- │- ▼-5. rateLimit(user, quota, publish) <- protected routes only- │- ▼-Route handler+ 1. apiCors app.use('*', apiCors) middleware/cors.ts+ 2. requestId app.use('*', requestId()) hono/request-id+ requestContext app.use('*', requestContext) middleware/requestContext.ts+ 3. securityHeaders app.use('*', securityHeaders) middleware/securityHeaders.ts+ 4. injectClients app.use('*', injectClients) middleware/clients.ts+ 5. 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))+ 6. requireAuth api.use('*', requireAuth) middleware/auth.ts <- protected routes only+ 7. rateLimit(user, quota, publish) middleware/rateLimit.ts <- protected routes only+ 8. route table api.route('/', protectedRoutes)+ jsonBody / queryParams middleware/validate.ts <- per route+ controller+Errors from any step -> errorHandler (app.onError), unknown routes -> notFoundHandler middleware/errorHandler.ts```----## 1. CORS Middleware+## 1. CORS++**Source:** `backend/middleware/cors.ts` (wraps `hono/cors`)+**Applied to:** Every request, first, so a preflight is answered before any other work++Only the app's own origins may call the API from a browser:++- `FRONTEND_URL`, and every origin in the optional `ALLOWED_ORIGINS` Worker variable (comma-separated). Each entry is reduced to its origin, and a malformed entry is skipped rather than allowing everything.+- When the Worker itself is served from `localhost` or `127.0.0.1` (a development instance), the Vite dev server origins `http://localhost:5173` and `http://127.0.0.1:5173` are allowed too.++A request from any other origin gets no `Access-Control-Allow-Origin` header, so the browser blocks it. The list is built by `corsOrigins()` in `lib/config.ts`.++`exposeHeaders` lets the browser read `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset`, `Retry-After` and `X-Request-Id`. Preflight results are cached for 10 minutes (`maxAge: 600`).-**Source:** `hono/cors` (Hono built-in)+---++## 2. Request Id and Request Context++**Source:** `hono/request-id`, then `backend/middleware/requestContext.ts`**Applied to:** Every request-Configured with defaults - allows all origins in development. For production, the Worker's CORS behavior should be tightened to only allow `FRONTEND_URL`.+`requestId()` sets `requestId` on the context and the `X-Request-Id` response header; an incoming `X-Request-Id` of safe characters is kept. `requestContext` then:++1. Sets `signal`, an `AbortSignal` that aborts when the client disconnects or after the 30 second request deadline. Services pass it to every platform `fetch`.+2. Writes one access log line after the response, with the method, path, status and duration.++It also exports two helpers: `requestLogger(c)`, a logger bound to the request id and user id, and `requestContextOf(c)`, which builds the `RequestContext` (`requestId`, `signal`, `log`) that controllers hand to services.-**Current config:** `cors({ exposeHeaders: RATE_LIMIT_HEADERS })`. All origins are allowed, which is acceptable for a self-hosted deployment where the Worker URL is not publicly advertised. `exposeHeaders` lets the browser read `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset` and `Retry-After`.+---++## 3. Security Headers++**Source:** `backend/middleware/securityHeaders.ts` (wraps `hono/secure-headers`)+**Applied to:** Every response, errors included++The API only answers JSON and redirects, so nothing it returns may be framed, sniffed or run as a page: a deny-all `Content-Security-Policy` (`default-src 'none'; frame-ancestors 'none'`), `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, `X-Content-Type-Options: nosniff` and `Strict-Transport-Security`.----## 2. Client Injection Middleware+## 4. Client Injection-**Source:** Inline in `backend/server.ts`+**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. This is the correct pattern for Cloudflare Workers - clients must be created fresh per request because there is no persistent process memory.+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.```ts-app.use('*', async (c, next) => {+export async function injectClients(c: AppContext, next: Next): Promise<void> {c.set('supabase', getSupabase(c.env));c.set('redis', getRedis(c.env));c.set('rateLimitRedis', getRateLimitRedis(c.env));await next();-});+}```-**`getSupabase(env)`** - creates a Supabase client with the service-role key. Used for all DB operations.-**`getRedis(env)`** - creates an Upstash Redis client if `UPSTASH_REDIS_REST_URL` is set, otherwise returns `null`. All cache functions in `lib/cache.ts` handle `null` silently.-**`getRateLimitRedis(env)`** - 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.+**`getSupabase(env)`** (`database/supabase.ts`) - a Supabase client with the service-role key, used by every repository.+**`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.-The keys and their types are declared in `AppVariables` in `backend/types/app.ts`, so `c.set()` rejects a value of the wrong type and `c.get()` needs no cast.+Controllers do not read these clients themselves; `servicesFor(c)` passes them to `createServices()` in `container.ts`. The keys and their types are declared in `AppVariables` in `backend/types/app.ts`, so `c.set()` rejects a value of the wrong type and `c.get()` needs no cast.----## 3. requireAuth Middleware+## 5. and 7. rateLimit++**Source:** `backend/middleware/rateLimit.ts`, rules and algorithms in `backend/lib/rateLimit/`+**Applied to:** every `/api` request (`ip` rule, before `requireAuth`), every protected request (`user`), quota-spending routes (`quota`), Instagram publishing routes (`publish`) and the public OAuth callback (`oauth`)++`rateLimit(rule, identify, applies?)` returns a middleware. `identify(c)` returns the key (`clientIp` or `userKey`); a request without one is not limited. `applies(c)` restricts a rule to some routes (`matchesRoute(QUOTA_ROUTES, ...)`). Allowed responses get `RateLimit-*` headers for the most restrictive rule. A request over a limit gets `429` with `Retry-After` and the standard error body plus `retryAfter`:++```json+{ "success": false, "code": "RATE_LIMITED", "message": "...", "requestId": "3f2a...", "retryAfter": 42 }+```++The IP limit runs before authentication, so a flood of bad tokens never reaches Supabase Auth. See `RATE_LIMITING.md` for the rules, the algorithms and how failures are handled.++---++## 6. requireAuth**Source:** `backend/middleware/auth.ts`-**Applied to:** All routes mounted under the `api` sub-application (`/api/*`)+**Applied to:** All routes mounted under the `api` sub-application (every `/api/*` route except the two public ones)```ts-export async function requireAuth(c: AppContext, next: Next) {- const token = c.req.header('Authorization')?.replace('Bearer ', '');- if (!token) return c.json({ error: 'Unauthorized' }, 401);- const supabaseAuth = getSupabaseAuth(c.env);- const { data: { user }, error } = await supabaseAuth.auth.getUser(token);- if (error || !user) return c.json({ error: 'Invalid or expired token' }, 401);+export async function requireAuth(c: AppContext, next: Next): Promise<void> {+ const token = c.req.header('Authorization')?.match(BEARER)?.[1];+ if (!token) throw new UnauthorizedError('Sign in to use the API');+ const { data: { user }, error } = await getSupabaseAuth(c.env).auth.getUser(token);+ if (error || !user) throw new UnauthorizedError('Your session has expired - sign in again');c.set('userId', user.id);c.set('userEmail', user.email);await next();@@ -80,24 +119,44 @@ export async function requireAuth(c: AppContext, next: Next) {```**What it does:**-1. Extracts `Authorization: Bearer <token>` header+1. Reads the token from the `Authorization: Bearer <token>` header2. Creates a Supabase **anon** client (not service-role) to verify the JWT-3. Calls `supabaseAuth.auth.getUser(token)` - Supabase validates the token signature+3. Calls `auth.getUser(token)` - Supabase validates the token signature4. Sets `userId` (UUID) and `userEmail` (`string | undefined`) on the Hono context-5. Returns 401 JSON if token is missing, invalid, or expired+5. Throws `UnauthorizedError` if the token is missing, invalid or expired; the error handler answers `401` with code `UNAUTHORIZED`-**Critical:** `userId` from this middleware is the only trusted source of user identity. Route handlers must use `c.get('userId')` - never accept a userId from request body or query params.+**Critical:** `userId` from this middleware is the only trusted source of user identity. Controllers read it with `c.get('userId')` and pass it to services - never accept a user id from the request body or query parameters.----## 4. rateLimit Middleware+## 8. Validation-**Source:** `backend/middleware/rateLimit.ts`, rules and algorithms in `backend/lib/rateLimit/`-**Applied to:** every `/api` request (`ip` rule, before `requireAuth`), every protected request (`user`), quota-spending routes (`quota`), Instagram publishing routes (`publish`) and the public OAuth callback (`oauth`)+**Source:** `backend/middleware/validate.ts`+**Applied to:** Individual routes, as the first handler passed to `controller.createHandlers(...)`-`rateLimit(rule, identify, applies?)` returns a middleware. `identify(c)` returns the key (`clientIp` or `userKey`); a request without one is not limited. `applies(c)` restricts a rule to some routes (`matchesRoute(QUOTA_ROUTES, ...)`). Allowed responses get `RateLimit-*` headers for the most restrictive rule; a request over a limit gets `429` with `Retry-After` and `{ success: false, error, retryAfter }`.+`jsonBody(parse)` and `queryParams(parse)` wrap Hono's `validator`. Each parser in `backend/validators/` reads fields with the helpers in `validators/fields.ts` and throws `ValidationError` (400). For a query, a repeated key keeps its first value. The controller reads the parsed result with `c.req.valid('json')` or `c.req.valid('query')`.-See `RATE_LIMITING.md` for the rules, the algorithms and how failures are handled.+```ts+export const addRedditAccount = controller.createHandlers(jsonBody(parseRedditAccount), async c => {+ const account = await servicesFor(c).accounts.addReddit(c.get('userId'), c.req.valid('json'));+ return c.json({ success: true, account: safeAccount(account) } satisfies AccountResponse);+});+```++---++## Error Handler++**Source:** `backend/middleware/errorHandler.ts`+**Applied to:** `app.onError(errorHandler)` and `app.notFound(notFoundHandler)`++Every error thrown by a middleware, controller, service or repository ends here. An `AppError` from `lib/errors.ts` is answered with the status for its code; Hono's own `HTTPException` (such as a malformed JSON body) is mapped by status; anything else is an `INTERNAL_ERROR` (500) with a message asking the user to quote the request id. Every failure gets the same body:++```json+{ "success": false, "code": "VALIDATION_ERROR", "message": "Username is required", "requestId": "3f2a..." }+```++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`.---@@ -110,21 +169,21 @@ Place new middleware files in `backend/middleware/`. Follow this pattern:import type { Next } from 'hono';import type { AppContext } from '../types/app.ts';-export async function myMiddleware(c: AppContext, next: Next) {- // do something before route handler+export async function myMiddleware(c: AppContext, next: Next): Promise<void> {+ // to reject a request, throw a typed error from lib/errors.ts; the error handler formats itawait next();- // optionally do something after route handler}```-A middleware that sets a new context value needs the key added to `AppVariables` in `backend/types/app.ts` first.+- Reject a request by throwing a typed error (`UnauthorizedError`, `ValidationError`, ...), never by building a JSON body by hand.+- A middleware that sets a new context value needs the key added to `AppVariables` in `backend/types/app.ts` first. Keep context values small and request-scoped.+- Log through `requestLogger(c)`, not `console`.-Apply globally in `server.ts`:-```ts-app.use('*', myMiddleware);-```+Apply it in `backend/app.ts` at the step where it belongs, and add a comment with its place in the order:-Or apply to a specific route group:```ts-api.use('/admin/*', adminOnlyMiddleware);+app.use('*', myMiddleware); // every request+api.use('*', myMiddleware); // protected routes only, after requireAuth```++Middleware for one route goes in the route's `controller.createHandlers(...)` call, before the handler. Update this file, `REQUEST_PIPELINE.md` and `HONO.md` when the stack changes.diff --git a/docs/architecture/backend/RATE_LIMITING.md b/docs/architecture/backend/RATE_LIMITING.mdindex 04b8acb..3c0328d 100644--- a/docs/architecture/backend/RATE_LIMITING.md+++ b/docs/architecture/backend/RATE_LIMITING.md@@ -11,16 +11,19 @@ Every `/api` request is rate limited inside the Worker. Cloudflare does not limi```Request-> CORS (exposes the rate limit headers to the browser)+ -> request id and request context, security headers-> client injection (supabase, redis, rateLimitRedis)-> rateLimit(ip) every /api request, keyed by client IP, before authentication-> requireAuth protected routes only-> rateLimit(user) every protected request, keyed by user id-> rateLimit(quota) routes that spend platform API quota, keyed by user id-> rateLimit(publish) Instagram container and publish routes, keyed by user id- -> route handler+ -> route table and controller```-The public OAuth callback (`GET /api/auth/instagram/callback`) also passes `rateLimit(oauth)`, keyed by IP.+The order is set in `backend/app.ts`; see `REQUEST_PIPELINE.md`.++The public OAuth callback (`GET /api/auth/instagram/callback`) also passes `rateLimit(oauth)`, keyed by IP; it is registered in `routes/index.ts`.## Rules@@ -65,7 +68,7 @@ Bucket levels are rounded to a millionth after each step, so the saved value surRate limiting never fails a request because of its own storage:- **No Redis configured:** every rule counts in memory.-- **Redis fails or times out:** the limiter uses a separate client (`getRateLimitRedis()` in `lib/redis.ts`) that does not retry and gives up after 1 second. On a failure the isolate logs once and counts in memory for 30 seconds before it tries Redis again, so an outage costs at most one second per isolate every 30 seconds.+- **Redis fails or times out:** the limiter uses a separate client (`getRateLimitRedis()` in `database/redis.ts`) that does not retry and gives up after 1 second. On a failure the isolate logs once and counts in memory for 30 seconds before it tries Redis again, so an outage costs at most one second per isolate every 30 seconds.- **Deny cache:** when Redis rejects a key, the isolate remembers the retry time and rejects that key locally until then. A client flooding a limit costs no Redis commands.## Responses@@ -86,10 +89,10 @@ RateLimit-Limit: 300RateLimit-Remaining: 0RateLimit-Reset: 12-{ "success": false, "error": "Too many requests from your network - try again in 12 seconds.", "retryAfter": 12 }+{ "success": false, "code": "RATE_LIMITED", "message": "Too many requests from your network - try again in 12 seconds.", "requestId": "3f2a...", "retryAfter": 12 }```-CORS exposes the four headers. The frontend needs no special handling: `request()` in `services/api.ts` throws the `error` text, and pages show it in a toast.+The body is the standard error body every failure gets (built by `errorBody()` in `middleware/errorHandler.ts`), plus `retryAfter` in seconds. CORS exposes the four headers. The frontend needs no special handling: `request()` in `services/api.ts` throws the `message` text, and pages show it in a toast.## Redis Keysdiff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.mdindex c7579e3..79e6fc9 100644--- a/docs/architecture/backend/ROUTES.md+++ b/docs/architecture/backend/ROUTES.md@@ -1,112 +1,153 @@# Backend Routes-All routes live under `/api`. Routes under the `api` sub-app require a valid Supabase JWT (`requireAuth` middleware). Public routes bypass auth.+All routes live under `/api`. Routes in the protected group require a valid Supabase JWT (`requireAuth` middleware). Public routes bypass auth.++Each route is one line in a route table in `backend/routes/` that points at a controller in `backend/controllers/`; the controller calls one service method. `backend/routes/index.ts` groups the tables into `publicRoutes` and `protectedRoutes`. See `REQUEST_PIPELINE.md` for the layers.Every route is rate limited and can answer `429` with `Retry-After`; see `RATE_LIMITING.md` for which rule covers which route.+## Error Responses++Every failure has a 4xx or 5xx status and the same body, written by `middleware/errorHandler.ts`:++```json+{ "success": false, "code": "NOT_FOUND", "message": "Account not found", "requestId": "3f2a..." }+```++These statuses apply to every route below and are not repeated in the tables:++| Status | Code | When |+|---|---|---|+| 400 | `VALIDATION_ERROR` | The body or query fails its validator, or a stored field the request needs (such as a token or uploads playlist) is missing |+| 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) |+| 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 |+| 504 | `UPSTREAM_TIMEOUT` | A platform call was cancelled or timed out |+## Public Routes-| Method | Path | Handler | Purpose |+Registered on `publicRoutes` in `routes/index.ts`.++| Method | Path | Controller | Purpose ||---|---|---|---|-| GET | `/api/health` | inline | Returns `{ status: 'ok', timestamp }` |-| GET | `/api/auth/instagram/callback` | `instagramAuth.callbackHandler` | OAuth code exchange; browser redirect after Instagram login |+| 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 |## Protected Routes (require `Authorization: Bearer <jwt>`)+The File column names the route table and the controller.+### Keys| Method | Path | File | Purpose ||---|---|---|---|-| GET | `/api/keys` | `routes/keys.ts` | Returns `{ youtube: bool, instagram: bool, cloudinary: bool }` - whether each API key is configured |+| GET | `/api/keys` | `settingsRoutes.ts`, `settingsController.getKeyStatus` | Returns `{ youtube, instagram, cloudinary }`, each `{ configured: boolean }` - whether each server key is set |### Accounts-Handlers delegate to `services/accountConnect.ts` and `services/accountRefresh.ts`; the Instagram OAuth handlers delegate to `services/instagramOAuth.ts`. See `SERVICES.md`.+Controllers call `AccountService` (`services/accountService.ts`); the Instagram OAuth routes call `InstagramConnectService`. See `SERVICES.md`.| Method | Path | File | Purpose ||---|---|---|---|-| GET | `/api/accounts` | `routes/accounts.ts` | List all user accounts (tokens stripped via `safeAccount()`) |-| POST | `/api/accounts` | `routes/accounts.ts` | Add YouTube channel - resolves URL/handle to channel ID, fetches stats |-| DELETE | `/api/accounts/:id` | `routes/accounts.ts` | Remove account + invalidate Redis cache for that account |-| POST | `/api/accounts/refresh-all` | `routes/accounts.ts` | Refresh stats for every account; returns updated accounts list |-| POST | `/api/accounts/:id/refresh` | `routes/accounts.ts` | Refresh a single account's stats |-| POST | `/api/accounts/instagram` | `routes/accounts.ts` | Add Instagram account via a raw access token (for manual setup) |-| POST | `/api/accounts/:id/refresh-ig-token` | `routes/accounts.ts` | Extend Instagram long-lived token (valid up to 60 days; refresh when < 15 days remain) |+| GET | `/api/accounts` | `accountRoutes.ts`, `accountController.listAccounts` | List all user accounts (credentials stripped via `safeAccount()`) |+| POST | `/api/resolve-channel` | `accountRoutes.ts`, `accountController.resolveChannel` | Resolve a channel URL, @handle or channel ID to its channel data without saving it; 503 without a YouTube key |+| POST | `/api/accounts` | `accountRoutes.ts`, `accountController.addYouTubeAccount` | Add YouTube channel - resolves URL/handle to channel ID, fetches stats; 409 when the channel is already added, 503 without a YouTube key |+| DELETE | `/api/accounts/:id` | `accountRoutes.ts`, `accountController.deleteAccount` | Remove account and delete its Redis cache entries |+| POST | `/api/accounts/refresh-all` | `accountRoutes.ts`, `accountController.refreshAllAccounts` | Refresh stats for every account; one failure does not stop the rest, and `results` reports each account's outcome |+| POST | `/api/accounts/:id/refresh` | `accountRoutes.ts`, `accountController.refreshAccount` | Refresh a single account's stats |+| POST | `/api/accounts/instagram` | `accountRoutes.ts`, `accountController.addInstagramAccount` | Add Instagram account via a raw access token (for manual setup); 409 when already added |+| POST | `/api/accounts/:id/refresh-ig-token` | `accountRoutes.ts`, `accountController.refreshInstagramToken` | Extend Instagram long-lived token (valid up to 60 days; refresh when < 15 days remain) |### Analytics-Channel metrics, the comparison and the all videos filter live in `services/youtubeLibrary.ts`; the channel backfill lives in `services/accountRefresh.ts`.+Controllers call `YouTubeAnalyticsService` and `InstagramAnalyticsService`. Channel metrics, the comparison and the all videos filter live in `services/youtube/youtubeLibrary.ts`.| Method | Path | File | Purpose ||---|---|---|---|-| GET | `/api/accounts/:id/analytics` | `routes/analytics.ts` | Full YouTube analytics - fetches up to 500 videos, runs `computeVideoAnalytics()`, returns 50+ metrics; 404 for an account that is not a YouTube channel, 400 when no uploads playlist is stored |-| GET | `/api/accounts/:id/videos` | `routes/analytics.ts` | Returns cached video list (from Redis if available); the same 404 and 400 checks before a live fetch |-| GET | `/api/accounts/:id/ig-analytics` | `routes/analytics.ts` | Instagram analytics - fetches up to 500 media with views, classifies each as reel, post, or video, runs `computeInstagramAnalytics()` |-| GET | `/api/accounts/:id/ig-media` | `routes/analytics.ts` | Returns the Instagram media list (with `contentType` and `viewCount`) from cache, fetching live on a miss |-| GET | `/api/comparison` | `routes/analytics.ts` | Cross-account comparison data for the Overview dashboard |+| GET | `/api/accounts/:id/analytics` | `analyticsRoutes.ts`, `analyticsController.getChannelAnalytics` | Full YouTube analytics - fetches up to 500 videos, runs `computeVideoAnalytics()`, returns 50+ metrics; 404 for an account that is not a YouTube channel, 400 when no uploads playlist is stored |+| GET | `/api/accounts/:id/videos` | `analyticsRoutes.ts`, `analyticsController.getChannelVideos` | Returns cached video list (from Redis if available); the same 404 and 400 checks before a live fetch |+| GET | `/api/videos/all` | `analyticsRoutes.ts`, `analyticsController.getVideoLibrary` | Every cached video across the user's channels, filtered and sorted by `channelId`, `search`, `minViews`, `maxViews`, `sort` and `order` query parameters |+| GET | `/api/accounts/:id/ig-analytics` | `analyticsRoutes.ts`, `analyticsController.getInstagramAnalytics` | Instagram analytics - fetches up to 500 media with views, classifies each as reel, post, or video, runs `computeInstagramAnalytics()` |+| GET | `/api/accounts/:id/ig-media` | `analyticsRoutes.ts`, `analyticsController.getInstagramMedia` | Returns the Instagram media list (with `contentType` and `viewCount`) from cache, fetching live on a miss |+| GET | `/api/comparison` | `analyticsRoutes.ts`, `analyticsController.getComparison` | Cross-account comparison data for the Overview dashboard |### Instagram OAuth| Method | Path | File | Purpose ||---|---|---|---|-| GET | `/api/auth/instagram/url` | `routes/instagramAuth.ts` | Generates Instagram OAuth URL with HMAC-signed state. Returns `{ url }`. |+| GET | `/api/auth/instagram/url` | `instagramAuthRoutes.ts`, `instagramAuthController.getInstagramAuthUrl` | Generates Instagram OAuth URL with HMAC-signed state. Returns `{ url }`; 503 when the Instagram app credentials are not set |### Publishing++Controllers call `PublishingService` (`services/publishingService.ts`).+| Method | Path | File | Purpose ||---|---|---|---|-| GET | `/api/cloudinary-config` | `routes/publishing.ts` | Returns `{ cloudName, uploadPreset }` for frontend Cloudinary upload; 503 when the Worker has no Cloudinary settings |-| GET | `/api/accounts/:id/ig-publishing-limit` | `routes/publishing.ts` | Checks daily Instagram publishing quota remaining |-| POST | `/api/accounts/:id/ig-publish` | `routes/publishing.ts` | Creates Instagram media container via Graph API; returns `{ containerId }` |-| GET | `/api/ig-container/:id/status` | `routes/publishing.ts` | Polls container status (`FINISHED`, `IN_PROGRESS`, `ERROR`, `EXPIRED`); needs `?accountId=` of an Instagram account with a token (400 or 404 otherwise) |-| POST | `/api/accounts/:id/ig-media-publish` | `routes/publishing.ts` | Publishes the container to Instagram; returns `{ mediaId }` |+| GET | `/api/cloudinary-config` | `publishingRoutes.ts`, `publishingController.getCloudinaryConfig` | Returns `{ cloudName, uploadPreset }` for frontend Cloudinary upload; 503 when the Worker has no Cloudinary settings |+| GET | `/api/accounts/:id/ig-publishing-limit` | `publishingRoutes.ts`, `publishingController.getPublishingLimit` | Checks daily Instagram publishing quota remaining |+| POST | `/api/accounts/:id/ig-publish` | `publishingRoutes.ts`, `publishingController.createContainer` | Creates Instagram media container via Graph API; returns `{ containerId }` |+| GET | `/api/ig-container/:containerId/status` | `publishingRoutes.ts`, `publishingController.getContainerStatus` | Polls container status (`FINISHED`, `IN_PROGRESS`, `ERROR`, `EXPIRED`); needs `?accountId=` of an Instagram account with a token (400 or 404 otherwise) |+| POST | `/api/accounts/:id/ig-media-publish` | `publishingRoutes.ts`, `publishingController.publishContainer` | Publishes the container to Instagram; returns `{ mediaId }` |### Scheduled Posts++Controllers call `ScheduledPostService` (`services/scheduledPostService.ts`).+| Method | Path | File | Purpose ||---|---|---|---|-| GET | `/api/scheduled-posts` | `routes/scheduledPosts.ts` | List all user's scheduled posts, ordered by `scheduled_at` ascending |-| POST | `/api/scheduled-posts` | `routes/scheduledPosts.ts` | Create a new scheduled post with `status: 'pending'` |-| PUT | `/api/scheduled-posts/:id` | `routes/scheduledPosts.ts` | Edit a pending post (caption, scheduled time, media, etc.) |-| DELETE | `/api/scheduled-posts/:id` | `routes/scheduledPosts.ts` | Delete a single post |-| DELETE | `/api/scheduled-posts` | `routes/scheduledPosts.ts` | Delete all posts except those with `status: 'publishing'` |-| GET | `/api/process-scheduled` | `routes/scheduledPosts.ts` | Manual trigger - runs `processScheduledPosts()` immediately (dev/test) |-| POST | `/api/process-scheduled` | `routes/scheduledPosts.ts` | Same as above |+| GET | `/api/scheduled-posts` | `scheduledPostRoutes.ts`, `scheduledPostController.listScheduledPosts` | List all user's scheduled posts, ordered by `scheduled_at` ascending |+| POST | `/api/scheduled-posts` | `scheduledPostRoutes.ts`, `scheduledPostController.createScheduledPost` | Create a new scheduled post with `status: 'pending'`; 400 unless `scheduledAt` is a future date |+| PUT | `/api/scheduled-posts/:id` | `scheduledPostRoutes.ts`, `scheduledPostController.updateScheduledPost` | Edit a pending post (caption, scheduled time, media, etc.); 400 for a post that is not pending |+| DELETE | `/api/scheduled-posts/:id` | `scheduledPostRoutes.ts`, `scheduledPostController.deleteScheduledPost` | Delete a single post; 400 while it is publishing |+| DELETE | `/api/scheduled-posts` | `scheduledPostRoutes.ts`, `scheduledPostController.deleteAllScheduledPosts` | Delete all posts except those with `status: 'publishing'`; returns `{ deleted, kept }` |+| GET | `/api/process-scheduled` | `scheduledPostRoutes.ts`, `scheduledPostController.publishDuePosts` | Manual trigger - runs `scheduledPublisher.publishDue()` immediately for every user's due posts (dev/test) |+| POST | `/api/process-scheduled` | `scheduledPostRoutes.ts`, `scheduledPostController.publishDuePosts` | Same as above |++Controllers call `AccountService` (adding) and `RedditAnalyticsService`.+| Method | Path | File | Purpose ||---|---|---|---|-| POST | `/api/accounts/reddit` | `routes/accounts.ts` | Add Reddit account by username + optional session cookie |-| GET | `/api/accounts/:id/reddit-analytics` | `routes/reddit.ts` | Fetch profile + posts + computed analytics; cached in Redis; 400 when the cookie or username is missing |-| GET | `/api/accounts/:id/reddit-posts` | `routes/reddit.ts` | Returns cached post list or live-fetched posts |+| POST | `/api/accounts/reddit` | `accountRoutes.ts`, `accountController.addRedditAccount` | Add Reddit account by username and session cookie (both required); 409 when already added |+| GET | `/api/accounts/:id/reddit-analytics` | `redditRoutes.ts`, `redditController.getRedditAnalytics` | Fetch profile + posts + computed analytics; cached in Redis; 400 when the cookie or username is missing |+| GET | `/api/accounts/:id/reddit-posts` | `redditRoutes.ts`, `redditController.getRedditPosts` | Returns cached post list or live-fetched posts |### Overview| Method | Path | File | Purpose ||---|---|---|---|-| GET | `/api/overview` | `routes/overview.ts` | Returns tracked content list + per-account analytics summary from Redis cache (no live API calls); used by the Overview dashboard to aggregate Total Content, Total Comments, Total Likes across all platforms |+| GET | `/api/overview` | `overviewRoutes.ts`, `overviewController.getOverview` | Returns tracked content list + per-account analytics summary from Redis cache (no live API calls in the response); accounts without a cache entry are warmed in the background with `waitUntil` and reported as `syncing`. Used by the Overview dashboard to aggregate Total Content, Total Comments, Total Likes across all platforms |### Tracked Content-Link detection and the manual views and image checks live in `services/trackedContent.ts`.+Controllers call `TrackedContentService`; link detection and the manual views and image checks live in `services/trackedContentRules.ts`.| Method | Path | File | Purpose ||---|---|---|---|-| GET | `/api/tracked-content` | `routes/trackedContent.ts` | List all tracked items for the current user (Reddit posts and YouTube videos) |-| POST | `/api/tracked-content` | `routes/trackedContent.ts` | Add a URL to track; auto-detects Reddit or YouTube; fetches live data immediately |-| PUT | `/api/tracked-content/:id` | `routes/trackedContent.ts` | Update `label`, `category`, `accountId`, `manualViews`, or `imageUrl` for a tracked item. `manualViews` and `imageUrl` are Reddit-only (400 for YouTube) and `null` clears either. `manualViews` must be a whole number of 0 or more; `imageUrl` must parse as an `https:` URL |-| DELETE | `/api/tracked-content/:id` | `routes/trackedContent.ts` | Remove a tracked item |-| POST | `/api/tracked-content/:id/refresh` | `routes/trackedContent.ts` | Re-fetch live data from Reddit or YouTube API for one tracked item |+| GET | `/api/tracked-content` | `trackedContentRoutes.ts`, `trackedContentController.listTrackedContent` | List all tracked items for the current user (Reddit posts and YouTube videos) |+| POST | `/api/tracked-content` | `trackedContentRoutes.ts`, `trackedContentController.addTrackedContent` | Add a URL to track; auto-detects Reddit or YouTube; fetches live data immediately; answers `201` |+| PUT | `/api/tracked-content/:id` | `trackedContentRoutes.ts`, `trackedContentController.updateTrackedContent` | Update `label`, `category`, `accountId`, `manualViews`, or `imageUrl` for a tracked item. `manualViews` and `imageUrl` are Reddit-only (400 for YouTube) and `null` clears either. `manualViews` must be a whole number of 0 or more; `imageUrl` must parse as an `https:` URL |+| DELETE | `/api/tracked-content/:id` | `trackedContentRoutes.ts`, `trackedContentController.deleteTrackedContent` | Remove a tracked item |+| POST | `/api/tracked-content/:id/refresh` | `trackedContentRoutes.ts`, `trackedContentController.refreshTrackedContent` | Re-fetch live data from Reddit or YouTube API for one tracked item |### Settings| Method | Path | File | Purpose ||---|---|---|---|-| GET | `/api/settings/github` | `routes/settings.ts` | Retrieve the scheduling repository (`repoOwner`, `repoName`, `branch`) for the current user |-| PUT | `/api/settings/github` | `routes/settings.ts` | Save the scheduling repository; rewrites `settings.github`, dropping any token an older version stored |+| GET | `/api/settings/github` | `settingsRoutes.ts`, `settingsController.getGithubSettings` | Retrieve the scheduling repository (`repoOwner`, `repoName`, `branch`) for the current user |+| PUT | `/api/settings/github` | `settingsRoutes.ts`, `settingsController.saveGithubSettings` | Save the scheduling repository; rewrites `settings.github`, dropping any token an older version stored |## Adding a New RouteSee `docs/features/NEW_API_ENDPOINT.md` for the complete workflow.**Quick checklist:**-1. Add the request and response types to `shared/types/`, then create `backend/routes/myFeature.ts` with `new Hono<AppEnv>()` (copy an existing route file as a template)-2. Export the router as default-3. Import and mount in `backend/server.ts` via `api.route('/', myFeatureRouter)`-4. Add all db operations to `backend/lib/db.ts`-5. Update `docs/architecture/backend/ROUTES.md` (this file)-6. Update `frontend/src/services/api.ts` with corresponding frontend methods that return the shared types, then run `npm run typecheck`+1. Add the request and response types to `shared/types/`+2. Add a parser to `backend/validators/` if the route takes a body or query+3. Add the query to a repository in `backend/repositories/` (user-scoped methods end in `ForUser`) and the logic to a service method+4. Add a controller with `controller.createHandlers(...)` in `backend/controllers/<feature>Controller.ts`+5. Add one line to the feature's route table in `backend/routes/`; a new table is added to the list in `routes/index.ts`+6. Wire a new service or repository in `backend/container.ts`+7. Update `docs/architecture/backend/ROUTES.md` (this file)+8. Update `frontend/src/services/api.ts` with corresponding frontend methods that return the shared types, then run `npm run typecheck`diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.mdindex 253b757..72847e7 100644--- a/docs/architecture/backend/SERVICES.md+++ b/docs/architecture/backend/SERVICES.md@@ -1,37 +1,113 @@# Backend Services-Services in `backend/services/` contain all logic for communicating with external APIs (YouTube, Instagram) and computing analytics. Route handlers call services; services never import from routes.+`backend/services/` holds two kinds of module:-## Shared analytics math (`backend/services/analyticsMath.ts`)+- **Feature services** at the top level (`accountService.ts`, `publishingService.ts`, ...). Each is a factory, `createXService(deps)`, that returns an object of methods. They hold the business rules: they find the user's records through repositories, call the platform modules, use the cache and throw typed errors from `lib/errors.ts`. Controllers call them; they never see the Hono context.+- **Platform modules** in `services/youtube/`, `services/instagram/` and `services/reddit/`. Plain functions that talk to one platform's API or compute analytics from its data. They know nothing about users, the database or the cache.-Pure helpers whose formulas are identical in the Instagram and Reddit analytics: `DAY_NAMES`, `DAY_MS`, `sumOf`, `roundedAverage`, `medianOf`, `countWithinDays` (inclusive `<=`), `postFrequency` (posts per week and month over the dated span), `consistencyScore` (coefficient of variation, needs 3 values), `bestToAverageRatio` (virality), `pickHighest` and `monthKey` (local time). YouTube keeps its own recency (strict `<`) and weekly consistency formulas: `youtubeAnalytics.ts` imports `DAY_MS`, `sumOf`, `roundedAverage` and `medianOf`, and `youtubeTrends.ts` imports `DAY_NAMES`, `DAY_MS` and `monthKey`.+Data access is not here: repositories in `backend/repositories/` own every Supabase query and Redis key (see `CACHING.md` and `docs/guidelines/SUPABASE.md`). Services never import from routes or controllers.++## Composition++`backend/container.ts` builds every repository and service for one request or one cron run:++```ts+export function createServices(clients: Clients, config: AppConfig, context: RequestContext): Services {+ const accounts = createAccountRepository(clients.supabase);+ const cache = createAnalyticsCacheRepository(clients.redis);+ // ...+ return {+ accounts: createAccountService({ accounts, cache, config, context }),+ // ...+ };+}+```++A service receives only what it uses: repositories, the cleaned `AppConfig` from `lib/config.ts`, and the `RequestContext` (`requestId`, `signal`, `log`). Every platform call is passed `context.signal`, so abandoned work stops when the client disconnects or the deadline passes. Tests build a service the same way with fake repositories or the fake Supabase client.++## Feature Services++| Service (key in `Services`) | File | Repositories | Methods |+|---|---|---|---|+| `accounts` | `accountService.ts` | accounts, cache | `list`, `resolveChannel`, `addYouTube`, `addReddit`, `addInstagram`, `refresh`, `refreshAll`, `refreshInstagramToken`, `remove` |+| `youtubeAnalytics` | `youtubeAnalyticsService.ts` | accounts, cache | `channelAnalytics`, `channelVideos`, `comparison`, `videoLibrary` |+| `instagramAnalytics` | `instagramAnalyticsService.ts` | accounts, cache | `analytics`, `media` |+| `redditAnalytics` | `redditAnalyticsService.ts` | accounts, cache | `analytics`, `posts` |+| `publishing` | `publishingService.ts` | accounts | `cloudinaryConfig`, `publishingLimit`, `createContainer`, `containerStatus`, `publishContainer` |+| `scheduledPosts` | `scheduledPostService.ts` | scheduled posts (and the publisher) | `list`, `create`, `update`, `remove`, `removeAll`, `publishDueNow` |+| `scheduledPublisher` | `scheduledPublisher.ts` | accounts, scheduled posts | `publishDue` (every user's due posts; cron and manual trigger) |+| `tokenRefresh` | `tokenRefreshService.ts` | accounts | `refreshExpiringInstagramTokens` (daily cron) |+| `trackedContent` | `trackedContentService.ts` | accounts, tracked posts | `list`, `add`, `update`, `remove`, `refresh` |+| `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` |++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`).++### Accounts (`accountService.ts`, `accountFactory.ts`)++`accountFactory.ts` holds pure builders: `newAccountId`, `tokenExpiryIso` (null without a lifetime), `buildYouTubeAccount`, `buildRedditAccount`, `buildInstagramAccount`.++`AccountService`:++- `addYouTube`, `addReddit` and `addInstagram` throw `ConflictError` (409) for an account the user already has. `addInstagram` tries the long-lived token exchange when `INSTAGRAM_APP_SECRET` is set and keeps the pasted token if it fails.+- `refresh` and `refreshAll` check the fields the platform call needs first (an Instagram token, a Reddit username and cookie, a YouTube channel id) and throw `ValidationError` (400) when one is missing; a missing YouTube key is a `NotConfiguredError` (503). A single refresh updates more fields than refresh-all. `refreshAll` uses `Promise.allSettled`, so one failure does not stop the rest, and its `results` line up with the account list by index.+- `remove` deletes the account row and its cache entries.++`YouTubeAnalyticsService.channelAnalytics` fills channel fields for a YouTube account without `publishedAt` the first time its analytics load; a failure is logged and skipped.++### Tracked content (`trackedContentService.ts`, `trackedContentRules.ts`)++`trackedContentRules.ts` holds the pure rules: `detectContentType(url)` (`reddit`, `youtube` or `null`), `manualViewsPatch(value, isYouTube)` and `imageUrlPatch(value, isYouTube)`. The two patch helpers return `{ patch }` to merge into the item's `data`, or `{ error }`, which the service throws as a `ValidationError`. Empty values clear the field, YouTube items refuse both, views must be whole numbers of 0 or more, and images must be `https` URLs.++### Overview summary (`overviewService.ts`)++`summary(userId)` reads each account's cache entry in parallel (`Promise.allSettled`) and returns `{ tracked, analyticsCache, warmTasks }`. A warm account gets its totals (`cacheWarmed: true`); an account with no cache gets `cacheWarmed: false`, and when Redis and the account's credentials are present its background fetch starts at once and `syncing` is `true`. An account whose cache read fails is left out of `analyticsCache`. Warming outlives the response, so it uses its own 25 second deadline instead of the request signal; the controller passes `warmTasks` to `waitUntil` so the response never waits for them.++### Instagram OAuth (`instagramConnectService.ts`, `instagram/instagramOAuth.ts`)++`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.++### 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.++`scheduledPublisher.publishDue()` lists due posts, claims each one atomically (`pending` to `publishing`, so the GitHub Actions scheduler and the cron never publish the same post), creates the container, waits for Reels and Stories to finish processing, publishes, and marks the post `published` or `failed`. See `docs/architecture/data-flows/SCHEDULING.md`.++---++## Shared analytics math (`backend/lib/analyticsMath.ts`)++Pure helpers whose formulas are identical in the Instagram and Reddit analytics: `DAY_NAMES`, `DAY_MS`, `sumOf`, `roundedAverage`, `medianOf`, `countWithinDays` (inclusive `<=`), `postFrequency` (posts per week and month over the dated span), `consistencyScore` (coefficient of variation, needs 3 values), `bestToAverageRatio` (virality), `pickHighest`, `monthKey` (local time), and `reportedCount` and `percentOfReportedViews` for counts a platform may hide. YouTube keeps its own recency (strict `<`) and weekly consistency formulas: `youtubeAnalytics.ts` imports `DAY_MS`, `sumOf`, `roundedAverage`, `medianOf` and `reportedCount`, and `youtubeTrends.ts` imports `DAY_NAMES`, `DAY_MS`, `monthKey`, `reportedCount` and `percentOfReportedViews`.----## Instagram (`backend/services/instagram*.ts`)+## Instagram (`backend/services/instagram/`)-`services/instagram.ts` is a barrel that re-exports the public names below, so routes and the scheduler import from it unchanged. Tests in `backend/tests/services/` import the individual modules directly. Each module imports its siblings directly, never the barrel.+There is no barrel: services and tests import each module directly, and each module imports its siblings directly.| Module | Contents ||---|---|-| `instagramApi.ts` | `igFetch(endpoint, params, retries)` transport (15 s timeout, one retry on abort, `EAI_AGAIN` or `ECONNRESET`, no API version prefix for `/oauth`, `/access_token`, `/refresh_access_token`) and `fetchInstagramProfile` |-| `instagramTokens.ts` | `exchangeForLongLivedToken`, `refreshLongLivedToken`, `autoRefreshInstagramTokens` |+| `instagramApi.ts` | `igFetch(endpoint, params, retries, signal)` GET transport (15 s timeout, one retry on a network blip, never after the request signal aborted; no API version prefix for `/oauth`, `/access_token`, `/refresh_access_token`), `igPost(endpoint, params, signal)` (never retried, so a publish cannot run twice), `readGraphResponse` and `fetchInstagramProfile` |+| `instagramTokens.ts` | `exchangeForLongLivedToken`, `refreshLongLivedToken` |+| `instagramOAuth.ts` | `isOAuthConfigured`, `buildAuthorizationUrl`, `exchangeCodeForToken`, `upgradeToLongLivedToken` || `instagramMedia.ts` | `classifyInstagramMedia`, `extractInstagramViews`, `normalizeInstagramMedia`, paged `fetchInstagramMedia` || `instagramContentTypes.ts` | `CONTENT_TYPES`, `summarizeContentTypes`, per type stats used by the analytics || `instagramTiming.ts` | Posts by day of week and hour, best posting day and hour, monthly breakdown || `instagramCaptions.ts` | Hashtag analysis and caption length correlation || `instagramAnalytics.ts` | `computeInstagramAnalytics` orchestrator, the empty state and the engagement, views and ranking helpers |-| `instagramPublishing.ts` | `buildMediaParams`, one helper per media type |+| `instagramPublishing.ts` | `buildMediaParams` (one helper per media type) and the Graph publishing calls: `createMediaContainer`, `fetchContainerStatus`, `publishMediaContainer`, `fetchPublishingLimit` |++A Graph API error becomes an `UpstreamError` (502) with Instagram's message; a cancelled or timed out call becomes an `UpstreamTimeoutError` (504).### Key Functions| Function | Purpose ||---|---|-| `fetchInstagramProfile(igUserId, accessToken)` | Fetches the profile for an account id, or for `/me` when `igUserId` is null |-| `exchangeForLongLivedToken(shortToken, appSecret)` | Short-lived -> 60-day long-lived token |-| `refreshLongLivedToken(accessToken)` | Extends a long-lived token; call before expiry |-| `autoRefreshInstagramTokens(supabase)` | Cron handler - refreshes all tokens expiring within 15 days |-| `fetchInstagramMedia(igUserId, accessToken, limit)` | Paginates media (50 per page, 10 pages max) up to `limit` (default 500), requesting `views` insights inline; returns normalized items |+| `fetchInstagramProfile(igUserId, accessToken, signal)` | Fetches the profile for an account id, or for `/me` when `igUserId` is null |+| `exchangeForLongLivedToken(shortToken, appSecret, signal)` | Short-lived -> 60-day long-lived token |+| `refreshLongLivedToken(accessToken, signal)` | Extends a long-lived token; call before expiry. The daily cron calls it through `tokenRefresh.refreshExpiringInstagramTokens()` for every token expiring within 15 days |+| `fetchInstagramMedia(igUserId, accessToken, limit, signal)` | Paginates media (50 per page, 10 pages max) up to `limit` (default 500), requesting `views` insights inline; returns normalized items || `classifyInstagramMedia(raw)` | Returns `'reel'`, `'post'`, or `'video'` for a raw Graph API media item || `extractInstagramViews(raw)` | Reads the `views` insight from a raw item; `null` when Instagram reports none || `normalizeInstagramMedia(raw)` | Maps a raw item to the cached media shape (`contentType`, `viewCount`, counts, URLs) |@@ -71,32 +147,32 @@ export function safeAccount(account: Account): SafeAccount {}```-**This function must be applied to every account object before it leaves the backend.** Route handlers are responsible for calling `safeAccount()` or using `db.getAccounts()` variants that apply it.+**This function must be applied to every account object before it leaves the backend.** Repositories return full `Account` objects; controllers call `safeAccount()` on every account they put in a response, and services that return accounts inside a larger result (the comparison, Instagram analytics) apply it themselves.----## YouTube (`backend/services/youtube*.ts`)+## YouTube (`backend/services/youtube/`)-`services/youtube.ts` is a barrel that re-exports `resolveChannelId`, `fetchChannelData`, `fetchAllVideos`, `fetchTrackedYouTubeData` and `computeVideoAnalytics`, so importers are unchanged.+There is no barrel: services and tests import each module directly.| Module | Contents ||---|---|-| `youtubeApi.ts` | `ytFetch(endpoint, params, apiKey)` (adds `key` to the params object it is given; errors carry `reason` and `status`) and `optionalCount` (null for a hidden or missing count) |+| `youtubeApi.ts` | `ytFetch(endpoint, params, apiKey, signal)` (adds `key` to the params object it is given; an API error becomes an `UpstreamError` carrying `reason` and `status`, a cancelled call an `UpstreamTimeoutError`) and `optionalCount` (null for a hidden or missing count) || `youtubeChannels.ts` | Channel id extraction from URLs and handles, the handle, username, search lookup chain, `resolveChannelId`, `fetchChannelData` || `youtubeVideos.ts` | `normalizeYouTubeVideo`, the playlist page fetch that treats `playlistNotFound` as no videos, `fetchAllVideos` || `youtubeTracked.ts` | `extractYouTubeVideoId`, `fetchTrackedYouTubeData` || `youtubeFormat.ts` | `parseDuration`, `formatCompact`, `formatDuration`, `formatVideoSummary` || `youtubeAnalytics.ts` | `computeVideoAnalytics` orchestrator, the empty state, totals, durations, rankings, Shorts split, format flags || `youtubeTrends.ts` | Publish day and hour distribution, categories, tags, recency counts, upload frequency, weekly consistency, views histogram, monthly trends |-| `youtubeLibrary.ts` | Pure helpers for `routes/analytics.ts`: `channelMetrics` (channel age, ratios and estimates; a channel without `publishedAt` counts as 365 days old), `accountComparison` (rankings and totals for `/comparison`), `filterAndSortVideos` (search, view range and sort for `/videos/all`) |+| `youtubeLibrary.ts` | Pure helpers for `YouTubeAnalyticsService`: `channelMetrics` (channel age, ratios and estimates; a channel without `publishedAt` counts as 365 days old), `accountComparison` (rankings and totals for `/comparison`), `filterAndSortVideos` (search, view range and sort for `/videos/all`) |### Key Functions| Function | Purpose ||---|---|-| `resolveChannelId(input, apiKey)` | Resolves a YouTube URL, handle, or channel ID to a canonical channel ID |-| `fetchChannelData(channelId, apiKey)` | Fetches channel snippet, statistics, and branding |-| `fetchAllVideos(playlistId, apiKey, maxPages)` | Paginates through playlist items API (50 per page, up to 10 pages = 500 videos) + batch-fetches video statistics |+| `resolveChannelId(input, apiKey, signal)` | Resolves a YouTube URL, handle, or channel ID to a canonical channel ID |+| `fetchChannelData(channelId, apiKey, signal)` | Fetches channel snippet, statistics, and branding |+| `fetchAllVideos(playlistId, apiKey, maxPages, signal)` | Paginates through playlist items API (50 per page, up to 10 pages = 500 videos) + batch-fetches video statistics || `computeVideoAnalytics(videos)` | Computes 50+ analytics metrics from the video dataset; captures the current time once and passes it to the trend helpers |### Analytics Computation@@ -110,7 +186,7 @@ export function safeAccount(account: Account): SafeAccount {- Monthly breakdown of uploads and views- Category distribution-`computeInstagramAnalytics()` (in `instagramAnalytics.ts`) returns:+`computeInstagramAnalytics()` (in `instagram/instagramAnalytics.ts`) returns:- Engagement rate (likes + comments / followers)- Average likes, comments per post- Best performing post@@ -121,20 +197,20 @@ export function safeAccount(account: Account): SafeAccount {----## `backend/services/reddit.ts`+## Reddit (`backend/services/reddit/`)### HTTP Client-`reddit.ts` holds the API code. All Reddit public JSON API calls go through `redditFetch(path, cookie)`, and `normalizeRedditPost()` maps each submitted post to the cached post shape. Requests include a descriptive `User-Agent` header (required by Reddit). Cookie is optional - if provided, it is sent as `Cookie: reddit_session=<value>` for private account access and higher rate limits.+`redditApi.ts` holds the API code. All Reddit public JSON API calls go through `redditFetch(path, cookie, signal)`, and `normalizeRedditPost()` maps each submitted post to the cached post shape. Requests include a descriptive `User-Agent` header (required by Reddit). When a cookie is passed, it is sent as `Cookie: reddit_session=<value>` for private account access and higher rate limits. A 404 becomes a `NotFoundError` (the user does not exist); a 403 (expired cookie), a 429 and other failures become an `UpstreamError` with a message that says what to do.### Key Functions| Function | Purpose ||---|---|-| `fetchRedditProfile(username, cookie)` | Fetches profile data from `/user/{username}/about.json` |-| `fetchRedditPosts(username, cookie, limit)` | Paginates submitted posts up to `limit` (default 100) via `/user/{username}/submitted.json` |-| `computeRedditAnalytics(profile, posts)` | Lives in `redditAnalytics.ts` (re-exported by `reddit.ts`); computes score stats, subreddit breakdown, media type distribution, posting time patterns, monthly breakdown, virality/consistency scores using the shared helpers in `analyticsMath.ts` |-| `fetchTrackedPostData(postUrl, cookie)` | Fetches score, comments, and metadata for any public Reddit post URL using the `.json` trick; optionally uses a session cookie |+| `fetchRedditProfile(username, cookie, signal)` | Fetches profile data from `/user/{username}/about.json` |+| `fetchRedditPosts(username, cookie, limit, signal)` | Paginates submitted posts up to `limit` (default 100) via `/user/{username}/submitted.json` |+| `computeRedditAnalytics(profile, posts)` | Lives in `redditAnalytics.ts` (re-exported by `redditApi.ts`); computes score stats, subreddit breakdown, media type distribution, posting time patterns, monthly breakdown, virality/consistency scores using the shared helpers in `lib/analyticsMath.ts` |+| `fetchTrackedPostData(postUrl, cookie, signal)` | Fetches score, comments, and metadata for any public Reddit post URL using the `.json` trick; optionally uses a session cookie |### Credentials in responses@@ -146,49 +222,25 @@ Reddit integration requires no Worker secrets. The session cookie is a per-user----## Accounts (`accountFactory.ts`, `accountConnect.ts`, `accountRefresh.ts`)--The account routes in `routes/accounts.ts` only parse the request, check required fields and shape the response; the work lives here.--| Module | Contents |-|---|---|-| `accountFactory.ts` | Pure builders: `newAccountId`, `tokenExpiryIso` (null without a lifetime), `buildYouTubeAccount`, `buildRedditAccount`, `buildInstagramAccount` |-| `accountConnect.ts` | `addYouTubeAccount`, `addRedditAccount`, `addInstagramAccount` (tries the long-lived exchange when `INSTAGRAM_APP_SECRET` is set and keeps the pasted token if it fails), `refreshInstagramToken` |-| `accountRefresh.ts` | `fetchAccountUpdates` (profile fields per platform; a single refresh updates more fields than refresh-all), `refreshAccount`, `refreshAllAccounts` (both check the fields the platform call needs first: an Instagram token, a Reddit username and cookie, a YouTube channel id and API key) (`Promise.allSettled`, results aligned with the account list by index), `backfillChannelData` (fills channel fields for a YouTube account without `publishedAt` when its analytics load; a failure is logged and skipped) |--Duplicate accounts throw an `Error` whose message the route returns with status 400, the same shape as any other failure. Failures that need another status (404 for a missing account, 400 for a missing credential) come back as `{ failure: { status, message } }`.-------## Tracked content (`trackedContent.ts`)--Pure rules for `routes/trackedContent.ts`: `detectContentType(url)` (`reddit`, `youtube` or `null`), `manualViewsPatch(value, isYouTube)` and `imageUrlPatch(value, isYouTube)`. The two patch helpers return `{ patch }` for the route to merge into the item's `data`, or `{ error }` for a 400 response. Empty values clear the field, YouTube items refuse both, views must be whole numbers of 0 or more, and images must be `https` URLs.-------## Overview summary (`overviewSummary.ts`)--Used by `routes/overview.ts`. `summarizeAccountCaches(accounts, { redis, userId, apiKey })` reads each account's Redis cache in parallel (`Promise.allSettled`) and returns `{ analyticsCache, warmTasks }`. A warm account gets its totals (`cacheWarmed: true`); an account with no cache gets `cacheWarmed: false`, and when Redis and the account's credentials are present its background fetch starts at once and `syncing` is `true`. An account whose cache read fails is left out of `analyticsCache`. The route passes `warmTasks` to `waitUntil` so the response never waits for them.-------## Instagram OAuth (`instagramOAuth.ts`)+## Shared Instagram publishing parameters-Used by `routes/instagramAuth.ts`. `readInstagramOAuthConfig(env)` 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`. `buildAuthorizationUrl` signs the state with the app secret. `connectInstagramFromOAuth` 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 route turns those into the `ig_error` and `ig_connected` redirects.+`buildMediaParams(post, accessToken)` in `services/instagram/instagramPublishing.ts` builds the Graph API container parameters for photos, Reels, Stories and carousel items. The same file holds the Graph calls both publishers make: `createMediaContainer`, `fetchContainerStatus`, `publishMediaContainer` and `fetchPublishingLimit`. `PublishingService` (publish now) and `scheduledPublisher` (the cron and the manual trigger) both call them. `scripts/publish-scheduled.ts` keeps its own copy on purpose: it runs in GitHub Actions with zero npm dependencies and cannot import Worker code.----## Shared Instagram publishing parameters+## Adding a New Service-`buildMediaParams(post, accessToken)` in `services/instagramPublishing.ts` (re-exported by `services/instagram.ts`) builds the Graph API container parameters for photos, Reels, Stories and carousel items. The publish route (`routes/publishing.ts`) and the cron scheduler (`utils/scheduler.ts`) both call it. `scripts/publish-scheduled.ts` keeps its own copy on purpose: it runs in GitHub Actions with zero npm dependencies and cannot import Worker code.+For a new platform:----+1. Create a folder `backend/services/myPlatform/` with an API module (`myPlatformApi.ts`) whose internal fetch helper handles the base URL, auth headers and error extraction, accepts an `AbortSignal`, casts the parsed JSON to the expected payload type once, and throws `UpstreamError` for a platform error and `UpstreamTimeoutError` for a cancelled call+2. Describe the raw upstream payloads with interfaces in the module (covering only the fields the code reads), and put the shapes the API returns in `shared/types/`+3. Export named functions for each operation (fetch data, exchange tokens, compute analytics), each with a declared return type; keep analytics computation in its own pure module+4. If the platform requires OAuth, add token exchange functions following `instagram/instagramOAuth.ts`-## Adding a New Service+For a new feature service:-1. Create `backend/services/myPlatform.ts`-2. Define an internal fetch helper (`myPlatformFetch<T>()`) that handles base URL, auth headers, and error extraction, and casts the parsed JSON to the expected payload type once-3. Describe the raw upstream payloads with interfaces in the service file (covering only the fields the code reads), and put the shapes the API returns in `shared/types/`-4. Export named functions for each operation (fetch data, exchange tokens, compute analytics), each with a declared return type-5. If the platform requires OAuth, add token exchange functions following the Instagram pattern-6. Update `docs/architecture/backend/SERVICES.md` (this file)+1. Create `backend/services/myFeatureService.ts` exporting a `MyFeatureDeps` interface, a `MyFeatureService` interface and `createMyFeatureService(deps)`+2. Take repositories, `config` and `context` as dependencies; never import the Supabase or Redis client, and never read the Hono context+3. Throw typed errors from `lib/errors.ts`; never return error objects+4. Add it to `Services` and `createServices()` in `backend/container.ts`+5. Update `docs/architecture/backend/SERVICES.md` (this file)diff --git a/docs/architecture/cloudflare/CI_CD.md b/docs/architecture/cloudflare/CI_CD.mdindex 81cfcea..e93c95f 100644--- a/docs/architecture/cloudflare/CI_CD.md+++ b/docs/architecture/cloudflare/CI_CD.md@@ -47,6 +47,8 @@ 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`.+**Does not** redeploy on frontend-only changes, documentation changes, or script changes.---diff --git a/docs/architecture/cloudflare/PAGES.md b/docs/architecture/cloudflare/PAGES.mdindex eda50ee..e1bfb5b 100644--- a/docs/architecture/cloudflare/PAGES.md+++ b/docs/architecture/cloudflare/PAGES.md@@ -68,6 +68,8 @@ The app is accessible at both:- `twiligent.pages.dev` (Cloudflare Pages default)- Custom domain configured in Cloudflare Pages -> Custom domains+The Worker's CORS policy only answers the origins it knows: `FRONTEND_URL` and the comma-separated `ALLOWED_ORIGINS` Worker secrets. Set `FRONTEND_URL` to the main address and list any other address the site is served from (such as `pages.dev` next to a custom domain) in `ALLOWED_ORIGINS`, or the browser blocks the API calls from that address. See `WORKERS.md`.+## Local DevelopmentFrom the repository root, start the Vite dev server (port 5173) and the backend Worker (port 8787) together:@@ -76,7 +78,7 @@ From the repository root, start the Vite dev server (port 5173) and the backendnpm run dev```-The frontend calls the Worker at `VITE_API_URL`, which defaults to `http://localhost:8787/api` when unset (see `frontend/src/services/api.ts`); Vite does not proxy requests. To run the frontend alone, use `npm run dev:frontend`.+The frontend calls the Worker at `VITE_API_URL`, which defaults to `http://localhost:8787/api` when unset (see `frontend/src/services/api.ts`); Vite does not proxy requests. A Worker running on `localhost` allows the Vite dev server origin (`http://localhost:5173` or `http://127.0.0.1:5173`) without any setting. To run the frontend alone, use `npm run dev:frontend`.## First-Time Setupdiff --git a/docs/architecture/cloudflare/WORKERS.md b/docs/architecture/cloudflare/WORKERS.mdindex 2d5377e..578a7b5 100644--- a/docs/architecture/cloudflare/WORKERS.md+++ b/docs/architecture/cloudflare/WORKERS.md@@ -22,20 +22,20 @@ The Worker exports two handlers:```tsexport default {- fetch: app.fetch, // handles HTTP requests (the Hono app)+ fetch: app.fetch, // handles HTTP requests (the Hono app from backend/app.ts)async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) { // handles cron triggers- // event.cron - the cron expression that fired- // env - Worker environment bindings (secrets + vars)- // ctx.waitUntil(promise) - keeps Worker alive for background work+ ctx.waitUntil(runScheduledJob(event.cron, env));},} satisfies ExportedHandler<Env>;```+`event.cron` is the cron expression that fired, `env` holds the Worker secrets and variables, and `ctx.waitUntil(promise)` keeps the Worker alive for the job. `runScheduledJob()` in `backend/jobs/scheduled.ts` picks the job for the expression; see `docs/architecture/backend/CRON.md`.+`ScheduledController`, `ExecutionContext` and `ExportedHandler` come from `@cloudflare/workers-types`, which `backend/tsconfig.json` loads as its only ambient types.## Environment Bindings (Secrets)-All secrets are set via `npx wrangler secret put <NAME>`, run from `backend/`. They are available at runtime as `env.NAME` or `c.env.NAME`, typed by the `Env` interface in `backend/types/env.ts`. The three Supabase values are declared as `string`; the rest are optional (`?: string`), so code that reads them handles the missing case.+All secrets are set via `npx wrangler secret put <NAME>`, run from `backend/`. They are available at runtime as `env.NAME` or `c.env.NAME`, typed by the `Env` interface in `backend/types/env.ts`. The three Supabase values are declared as `string`; the rest are optional (`?: string`), so code that reads them handles the missing case. Application code reads them through `readConfig(env)` in `backend/lib/config.ts`, which trims stray whitespace and byte order marks; a request that needs a missing optional value fails with `503` (`NOT_CONFIGURED`).| Secret | Required | Purpose ||---|---|---|@@ -48,7 +48,8 @@ All secrets are set via `npx wrangler secret put <NAME>`, run from `backend/`. T| `CLOUDINARY_CLOUD_NAME` | Yes | Cloudinary cloud name || `CLOUDINARY_UPLOAD_PRESET` | Yes | Unsigned upload preset for direct browser uploads || `BACKEND_URL` | Yes | This Worker's public URL (for OAuth callback construction) |-| `FRONTEND_URL` | Yes | Frontend URL (for post-OAuth redirect back to the SPA) |+| `FRONTEND_URL` | Yes | Frontend URL: the browser origin CORS allows, and the post-OAuth redirect back to the SPA |+| `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 |@@ -76,12 +77,17 @@ CLOUDINARY_CLOUD_NAME=mycloudCLOUDINARY_UPLOAD_PRESET=ml_defaultBACKEND_URL=http://localhost:8787FRONTEND_URL=http://localhost:5173+# ALLOWED_ORIGINS=https://another-domain.example.comUPSTASH_REDIS_REST_URL=https://...UPSTASH_REDIS_REST_TOKEN=...```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.+### CORS origins++The API answers browsers only on `FRONTEND_URL` and the origins in `ALLOWED_ORIGINS`; a browser on any other origin is blocked. A Worker served from `localhost` or `127.0.0.1` also allows the Vite dev server (`http://localhost:5173` and `http://127.0.0.1:5173`), so local development needs no extra setting. Requests without an `Origin` header (curl, the GitHub Actions scheduler) are not affected. See `docs/architecture/backend/MIDDLEWARE.md`.+## Worker ConstraintsThese are hard constraints imposed by the Cloudflare Workers runtime. Violating them causes runtime errors:@@ -90,7 +96,7 @@ These are hard constraints imposed by the Cloudflare Workers runtime. Violating2. **No binary file handling.** The Worker cannot efficiently stream large binary files. Never add routes that accept file uploads - Cloudinary handles that directly from the browser.-3. **No persistent state between requests.** The Worker isolate may be a fresh instance on every request. Do not rely on module-level variables to persist state across requests. All state must come from Supabase, Redis, or Worker KV.+3. **No persistent state between requests.** The Worker isolate may be a fresh instance on every request. Do not rely on module-level variables to persist state across requests. All state must come from Supabase, Redis, or Worker KV. (The cache cooldown and the rate limiter's memory fallback keep per-isolate state on purpose, as a best-effort optimization that is safe to lose.)4. **CPU time limit.** Workers have a CPU time limit per request (typically 50ms on free tier, up to 30s on paid). Long-running synchronous operations will be killed. Use async/await for all I/O.@@ -100,7 +106,7 @@ These are hard constraints imposed by the Cloudflare Workers runtime. Violating## Adding a New Worker Secret-1. Declare it in the `Env` interface in `backend/types/env.ts` (`NEW_SECRET_NAME?: string` unless the Worker cannot run without it)+1. Declare it in the `Env` interface in `backend/types/env.ts` (`NEW_SECRET_NAME?: string` unless the Worker cannot run without it), and read it into `AppConfig` in `backend/lib/config.ts` with `cleanSecret()`2. Set via `npx wrangler secret put NEW_SECRET_NAME` from `backend/`3. Add to `backend/.env.example` with a placeholder value4. Add to `backend/.dev.vars` locallydiff --git a/docs/architecture/data-flows/ANALYTICS.md b/docs/architecture/data-flows/ANALYTICS.mdindex 68e0fec..d4bd72c 100644--- a/docs/architecture/data-flows/ANALYTICS.md+++ b/docs/architecture/data-flows/ANALYTICS.md@@ -10,23 +10,23 @@ ChannelAnalytics.tsx mounts -> api.getAnalytics(id)-> GET /api/accounts/:id/analytics│▼- Worker: analyticsRouter- 1. getAccountById(supabase, id, userId) - verify ownership- 2. redis cache check: getVideosCache(redis, userId, id)- -> cache hit: return cached data immediately- -> cache miss: continue- 3. Fetch from YouTube Data API:- a. GET /channels?part=snippet,statistics,contentDetails&id={channelId}- -> channel metadata + subscriber/view/video counts + uploadPlaylistId- b. Paginate /playlistItems?part=contentDetails&playlistId={uploadPlaylistId}+ Worker: analyticsRoutes -> analyticsController.getChannelAnalytics+ -> youtubeAnalytics.channelAnalytics(userId, id) [services/youtubeAnalyticsService.ts]+ 1. 503 when the Worker has no YouTube API key+ 2. accounts.findForUser(id, userId) - verify ownership+ -> 404 unless it is a YouTube channel, 400 when no uploads playlist is stored+ 3. Fetch from YouTube Data API (always live; the cache is written, not read):+ a. Paginate /playlistItems?part=contentDetails&playlistId={uploadsPlaylistId}-> up to 10 pages × 50 items = 500 video IDs- c. Batch /videos?part=snippet,statistics&id={id1,id2,...}+ b. Batch /videos?part=snippet,statistics&id={id1,id2,...}-> 50 videos per batch request -> statistics (views, likes, comments, duration)- 4. computeVideoAnalytics(videos, channel)+ 4. cache.setVideos(userId, id, { videos, fetchedAt })+ -> GET /api/accounts/:id/videos and the video library read this entry+ 5. computeVideoAnalytics(videos)-> 50+ computed metrics- 5. setVideosCache(redis, userId, id, result)- -> cache result for future requests- 6. Return JSON+ 6. For an account without publishedAt, fetch /channels once and save the+ channel fields (a failure is logged and skipped)+ 7. Return JSON```### computeVideoAnalytics() Output (partial)@@ -92,8 +92,10 @@ InstagramAnalytics.tsx mounts -> api.getIGAnalytics(id)-> GET /api/accounts/:id/ig-analytics│▼- Worker: analyticsRouter- 1. getAccountById(supabase, id, userId) - verify ownership + get accessToken+ Worker: analyticsRoutes -> analyticsController.getInstagramAnalytics+ -> instagramAnalytics.analytics(userId, id) [services/instagramAnalyticsService.ts]+ 1. accounts.findForUser(id, userId) - verify ownership + get accessToken+ -> 404 unless it is an Instagram account, 400 without a stored token2. Fetch from Instagram Graph API (always live; the cache is written, not read):a. GET /{igUserId}?fields=user_id,username,name,followers_count,follows_count,media_count,...-> profile data@@ -103,7 +105,7 @@ InstagramAnalytics.tsx mounts -> api.getIGAnalytics(id)-> up to 500 media items (10 pages x 50)-> a page that fails with insights is refetched without them (viewCount: null)c. normalizeInstagramMedia() classifies each item as reel, post, or video- 3. setIGCache(redis, userId, id, { media, fetchedAt }) and update account counts+ 3. cache.setInstagramMedia(userId, id, { media, fetchedAt }) and update account counts4. computeInstagramAnalytics(profile, media)5. Return JSON@@ -160,19 +162,21 @@ RedditAnalytics.tsx mounts -> api.getRedditAnalytics(id)-> GET /api/accounts/:id/reddit-analytics│▼- Worker: redditRouter- 1. getAccountById(supabase, id, userId) - verify ownership- 2. redis cache check: key reddit:{userId}:{accountId}+ Worker: redditRoutes -> redditController.getRedditAnalytics+ -> redditAnalytics.analytics(userId, id) [services/redditAnalyticsService.ts]+ 1. accounts.findForUser(id, userId) - verify ownership+ -> 404 unless it is a Reddit account, 400 without a stored cookie or username+ 2. cache.getReddit(userId, id): key reddit:{userId}:{accountId}-> cache hit: return immediately-> cache miss: continue- 3. Fetch from Reddit public JSON API (with optional session cookie):+ 3. Fetch from Reddit public JSON API (with the stored session cookie):a. GET /user/{username}/about.json-> profile: totalKarma, postKarma, commentKarma, awardeeKarma, iconUrl, createdAt- b. Paginate /user/{username}/submitted.json?limit=100- -> up to 10 pages x 100 items = up to 1000 posts+ b. GET /user/{username}/submitted.json?limit=100&sort=new+ -> up to 100 posts4. computeRedditAnalytics(profile, posts)-> score stats, subreddit breakdown, timing analysis- 5. Cache result in Redis+ 5. cache.setReddit(userId, id, result)6. Return { profile, analytics, posts } (RedditCacheData)```diff --git a/docs/architecture/data-flows/AUTHENTICATION.md b/docs/architecture/data-flows/AUTHENTICATION.mdindex 77e85a6..c8be34a 100644--- a/docs/architecture/data-flows/AUTHENTICATION.md+++ b/docs/architecture/data-flows/AUTHENTICATION.md@@ -88,7 +88,9 @@ requireAuth middleware-> On success: { user: { id, email } }-> c.set('userId', user.id)-> c.set('userEmail', user.email)- -> await next() -> route handler executes+ -> await next() -> per-user rate limits, route table, controller+ -> On a missing, invalid or expired token: throws UnauthorizedError+ -> errorHandler answers 401 { success: false, code: 'UNAUTHORIZED', message, requestId }```## Sign Out Flowdiff --git a/docs/architecture/data-flows/PUBLISHING.md b/docs/architecture/data-flows/PUBLISHING.mdindex fa7dcd2..dce695c 100644--- a/docs/architecture/data-flows/PUBLISHING.md+++ b/docs/architecture/data-flows/PUBLISHING.md@@ -17,7 +17,7 @@ User selects account + uploads media + fills caption2. Frontend: Create media containerapi.createIGContainer(accountId, { mediaUrl, caption, mediaType, ... })-> POST /api/accounts/:id/ig-publish- -> Backend: calls Instagram Graph API+ -> Backend: publishing.createContainer() -> buildMediaParams() and createMediaContainer()POST https://graph.instagram.com/v25.0/{igUserId}/mediaparams: { image_url|video_url, caption, media_type, access_token }-> 404 when the account is not an Instagram account of this user, 400 when it has no stored token@@ -56,12 +56,13 @@ User creates a scheduled post▼1. Frontend: api.createScheduledPost({ accountId, scheduledAt, mediaUrl, caption, ... })-> POST /api/scheduled-posts- -> Backend: db.createPost(supabase, post, userId)+ -> Backend: scheduledPosts.create(userId, request) -> posts.create(post, userId)+ (400 unless scheduledAt is a future date)INSERT INTO scheduled_posts (id, user_id, account_id, status='pending', scheduled_at, data)│▼2. Every 15 minutes, one of two schedulers fires:- A. Cloudflare Worker cron -> processScheduledPosts(supabase)+ A. Cloudflare Worker cron -> runScheduledJob() -> scheduledPublisher.publishDue()B. GitHub Actions -> node scripts/publish-scheduled.ts -> direct Supabase REST calls│▼@@ -100,6 +101,6 @@ User creates a scheduled post|---|---|---|| Container `ERROR` | Instagram processing failed (bad codec, too long, etc.) | User must re-upload || Container `EXPIRED` | >24 hours since container was created | User must re-create container |-| `media_publish` 400 | Usually quota exceeded or invalid containerId | Check publishing limit |+| `media_publish` rejected | Usually quota exceeded or invalid containerId; the Worker answers 502 (`UPSTREAM_ERROR`) with Instagram's message | Check publishing limit || Processing timeout | The container was still processing after the last poll | Try again later, or use a shorter or smaller video || `status=failed` in scheduled post | Any of the above, plus `accessToken` expired | Re-connect the account |diff --git a/docs/architecture/data-flows/SCHEDULING.md b/docs/architecture/data-flows/SCHEDULING.mdindex f3c5dc7..a4c986d 100644--- a/docs/architecture/data-flows/SCHEDULING.md+++ b/docs/architecture/data-flows/SCHEDULING.md@@ -7,8 +7,9 @@ Two independent systems check for due posts every 15 minutes. Both target the sa## System A: Cloudflare Worker Cron**Trigger:** `*/15 * * * *` cron in `wrangler.toml`-**Handler:** `backend/utils/scheduler.ts` -> `processScheduledPosts(supabase)`-**Supabase client:** service-role (created from Worker env)+**Handler:** `backend/jobs/scheduled.ts` -> `runScheduledJob()` -> `scheduledPublisher.publishDue()` in `backend/services/scheduledPublisher.ts`+**Supabase client:** service-role (created from Worker env)+**Manual trigger:** `GET` or `POST /api/process-scheduled` runs the same `publishDue()`## System B: GitHub Actions@@ -34,7 +35,7 @@ WHERE id = :id AND status = 'pending'The `AND status = 'pending'` condition means only one scheduler can successfully claim a post. The second scheduler to run will find no matching rows for that post ID and skip it.-Both schedulers implement this claim: `claimPost()` in `backend/lib/db.ts` for the Worker, and `claimPost()` in `scripts/publish-scheduled.ts` (a `PATCH` filtered on `status=eq.pending` with `Prefer: return=representation`). A scheduler that gets no row back skips the post. PostgreSQL serializes the two updates, so exactly one scheduler publishes each post even when both run at the same moment.+Both schedulers implement this claim: `claim()` in `backend/repositories/scheduledPostRepository.ts` for the Worker, and `claimPost()` in `scripts/publish-scheduled.ts` (a `PATCH` filtered on `status=eq.pending` with `Prefer: return=representation`). A scheduler that gets no row back skips the post. PostgreSQL serializes the two updates, so exactly one scheduler publishes each post even when both run at the same moment.## Post Status Lifecycle@@ -58,13 +59,15 @@ publishing Claimed by a scheduler - in-flightBoth schedulers implement the same logic:-| Step | Worker (`scheduler.ts`) | GitHub Actions (`publish-scheduled.ts`) |+| Step | Worker (`scheduledPublisher.ts`) | GitHub Actions (`publish-scheduled.ts`) ||---|---|---|-| Fetch due posts | `db.getDuePosts(supabase)` | `GET /scheduled_posts?status=eq.pending&scheduled_at=lte.now` |-| Fetch account | `db.getAccountById(supabase, accountId)` | `GET /accounts?id=eq.{accountId}` |-| Mark publishing | `db.updatePost(...)` | `PATCH /scheduled_posts?id=eq.{id}` |-| Publish to IG | Instagram Graph API calls | Same |-| Update status | `db.updatePost(...)` | `PATCH /scheduled_posts?id=eq.{id}` |+| Fetch due posts | `posts.listDue()` | `GET /scheduled_posts?status=eq.pending&scheduled_at=lte.now` |+| Mark publishing | `posts.claim(id)` | `PATCH /scheduled_posts?id=eq.{id}&status=eq.pending` |+| Fetch account | `accounts.findById(accountId)`, checked by `publishableAccount()` | `GET /accounts?id=eq.{accountId}` |+| Publish to IG | `createMediaContainer`, `fetchContainerStatus`, `publishMediaContainer` from `services/instagram/instagramPublishing.ts` | Its own Graph API calls |+| Update status | `posts.updateById(id, ...)` | `PATCH /scheduled_posts?id=eq.{id}` |++The Worker's repository methods `listDue`, `claim`, `findById` and `updateById` have no `userId` filter; only the schedulers use them.## Configuration Requirementsdiff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.mdindex 806272e..9b59474 100644--- a/docs/architecture/database/SCHEMA.md+++ b/docs/architecture/database/SCHEMA.md@@ -6,7 +6,7 @@ Supabase (PostgreSQL) with four application tables. All tables include `user_id`The backend uses the **service-role key** (bypasses Row Level Security) but enforces isolation by always appending `.eq('user_id', userId)` on user-scoped queries. The `userId` comes exclusively from the verified JWT - never from request input.-Cron handlers (`processScheduledPosts`, `autoRefreshInstagramTokens`) intentionally omit the `userId` filter to operate across all users.+The cron jobs (`scheduledPublisher.publishDue()`, `tokenRefresh.refreshExpiringInstagramTokens()`) intentionally use the repository methods without a `userId` filter to operate across all users.RLS must be enabled on all four tables, with no policies, so the public anon key cannot reach them. See `SECURITY.md`.@@ -162,7 +162,7 @@ Stores Reddit posts and YouTube videos the user wants to monitor. Previously Red### `data` jsonb shape for Reddit items-Populated by `fetchTrackedPostData()` in `backend/services/reddit.ts`:+Populated by `fetchTrackedPostData()` in `backend/services/reddit/redditApi.ts`:```json{@@ -200,7 +200,7 @@ Both keys are rejected for YouTube items, which already carry a real `viewCount`### `data` jsonb shape for YouTube items-Populated by `fetchTrackedYouTubeData()` in `backend/services/youtube.ts`:+Populated by `fetchTrackedYouTubeData()` in `backend/services/youtube/youtubeTracked.ts`:```json{@@ -249,45 +249,51 @@ ALTER TABLE tracked_posts ADD COLUMN IF NOT EXISTS content_type text NOT NULL DE----## `lib/db.ts` - Query Layer+## Repositories - Query Layer-All SQL operations are centralized in `backend/lib/db.ts`. Route handlers and cron handlers import named functions from this file - they never call `supabase.from()` directly.+All SQL operations live in `backend/repositories/`, one repository per table. Services receive repositories from `backend/container.ts` and call their methods - they never call `supabase.from()` directly. Every query runs through `execute`, `rows` or `maybeRow` in `repositories/query.ts`, which turn a failed query into a `DatabaseError` named after the operation (a 500 whose driver message goes to the log, not the client).-### Available functions+### Available methods-Each function takes the `SupabaseClient` first and returns a type from `shared/types/domain.ts`. A `userId` of `null` means service-level access (cron handlers that scan every user).+Each repository is built with `createXRepository(supabase)` and returns types from `shared/types/domain.ts`. Methods named `...ForUser` take the verified `userId` and always filter by it. The methods without a `userId` (`listAll`, `findById`, `updateById`, `listDue`, `claim`) reach every user and are only for the cron jobs.```ts-// Accounts-getAccounts(supabase, userId: string | null = null): Promise<Account[]>-getAccountById(supabase, id, userId: string | null = null): Promise<Account | null>-createAccount(supabase, account: NewAccount, userId): Promise<void>-updateAccount(supabase, id, updates: Partial<Account>, userId: string | null = null): Promise<void>-deleteAccount(supabase, id, userId: string | null = null): Promise<void>--// Settings-getSettings(supabase, userId): Promise<Settings>-saveSettings(supabase, keys: Settings, userId): Promise<void>--// Scheduled Posts-getPosts(supabase, userId: string | null): Promise<ScheduledPost[]>-getPostById(supabase, id, userId: string | null = null): Promise<ScheduledPost | null>-getDuePosts(supabase): Promise<ScheduledPost[]> // for cron - no userId filter, selects pending+overdue-claimPost(supabase, id): Promise<boolean> // pending to publishing; false when another scheduler won-createPost(supabase, post: ScheduledPost, userId): Promise<void>-updatePost(supabase, id, updates: Partial<ScheduledPost>, userId: string | null = null): Promise<void>-deletePost(supabase, id, userId: string | null = null): Promise<void>-deleteAllPosts(supabase, userId: string | null): Promise<{ deleted: number; kept: number }> // skips 'publishing' status posts--// Tracked Content-getTrackedPosts(supabase, userId): Promise<TrackedPost[]>-getTrackedPostById(supabase, id, userId): Promise<TrackedPost | null>-createTrackedPost(supabase, post: NewTrackedPost, userId): Promise<void>-updateTrackedPost(supabase, id, updates: TrackedPostUpdates, userId): Promise<void>-patchTrackedPostData(supabase, id, patch: Record<string, unknown>, userId): Promise<void>-deleteTrackedPost(supabase, id, userId): Promise<void>+// Accounts (accountRepository.ts)+listForUser(userId): Promise<Account[]>+listAll(): Promise<Account[]> // cron only+findForUser(id, userId): Promise<Account | null>+findById(id): Promise<Account | null> // cron only+create(account: NewAccount, userId): Promise<void>+updateForUser(id, updates: Partial<Account>, userId): Promise<void> // merges into data+updateById(id, updates: Partial<Account>): Promise<void> // cron only+deleteForUser(id, userId): Promise<void>++// Settings (settingsRepository.ts)+getForUser(userId): Promise<Settings>+saveForUser(settings: Settings, userId): Promise<void>++// Scheduled Posts (scheduledPostRepository.ts)+listForUser(userId): Promise<ScheduledPost[]>+findForUser(id, userId): Promise<ScheduledPost | null>+listDue(): Promise<ScheduledPost[]> // cron only - pending and overdue, every user+claim(id): Promise<boolean> // cron only - pending to publishing; false when another scheduler won+create(post: ScheduledPost, userId): Promise<void>+updateForUser(id, updates: Partial<ScheduledPost>, userId): Promise<void>+updateById(id, updates: Partial<ScheduledPost>): Promise<void> // cron only+deleteForUser(id, userId): Promise<void>+deleteAllForUser(userId): Promise<{ deleted: number; kept: number }> // skips 'publishing' status posts++// Tracked Content (trackedPostRepository.ts)+listForUser(userId): Promise<TrackedPost[]>+findForUser(id, userId): Promise<TrackedPost | null>+create(post: NewTrackedPost, userId): Promise<void>+updateForUser(id, updates: TrackedPostUpdates, userId): Promise<void>+patchDataForUser(id, patch: Record<string, unknown>, userId): Promise<void>+deleteForUser(id, userId): Promise<void>```+The Redis analytics cache has its own repository, `analyticsCacheRepository.ts`; see `docs/architecture/backend/CACHING.md`.+## Adding a New TableSee `docs/features/NEW_DATABASE_TABLE.md` for the full workflow including migration strategy.diff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.mdindex 2b95311..43da13e 100644--- a/docs/architecture/database/SECURITY.md+++ b/docs/architecture/database/SECURITY.md@@ -4,11 +4,11 @@The backend uses the **service-role key** for all database operations. This key bypasses Row Level Security (RLS). Data isolation is enforced by the application:-1. `requireAuth` middleware verifies the JWT and sets `c.userId` from Supabase's response - this is the only trusted source of `userId`-2. Every user-scoped query in `lib/db.ts` appends `.eq('user_id', userId)` using this verified value+1. `requireAuth` middleware verifies the JWT and sets `userId` on the Hono context from Supabase's response - this is the only trusted source of `userId`+2. Controllers pass that `userId` to services, and every user-scoped repository method (named `...ForUser`) appends `.eq('user_id', userId)` using this verified value3. `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 `lib/db.ts` makes this auditable - every public function signature documents whether it accepts a userId.+**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 (`listAll`, `findById`, `updateById`, `listDue`, `claim`) are used only by the cron services. Because ownership is a query filter, another user's record is simply not found (404).## Why Not Use RLS?@@ -58,12 +58,12 @@ The Instagram `accessToken` stored in `accounts.data.accessToken` is a long-live1. Stored only in the Supabase `accounts` table (server-side)2. Never returned in API responses - `safeAccount()` strips it3. Only used server-side, by these modules:- - Graph API calls: `services/instagramApi.ts`, `services/instagramMedia.ts` and `services/instagramPublishing.ts` (the token is passed in as `access_token`)- - Obtaining and storing tokens: `services/instagramTokens.ts` (long-lived exchange and refresh), `services/instagramOAuth.ts` (OAuth code exchange), `services/accountConnect.ts` and `services/accountFactory.ts` (pasted tokens and new account rows)- - Reading the stored token: `routes/publishing.ts` and `utils/scheduler.ts` (publishing), `routes/analytics.ts` (Instagram analytics and media), `services/accountRefresh.ts` (profile refresh) and `services/overviewSummary.ts` (overview cache warm-up)+ - 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) and `services/overviewService.ts` (overview cache warm-up)4. The `GET /api/accounts` endpoint passes all accounts through `safeAccount()` before returning-**If you add a new route that returns account data, you must call `safeAccount()`.** There is no automatic stripping - it is an explicit step in route handlers.+**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).## GitHub Settings@@ -73,6 +73,7 @@ The Instagram `accessToken` stored in `accounts.data.accessToken` is a long-liveWhen reviewing security, check these files:- `backend/middleware/auth.ts` - JWT verification-- `backend/lib/db.ts` - every function that accepts an optional `userId` should either: require it explicitly, or have a documented reason for omitting it (cron use case)+- `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/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 route files in `backend/routes/` - verify `safeAccount()` is called on every account response+- All controllers in `backend/controllers/` - verify `safeAccount()` is called on every account responsediff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.mdindex 681c29a..637f9cc 100644--- a/docs/architecture/frontend/API_LAYER.md+++ b/docs/architecture/frontend/API_LAYER.md@@ -9,9 +9,7 @@ The single source of truth for all frontend-to-backend communication. **Never ca```tsconst API = import.meta.env.VITE_API_URL || 'http://localhost:8787/api';-// callers that check success also handle a failure body the server sent with a 2xx status; success bodies carry no message-export type ApiResult<T> = (T & { message?: undefined }) | ApiFailure;-+// every failure arrives with a 4xx or 5xx status and the ApiFailure body, so a 2xx is always a successasync function request<T>(path: string, options: RequestInit = {}): Promise<T> {const { data: { session } } = await supabase.auth.getSession();const token = session?.access_token;@@ -23,35 +21,39 @@ async function request<T>(path: string, options: RequestInit = {}): Promise<T> {},...options,});- const data = await res.json() as T & ResponseStatusFields;- if (!res.ok && !data.success) throw new Error(data.message || data.error || 'Request failed');- return data;+ // a proxy error page is not JSON; the status still explains the failure+ const data = await res.json().catch(() => null) as unknown;+ if (!res.ok) throw new Error(failureMessage(res.status, data as Partial<ApiFailure> | null));+ return data as T;}```-`T` is the response type from `shared/types/` that the route returns; `request<T>()` casts the parsed JSON to it once and does not validate it at runtime. `ResponseStatusFields` (`success?`, `message?`, `error?`) is the private type for the fields `request()` reads to decide whether the call failed. `import.meta.env` is typed by `ImportMetaEnv` in `frontend/src/vite-env.d.ts`; add a new `VITE_*` variable there.+`T` is the response type from `shared/types/` that the route returns; `request<T>()` casts the parsed JSON to it once and does not validate it at runtime. `import.meta.env` is typed by `ImportMetaEnv` in `frontend/src/vite-env.d.ts`; add a new `VITE_*` variable there.**What it does automatically:**1. Gets the current Supabase session token2. Attaches `Authorization: Bearer <token>` header if logged in-3. Parses the JSON response-4. Throws an `Error` if the response is not OK (unless `data.success` is explicitly true)+3. Parses the JSON response (a body that is not JSON, such as a proxy error page, is read as `null`)+4. Throws an `Error` for any status outside 2xx; a 2xx response is always a success-**Error handling:** The error message comes from the backend's `message` or `error` field, falling back to `'Request failed'`. Callers are responsible for catching this error and showing appropriate UI.+**Error handling:** The backend answers every failure with a 4xx or 5xx status and one body, the `ApiFailure` type in `shared/types/domain.ts`:-### `ApiResult<T>`+```json+{ "success": false, "code": "NOT_FOUND", "message": "Account not found", "requestId": "3f2a..." }+```-A few routes answer `{ success: false, message }` (the `ApiFailure` type in `shared/types/domain.ts`) with a 2xx status, which `request()` returns instead of throwing. Their methods return `request<ApiResult<T>>()`: `createIGContainer`, `publishIGContainer`, `getScheduledPosts`, `createScheduledPost` and `updateScheduledPost`. The caller narrows on `success` before reading the data:+`failureMessage(status, body)` in `frontend/src/lib/apiErrors.ts` builds the thrown message: the backend's `message`, or `The server answered with status <status>. Try again in a moment.` when there is none. For a 5xx failure it adds the request id, `(request <id>)`, so a user can quote it and the owner can find the matching log line. Callers are responsible for catching this error and showing appropriate UI. Callers never check `success` on a 2xx response; there is no failure body with a success status.```ts-const res = await api.createScheduledPost(post);-if (!res.success) {- showToast(res.message, 'error');- return;+// a server-side failure is logged under its request id, so the message carries the id for the user to quote+export function failureMessage(status: number, body: Partial<ApiFailure> | null): string {+ const message = body?.message || `The server answered with status ${status}. Try again in a moment.`;+ return status >= 500 && body?.requestId ? `${message} (request ${body.requestId})` : message;}-// res is ScheduledPostResponse here```+A 429 body also carries `retryAfter` (seconds); `request()` shows its `message`, which already says how long to wait. See `docs/architecture/backend/REQUEST_PIPELINE.md` for the codes and statuses.+## The `api` ObjectAll backend endpoints are methods on the exported `api` object. Each method types its parameters and passes the shared response type to `request<T>()`, so the call site gets a typed result without a cast:diff --git a/docs/features/NEW_ANALYTICS_PAGE.md b/docs/features/NEW_ANALYTICS_PAGE.mdindex fc490fd..a97a704 100644--- a/docs/features/NEW_ANALYTICS_PAGE.md+++ b/docs/features/NEW_ANALYTICS_PAGE.md@@ -9,11 +9,12 @@ Adding a platform analytics page touches all layers:| Layer | What changes ||---|---|| **Shared types** | New `shared/types/<platform>.ts` with the profile, post, analytics and cache shapes |-| **Backend service** | New service file with platform API client, data fetcher, analytics computation |-| **Backend cache** | New cache key functions in `lib/cache.ts` |-| **Backend db** | No schema change needed - `platform='reddit'` works with existing `accounts` table |-| **Backend routes** | New analytics routes (`/accounts/:id/platform-analytics`, `/accounts/:id/platform-media`) |-| **Backend server** | Mount new router in `server.ts` |+| **Backend platform modules** | New `services/<platform>/` folder with the API client and the analytics computation |+| **Backend feature service** | New `services/<platform>AnalyticsService.ts`, wired in `container.ts` |+| **Backend cache** | New cache methods in `repositories/analyticsCacheRepository.ts` |+| **Backend db** | No schema change needed - `platform='reddit'` works with the existing `accounts` table and `accountRepository` |+| **Backend controller and routes** | New `controllers/<platform>Controller.ts` and `routes/<platform>Routes.ts` (`/accounts/:id/platform-analytics`, `/accounts/:id/platform-media`) |+| **Backend route index** | Add the route table to `protectedRoutes` in `routes/index.ts` || **Frontend api** | New methods in `api.ts` || **Frontend page** | New analytics page in `features/analytics/platform/` || **Frontend routing** | New route in `App.tsx` |@@ -28,9 +29,14 @@ shared/types/backend/services/- reddit.ts <- API client + analytics computation+ reddit/+ redditApi.ts <- API client+ redditAnalytics.ts <- pure analytics computation+ redditAnalyticsService.ts <- ownership checks, cache, platform calls+ controllers/+ redditController.tsroutes/- reddit.ts <- analytics routes+ redditRoutes.ts <- analytics routesfrontend/src/features/@@ -51,110 +57,123 @@ export interface RedditAnalytics { /* totals, breakdowns */ }export interface RedditCacheData { profile: RedditProfile; analytics: RedditAnalytics; posts: RedditPost[] }```-## Step 2: Backend Service+## Step 2: Backend Platform Modules-Model it after `backend/services/instagram.ts`. Raw upstream payloads get their own interfaces in the service file, covering only the fields the code reads:+Model them after `backend/services/reddit/`. Raw upstream payloads get their own interfaces in the module, covering only the fields the code reads. Every call accepts an `AbortSignal` and turns a failure into a typed error:```ts-// backend/services/reddit.ts-import type { RedditAnalytics, RedditPost, RedditProfile } from '../../shared/types/reddit.ts';--async function redditFetch<T>(path: string, cookie: string): Promise<T> {- const res = await fetch(`https://www.reddit.com${path}`, {- headers: {- 'Cookie': cookie,- 'User-Agent': 'Twiligent/1.0',- },- });- if (!res.ok) throw new Error(`Reddit API ${res.status}`);+// backend/services/reddit/redditApi.ts+import { NotFoundError, UpstreamError, UpstreamTimeoutError, isAbortError } from '../../lib/errors.ts';+import type { RedditPost, RedditProfile } from '../../../shared/types/reddit.ts';++async function redditFetch<T>(path: string, cookie: string | null | undefined, signal?: AbortSignal): Promise<T> {+ const headers: Record<string, string> = { 'User-Agent': USER_AGENT, 'Accept': 'application/json' };+ if (cookie) headers['Cookie'] = `reddit_session=${cookie}`;+ let res: Response;+ try {+ res = await fetch(`${REDDIT_BASE}${path}`, { headers, signal });+ } catch (err) {+ if (isAbortError(err)) throw new UpstreamTimeoutError('Reddit', err);+ throw new UpstreamError(`Reddit could not be reached (${(err as Error).message})`, { cause: err });+ }+ if (res.status === 404) throw new NotFoundError('Reddit user not found - check the username');+ if (!res.ok) throw new UpstreamError(`Reddit API ${res.status}: ${res.statusText}`, { status: res.status });return await res.json() as T;}-export async function fetchRedditProfile(username: string, cookie: string): Promise<RedditProfile> { ... }-export async function fetchRedditPosts(username: string, cookie: string, limit = 100): Promise<RedditPost[]> { ... }-export function computeRedditAnalytics(profile: RedditProfile, posts: RedditPost[]): RedditAnalytics {- // Return analytics object with:- // - totalPosts, totalKarma, avgUpvotes, avgComments- // - best performing post- // - posting time distribution- // - subreddit breakdown- // - monthly breakdown- return { ... };+export async function fetchRedditProfile(username: string, cookie: string | null | undefined, signal?: AbortSignal): Promise<RedditProfile> { ... }+export async function fetchRedditPosts(username: string, cookie: string | null | undefined, limit = 100, signal?: AbortSignal): Promise<RedditPost[]> { ... }+```++```ts+// backend/services/reddit/redditAnalytics.ts - pure, so it is easy to test+export function computeRedditAnalytics(profile: RedditProfile, posts: RedditPost[] | null | undefined): RedditAnalytics {+ // totals, best post, posting time distribution, subreddit and monthly breakdowns,+ // using the shared helpers in lib/analyticsMath.ts}```## Step 3: Backend Cache-Use the private `readKey`, `writeKey` and `deleteKey` helpers in `cache.ts`; they return early without Redis, swallow Redis errors and apply the analytics TTL:+Add the methods to `AnalyticsCacheRepository` in `backend/repositories/analyticsCacheRepository.ts`. Build them on the private `readKey` and `writeKey` helpers, which return early without Redis, swallow Redis errors and apply the analytics TTL:```ts-// Add to backend/lib/cache.ts-export async function getRedditCache(redis: Redis | null, userId: string, accountId: string): Promise<RedditCacheData | null> {- return (await readKey<RedditCacheData>(redis, `reddit:${userId}:${accountId}`)) || null;-}--export async function setRedditCache(redis: Redis | null, userId: string, accountId: string, data: RedditCacheData): Promise<void> {- await writeKey(redis, `reddit:${userId}:${accountId}`, data);-}+// in createAnalyticsCacheRepository()+async getReddit(userId, accountId) {+ return (await readKey<RedditCacheData>(`reddit:${userId}:${accountId}`)) || null;+},-export async function deleteRedditCache(redis: Redis | null, userId: string, accountId: string): Promise<void> {- await deleteKey(redis, `reddit:${userId}:${accountId}`);-}+setReddit: (userId, accountId, data) => writeKey(`reddit:${userId}:${accountId}`, data),```-## Step 4: Backend Routes+Add the key to `deleteAllForAccount()`, which `AccountService.remove()` calls when the account is deleted.-```ts-// backend/routes/reddit.ts-import { Hono } from 'hono';-import { getAccountById } from '../lib/db.ts';-import { getRedditCache, setRedditCache } from '../lib/cache.ts';-import { fetchRedditProfile, fetchRedditPosts, computeRedditAnalytics } from '../services/reddit.ts';-import type { AppEnv } from '../types/app.ts';-import type { RedditCacheData } from '../../shared/types/reddit.ts';+## Step 4: Backend Service, Controller and Routes-const router = new Hono<AppEnv>();+The feature service checks ownership and the stored credentials, reads the cache, and fetches live on a miss:-router.get('/accounts/:id/reddit-analytics', async (c) => {- const id = c.req.param('id');- const userId = c.get('userId');- const supabase = c.get('supabase');- const redis = c.get('redis');- try {- const account = await getAccountById(supabase, id, userId);- if (!account || account.platform !== 'reddit') return c.json({ error: 'Reddit account not found' }, 404);- if (!account.cookie || !account.username) return c.json({ error: 'No session cookie stored - re-add this account' }, 400);+```ts+// backend/services/redditAnalyticsService.ts+export function createRedditAnalyticsService({ accounts, cache, context }: RedditAnalyticsDeps): RedditAnalyticsService {+ const { signal } = context;++ async function credentialsFor(userId: string, accountId: string): Promise<RedditCredentials> {+ const account = await accounts.findForUser(accountId, userId);+ if (!account || account.platform !== 'reddit') throw new NotFoundError('Reddit account not found');+ if (!account.cookie) throw new ValidationError(NO_COOKIE_MESSAGE);+ if (!account.username) throw new ValidationError('No Reddit username stored - delete this account and add it again');+ return { username: account.username, cookie: account.cookie };+ }- const cached = await getRedditCache(redis, userId, id);- if (cached) return c.json(cached);+ return {+ async analytics(userId, accountId) {+ const { username, cookie } = await credentialsFor(userId, accountId);+ const cached = await cache.getReddit(userId, accountId);+ if (cached) return cached;++ const [profile, posts] = await Promise.all([+ fetchRedditProfile(username, cookie, signal),+ fetchRedditPosts(username, cookie, POST_LIMIT, signal),+ ]);+ const result: RedditCacheData = { profile, analytics: computeRedditAnalytics(profile, posts), posts };+ await cache.setReddit(userId, accountId, result);+ return result;+ },+ // ...+ };+}+```- const profile = await fetchRedditProfile(account.username, account.cookie);- const posts = await fetchRedditPosts(account.username, account.cookie);- const data: RedditCacheData = { profile, analytics: computeRedditAnalytics(profile, posts), posts };+Wire it in `backend/container.ts` (`redditAnalytics: createRedditAnalyticsService({ accounts, cache, context })`). The controller and route table stay thin:- await setRedditCache(redis, userId, id, data);- return c.json(data);- } catch (err) {- console.error(`GET /accounts/${id}/reddit-analytics:`, (err as Error).message);- return c.json({ error: (err as Error).message }, 500);- }+```ts+// backend/controllers/redditController.ts+export const getRedditAnalytics = controller.createHandlers(async c => {+ const result = await servicesFor(c).redditAnalytics.analytics(c.get('userId'), pathParam(c, 'id'));+ return c.json(result satisfies RedditCacheData);});+// backend/routes/redditRoutes.ts+const router = new Hono<AppEnv>();++router.get('/accounts/:id/reddit-analytics', ...getRedditAnalytics);+router.get('/accounts/:id/reddit-posts', ...getRedditPosts);+export default router;```-## Step 5: Mount Route + Account Deletion Cache Invalidation+## Step 5: Register the Route Table```ts-// backend/server.ts-import redditRouter from './routes/reddit.ts';-api.route('/', redditRouter);+// backend/routes/index.ts+import redditRoutes from './redditRoutes.ts';+// ...+for (const routes of [accountRoutes, analyticsRoutes, redditRoutes, /* ... */]) {+ protectedRoutes.route('/', routes);+}```-```ts-// backend/routes/accounts.ts - in the delete handler-await deleteRedditCache(redis, userId, id); // add alongside existing cache deletes-```+Routes that call the platform on a cache miss count against the shared API limits; add them to `QUOTA_ROUTES` in `backend/lib/rateLimit/rules.ts` if they can be called often.## Step 6: Frontend Page@@ -192,7 +211,7 @@ export function accountPath(account: AccountFields): string {## Step 8: Type-check and Test-Run `npm run typecheck`, `npm run lint` and `npm test` from the repository root. Pure analytics helpers (like `computeRedditAnalytics`) get a test in `backend/tests/services/` at the mirrored path.+Run `npm run typecheck`, `npm run lint` and `npm test` from the repository root. Pure analytics helpers (like `computeRedditAnalytics`) get a test in `backend/tests/services/` at the mirrored path (`backend/tests/services/reddit/redditAnalytics.test.ts`), and the route table gets one in `backend/tests/routes/redditRoutes.test.ts`.## Step 9: Update Documentationdiff --git a/docs/features/NEW_API_ENDPOINT.md b/docs/features/NEW_API_ENDPOINT.mdindex 8a0e24f..ef47081 100644--- a/docs/features/NEW_API_ENDPOINT.md+++ b/docs/features/NEW_API_ENDPOINT.md@@ -1,17 +1,20 @@# Guide: Adding a New API Endpoint-Follow this guide when adding a route to the Hono backend. Read the existing `backend/routes/accounts.ts` and `backend/routes/scheduledPosts.ts` as reference implementations before starting, and `docs/guidelines/TYPESCRIPT.md` for the typing rules.+Follow this guide when adding a route to the Hono backend. Read `docs/architecture/backend/REQUEST_PIPELINE.md` for the layers, then the tracked content feature as a reference implementation: `backend/validators/trackedContentValidators.ts`, `repositories/trackedPostRepository.ts`, `services/trackedContentService.ts`, `controllers/trackedContentController.ts` and `routes/trackedContentRoutes.ts`. `docs/guidelines/TYPESCRIPT.md` has the typing rules.## Files to Create or Modify| Action | File ||---|---|| Modify | `shared/types/domain.ts` (or the platform file) - request and response types |-| Create (if new feature area) | `backend/routes/myFeature.ts` |-| Modify | `backend/lib/db.ts` (add query functions) |-| Modify | `backend/server.ts` (mount new router) |+| Create or modify | `backend/validators/myFeatureValidators.ts` - body and query parsers |+| Create or modify | `backend/repositories/myResourceRepository.ts` - queries (if the endpoint needs new ones) |+| Create or modify | `backend/services/myFeatureService.ts` - the business rules |+| Modify (new service or repository) | `backend/container.ts` - wire it into `Services` |+| Create or modify | `backend/controllers/myFeatureController.ts` |+| Create or modify | `backend/routes/myFeatureRoutes.ts`, and `backend/routes/index.ts` for a new table || Modify | `frontend/src/services/api.ts` (add frontend method) |-| Create | `backend/tests/routes/myFeature.test.ts` |+| Create | `backend/tests/routes/myFeatureRoutes.test.ts`, plus service, repository and validator tests as needed || Update | `docs/architecture/backend/ROUTES.md` |## Step 1: Define the Request and Response Types@@ -35,96 +38,152 @@ export interface MyResourceCreateResponse {}```-When you change an existing route's response, change its type here first: `npm run typecheck` then lists every backend and frontend file that reads the old shape.+When you change an existing route's response, change its type here first: `npm run typecheck` then lists every backend and frontend file that reads the old shape. Failures need no type of their own: every error is an `ApiFailure`.-## Step 2: Add Database Functions (if needed)+## Step 2: Add a Validator-In `backend/lib/db.ts`, add query functions for the new resource. Follow the established patterns:+In `backend/validators/myFeatureValidators.ts`, add a parser that reads the body with the helpers in `validators/fields.ts` and returns the request type. A missing or malformed field throws `ValidationError` (400) with a message the user can act on:```ts+import { requiredString } from './fields.ts';+import type { Fields } from './fields.ts';+import type { MyResourceCreateRequest } from '../../shared/types/domain.ts';++export function parseMyResource(body: Fields): MyResourceCreateRequest {+ return { name: requiredString(body, 'name', 'Enter a name') };+}+```++Validators check shape and presence only. Rules that need stored data belong in the service. Query strings use the same helpers through `queryParams(parse)`.++## Step 3: Add Repository Methods (if needed)++In `backend/repositories/`, add the queries to the table's repository, or create one for a new table (see `NEW_DATABASE_TABLE.md`). Every user-scoped method takes the verified `userId`, ends in `ForUser`, and filters by it. Run every query through `rows`, `maybeRow` or `execute` from `repositories/query.ts`, which turn a failure into a `DatabaseError`:++```ts+// backend/repositories/myResourceRepository.ts+import { execute, rows } from './query.ts';+import type { SupabaseClient } from '../types/app.ts';+import type { MyResource } from '../../shared/types/domain.ts';+interface MyResourceRow {id: string;name: string;- data: Record<string, unknown>;+ data: Record<string, unknown> | null;}-// For user-scoped data: always accept userId, always apply .eq('user_id', userId)-export async function getMyResources(supabase: SupabaseClient, userId: string): Promise<MyResource[]> {- const { data, error } = await supabase- .from('my_table')- .select('id, name, data')- .eq('user_id', userId)- .order('created_at', { ascending: false });- if (error) throw error;- return ((data || []) as MyResourceRow[]).map(row => ({ id: row.id, name: row.name, ...row.data }));+export interface MyResourceRepository {+ listForUser(userId: string): Promise<MyResource[]>;+ create(resource: MyResource, userId: string): Promise<void>;}-export async function createMyResource(supabase: SupabaseClient, resource: MyResource, userId: string): Promise<void> {- const { id, name, ...rest } = resource;- const { error } = await supabase- .from('my_table')- .insert({ id, user_id: userId, name, data: rest });- if (error) throw error;+export function createMyResourceRepository(db: SupabaseClient): MyResourceRepository {+ return {+ async listForUser(userId) {+ const found = await rows<MyResourceRow>('myResources.listForUser', () => db+ .from('my_table')+ .select('id, name, data')+ .eq('user_id', userId)+ .order('created_at', { ascending: false }));+ return found.map(row => ({ id: row.id, name: row.name, ...(row.data || {}) }));+ },++ async create(resource, userId) {+ const { id, name, ...rest } = resource;+ await execute('myResources.create', () => db.from('my_table').insert({ id, user_id: userId, name, data: rest }));+ },+ };}```-## Step 3: Add Service Functions (if external API calls needed)+## Step 4: Add the Service Method++In `backend/services/myFeatureService.ts`, put the business rules. A service is a factory that receives repositories, `config` and `context`, never the Hono context, and throws typed errors from `lib/errors.ts`:-In `backend/services/myPlatform.ts`, add functions for external API calls. Keep business logic out of routes. Describe each upstream payload with an interface that covers the fields the service reads, kept in the service module.+```ts+import { NotFoundError } from '../lib/errors.ts';+import type { MyResourceRepository } from '../repositories/myResourceRepository.ts';+import type { MyResource, MyResourceCreateRequest } from '../../shared/types/domain.ts';++export interface MyFeatureDeps {+ resources: MyResourceRepository;+}++export interface MyFeatureService {+ list(userId: string): Promise<MyResource[]>;+ create(userId: string, request: MyResourceCreateRequest): Promise<string>;+}++export function createMyFeatureService({ resources }: MyFeatureDeps): MyFeatureService {+ return {+ list: userId => resources.listForUser(userId),++ async create(userId, { name }) {+ const id = crypto.randomUUID();+ await resources.create({ id, name }, userId);+ return id;+ },+ };+}+```-## Step 4: Create the Route File+If the endpoint calls a platform API, put the call in the platform module (`services/youtube/`, `services/instagram/`, `services/reddit/`) and pass it `context.signal`. A missing Worker secret is a `NotConfiguredError` (503); a record the user does not own is a `NotFoundError` (404).++Wire a new repository or service in `backend/container.ts`: build the repository from `clients.supabase`, add the service to the `Services` interface, and create it in `createServices()`.++## Step 5: Add the Controller++```ts+// backend/controllers/myFeatureController.ts+import { controller, servicesFor } from './http.ts';+import { jsonBody } from '../middleware/validate.ts';+import { parseMyResource } from '../validators/myFeatureValidators.ts';+import type { MyResource, MyResourceCreateResponse } from '../../shared/types/domain.ts';++export const listMyResources = controller.createHandlers(async c => {+ const resources = await servicesFor(c).myFeature.list(c.get('userId'));+ return c.json(resources satisfies MyResource[]);+});++export const createMyResource = controller.createHandlers(jsonBody(parseMyResource), async c => {+ const id = await servicesFor(c).myFeature.create(c.get('userId'), c.req.valid('json'));+ return c.json({ success: true, id } satisfies MyResourceCreateResponse, 201);+});+```++A controller reads the user id, path parameters (`pathParam(c, 'id')`) and validated input, calls one service method, and builds the response. It never catches errors, never queries the database and never builds an error body.++## Step 6: Add the Route```ts-// backend/routes/myFeature.ts+// backend/routes/myFeatureRoutes.tsimport { Hono } from 'hono';-import { getMyResources, createMyResource } from '../lib/db.ts';+import { listMyResources, createMyResource } from '../controllers/myFeatureController.ts';import type { AppEnv } from '../types/app.ts';-import type { MyResource, MyResourceCreateRequest, MyResourceCreateResponse } from '../../shared/types/domain.ts';const router = new Hono<AppEnv>();-router.get('/my-resources', async (c) => {- const userId = c.get('userId');- const supabase = c.get('supabase');- try {- const resources = await getMyResources(supabase, userId);- return c.json(resources satisfies MyResource[]);- } catch (err) {- console.error('GET /my-resources:', (err as Error).message);- return c.json({ error: (err as Error).message }, 500);- }-});--router.post('/my-resources', async (c) => {- const userId = c.get('userId');- const supabase = c.get('supabase');- const { name } = await c.req.json() as MyResourceCreateRequest;- if (!name) return c.json({ error: 'Missing required field: name' }, 400);- try {- const id = Date.now().toString(36) + Math.random().toString(36).slice(2);- await createMyResource(supabase, { id, name }, userId);- return c.json({ success: true, id } satisfies MyResourceCreateResponse, 201);- } catch (err) {- console.error('POST /my-resources:', (err as Error).message);- return c.json({ error: (err as Error).message }, 500);- }-});+router.get('/my-resources', ...listMyResources);+router.post('/my-resources', ...createMyResource);export default router;```-## Step 5: Mount in server.ts+Add a new table to the list in `backend/routes/index.ts`:```ts-// backend/server.ts-import myFeatureRouter from './routes/myFeature.ts';+import myFeatureRoutes from './myFeatureRoutes.ts';// ...-api.route('/', myFeatureRouter);+for (const routes of [+ accountRoutes, analyticsRoutes, /* ... */, myFeatureRoutes,+]) {+ protectedRoutes.route('/', routes);+}```-Routes mounted on `api` get authentication and the per-IP and per-user rate limits automatically. If the endpoint spends platform API quota or publishes, add it to `QUOTA_ROUTES` or `PUBLISH_ROUTES` in `backend/lib/rateLimit/rules.ts` (see `docs/architecture/backend/RATE_LIMITING.md`).+Routes on `protectedRoutes` get authentication and the per-IP and per-user rate limits automatically. If the endpoint spends platform API quota or publishes, add it to `QUOTA_ROUTES` or `PUBLISH_ROUTES` in `backend/lib/rateLimit/rules.ts` (see `docs/architecture/backend/RATE_LIMITING.md`).-## Step 6: Add Frontend API Methods+## Step 7: Add Frontend API Methods```ts// frontend/src/services/api.ts@@ -137,9 +196,9 @@ export const api = {};```-If the route can answer `{ success: false, message }` with a 2xx status, return `request<ApiResult<T>>` instead so callers check `success` (see `docs/architecture/frontend/API_LAYER.md`).+`request()` throws on any non-2xx status with the backend's message, so the method returns the success type and callers never check `success` (see `docs/architecture/frontend/API_LAYER.md`).-## Step 7: Type-check+## Step 8: Type-check```bashnpm run typecheck@@ -147,22 +206,22 @@ npm run typecheckFix every error before moving on. Wrangler and Vite strip types without checking them, so this is the only place a wrong shape is caught.-## Step 8: Update Documentation+## Step 9: Update Documentation-Add the new routes to `docs/architecture/backend/ROUTES.md`.+Add the new routes to `docs/architecture/backend/ROUTES.md` with their route table and controller, and any status that is specific to them.## Security Checklist-- [ ] Route is mounted under `api` (protected by `requireAuth`)-- [ ] Route handler reads `userId` from `c.get('userId')` - not from request body-- [ ] All DB queries include `.eq('user_id', userId)` for user-scoped data-- [ ] Any account data in the response passes through `safeAccount()` if it contains tokens-- [ ] Input validation returns 400 for missing required fields (the `as` cast on `c.req.json()` checks nothing at runtime)-- [ ] Errors are caught and return JSON with appropriate status code+- [ ] Route is registered on `protectedRoutes` (protected by `requireAuth`), unless it must be public+- [ ] Controller reads `userId` from `c.get('userId')` and passes it to the service - never from the request body or query+- [ ] Every repository method the service calls for user data ends in `ForUser` and filters by `user_id`+- [ ] Any account data in the response passes through `safeAccount()`+- [ ] Input goes through a validator, so a missing or malformed field is a 400 before the service runs+- [ ] Failures are typed errors; nothing builds `{ error }` or catches an error only to reformat it## Testing-Pure logic behind the route (validation, response shaping) gets a unit test in `backend/tests/`, at the path that mirrors the source file: a handler in `backend/routes/myFeature.ts` is tested in `backend/tests/routes/myFeature.test.ts`. Route tests run the real handler against the fakes in `backend/tests/fixtures/` (`routeHarness.ts`, `fakeSupabase.ts`, `fakeFetch.ts`) and compare the result with a `*.golden.json` snapshot there; see `backend/tests/routes/accounts.test.ts` and `docs/workflows/TESTING.md`. Run `npm test` and `npm run typecheck` from the repository root.+Tests live in `backend/tests/`, at the path that mirrors the source file. A route table gets an end-to-end test in `backend/tests/routes/myFeatureRoutes.test.ts`: `mountWithContext()` from `fixtures/routeHarness.ts` mounts the table behind the error handler and a request id, with the fake Supabase client from `fixtures/fakeSupabase.ts` and, for platform calls, `fixtures/fakeFetch.ts`. Assert the status and body, or compare with a `*.golden.json` snapshot through `fixtures/golden.ts`; see `backend/tests/routes/settingsRoutes.test.ts` and `accountRoutes.test.ts`. Add `backend/tests/services/`, `repositories/` or `validators/` tests for logic worth testing on its own. Run `npm test` and `npm run typecheck` from the repository root.```bash# Local test, from the repository root@@ -176,4 +235,10 @@ curl -X POST http://localhost:8787/api/my-resources \-H "Authorization: Bearer TOKEN" \-H "Content-Type: application/json" \-d '{"name":"test"}'++# A missing field answers 400 with { success: false, code: "VALIDATION_ERROR", message, requestId }+curl -X POST http://localhost:8787/api/my-resources \+ -H "Authorization: Bearer TOKEN" \+ -H "Content-Type: application/json" \+ -d '{}'```diff --git a/docs/features/NEW_DATABASE_TABLE.md b/docs/features/NEW_DATABASE_TABLE.mdindex 7745fed..45ed179 100644--- a/docs/features/NEW_DATABASE_TABLE.md+++ b/docs/features/NEW_DATABASE_TABLE.md@@ -42,21 +42,16 @@ Option B: Supabase Dashboard -> Table Editor -> create visuallyThere is currently no migration tool configured. SQL is applied directly. **Document the SQL in this guide for future reference** if it needs to be recreated.-### Step 3: Add Row-Level Security (Optional)+### Step 3: Enable Row-Level Security (Required)-The backend uses the service-role key which bypasses RLS. However, enabling RLS with a permissive policy is good defense-in-depth:+The backend uses the service-role key, which bypasses RLS. Every application table must still have RLS enabled with no policies, so the public anon key cannot read or write it through Supabase's Data API (see `docs/architecture/database/SECURITY.md`):```sqlALTER TABLE content_drafts ENABLE ROW LEVEL SECURITY;---- The backend uses service-role key which bypasses RLS.--- This policy would apply only if the anon key were used.-CREATE POLICY "Users can manage their own drafts"- ON content_drafts- FOR ALL- USING (user_id = auth.uid());```+Add the statement to the setup SQL in the README and on the `/docs/self-host/supabase` page (`frontend/src/docs/pages/selfHost/selfHostSql.ts`).+### Step 4: Add the TypesAdd the entity as the API returns it to `shared/types/domain.ts` (types only, no runtime code). Status columns become a union of string literals, never an `enum`:@@ -78,14 +73,18 @@ export interface ContentDraft {export type ContentDraftUpdate = Partial<Omit<ContentDraft, 'id' | 'accountId' | 'platform' | 'createdAt' | 'updatedAt'>>;```-The raw row shape stays private to `lib/db.ts`, next to the functions that read it.+The raw row shape stays private to the table's repository, next to the methods that read it.-### Step 5: Add Query Functions to `lib/db.ts`+### Step 5: Add a Repository-Follow the established pattern exactly:+Create `backend/repositories/contentDraftRepository.ts`. Follow the existing repositories (`trackedPostRepository.ts`, `scheduledPostRepository.ts`) exactly: an interface with one method per query, a factory that takes the Supabase client, user-scoped methods that end in `ForUser` and filter by `user_id`, and every query run through `rows`, `maybeRow` or `execute` from `query.ts` so a failure becomes a `DatabaseError`.```ts-// backend/lib/db.ts+// backend/repositories/contentDraftRepository.ts+import { execute, maybeRow, rows } from './query.ts';+import type { SupabaseClient } from '../types/app.ts';+import type { ContentDraft, ContentDraftUpdate, DraftStatus, Platform } from '../../shared/types/domain.ts';+interface ContentDraftRow {id: string;account_id: string;@@ -96,7 +95,9 @@ interface ContentDraftRow {data: Partial<ContentDraft> | null;}-function rowToDraft(row: ContentDraftRow): ContentDraft {+const COLUMNS = 'id, account_id, platform, status, created_at, updated_at, data';++function toDraft(row: ContentDraftRow): ContentDraft {return {...(row.data || {}),id: row.id,@@ -108,55 +109,74 @@ function rowToDraft(row: ContentDraftRow): ContentDraft {};}-export async function getDrafts(supabase: SupabaseClient, userId: string): Promise<ContentDraft[]> {- const { data, error } = await supabase- .from('content_drafts')- .select('id, account_id, platform, status, created_at, updated_at, data')- .eq('user_id', userId)- .order('created_at', { ascending: false });- if (error) throw error;- return ((data || []) as ContentDraftRow[]).map(rowToDraft);-}--export async function createDraft(supabase: SupabaseClient, draft: ContentDraft, userId: string): Promise<void> {- const { id, accountId, platform, status, createdAt: _c, updatedAt: _u, ...rest } = draft;- const { error } = await supabase.from('content_drafts').insert({- id,- user_id: userId,- account_id: accountId,- platform,- status,- data: rest,- });- if (error) throw error;+// every method is scoped to the verified user+export interface ContentDraftRepository {+ listForUser(userId: string): Promise<ContentDraft[]>;+ findForUser(id: string, userId: string): Promise<ContentDraft | null>;+ create(draft: ContentDraft, userId: string): Promise<void>;+ updateForUser(id: string, updates: ContentDraftUpdate, userId: string): Promise<void>;+ deleteForUser(id: string, userId: string): Promise<void>;}-export async function updateDraft(supabase: SupabaseClient, id: string, updates: ContentDraftUpdate, userId: string | null = null): Promise<void> {- // Merge data fields with existing (never replace the whole data object)- const current = await getDraftById(supabase, id, userId);- if (!current) throw new Error('Draft not found: ' + id);- const colUpdates: { updated_at: string; status?: DraftStatus; data?: Partial<ContentDraft> } = { updated_at: new Date().toISOString() };- const { status, ...dataUpdates } = updates;- if (status) colUpdates.status = status;- if (Object.keys(dataUpdates).length > 0) {- const { id: _id, accountId: _aid, platform: _p, status: _s, createdAt: _c, updatedAt: _u, ...currentData } = current;- colUpdates.data = { ...currentData, ...dataUpdates };+export function createContentDraftRepository(db: SupabaseClient): ContentDraftRepository {+ async function findForUser(id: string, userId: string): Promise<ContentDraft | null> {+ const row = await maybeRow<ContentDraftRow>('contentDrafts.findForUser', () => db+ .from('content_drafts')+ .select(COLUMNS)+ .eq('id', id)+ .eq('user_id', userId)+ .maybeSingle());+ return row ? toDraft(row) : null;}- let query = supabase.from('content_drafts').update(colUpdates).eq('id', id);- if (userId) query = query.eq('user_id', userId);- const { error } = await query;- if (error) throw error;-}-export async function deleteDraft(supabase: SupabaseClient, id: string, userId: string | null = null): Promise<void> {- let query = supabase.from('content_drafts').delete().eq('id', id);- if (userId) query = query.eq('user_id', userId);- const { error } = await query;- if (error) throw error;+ return {+ async listForUser(userId) {+ const found = await rows<ContentDraftRow>('contentDrafts.listForUser', () => db+ .from('content_drafts')+ .select(COLUMNS)+ .eq('user_id', userId)+ .order('created_at', { ascending: false }));+ return found.map(toDraft);+ },++ findForUser,++ async create(draft, userId) {+ const { id, accountId, platform, status, createdAt: _c, updatedAt: _u, ...rest } = draft;+ await execute('contentDrafts.create', () => db.from('content_drafts').insert({+ id,+ user_id: userId,+ account_id: accountId,+ platform,+ status,+ data: rest,+ }));+ },++ // merges into data, so fields the update does not name are kept+ async updateForUser(id, updates, userId) {+ const current = await findForUser(id, userId);+ if (!current) return;+ const columns: { updated_at: string; status?: DraftStatus; data?: Partial<ContentDraft> } = { updated_at: new Date().toISOString() };+ const { status, ...dataUpdates } = updates;+ if (status) columns.status = status;+ if (Object.keys(dataUpdates).length > 0) {+ const { id: _id, accountId: _aid, platform: _p, status: _s, createdAt: _c, updatedAt: _u, ...currentData } = current;+ columns.data = { ...currentData, ...dataUpdates };+ }+ await execute('contentDrafts.update', () => db.from('content_drafts').update(columns).eq('id', id).eq('user_id', userId));+ },++ async deleteForUser(id, userId) {+ await execute('contentDrafts.delete', () => db.from('content_drafts').delete().eq('id', id).eq('user_id', userId));+ },+ };}```-Run `npm run typecheck` from the root after adding them.+Whether a missing draft is a `NotFoundError` is the service's decision: it calls `findForUser` first and throws. Only add a method without a `userId` if a cron job needs to scan every user, and name it without the `ForUser` suffix (`listAll`, `findById`, `updateById`).++Build the repository in `createServices()` in `backend/container.ts` (`const drafts = createContentDraftRepository(clients.supabase);`) and pass it to the services that need it. Add a test in `backend/tests/repositories/contentDraftRepository.test.ts` against the fake Supabase client (see `accountRepository.test.ts`), then run `npm run typecheck` from the root.### Step 6: Document the Schema@@ -169,9 +189,8 @@ Update `docs/architecture/database/SCHEMA.md` with:### Step 7: Wire Up the FeatureFollow the guides for:-- `docs/features/NEW_API_ENDPOINT.md` - add backend routes+- `docs/features/NEW_API_ENDPOINT.md` - add the validator, service, controller, route table and frontend `api.ts` methods- `docs/features/NEW_REACT_PAGE.md` - add frontend page-- `docs/features/NEW_API_ENDPOINT.md` - add frontend api.ts methods## Naming Conventions for New Tablesdiff --git a/docs/features/NEW_INTEGRATION.md b/docs/features/NEW_INTEGRATION.mdindex 9d1bff5..065e9db 100644--- a/docs/features/NEW_INTEGRATION.md+++ b/docs/features/NEW_INTEGRATION.md@@ -1,6 +1,6 @@# Guide: Adding a New Platform Integration-A "platform integration" is a new social or content platform (e.g., Reddit, Twitter/X, TikTok, LinkedIn). This guide walks through every layer that needs to change. Read `docs/guidelines/TYPESCRIPT.md` first: the types for the new platform are written before the code that uses them.+A "platform integration" is a new social or content platform (e.g., Reddit, Twitter/X, TikTok, LinkedIn). This guide walks through every layer that needs to change. Read `docs/architecture/backend/REQUEST_PIPELINE.md` for the backend layers and `docs/guidelines/TYPESCRIPT.md` for the typing rules: the types for the new platform are written before the code that uses them. The Reddit integration (`services/reddit/`, `redditAnalyticsService.ts`, `redditController.ts`, `redditRoutes.ts`) is the smallest complete example.## Decision Checklist Before Starting@@ -20,13 +20,16 @@ Document the answers in `DECISIONS.md` as a new ADR before writing any code.|---|---|---|| Shared | `shared/types/{platform}.ts` | Create: profile, post, analytics and cache types || Shared | `shared/types/domain.ts` | Add the platform to `Platform` and its fields to `Account` |-| Backend | `backend/services/{platform}.ts` | Create |-| Backend | `backend/routes/{platform}.ts` | Create |-| Backend | `backend/lib/db.ts` | Extend (if needed) |-| Backend | `backend/lib/cache.ts` | Extend |+| Backend | `backend/services/{platform}/` | Create: API client and pure analytics modules |+| Backend | `backend/services/{platform}AnalyticsService.ts` | Create: the feature service |+| Backend | `backend/services/accountService.ts`, `accountFactory.ts` | Extend: add and refresh accounts of the new platform |+| Backend | `backend/repositories/analyticsCacheRepository.ts` | Extend: cache methods and `deleteAllForAccount()` |+| Backend | `backend/validators/{platform}Validators.ts` | Create (for routes that take input) |+| Backend | `backend/controllers/{platform}Controller.ts` | Create |+| Backend | `backend/routes/{platform}Routes.ts`, `backend/routes/index.ts` | Create the route table and add it to `protectedRoutes` |+| Backend | `backend/container.ts` | Wire the new service || Backend | `backend/lib/safeAccount.ts` | Add secret fields to `SECRET_FIELDS` (and to `SafeAccount` in `shared/types/domain.ts`) |-| Backend | `backend/types/env.ts` | Add new secrets to `Env` |-| Backend | `backend/server.ts` | Mount router |+| Backend | `backend/types/env.ts`, `backend/lib/config.ts` | Add new secrets to `Env` and read them into `AppConfig` || Frontend | `frontend/src/services/api.ts` | Add methods || Frontend | `frontend/src/features/` | Create page(s) || Frontend | `frontend/src/App.tsx` | Add routes |@@ -85,22 +88,22 @@ export interface TweetPostResponse {}```-## Step 2: Create the Service File+## Step 2: Create the Platform Modules-Raw API payloads get interfaces in the service file, covering only the fields the code reads.+Platform modules in `backend/services/twitter/` talk to the API and compute analytics. They know nothing about users, the database or the cache. Raw API payloads get interfaces in the module, covering only the fields the code reads. Every call accepts an `AbortSignal`, and every failure is a typed error, so the error handler can answer it with the right status.```ts-// backend/services/twitter.ts-import type { TwitterAnalytics, TwitterTweet } from '../../shared/types/twitter.ts';+// backend/services/twitter/twitterApi.ts+import { UpstreamError, UpstreamTimeoutError, isAbortError } from '../../lib/errors.ts';-interface TwitterApiUser {+export interface TwitterApiUser {id: string;username: string;name: string;public_metrics: { followers_count: number; following_count: number; tweet_count: number };}-interface TwitterApiTweet {+export interface TwitterApiTweet {id: string;text: string;created_at: string;@@ -112,37 +115,58 @@ interface TwitterApiError {detail?: string;}-async function twitterFetch<T>(path: string, accessToken: string, method = 'GET', body: unknown = null): Promise<T> {+async function twitterFetch<T>(path: string, accessToken: string, signal?: AbortSignal, method = 'GET', body: unknown = null): Promise<T> {const options: RequestInit = {method,headers: {'Authorization': `Bearer ${accessToken}`,'Content-Type': 'application/json',},+ signal,};if (body) options.body = JSON.stringify(body);- const res = await fetch(`https://api.twitter.com/2${path}`, options);+ let res: Response;+ try {+ res = await fetch(`https://api.twitter.com/2${path}`, options);+ } catch (err) {+ if (isAbortError(err)) throw new UpstreamTimeoutError('Twitter', err);+ throw new UpstreamError(`Twitter could not be reached (${(err as Error).message})`, { cause: err });+ }if (!res.ok) {const err = await res.json().catch(() => ({ title: res.statusText })) as TwitterApiError;- throw new Error(`Twitter API ${res.status}: ${err.title || err.detail || res.statusText}`);+ throw new UpstreamError(`Twitter API ${res.status}: ${err.title || err.detail || res.statusText}`, { status: res.status });}return await res.json() as T;}-export async function getTwitterProfile(accessToken: string): Promise<TwitterApiUser> {- const { data } = await twitterFetch<{ data: TwitterApiUser }>('/users/me?user.fields=public_metrics,profile_image_url', accessToken);+export async function fetchTwitterProfile(accessToken: string, signal?: AbortSignal): Promise<TwitterApiUser> {+ const { data } = await twitterFetch<{ data: TwitterApiUser }>('/users/me?user.fields=public_metrics,profile_image_url', accessToken, signal);return data;}-export async function getTwitterTweets(userId: string, accessToken: string): Promise<TwitterApiTweet[]> {+export async function fetchTwitterTweets(userId: string, accessToken: string, signal?: AbortSignal): Promise<TwitterApiTweet[]> {const { data } = await twitterFetch<{ data?: TwitterApiTweet[] }>(`/users/${userId}/tweets?max_results=100&tweet.fields=public_metrics,created_at`,accessToken,+ signal,);return data || [];}-// Analytics computation (pure function - easy to test)+// POST is never retried: a repeated request could publish twice+export async function postTweet(text: string, accessToken: string, signal?: AbortSignal): Promise<{ data?: { id: string } }> {+ return twitterFetch('/tweets', accessToken, signal, 'POST', { text });+}+```++Analytics computation is a pure function in its own module, which is easy to test. Use the shared helpers in `backend/lib/analyticsMath.ts` (`sumOf`, `roundedAverage`, `medianOf`, ...) where the formula is the same as for the other platforms.++```ts+// backend/services/twitter/twitterAnalytics.ts+import { sumOf } from '../../lib/analyticsMath.ts';+import type { TwitterApiTweet, TwitterApiUser } from './twitterApi.ts';+import type { TwitterAnalytics, TwitterTweet } from '../../../shared/types/twitter.ts';+export function computeTwitterAnalytics(apiTweets: TwitterApiTweet[], profile: TwitterApiUser): TwitterAnalytics {const tweets: TwitterTweet[] = apiTweets.map(t => ({id: t.id,@@ -152,9 +176,9 @@ export function computeTwitterAnalytics(apiTweets: TwitterApiTweet[], profile: TretweetCount: t.public_metrics?.retweet_count || 0,replyCount: t.public_metrics?.reply_count || 0,}));- const totalLikes = tweets.reduce((sum, t) => sum + t.likeCount, 0);- const totalRetweets = tweets.reduce((sum, t) => sum + t.retweetCount, 0);- const totalReplies = tweets.reduce((sum, t) => sum + t.replyCount, 0);+ const totalLikes = sumOf(tweets, t => t.likeCount);+ const totalRetweets = sumOf(tweets, t => t.retweetCount);+ const totalReplies = sumOf(tweets, t => t.replyCount);const avgEngagement = tweets.length > 0? Number(((totalLikes + totalRetweets + totalReplies) / tweets.length).toFixed(2)): 0;@@ -171,11 +195,6 @@ export function computeTwitterAnalytics(apiTweets: TwitterApiTweet[], profile: Ttweets: tweets.slice(0, 50),};}--// Publishing (if applicable)-export async function postTweet(text: string, accessToken: string): Promise<{ data?: { id: string } }> {- return twitterFetch('/tweets', accessToken, 'POST', { text });-}```## Step 3: Strip Secrets From Responses@@ -188,111 +207,120 @@ const SECRET_FIELDS: (keyof Account)[] = ['accessToken', 'cookie', 'encryptedPasAdd the same field to the `Omit` list of `SafeAccount` in `shared/types/domain.ts`, so the frontend type does not claim the field exists.-## Step 4: Create Cache Functions+## Step 4: Add Cache Methods++Add the methods to the `AnalyticsCacheRepository` interface and its factory in `backend/repositories/analyticsCacheRepository.ts`. Build them on the private `readKey` and `writeKey` helpers, which return early without Redis, apply the TTL and the failure cooldown, and swallow Redis errors:-Use the private `readKey`, `writeKey` and `deleteKey` helpers in `cache.ts`; they return early without Redis and swallow Redis errors.+```ts+// in the AnalyticsCacheRepository interface+getTwitter(userId: string, accountId: string): Promise<TwitterAnalytics | null>;+setTwitter(userId: string, accountId: string, data: TwitterAnalytics): Promise<void>;++// in createAnalyticsCacheRepository()+async getTwitter(userId, accountId) {+ return (await readKey<TwitterAnalytics>(`twitter:${userId}:${accountId}`)) || null;+},++setTwitter: (userId, accountId, data) => writeKey(`twitter:${userId}:${accountId}`, data),+```++Add `deleteKey(`twitter:${userId}:${accountId}`)` to `deleteAllForAccount()`, so deleting the account also clears its cache (`AccountService.remove()` already calls it). Add a test to `backend/tests/repositories/analyticsCacheRepository.test.ts`.++## Step 5: Create the Feature Service++The service holds the rules: find the user's account, check it is on the right platform and has the credential it needs, read the cache, call the platform, write the cache.```ts-// Additions to backend/lib/cache.ts+// backend/services/twitterAnalyticsService.ts+import { fetchTwitterProfile, fetchTwitterTweets, postTweet } from './twitter/twitterApi.ts';+import { computeTwitterAnalytics } from './twitter/twitterAnalytics.ts';+import { NotFoundError, ValidationError } from '../lib/errors.ts';+import type { AccountRepository } from '../repositories/accountRepository.ts';+import type { AnalyticsCacheRepository } from '../repositories/analyticsCacheRepository.ts';+import type { RequestContext } from '../types/context.ts';import type { TwitterAnalytics } from '../../shared/types/twitter.ts';-export async function getTwitterCache(redis: Redis | null, userId: string, accountId: string): Promise<TwitterAnalytics | null> {- return (await readKey<TwitterAnalytics>(redis, `twitter:${userId}:${accountId}`)) || null;+export interface TwitterAnalyticsDeps {+ accounts: AccountRepository;+ cache: AnalyticsCacheRepository;+ context: RequestContext;}-export async function setTwitterCache(redis: Redis | null, userId: string, accountId: string, data: TwitterAnalytics): Promise<void> {- await writeKey(redis, `twitter:${userId}:${accountId}`, data);+export interface TwitterAnalyticsService {+ analytics(userId: string, accountId: string): Promise<TwitterAnalytics>;+ tweet(userId: string, accountId: string, text: string): Promise<string | undefined>;}-export async function deleteTwitterCache(redis: Redis | null, userId: string, accountId: string): Promise<void> {- await deleteKey(redis, `twitter:${userId}:${accountId}`);-}-```+export function createTwitterAnalyticsService({ accounts, cache, context }: TwitterAnalyticsDeps): TwitterAnalyticsService {+ const { signal } = context;-## Step 5: Create Route File+ async function tokenFor(userId: string, accountId: string): Promise<string> {+ const account = await accounts.findForUser(accountId, userId);+ if (!account || account.platform !== 'twitter') throw new NotFoundError('Twitter account not found');+ if (!account.accessToken) throw new ValidationError('No access token stored - reconnect this Twitter account');+ return account.accessToken;+ }-```ts-// backend/routes/twitter.ts-import { Hono } from 'hono';-import { getAccountById } from '../lib/db.ts';-import { getTwitterCache, setTwitterCache } from '../lib/cache.ts';-import { getTwitterProfile, getTwitterTweets, computeTwitterAnalytics, postTweet } from '../services/twitter.ts';-import type { AppEnv } from '../types/app.ts';-import type { TweetPostResponse } from '../../shared/types/twitter.ts';--interface TweetRequest {- text?: string;-}+ return {+ async analytics(userId, accountId) {+ const accessToken = await tokenFor(userId, accountId);+ const cached = await cache.getTwitter(userId, accountId);+ if (cached) return cached;++ const profile = await fetchTwitterProfile(accessToken, signal);+ const tweets = await fetchTwitterTweets(profile.id, accessToken, signal);+ const analytics = computeTwitterAnalytics(tweets, profile);+ await cache.setTwitter(userId, accountId, analytics);+ return analytics;+ },-const router = new Hono<AppEnv>();+ async tweet(userId, accountId, text) {+ const result = await postTweet(text, await tokenFor(userId, accountId), signal);+ return result.data?.id;+ },+ };+}+```-// Analytics-router.get('/accounts/:id/twitter-analytics', async (c) => {- const id = c.req.param('id');- const userId = c.get('userId');- const supabase = c.get('supabase');- const redis = c.get('redis');- try {- const account = await getAccountById(supabase, id, userId);- if (!account || account.platform !== 'twitter' || !account.accessToken) return c.json({ error: 'Account not found' }, 404);+Wire it in `backend/container.ts`: add `twitterAnalytics: TwitterAnalyticsService` to `Services` and `twitterAnalytics: createTwitterAnalyticsService({ accounts, cache, context })` to `createServices()`. Adding and refreshing accounts of the new platform goes in `AccountService` (`accountService.ts`) and a builder in `accountFactory.ts`, following the Reddit and Instagram branches.- const cached = await getTwitterCache(redis, userId, id);- if (cached) return c.json(cached);+## Step 6: Add the Validator, Controller and Route Table- const profile = await getTwitterProfile(account.accessToken);- const tweets = await getTwitterTweets(profile.id, account.accessToken);- const analytics = computeTwitterAnalytics(tweets, profile);+```ts+// backend/validators/twitterValidators.ts+export function parseTweet(body: Fields): TweetRequest {+ return { text: requiredString(body, 'text', 'Write the text of the tweet') };+}- await setTwitterCache(redis, userId, id, analytics);- return c.json(analytics);- } catch (err) {- console.error(`GET /accounts/${id}/twitter-analytics:`, (err as Error).message);- return c.json({ error: (err as Error).message }, 500);- }+// backend/controllers/twitterController.ts+export const getTwitterAnalytics = controller.createHandlers(async c => {+ const analytics = await servicesFor(c).twitterAnalytics.analytics(c.get('userId'), pathParam(c, 'id'));+ return c.json(analytics satisfies TwitterAnalytics);});-// Post a tweet-router.post('/accounts/:id/tweet', async (c) => {- const id = c.req.param('id');- const userId = c.get('userId');- const supabase = c.get('supabase');- const { text } = await c.req.json() as TweetRequest;- if (!text) return c.json({ error: 'Missing text' }, 400);- try {- const account = await getAccountById(supabase, id, userId);- if (!account || !account.accessToken) return c.json({ error: 'Account not found' }, 404);- const result = await postTweet(text, account.accessToken);- return c.json({ success: true, tweetId: result.data?.id } satisfies TweetPostResponse);- } catch (err) {- console.error(`POST /accounts/${id}/tweet:`, (err as Error).message);- return c.json({ error: (err as Error).message }, 500);- }+export const postTweetToAccount = controller.createHandlers(jsonBody(parseTweet), async c => {+ const tweetId = await servicesFor(c).twitterAnalytics.tweet(c.get('userId'), pathParam(c, 'id'), c.req.valid('json').text);+ return c.json({ success: true, tweetId } satisfies TweetPostResponse);});-export default router;-```+// backend/routes/twitterRoutes.ts+const router = new Hono<AppEnv>();-## Step 6: Mount in server.ts+router.get('/accounts/:id/twitter-analytics', ...getTwitterAnalytics);+router.post('/accounts/:id/tweet', ...postTweetToAccount);-```ts-// backend/server.ts-import twitterRouter from './routes/twitter.ts';-api.route('/', twitterRouter);+export default router;```-Add publishing and quota-spending routes to `PUBLISH_ROUTES` or `QUOTA_ROUTES` in `backend/lib/rateLimit/rules.ts` (see `docs/architecture/backend/RATE_LIMITING.md`).--## Step 7: Add Cache Invalidation on Account Delete+Add `twitterRoutes` to the list in `backend/routes/index.ts`. Add publishing and quota-spending routes to `PUBLISH_ROUTES` or `QUOTA_ROUTES` in `backend/lib/rateLimit/rules.ts` (see `docs/architecture/backend/RATE_LIMITING.md`). Put `TweetRequest` in `shared/types/twitter.ts` with the other shapes.-In `backend/routes/accounts.ts`, add the cache delete alongside existing ones:+## Step 7: Account Deletion-```ts-await deleteTwitterCache(redis, userId, id);-```+`AccountService.remove()` deletes the account row and calls `cache.deleteAllForAccount()`. Once Step 4 adds the new key there, nothing else changes.## Step 8: Declare New Secrets-Declare each secret in the `Env` interface in `backend/types/env.ts`, so `c.env.TWITTER_CLIENT_ID` type-checks. Use `?: string` for optional secrets and handle the missing case.+Declare each secret in the `Env` interface in `backend/types/env.ts`, then read it into `AppConfig` in `backend/lib/config.ts` with `cleanSecret()`, so services receive a trimmed value. Use `?: string` for optional secrets; a service that needs a missing one throws `NotConfiguredError` (503).```ts// backend/types/env.ts@@ -344,14 +372,15 @@ postTweet: (id: string, text: string) => request<TweetPostResponse>(`/accounts/$## Step 11: OAuth Flow (if applicable)If the platform uses OAuth:-- Backend: add `GET /auth/{platform}/start` and `GET /auth/{platform}/callback` routes+- Backend: add `GET /auth/{platform}/url` to the protected routes and `GET /auth/{platform}/callback` to `publicRoutes` in `backend/routes/index.ts` (with the `oauth` rate limit), following `instagramAuthController.ts` and `instagramConnectService.ts`+- The callback is the one controller that catches errors: it must always redirect the browser back to the app- Use the HMAC-signed state pattern in `backend/lib/oauthState.ts` (see `docs/architecture/backend/CACHING.md` and `ADR-006` in `DECISIONS.md`)- Store tokens in `accounts.data` - never in a separate table- Delete cache on every token refresh## Step 12: Verify-Run `npm run typecheck`, `npm run lint` and `npm test` from the repository root. Add tests for the pure helpers (such as `computeTwitterAnalytics`) in `backend/tests/services/twitter.test.ts`.+Run `npm run typecheck`, `npm run lint` and `npm test` from the repository root. Add tests for the pure helpers (such as `computeTwitterAnalytics`) in `backend/tests/services/twitter/twitterAnalytics.test.ts`, the API client against `fixtures/fakeFetch.ts` in `backend/tests/services/twitter/twitterApi.test.ts`, and the route table in `backend/tests/routes/twitterRoutes.test.ts`.## Security Checklistdiff --git a/docs/features/NEW_SCHEDULED_TASK.md b/docs/features/NEW_SCHEDULED_TASK.mdindex d60ebc9..19f1a84 100644--- a/docs/features/NEW_SCHEDULED_TASK.md+++ b/docs/features/NEW_SCHEDULED_TASK.md@@ -15,67 +15,94 @@ For most tasks: use the Cloudflare Worker cron first. It's simpler and doesn't r## Option A: Add a New Worker Cron Handler-### Step 1: Write the handler function+### Step 1: Write the job as a service method-There is no separate cron module. Cron work lives in the service or utils file it belongs to (`processScheduledPosts` in `backend/utils/scheduler.ts`, `autoRefreshInstagramTokens` in `backend/services/instagram.ts`) and takes the service-role Supabase client that `scheduled()` creates. Database access goes through `lib/db.ts`, called with `userId = null` because a cron job scans every user.+Cron work is a service method, wired in `backend/container.ts` like any other service (`scheduledPublisher.publishDue()` in `services/scheduledPublisher.ts`, `tokenRefresh.refreshExpiringInstagramTokens()` in `services/tokenRefreshService.ts`). The job receives repositories and a `RequestContext`, so it logs with the cron's request id and passes the cron's deadline signal to every platform call. A job that scans every user uses the cross-user repository methods (`listAll`, `findById`, `updateById`); add one to the repository if the job needs a query that does not exist yet, and keep it out of every request path.```ts-// backend/services/myPlatform.ts-import type { SupabaseClient } from '@supabase/supabase-js';-import { getAccounts, updateAccount } from '../lib/db.ts';--export async function autoRefreshMyPlatformTokens(supabase: SupabaseClient): Promise<void> {- const accounts = (await getAccounts(supabase)).filter(a => a.platform === 'myPlatform');-- for (const account of accounts) {- if (!account.accessToken) continue;- try {- const accessToken = await refreshMyPlatformToken(account.accessToken);- await updateAccount(supabase, account.id, { accessToken });- } catch (err) {- console.error(`cron/my-platform-refresh account ${account.id}:`, (err as Error).message);- }- }+// backend/services/myPlatformTokenRefreshService.ts+import { refreshMyPlatformToken } from './myPlatform/myPlatformTokens.ts';+import { errorFields } from '../lib/logger.ts';+import type { AccountRepository } from '../repositories/accountRepository.ts';+import type { RequestContext } from '../types/context.ts';++export interface MyPlatformTokenRefreshDeps {+ accounts: AccountRepository;+ context: RequestContext;+}++export interface MyPlatformTokenRefreshService {+ refreshTokens(): Promise<void>;+}++export function createMyPlatformTokenRefreshService({ accounts, context }: MyPlatformTokenRefreshDeps): MyPlatformTokenRefreshService {+ const { signal, log } = context;++ return {+ async refreshTokens() {+ const listed = (await accounts.listAll()).filter(account => account.platform === 'myPlatform');+ for (const account of listed) {+ if (!account.accessToken) continue;+ try {+ const accessToken = await refreshMyPlatformToken(account.accessToken, signal);+ await accounts.updateById(account.id, { accessToken });+ log.info('my platform token refreshed', { accountId: account.id });+ } catch (err) {+ // one failed account must not stop the others+ log.error('my platform token refresh failed', { accountId: account.id, ...errorFields(err) });+ }+ }+ },+ };}```-A cron job must never throw for one bad account: catch per account and log, as above. Comparing `a.platform` with `'myPlatform'` only type-checks once the platform is in the `Platform` union in `shared/types/domain.ts` (see `NEW_INTEGRATION.md`).+A cron job must never throw for one bad account: catch per account and log, as above. Comparing `account.platform` with `'myPlatform'` only type-checks once the platform is in the `Platform` union in `shared/types/domain.ts` (see `NEW_INTEGRATION.md`).++Add it to `Services` and `createServices()` in `backend/container.ts`:++```ts+myPlatformTokenRefresh: createMyPlatformTokenRefreshService({ accounts, context }),+```### Step 2: Register the Trigger in `wrangler.toml````toml[triggers]crons = [- "*/15 * * * *", # existing: processScheduledPosts- "0 0 * * *", # existing: autoRefreshInstagramTokens- "30 3 * * *" # new: autoRefreshMyPlatformTokens (runs at 3:30 AM UTC daily)+ "*/15 * * * *", # existing: scheduledPublisher.publishDue()+ "0 0 * * *", # existing: tokenRefresh.refreshExpiringInstagramTokens()+ "30 3 * * *" # new: myPlatformTokenRefresh.refreshTokens() (runs at 3:30 AM UTC daily)]```-**Important:** every cron trigger calls the same `scheduled()` handler exported from `backend/server.ts`. When you add a new cron string, you must also handle it there.+**Important:** every cron trigger calls the same `scheduled()` handler exported from `backend/server.ts`, which hands the expression to `runScheduledJob()` in `backend/jobs/scheduled.ts`. When you add a new cron string, you must also handle it there.-### Step 3: Dispatch in `server.ts`+### Step 3: Dispatch in `jobs/scheduled.ts````ts-// backend/server.ts-export default {- fetch: app.fetch,-- async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {- const supabase = getSupabase(env);-- if (event.cron === '*/15 * * * *') {- ctx.waitUntil(processScheduledPosts(supabase));- } else if (event.cron === '0 0 * * *') {- ctx.waitUntil(autoRefreshInstagramTokens(supabase));- } else if (event.cron === '30 3 * * *') {- ctx.waitUntil(autoRefreshMyPlatformTokens(supabase));- }- },-} satisfies ExportedHandler<Env>;+// backend/jobs/scheduled.ts+export const PUBLISH_DUE_POSTS_CRON = '*/15 * * * *';+export const REFRESH_TOKENS_CRON = '0 0 * * *';+export const REFRESH_MY_PLATFORM_TOKENS_CRON = '30 3 * * *';++export async function runScheduledJob(cron: string, env: Env): Promise<void> {+ const context = cronContext(cron);+ const services = createServices({ supabase: getSupabase(env), redis: getRedis(env) }, readConfig(env), context);++ if (cron === PUBLISH_DUE_POSTS_CRON) {+ // ...+ } else if (cron === REFRESH_TOKENS_CRON) {+ await services.tokenRefresh.refreshExpiringInstagramTokens();+ } else if (cron === REFRESH_MY_PLATFORM_TOKENS_CRON) {+ await services.myPlatformTokenRefresh.refreshTokens();+ } else {+ context.log.warn('no job for this cron', { cron });+ }+}```-`event.cron` is the exact cron string from `wrangler.toml`, so the strings must match character for character. Run `npm run typecheck` before deploying.+`event.cron` is the exact cron string from `wrangler.toml`, so the strings must match character for character. `server.ts` already wraps the job in `ctx.waitUntil()`, and the cron context gives it a `cron-` request id and a 14 minute deadline. Add a test in `backend/tests/services/` with fake repositories or the fake Supabase client (see `tokenRefreshService.test.ts`), and run `npm run typecheck` before deploying.### Step 4: Test Locallydiff --git a/docs/guidelines/API_CONVENTIONS.md b/docs/guidelines/API_CONVENTIONS.mdindex 857e0e8..b348248 100644--- a/docs/guidelines/API_CONVENTIONS.md+++ b/docs/guidelines/API_CONVENTIONS.md@@ -4,7 +4,7 @@### Success responses-Every response body has a TypeScript type in `shared/types/` (`domain.ts`, `youtube.ts`, `instagram.ts`, `reddit.ts`). The route checks the object it returns with `satisfies`, and the matching `api.ts` method returns the same type, so a change to a response shape is caught by `npm run typecheck` on both sides.+Every response body has a TypeScript type in `shared/types/` (`domain.ts`, `youtube.ts`, `instagram.ts`, `reddit.ts`). The controller checks the object it returns with `satisfies`, and the matching `api.ts` method returns the same type, so a change to a response shape is caught by `npm run typecheck` on both sides.Most endpoints return the data directly as a JSON object or array:@@ -23,15 +23,17 @@ Most endpoints return the data directly as a JSON object or array:### Error responses-Errors return a JSON object with an `error` key, or, in routes whose success body has `success: true`, `success: false` with a `message` (the `ApiFailure` type in `shared/types/domain.ts`):+Every failure has a 4xx or 5xx status and one body, the `ApiFailure` type in `shared/types/domain.ts`, written by `backend/middleware/errorHandler.ts`:```json-{ "error": "Account not found" }-{ "error": "Missing required field: scheduledAt" }-{ "success": false, "message": "Account not found" }+{ "success": false, "code": "NOT_FOUND", "message": "Account not found", "requestId": "3f2a..." }+{ "success": false, "code": "VALIDATION_ERROR", "message": "accountId, mediaUrl, and scheduledAt are required", "requestId": "3f2a..." }+{ "success": false, "code": "RATE_LIMITED", "message": "...", "requestId": "3f2a...", "retryAfter": 12 }```-The `request()` function in `frontend/src/services/api.ts` throws an `Error` with `data.message` or `data.error` when the status is not 2xx. Methods whose route can send `success: false` with a 2xx status return `ApiResult<T>`, so the caller checks `success` before reading the data. Keep one shape per route.+`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.++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@@ -39,56 +41,64 @@ The `request()` function in `frontend/src/services/api.ts` throws an `Error` wit|---|---|| `200` | Successful GET, PUT, DELETE || `201` | Successful POST that creates a resource |-| `400` | Bad request - missing fields, invalid input |-| `401` | Authentication required or token invalid (returned by `requireAuth`) |-| `403` | Authenticated but not authorized (wrong user for this resource) |-| `404` | Resource not found |-| `429` | Rate limit exceeded; returned by the `rateLimit` middleware only, with `Retry-After` and `{ success: false, error, retryAfter }` (see `docs/architecture/backend/RATE_LIMITING.md`) |-| `500` | Unexpected server error |+| `400` | `VALIDATION_ERROR` - missing fields, invalid input, or a stored field the request needs is missing |+| `401` | `UNAUTHORIZED` - authentication required or token invalid (thrown by `requireAuth`) |+| `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`) |+| `500` | `DATABASE_ERROR` or `INTERNAL_ERROR` - a failed query or an unexpected error |+| `502` | `UPSTREAM_ERROR` - YouTube, Instagram or Reddit 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 |-## Request Bodies+## Request Bodies and Query Strings-POST and PUT handlers read the request body via:+Input is parsed and checked before the controller runs, by a validator passed to `controller.createHandlers(...)`:```ts-const body = await c.req.json() as ScheduledPostRequest;+export const createScheduledPost = controller.createHandlers(jsonBody(parseScheduledPost), async c => {+ const post = await servicesFor(c).scheduledPosts.create(c.get('userId'), c.req.valid('json'));+ return c.json({ success: true, post } satisfies ScheduledPostResponse);+});```-`c.req.json()` is untyped, so cast it once to the shared request type where it enters. The cast does not check anything at runtime: always validate required fields and return 400 for missing ones:+The parser in `backend/validators/` returns the shared request type and throws `ValidationError` (400) for a missing or malformed field:```ts-const { scheduledAt, accountId, mediaUrl } = body;-if (!scheduledAt || !accountId || !mediaUrl) {- return c.json({ error: 'Missing required fields: scheduledAt, accountId, mediaUrl' }, 400);+export function parseScheduledPost(body: Fields): ScheduledPostRequest {+ const required = 'accountId, mediaUrl, and scheduledAt are required';+ return {+ ...postDetails(body),+ accountId: requiredString(body, 'accountId', required),+ mediaUrl: requiredString(body, 'mediaUrl', required),+ scheduledAt: requiredString(body, 'scheduledAt', required),+ platform: platform(body),+ mediaType: mediaType(body, SCHEDULED_MEDIA_TYPES),+ };}```+Use `jsonBody(parse)` for a JSON body and `queryParams(parse)` for a query string (both in `backend/middleware/validate.ts`). A body that is not a JSON object is a 400. Never read `c.req.json()` or `c.req.query()` in a controller.+## URL Parameters-Access route params via `c.req.param('name')`:+Read path parameters with `pathParam(c, 'name')` from `backend/controllers/http.ts`, which throws `ValidationError` when the parameter is missing:```ts-router.delete('/accounts/:id', async (c) => {- const id = c.req.param('id');- // ...+export const deleteAccount = controller.createHandlers(async c => {+ await servicesFor(c).accounts.remove(c.get('userId'), pathParam(c, 'id'));+ return c.json({ success: true } satisfies SuccessResponse);});```-Access query params via `c.req.query('name')`, which returns `string | undefined`:--```ts-router.get('/ig-container/:id/status', async (c) => {- const containerId = c.req.param('id');- const accountId = c.req.query('accountId');- // ...-});-```+Query parameters go through a validator, like `parseContainerStatusQuery` for `GET /ig-container/:containerId/status?accountId=`.## Authentication HeaderThe frontend always sends: `Authorization: Bearer <supabase-access-token>`-The backend extracts and verifies it in `requireAuth`. Route handlers access the verified `userId` via `c.get('userId')`.+The backend extracts and verifies it in `requireAuth`. Controllers read the verified `userId` via `c.get('userId')` and pass it to the service.## Route Naming@@ -109,7 +119,7 @@ addAccount: (input: string) => request<YouTubeAccountAddResponse>('/accounts', {deleteAccount: (id: string) => request<SuccessResponse>(`/accounts/${id}`, { method: 'DELETE' }),refreshAccount: (id: string) => request<AccountResponse>(`/accounts/${id}/refresh`, { method: 'POST' }),getAnalytics: (id: string) => request<YouTubeAnalyticsPayload>(`/accounts/${id}/analytics`),-createScheduledPost: (data: ScheduledPostRequest) => request<ApiResult<ScheduledPostResponse>>('/scheduled-posts', { method: 'POST', body: JSON.stringify(data) }),+createScheduledPost: (data: ScheduledPostRequest) => request<ScheduledPostResponse>('/scheduled-posts', { method: 'POST', body: JSON.stringify(data) }),```Name frontend methods to describe what they do from the user's perspective, not the HTTP method: `addAccount` not `postAccount`, `deleteAccount` not `removeAccount`.diff --git a/docs/guidelines/CLOUDFLARE_WORKERS.md b/docs/guidelines/CLOUDFLARE_WORKERS.mdindex 5b2f663..2364d51 100644--- a/docs/guidelines/CLOUDFLARE_WORKERS.md+++ b/docs/guidelines/CLOUDFLARE_WORKERS.md@@ -2,20 +2,22 @@## Environment Access-Access environment variables and secrets via `c.env` (in Hono handlers) or `env` (in the `scheduled` cron handler). Never use `process.env` - it does not exist in the Workers runtime.+Environment variables and secrets arrive as `c.env` (in middleware and controllers) or `env` (in the `scheduled` cron handler). Never use `process.env` - it does not exist in the Workers runtime.-Every binding is declared in the `Env` interface in `backend/types/env.ts`. Add a new secret there (optional ones as `?: string`) before reading it, or the type checker rejects `c.env.MY_SECRET`.+Every binding is declared in the `Env` interface in `backend/types/env.ts`. Add a new secret there (optional ones as `?: string`) before reading it, or the type checker rejects `c.env.MY_SECRET`. Application code does not read `c.env` directly: `readConfig(env)` in `backend/lib/config.ts` cleans the values into an `AppConfig`, and services receive that config from `createServices()`. Only `lib/config.ts` and the client factories in `backend/database/` read the raw variables.```ts-// In a Hono handler or middleware (the router is new Hono<AppEnv>()):-const apiKey = c.env.YOUTUBE_API_KEY; // string | undefined-const url = c.env.SUPABASE_URL; // string+// backend/lib/config.ts: pasted secrets can carry a byte order mark or stray whitespace+youtubeApiKey: cleanSecret(env.YOUTUBE_API_KEY),-// In the cron handler (backend/server.ts):+// a service reads the cleaned value+if (!config.youtubeApiKey) throw new NotConfiguredError(NO_YOUTUBE_KEY_MESSAGE);++// the cron handler (backend/server.ts) hands env to the jobexport default {fetch: app.fetch,async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {- const supabase = getSupabase(env);+ ctx.waitUntil(runScheduledJob(event.cron, env));},} satisfies ExportedHandler<Env>;```@@ -44,17 +46,25 @@ The Workers runtime does not have Node.js built-ins. These are unavailable:## `ctx.waitUntil()`-In cron handlers, use `ctx.waitUntil()` to keep the Worker alive for async background work:+In the cron handler, use `ctx.waitUntil()` to keep the Worker alive for async background work:```tsasync scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {- ctx.waitUntil(myAsyncJob(getSupabase(env)));+ ctx.waitUntil(runScheduledJob(event.cron, env));}```Without `ctx.waitUntil()`, the Worker isolate may terminate before the promise resolves.-Do not use `ctx.waitUntil()` in HTTP request handlers - just `await` the work normally.+In controllers, `await` the work the response needs. Use `c.executionCtx.waitUntil()` only for work that must outlive the response, as the Overview does for cache warming, and give that work its own deadline, because the request's `signal` aborts when the client disconnects:++```ts+if (warmTasks.length > 0) c.executionCtx.waitUntil(Promise.allSettled(warmTasks));+```++## Cancellation++Every platform `fetch` receives an `AbortSignal`. In a request it is the context's `signal` (client disconnect or a 30 second deadline); in a cron run it is a 14 minute deadline built in `backend/jobs/scheduled.ts`. Services get it from their `RequestContext` and pass it down, so abandoned work stops instead of spending CPU time and platform quota.## Stateless Requests@@ -69,14 +79,15 @@ export default { fetch: async (request: Request, env: Env) => {return Response.json(cachedData);}};-// GOOD - use Redis or Supabase for persistence-const cached = await redis.get<MyData>('my-key');-if (cached) return c.json(cached);-const fresh = await fetchData(env);-await redis.set('my-key', fresh);-return c.json(fresh);+// GOOD - use Redis or Supabase for persistence, through a repository+const cached = await cache.getVideos(userId, accountId);+if (cached?.videos) return { videos: cached.videos, fetchedAt: cached.fetchedAt };+const videos = await fetchAllVideos(playlistId, apiKey, MAX_PLAYLIST_PAGES, signal);+await cache.setVideos(userId, accountId, { videos, fetchedAt: new Date().toISOString() });```+Module-level state is acceptable only as a per-isolate optimization that is safe to lose, such as the cache cooldown in `analyticsCacheRepository.ts` and the rate limiter's in-memory fallback.+## Bundle SizeWrangler bundles `backend/server.ts` and everything it imports into a single ESM file, stripping the types without checking them. Type-only imports (`import type`, including everything from `shared/types`) add nothing to the bundle. Large dependencies increase cold-start time and may exceed Workers bundle size limits. The current backend has minimal dependencies:@@ -134,15 +145,14 @@ Or push to `main` with changes in `backend/`, `shared/`, `tsconfig.base.json` or## CORS-The current CORS configuration in `server.ts`, `cors({ exposeHeaders: RATE_LIMIT_HEADERS })`, allows all origins and lets the browser read the rate limit headers. For a more restrictive policy, return the `FRONTEND_URL` as the allowed origin. `c.env` only exists inside a request, so pass a function:+`backend/middleware/cors.ts` allows only the app's own origins: `FRONTEND_URL` and the comma-separated `ALLOWED_ORIGINS`, read through `corsOrigins()` in `backend/lib/config.ts`. `c.env` only exists inside a request, so the origin is a function:```ts-app.use('*', cors({- origin: (origin, c) => c.env.FRONTEND_URL ?? origin,- allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],- allowHeaders: ['Content-Type', 'Authorization'],- exposeHeaders: RATE_LIMIT_HEADERS,-}));+export const apiCors = cors({+ origin: (origin, c) => (corsOrigins(readConfig(c.env), c.req.url).includes(origin) ? origin : null),+ exposeHeaders: [...RATE_LIMIT_HEADERS, 'X-Request-Id'],+ maxAge: 600,+});```-This change would need to be applied carefully - it would break requests from local development (`localhost:5173`) unless the allowed origin list includes it.+When the Worker itself runs on `localhost` or `127.0.0.1`, `corsOrigins()` adds the Vite dev server (`http://localhost:5173` and `http://127.0.0.1:5173`), so local development works without extra settings while a deployed Worker never allows them. To allow another browser origin, add it to `ALLOWED_ORIGINS`; do not widen the function. See `docs/architecture/backend/MIDDLEWARE.md`.diff --git a/docs/guidelines/ERROR_HANDLING.md b/docs/guidelines/ERROR_HANDLING.mdindex 6b7b504..5087189 100644--- a/docs/guidelines/ERROR_HANDLING.md+++ b/docs/guidelines/ERROR_HANDLING.md@@ -1,35 +1,60 @@# Error Handling Standards+Every backend failure is a typed error thrown where the problem is found and formatted in one place. `docs/architecture/backend/REQUEST_PIPELINE.md` has the full table of errors, codes and statuses.++## Typed Errors (`backend/lib/errors.ts`)++| 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) |+| `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 |+| `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`) |++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).+## Layer-by-Layer Rules-### External API Calls (services/)+### Platform API Calls (`services/youtube/`, `services/instagram/`, `services/reddit/`)-Throw descriptive errors immediately when the external API returns an error object. Let the caller decide what to do:+Throw an `UpstreamError` as soon as the platform returns an error, keeping the platform's own wording (users can act on it) and its reason and status:```ts-const data = await res.json() as YouTubeApiErrorBody;-if (data.error) throw new Error(data.error.message);+const data = await response.json() as T & YouTubeApiErrorBody;+if (data.error) {+ throw new UpstreamError(data.error.message, { reason: data.error.errors?.[0]?.reason || '', status: data.error.code });+}```-Cast the parsed JSON once to an interface that covers the fields the service reads (see `docs/guidelines/TYPESCRIPT.md`).+`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`).++Pass the request's `AbortSignal` to every `fetch`. A cancelled or timed out call becomes an `UpstreamTimeoutError`; a network failure an `UpstreamError`:-For HTTP-level errors (non-200 but no error body):```ts-if (!res.ok) throw new Error(`YouTube API ${res.status}: ${await res.text()}`);+try {+ response = await fetch(url.toString(), { signal });+} catch (err) {+ if (isAbortError(err)) throw new UpstreamTimeoutError('YouTube', err);+ throw new UpstreamError(`YouTube could not be reached (${(err as Error).message})`, { cause: err });+}```-### Database Calls (lib/db.ts)+### Database Calls (`repositories/`)-Check the Supabase `error` field and throw:+Run every query through `execute`, `rows` or `maybeRow` in `repositories/query.ts`. A thrown error or a returned Supabase `error` becomes a `DatabaseError` named after the operation:```ts-const { data, error } = await supabase.from('accounts').select('*').eq('user_id', userId);-if (error) throw error;+const found = await rows<AccountRow>('accounts.listForUser', () => db.from('accounts').select(COLUMNS).eq('user_id', userId));```-Supabase errors are objects with `message`, `code`, and `details`. Throwing the error object directly passes the message through cleanly.+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`.-### Cache Operations (lib/cache.ts)+### Cache Operations (`repositories/analyticsCacheRepository.ts`)Always catch and fall back silently - cache failures must never surface to users. Every `catch` returns an explicit fallback with a one-line reason, so no catch block is empty:@@ -38,41 +63,46 @@ try {return await redis.get<T>(key);} catch {// a cache miss falls back to the live api+ markDown();return null;}```-`cache.ts` keeps this in three private helpers (`readKey`, `writeKey`, `deleteKey`) that every exported function uses. Do not log cache errors - they create noise for transient Redis connection issues.+The repository keeps this in three private helpers (`readKey`, `writeKey`, `deleteKey`) that every method uses. Do not log cache errors - they create noise for transient Redis connection issues.++### Services (`services/*Service.ts`)-### Route Handlers (routes/)+Services hold the rules, so they throw most errors: `NotFoundError` when a `...ForUser` lookup returns `null`, `ValidationError` when a stored field the call needs is missing or a business rule fails, `ConflictError` for a duplicate, `NotConfiguredError` when a Worker secret is not set. Let platform and database errors propagate unchanged.-Wrap the main logic in try/catch, log the error, and return a JSON error response:+Catch only when one failure must not stop other work, and say why:```ts-router.get('/accounts/:id/analytics', async (c) => {- const id = c.req.param('id');- const userId = c.get('userId');- const supabase = c.get('supabase');- try {- const account = await getAccountById(supabase, id, userId);- if (!account) return c.json({ error: 'Account not found' }, 404);- const analytics = await getAnalytics(account, c.env);- return c.json(analytics);- } catch (err) {- console.error(`GET /accounts/${id}/analytics:`, (err as Error).message);- return c.json({ error: (err as Error).message }, 500);- }+// one failure must not stop the rest; results line up with the accounts by index+const settled = await Promise.allSettled(listed.map(account => refreshListed(userId, account)));+```++### Controllers (`controllers/`)++Controllers do not catch errors. A thrown error goes straight to the error handler:++```ts+export const getRedditAnalytics = controller.createHandlers(async c => {+ const result = await servicesFor(c).redditAnalytics.analytics(c.get('userId'), pathParam(c, 'id'));+ return c.json(result satisfies RedditCacheData);});```-Caught errors are `unknown` in strict TypeScript, so read the message with `(err as Error).message`.+The one exception is the Instagram OAuth callback, which catches every error and redirects the browser back to the accounts page with `ig_error`, because the user arrives there from Instagram, not from the app.++### Global Error Handler (`middleware/errorHandler.ts`)++Registered with `app.onError(errorHandler)` and `app.notFound(notFoundHandler)`. It is the only place a failure becomes a response:++```json+{ "success": false, "code": "NOT_FOUND", "message": "Account not found", "requestId": "3f2a..." }+```-**Status codes:**-- `400` - bad request (missing required fields, invalid input)-- `401` - unauthorized (handled by `requireAuth`, not route handlers)-- `403` - forbidden (account belongs to another user)-- `404` - resource not found-- `500` - unexpected server error+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`.### Frontend API Calls@@ -95,35 +125,24 @@ async function handleSubmit() {}```-The `api.ts` `request()` function throws an `Error` built from the response's `message` or `error` field when the status is not 2xx, so `(err as Error).message` is the backend's error string. A body with `success: false` sent with a 2xx status is returned, not thrown; methods typed `ApiResult<T>` make the caller check `success`. See `docs/architecture/frontend/API_LAYER.md`.+The `api.ts` `request()` function throws an `Error` for any status outside 2xx, with the message from `failureMessage(status, body)` in `frontend/src/lib/apiErrors.ts`: the backend's `message`, plus `(request <id>)` on a 5xx so the user can quote it. A 2xx response is always a success, so callers never check `success`. See `docs/architecture/frontend/API_LAYER.md`.-### Global Error Handler (server.ts)+## Logging-The Hono global error handler catches any uncaught errors that bubble up past route handlers:+Log through `lib/logger.ts`: services use `context.log`, middleware and controllers use `requestLogger(c)`. Each call writes one JSON line with the level, message, request id, user id and any fields:```ts-app.onError((err, c) => {- console.error('Worker error:', err.message);- return c.json({ error: 'Internal server error' }, 500);-});+log.error('scheduled post failed', { postId: post.id, ...errorFields(err) });```-This is the last resort. Route handlers should not rely on it.--## Logging--Use `console.error()` for errors in route handlers - Cloudflare Workers captures these in the dashboard logs.--Format: `console.error('METHOD /path:', (err as Error).message)` - includes the route for easy filtering.--Do not log sensitive values: access tokens, API keys, user emails, Supabase URLs.+`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.-Do not use `console.log()` in production code paths except for cron job status messages (these are useful for monitoring scheduled tasks).+Do not log sensitive values: access tokens, API keys, cookies, user emails, Supabase URLs.## User-Facing Error MessagesBackend errors should be descriptive but not expose implementation details:-- Good: `'Account not found'`, `'Instagram API rate limit exceeded'`, `'Missing required field: scheduledAt'`+- Good: `'Account not found'`, `'This channel is already added'`, `'scheduledAt must be a valid future date'`- Bad: `'supabase error: duplicate key value violates unique constraint accounts_pkey'`-When the Supabase or Instagram API returns a message that is end-user readable, pass it through. When it is technical (e.g., PostgreSQL constraint violation), translate it.+Say what went wrong and what to do (`'No session cookie stored - re-add this account with a session cookie from reddit.com DevTools'`). When the platform API returns a message that is end-user readable, `UpstreamError` passes it through. Database driver messages never reach the client.diff --git a/docs/guidelines/HONO.md b/docs/guidelines/HONO.mdindex 463e4ae..8ca34fd 100644--- a/docs/guidelines/HONO.md+++ b/docs/guidelines/HONO.md@@ -1,135 +1,141 @@# Hono Guidelines-## Route Handler Structure+The backend is split into layers: middleware, route tables, controllers, services and repositories. `docs/architecture/backend/REQUEST_PIPELINE.md` describes each layer and the order a request passes through them. These rules cover the Hono-facing parts: route tables, controllers and middleware.-Every router is `new Hono<AppEnv>()`, so `c.get()`, `c.set()` and `c.env` are typed from `backend/types/app.ts` and `backend/types/env.ts`. Every route handler follows this exact shape:+## Controller Structure++Every controller is built with `controller.createHandlers(...)` from `backend/controllers/http.ts`, so `c.get()`, `c.set()`, `c.env` and `c.req.valid()` are typed from `backend/types/app.ts`. Every controller follows this shape:```ts-router.METHOD('/path', async (c) => {- const userId = c.get('userId'); // from requireAuth middleware- const supabase = c.get('supabase'); // from client injection middleware- const redis = c.get('redis'); // may be null - always guard-- // 1. Read inputs- const id = c.req.param('id');- const body = await c.req.json() as MyThingRequest; // POST/PUT only-- // 2. Validate inputs early- if (!body.name) return c.json({ error: 'Missing required field: name' }, 400);-- // 3. Execute business logic (in try/catch)- try {- const result = await doSomething(supabase, userId, id);- return c.json(result satisfies MyThingResponse);- } catch (err) {- console.error('METHOD /path:', (err as Error).message);- return c.json({ error: (err as Error).message }, 500);- }+export const updateScheduledPost = controller.createHandlers(jsonBody(parseScheduledPostUpdate), async c => {+ // 1. read the verified user id, path parameters and the validated input+ // 2. call one service method+ const post = await servicesFor(c).scheduledPosts.update(c.get('userId'), pathParam(c, 'id'), c.req.valid('json'));+ // 3. pick the status and build the response, checked against the shared type+ return c.json({ success: true, post } satisfies ScheduledPostUpdateResponse);});```-Request and response types (`MyThingRequest`, `MyThingResponse`) live in `shared/types/` so the frontend reads the same shape. A handler extracted from the router (like `callbackHandler` in `routes/instagramAuth.ts`) takes `c: AppContext`.+A controller does nothing else. It does not validate fields by hand (the validator ran first), does not query Supabase or Redis (repositories do), does not hold business rules (services do), and does not catch errors (the error handler does).++Request and response types live in `shared/types/` so the frontend reads the same shape. Controllers check every response with `satisfies`.## Context Values-Access these via `c.get()` - never reconstruct them inside handlers. They are declared in `AppVariables` in `backend/types/app.ts`; add a key there before setting a new one.+Access these via `c.get()` - never reconstruct them inside controllers. They are declared in `AppVariables` in `backend/types/app.ts`; add a key there before setting a new one, and keep each one small and request-scoped.| Key | Type | Notes ||---|---|---|+| `requestId` | `string` | Set by `hono/request-id`. Returned in `X-Request-Id` and in every error body |+| `signal` | `AbortSignal` | Set by `requestContext`. Aborts on client disconnect or after 30 seconds || `userId` | `string` (UUID) | Set by `requireAuth`. Always present on protected routes || `userEmail` | `string \| undefined` | Set by `requireAuth`. May be undefined on older JWTs |-| `supabase` | `SupabaseClient` | Set by client injection middleware |-| `redis` | `Redis \| null` | Set by client injection middleware. Null if not configured |-| `rateLimitRedis` | `Redis \| null` | Set by client injection middleware for the rate limiter only. See `docs/architecture/backend/RATE_LIMITING.md` |+| `supabase` | `SupabaseClient` | Set by `injectClients`. Read by `servicesFor(c)`, not by controllers |+| `redis` | `Redis \| null` | Set by `injectClients`. Null if not configured. Read by `servicesFor(c)` |+| `rateLimitRedis` | `Redis \| null` | Set by `injectClients` for the rate limiter only. See `docs/architecture/backend/RATE_LIMITING.md` |++Services never receive the Hono context. `servicesFor(c)` builds the request's services with a `RequestContext` (`requestId`, `signal`, `log`) from `requestContextOf(c)`, and the controller passes the user id as an argument.## Reading Request Data```ts-// URL params (/accounts/:id)-const id = c.req.param('id');+// path parameters (/accounts/:id); throws ValidationError when missing+const id = pathParam(c, 'id');-// Query string (?limit=10), string | undefined-const limit = c.req.query('limit');+// JSON body or query string, parsed and checked by the validator passed to createHandlers+const changes = c.req.valid('json');+const query = c.req.valid('query');-// JSON body (POST/PUT): cast once to the shared request type-const body = await c.req.json() as ScheduledPostRequest;+// the verified user id from requireAuth+const userId = c.get('userId');+```-// Headers-const auth = c.req.header('Authorization');+Input enters through a validator, never through `c.req.json()` or `c.req.query()` in a controller. `jsonBody(parse)` and `queryParams(parse)` in `backend/middleware/validate.ts` wrap Hono's `validator`; each parser lives in `backend/validators/<feature>Validators.ts`, reads fields with the helpers in `validators/fields.ts` (`requiredString`, `optionalString`, `optionalNumber`, `optionalBoolean`, `optionalArray`, `presentField`) and throws `ValidationError` with a message the user can act on:++```ts+export function parseRedditAccount(body: Fields): RedditAccountInput {+ return {+ username: requiredString(body, 'username', 'Username is required'),+ cookie: requiredString(body, 'cookie', 'Session cookie is required - ...'),+ };+}```-Never destructure `c.req` directly - always call the method. `c.req.json()` returns untyped JSON, so cast it once where it enters and validate the fields the handler needs before using them.+Validators check shape and presence. Rules that need stored data (a post must be pending, an account must be Instagram) belong in the service.## Returning Responses```ts// JSON success, checked against the shared response typereturn c.json({ success: true, posts } satisfies ScheduledPostListResponse); // 200-return c.json(data, 201); // 201 Created+return c.json(item, 201); // 201 Created-// JSON error-return c.json({ error: 'message' }, 400); // client error-return c.json({ error: (err as Error).message }, 500); // server error--// Early return (validation fail)-if (!id) return c.json({ error: 'Missing id' }, 400);+// a failure: throw a typed error from lib/errors.ts, usually in the service+throw new NotFoundError('Scheduled post not found'); // 404```-Always return `c.json()`. Never use `return new Response()` inside app route handlers (that is for the Worker's `fetch()` export).+Always return `c.json()` (or `c.redirect()` for the OAuth callback). Never build an error body by hand: `{ error }` and `{ success: false, message }` bodies are not used. Never use `return new Response()` inside app controllers (that is for the Worker's `fetch()` export).-## Router Organization+## Route Table Organization```ts-// backend/routes/myFeature.ts+// backend/routes/myFeatureRoutes.tsimport { Hono } from 'hono';+import { listMyResources, createMyResource, deleteMyResource } from '../controllers/myFeatureController.ts';import type { AppEnv } from '../types/app.ts';const router = new Hono<AppEnv>();-router.get('/my-resources', async (c) => { ... });-router.post('/my-resources', async (c) => { ... });-router.delete('/my-resources/:id', async (c) => { ... });+router.get('/my-resources', ...listMyResources);+router.post('/my-resources', ...createMyResource);+router.delete('/my-resources/:id', ...deleteMyResource);export default router;```-Mount in `server.ts`:+Add the table to the list in `backend/routes/index.ts`, which mounts every protected table on `protectedRoutes`:```ts-import myFeatureRouter from './routes/myFeature.ts';-api.route('/', myFeatureRouter);+import myFeatureRoutes from './myFeatureRoutes.ts';+// ...+for (const routes of [accountRoutes, /* ... */, myFeatureRoutes]) {+ protectedRoutes.route('/', routes);+}```+A route that must answer without a token is registered on `publicRoutes` in the same file. Register a fixed path before a parameterized one that could match it (`/accounts/refresh-all` before `/accounts/:id/refresh`).+## Middleware-Middleware is `async (c: AppContext, next: Next) => { ... await next(); }`. Never skip `next()` unless intentionally short-circuiting:+Middleware is `async (c: AppContext, next: Next): Promise<void> => { ... await next(); }`. To reject a request, throw a typed error; the error handler formats it:```ts-// backend/middleware/auth.ts: short-circuits (returns early without calling next)-import type { Next } from 'hono';-import type { AppContext } from '../types/app.ts';--export async function requireAuth(c: AppContext, next: Next) {- const token = c.req.header('Authorization')?.replace('Bearer ', '');- if (!token) return c.json({ error: 'Unauthorized' }, 401);+// backend/middleware/auth.ts+export async function requireAuth(c: AppContext, next: Next): Promise<void> {+ const token = c.req.header('Authorization')?.match(BEARER)?.[1];+ if (!token) throw new UnauthorizedError('Sign in to use the API');// verify the token, set context, then continuec.set('userId', user.id);await next();}```+The rate limiter is the one middleware that answers directly (`429`), using `errorBody()` from `middleware/errorHandler.ts` so its body matches every other failure. See `docs/architecture/backend/MIDDLEWARE.md` for the stack and its order.+## Error Handling Rules-- Always wrap external calls (Supabase, platform APIs) in try/catch-- Log with `console.error('VERB /path:', (err as Error).message)` - include the route in the log-- Never throw from a route handler - catch and return `c.json({ error }, status)`-- 400 for client errors (missing fields, invalid format, resource not found)-- 500 for server errors (DB failures, external API failures)-- Never expose stack traces in the response body+- Throw typed errors from `backend/lib/errors.ts`; never catch an error only to turn it into JSON+- Pick the error by what went wrong: `ValidationError` (400), `NotFoundError` (404, also for another user's record), `ConflictError` (409), `NotConfiguredError` (503), `UpstreamError` (502), `UpstreamTimeoutError` (504); a failed query becomes `DatabaseError` (500) in the repository helpers+- Log through `requestLogger(c)` or the service's `context.log`, never `console`; the error handler already logs every failure with the request id+- Never expose stack traces or driver messages in the response body+- The Instagram OAuth callback is the only controller that catches errors, because it must always redirect the browser++See `docs/guidelines/ERROR_HANDLING.md`.## What Not To Do-- Do not import `env` directly - access it via `c.env` or via the middleware-injected clients-- Do not use `c.env` directly in route handlers - always use `c.get('supabase')` / `c.get('redis')`-- Do not build Supabase clients inside route handlers - the middleware does this once per request+- Do not import `env` directly - services get the cleaned `AppConfig` from `lib/config.ts` through `servicesFor(c)`+- Do not read `c.env` in controllers, and do not pass the Hono context to services+- Do not build Supabase or Redis clients inside controllers or services - the middleware does this once per request+- Do not call `supabase.from()` outside `backend/repositories/`- Do not use `app.use()` for business logic - that is for cross-cutting middleware onlydiff --git a/docs/guidelines/NAMING.md b/docs/guidelines/NAMING.mdindex af26c22..843095c 100644--- a/docs/guidelines/NAMING.md+++ b/docs/guidelines/NAMING.md@@ -4,10 +4,15 @@| Location | Convention | Examples ||---|---|---|-| Backend routes | `camelCase.ts` | `accounts.ts`, `scheduledPosts.ts`, `instagramAuth.ts` |-| Backend services | `camelCase.ts` | `instagram.ts`, `youtube.ts` |-| Backend lib | `camelCase.ts` | `db.ts`, `cache.ts`, `supabase.ts`, `redis.ts` |-| Backend middleware | `camelCase.ts` | `auth.ts`, `rateLimit.ts` |+| Backend route tables | `<feature>Routes.ts` | `accountRoutes.ts`, `scheduledPostRoutes.ts`, `instagramAuthRoutes.ts` |+| Backend controllers | `<feature>Controller.ts` | `accountController.ts`, `scheduledPostController.ts` |+| Backend validators | `<feature>Validators.ts` | `accountValidators.ts`, `publishingValidators.ts` |+| Backend feature services | `<feature>Service.ts` | `accountService.ts`, `youtubeAnalyticsService.ts` |+| Backend platform modules | `<platform><Topic>.ts` in `services/<platform>/` | `youtube/youtubeApi.ts`, `instagram/instagramPublishing.ts`, `reddit/redditApi.ts` |+| Backend repositories | `<table>Repository.ts` | `accountRepository.ts`, `scheduledPostRepository.ts`, `analyticsCacheRepository.ts` |+| Backend database clients | `camelCase.ts` in `database/` | `supabase.ts`, `redis.ts` |+| Backend lib | `camelCase.ts` | `errors.ts`, `logger.ts`, `config.ts`, `safeAccount.ts` |+| Backend middleware | `camelCase.ts` | `auth.ts`, `cors.ts`, `rateLimit.ts`, `errorHandler.ts` || Type-only modules | `camelCase.ts` | `shared/types/domain.ts`, `backend/types/env.ts`, `backend/types/app.ts` || Frontend pages | `PascalCase.tsx` | `Login.tsx`, `Overview.tsx` || Frontend feature components | `PascalCase.tsx` | `ChannelAnalytics.tsx`, `AccountManager.tsx` |@@ -17,16 +22,18 @@| Frontend shared hooks | `use-kebab-case.ts` in `src/hooks` | `use-mobile.ts` || Frontend utilities | `camelCase.ts` | `formatters.ts`, `api.ts`, `utils.ts` || shadcn components | `kebab-case.tsx` | `button.tsx`, `card.tsx` (generated - do not rename) |-| Tests | `<source name>.test.ts` in the workspace `tests/` folder | `backend/tests/services/youtube.test.ts` |+| Tests | `<source name>.test.ts` in the workspace `tests/` folder | `backend/tests/routes/accountRoutes.test.ts`, `backend/tests/services/youtube/youtubeChannels.test.ts` || Documentation | `SCREAMING_SNAKE_CASE.md` | `OVERVIEW.md`, `TYPESCRIPT.md`, `SCHEMA.md` |Use `.tsx` only for files that contain JSX; everything else is `.ts`.## Functions-- Backend route handlers: `camelCase` verb + noun - `getAnalytics(c)`, `createAccount(c)`, `deletePost(c)`-- Backend service functions: `camelCase` verb + noun - `fetchChannelData()`, `computeVideoAnalytics()`, `publishIGContainer()`-- Backend db functions: `camelCase` verb + noun - `getAccounts()`, `createPost()`, `updateAccount()`, `deletePost()`+- Backend controllers: `camelCase` verb + noun - `getChannelAnalytics`, `addYouTubeAccount`, `deleteScheduledPost`+- Backend validators: `parse` + noun - `parseScheduledPost`, `parseVideoLibraryQuery`+- Backend service factories: `create` + service name - `createAccountService`, `createScheduledPublisher`; their methods are short verbs, because the service names the noun - `accounts.list`, `accounts.refresh`, `scheduledPosts.removeAll`+- Backend platform functions: `camelCase` verb + noun - `fetchChannelData()`, `computeVideoAnalytics()`, `createMediaContainer()`+- Backend repository methods: verb + `ForUser` when scoped to the verified user - `listForUser()`, `findForUser()`, `updateForUser()`, `deleteForUser()`; the cross-user methods for cron jobs have no suffix - `listAll()`, `findById()`, `updateById()`, `listDue()`, `claim()`- Frontend API methods: `camelCase` verb + noun - `getAnalytics()`, `createScheduledPost()`, `deleteAccount()`- React event handlers: `handle` + PascalCase noun/event - `handleSubmit()`, `handleDeleteClick()`, `handleInputChange()`- React custom hooks: `use` + PascalCase noun - `useAppContext()`, `useIsMobile()`@@ -37,6 +44,8 @@ Use `.tsx` only for files that contain JSX; everything else is `.ts`.- Component props: `<Component>Props` - `ChannelHeaderProps`- Request and response bodies: `<Thing>Request`, `<Thing>Response` - `ScheduledPostRequest`, `ScheduledPostListResponse`- Raw upstream payloads: platform name + `Api` + entity - `YouTubeApiVideo`+- Services and their dependencies: `<Name>Service` and `<Name>Deps` - `AccountService`, `AccountServiceDeps`; repositories: `<Table>Repository` - `AccountRepository`+- Errors: `<Reason>Error` extending `AppError` - `NotFoundError`, `UpstreamTimeoutError`; error codes are `SCREAMING_SNAKE_CASE` - `NOT_FOUND`## Variables@@ -65,9 +74,9 @@ Use `.tsx` only for files that contain JSX; everything else is `.ts`.- Resource nesting: `/accounts/:id/ig-analytics` (not `/ig-analytics/:accountId`)- Kebab-case multi-word paths - `/refresh-all`, `/ig-publish`, `/process-scheduled`-## Supabase Cache Keys+## Redis Cache Keys-`{entity}:{userId}:{accountId}` - `videos:abc-123:def-456`, `ig:abc-123:def-456`+`{entity}:{userId}:{accountId}` - `videos:abc-123:def-456`, `ig:abc-123:def-456`, `reddit:abc-123:def-456` (defined only in `repositories/analyticsCacheRepository.ts`)## Environment Variablesdiff --git a/docs/guidelines/SUPABASE.md b/docs/guidelines/SUPABASE.mdindex 782a8b2..d379cd6 100644--- a/docs/guidelines/SUPABASE.md+++ b/docs/guidelines/SUPABASE.md@@ -4,111 +4,112 @@| Client | Key used | Created by | Purpose ||---|---|---|---|-| Service client | `SUPABASE_SERVICE_KEY` | `getSupabase(env)` in `lib/supabase.ts` | All DB operations (bypasses RLS) |-| Auth client | `SUPABASE_ANON_KEY` | `getSupabaseAuth(env)` in `lib/supabase.ts` | JWT verification only (`auth.getUser(token)`) |+| Service client | `SUPABASE_SERVICE_KEY` | `getSupabase(env)` in `backend/database/supabase.ts` | All DB operations (bypasses RLS) |+| Auth client | `SUPABASE_ANON_KEY` | `getSupabaseAuth(env)` in `backend/database/supabase.ts` | JWT verification only (`auth.getUser(token)`) || Frontend client | `VITE_SUPABASE_ANON_KEY` | `lib/supabase.ts` in frontend | Supabase Auth (sign in/out, session) - no DB queries |**Rule:** The service client is the only client used for database queries. The auth client is used exclusively in `requireAuth` middleware. The frontend client is used only for Supabase Auth, never for database access.## Query Pattern-All Supabase queries are in `backend/lib/db.ts`. Route handlers never call `supabase.from()` directly.+All Supabase queries live in `backend/repositories/`, one repository per table. Services call repository methods; controllers and services never call `supabase.from()` directly.```ts-// In lib/db.ts:-export async function getAccounts(supabase: SupabaseClient, userId: string | null = null): Promise<Account[]> {- let query = supabase.from('accounts').select('id, platform, data');- if (userId) query = query.eq('user_id', userId);- const { data, error } = await query;- if (error) throw error;- return ((data || []) as AccountRow[]).map(row => ({ id: row.id, platform: row.platform, ...row.data }));+// backend/repositories/accountRepository.ts+export interface AccountRepository {+ listForUser(userId: string): Promise<Account[]>;+ // ...}-// In route handler:-import { getAccounts } from '../lib/db.ts';+export function createAccountRepository(db: SupabaseClient): AccountRepository {+ return {+ async listForUser(userId) {+ const found = await rows<AccountRow>('accounts.listForUser', () => db.from('accounts').select(COLUMNS).eq('user_id', userId));+ return found.map(toAccount);+ },+ // ...+ };+}-router.get('/accounts', async (c) => {- const supabase = c.get('supabase');- const userId = c.get('userId');- const accounts = await getAccounts(supabase, userId);- return c.json(accounts.map(safeAccount) satisfies AccountListResponse);-});+// backend/services/accountService.ts+list: userId => accounts.listForUser(userId),```-The client is untyped (there is no generated database type), so each `db.ts` function casts the rows once to a local row interface (`AccountRow`, `ScheduledPostRow`) and returns a `shared/types` shape. Every exported `db.ts` function declares its return type.+`backend/container.ts` builds each repository with the request's service client and hands it to the services that need it. A test passes the fake Supabase client from `backend/tests/fixtures/fakeSupabase.ts` instead.++The client is untyped (there is no generated database type), so each repository casts the rows once to a local row interface (`AccountRow`, `ScheduledPostRow`) through `rows<T>()` or `maybeRow<T>()`, and maps them to a `shared/types` shape. Every repository method is declared on the repository's interface with its return type.## Error Handling-Always check the `error` field from Supabase responses and throw:+Run every query through `execute`, `rows` or `maybeRow` in `backend/repositories/query.ts`. Each takes an operation name and a function that builds the query:```ts-const { data, error } = await supabase.from('accounts').select('*');-if (error) throw error;+await execute('settings.save', () => db+ .from('settings')+ .upsert({ user_id: userId, key: SETTINGS_KEY, value: settings }, { onConflict: 'user_id,key' }));```-Do not silently ignore errors. Route handlers will catch the thrown error and return a 500 JSON response.+A thrown error or a returned Supabase `error` becomes a `DatabaseError` named after the operation. The error handler answers it with `500` and a plain message, and logs the driver's message with the operation and request id; the driver's text never reaches the client. Do not check `error` by hand and do not silently ignore it.-## Upserts+`maybeRow` returns `null` when no row matches. Whether that is a `NotFoundError` is the service's decision.-Use `onConflict` to specify the conflict resolution key:+## Upserts-```ts-const { error } = await supabase- .from('settings')- .upsert({ user_id: userId, key: 'api_keys', value: keys }, { onConflict: 'user_id,key' });-if (error) throw error;-```+Use `onConflict` to specify the conflict resolution key, as in `settingsRepository.saveForUser()` above.## jsonb Data Column Pattern-The `data` jsonb column stores platform-specific fields for accounts and post metadata for scheduled posts. The pattern for reading and updating:+The `data` jsonb column stores platform-specific fields for accounts and post metadata for scheduled posts and tracked items. The pattern for reading and updating, from `accountRepository.ts`:```ts// Reading: spread data into the returned object-return { id: row.id, platform: row.platform, ...row.data };+function toAccount(row: AccountRow): Account {+ return { id: row.id, platform: row.platform, ...row.data };+}// Updating: merge new fields with existing data (don't replace the whole object)-const current = await getAccountById(supabase, id, userId);-if (!current) throw new Error('Account not found: ' + id);-const { id: _, platform: currentPlatform, ...currentData } = current;+const current = await find(id, userId);+if (!current) throw new NotFoundError('Account not found');+const { id: _id, platform: currentPlatform, ...currentData } = current;const { platform: newPlatform, ...dataUpdates } = updates;-await supabase.from('accounts').update({- platform: newPlatform || currentPlatform,- data: { ...currentData, ...dataUpdates }, // merge, not replace-}).eq('id', id);+await execute('accounts.update', () => {+ const query = db.from('accounts').update({+ platform: newPlatform || currentPlatform,+ data: { ...currentData, ...dataUpdates }, // merge, not replace+ }).eq('id', id);+ return userId ? query.eq('user_id', userId) : query;+});```**Never replace the entire `data` object** without first reading the current value - you'll lose fields that aren't in the update.## Row Isolation-Every user-scoped query must include `.eq('user_id', userId)`. Functions that intentionally omit this (for cron use) should document it with a comment:+Every user-scoped repository method takes the verified `userId`, ends in `ForUser`, and includes `.eq('user_id', userId)`. Methods that intentionally omit the filter serve the cron jobs only; they have no `ForUser` suffix and the repository's interface says so in its one comment:```ts-// No userId filter - used by cron scheduler to process all users' posts-export async function getDuePosts(supabase: SupabaseClient): Promise<ScheduledPost[]> {- const { data, error } = await supabase- .from('scheduled_posts')- .select('id, account_id, status, scheduled_at, data')- .eq('status', 'pending')- .lte('scheduled_at', new Date().toISOString());- if (error) throw error;- return (data || []).map(rowToPost);+// methods named ...ForUser filter by the verified user id; listDue, claim and updateById serve the schedulers across all users+export interface ScheduledPostRepository {+ listForUser(userId: string): Promise<ScheduledPost[]>;+ listDue(): Promise<ScheduledPost[]>;+ // ...}```+Only `scheduledPublisher.ts` and `tokenRefreshService.ts` call the cross-user methods (`listAll`, `findById`, `updateById`, `listDue`, `claim`). See `docs/architecture/database/SECURITY.md`.+## Client Lifecycle-Supabase clients are created fresh per request in the Worker - they are stateless HTTP clients and safe to create on each request. Do not cache client instances in module-level variables; they would hold references to a specific request's `env` bindings.+Supabase clients are created fresh per request in the Worker by the `injectClients` middleware (and once per cron run in `backend/jobs/scheduled.ts`) - they are stateless HTTP clients and safe to create on each request. Do not cache client instances in module-level variables; they would hold references to a specific request's `env` bindings.```ts-// lib/supabase.ts+// backend/database/supabase.tsexport function getSupabase(env: Env): SupabaseClient {return createClient(clean(env.SUPABASE_URL), clean(env.SUPABASE_SERVICE_KEY), CLIENT_OPTS);}```-`CLIENT_OPTS` turns off session persistence and passes a `fetch` wrapper that drops the `cache` request option, which Workers reject. Import `SupabaseClient` as a type (`import type { SupabaseClient } from '@supabase/supabase-js'`) when a function takes the client as a parameter.+`CLIENT_OPTS` turns off session persistence and passes a `fetch` wrapper that drops the `cache` request option, which Workers reject. Import `SupabaseClient` as a type (`import type { SupabaseClient } from '../types/app.ts'`, which re-exports it) when a function takes the client as a parameter.## Frontend - No DB Accessdiff --git a/docs/guidelines/TYPESCRIPT.md b/docs/guidelines/TYPESCRIPT.mdindex c483de9..a9594a6 100644--- a/docs/guidelines/TYPESCRIPT.md+++ b/docs/guidelines/TYPESCRIPT.md@@ -26,7 +26,7 @@ Because Node runs `.ts` files by removing the types, only syntax that can be era- No `enum`. Use a union of string literals, or an object with `as const`.- No `namespace` with runtime code, no parameter properties (`constructor(private x)`), no `import x = require()`.- Type-only imports use `import type { X }` or `import { type X }`. `verbatimModuleSyntax` makes this an error otherwise, and without it Node would try to import a value that does not exist.-- Relative imports name the file with its extension: `import { getAccounts } from '../lib/db.ts'`. The frontend's `@/` imports stay extensionless because Vite resolves them; files imported by Node tests (see `docs/workflows/TESTING.md`) use relative `.ts` imports only.+- Relative imports name the file with its extension: `import { safeAccount } from '../lib/safeAccount.ts'`. The frontend's `@/` imports stay extensionless because Vite resolves them; files imported by Node tests (see `docs/workflows/TESTING.md`) use relative `.ts` imports only.## Where Types Live@@ -34,7 +34,10 @@ Because Node runs `.ts` files by removing the types, only syntax that can be era|---|---|| Shapes the API sends or receives: accounts, posts, analytics, request bodies, responses | `shared/types/*.ts` (`domain.ts`, `youtube.ts`, `instagram.ts`, `reddit.ts`) || Worker bindings and Hono context | `backend/types/env.ts` (`Env`), `backend/types/app.ts` (`AppEnv`, `AppContext`, `AppVariables`) |-| Raw payloads from YouTube, Instagram and Reddit | The service module that parses them (`YouTubeApiVideo` in `services/youtubeApi.ts`) |+| Request metadata for services | `backend/types/context.ts` (`RequestContext`) |+| Service and repository contracts | The module that implements them (`AccountService` and `AccountServiceDeps` in `services/accountService.ts`, `AccountRepository` in `repositories/accountRepository.ts`); `Services` in `backend/container.ts` |+| Error codes | `ApiErrorCode` and `ApiFailure` in `shared/types/domain.ts`; the error classes in `backend/lib/errors.ts` |+| Raw payloads from YouTube, Instagram and Reddit | The platform module that parses them (`YouTubeApiVideo` in `services/youtube/youtubeApi.ts`) || Props, hook results, local state | The component or hook file, exported when another file needs it |`shared/types` holds types only. It never imports runtime code, so either app can import it with `import type` and nothing from it reaches a bundle. The backend imports it by relative path (`../../shared/types/domain.ts`), the frontend by alias (`@shared/types/domain.ts`), except files that Node tests import, which use the relative path.@@ -43,32 +46,39 @@ When a route's response changes, change its type in `shared/types` first. The ty## Typing Rules-- `any` is a lint error. Use a precise type. At a true boundary (JSON from `fetch`, `c.req.json()`, a test fake), use `unknown` or cast once to a named interface right where the value enters: `const body = await c.req.json() as AddAccountBody`.+- `any` is a lint error. Use a precise type. At a true boundary (JSON from `fetch`, a request body, a test fake), use `unknown` or cast once to a named interface right where the value enters: `const data = await response.json() as T & YouTubeApiErrorBody`. Request bodies enter through a validator in `backend/validators/`, which reads each field from `Fields` (`Record<string, unknown>`) and returns the shared request type.- Describe external API payloads with an interface covering the fields the code reads, not the whole upstream schema.- Exported functions declare their return type. Local helpers may rely on inference.- `interface` for object shapes, `type` for unions, aliases and mapped types.- Prefer narrowing (`if (!account) return ...`) over non-null assertions. Use `!` only where an earlier check guarantees the value, and never to hide a missing check.- Caught errors are `unknown`: read the message with `(err as Error).message`.-- Response objects built in a route are checked with `satisfies`: `return c.json({ success: true, posts } satisfies ScheduledPostListResponse)`.+- Response objects built in a controller are checked with `satisfies`: `return c.json({ success: true, posts } satisfies ScheduledPostListResponse)`.- No `// @ts-ignore` or `// @ts-expect-error`. Fix the type, or cast narrowly with a one-line comment that says why.### Backend patterns```ts-import { Hono } from 'hono';-import type { AppEnv, AppContext } from '../types/app.ts';+// controllers: createHandlers keeps the validator's types, so c.req.valid() is typed+export const addRedditAccount = controller.createHandlers(jsonBody(parseRedditAccount), async c => {+ const account = await servicesFor(c).accounts.addReddit(c.get('userId'), c.req.valid('json'));+ return c.json({ success: true, account: safeAccount(account) } satisfies AccountResponse);+});-const app = new Hono<AppEnv>();+// services: an interface for the contract and one for the dependencies, built by a factory+export interface SettingsService {+ githubSettings(userId: string): Promise<GitHubSettingsResponse>;+}-app.get('/accounts', async (c) => {- const accounts = await getAccounts(c.get('supabase'), c.get('userId'));- return c.json(accounts.map(safeAccount) satisfies AccountListResponse);-});+export function createSettingsService({ settings, config }: SettingsDeps): SettingsService {+ return { /* ... */ };+}-// handlers extracted from the router take the typed context-export async function callbackHandler(c: AppContext) { /* ... */ }+// middleware and helpers outside a router take the typed context+export async function requireAuth(c: AppContext, next: Next): Promise<void> { /* ... */ }```+Failures are typed errors from `backend/lib/errors.ts` (`throw new NotFoundError('Account not found')`), never a returned error object.+### Frontend patterns```tsx@@ -97,14 +107,14 @@ ES modules everywhere (`"type": "module"` in both workspaces). Use `import`/`exp| Kind | Name | Example ||---|---|---|-| Backend modules | `camelCase.ts` | `server.ts`, `db.ts`, `instagramApi.ts` |+| Backend modules | `camelCase.ts`, with the layer as a suffix where there is one | `server.ts`, `accountRoutes.ts`, `accountController.ts`, `accountService.ts`, `accountRepository.ts`, `instagramApi.ts` || Frontend helpers and services | `camelCase.ts` | `api.ts`, `formatters.ts`, `overviewStats.ts` || React components and pages | `PascalCase.tsx` | `Overview.tsx`, `AppContext.tsx` || Feature hooks | `useCamelCase.ts` in the feature folder | `useOverviewData.ts` || Shared hooks | `use-kebab-case.ts` in `src/hooks` | `use-account-analytics.ts` || shadcn generated files | `kebab-case.tsx`, do not rename | `dropdown-menu.tsx` || Type-only modules | `camelCase.ts` | `shared/types/domain.ts`, `backend/types/env.ts` |-| Tests | `<source name>.test.ts` in the workspace `tests/` folder | `backend/tests/services/youtube.test.ts` |+| Tests | `<source name>.test.ts` in the workspace `tests/` folder | `backend/tests/services/youtube/youtubeChannels.test.ts` |A `.tsx` extension is only for files that contain JSX.@@ -120,45 +130,39 @@ Write no comments by default. Add a comment only when the WHY is non-obvious and**Do write (sparingly):**```ts-// userId=null means service-level - used by cron handlers that scan all users-export async function getAccounts(supabase: SupabaseClient, userId: string | null = null): Promise<Account[]> { ... }+// methods named ...ForUser filter by the verified user id; the others reach every user and are only for cron jobs+export interface AccountRepository { ... }```## Naming-- Functions and variables: `camelCase` - `getAccounts`, `computeVideoAnalytics`, `scheduledAt`+- Functions and variables: `camelCase` - `listForUser`, `computeVideoAnalytics`, `scheduledAt`- Types, interfaces and React components: `PascalCase` - `ScheduledPost`, `ChannelAnalytics`- Constants: `SCREAMING_SNAKE_CASE` only for true module-level constants- Prop interfaces: `<Component>Props`; request and response types: `<Thing>Request`, `<Thing>Response`Prefer names that describe intent, not implementation:-- `getVideosCache` not `redisGetVideos`+- `cache.getVideos` not `redisGetVideos`- `requireAuth` not `jwtMiddleware`- `safeAccount` not `stripToken`## Error Handling-In **route handlers**, always catch and return JSON errors:-```ts-try {- const data = await someOperation();- return c.json(data);-} catch (err) {- console.error('GET /my-route:', (err as Error).message);- return c.json({ error: (err as Error).message }, 500);-}-```+In **controllers**, do not catch: a thrown error reaches `middleware/errorHandler.ts`, which answers with the status for its code and `{ success: false, code, message, requestId }`.-In **service functions**, throw descriptive errors and let the caller decide how to handle them:+In **services and platform modules**, throw a typed error from `backend/lib/errors.ts` and let it propagate:```ts-if (data.error) throw new Error(data.error.message);+if (!account) throw new NotFoundError('Account not found');+if (data.error) throw new UpstreamError(data.error.message, { status: data.error.code });```-In **cache functions**, always catch and silently ignore; cache failures must never bubble up:+In **the cache repository**, always catch and fall back; cache failures must never bubble up:```ts-try { return await redis.get<T>(key); } catch { return null; }+try { return await redis.get<T>(key); } catch { markDown(); return null; }```+See `docs/guidelines/ERROR_HANDLING.md`.+In **frontend components**, catch API errors and show toasts:```tstry {diff --git a/docs/mcp/SEQUENTIAL_THINKING.md b/docs/mcp/SEQUENTIAL_THINKING.mdindex 6d8e531..b8dc0de 100644--- a/docs/mcp/SEQUENTIAL_THINKING.md+++ b/docs/mcp/SEQUENTIAL_THINKING.md@@ -67,7 +67,7 @@ Sequential Thinking would work through:- How to store credentials (in `accounts.data` jsonb alongside Instagram pattern)- Token refresh strategy (poll `Set-Cookie` header on each API call)- Which shapes go in `shared/types/reddit.ts` (profile, post, analytics, cache entry)-- New cache keys to add to `cache.ts`+- New cache keys to add to `repositories/analyticsCacheRepository.ts`- New routes to add to backend- New analytics page structure- How the sidebar/nav changesdiff --git a/docs/philosophy/ARCHITECTURE.md b/docs/philosophy/ARCHITECTURE.mdindex 22d968b..1822c5c 100644--- a/docs/philosophy/ARCHITECTURE.md+++ b/docs/philosophy/ARCHITECTURE.md@@ -10,13 +10,13 @@ The Cloudflare Worker sits at the edge, close to the user. All data fetching - f### 2. One source of auth truth-Authentication is Supabase JWTs. The Worker verifies the JWT on every protected request. `userId` derived from the verified JWT is the only identity that matters. No session state. No cookies. The JWT is verified by checking its signature against the Supabase JWT secret - not by calling Supabase on every request.+Authentication is Supabase JWTs. The Worker verifies the JWT on every protected request by asking Supabase Auth (`auth.getUser(token)` with the anon key, in `requireAuth`), which checks the signature, the expiry and whether the session was revoked. `userId` derived from the verified JWT is the only identity that matters. No session state in the Worker. No cookies. The per-IP rate limit runs before this check, so a flood of bad tokens never reaches Supabase Auth.-**Why:** Stateless auth scales to zero infrastructure. JWTs are self-verifying.+**Why:** The Worker keeps no auth state of its own, and a signed-out session stops working at once.### 3. Application-layer isolation instead of RLS-Every DB query appends `.eq('user_id', userId)` where `userId` comes from the verified JWT. The Worker uses the service-role key (which bypasses RLS). RLS is not relied upon for security.+Every user-scoped repository method (named `...ForUser`) appends `.eq('user_id', userId)` where `userId` comes from the verified JWT and is passed down from the controller. The Worker uses the service-role key (which bypasses RLS). RLS is enabled with no policies only to keep the public anon key away from the tables; it is not relied upon for isolation.**Why:** RLS adds complexity without benefit when the application layer already enforces isolation. The service-role key is needed for admin operations (cron jobs, token refresh) that run without a user JWT. See `ADR-011`.@@ -24,7 +24,7 @@ Every DB query appends `.eq('user_id', userId)` where `userId` comes from the ve### 4. Fail silently on the cache-Redis is optional infrastructure. The cache layer always catches errors and returns `null` on failure. The application falls through to the source of truth (Supabase / platform API). A Redis outage is invisible to users.+Redis is optional infrastructure. The cache repository (`analyticsCacheRepository.ts`) always catches errors and returns `null` on failure. The application falls through to the source of truth (Supabase / platform API). A Redis outage is invisible to users.**Why:** Cache is a performance optimization, not a correctness requirement. Making it optional makes the system more resilient. See `ADR-008`.@@ -42,6 +42,12 @@ New platform-specific fields go into the `data jsonb` column on `accounts` or `sEvery layer is TypeScript in `strict` mode, and the API contract lives once in `shared/types/`, used by both the Worker and the frontend. Nothing is compiled ahead of time: Wrangler, Vite and Node strip the types, and `npm run typecheck` gates every deploy and pull request. Only erasable syntax is allowed, so any file can run directly under Node. See `ADR-030` (which replaces `ADR-010`) and `docs/guidelines/TYPESCRIPT.md`.+### 8. One job per layer, one error contract++A request passes through middleware, a route table, a controller, a service and a repository, and each layer has one job: HTTP concerns in middleware and controllers, business rules in services, queries in repositories. Services never see the Hono context, so a cron job runs the same code with its own request context. Every failure is a typed error that one error handler turns into `{ success: false, code, message, requestId }`. See `ADR-032` and `docs/architecture/backend/REQUEST_PIPELINE.md`.++**Why:** Each rule has one place to live and one place to test, and the client handles every failure the same way.+## What This Architecture Is Not**Not a microservices architecture.** One Worker serves all backend routes. One Hono app. One entry point.diff --git a/docs/philosophy/PERFORMANCE.md b/docs/philosophy/PERFORMANCE.mdindex 5772d88..87f5084 100644--- a/docs/philosophy/PERFORMANCE.md+++ b/docs/philosophy/PERFORMANCE.md@@ -23,20 +23,13 @@ Request| Reddit analytics | `reddit:{userId}:{accountId}` | 6 hours | || OAuth state | none (HMAC-signed token, see `lib/oauthState.ts`) | 10 minutes | Security-critical - do not extend |-Cache invalidation happens on:-- Account deletion (explicit `redis.del()`)-- Token refresh (explicit `redis.del()`)-- Manual "Refresh" action in the UI (calls the API which skips cache)+Cache entries change on:+- Expiry: every analytics key is written with a 6 hour TTL (`ANALYTICS_TTL_SECONDS` in `repositories/analyticsCacheRepository.ts`)+- Account deletion: `cache.deleteAllForAccount()` removes the account's three keys+- Opening YouTube or Instagram analytics: those load live and overwrite the entry+- A cache version bump: an entry with an old `version` reads as a miss-There is no time-based expiration for analytics caches yet (known issue). Until TTLs are set, users see stale analytics until they explicitly refresh.--### Adding TTLs--When fixing the known TTL issue, use the Upstash Redis `EX` option:--```ts-await redis.set(key, data, { ex: 3600 }); // expire after 1 hour-```+All Redis access goes through `analyticsCacheRepository.ts`, which applies the TTL, the version check and the failure cooldown in one place.## Rate Limiting Costdiff --git a/docs/philosophy/SECURITY.md b/docs/philosophy/SECURITY.mdindex 4644229..70d9b21 100644--- a/docs/philosophy/SECURITY.md+++ b/docs/philosophy/SECURITY.md@@ -64,7 +64,7 @@ The Instagram OAuth flow uses a self-verifying HMAC state token to prevent CSRF:2. Nothing is stored server-side; the timestamp inside the signed payload expires the state after 10 minutes3. On OAuth callback: verify HMAC before accepting the `code` parameter-If the HMAC check fails, the callback returns 400 and discards the code. An attacker cannot forge a valid state without the `INSTAGRAM_APP_SECRET`.+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`.## Rate Limiting@@ -72,15 +72,17 @@ Every `/api` request is rate limited per client IP before authentication, so a f## Input Validation-The backend validates:-- Required fields: `if (!field) return c.json({ error: 'Missing: field' }, 400)`-- Platform enum: only known `platform` values are accepted when creating accounts+The backend validates every body and query string before the controller runs: a parser in `backend/validators/` checks required fields, types and allowed values (`mediaType`, `platform`, sort order) and throws `ValidationError`, which the error handler answers with `400`. Services then check the rules that need stored data, such as a scheduled time in the future or a post that is still pending.++- Required fields: `requiredString(body, 'url', 'url is required')`+- Allowed values: only known media types are accepted, and scheduled posts accept only the `instagram` platform- File types: Cloudinary upload accepts only image and video MIME typesThe backend does not validate:-- URL formats in user-provided content (the platform API will reject invalid URLs)+- URL formats in user-provided content (the platform API will reject invalid URLs), except tracked content links (Reddit or YouTube only) and tracked item images (`https` only)- Text length in scheduled posts (the platform API enforces limits)-- Future scheduled times (a post scheduled in the past is harmlessly treated as due)++Error responses never carry a stack trace or a database driver message: `DatabaseError` sends a plain message and logs the driver's, and `UpstreamError` removes URLs, which can carry an API key or token, from the platform's message.## What the Frontend Can Trustdiff --git a/docs/workflows/DEPLOYMENT.md b/docs/workflows/DEPLOYMENT.mdindex bc8912f..0730f0b 100644--- a/docs/workflows/DEPLOYMENT.md+++ b/docs/workflows/DEPLOYMENT.md@@ -69,12 +69,15 @@ npx wrangler secret put CLOUDINARY_CLOUD_NAMEnpx wrangler secret put CLOUDINARY_UPLOAD_PRESETnpx wrangler secret put BACKEND_URLnpx wrangler secret put FRONTEND_URL+npx 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```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.+## Setting GitHub Actions SecretsRequired for `deploy-frontend.yml` and `publish-scheduled.yml`:@@ -105,10 +108,15 @@ Required for `deploy-frontend.yml` and `publish-scheduled.yml`:**Backend:**```bash-curl https://twiligent.ujjwalkrai.workers.dev/api/health-# Expected: {"status":"ok","timestamp":"2025-..."}+curl -i https://twiligent.ujjwalkrai.workers.dev/api/health+# Expected: 200 with {"status":"ok","timestamp":"2025-..."} and an X-Request-Id header++curl -i -H "Origin: https://twiligent.ujjwal.fyi" https://twiligent.ujjwalkrai.workers.dev/api/health+# Expected: Access-Control-Allow-Origin: https://twiligent.ujjwal.fyi (the FRONTEND_URL origin)```+A request with any other `Origin` gets no `Access-Control-Allow-Origin` header. The Worker writes one JSON log line per request with its request id; use `npx wrangler tail` from `backend/` to watch them, and search for the id a user quotes from an error message.+**Frontend:**Open `https://twiligent.ujjwal.fyi` (custom domain on the `twiligent` Pages project; `twiligent.spacesdrive.cc` 301-redirects here) -> verify login page loads -> sign in -> verify accounts load.diff --git a/docs/workflows/FEATURE_DEVELOPMENT.md b/docs/workflows/FEATURE_DEVELOPMENT.mdindex b731c53..c93837a 100644--- a/docs/workflows/FEATURE_DEVELOPMENT.md+++ b/docs/workflows/FEATURE_DEVELOPMENT.md@@ -68,8 +68,8 @@ Determine:**Step 10 - Identify reuse opportunities**Before creating new patterns, check:-- Is there a db.ts function that almost does what you need? Extend it.-- Is there a service function you can call? Use it.+- Is there a repository method that almost does what you need? Extend it.+- Is there a service method or platform function you can call? Use it.- Is there a shadcn component that fits? Use it.- Is there a formatting function in formatters.ts? Use it.@@ -80,20 +80,20 @@ Before creating new patterns, check:**Step 11 - Implement in this order:**1. DB schema changes (if any) - see `docs/features/NEW_DATABASE_TABLE.md`2. Types: request, response and entity shapes in `shared/types/` (types only, no runtime code); see `docs/guidelines/TYPESCRIPT.md`-3. Backend: `lib/db.ts` additions (new query functions)-4. Backend: `services/` additions (new external API calls)-5. Backend: `routes/` additions (new route handlers on `new Hono<AppEnv>()`, responses checked with `satisfies`)-6. Backend: `server.ts` mounting (if new router)+3. Backend: `validators/` parsers for new request bodies and query strings+4. Backend: `repositories/` additions (new query methods; user-scoped ones end in `ForUser`)+5. Backend: `services/` additions (business rules in a feature service, platform calls in `services/<platform>/`), wired in `container.ts`+6. Backend: `controllers/` (built with `controller.createHandlers`, responses checked with `satisfies`) and a line in the feature's `routes/<feature>Routes.ts`; a new route table goes in `routes/index.ts`. See `docs/features/NEW_API_ENDPOINT.md`7. Frontend: `services/api.ts` additions (new API methods returning the shared types)8. Frontend: new page/feature component, with a `<Component>Props` interface for each component that takes props9. Frontend: `App.tsx` routing (if new page)10. Frontend: `layout/navigation.ts` (if new page needs a nav entry)-11. Tests for new pure logic, in the workspace's `tests/` folder at the path that mirrors the source file (`backend/services/youtube.ts` -> `backend/tests/services/youtube.test.ts`, `frontend/src/lib/accounts.ts` -> `frontend/tests/lib/accounts.test.ts`); see `docs/workflows/TESTING.md`+11. Tests for new pure logic, in the workspace's `tests/` folder at the path that mirrors the source file (`backend/routes/accountRoutes.ts` -> `backend/tests/routes/accountRoutes.test.ts`, `backend/services/youtube/youtubeChannels.ts` -> `backend/tests/services/youtube/youtubeChannels.test.ts`, `frontend/src/lib/accounts.ts` -> `frontend/tests/lib/accounts.test.ts`); see `docs/workflows/TESTING.md`If the feature needs a new npm package (approval required, see CLAUDE.md), add it to the app that uses it from the repository root: `npm install <pkg> --workspace backend` or `--workspace frontend`. Never run `npm install` inside `backend/` or `frontend/`; the root `package-lock.json` is the only lockfile.**Step 12 - Eliminate duplication**-After implementing, look for logic that duplicates something that already existed. Extract it into the appropriate shared location (`lib/db.ts`, `services/`, `utils/formatters.ts`, shared components).+After implementing, look for logic that duplicates something that already existed. Extract it into the appropriate shared location (`repositories/`, `services/`, `lib/analyticsMath.ts`, `utils/formatters.ts`, shared components).---diff --git a/docs/workflows/GIT.md b/docs/workflows/GIT.mdindex fc90783..67990da 100644--- a/docs/workflows/GIT.md+++ b/docs/workflows/GIT.md@@ -100,7 +100,7 @@ release: v1.1.0 - Reddit integration## What to Commit Together### Always group these in a single commit:-- A new route + its db.ts functions + its api.ts method+- A new route + its controller, service and repository methods + its api.ts method- A new page + its route in App.tsx + its Sidebar entry- A bug fix + updated docs if the fix changes documented behavior- A new feature + CHANGELOG.md update + relevant architecture doc updatesdiff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.mdindex 304617b..e294ea7 100644--- a/docs/workflows/TESTING.md+++ b/docs/workflows/TESTING.md@@ -21,24 +21,31 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that| Source file | Test file ||---|---|-| `backend/services/youtube.ts` | `backend/tests/services/youtube.test.ts` |-| `backend/routes/accounts.ts` | `backend/tests/routes/accounts.test.ts` |+| `backend/services/youtube/youtubeChannels.ts` | `backend/tests/services/youtube/youtubeChannels.test.ts` |+| `backend/routes/accountRoutes.ts` | `backend/tests/routes/accountRoutes.test.ts` || `backend/routes/publishingRoutes.ts` | `backend/tests/routes/publishingRoutes.test.ts` |-| `backend/routes/settings.ts` | `backend/tests/routes/settings.test.ts` |-| `backend/utils/scheduler.ts` | `backend/tests/utils/scheduler.test.ts` |+| `backend/routes/settingsRoutes.ts` | `backend/tests/routes/settingsRoutes.test.ts` |+| `backend/services/scheduledPublisher.ts` | `backend/tests/services/scheduledPublisher.test.ts` |+| `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/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` || `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` |-Backend tests are in `backend/tests/lib`, `backend/tests/middleware`, `backend/tests/routes`, `backend/tests/services` and `backend/tests/utils`. Shared test helpers (`fakeSupabase.ts`, `fakeFetch.ts`, `golden.ts`, `routeHarness.ts`, the per-platform `*Fixtures.ts` data) and the `*.golden.json` snapshots are in `backend/tests/fixtures/`. Wrangler only bundles files reachable from `server.ts`, so nothing in `backend/tests/` ships in the Worker.+Backend tests are in `backend/tests/lib`, `backend/tests/middleware`, `backend/tests/repositories`, `backend/tests/routes`, `backend/tests/services` (with `youtube/`, `instagram/` and `reddit/` for the platform modules) and `backend/tests/validators`. A route test is named after its route table (`accountRoutes.test.ts`) and exercises the whole stack below it: controller, service and repository. Shared test helpers (`fakeSupabase.ts`, `fakeFetch.ts`, `golden.ts`, `routeHarness.ts`, the per-platform `*Fixtures.ts` data) and the `*.golden.json` snapshots are in `backend/tests/fixtures/`. Wrangler only bundles files reachable from `server.ts`, so nothing in `backend/tests/` ships in the Worker.Frontend tests cover shared helpers in `src/lib/` and `src/utils/` (hold-to-confirm timing, command palette ranking, library filtering and paging, platform helpers, and a check that every Lucide icon imported in `src` exists) and page helpers in `src/features/**` and `src/docs/**`, such as `features/analytics/overview/overviewStats.ts`. A testable helper is a plain `.ts` file with no JSX and no `@/` or `@shared/` imports, and its imports of project files (including `shared/types`) are relative paths that end in `.ts`, so Node can load it directly. It uses only erasable TypeScript (no `enum`, no parameter properties) and `import type` for types. This rule lives here, so helper files do not repeat it in a header comment.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.+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`).-Backend route and scheduler tests (`tests/routes/*.test.ts`, `tests/utils/scheduler.test.ts`) run the real handlers against `tests/fixtures/fakeSupabase.ts` and a scripted `fetch`, then compare responses, queries and outgoing requests with the `tests/fixtures/*.golden.json` snapshots. 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.+Backend 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 testing workflow documented here describes what should run before shipping any change.@@ -86,11 +93,14 @@ Prettier and EditorConfig are configured at the root (`.prettierrc.json`, `.pretFor any backend change, verify the affected routes directly:```bash-# Health check (should always work)-curl https://twiligent.ujjwalkrai.workers.dev/api/health+# Health check (should always work); the response carries an X-Request-Id header+curl -i https://twiligent.ujjwalkrai.workers.dev/api/health# Authenticated route (replace TOKEN with a real Supabase JWT)curl -H "Authorization: Bearer TOKEN" https://twiligent.ujjwalkrai.workers.dev/api/accounts++# Without a token: 401 with { "success": false, "code": "UNAUTHORIZED", "message": ..., "requestId": ... }+curl -i https://twiligent.ujjwalkrai.workers.dev/api/accounts```For local testing:@@ -108,9 +118,17 @@ Open the app in a browser. For each changed area, test:- [ ] Login with invalid credentials -> error message shown- [ ] Sign out -> redirects to login+**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 origin+- [ ] `curl -i -H "Origin: https://unlisted.example.com" .../api/health` returns no `Access-Control-Allow-Origin` header, and the browser blocks a call from that origin+- [ ] 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>)`+**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`-- [ ] More requests than the rule allows return `429` with `Retry-After` and a message that says when to retry+- [ ] More requests than the rule allows return `429` with `Retry-After` and `{ success: false, code: "RATE_LIMITED", message, requestId, retryAfter }`, with a message that says when to retry- [ ] The Overview, bulk publishing and tracked content refresh still work without a `429`**Accounts:**@@ -142,8 +160,9 @@ Open the app in a browser. For each changed area, test:- [ ] What happens with no accounts? (empty state)- [ ] What happens when the backend is unreachable? (error toast)-- [ ] What happens when an Instagram token is expired? (descriptive error)-- [ ] What happens when YouTube API quota is exceeded? (error propagated)+- [ ] What happens when an Instagram token is expired? (descriptive error, `502`)+- [ ] What happens when YouTube API quota is exceeded? (YouTube's message propagated, `502`)+- [ ] What happens when a Worker secret is missing? (`503` with a message naming what is not configured)### 6. Console Error Verification@@ -183,11 +202,11 @@ After any change to `scripts/publish-scheduled.ts` or `publish-scheduled.yml`:2. Watch the run output3. Verify: "No posts due for publishing" (if no scheduled posts) or successful publish-If you have a test post scheduled in the near future, use `GET /api/process-scheduled` to trigger the Worker cron manually.+If you have a test post scheduled in the near future, use `GET /api/process-scheduled` to run the Worker's publisher (`scheduledPublisher.publishDue()`) manually.## Future Test Infrastructure-Already in place: golden tests for `computeVideoAnalytics()`, `computeInstagramAnalytics()` and `computeRedditAnalytics()`, and route tests that run the Hono handlers against a fake Supabase client (`backend/tests/fixtures/`). Still to add, in priority order:+Already in place: golden tests for `computeVideoAnalytics()`, `computeInstagramAnalytics()` and `computeRedditAnalytics()`, route tests that run each route table, controller, service and repository against a fake Supabase client (`backend/tests/fixtures/`), and repository tests against the same fake. Still to add, in priority order:-1. **Tests for `lib/db.ts` against a real database** - using a Supabase test project+1. **Tests for the repositories against a real database** - using a Supabase test project2. **End-to-end tests** - Playwright for the full login -> view analytics -> publish flowdiff --git a/frontend/src/docs/pages/reference/Environment.tsx b/frontend/src/docs/pages/reference/Environment.tsxindex b89141e..e69d104 100644--- a/frontend/src/docs/pages/reference/Environment.tsx+++ b/frontend/src/docs/pages/reference/Environment.tsx@@ -13,7 +13,8 @@ const BACKEND_VARS: [string, Need, boolean, string, string][] = [['CLOUDINARY_CLOUD_NAME', 'publishing', false, 'Cloudinary dashboard', 'Where uploaded media goes.'],['CLOUDINARY_UPLOAD_PRESET', 'publishing', false, 'Cloudinary, Settings, Upload, Upload presets (unsigned)', 'Lets browsers upload without the Cloudinary API secret.'],['BACKEND_URL', 'instagram', false, 'Your Worker address, no trailing slash', 'Builds the Instagram redirect URI.'],- ['FRONTEND_URL', 'instagram', false, 'Your Pages address', 'Where members land after Instagram sign-in.'],+ ['FRONTEND_URL', 'required', false, 'Your Pages address', 'The only site the backend accepts requests from, and where members land after Instagram sign-in.'],+ ['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.'],];@@ -45,6 +46,7 @@ export default function Environment() {<H2>Backend (Cloudflare Worker)</H2><P>Set each one with <Code>npx wrangler secret put NAME</Code> in <Code>backend/</Code>. For local development, put them in <Code>backend/.dev.vars</Code>, which Git ignores. See <A to="/docs/self-host/deploy-backend">Deploy the backend</A>.</P>+ <P>The backend only answers browsers on <Code>FRONTEND_URL</Code> and the addresses in <Code>ALLOWED_ORIGINS</Code>. If the site loads but every page fails to load data, check that <Code>FRONTEND_URL</Code> matches the address in the browser exactly, including <Code>https://</Code>. A backend running on your own computer also accepts the local website on port 5173.</P><Tablehead={['Name', 'Needed', 'Where to get it', 'Used for']}rows={BACKEND_VARS.map(([name, need, secret, from, use]) => [diff --git a/frontend/src/docs/pages/selfHost/DeployBackend.tsx b/frontend/src/docs/pages/selfHost/DeployBackend.tsxindex 78c846d..ce0fbcc 100644--- a/frontend/src/docs/pages/selfHost/DeployBackend.tsx+++ b/frontend/src/docs/pages/selfHost/DeployBackend.tsx@@ -34,10 +34,10 @@ 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.</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.</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.</P>+ <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></Step></Steps>diff --git a/frontend/src/docs/pages/selfHost/DeployFrontend.tsx b/frontend/src/docs/pages/selfHost/DeployFrontend.tsxindex b7b622f..b971438 100644--- a/frontend/src/docs/pages/selfHost/DeployFrontend.tsx+++ b/frontend/src/docs/pages/selfHost/DeployFrontend.tsx@@ -28,14 +28,14 @@ npx wrangler pages deploy dist --project-name=twiligent<P><Code>npm run build</Code> runs Vite with <Code>frontend/vite.config.ts</Code> and writes the site to <Code>frontend/dist</Code>. The first time, Wrangler creates the Pages project and prints the address, for example <Code>https://twiligent.pages.dev</Code>.</P></Step><Step title="Point the backend at it">- <P>Set <Code>FRONTEND_URL</Code> on the Worker to that address, so Instagram sign-in returns members to the right place:</P>+ <P>Set <Code>FRONTEND_URL</Code> on the Worker to that address. The backend only answers requests from it, and Instagram sign-in returns members there:</P><CodeBlock>{`cd ../backendnpx wrangler secret put FRONTEND_URL`}</CodeBlock></Step></Steps>- <P>Open the site, create your account and connect something. For a custom domain, add it under the Pages project's <strong>Custom domains</strong> tab and update <Code>FRONTEND_URL</Code> to match.</P>+ <P>Open the site, create your account and connect something. For a custom domain, add it under the Pages project's <strong>Custom domains</strong> tab and update <Code>FRONTEND_URL</Code> to match. To keep the <Code>pages.dev</Code> address working too, add it to <Code>ALLOWED_ORIGINS</Code> on the Worker.</P></>);}diff --git a/frontend/src/docs/pages/use/Troubleshooting.tsx b/frontend/src/docs/pages/use/Troubleshooting.tsxindex 388b58e..a0637be 100644--- a/frontend/src/docs/pages/use/Troubleshooting.tsx+++ b/frontend/src/docs/pages/use/Troubleshooting.tsx@@ -20,7 +20,7 @@ export default function Troubleshooting() {]}/><H2>Contact the administrator</H2>- <P>For anything only the person running this instance can fix, email <AdminLink subject="Help with Twiligent" />. Include what you were doing, the account involved and the exact message you saw.</P>+ <P>For anything only the person running this instance can fix, email <AdminLink subject="Help with Twiligent" />. Include what you were doing, the account involved and the exact message you saw. If the message ends with a request id, include it; it lets the administrator find what happened.</P></>);}