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(database): document migrations, enforced access and ownership
spacesdriveba3614272d82
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5fb1c2e..695fa04 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,27 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).## [Unreleased]+### Added++- The database layout is kept as versioned migrations in `supabase/migrations/`, applied with the Supabase CLI, with the reverse of each change in `supabase/rollbacks/`; existing instances run `npm run db:push` before deploying this version, and the setup SQL in the README and docs is replaced by the same command (#74, ADR-038)+- `npm run db:new`, `db:status`, `db:check` and `db:push` create, list, preview and apply migrations (#74)++### Changed++- The database now refuses values the app never writes: an unknown platform, post status or tracked item type, a YouTube tracked item with an account, or a post marked Publishing without a claim time (#77)+- Every table has an `updated_at` time that the database keeps current (#77)+- Removing an account also removes its scheduled posts, published ones included; tracked items stay and lose only the account (#76)+- Account, scheduled post and tracked item lists are served by indexes that match their order, and the schedulers read only pending and publishing posts (#78)+- New accounts, scheduled posts and tracked items get random ids that cannot be worked out from another one (#80)++### Fixed++- Security: a signed-in member could read their stored Instagram tokens and Reddit cookies and write rows directly through Supabase's public API; the tables and database functions are now closed to the browser (#75)+- Security: a scheduled post could name another member's Instagram account, and the scheduler would publish to it; the account must now be one of your own Instagram accounts (#76)+- Changing a tracked item's account now only accepts one of your own Reddit accounts, and refuses an account on a YouTube item (#76)+- A token refresh and an analytics refresh on the same account at the same moment no longer put the old access token back, and a manual view count no longer disappears when a refresh lands at the same time (#79)+- Accounts are listed in the order they were added, the same on every load (#78)+---## [1.1.1] - 2026-10-15diff --git a/DECISIONS.md b/DECISIONS.mdindex f2b3dbc..b2b0d76 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -793,3 +793,37 @@ Records every significant architectural decision, the alternatives considered, a- Retries add up to two more scheduler runs, about half an hour, before a temporary failure is reported.- The GitHub fallback's timing stays best effort. Moving it off the top of the hour follows GitHub's advice, but GitHub still decides when the runs start; the docs and the app now say the Worker publishes within 15 minutes and the fallback catches missed posts later.- A file in `backend/lib/` is now part of the script's runtime, so it must stay import-free; `docs/guidelines/TYPESCRIPT.md` records the rule.++---++## ADR-038: Versioned migrations with the Supabase CLI, and a database that guards its own rules++**Date:** 2026-10-16+**Status:** Accepted++**Decision:** The schema is versioned as SQL migrations in `supabase/migrations/` and applied with the Supabase CLI (`supabase`, a root dev dependency) through `npm run db:new`, `db:status`, `db:check` (`supabase db push --dry-run`) and `db:push`. The CLI connects through its short-lived login role, so no database password is stored. Each file changes one table or one function, at the owner's request, so a change can be read, applied and undone on its own. The first four files are baselines: each recreates one table as it stood before migrations, with `if not exists` throughout, and brings older setups to the same shape (adds `created_at` and the claim columns, replaces null `data` and `value` with `{}`, fails posts stuck in `publishing` with no claim). The CLI has no down migrations, so `supabase/rollbacks/` holds the reverse of every non-baseline migration under the same file name; a rollback is run in the SQL editor and recorded with `supabase migration repair --status reverted <version>`. On top of the baseline the migrations:++- Drop the three `users_own_*` policies and revoke all on the four tables from `anon` and `authenticated`, and revoke the default privileges for tables and functions that `postgres` creates in `public`. Row level security stays on with no policies.+- Add CHECK constraints for the allowed values (`platform`, `status`, `content_type`), for `attempts >= 0`, for a `publishing` post having a `claimed_at`, for only Reddit items having an account, and for `data` and `value` being JSON objects.+- Add `unique (id, user_id)` on `accounts` and composite foreign keys from `scheduled_posts (account_id, user_id)` (on delete cascade) and `tracked_posts (account_id, user_id)` (on delete set null of `account_id` only, Postgres 15 syntax), so a row can only name an account of the same user. The services check the same rule first, so the API answers 404 instead of a database error.+- Add `updated_at` to every table, kept by one `set_updated_at()` trigger function.+- Add `merge_account_data`, `merge_scheduled_post` and `merge_tracked_post_data`: SQL functions that run `data = data || p_patch` (and the status and time for posts) in one UPDATE, with `search_path = ''`, returning `true` or null, executable only by `service_role`. A null `p_user_id` is the cron form. The repositories and `scripts/publish-scheduled.ts` call them instead of reading `data` and writing it back.+- Index by workload: `accounts (user_id, created_at, id)`, `scheduled_posts (user_id, scheduled_at)` and `tracked_posts (user_id, created_at desc)` serve each list query with no sort, and two partial indexes serve the schedulers (`scheduled_at` where `pending`, `claimed_at` where `publishing`). `accounts.platform` and the two `account_id` columns are left unindexed, because only the daily token refresh and account removal read them.++New row ids come from `crypto.randomUUID()` (`newRowId()` in `backend/lib/ids.ts`). `accounts.listForUser` orders by `created_at, id`, and the token refresh lists Instagram accounts with `listByPlatform('instagram')` instead of loading every account.++**Context:** The schema lived only as SQL pasted into the README and the docs page, with no record of what ran where, and production had drifted from it (#73, #74). `scheduled_posts.account_id` had no foreign key, although `SCHEMA.md` listed one. Three tables had policies `for all using (auth.uid() = user_id)` and every table had full grants to `anon` and `authenticated`, so a signed-in member could read their raw Instagram tokens and Reddit cookies through the Data API and write rows directly, such as a scheduled post naming another user's account; the API itself never checked a scheduled post's account either (#75, #76). Account, post and tracked item updates read the `data` column and wrote it back, so a token refresh and an analytics refresh on one account could put the old token back (#79). The account list had no stable order and no matching index, and the scheduler indexes covered the whole growing history (#78). Ids were built from the time and `Math.random`, which is predictable (#80). Before the push, every migration ran on a local Postgres (PGlite, Postgres 18) from three starting points (a fresh database, production's shape and the old README shape), and all three ended with the same schema; every rollback ran in reverse and the migrations ran again to the same schema; `EXPLAIN` showed each list query on its index with no sort. All 28 then ran on production inside a transaction that was rolled back, before the real `db push`. Afterwards the anon key got 401 for all four tables and the merge functions, and the data was intact.++**Alternatives considered:**+- dbmate. A small, database-agnostic migration tool with down migrations, but one more tool beside Supabase, and it needs the database connection string and password. The owner chose the Supabase CLI.+- Plain numbered SQL files run by hand in the SQL editor. No dependency, but nothing records what ran on which instance, which is how production drifted.+- Postgres enum types for `platform`, `status` and `content_type`. They document the values just as well, but a value cannot be removed and adding one needs care, while a CHECK constraint is replaced in one migration.+- RLS policies for ownership, letting the browser reach its own rows. The browser has no reason to read the tables, and a policy would expose stored tokens and cookies and let it write rows the API refuses.+- Row locking with `select ... for update` around a read and a write. It also prevents lost updates, but needs a transaction across two round trips, which supabase-js over PostgREST does not offer; one merge statement needs neither.++**Trade-offs:**+- The `supabase` CLI is a root dev dependency (about 200 lines of lockfile); `npm ci` installs it in every workflow, though no workflow calls it.+- Removing an account now removes its scheduled posts, published records included, because the foreign key cascades. Tracked items keep the item and lose only the account.+- A field passed as `undefined` in an update is dropped from the JSON, so it keeps its stored value instead of being removed. Clearing a field takes an explicit `null`.+- Rolling back is manual: run the rollback file, then repair the migration history. The baselines cannot be rolled back.+- The PGlite harness that ran the migrations lived in a scratchpad and is not in the repository. Running the SQL in CI would need the `@electric-sql/pglite` dev dependency, which was not approved; `migrations.test.ts` checks names, order, rollback pairs, repeatable baselines and closed functions without running the SQL. Adding the harness is a possible follow-up.diff --git a/README.md b/README.mdindex fa3090e..78e0d40 100644--- a/README.md+++ b/README.md@@ -187,62 +187,22 @@ The repository is an npm workspaces monorepo: `backend/`, `frontend/` and `site/**3. Create the Supabase database tables**-In your Supabase project, open the SQL editor and run the following:--```sql--- Accounts table-create table accounts (- id text primary key,- user_id uuid not null references auth.users(id) on delete cascade,- platform text not null,- data jsonb not null-);---- Settings table-create table settings (- user_id uuid not null references auth.users(id) on delete cascade,- key text not null,- value jsonb,- primary key (user_id, key)-);---- Scheduled posts table-create table scheduled_posts (- id text primary key,- user_id uuid not null references auth.users(id) on delete cascade,- account_id text not null references accounts(id) on delete cascade,- status text not null default 'pending',- scheduled_at timestamptz not null,- claimed_at timestamptz,- attempts integer not null default 0,- data jsonb-);-create index scheduled_posts_user_id_idx on scheduled_posts (user_id);-create index scheduled_posts_due_idx on scheduled_posts (status, scheduled_at);---- Tracked content table-create table tracked_posts (- id text primary key,- user_id uuid not null references auth.users(id) on delete cascade,- account_id text references accounts(id) on delete set null,- url text not null,- label text not null default '',- category text not null default '',- content_type text not null default 'reddit',- created_at timestamptz not null default now(),- updated_at timestamptz not null default now(),- data jsonb-);---- Row level security: the backend uses the secret key, which bypasses it.--- With no policies, the public publishable key cannot read or change any table.-alter table accounts enable row level security;-alter table settings enable row level security;-alter table scheduled_posts enable row level security;-alter table tracked_posts enable row level security;+The schema is versioned in `supabase/migrations/` and applied with the Supabase CLI, which `npm install` installed. Link the CLI to your project once, then apply every migration:++```bash+npx supabase login # or set SUPABASE_ACCESS_TOKEN+npx supabase link --project-ref <project-ref> # the id in your project's dashboard URL+npm run db:check # lists the migrations it will apply+npm run db:push # applies them```-If you created the tables from an earlier version of this README, run the `tracked_posts` and `alter table` statements above as well. If your `scheduled_posts` table has no `claimed_at` column, run the upgrade SQL in [the Supabase setup docs](https://twiligent.ujjwal.fyi/docs/self-host/supabase) before deploying this version: the schedulers need the `claimed_at` and `attempts` columns. Then, in Supabase Authentication, turn off **Confirm email** unless you have set up email verification codes ([docs](https://twiligent.ujjwal.fyi/docs/self-host/email-codes)), and turn off new signups once your team has accounts if the instance is private. The sign-in page's email field sends a sign-in code; without the email codes setup, Supabase sends its own rate-limited Magic Link email, which holds a link (add `{{ .Token }}` to its template in Authentication, Emails to show the code too).+This creates the four tables Twiligent uses and closes them to the browser: row level security is on with no policies, and the roles behind the public publishable key have no grants. It also adds the value checks, the keys that tie posts to their owner's accounts, the `updated_at` triggers, the functions that merge row data in one statement, and the indexes. `npm run db:status` lists which migrations are applied.++An instance created from an earlier version of this README, including one that ran the `claimed_at` and `attempts` upgrade SQL, runs the same commands before deploying this version. The first four migrations are baselines that are safe on existing tables and bring every earlier setup to the same schema. If a value check stops the push because of an old row, the error names the constraint; fix the row and run `npm run db:push` again.++If you cannot use the CLI, open the SQL editor and run each file from `supabase/migrations/` in file name order, then apply later files the same way, since the CLI will not know they ran.++Then, in Supabase Authentication, turn off **Confirm email** unless you have set up email verification codes ([docs](https://twiligent.ujjwal.fyi/docs/self-host/email-codes)), and turn off new signups once your team has accounts if the instance is private. The sign-in page's email field sends a sign-in code; without the email codes setup, Supabase sends its own rate-limited Magic Link email, which holds a link (add `{{ .Token }}` to its template in Authentication, Emails to show the code too).**4. Configure credentials**@@ -273,6 +233,10 @@ Run every command from the repository root.| `npm test` | Runs the backend, frontend and site tests (Node's built-in test runner on `tests/**/*.test.ts`) || `npm run lint` | Runs ESLint over the whole repository with the shared `eslint.config.mjs` || `npm run format` | Applies Prettier (`.prettierrc.json`) to the whole repository |+| `npm run db:new <name>` | Creates a migration file in `supabase/migrations/` (`supabase migration new`) |+| `npm run db:status` | Lists the migrations and whether each is applied to the linked project (`supabase migration list`) |+| `npm run db:check` | Shows what `db:push` would apply, without applying it (`supabase db push --dry-run`) |+| `npm run db:push` | Applies pending migrations to the linked project (`supabase db push`) |Add a dependency to the workspace that uses it: `npm install <package> --workspace backend`, `--workspace frontend` or `--workspace site`. Only shared development tooling goes in the root `package.json`.@@ -280,6 +244,8 @@ The whole project is TypeScript in `strict` mode. Nothing is compiled ahead of tTests live outside the source folders, in `backend/tests/`, `frontend/tests/` and `site/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/`.+Database changes are migrations: `npm run db:new <name>` creates the file, its reverse goes in `supabase/rollbacks/` with the same name, and `npm run db:push` applies it before the code that needs it is merged. See `docs/features/NEW_DATABASE_TABLE.md` and `docs/workflows/DEPLOYMENT.md`.+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.---@@ -474,6 +440,7 @@ twiligent/│ │ └── scheduled.ts # Cron entry point: publish due posts, refresh Instagram tokens│ ├── lib/│ │ ├── errors.ts # Typed errors; the error handler maps each code to a status+│ │ ├── ids.ts # newRowId(): random UUIDs for new rows│ │ ├── 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@@ -485,7 +452,7 @@ twiligent/│ │ ├── env.ts # Env: Worker secrets and bindings│ │ ├── 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+│ ├── tests/ # Node tests (*.test.ts) mirroring lib/, middleware/, repositories/, routes/, services/, validators/; database/ checks the migration files; 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-types@@ -531,6 +498,11 @@ twiligent/├── shared/│ └── types/ # API contract shared by backend and frontend (types only)│+├── supabase/+│ ├── migrations/ # Versioned schema changes, one table or function per file, applied with npm run db:push+│ ├── rollbacks/ # The reverse of each migration, same file name, run by hand+│ └── config.toml # Supabase CLI config (Postgres 17)+│├── scripts/│ ├── publish-scheduled.ts # TypeScript run directly by Node in the GitHub Actions fallback (no dependencies)│ └── tsconfig.json # Type check for scripts/ (Node types)@@ -554,6 +526,7 @@ twiligent/| TypeScript | 6.0 | Strict type checking across the backend, frontend, public site, shared types, scripts and tests || typescript-eslint | 8 | TypeScript lint rules || Node.js | 22.18 or later | Runs the tests and the scheduled publisher by stripping types |+| Supabase CLI (`supabase`) | 2 | Applies the database migrations (root dev dependency) |**Frontend**diff --git a/claude.md b/claude.mdindex fadd1df..e241bed 100644--- a/claude.md+++ b/claude.md@@ -46,10 +46,14 @@ frontend/ React SPA (the app); tests in frontend/tests/ mirroring frsite/ public marketing site and docs (Vite, React, MDX); docs pages in site/content/docs/,build plugins in site/build/, tests in site/tests/scripts/ publish-scheduled.ts, run by GitHub Actions with no dependencies+supabase/ the database schema: migrations/ (versioned SQL, one table or function per file, applied+ with the Supabase CLI), rollbacks/ (the reverse of each migration, same file name),+ config.toml (CLI config, Postgres 17)```- `npm install` at the root installs every workspace. Never run `npm install` inside `backend/`, `frontend/` or `site/`, and never commit a lockfile there.- `npm run dev` starts the Worker (port 8787) and Vite (port 5173) together; `npm run dev:site` starts the public site on its own. `npm run typecheck`, `npm test`, `npm run lint` and `npm run build` cover the whole repo, the site included (`build` builds the app, then the site).+- `npm run db:new <name>` creates a migration, `npm run db:status` lists which are applied, `npm run db:check` shows what a push would apply and `npm run db:push` applies it (the Supabase CLI is a root dev dependency; link it once with `npx supabase link --project-ref <ref>`). CI never runs migrations.- Add a dependency to the workspace that uses it: `npm install <pkg> --workspace backend`, `--workspace frontend` or `--workspace site`. Only shared dev tooling belongs in the root `package.json`.- 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`; site tests live in `site/tests/`.@@ -103,7 +107,7 @@ docs/SITE.md Public site and docs: stack, folders, docs pipeline, theming, icons, deploydatabase/SCHEMA.md All tables, columns, types, constraints- SECURITY.md RLS policy, service vs anon key, isolation+ SECURITY.md Browser access (RLS, grants), service vs anon key, isolationcloudflare/WORKERS.md Worker export, env binding, cron handlerPAGES.md App and site deployment, build step, env vars@@ -203,6 +207,8 @@ Read `docs/guidelines/CODE_STYLE.md` before writing code and run its checklist b- Formatting follows the file: 4 spaces in `backend/`, 2 elsewhere, single quotes, semicolons, trailing commas- Pure logic goes in a plain `.ts` helper (`lib/`) so Node can test it; markup used twice becomes a component; copy that changes by mode lives in a typed table- `scripts/` stays free of npm packages but may import a `backend/lib/` helper that imports nothing at runtime, so both schedulers share one set of rules (`scheduledPublishing.ts`)+- The schema changes only through a migration in `supabase/migrations/` plus its rollback in `supabase/rollbacks/`, one table or one function per file; repositories update `data` through the merge functions, never by reading it and writing it back+- New row ids come from `newRowId()` in `backend/lib/ids.ts` (`crypto.randomUUID()`)- Tests use `node:test` with sentence names that describe behaviour, live in `tests/` mirroring the source path, and use the smallest typed fake- When the code and `CODE_STYLE.md` disagree, update the guide in the same change@@ -356,8 +362,9 @@ When anything changes, update every relevant docs file from the table below. The| Request pipeline, middleware order, request context or error contract changed | `docs/architecture/backend/REQUEST_PIPELINE.md`, `docs/architecture/backend/MIDDLEWARE.md`, `docs/guidelines/ERROR_HANDLING.md`, `docs/guidelines/API_CONVENTIONS.md`, `shared/types/domain.ts` (`ApiFailure`) || New repository or repository method | `docs/architecture/backend/REQUEST_PIPELINE.md` (if a new repository), `docs/architecture/database/SECURITY.md` (if it is not user-scoped) || Route deleted or changed | `docs/architecture/backend/ROUTES.md`, `docs/architecture/OVERVIEW.md` |-| New DB table | `docs/architecture/database/SCHEMA.md`, `docs/architecture/database/SECURITY.md`, `DECISIONS.md`, `CHANGELOG.md` |-| New DB column | `docs/architecture/database/SCHEMA.md` |+| New DB table | A migration and its rollback in `supabase/` (`docs/features/NEW_DATABASE_TABLE.md`), `docs/architecture/database/SCHEMA.md`, `docs/architecture/database/SECURITY.md`, `DECISIONS.md`, `CHANGELOG.md` |+| New DB column | A migration and its rollback in `supabase/`, `docs/architecture/database/SCHEMA.md` |+| Schema, constraint, index, trigger or function changed | A migration and its rollback in `supabase/`, `docs/architecture/database/SCHEMA.md`, `docs/architecture/database/SECURITY.md` (if access changes) || New env var / Worker secret | `docs/architecture/cloudflare/WORKERS.md`, `docs/architecture/cloudflare/CI_CD.md`, `docs/workflows/DEPLOYMENT.md`, `DECISIONS.md` || Env var removed | `docs/architecture/cloudflare/WORKERS.md`, `docs/architecture/cloudflare/CI_CD.md`, `docs/workflows/DEPLOYMENT.md` || New npm package (backend) | `docs/architecture/backend/HONO.md`, `DECISIONS.md` |diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.mdindex 9f5eb6b..2ff7fae 100644--- a/docs/architecture/OVERVIEW.md+++ b/docs/architecture/OVERVIEW.md@@ -62,7 +62,7 @@| Backend API | Cloudflare Workers | `twiligent.ujjwalkrai.workers.dev` || Public site and docs | Cloudflare Pages, project `twiligent-site` | `twiligent.ujjwal.fyi` (`twiligent.spacesdrive.cc` redirects here with a 301 rule on the spacesdrive.cc zone) || Frontend SPA (the app) | Cloudflare Pages, project `twiligent` | `app.twiligent.ujjwal.fyi` (also `twiligent.pages.dev`) |-| Database + Auth | Supabase | `nheuatbcevaxgxyvahtr.supabase.co` |+| Database + Auth | Supabase; the schema is applied from `supabase/migrations/` with `npm run db:push` | `nheuatbcevaxgxyvahtr.supabase.co` || Media cache | Upstash Redis | Configured via `UPSTASH_REDIS_REST_URL` || Media hosting | Cloudinary | `CLOUDINARY_CLOUD_NAME` || Auth emails | Resend, through Supabase's Send Email hook | `RESEND_API_KEY`, `EMAIL_FROM` |@@ -116,7 +116,7 @@ Cloudflare scheduler fires cron triggeror back to 'pending' for a temporary failure (up to 3 attempts), or 'failed'-> if cron === '0 0 * * *':tokenRefresh.refreshExpiringInstagramTokens()- -> accounts.listAll() [all users, Instagram accounts with a token]+ -> accounts.listByPlatform('instagram') [all users, filtered in SQL]-> for each expiring token: refreshLongLivedToken()-> accounts.updateById(id, { accessToken, tokenExpiresAt })```diff --git a/docs/architecture/backend/CRON.md b/docs/architecture/backend/CRON.mdindex 04e1a44..e3eb558 100644--- a/docs/architecture/backend/CRON.md+++ b/docs/architecture/backend/CRON.md@@ -62,10 +62,10 @@ The lease, attempt limit and failure rules live in `backend/lib/scheduledPublish**Function:** `tokenRefresh.refreshExpiringInstagramTokens()` in `backend/services/tokenRefreshService.ts`**What it does:**-1. Lists every account with `accountRepository.listAll()` and keeps the Instagram accounts with a token and an expiry+1. Lists the Instagram accounts of every user with `accountRepository.listByPlatform('instagram')`, filtered in SQL, and keeps those with a token and an expiry2. For each account, checks if the Instagram long-lived token expires within 15 days3. 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()`+4. Updates the account's `accessToken` and `tokenExpiresAt` with `accountRepository.updateById()`, which merges them into `data` in one statement (`merge_account_data`), so an analytics refresh at the same moment cannot put the old token backOne failed account is logged and skipped; it never stops the others. `backend/tests/services/tokenRefreshService.test.ts` covers the selection and the updates.diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.mdindex a67da78..069e638 100644--- a/docs/architecture/backend/ROUTES.md+++ b/docs/architecture/backend/ROUTES.md@@ -110,7 +110,7 @@ Controllers call `ScheduledPostService` (`services/scheduledPostService.ts`).| Method | Path | File | Purpose ||---|---|---|---|| 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 |+| POST | `/api/scheduled-posts` | `scheduledPostRoutes.ts`, `scheduledPostController.createScheduledPost` | Create a new scheduled post with `status: 'pending'`; 400 unless `scheduledAt` is a future date; 404 `Instagram account not found` unless `accountId` is one of the user's Instagram accounts; 400 when that account has no token || 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 }` |@@ -140,7 +140,7 @@ Controllers call `TrackedContentService`; link detection and the manual views an|---|---|---|---|| 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 |+| 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. An `accountId` on a YouTube item is 400, and one that is not the user's Reddit account is 404 `Reddit account not found` || 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 |diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.mdindex e90d185..211f404 100644--- a/docs/architecture/backend/SERVICES.md+++ b/docs/architecture/backend/SERVICES.md@@ -34,7 +34,7 @@ A service receives only what it uses: repositories, the cleaned `AppConfig` from| `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` |+| `scheduledPosts` | `scheduledPostService.ts` | accounts, 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` |@@ -43,22 +43,27 @@ A service receives only what it uses: repositories, the cleaned `AppConfig` from| `instagramConnect` | `instagramConnectService.ts` | accounts | `authorizationUrl`, `userIdFromState`, `connect`, plus `configured` and `accountsPageUrl` || `authEmail` | `authEmailService.ts` | email quota (Redis, the fail-fast client) | `send(hook, webhookId)` (Supabase Auth's Send Email hook; no user) |-Every user-scoped method takes the verified `userId` as its first argument. Methods that need one of the user's records load it with a `...ForUser` repository method and throw `NotFoundError` when it is missing or on the wrong platform, so another user's record is never found. `scheduledPublisher` and `tokenRefresh` are the only services that use the cross-user repository methods (`listAll`, `findById`, `updateById`, `listDue`, `listStale`, `claim`).+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 (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `claim`).++New rows get their id from `newRowId()` in `backend/lib/ids.ts`, a UUID from `crypto.randomUUID()`, so an id cannot be worked out from another one. Tests pin the ids with `mockRowIds()` from `backend/tests/fixtures/rowIds.ts`.### Accounts (`accountService.ts`, `accountFactory.ts`)-`accountFactory.ts` holds pure builders: `newAccountId`, `tokenExpiryIso` (null without a lifetime), `buildYouTubeAccount`, `buildRedditAccount`, `buildInstagramAccount`.+`accountFactory.ts` holds pure builders: `tokenExpiryIso` (null without a lifetime), `buildYouTubeAccount`, `buildRedditAccount`, `buildInstagramAccount`. Each builder takes its id from `newRowId()`.`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.+- `remove` deletes the account row and its cache entries. The database removes the account's scheduled posts with it and clears the account from its tracked items (the foreign keys in `docs/architecture/database/SCHEMA.md`).+- Account updates go through `merge_account_data`, one statement in the database, so a token refresh and an analytics refresh on the same account never undo each other. A field passed as `undefined` keeps its stored value.`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`)+`TrackedContentService.add` stores the fetched data in the same insert that creates the item. `update` checks a new `accountId` before storing it: a YouTube item answers 400 `YouTube videos are read without an account; remove the account from this item.`, and an account that is not one of the user's Reddit accounts answers 404 `Reddit account not found`. `refresh` and the manual fields merge into `data` with `merge_tracked_post_data`.+`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`)@@ -95,6 +100,8 @@ A notice that hits a cap is skipped with a warning instead of failing, because t`scheduledPublisher.publishDue()` lists due posts and posts whose claim is older than the 20 minute lease, and claims each one in a single conditional update (`publishing`, `claimed_at = now`, `attempts + 1`), so the GitHub Actions scheduler and the cron never hold the same post and a run that died is taken over. It saves the container id before publishing, and a post with a saved container is checked on Instagram first, so a post that already went out is never published again. It then waits for Reels and Stories to finish processing, publishes, and marks the post `published`. A temporary failure goes back to `pending` for up to 3 attempts, a definite one or the third attempt marks it `failed`, and an outcome it cannot confirm leaves the post `publishing` for a run after the lease. The rules it shares with `scripts/publish-scheduled.ts` live in `backend/lib/scheduledPublishing.ts`. See `docs/architecture/data-flows/SCHEDULING.md`.+`scheduledPostService.create` checks the scheduled time first, then loads the account with `accounts.findForUser(accountId, userId)` and passes it to `publishableAccount()`. Another user's account, a missing one or one that is not Instagram answers 404 `Instagram account not found`; an account with no token answers 400 `No Instagram access token stored - reconnect this account`. The composite foreign key on `scheduled_posts` refuses the same rows in the database.+`scheduledPostService.update` and `remove` re-check the status inside the write: `updatePendingForUser` only changes a `pending` post and `deleteForUser` never deletes a `publishing` one, so a scheduler claiming the post in between cannot be overridden. The errors stay `Can only edit pending posts` and `Cannot delete a post that is currently publishing`.---diff --git a/docs/architecture/cloudflare/CI_CD.md b/docs/architecture/cloudflare/CI_CD.mdindex 5377f44..7bbbce7 100644--- a/docs/architecture/cloudflare/CI_CD.md+++ b/docs/architecture/cloudflare/CI_CD.md@@ -10,6 +10,8 @@| `deploy-site.yml` | Pushes to `main` that touch the site, manual | Type check and test the public site, then build and deploy it to Pages || `publish-scheduled.yml` | Minutes 7, 22, 37 and 52 of every hour (when GitHub starts them), manual | Publish due Instagram posts (fallback for the Worker cron) |+No workflow runs database migrations. The owner applies `supabase/migrations/` with `npm run db:check` and `npm run db:push` before merging code that needs them (`docs/workflows/DEPLOYMENT.md`), and a change under `supabase/` alone deploys nothing. CI checks the migration files through `npm test` (`backend/tests/database/migrations.test.ts`: names, order, rollback pairs, repeatable baselines, closed functions) without a database. The `supabase` CLI is a root dev dependency, so `npm ci` installs it in every workflow, but no workflow calls it.+Nothing compiles TypeScript ahead of time: Wrangler and Vite strip the types while bundling, and Node strips them when it runs tests and `scripts/publish-scheduled.ts`. None of those steps checks types, so each workflow that ships code runs `tsc` first.### `ci.yml`diff --git a/docs/architecture/data-flows/SCHEDULING.md b/docs/architecture/data-flows/SCHEDULING.mdindex fc72c10..a1eb6da 100644--- a/docs/architecture/data-flows/SCHEDULING.md+++ b/docs/architecture/data-flows/SCHEDULING.md@@ -126,18 +126,23 @@ Both schedulers implement the same logic:| Fetch due posts | `posts.listDue()` | `GET /scheduled_posts?status=eq.pending&scheduled_at=lte.now` || Fetch stale posts | `posts.listStale(staleClaimCutoff(now))` | `GET /scheduled_posts?status=eq.publishing&claimed_at=lt.{cutoff}` || Claim | `posts.claim(post)` | `PATCH /scheduled_posts?id=eq.{id}&attempts=eq.{n}&status=eq.pending` (or `status=eq.publishing&claimed_at=eq.{claimedAt}`) |-| Fetch account | `accounts.findById(accountId)`, checked by `publishableAccount()` | `GET /accounts?id=eq.{accountId}` |+| Fetch account | `accounts.findById(accountId)`, checked by `publishableAccount()` | `GET /accounts?id=eq.{accountId}` (the id passed through `encodeURIComponent`) || Publish to IG | `createMediaContainer`, `fetchContainerStatus`, `publishMediaContainer` from `services/instagram/instagramPublishing.ts` | Its own Graph API calls |-| Save the container | `posts.updateById(id, { containerId })` | `PATCH /scheduled_posts?id=eq.{id}` |+| Save the container | `posts.updateById(id, { containerId })` | `POST /rpc/merge_scheduled_post` || Decide after a failure | `containerStep`, `isTransientGraphCode`, `failureOutcome`, `failureMessage` from `lib/scheduledPublishing.ts` | The same functions, imported by relative path |-| Update status | `posts.updateById(id, ...)` | `PATCH /scheduled_posts?id=eq.{id}` |+| Update status | `posts.updateById(id, ...)` | `POST /rpc/merge_scheduled_post` |The Worker's repository methods `listDue`, `listStale`, `claim`, `findById` and `updateById` have no `userId` filter; only the schedulers use them.+Both schedulers save a status and a data patch with the database function `merge_scheduled_post` (`supabase/migrations/`), one UPDATE that merges the patch into `data`. Before, the script read `data` and wrote it back, so a change made between the two was lost. The script calls it with `p_user_id: null`, the cron form; the Worker's `updateById` does the same. `claimed_at` and `attempts` change only in the claim. The ids in the script's PostgREST filters go through `encodeURIComponent`.++The due and stale lists are served by two partial indexes, `scheduled_posts_due_idx` on `scheduled_at` where `status = 'pending'` and `scheduled_posts_claimed_idx` on `claimed_at` where `status = 'publishing'`, so the published history does not slow the schedulers down as it grows.+## Configuration Requirements### Database-- `scheduled_posts` needs the `claimed_at` and `attempts` columns and the two indexes. An instance created before the lease runs the upgrade SQL in `docs/architecture/database/SCHEMA.md` before deploying the code.+- `scheduled_posts` needs the `claimed_at` and `attempts` columns, the `merge_scheduled_post` function and the two partial indexes. All come from the migrations in `supabase/migrations/`: run `npm run db:push` before deploying the code. The baseline migration also marks posts stuck in `publishing` with no claim as `failed`.+- A post can only name one of its owner's Instagram accounts. `POST /api/scheduled-posts` loads the account with `findForUser` and answers 404 `Instagram account not found` for another user's, a missing or a non-Instagram account (400 when it has no token), and the composite foreign key `(account_id, user_id)` refuses such a row in the database. Removing an account removes its scheduled posts.### For Worker Cron (System A)- Worker secrets: `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`, `INSTAGRAM_APP_ID` (not used by scheduler directly - the account's stored `accessToken` is used)diff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.mdindex a8fe67f..7a89dac 100644--- a/docs/architecture/database/SCHEMA.md+++ b/docs/architecture/database/SCHEMA.md@@ -2,26 +2,63 @@## Overview-Supabase (PostgreSQL) with four application tables. All tables include `user_id` (UUID) referencing `auth.users` to scope data per user.+Supabase (PostgreSQL 17) with four application tables. Every table has `user_id` (uuid) referencing `auth.users`, so rows belong to one user, and `created_at` and `updated_at` timestamps.-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.+The backend uses the **service-role key** and 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.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`.+The browser roles (`anon`, `authenticated`) have no access to any table or function: row level security is on with no policies, and their grants are revoked. See `SECURITY.md`.++---++## How the Schema Is Managed++The schema lives in versioned migrations in `supabase/migrations/`, applied with the Supabase CLI (a root dev dependency). Production records each applied file in `supabase_migrations.schema_migrations`. Nothing is pasted into the SQL editor any more. ADR-038 records the decision.++| Path | Holds |+|---|---|+| `supabase/migrations/<version>_<name>.sql` | One change to one table or one function. The 14 digit version orders the files |+| `supabase/rollbacks/<version>_<name>.sql` | The reverse of the migration with the same file name. The CLI has no down migrations, so these are run by hand |+| `supabase/config.toml` | The CLI's default config, with `major_version = 17` to match the hosted database |+| `supabase/.gitignore` | Keeps the CLI's `.temp` and `.branches` folders and local env files out of git |++The first four files are baselines. Each recreates one table as it stood before migrations, with `if not exists` everywhere, so they are safe on a database that already has the tables. They also bring older setups to the same starting point: they add `created_at` and the claim columns where missing, replace null `data` and `value` with `{}`, and mark posts stuck in `publishing` with no claim as `failed`. The baselines have no rollback, because undoing them would drop tables with data.++| Order | Migrations | What they do |+|---|---|---|+| 1 | `baseline_accounts`, `baseline_settings`, `baseline_scheduled_posts`, `baseline_tracked_posts` | The pre-migration tables, repeatable and normalising older shapes |+| 2 | `revoke_browser_access_<table>` (four files) | Drop the old `users_own_*` policies and revoke all from `anon` and `authenticated` |+| 3 | `revoke_browser_default_privileges` | New tables and functions in `public` start without browser grants |+| 4 | `check_<table>_values` (four files) | The CHECK constraints below |+| 5 | `add_accounts_id_user_id_key` | `unique (id, user_id)` on `accounts`, the target of the composite foreign keys |+| 6 | `add_scheduled_posts_account_fkey`, `add_tracked_posts_account_fkey` | The composite foreign keys below |+| 7 | `create_set_updated_at_function`, `add_<table>_updated_at` (three files), `add_tracked_posts_updated_at_trigger` | The `updated_at` column and its trigger on every table |+| 8 | `create_merge_account_data_function`, `create_merge_scheduled_post_function`, `create_merge_tracked_post_data_function` | The merge functions below |+| 9 | `index_accounts_list`, `index_scheduled_posts_list`, `index_scheduled_posts_schedulers`, `index_tracked_posts_list` | The indexes below |++To change the schema, follow `docs/features/NEW_DATABASE_TABLE.md` (Write the Migration). The commands are in `docs/workflows/DEPLOYMENT.md`.---## Table: `accounts`-Stores connected YouTube channels and Instagram accounts.+Stores connected YouTube channels, Instagram accounts and Reddit profiles.| Column | Type | Nullable | Description ||---|---|---|---|-| `id` | text | NOT NULL | PK. Client-generated: `Date.now().toString(36) + Math.random().toString(36).slice(2)` |-| `user_id` | uuid | NOT NULL | FK -> `auth.users.id`. All user-scoped queries filter on this. |-| `platform` | text | NOT NULL | `'youtube'` or `'instagram'` |-| `data` | jsonb | NOT NULL | All platform-specific fields (see below) |+| `id` | text | NOT NULL | PK. A UUID from `newRowId()` (`crypto.randomUUID()`); older rows keep their earlier ids |+| `user_id` | uuid | NOT NULL | FK -> `auth.users.id` ON DELETE CASCADE. All user-scoped queries filter on this |+| `platform` | text | NOT NULL | `'youtube'`, `'instagram'` or `'reddit'` |+| `data` | jsonb | NOT NULL DEFAULT `'{}'` | All platform-specific fields (see below) |+| `created_at` | timestamptz | NOT NULL DEFAULT now() | When the account was connected. The list order |+| `updated_at` | timestamptz | NOT NULL DEFAULT now() | Set by the trigger on every update |++| Constraint | Rule |+|---|---|+| `accounts_platform_check` | `platform in ('youtube', 'instagram', 'reddit')` |+| `accounts_data_check` | `data` is a JSON object |+| `accounts_id_user_id_key` | `unique (id, user_id)`, so posts can reference an account together with its owner |### `data` jsonb shape for YouTube accounts@@ -57,12 +94,7 @@ Stores connected YouTube channels and Instagram accounts.}```-**Critical:** `accessToken` is always stripped by `safeAccount()` before being returned in any API response. It is intentionally stored server-side for use by the publishing and token-refresh pipelines.--### Indexes recommended--- `accounts(user_id)` - speeds up all user-scoped queries-- `accounts(platform)` - speeds up cross-user platform queries in cron handlers+**Critical:** `accessToken` (and a Reddit account's `cookie`) is always stripped by `safeAccount()` before being returned in any API response. It is intentionally stored server-side for use by the publishing and token-refresh pipelines.---@@ -72,13 +104,16 @@ Per-user key-value configuration store.| Column | Type | Nullable | Description ||---|---|---|---|-| `user_id` | uuid | NOT NULL | PK (composite). FK -> `auth.users.id` |+| `user_id` | uuid | NOT NULL | PK (composite). FK -> `auth.users.id` ON DELETE CASCADE || `key` | text | NOT NULL | PK (composite). Currently only `'api_keys'` |-| `value` | jsonb | - | Configuration payload |+| `value` | jsonb | NOT NULL DEFAULT `'{}'` | Configuration payload |+| `created_at` | timestamptz | NOT NULL DEFAULT now() | When the row was first saved |+| `updated_at` | timestamptz | NOT NULL DEFAULT now() | Set by the trigger on every update, the upsert's update included |-### Primary key: `(user_id, key)`--This means each user can have one row per `key`. Upserts use `onConflict: 'user_id,key'`.+| Constraint | Rule |+|---|---|+| Primary key | `(user_id, key)`: one row per user per key. Upserts use `onConflict: 'user_id,key'` |+| `settings_value_check` | `value` is a JSON object |### `value` jsonb shape for `key='api_keys'`@@ -99,17 +134,29 @@ Stores Instagram posts queued for future publishing.| Column | Type | Nullable | Description ||---|---|---|---|-| `id` | text | NOT NULL | PK. Client-generated: same pattern as `accounts.id` |-| `user_id` | uuid | NOT NULL | FK -> `auth.users.id` |-| `account_id` | text | NOT NULL | FK -> `accounts.id` |-| `status` | text | NOT NULL | `'pending'`, `'publishing'`, `'published'`, `'failed'` |+| `id` | text | NOT NULL | PK. A UUID from `newRowId()`; older rows keep their earlier ids |+| `user_id` | uuid | NOT NULL | FK -> `auth.users.id` ON DELETE CASCADE |+| `account_id` | text | NOT NULL | With `user_id`, FK -> `accounts (id, user_id)` ON DELETE CASCADE |+| `status` | text | NOT NULL DEFAULT 'pending' | `'pending'`, `'publishing'`, `'published'`, `'failed'` || `scheduled_at` | timestamptz | NOT NULL | UTC timestamp when the post should be published || `claimed_at` | timestamptz | NULL | When a scheduler last claimed the post. A `publishing` post whose claim is older than 20 minutes is taken over by the next run || `attempts` | integer | NOT NULL DEFAULT 0 | How many times a scheduler has claimed the post. The third failed attempt is final |-| `data` | jsonb | - | Post content and result data (see below) |+| `data` | jsonb | NOT NULL DEFAULT `'{}'` | Post content and result data (see below) |+| `created_at` | timestamptz | NOT NULL DEFAULT now() | When the post was scheduled |+| `updated_at` | timestamptz | NOT NULL DEFAULT now() | Set by the trigger on every update, the claim included |`claimed_at` and `attempts` change only in the claim, never through `updateById` or `updatePendingForUser`. The API returns them as `claimedAt` and `attempts` on `ScheduledPost`.+| Constraint | Rule |+|---|---|+| `scheduled_posts_status_check` | `status in ('pending', 'publishing', 'published', 'failed')` |+| `scheduled_posts_attempts_check` | `attempts >= 0` |+| `scheduled_posts_claim_check` | A `publishing` post has a `claimed_at`, because the lease is measured from it |+| `scheduled_posts_data_check` | `data` is a JSON object |+| `scheduled_posts_account_fkey` | `(account_id, user_id)` -> `accounts (id, user_id)` ON DELETE CASCADE |++The composite foreign key means a post can only name an account of the same user. Removing an account removes its scheduled posts, published records included.+### Status lifecycle```@@ -147,39 +194,6 @@ A claim is one UPDATE that sets `status = 'publishing'`, `claimed_at = now()` an- `publishedMediaId` is `null` when a run found the post already published through the container status, because that status does not carry the media id.- `error` is set on a `failed` post, and also on a `pending` post that is being retried, where it holds the reason the last attempt failed.-### Indexes--```sql-create index if not exists scheduled_posts_user_id_idx on public.scheduled_posts (user_id);-create index if not exists scheduled_posts_due_idx on public.scheduled_posts (status, scheduled_at);-```--- `scheduled_posts_user_id_idx` - user-scoped queries-- `scheduled_posts_due_idx` - the scheduler queries: due posts (`status = 'pending' AND scheduled_at <= now()`) and stale claims (`status = 'publishing'`)--These were listed as recommended before but did not exist in the production database; the upgrade SQL below creates them.--### Upgrade SQL (claim lease and attempts)--Run once in the Supabase SQL editor on an instance created before the claim lease. Run it before deploying the code that reads `claimed_at` and `attempts`.--```sql-alter table public.scheduled_posts- add column if not exists claimed_at timestamptz,- add column if not exists attempts integer not null default 0;---- posts stuck before this change have no saved container, so nothing can tell whether they went out-update public.scheduled_posts-set status = 'failed',- data = data || jsonb_build_object('error', 'Publishing was interrupted before Twiligent tracked it. Check Instagram before scheduling this post again.')-where status = 'publishing' and claimed_at is null;--create index if not exists scheduled_posts_user_id_idx on public.scheduled_posts (user_id);-create index if not exists scheduled_posts_due_idx on public.scheduled_posts (status, scheduled_at);-```--A new instance gets the columns and indexes from the setup SQL in `README.md` and `site/content/docs/self-host/supabase.mdx`.----## Table: `tracked_posts`@@ -188,16 +202,25 @@ Stores Reddit posts and YouTube videos the user wants to monitor. Previously Red| Column | Type | Nullable | Description ||---|---|---|---|-| `id` | text | NOT NULL | PK. Client-generated: `Date.now().toString(36) + Math.random().toString(36).slice(2)` |+| `id` | text | NOT NULL | PK. A UUID from `newRowId()`; older rows keep their earlier ids || `user_id` | uuid | NOT NULL | FK -> `auth.users.id` ON DELETE CASCADE |-| `account_id` | text | NULL | FK -> `accounts.id` ON DELETE SET NULL. Reddit only: which account's cookie to use |+| `account_id` | text | NULL | With `user_id`, FK -> `accounts (id, user_id)` ON DELETE SET NULL (`account_id`). Reddit only: which account's cookie to use || `url` | text | NOT NULL | Full URL of the Reddit post or YouTube video || `label` | text | NOT NULL DEFAULT '' | User-defined name for the item || `category` | text | NOT NULL DEFAULT '' | User-defined grouping label; shared across Reddit and YouTube items || `content_type` | text | NOT NULL DEFAULT 'reddit' | `'reddit'` or `'youtube'` || `created_at` | timestamptz | NOT NULL DEFAULT now() | When the user added the item |-| `updated_at` | timestamptz | NOT NULL DEFAULT now() | Last time any field or the cached data was changed |-| `data` | jsonb | NULL | Cached data fetched from the platform API (see below) |+| `updated_at` | timestamptz | NOT NULL DEFAULT now() | Set by the trigger on every update; the code no longer sets it |+| `data` | jsonb | NULL | Cached data fetched from the platform API, stored in the same insert that creates the row (see below) |++| Constraint | Rule |+|---|---|+| `tracked_posts_content_type_check` | `content_type in ('reddit', 'youtube')` |+| `tracked_posts_account_check` | Only Reddit items have an account: `content_type = 'reddit' or account_id is null` |+| `tracked_posts_data_check` | `data` is null or a JSON object |+| `tracked_posts_account_fkey` | `(account_id, user_id)` -> `accounts (id, user_id)` ON DELETE SET NULL (`account_id`) |++Removing an account keeps its tracked items and clears only their `account_id`. The column list on SET NULL needs Postgres 15 or later; a plain SET NULL would try to clear `user_id` too.### `data` jsonb shape for Reddit items@@ -230,10 +253,11 @@ until then.reaches the Worker, which stores it after checking the URL parses and uses `https:`. Thatcheck matters because the value is rendered straight into an `img src`.-Because of this, the refresh route calls `patchTrackedPostData()` rather than-`updateTrackedPost({ data })` - the former merges freshly fetched keys into the existing-blob so a manually entered view count survives a refresh. Anything writing to `data` for a-Reddit item must merge, never replace.+Because of this, the refresh route calls `patchDataForUser()` rather than+`updateForUser({ data })` - the former merges freshly fetched keys into the existing+blob in the database (`merge_tracked_post_data`), so a manually entered view count survives+a refresh that lands at the same moment. Anything writing to `data` for a Reddit item must+merge, never replace.Both keys are rejected for YouTube items, which already carry a real `viewCount` and `thumbnail`.@@ -260,31 +284,54 @@ Populated by `fetchTrackedYouTubeData()` in `backend/services/youtube/youtubeTraData is fetched on create and on manual refresh only. Not re-fetched on every GET.-### Indexes+----```sql-CREATE INDEX tracked_posts_user_id_idx ON tracked_posts(user_id);-```+## Why CHECK Constraints, Not Enums-### Migration SQL (initial table + content_type addition)--```sql-CREATE TABLE tracked_posts (- id text PRIMARY KEY,- user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,- account_id text REFERENCES accounts(id) ON DELETE SET NULL,- url text NOT NULL,- label text NOT NULL DEFAULT '',- category text NOT NULL DEFAULT '',- created_at timestamptz NOT NULL DEFAULT now(),- updated_at timestamptz NOT NULL DEFAULT now(),- data jsonb-);-CREATE INDEX tracked_posts_user_id_idx ON tracked_posts(user_id);---- Added in Tracked Content expansion-ALTER TABLE tracked_posts ADD COLUMN IF NOT EXISTS content_type text NOT NULL DEFAULT 'reddit';-```+Allowed values (`platform`, `status`, `content_type`) are CHECK constraints, not Postgres enum types. A value is added or removed by replacing one constraint in a migration; an enum value cannot be removed, and adding one needs care inside a transaction. The constraint still records the allowed values in the schema, and a wrong value fails at the write instead of breaking a later read.++---++## Indexes++An index exists because a frequent query filters or orders on its columns. Each list query is served by its index with no sort step.++| Index | Columns | Query it serves | Why |+|---|---|---|---|+| `accounts_user_id_created_at_idx` | `accounts (user_id, created_at, id)` | `accounts.listForUser`: `where user_id = $1 order by created_at, id` | Every page load lists the user's accounts; `id` breaks ties so the order never changes |+| `scheduled_posts_user_id_scheduled_at_idx` | `scheduled_posts (user_id, scheduled_at)` | `scheduledPosts.listForUser`: `where user_id = $1 order by scheduled_at`, and the counts behind delete all | Replaces `scheduled_posts_user_id_idx` |+| `scheduled_posts_due_idx` | `scheduled_posts (scheduled_at) where status = 'pending'` | `listDue`: pending posts at or before now | Partial, so the growing published history is left out. Runs every 15 minutes from two schedulers |+| `scheduled_posts_claimed_idx` | `scheduled_posts (claimed_at) where status = 'publishing'` | `listStale`: publishing posts whose claim is older than the lease | Partial, the same reason |+| `tracked_posts_user_id_created_at_idx` | `tracked_posts (user_id, created_at desc)` | `trackedPosts.listForUser`: `where user_id = $1 order by created_at desc` | Replaces `tracked_posts_user_id_idx` |++The primary keys serve every lookup by `id`, and `settings` is read through its `(user_id, key)` primary key.++### Not indexed on purpose++| Column | Why not |+|---|---|+| `accounts.platform` | Only the daily token refresh filters on it (`listByPlatform('instagram')`), once a day over a small table. A scan is cheaper than keeping an index on every write |+| `scheduled_posts.account_id` | Only used when an account is removed (the cascade), which is rare |+| `tracked_posts.account_id` | Only used when an account is removed (the set null), which is rare |++No query uses window functions or ranking. The channel comparison ranks a handful of YouTube channels in TypeScript, so no ranking index applies.++---++## Triggers and Functions++Every function sets `search_path = ''` and names its tables with the schema. Functions in `public` are exposed through the Data API, so each one revokes execute from `public`, `anon` and `authenticated`, and the merge functions grant it only to `service_role`. `backend/tests/database/migrations.test.ts` fails if a migration creates a function without the revoke.++| Function | Kind | What it does |+|---|---|---|+| `set_updated_at()` | plpgsql trigger | Sets `updated_at = now()`. A `before update` trigger on each table (`<table>_set_updated_at`) calls it, so no query has to set the column |+| `merge_account_data(p_id, p_user_id, p_patch)` | sql | `data = data \|\| p_patch` on one account |+| `merge_scheduled_post(p_id, p_user_id, p_patch, p_status, p_scheduled_at, p_only_status)` | sql | Merges `p_patch` into `data` and sets `status` and `scheduled_at` when given, in one UPDATE. `p_only_status` limits the update to a post still in that status |+| `merge_tracked_post_data(p_id, p_user_id, p_patch)` | sql | `data = coalesce(data, '{}') \|\| p_patch` on one tracked item |++The merge functions return `true` when a row matched and `null` when none did. A null `p_user_id` is the cron form, which reaches any user's row; `merge_tracked_post_data` always needs a user. The merge is one statement, so two writers at the same moment (a token refresh and an analytics refresh on one account) never put an old value back.++`data || patch` is a shallow, top-level merge, like the spread it replaced. A field sent as `undefined` is dropped from the JSON request, so it keeps its stored value instead of being removed.---@@ -292,20 +339,22 @@ ALTER TABLE tracked_posts ADD COLUMN IF NOT EXISTS content_type text NOT NULL DEAll 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).+Updates to `accounts.data` and `scheduled_posts` go through the merge functions with `db.rpc(...)`, never a read followed by a write. `trackedPosts.patchDataForUser` uses `merge_tracked_post_data`.+### Available methods-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`, `listStale`, `claim`) reach every user and are only for the cron jobs.+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` (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `claim`) reach every user and are only for the cron jobs.```ts// Accounts (accountRepository.ts)-listForUser(userId): Promise<Account[]>-listAll(): Promise<Account[]> // cron only+listForUser(userId): Promise<Account[]> // ordered by created_at, then id+listByPlatform(platform): Promise<Account[]> // cron only - filtered in SQLfindForUser(id, userId): Promise<Account | null>findById(id): Promise<Account | null> // cron onlycreate(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>+updateForUser(id, updates: Partial<Account>, userId): Promise<void> // merge_account_data; NotFoundError when no row matched+updateById(id, updates: Partial<Account>): Promise<void> // cron only - merge_account_data+deleteForUser(id, userId): Promise<void> // also removes the account's scheduled posts (cascade)// Settings (settingsRepository.ts)getForUser(userId): Promise<Settings>@@ -318,17 +367,17 @@ listDue(): Promise<ScheduledPost[]> // cron onlistStale(claimedBefore): Promise<ScheduledPost[]> // cron only - publishing with a claim older than the cutoffclaim(post): Promise<ScheduledPost | null> // cron only - the claimed post; null when another run woncreate(post: ScheduledPost, userId): Promise<void>-updatePendingForUser(id, updates: Partial<ScheduledPost>, userId): Promise<boolean> // false when the post is no longer pending-updateById(id, updates: Partial<ScheduledPost>): Promise<void> // cron only+updatePendingForUser(id, updates: Partial<ScheduledPost>, userId): Promise<boolean> // merge_scheduled_post with p_only_status 'pending'; false when the post is no longer pending+updateById(id, updates: Partial<ScheduledPost>): Promise<void> // cron only - merge_scheduled_postdeleteForUser(id, userId): Promise<boolean> // never deletes a 'publishing' post; false when nothing was deleteddeleteAllForUser(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>+create(post: NewTrackedPost, userId): Promise<void> // data goes in the same insertupdateForUser(id, updates: TrackedPostUpdates, userId): Promise<void>-patchDataForUser(id, patch: Record<string, unknown>, userId): Promise<void>+patchDataForUser(id, patch: Record<string, unknown>, userId): Promise<void> // merge_tracked_post_data; NotFoundError when no row matcheddeleteForUser(id, userId): Promise<void>```@@ -336,4 +385,4 @@ The Redis analytics cache has its own repository, `analyticsCacheRepository.ts`;## Adding a New Table-See `docs/features/NEW_DATABASE_TABLE.md` for the full workflow including migration strategy.+See `docs/features/NEW_DATABASE_TABLE.md` for the full workflow: the migration, its rollback, the repository and the docs.diff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.mdindex cd55fe2..84be526 100644--- a/docs/architecture/database/SECURITY.md+++ b/docs/architecture/database/SECURITY.md@@ -8,13 +8,25 @@ The backend uses the **service-role key** for all database operations. This key2. 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 `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`, `listStale`, `claim`) are used only by the cron services. Because ownership is a query filter, another user's record is simply not found (404).+**This means a missing `.eq('user_id', userId)` call is a security bug.** The centralization of all queries in `backend/repositories/` makes this auditable: a method that takes a `userId` ends in `ForUser`, and the few that reach every user (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `claim`) 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?+The merge functions follow the same rule: the `...ForUser` repository methods pass the verified `userId` as `p_user_id`, and only `updateById` passes `null`, the cron form that reaches any user's row.-See `DECISIONS.md` ADR-011 for the full reasoning. Summary:+## Ownership of Referenced Accounts++A scheduled post names the account it publishes to, and a tracked Reddit item names the account whose cookie reads it. Both are checked twice:++1. **In the service.** `scheduledPostService.create` loads the account with `accounts.findForUser(accountId, userId)` and passes it to `publishableAccount()`: another user's account, a missing one or one that is not Instagram answers 404 `Instagram account not found`, and one with no token answers 400 `No Instagram access token stored - reconnect this account`. `trackedContentService.update` refuses an account on a YouTube item (400) and answers 404 `Reddit account not found` for an account that is not one of the user's Reddit accounts.+2. **In the database.** `scheduled_posts` and `tracked_posts` reference `accounts (id, user_id)` with a composite foreign key, so a row whose `account_id` belongs to another user cannot be written, whatever the code does.++Row ids are UUIDs from `crypto.randomUUID()` (`newRowId()` in `backend/lib/ids.ts`). Before, they were built from the time and `Math.random`, which is predictable; an id is still never trusted on its own, but it can no longer be worked out from another.++## Why Not Use RLS Policies?++See `DECISIONS.md` ADR-011 and ADR-038 for the full reasoning. Summary:- Cron handlers (scheduler, token refresh) need to query across all users - they cannot be scoped to a single JWT- Using the service-role key with application-layer filtering achieves the same isolation with less complexity+- A policy that lets a signed-in user reach their own rows would also let them read their raw Instagram tokens and Reddit cookies and write rows the API would refuse. The browser has no reason to touch the tables, so it gets no access at all## Key Hierarchy@@ -24,20 +36,26 @@ See `DECISIONS.md` ADR-011 for the full reasoning. Summary:| `SUPABASE_ANON_KEY` | Cloudflare Worker (`requireAuth` only) | Only `getUser(token)` - JWT verification || `VITE_SUPABASE_ANON_KEY` | Frontend browser | Supabase Auth (sign in, sign up, sign out, session management) |-The anon key is public: it ships in the frontend bundle. It cannot read or write application tables **only if RLS is enabled on them**. With RLS disabled, Supabase's Data API lets anyone holding the anon key query the tables directly, bypassing the Worker.+The anon key is public: it ships in the frontend bundle, and a signed-in browser also holds a JWT for the `authenticated` role. Supabase's Data API accepts both, so the database itself must refuse them.++## Required: No Browser Access to Tables or Functions++The migrations in `supabase/migrations/` enforce this on every instance:++| Rule | Migration | Effect |+|---|---|---|+| Row level security on, with no policies | `baseline_<table>` (four files) | The `anon` and `authenticated` roles match no row |+| No grants to the browser roles | `revoke_browser_access_<table>` (four files) | `revoke all on table ... from anon, authenticated`; the Data API answers 401 permission denied |+| No grants on future objects | `revoke_browser_default_privileges` | `alter default privileges for role postgres in schema public revoke all on tables` and `on functions from anon, authenticated` |+| Functions closed | each `create_*_function` file | `revoke execute ... from public, anon, authenticated`; the merge functions are granted only to `service_role` |-## Required: RLS Enabled With No Policies+The service-role key used by the Worker and the GitHub Actions scheduler bypasses row level security and keeps its grants. The frontend never queries tables directly (it uses Supabase only for Auth). `backend/tests/database/migrations.test.ts` fails if a migration creates a function without the revoke.-Every application table must have RLS enabled and no policies:+To check a live instance, call the Data API with the anon key (`GET <SUPABASE_URL>/rest/v1/accounts` with the `apikey` header): it must answer 401 for all four tables and for `POST /rest/v1/rpc/merge_account_data`. The manual check is in `docs/workflows/TESTING.md`.-```sql-alter table accounts enable row level security;-alter table settings enable row level security;-alter table scheduled_posts enable row level security;-alter table tracked_posts enable row level security;-```+### What was wrong before-This denies the anon and authenticated roles everything, while the service-role key used by the Worker and the GitHub Actions scheduler still bypasses RLS. The frontend never queries tables directly (it uses Supabase only for Auth), so no policies are needed. Supabase's Table Editor flags any table with RLS disabled. The setup SQL in the README and on the public docs page `/docs/self-host/supabase` (`site/content/docs/self-host/supabase.mdx`) includes these statements.+Before the migrations, production had drifted from this model. The tables had the policies `users_own_accounts`, `users_own_settings` and `users_own_posts` (`for all using (auth.uid() = user_id)`) and full table grants to `anon` and `authenticated`. A signed-in user could read their raw Instagram tokens and Reddit cookies through the Data API and write rows directly, for example a scheduled post naming another user's account, which the scheduler would then publish to. `scheduled_posts` also had no foreign key to `accounts`, and the API never checked scheduled post account ownership. The migrations removed the policies and grants and added the composite keys; the service checks above were added at the same time.## Signups@@ -75,8 +93,10 @@ The Instagram `accessToken` stored in `accounts.data.accessToken` is a long-liveWhen reviewing security, check these files:- `backend/middleware/auth.ts` - JWT verification-- `backend/repositories/` - every user-scoped method ends in `ForUser` and filters by `user_id`; the methods without a `userId` are used only by `scheduledPublisher.ts` and `tokenRefreshService.ts`. `emailQuotaRepository.ts` is not user-scoped: it keeps instance-wide Redis counters for the Send Email hook, keyed by a hash of the address+- `backend/repositories/` - every user-scoped method ends in `ForUser` and filters by `user_id` (or passes it as `p_user_id` to a merge function); the methods without a `userId` are used only by `scheduledPublisher.ts` and `tokenRefreshService.ts`. `emailQuotaRepository.ts` is not user-scoped: it keeps instance-wide Redis counters for the Send Email hook, keyed by a hash of the address- `backend/middleware/authHook.ts` and `backend/lib/webhookSignature.ts` - the only thing that authenticates the public Send Email hook- `backend/controllers/` and `backend/services/` - the `userId` passed to a repository always comes from `c.get('userId')`, never from the body or query- `backend/lib/safeAccount.ts` - `safeAccount()` definition; it strips every stored credential for all platforms+- `supabase/migrations/` - no migration grants anything to `anon` or `authenticated`, and every function revokes execute from them+- `backend/services/scheduledPostService.ts` and `trackedContentService.ts` - an account named in a request is loaded with `findForUser` before it is stored- All controllers in `backend/controllers/` - verify `safeAccount()` is called on every account responsediff --git a/docs/features/NEW_DATABASE_TABLE.md b/docs/features/NEW_DATABASE_TABLE.mdindex 69a6ef5..c7bde4e 100644--- a/docs/features/NEW_DATABASE_TABLE.md+++ b/docs/features/NEW_DATABASE_TABLE.md@@ -12,45 +12,92 @@ Before creating a new table, consider whether the data fits the existing jsonb p### Step 1: Define the SchemaDecide the column structure. Follow the existing conventions:-- Include `id text NOT NULL PRIMARY KEY` (client-generated)-- Include `user_id uuid NOT NULL` (FK to auth.users)-- Use `data jsonb` for flexible platform-specific fields+- Include `id text primary key`, filled by `newRowId()` from `backend/lib/ids.ts` (a UUID)+- Include `user_id uuid not null` (FK to `auth.users`, on delete cascade)+- Include `created_at` and `updated_at` (`timestamptz not null default now()`); the `set_updated_at()` trigger keeps `updated_at`+- Use `data jsonb not null default '{}'` for flexible platform-specific fields, with a check that it is an object- Use dedicated columns for fields you'll query/filter on (status, timestamps, foreign keys)+- Allowed values are a CHECK constraint, never a Postgres enum (see `docs/architecture/database/SCHEMA.md`)+- A reference to an account is composite, `(account_id, user_id)` -> `accounts (id, user_id)`, so a row can only name an account of the same user+- Index only what a frequent query filters or orders on, in the order the query uses-Example schema for a hypothetical `content_drafts` table:-```sql-CREATE TABLE content_drafts (- id text PRIMARY KEY,- user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,- account_id text NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,- platform text NOT NULL,- status text NOT NULL DEFAULT 'draft',- created_at timestamptz NOT NULL DEFAULT now(),- updated_at timestamptz NOT NULL DEFAULT now(),- data jsonb-);+### Step 2: Write the Migration-CREATE INDEX content_drafts_user_id_idx ON content_drafts(user_id);-CREATE INDEX content_drafts_status_idx ON content_drafts(status);+The schema is versioned in `supabase/migrations/` and applied with the Supabase CLI. Never create or change a table in the SQL editor or the Table Editor. One file holds one change to one table or one function.++```bash+npm run db:new create_content_drafts```-### Step 2: Create the Table in Supabase+This creates `supabase/migrations/<timestamp>_create_content_drafts.sql`. Write the table with its constraints, row level security, trigger and index:-Option A: Supabase Dashboard -> SQL Editor -> paste and run the SQL above+```sql+-- drafts a user prepares before scheduling them+create table public.content_drafts (+ id text primary key,+ user_id uuid not null references auth.users (id) on delete cascade,+ account_id text not null,+ platform text not null,+ status text not null default 'draft',+ data jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ constraint content_drafts_account_fkey foreign key (account_id, user_id)+ references public.accounts (id, user_id) on delete cascade,+ constraint content_drafts_status_check check (status in ('draft', 'ready', 'archived')),+ constraint content_drafts_data_check check (jsonb_typeof(data) = 'object')+);-Option B: Supabase Dashboard -> Table Editor -> create visually+-- only the Worker's service role reads the table; the anon key ships in every browser+alter table public.content_drafts enable row level security;+revoke all on table public.content_drafts from anon, authenticated;-There 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.+create trigger content_drafts_set_updated_at before update on public.content_drafts+ for each row execute function public.set_updated_at();-### Step 3: Enable Row-Level Security (Required)+-- contentDrafts.listForUser: where user_id = $1 order by created_at desc+create index content_drafts_user_id_created_at_idx on public.content_drafts (user_id, created_at desc);+```-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`):+Write the reverse in `supabase/rollbacks/` with the same file name. `backend/tests/database/migrations.test.ts` fails when a migration has no rollback:```sql-ALTER TABLE content_drafts ENABLE ROW LEVEL SECURITY;+-- removes the table and every draft in it+drop table if exists public.content_drafts;```-Add the statement to the setup SQL in the README and in the SQL block of the public docs page `/docs/self-host/supabase` (`site/content/docs/self-host/supabase.mdx`). Add the `CREATE TABLE` there too, so a new instance gets the table.+If the repository updates `data`, add a merge function in its own migration (`npm run db:new create_merge_content_draft_function`), so an update is one statement and two writers never undo each other. Copy `create_merge_scheduled_post_function.sql`. A function in `public` is exposed through the Data API, so it always revokes execute from the browser roles and grants it only to the service role; the migration test enforces the revoke:++```sql+-- merges a patch into data in one UPDATE, so two writers never undo each other+create or replace function public.merge_content_draft(p_id text, p_user_id uuid, p_patch jsonb, p_status text default null)+returns boolean+language sql+set search_path = ''+as $$+ update public.content_drafts+ set data = data || p_patch,+ status = coalesce(p_status, status)+ where id = p_id and user_id = p_user_id+ returning true;+$$;++-- functions in public are exposed through the Data API, so only the service role may call it+revoke execute on function public.merge_content_draft(text, uuid, jsonb, text) from public, anon, authenticated;+grant execute on function public.merge_content_draft(text, uuid, jsonb, text) to service_role;+```++Its rollback is `drop function if exists public.merge_content_draft(text, uuid, jsonb, text);`.++### Step 3: Apply the Migration++1. Run `npm test --workspace backend`. The migration test checks the file names, the rollback pairs and the function grants.+2. Link the CLI to the project once: `npx supabase link --project-ref <ref>`. It needs `SUPABASE_ACCESS_TOKEN` in the environment or `npx supabase login`.+3. Run `npm run db:check` and read the list of migrations it would apply.+4. Run `npm run db:push` before merging the code that needs the table, because merging deploys the Worker at once.+5. Run `npm run db:status` and check that the new version is in both the Local and Remote columns.++A new instance gets the table from the same `npm run db:push`; there is no setup SQL to update in the README or the docs site. To undo the change, see Rolling Back a Database Change in `docs/workflows/DEPLOYMENT.md`.### Step 4: Add the Types@@ -153,18 +200,10 @@ export function createContentDraftRepository(db: SupabaseClient): ContentDraftRe}));},- // merges into data, so fields the update does not name are kept+ // one atomic merge in the database, so fields the update does not name are keptasync 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));+ const { status, ...patch } = updates;+ await execute('contentDrafts.update', () => db.rpc('merge_content_draft', { p_id: id, p_user_id: userId, p_patch: patch, p_status: status ?? null }));},async deleteForUser(id, userId) {@@ -174,7 +213,7 @@ export function createContentDraftRepository(db: SupabaseClient): ContentDraftRe}```-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`).+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, name it without the `ForUser` suffix (`listByPlatform`, `findById`, `updateById`), and filter in SQL rather than loading every row and filtering in TypeScript. New ids come from `newRowId()` in `backend/lib/ids.ts`; tests pin them with `mockRowIds()` from `backend/tests/fixtures/rowIds.ts`.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.@@ -183,8 +222,9 @@ Build the repository in `createServices()` in `backend/container.ts` (`const draUpdate `docs/architecture/database/SCHEMA.md` with:- Table name and purpose- All columns with types, constraints, and descriptions+- The constraints, foreign keys and their delete actions- The `data` jsonb shape-- Recommended indexes+- Each index with the query it serves, and the merge function if there is one### Step 7: Wire Up the Feature@@ -196,7 +236,8 @@ Follow the guides for:- Table names: `snake_case`, plural - `content_drafts`, `webhook_configs`- All tables must have `user_id uuid NOT NULL`-- If table relates to an account: also include `account_id text NOT NULL`-- Status columns: text, with documented enum values-- Timestamp columns: `timestamptz` with `DEFAULT now()`+- If table relates to an account: also include `account_id text NOT NULL` and the composite foreign key to `accounts (id, user_id)`+- Status columns: text with a CHECK constraint listing the values (`<table>_status_check`)+- Timestamp columns: `timestamptz` with `DEFAULT now()`; every table has `created_at` and `updated_at` with the `set_updated_at()` trigger+- Migration files: named for the change, verb first (`create_content_drafts`, `index_content_drafts_list`); see `docs/guidelines/NAMING.md`- jsonb data column: always name it `data` (consistent with existing tables)diff --git a/docs/features/NEW_INTEGRATION.md b/docs/features/NEW_INTEGRATION.mdindex 065e9db..480a6b7 100644--- a/docs/features/NEW_INTEGRATION.md+++ b/docs/features/NEW_INTEGRATION.md@@ -20,6 +20,7 @@ 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` |+| Database | `supabase/migrations/`, `supabase/rollbacks/` | A migration that replaces `accounts_platform_check` with one that lists the new platform, and its rollback (`docs/features/NEW_DATABASE_TABLE.md`); run `npm run db:push` before deploying || 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 |diff --git a/docs/features/NEW_SCHEDULED_TASK.md b/docs/features/NEW_SCHEDULED_TASK.mdindex 19f1a84..848777e 100644--- a/docs/features/NEW_SCHEDULED_TASK.md+++ b/docs/features/NEW_SCHEDULED_TASK.md@@ -17,7 +17,7 @@ For most tasks: use the Cloudflare Worker cron first. It's simpler and doesn't r### Step 1: Write the job as a service method-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.+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 (`listByPlatform`, `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. Filter in SQL, not by loading every row and filtering in TypeScript, and only add an index if the job runs often enough to need one (`docs/philosophy/PERFORMANCE.md`).```ts// backend/services/myPlatformTokenRefreshService.ts@@ -40,7 +40,7 @@ export function createMyPlatformTokenRefreshService({ accounts, context }: MyPlareturn {async refreshTokens() {- const listed = (await accounts.listAll()).filter(account => account.platform === 'myPlatform');+ const listed = await accounts.listByPlatform('myPlatform');for (const account of listed) {if (!account.accessToken) continue;try {@@ -57,7 +57,7 @@ export function createMyPlatformTokenRefreshService({ accounts, context }: MyPla}```-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`).+A cron job must never throw for one bad account: catch per account and log, as above. `listByPlatform('myPlatform')` only type-checks once the platform is in the `Platform` union in `shared/types/domain.ts`, and the database only stores such an account once a migration adds the platform to `accounts_platform_check` (see `NEW_INTEGRATION.md`).Add it to `Services` and `createServices()` in `backend/container.ts`:diff --git a/docs/guidelines/CODE_STYLE.md b/docs/guidelines/CODE_STYLE.mdindex 923daac..c2b2700 100644--- a/docs/guidelines/CODE_STYLE.md+++ b/docs/guidelines/CODE_STYLE.md@@ -80,6 +80,8 @@ The layers are in `docs/architecture/backend/REQUEST_PIPELINE.md`; the recipes a- Services never import `hono`. They receive repositories, `AppConfig` and the `RequestContext`, and log through `context.log` with a short lowercase message and fields: `context.log.warn('auth email skipped', { action, reason: 'limit reached' })`.- Every platform `fetch` gets `context.signal` (plus its own timeout when the caller has a budget).- Redis code catches every failure and falls back; nothing else swallows errors.+- The schema changes only through a migration in `supabase/migrations/` (`npm run db:new <verb>_<object>`) with its reverse in `supabase/rollbacks/` under the same name, one table or one function per file; a repository updates `data` through a merge function with `db.rpc()`, never by reading and writing it back. See `docs/features/NEW_DATABASE_TABLE.md`.+- New row ids come from `newRowId()` in `lib/ids.ts`; tests pin them with `mockRowIds()` from `tests/fixtures/rowIds.ts`.- No new runtime dependency in the Worker without approval: call HTTP APIs with `fetch` (Resend is called this way, not through its SDK).## Errors and Messagesdiff --git a/docs/guidelines/NAMING.md b/docs/guidelines/NAMING.mdindex c36c06e..e42bd8f 100644--- a/docs/guidelines/NAMING.md+++ b/docs/guidelines/NAMING.md@@ -25,6 +25,8 @@ Start with `docs/guidelines/CODE_STYLE.md`, which shows how code reads across th| 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/routes/accountRoutes.test.ts`, `backend/tests/services/youtube/youtubeChannels.test.ts` |+| Database migrations | `<14 digit version>_<verb>_<object>.sql` in `supabase/migrations/`, created by `npm run db:new <verb>_<object>` | `20261016001700_add_accounts_updated_at.sql`, `20261016002400_index_accounts_list.sql` |+| Database rollbacks | the same file name as the migration, in `supabase/rollbacks/` | `20261016001700_add_accounts_updated_at.sql` || Documentation | `SCREAMING_SNAKE_CASE.md` | `OVERVIEW.md`, `TYPESCRIPT.md`, `SCHEMA.md` |Use `.tsx` only for files that contain JSX; everything else is `.ts`.@@ -35,7 +37,7 @@ Use `.tsx` only for files that contain JSX; everything else is `.ts`.- 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()`, `listStale()`, `claim()`+- 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 - `listByPlatform()`, `findById()`, `updateById()`, `listDue()`, `listStale()`, `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()`@@ -69,6 +71,19 @@ Use `.tsx` only for files that contain JSX; everything else is `.ts`.- Table names: `snake_case`, plural - `accounts`, `settings`, `scheduled_posts`- Column names: `snake_case` - `user_id`, `account_id`, `scheduled_at`, `access_token` (inside jsonb)- jsonb field names: `camelCase` - they become fields on TypeScript objects, so they follow the code's naming: `accessToken`, `subscriberCount`, `publishedAt`+- Every table has `created_at` and `updated_at`; `updated_at` is kept by the `<table>_set_updated_at` trigger++| Object | Convention | Examples |+|---|---|---|+| Migration name | verb first, then the object; one table or one function per file | `baseline_accounts`, `add_accounts_updated_at`, `create_merge_account_data_function`, `revoke_browser_access_settings` |+| Value checks migration | `check_<table>_values` | `check_scheduled_posts_values` |+| Index migration | `index_<table>_<query>`, named for the query the index serves | `index_accounts_list`, `index_scheduled_posts_schedulers` |+| Index | `<table>_<columns>_idx`, or the purpose for a partial index | `accounts_user_id_created_at_idx`, `scheduled_posts_due_idx`, `scheduled_posts_claimed_idx` |+| CHECK constraint | `<table>_<column>_check` | `accounts_platform_check`, `scheduled_posts_claim_check` |+| Foreign key | `<table>_<referenced>_fkey` | `scheduled_posts_account_fkey` |+| Unique key | `<table>_<columns>_key` | `accounts_id_user_id_key` |+| Trigger | `<table>_set_updated_at` | `tracked_posts_set_updated_at` |+| Function | `snake_case` verb first; parameters prefixed `p_` | `set_updated_at()`, `merge_scheduled_post(p_id, p_user_id, p_patch)` |## Routesdiff --git a/docs/guidelines/SUPABASE.md b/docs/guidelines/SUPABASE.mdindex 01a7f12..8629784 100644--- a/docs/guidelines/SUPABASE.md+++ b/docs/guidelines/SUPABASE.md@@ -24,7 +24,12 @@ export interface AccountRepository {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));+ const found = await rows<AccountRow>('accounts.listForUser', () => db+ .from('accounts')+ .select(COLUMNS)+ .eq('user_id', userId)+ .order('created_at', { ascending: true })+ .order('id', { ascending: true }));return found.map(toAccount);},// ...@@ -67,21 +72,27 @@ 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 find(id, userId);-if (!current) throw new NotFoundError('Account not found');-const { id: _id, platform: currentPlatform, ...currentData } = current;-const { platform: newPlatform, ...dataUpdates } = updates;-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;-});+// Updating: one atomic merge in the database through a function in supabase/migrations+const { id: _id, platform: _platform, ...patch } = updates;+const { data } = await execute('accounts.update', () => db.rpc('merge_account_data', { p_id: id, p_user_id: userId, p_patch: patch }));+if (!data) throw new NotFoundError('Account not found');```-**Never replace the entire `data` object** without first reading the current value - you'll lose fields that aren't in the update.+**Never read `data` and write it back.** Two writers at the same moment (a token refresh and an analytics refresh on one account) would each write their copy, and the later one puts the other's old values back. Updates to `data` call a merge function with `db.rpc()`, which runs `data = data || p_patch` in one UPDATE:++| Function | Repository methods |+|---|---|+| `merge_account_data(p_id, p_user_id, p_patch)` | `accounts.updateForUser`, `accounts.updateById` |+| `merge_scheduled_post(p_id, p_user_id, p_patch, p_status, p_scheduled_at, p_only_status)` | `scheduledPosts.updatePendingForUser` (with `p_only_status: 'pending'`), `scheduledPosts.updateById`, and `updatePost` in `scripts/publish-scheduled.ts` |+| `merge_tracked_post_data(p_id, p_user_id, p_patch)` | `trackedPosts.patchDataForUser` |++Each function returns `true` when a row matched and `null` when none did, so the repository can throw `NotFoundError` or return `false`. A `...ForUser` method passes the verified `userId` as `p_user_id`; only the cron methods pass `null`. The merge is shallow (top-level keys), and a field set to `undefined` is dropped from the JSON request, so it keeps its stored value. `updated_at` is set by a database trigger on every table; never set it in a query. The functions are described in `docs/architecture/database/SCHEMA.md`.++## Schema Changes++The schema is versioned in `supabase/migrations/` and applied with the Supabase CLI (`npm run db:check`, then `npm run db:push`). Never change a table, index or function in the SQL editor. Each change is one file for one table or one function, with its reverse in `supabase/rollbacks/` under the same name. A new function in `public` revokes execute from `public, anon, authenticated` and grants it only to `service_role`. The workflow is in `docs/features/NEW_DATABASE_TABLE.md`.++New row ids come from `newRowId()` in `backend/lib/ids.ts` (`crypto.randomUUID()`), never from the time or `Math.random`.## Row Isolation@@ -96,7 +107,7 @@ export interface ScheduledPostRepository {}```-Only `scheduledPublisher.ts` and `tokenRefreshService.ts` call the cross-user methods (`listAll`, `findById`, `updateById`, `listDue`, `listStale`, `claim`). See `docs/architecture/database/SECURITY.md`.+Only `scheduledPublisher.ts` and `tokenRefreshService.ts` call the cross-user methods (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `claim`). A cross-user method filters in SQL (`listByPlatform('instagram')`), never by loading every row and filtering in TypeScript. See `docs/architecture/database/SECURITY.md`.## Client Lifecyclediff --git a/docs/philosophy/ARCHITECTURE.md b/docs/philosophy/ARCHITECTURE.mdindex 1822c5c..3e4264d 100644--- a/docs/philosophy/ARCHITECTURE.md+++ b/docs/philosophy/ARCHITECTURE.md@@ -16,7 +16,7 @@ Authentication is Supabase JWTs. The Worker verifies the JWT on every protected### 3. Application-layer isolation instead of RLS-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.+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 and the browser roles have no grants, only to keep the public anon key and members' own tokens away from the tables; it is not relied upon for isolation. The schema adds a second guard: composite foreign keys tie a post's account to the same user (ADR-038).**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`.diff --git a/docs/philosophy/PERFORMANCE.md b/docs/philosophy/PERFORMANCE.mdindex 87f5084..14f1fa0 100644--- a/docs/philosophy/PERFORMANCE.md+++ b/docs/philosophy/PERFORMANCE.md@@ -37,6 +37,19 @@ Each protected request runs two rate limit checks (`ip` before authentication, `The analytics cache follows the same rule: a 3 second timeout, one retry, then 30 seconds without Redis in that isolate after a failure (see `docs/architecture/backend/CACHING.md`).+## Database Queries and Indexes++Indexes follow the workload. A column gets an index when a frequent query filters or orders on it, and the index lists the columns in the order the query uses them. The full table, with the query each index serves, is in `docs/architecture/database/SCHEMA.md`.++- **Every list query is served by one index with no sort step.** `accounts (user_id, created_at, id)`, `scheduled_posts (user_id, scheduled_at)` and `tracked_posts (user_id, created_at desc)` match the filter and the `order by` of each `listForUser`. An index on `user_id` alone would still need a sort, so those were replaced.+- **The schedulers use partial indexes.** `listDue` reads only `pending` posts and `listStale` only `publishing` ones, so `scheduled_posts_due_idx` and `scheduled_posts_claimed_idx` cover just those rows. The published history grows for ever and never enters them.+- **Rare queries get no index.** `accounts.platform` is read once a day by the token refresh over a small table, and `account_id` on the post tables is only read when an account is removed. A scan there is cheaper than keeping an index current on every write.+- **Filter in SQL before fetching.** A query asks the database for the rows it needs (`listByPlatform('instagram')`), never every row to filter in TypeScript.+- **Write in one statement.** Updates to jsonb `data` call a merge function (`data || patch`), one round trip instead of a read and a write, and safe when two writers meet.+- **No ranking queries.** The channel comparison ranks a handful of YouTube channels in TypeScript; there are no window functions to index for.++A new index arrives as a migration named for its query (`index_<table>_<query>`), with the query in its one-line comment. Check it with `EXPLAIN` on the real query before relying on it.+## Edge DeploymentThe Cloudflare Worker runs at the edge - in a data center close to the user. This means:@@ -67,7 +80,6 @@ If a route feels slow, add Redis caching first before optimizing the underlying## What We Don't Optimize (Yet)-- **Database indexes:** The `accounts` and `scheduled_posts` tables have only a primary key index. If query performance degrades as the table grows, add an index on `user_id`. See ROADMAP.- **Response compression:** Cloudflare automatically compresses Worker responses with gzip/brotli - no code needed.- **Image optimization:** Cloudinary handles image resizing and format conversion for Instagram posts. No custom image optimization in the app layer.- **Frontend rendering performance:** The app is not a high-frequency update scenario. No virtualization, no memoization beyond standard React patterns. If analytics tables get large (1000+ rows), add pagination.diff --git a/docs/philosophy/SECURITY.md b/docs/philosophy/SECURITY.mdindex 0b7f6c2..2f11367 100644--- a/docs/philosophy/SECURITY.md+++ b/docs/philosophy/SECURITY.md@@ -4,7 +4,7 @@| Credential | Where stored | Who reads it | Exposed to client? ||---|---|---|---|-| Supabase anon key | `VITE_SUPABASE_ANON_KEY` (env var in frontend build) | Frontend (Supabase JS auth) | **Yes - intentionally public**, which is why RLS must be enabled on every application table (see `docs/architecture/database/SECURITY.md`) |+| Supabase anon key | `VITE_SUPABASE_ANON_KEY` (env var in frontend build) | Frontend (Supabase JS auth) | **Yes - intentionally public**, which is why every application table and function is closed to the browser roles: RLS on with no policies, and no grants (see `docs/architecture/database/SECURITY.md`) || Supabase service role key | Worker secret | Worker only | **Never** || Instagram App ID | Worker secret | Worker only | **Never** || Instagram App Secret | Worker secret | Worker only | **Never** |@@ -33,7 +33,8 @@ Instagram access tokens grant posting authority on behalf of users. They must be**Rules:**- Stored in `accounts.data.accessToken` (jsonb field, not a dedicated column - intentional)- Never selected and returned to the frontend. The `safeAccount()` function strips them before responses-- When updating an account, the token field must survive the jsonb merge - never replace the whole `data` object with a subset+- When updating an account, the token field must survive the jsonb merge - never replace the whole `data` object with a subset. Updates go through `merge_account_data`, one statement in the database, so a concurrent refresh cannot put an old token back+- The browser roles have no access to the `accounts` table, so the token cannot be read through Supabase's public Data API either, not even by its owner- When deleting an account, the token becomes inaccessible because the row is deleted## User Row Isolation@@ -42,7 +43,7 @@ The Worker uses the service role key and is therefore responsible for its own ac**The invariant:** Every user-data query must include `.eq('user_id', userId)` where `userId` comes exclusively from the verified Supabase JWT.-**What this prevents:** User A querying user B's accounts, posts, or settings by guessing an account ID.+**What this prevents:** User A querying user B's accounts, posts, or settings by guessing an account ID. Ids are also UUIDs from `crypto.randomUUID()` (`newRowId()`), so they cannot be guessed from another id.**What to verify when adding new queries:**```ts@@ -58,6 +59,19 @@ const { data } = await supabaseconst { data } = await supabase.from('accounts').select('*').eq('id', accountId);```+## The Database Guards Ownership Too++The query filter is the first guard. The schema adds a second one that holds even if the code has a bug (ADR-038):++- **No browser access.** The migrations turn row level security on with no policies, revoke every grant on the tables from `anon` and `authenticated`, revoke the default privileges for new tables and functions, and let only `service_role` call the merge functions. The anon key gets 401 permission denied from the Data API.+- **Composite foreign keys.** `scheduled_posts` and `tracked_posts` reference `accounts (id, user_id)`, so a row can only name an account that belongs to the same user.+- **Service checks first.** Creating a scheduled post loads the account with `findForUser` and refuses another user's account with 404; changing a tracked item's account does the same for Reddit accounts. The foreign key refuses the same write if a check is ever missed.+- **Value checks.** CHECK constraints refuse an unknown platform, post status or tracked item type.++Before the migrations, three tables had policies that let a signed-in user reach their own rows through the Data API, every table had full grants to the browser roles, and the API never checked a scheduled post's account. A user could read their raw tokens and cookies and write a scheduled post that named another user's Instagram account. All of these are closed; see `docs/architecture/database/SECURITY.md`.++Schema changes only arrive through migrations in `supabase/migrations/`, reviewed like code. A migration that grants anything to `anon` or `authenticated`, or creates a function without revoking execute from them, is a security bug; `backend/tests/database/migrations.test.ts` catches the second.+## OAuth State VerificationThe Instagram OAuth flow uses a self-verifying HMAC state token to prevent CSRF:diff --git a/docs/workflows/DEPLOYMENT.md b/docs/workflows/DEPLOYMENT.mdindex 731721f..17a7414 100644--- a/docs/workflows/DEPLOYMENT.md+++ b/docs/workflows/DEPLOYMENT.md@@ -13,6 +13,7 @@ A pull request merged into `main` -> GitHub Actions deploys automatically. `main| `shared/**` | Backend and frontend workflows | Worker and app (in parallel) || `tsconfig.base.json` | All three workflows | Worker, app and site (in parallel) || Root `package.json` or `package-lock.json` | All three workflows | Worker, app and site (in parallel) |+| `supabase/**` | None | Nothing deployed; the owner applies migrations with `npm run db:push` (see Database Changes) || `docs/`, `scripts/`, root `*.md` | None | Nothing deployed (`publish-scheduled.yml` runs `scripts/publish-scheduled.ts` and `backend/lib/scheduledPublishing.ts` from `main` on its next run) |Monitor deployment status at:@@ -68,28 +69,49 @@ The site needs no environment variables or secrets. Self-hosters can skip this s## Database Changes-Supabase is not migrated by any workflow. A change to the database is SQL the owner runs in the Supabase SQL editor, and it goes in before the code that needs it is merged, because merging deploys the Worker at once.+No workflow migrates Supabase. The schema is versioned in `supabase/migrations/` and the owner applies it with the Supabase CLI from the repository root. A migration goes in before the code that needs it is merged, because merging deploys the Worker at once. `supabase/` changes alone deploy nothing.-### Claim lease and attempts (`scheduled_posts`)--The scheduler fix that adds the claim lease, retries and the container check reads two new columns. Run this in the Supabase SQL editor before merging it:+| Script | Runs | Does |+|---|---|---|+| `npm run db:new <name>` | `supabase migration new` | Creates `supabase/migrations/<timestamp>_<name>.sql` |+| `npm run db:status` | `supabase migration list` | Lists each migration as Local, Remote or both |+| `npm run db:check` | `supabase db push --dry-run` | Shows the migrations a push would apply, without applying them |+| `npm run db:push` | `supabase db push` | Applies the pending migrations and records them in `supabase_migrations.schema_migrations` |-```sql-alter table public.scheduled_posts- add column if not exists claimed_at timestamptz,- add column if not exists attempts integer not null default 0;+### Linking the CLI--- posts stuck before this change have no saved container, so nothing can tell whether they went out-update public.scheduled_posts-set status = 'failed',- data = data || jsonb_build_object('error', 'Publishing was interrupted before Twiligent tracked it. Check Instagram before scheduling this post again.')-where status = 'publishing' and claimed_at is null;+Link once per clone. The CLI asks Supabase for a short-lived login role, so no database password is needed:-create index if not exists scheduled_posts_user_id_idx on public.scheduled_posts (user_id);-create index if not exists scheduled_posts_due_idx on public.scheduled_posts (status, scheduled_at);+```bash+npx supabase login # or set SUPABASE_ACCESS_TOKEN+npx supabase link --project-ref <project-ref> # the id in the project's dashboard URL```-The columns are additive and the old code ignores them, so running the SQL first is safe. The two indexes were listed in `SCHEMA.md` before but did not exist in production. Check afterwards with `select status, count(*) from public.scheduled_posts group by status;`: no post should be `publishing` without a recent `claimed_at`. See `docs/architecture/database/SCHEMA.md`.+The link is stored in `supabase/.temp/`, which git ignores.++### Applying a change++1. Write the migration and its rollback (`docs/features/NEW_DATABASE_TABLE.md`), and run `npm test --workspace backend`.+2. `npm run db:check` and read the list. It must show only the new files.+3. `npm run db:push`.+4. `npm run db:status`: every migration is in both columns.+5. Merge the pull request with the code that needs the change.++A change the old code cannot live with (a dropped column, a renamed function) needs two releases: first the code that works with both shapes, then the migration.++### Rolling Back a Database Change++The CLI has no down migrations. To undo one change on a remote database:++1. Deploy code that does not need the change first, if any does. The merge function rollbacks say so in their comment.+2. Open the matching file in `supabase/rollbacks/` (same name as the migration) and run it in the Supabase SQL editor.+3. Mark the migration as not applied: `npx supabase migration repair --status reverted <version>`, where `<version>` is the 14 digit prefix of the file name.++Roll back in reverse order when several changes are involved. The four baseline migrations have no rollback, because undoing them would drop tables with data.++### Existing instances++An instance set up from the old README SQL, or one that ran the claim lease upgrade SQL from v1.1.1, runs the same `npm run db:push`. The baseline files use `if not exists` throughout, add any missing `created_at`, `claimed_at` and `attempts` columns, and mark posts stuck in `publishing` with no claim as `failed`, so every earlier shape ends at the same schema.## Setting Worker Secrets@@ -218,7 +240,7 @@ For a fresh deployment from this repo:6. Install Node 22.18 or newer, run `npm ci` at the repository root, then `npx wrangler login`7. Set all Worker secrets (see above)8. Set all GitHub Actions secrets (see above)-9. Run the setup SQL from `README.md` in the Supabase SQL editor (tables, the `scheduled_posts` columns and indexes, RLS)+9. Link the Supabase CLI (`npx supabase login`, then `npx supabase link --project-ref <ref>`) and run `npm run db:push` to create the tables, constraints, functions and indexes from `supabase/migrations/`10. `npm run typecheck`, then `cd backend && npx wrangler deploy` (first manual deploy)11. Verify health endpoint12. `npm run build` at the root, then `cd frontend && npx wrangler pages deploy dist --project-name=twiligent`diff --git a/docs/workflows/FEATURE_DEVELOPMENT.md b/docs/workflows/FEATURE_DEVELOPMENT.mdindex 448577e..2863b39 100644--- a/docs/workflows/FEATURE_DEVELOPMENT.md+++ b/docs/workflows/FEATURE_DEVELOPMENT.md@@ -81,7 +81,7 @@ Before creating new patterns, check:## Phase 4: Implement**Step 11 - Implement in this order:**-1. DB schema changes (if any) - see `docs/features/NEW_DATABASE_TABLE.md`+1. DB schema changes (if any): a migration from `npm run db:new <verb>_<object>` and its rollback in `supabase/rollbacks/`, one table or one function per file - 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: `validators/` parsers for new request bodies and query strings4. Backend: `repositories/` additions (new query methods; user-scoped ones end in `ForUser`)@@ -110,8 +110,11 @@ npm run build # the app and the public site must build without errorsnpm test # backend, frontend and site unit tests must passnpm run dev # Worker (8787) and Vite (5173) must both start without errorsnpm run dev:site # the public site, when the change touches site/+npm run db:check # when the change has a migration: lists what db:push would apply```+A change with a migration is applied with `npm run db:push` before its pull request is merged, and `npm run db:status` must then show every migration applied. CI never touches the database; it only runs `backend/tests/database/migrations.test.ts`, which checks the files. See `docs/workflows/DEPLOYMENT.md` (Database Changes).+**Step 14 - Lint**```bashnpm run lint # one ESLint run over backend, frontend, site, tests and scriptsdiff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.mdindex 004207d..757a855 100644--- a/docs/workflows/TESTING.md+++ b/docs/workflows/TESTING.md@@ -33,6 +33,7 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that| `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` |+| `supabase/migrations/*.sql` and `supabase/rollbacks/*.sql` | `backend/tests/database/migrations.test.ts` || `frontend/src/lib/accounts.ts` | `frontend/tests/lib/accounts.test.ts` || `frontend/src/lib/apiErrors.ts` | `frontend/tests/lib/apiErrors.test.ts` || `backend/routes/authHookRoutes.ts` | `backend/tests/routes/authHookRoutes.test.ts` |@@ -48,7 +49,7 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that| `site/src/lib/chart.ts` | `site/tests/lib/chart.test.ts` || `site/src/lib/format.ts` | `site/tests/lib/format.test.ts` |-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.+Backend tests are in `backend/tests/database`, `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`, `rowIds.ts`, the per-platform `*Fixtures.ts` data) and the `*.golden.json` snapshots are in `backend/tests/fixtures/`. `fakeSupabase.ts` also answers `rpc()` for the three merge functions, running the same shallow merge on its in-memory rows (with `p_only_status` and the null-user cron form), and sets `updated_at` on every update and upsert as the database trigger does. `mockRowIds()` in `rowIds.ts` replaces `crypto.randomUUID()` with numbered UUIDs, so the ids in responses and golden snapshots stay the same between runs. 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/**`, 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.@@ -60,10 +61,12 @@ The error contract has its own tests: `tests/middleware/errorHandler.test.ts` (tRate 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 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.+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, and so are rows the code inserts, which the fake tags with their table; untagged seed 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.Scheduled publishing recovery has its own tests. `tests/lib/scheduledPublishing.test.ts` covers the shared rules: the 20 minute lease outlasts the 14 minute limit of both schedulers, what a run does for each container status, which Graph API codes count as temporary, when a failure retries or fails, and when the final message says publishing stopped. `tests/repositories/scheduledPostRepository.test.ts` runs the claim against the fake Supabase client: two schedulers claiming the same listed post (only the first gets it, and the claim counts an attempt), which claims are stale and that a takeover must match the expired claim it saw, that a post being published is not deleted, and that an edit only lands while the post is pending. The `scheduled publisher recovery` block in `tests/services/scheduledPublisher.test.ts` runs the whole publisher: a publish reply lost on the way back is checked on Instagram and marked published, an unreadable container status leaves the post claimed, an expired claim is taken over and found published or publishes its ready container, a claim inside its lease is left alone, a passing failure goes back to `pending` and the third fails the post, a run past its deadline claims nothing, and a post taken over after its last attempt is only checked. On the frontend, `tests/features/publishing/scheduleHelpers.test.ts` covers when the overdue alert counts a retried post (from its last claim) and a stuck claim (after the lease and 30 minutes).+The database migrations have their own test. `tests/database/migrations.test.ts` reads `supabase/migrations/` and `supabase/rollbacks/` and checks that every file is named `<14 digit version>_<lowercase name>.sql` with a unique version, that the baseline files come before every change, that every change has a rollback with the same name and every rollback has its migration, that the baselines use only `if not exists` for tables, indexes and columns so they can run again, that every function a migration creates revokes execute from `public, anon, authenticated`, and that no file uses an em or en dash. It does not run the SQL; CI has no database. The migrations themselves were checked once on a local Postgres before the first push (ADR-038).+The Send Email hook has its own tests: `tests/lib/webhookSignature.test.ts` (valid, tampered, wrong-key, multi-signature and replayed requests), `tests/validators/authHookValidators.test.ts`, `tests/services/email/authEmails.test.ts` (the email for each action, the verify links, HTML escaping and the two Secure Email Change emails), `tests/repositories/emailQuotaRepository.test.ts` (daily and per-address caps, hashed keys, Redis failures), `tests/services/authEmailService.test.ts` (Resend requests, idempotency keys, the caps and Resend's own quota errors, skipped notices) and `tests/routes/authHookRoutes.test.ts` (the hook error shape, and the route answering unsigned calls with 401 in the full app). `tests/fixtures/authHook.ts` signs requests the way Supabase Auth does. The Lua claim script cannot run in Node; the repository test runs the same rules in memory. On the frontend, `tests/lib/authErrors.test.ts` covers when the sign-in page shows the daily cap warning and whether it offers Google, `tests/lib/emailAddress.test.ts` when an address looks complete enough to enable the Continue arrow, and `tests/lib/googleIdentity.test.ts` the label drawn on the Google button for each text option.The testing workflow documented here describes what should run before shipping any change.@@ -193,8 +196,15 @@ Open the app in a browser. For each changed area, test:- [ ] Status polling shows progress for video- [ ] Publish succeeds -> media ID shown+**Database (if a migration changed):**+- [ ] `npm run db:check` lists only the new migrations, and `npm run db:push` applies them without an error+- [ ] `npm run db:status` shows every migration in both the Local and Remote columns+- [ ] The anon key gets 401 permission denied on every table and on the merge functions: `curl -i "<SUPABASE_URL>/rest/v1/accounts?select=id" -H "apikey: <anon key>"` (repeat for `settings`, `scheduled_posts`, `tracked_posts`) and `curl -i -X POST "<SUPABASE_URL>/rest/v1/rpc/merge_account_data" -H "apikey: <anon key>" -H "Content-Type: application/json" -d '{}'`+- [ ] The app still lists accounts, scheduled posts and tracked items, and the row counts in the Table Editor are unchanged+**Scheduling (if changed):**- [ ] Create a scheduled post -> appears in queue+- [ ] Create a scheduled post with another user's account id (`curl` with your token) -> 404 `Instagram account not found`- [ ] Manual trigger processes due posts correctly- [ ] Failed posts show error in UI- [ ] A post interrupted mid-publish (status `publishing`, `claimed_at` set more than 20 minutes ago in the SQL editor) is taken over by the next run: it ends `published` if its saved container already went out, without a second post on Instagramdiff --git a/site/content/docs/reference/scheduling.mdx b/site/content/docs/reference/scheduling.mdxindex 9ccc38d..126ac71 100644--- a/site/content/docs/reference/scheduling.mdx+++ b/site/content/docs/reference/scheduling.mdx@@ -46,7 +46,7 @@ Timeouts, an unreachable Instagram, database errors and Instagram's temporary er- The Worker was never deployed, or its cron triggers were removed. Check **Triggers** on the Worker in the Cloudflare dashboard.- `SUPABASE_SERVICE_KEY` or `SUPABASE_URL` is wrong on the Worker.-- The database is missing the `claimed_at` and `attempts` columns. Run the upgrade SQL in [Supabase](/docs/self-host/supabase#upgrading-an-existing-instance).+- The database has not had the latest migrations applied. Run `npm run db:push` as described in [Supabase](/docs/self-host/supabase#upgrading-an-existing-instance).- The connected Instagram account's access was removed. Reconnect it.Twiligent warns members when a post is more than 30 minutes late and not yet published, and tells them to contact the administrator. A retried post counts from its last attempt, and a post counts as stuck in `publishing` 50 minutes after its claim: the 20 minute claim plus 30 minutes in which a run should have taken it over.diff --git a/site/content/docs/reference/security.mdx b/site/content/docs/reference/security.mdxindex dffb903..442671b 100644--- a/site/content/docs/reference/security.mdx+++ b/site/content/docs/reference/security.mdx@@ -8,16 +8,16 @@ export const meta = { title: 'Security', description: 'How member data is kept a## How isolation works-The browser signs in with Supabase and sends its token with every request. The Worker verifies the token and takes the member's ID from it, never from anything the browser sends. Every database query is limited to that ID. Responses are stripped of tokens and cookies before they leave the Worker.+The browser signs in with Supabase and sends its token with every request. The Worker verifies the token and takes the member's ID from it, never from anything the browser sends. Every database query is limited to that ID. A scheduled post or tracked item can only use one of the member's own accounts: the Worker checks it, and the database refuses it too. Responses are stripped of tokens and cookies before they leave the Worker.## Administrator responsibilities| Setting | Why it matters || --- | --- |-| Row level security on all four tables | The publishable key ships in the website. With security off, anyone could use it to read every table directly. |+| All migrations applied | The publishable key ships in the website. The migrations turn row level security on and remove the browser's access to every table, so nobody can use that key to read or change the tables directly. || Secret key only in server secrets | It bypasses all database rules. Keep it in Worker secrets and GitHub Actions secrets only. || Signups | Supabase allows anyone with the address to sign up. Turn signups off for a private instance. || backend/.dev.vars never committed | It holds every secret for local development. || Instagram testers | In development mode, only people you add can connect Instagram. |-The SQL to turn on row level security is on the [Supabase](/docs/self-host/supabase) page.+Applying the migrations is on the [Supabase](/docs/self-host/supabase) page.diff --git a/site/content/docs/self-host/checklist.mdx b/site/content/docs/self-host/checklist.mdxindex 2912b9e..b831151 100644--- a/site/content/docs/self-host/checklist.mdx+++ b/site/content/docs/self-host/checklist.mdx@@ -8,7 +8,7 @@ export const meta = { title: 'Launch checklist', description: 'Confirm everythin| YouTube works | Add any public channel in Accounts. || Instagram works | Connect your own tester account in Accounts. || Publishing works | Schedule a post 5 minutes ahead. It shows Published within 20 minutes. |-| Data is private | Row level security is on for all four tables (Supabase, Table Editor shows no "RLS disabled" warning). |+| Data is private | `npm run db:status` shows every migration applied, and the Table Editor shows no "RLS disabled" warning on the four tables. || Signups match your plan | Turn off new signups in Supabase if the instance is private. || Members can reach you | VITE_ADMIN_EMAIL is your address. |diff --git a/site/content/docs/self-host/index.mdx b/site/content/docs/self-host/index.mdxindex 02b86d2..f80dacb 100644--- a/site/content/docs/self-host/index.mdx+++ b/site/content/docs/self-host/index.mdx@@ -29,7 +29,7 @@ Reddit needs no key. Each member pastes their own Reddit session cookie when the## Order of setup-1. [Supabase](/docs/self-host/supabase): create the project, the tables and turn on row level security.+1. [Supabase](/docs/self-host/supabase): create the project, then create the tables with `npm run db:push`.2. [YouTube API key](/docs/self-host/youtube), [Instagram app](/docs/self-host/instagram), [Cloudinary](/docs/self-host/cloudinary) and optionally [Upstash Redis](/docs/self-host/redis), in any order.3. [Deploy the backend](/docs/self-host/deploy-backend) and give it every secret.4. [Deploy the frontend](/docs/self-host/deploy-frontend).diff --git a/site/content/docs/self-host/supabase.mdx b/site/content/docs/self-host/supabase.mdxindex 50a50c7..bbfee3c 100644--- a/site/content/docs/self-host/supabase.mdx+++ b/site/content/docs/self-host/supabase.mdx@@ -8,57 +8,27 @@ Sign in at [supabase.com/dashboard](https://supabase.com/dashboard) and choose *</Step><Step title="Create the tables">-Open **SQL Editor**, choose **New query**, paste the SQL below and choose **Run**. It creates the four tables Twiligent uses and turns on row level security for each.--```sql-create table accounts (- id text primary key,- user_id uuid not null references auth.users(id) on delete cascade,- platform text not null,- data jsonb not null-);-create index accounts_user_id_idx on accounts(user_id);--create table settings (- user_id uuid not null references auth.users(id) on delete cascade,- key text not null,- value jsonb,- primary key (user_id, key)-);--create table scheduled_posts (- id text primary key,- user_id uuid not null references auth.users(id) on delete cascade,- account_id text not null references accounts(id) on delete cascade,- status text not null default 'pending',- scheduled_at timestamptz not null,- claimed_at timestamptz,- attempts integer not null default 0,- data jsonb-);-create index scheduled_posts_user_id_idx on scheduled_posts(user_id);-create index scheduled_posts_due_idx on scheduled_posts(status, scheduled_at);--create table tracked_posts (- id text primary key,- user_id uuid not null references auth.users(id) on delete cascade,- account_id text references accounts(id) on delete set null,- url text not null,- label text not null default '',- category text not null default '',- content_type text not null default 'reddit',- created_at timestamptz not null default now(),- updated_at timestamptz not null default now(),- data jsonb-);-create index tracked_posts_user_id_idx on tracked_posts(user_id);--alter table accounts enable row level security;-alter table settings enable row level security;-alter table scheduled_posts enable row level security;-alter table tracked_posts enable row level security;+Twiligent keeps its database layout as migration files in `supabase/migrations/`, and the Supabase CLI applies them. The CLI came with `npm install` in the cloned `twiligent` folder (see [What you need on your computer](/docs/self-host#what-you-need-on-your-computer)). Run these from that folder:++```bash+npx supabase login+npx supabase link --project-ref <project-id>+npm run db:check+npm run db:push```+- `npx supabase login` opens the browser to sign in to Supabase. On a machine without a browser, set `SUPABASE_ACCESS_TOKEN` to an access token from **Account**, **Access Tokens** instead.+- The project ID is in **Project Settings**, **General**. It is also the part before `.supabase.co` in the project URL. No database password is needed.+- `npm run db:check` lists the migrations it will apply, and `npm run db:push` applies them.++This creates the four tables Twiligent uses and closes them to the browser. It also adds the checks that keep stored values valid, the keys that tie each post to its owner's accounts, and the indexes the app's lists use. `npm run db:status` shows each migration and whether it is applied.++<Callout type="note" title="Without the CLI">++Open **SQL Editor**, then run each file from `supabase/migrations/` in file name order, one at a time. Apply later files the same way when you update Twiligent, because the CLI does not know about migrations run in the editor.++</Callout>+</Step><Step title="Configure sign-in">@@ -93,39 +63,16 @@ The secret key can read and change every row in the database. It belongs only in</Step></Steps>-## Already have the tables?--If you created the tables from an older README, make sure `tracked_posts` exists and has the `content_type` column, and that row level security is on. This is safe to run more than once:--```sql-alter table tracked_posts add column if not exists content_type text not null default 'reddit';-alter table accounts enable row level security;-alter table settings enable row level security;-alter table scheduled_posts enable row level security;-alter table tracked_posts enable row level security;-```-## Upgrading an existing instance-Twiligent's schedulers record when a run claimed a post (`claimed_at`) and how many times it tried (`attempts`), so a run that stops halfway is taken over and a passing problem is retried. If your `scheduled_posts` table has no `claimed_at` column, run this in the **SQL Editor** before you deploy the new version of the Worker. It is safe to run more than once:+If you set up the tables with SQL from an older version of these docs or the README, including the `claimed_at` and `attempts` upgrade, link the CLI as above and run `npm run db:check`, then `npm run db:push`, before you deploy the new version of the Worker.-```sql-alter table public.scheduled_posts- add column if not exists claimed_at timestamptz,- add column if not exists attempts integer not null default 0;+The first four migrations describe the tables as they were before migrations existed. They are safe to run on tables that already exist, and they bring every earlier setup to the same starting point: they add any missing columns and mark posts stuck in Publishing with no claim as failed, with a note to check Instagram first, because nothing recorded whether they went out. The migrations after them change the tables in small steps.--- posts stuck before this change have no saved container, so nothing can tell whether they went out-update public.scheduled_posts-set status = 'failed',- data = data || jsonb_build_object('error', 'Publishing was interrupted before Twiligent tracked it. Check Instagram before scheduling this post again.')-where status = 'publishing' and claimed_at is null;--create index if not exists scheduled_posts_user_id_idx on public.scheduled_posts (user_id);-create index if not exists scheduled_posts_due_idx on public.scheduled_posts (status, scheduled_at);-```--Posts that were stuck in Publishing are marked failed with a note to check Instagram first, because nothing recorded whether they went out.+If a check stops the push because of an old row, the error names the rule. Fix that row in the **Table Editor** and run `npm run db:push` again.### Why row level security with no policies-The backend uses the secret key, which bypasses row level security, and limits every query to the signed-in user itself. Turning security on with no policies means the public publishable key, which ships in the frontend, cannot read or change any table directly. Without it, anyone holding that public key could read other members' data.+The backend uses the secret key, which bypasses row level security, and limits every query to the signed-in user itself. The browser never reads the tables; it only signs in with Supabase. So the migrations turn security on with no policies and also remove every permission the publishable key's roles had on the tables and on Twiligent's database functions. The public publishable key, which ships in the frontend, cannot read or change any table directly, and neither can a signed-in member's own token.++A policy that let members reach their own rows would still expose their raw Instagram tokens and Reddit cookies to the browser, and would let them write rows the backend refuses, such as a post on another member's account. Older setups had such policies; the migrations remove them.