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: document comment-to-DM automation, its setup and limits
spacesdrive74ca9cc9013e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1c33abd..66dcb9b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,20 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).## [Unreleased]+### Added++- Automations: a private reply on Instagram to anyone who comments a keyword on your posts or reels, from rules with keywords, a reply and a link, aimed at every post or chosen ones, with a preview and a test that sends nothing (#87, #90)+- A signed Instagram comments webhook that stores every comment before answering Meta, sends matched replies within seconds and retries, waits out limits and recovers stopped runs without sending a reply twice (#89, ADR-040)+- Reply limits per hour for the instance, each member, each Instagram account and each rule, and per day for each person, with a cooldown when Instagram limits the account; `AUTOMATION_PAUSED` holds every reply (#89)+- The Automations page shows each account's state with pause and resume, counts for the period, and the activity of every comment with its status and a retry (#90)+- New tables `automation_accounts`, `automation_rules`, `automation_comments`, `automation_attempts` and `audit_events`, and their functions; existing instances run `npm run db:push` before deploying (#88)+- An audit record of connecting, reconnecting and removing accounts and of every automation change, kept a year (#89)++### Changed++- Connecting an Instagram account that is already connected renews its token instead of answering that it is already added, so a revoked token can be fixed without removing the account (#89)+- The Worker's publishing cron runs every 5 minutes instead of 15; posts still publish on the quarter hour, and the other runs send waiting comment replies (#89)+---## [1.2.0] - 2026-10-16diff --git a/DECISIONS.md b/DECISIONS.mdindex 3d0705d..9cd4bae 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -849,3 +849,32 @@ New row ids come from `crypto.randomUUID()` (`newRowId()` in `backend/lib/ids.ts**Trade-offs:**- A skipped platform package now costs one extra `npm ci` (about 20 seconds) instead of a failed run.- The audit is not clean while the shadcn chain waits for upstream; check it again when `braces` or `fast-glob` releases a fix.++## ADR-040: Comment-to-DM automation with the database as the queue, on one shared cron trigger++**Date:** 2026-10-16+**Status:** Accepted++**Decision:** Instagram comments arrive through Meta's `comments` webhook at a public, signed route on the existing Worker. Each comment is stored in `automation_comments` before the webhook answers, and a matched comment's row is the job that sends its private reply: the Worker sends it after the response with `ctx.waitUntil()`, and the existing five minute cron sweeps what is left. Claims, limits and outcomes are Postgres functions (`claim_automation_comments`, `reserve_automation_send`, `finish_automation_send`). The Worker's two cron triggers stay two: `*/15 * * * *` becomes `*/5 * * * *`, publishing keeps its quarter-hour runs and the other runs sweep the reply queue. Connecting an Instagram account again renews its token instead of answering "already added", and sensitive changes are recorded in a new `audit_events` table.++**Context:** The owner asked for keyword-triggered private replies with production-grade reliability: no lost or duplicated replies, bounded retries, limits enforced across Worker instances, per-account isolation, and nothing left uncertain reported as delivered (#87). The Instagram account connection already used Instagram Login with `instagram_business_manage_comments` and `instagram_business_manage_messages`, so no new OAuth flow was needed. Meta's documentation (checked 2026-10-16) allows one private reply per comment within 7 days, 750 private replies an hour per account for posts and reels, text up to 1,000 bytes, and retries unacknowledged webhooks for 36 hours. The Cloudflare account runs on the Workers Free plan (10 ms CPU and 50 subrequests per invocation, `waitUntil` up to 30 seconds after a response) and its five cron triggers are all in use, three by other projects that the owner chose to keep.++**Why the database and not Cloudflare Queues:** Queues has been on the free plan since February 2026 (10,000 operations a day, 24 hour retention). It was not chosen because the comment row is needed anyway, for deduplication, status and history, so a queue message would only repeat it; a queue still needs a database sweep for comments whose publish to the queue failed, so it would not remove the sweep; the free plan's 24 hour retention is shorter than the 7 day reply window; per-account fairness and the hourly limits need the database regardless; and every self-hoster would have to create and bind two queues. With the row as the job, acceptance is one insert, and there is no window in which an acknowledged comment exists only in a queue.++**Why limits live in Postgres:** Redis is optional in this project and its fallback is per-isolate memory, which is not shared between Worker instances. One transaction under a transaction-scoped advisory lock counts the last hour's attempts per instance, user, account and rule and the last day's replies per person, so two Workers cannot both take the last slot. The serialisation is acceptable at the volumes one account can send (Instagram stops at 750 an hour).++**Ambiguous sends:** a send whose answer is lost is marked `needs_review` and never resent automatically; a person retries after checking Instagram, and Instagram refuses a second private reply to one comment (10900), so a retry cannot message the person twice. A send the runtime refused at the subrequest cap is known not to have left and waits for the next run.++**Alternatives considered:**+- Cloudflare Queues for dispatch, as above.+- A separate every-minute cron trigger for the sweep. The account has no free slot, and freeing one meant removing another project's job.+- Sweeping inside the existing quarter-hour runs. Publishing and replies would share one run's 50 subrequests, and the fallback wait would be 15 minutes.+- Matching at send time instead of at intake. Unmatched comments would have to be stored with their text; matching at intake keeps only matched comments' words.+- Processing every comment inline in the webhook before answering. Meta wants a prompt answer, and a slow Instagram call would hold the acknowledgement.++**Trade-offs:**+- The quarter-hour runs now also decide whether to sweep, so publishing and the sweep share a trigger; `cronPlan()` and its test keep the split explicit.+- The fallback for a reply that misses the immediate send is up to 5 minutes (10 around a run that published), not seconds.+- `expires_at` is measured from Meta's notification time, which can be later than the comment on a redelivery; a late reply is refused by Instagram and recorded as failed.+- Reconnecting renews the token in place, so the "already connected" refusal is gone; the audit table records each reconnect.+- A burst over `AUTOMATION_BATCH_SIZE` in one notification waits for the sweep; the cap of 15 follows the free plan's subrequests and can be raised in the code on Workers Paid.diff --git a/README.md b/README.mdindex 78e0d40..e42dc9a 100644--- a/README.md+++ b/README.md@@ -65,6 +65,7 @@ The project's own public site and documentation are at [twiligent.ujjwal.fyi](ht| **Unified overview** | Cross-platform totals, audience comparison chart, audience share pie, leaderboards || **Content explorers** | Sortable and filterable grids for all YouTube Videos, all YouTube Shorts, and all Instagram Reels and posts || **Scheduled publishing** | Schedule Instagram photos, Reels, and Stories; a Cloudflare Worker cron publishes them every 15 minutes automatically |+| **Comment-to-DM automation** | When someone comments a keyword such as GUIDE on your Instagram posts or Reels, Twiligent sends them your private reply and link within seconds, through Meta's comments webhook and official private replies; per-account, per-rule and per-person limits, retries and an activity log || **Bulk upload** | Upload multiple files at once, assign captions individually or apply a shared caption, schedule them with configurable intervals || **Cloudinary CDN** | Upload media directly from the dashboard; Instagram requires public URLs before publishing || **Token auto-refresh** | Instagram long-lived tokens renew automatically every 24 hours via a daily Worker cron so analytics never break |@@ -309,8 +310,12 @@ npx wrangler secret put SEND_EMAIL_HOOK_SECRET # optional; email verificatinpx wrangler secret put RESEND_API_KEY # optionalnpx wrangler secret put EMAIL_FROM # optionalnpx wrangler secret put EMAIL_DAILY_LIMIT # optional; defaults to 100+npx wrangler secret put INSTAGRAM_WEBHOOK_VERIFY_TOKEN # optional; comment-to-DM automation+npx wrangler secret put META_APP_SECRET # optional; a second key for webhook signatures```+Comment-to-DM automation needs `INSTAGRAM_WEBHOOK_VERIFY_TOKEN`, the webhook added in the Meta dashboard (`https://<worker>/api/webhooks/instagram`, field `comments`) and, for comments from people without a role on your app, a Live app with Advanced Access. Optional `AUTOMATION_*` settings change the reply limits or pause every reply. Setup steps are in the [docs](https://twiligent.ujjwal.fyi/docs/self-host/comment-automation).+The four email secrets turn on the 6-digit codes that sign people in and confirm password sign-ups, sent free through Resend (100 a day). Supabase Auth hands each email to the Worker through its Send Email hook (`POST /api/auth/email-hook`); every code sign-in is one email. Past the daily limit, the sign-in page pauses email codes and points people to Google or their password. Setup steps are in the [docs](https://twiligent.ujjwal.fyi/docs/self-host/email-codes).### Getting API credentials@@ -401,10 +406,10 @@ flowchart TD**Cron lifecycle:**-1. The Cloudflare scheduler fires the Worker on a `*/15 * * * *` cron+1. The Cloudflare scheduler fires the Worker every 5 minutes (`*/5 * * * *`); the runs on the quarter hour publish, the others send waiting comment replies2. The Worker queries `scheduled_posts` for rows with `status = 'pending'` and `scheduled_at <= now()`, and for `publishing` rows whose claim is older than 20 minutes3. Each post is claimed (`publishing`, with `claimed_at` and `attempts`), published to Instagram, then set to `published`, back to `pending` for a retry, or `failed`-4. A separate `0 0 * * *` cron refreshes expiring Instagram access tokens across all users+4. A separate `0 0 * * *` cron refreshes expiring Instagram access tokens across all users and deletes comment automation records past their retention---@@ -424,20 +429,21 @@ twiligent/│ ├── app.ts # createApp(): the ordered middleware pipeline and route groups│ ├── server.ts # Worker export (fetch + scheduled)│ ├── container.ts # Composition root: builds repositories and services per request-│ ├── middleware/ # cors, requestContext, securityHeaders, clients, rateLimit, auth, validate, errorHandler+│ ├── middleware/ # cors, requestContext, securityHeaders, clients, rateLimit, auth, authHook, metaWebhook, validate, errorHandler│ ├── routes/ # One route table per feature (<feature>Routes.ts) and index.ts (public and protected)│ ├── controllers/ # HTTP only: read input, call one service method, build the response│ ├── validators/ # Request body and query parsers│ ├── services/│ │ ├── *Service.ts # Feature services: business rules, no Hono types│ │ ├── scheduledPublisher.ts # Publishes due scheduled posts (cron and manual trigger)+│ │ ├── automationProcessor.ts # Sends comment-to-DM replies within limits (webhook, retry and 5 minute cron)│ │ ├── youtube/ # YouTube Data API v3 client and analytics│ │ ├── instagram/ # Instagram Graph API client, OAuth, publishing and analytics│ │ └── reddit/ # Reddit public JSON API client and analytics│ ├── repositories/ # All Supabase queries and the Redis analytics cache│ ├── database/ # Supabase and Upstash Redis client factories│ ├── jobs/-│ │ └── scheduled.ts # Cron entry point: publish due posts, refresh Instagram tokens+│ │ └── scheduled.ts # Cron entry point: due posts and the reply sweep every 5 minutes, token refresh and retention daily│ ├── lib/│ │ ├── errors.ts # Typed errors; the error handler maps each code to a status│ │ ├── ids.ts # newRowId(): random UUIDs for new rows@@ -447,6 +453,9 @@ twiligent/│ │ ├── oauthState.ts # HMAC-signed Instagram OAuth state│ │ ├── analyticsMath.ts # Shared analytics formulas│ │ ├── scheduledPublishing.ts # Lease, retry and container rules shared with the GitHub Actions script+│ │ ├── automationMatching.ts # Keyword matching for comment automation rules+│ │ ├── automationDelivery.ts # What each Instagram answer means for a reply: retry, wait, stop or review+│ │ ├── metaWebhookSignature.ts # X-Hub-Signature-256 check for Meta's webhooks│ │ └── rateLimit/ # Rate limit rules, algorithms and Lua scripts│ ├── types/│ │ ├── env.ts # Env: Worker secrets and bindings@@ -477,6 +486,7 @@ twiligent/│ │ │ └── reels/ # Instagram content explorer│ │ ├── accounts/ # Account management UI│ │ ├── publishing/ # Single and bulk upload with scheduler+│ │ ├── automations/ # Comment-to-DM rules, account controls and reply activity│ │ └── settings/ # Theme, server status, setup guides│ ├── context/│ │ └── AppContext.tsx # Global accounts and loading statediff --git a/backend/.env.example b/backend/.env.exampleindex d95f7d1..5b0488e 100644--- a/backend/.env.example+++ b/backend/.env.example@@ -27,6 +27,19 @@ CLOUDINARY_UPLOAD_PRESET=your-upload-presetINSTAGRAM_APP_ID=your-instagram-app-idINSTAGRAM_APP_SECRET=your-instagram-app-secret+# ── Instagram comment automation ──────────────────────────────────────────────+# The Verify Token you type into the Meta dashboard's webhook settings (any long random string).+# Webhooks are signed with INSTAGRAM_APP_SECRET; set META_APP_SECRET too if your app signs with the Meta app secret.+INSTAGRAM_WEBHOOK_VERIFY_TOKEN=a-long-random-string+# META_APP_SECRET=your-meta-app-secret+# Optional limits and controls; each falls back to its default when unset.+# AUTOMATION_PAUSED=true+# AUTOMATION_ACCOUNT_HOURLY_LIMIT=200+# AUTOMATION_USER_HOURLY_LIMIT=500+# AUTOMATION_GLOBAL_HOURLY_LIMIT=1000+# AUTOMATION_RECIPIENT_DAILY_LIMIT=3+# AUTOMATION_BATCH_SIZE=10+# ── URLs ──────────────────────────────────────────────────────────────────────# Used for the Instagram OAuth redirect and as the allowed CORS origin. Update these for production.BACKEND_URL=http://localhost:8787diff --git a/backend/tests/middleware/rateLimit.test.ts b/backend/tests/middleware/rateLimit.test.tsindex f63388a..dbf38fa 100644--- a/backend/tests/middleware/rateLimit.test.ts+++ b/backend/tests/middleware/rateLimit.test.ts@@ -133,6 +133,8 @@ test('quota and publish routes match the endpoints that spend platform API callsassert.equal(quota('PUT', '/api/tracked-content/abc'), false);assert.equal(quota('POST', '/api/tracked-content/abc/refresh'), true);assert.equal(quota('GET', '/api/process-scheduled'), true);+ assert.equal(quota('POST', '/api/automations/accounts/ig1/subscribe'), true);+ assert.equal(quota('PUT', '/api/automations/accounts/ig1'), false);assert.equal(quota('GET', '/api/accounts/abc123/analytics'), false);const publish = (method: string, path: string) => matchesRoute(PUBLISH_ROUTES, method, path);diff --git a/claude.md b/claude.mdindex ff0478b..057e3b7 100644--- a/claude.md+++ b/claude.md@@ -5,8 +5,8 @@Twiligent is a self-hosted social media analytics and publishing dashboard for creators and teams managing multiple YouTube channels, Instagram accounts and Reddit profiles. It is a private deployment product - the owner runs their own instance with their own API credentials. There is no SaaS model, no multi-tenancy abstraction, and no billing system.- Primary users: Small creator teams, agencies, individual power users-- Primary value: Unified analytics and scheduled Instagram publishing across multiple accounts-- Current platforms: YouTube (analytics only), Instagram (analytics and publishing), Reddit (analytics only)+- Primary value: Unified analytics, scheduled Instagram publishing, and automatic private replies to Instagram comments across multiple accounts+- Current platforms: YouTube (analytics only), Instagram (analytics, publishing and comment-to-DM automation), Reddit (analytics only)- Public site: https://twiligent.ujjwal.fyi is the project's own marketing site and documentation (the `site/` workspace); the app runs at https://app.twiligent.ujjwal.fyi. Self-hosters run only the app and the Worker; the site is not needed to run Twiligent- GitHub repository: https://github.com/spacesdrive/twiligent- Goals and priorities: `ROADMAP.md`@@ -118,6 +118,7 @@ docs/PUBLISHING.md Cloudinary to IG container to publish pipelineANALYTICS.md YouTube and Instagram analytics fetch and computeSCHEDULING.md Scheduled post lifecycle, dual-scheduler design+ AUTOMATION.md Comment webhook, keyword rules, reply queue, limits and failure handlingguidelines/CODE_STYLE.md How code reads: the shapes to copy per layer, comments, naming, messages, tests, pre-commit checklistTYPESCRIPT.md Compiler settings, typing rules, where types live, code style, comments policy@@ -306,6 +307,7 @@ This is not optional for features that touch new UI patterns, new APIs, or new i- Instagram `accessToken` is always stripped by `safeAccount()` before any response- All user-scoped queries always append `.eq('user_id', userId)` where `userId` comes from a verified JWT, never from user input; only repository methods named `...ForUser` serve requests, and the unscoped ones are for cron jobs- `backend/.dev.vars` must never be committed+- Public webhooks (`/api/auth/email-hook`, `/api/webhooks/instagram`) act only after their signature is verified, and a private reply whose outcome is unknown is never sent again without a person's decision**Keep each layer to its job.** Read `docs/architecture/backend/REQUEST_PIPELINE.md`. Middleware handles cross-cutting work in the order set in `backend/app.ts`. A route table only maps a path to middleware and a controller. A controller reads validated input (`backend/validators/`) and the user id, calls one service method and builds the response; it never queries the database or catches errors to format them. A service holds the rules, receives repositories and a `RequestContext`, never imports `hono`, and throws the typed errors in `lib/errors.ts`. Every Supabase query and every cache read or write lives in a repository in `backend/repositories/`, one method per query.diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.mdindex 2ff7fae..9786d88 100644--- a/docs/architecture/OVERVIEW.md+++ b/docs/architecture/OVERVIEW.md@@ -25,14 +25,16 @@│ ├── Middleware: CORS, request id, security headers, clients, ││ │ per-IP rate limit ││ ├── Public: GET /api/health, GET /api/auth/instagram/callback, │-│ │ POST /api/auth/email-hook (signed by Supabase Auth) │+│ │ POST /api/auth/email-hook (signed by Supabase Auth), │+│ │ GET/POST /api/webhooks/instagram (signed by Meta) ││ ├── Protected (/api/*): requireAuth -> rate limits ││ │ -> route table -> controller -> service -> repository ││ └── Errors: errorHandler -> { success, code, message, ... } ││ ││ Cron handlers (wrangler.toml triggers, jobs/scheduled.ts): │-│ ├── */15 * * * * -> scheduledPublisher.publishDue() │-│ └── 0 0 * * * -> tokenRefresh.refreshExpiringInstagram... │+│ ├── */5 * * * * -> on :00 :15 :30 :45 publishDue(), then │+│ │ automationProcessor.run() (reply sweep) │+│ └── 0 0 * * * -> token refresh, retention purge │└──────┬──────────┬──────────────┬────────────────────────────────┘│ │ │▼ ▼ ▼@@ -49,6 +51,10 @@│ posts │ │ videos: ││ tracked_ │ │ ig: ││ posts │ │ reddit: │+│ automa- │ │ │+│ tion_* │ │ │+│ audit_ │ │ │+│ events │ │ ││ │ │ ││ auth: │ │ ││ users │ │ optional│@@ -102,9 +108,14 @@ Cloudflare Worker edge node (nearest to user)```Cloudflare scheduler fires cron trigger-> Worker.scheduled(event, env, ctx)- -> ctx.waitUntil(runScheduledJob(event.cron, env)) [jobs/scheduled.ts]+ -> ctx.waitUntil(runScheduledJob(event.cron, env, event.scheduledTime)) [jobs/scheduled.ts]-> createServices(service-role Supabase, Redis, config, cron context)- -> if cron === '*/15 * * * *':+ -> cronPlan(cron, scheduledTime)+ -> '*/5 * * * *' at minutes 0, 15, 30, 45: publish, then sweep 3 replies if nothing was due+ -> '*/5 * * * *' at the other minutes: automationProcessor.run()+ -> claim due reply jobs (at most half the batch per account), reserve within limits,+ send the private reply, record the outcome [see data-flows/AUTOMATION.md]+ -> publishing:scheduledPublisher.publishDue()-> posts.listDue(), posts.listStale(cutoff) [no userId filter - scans all users;stale = publishing, claim older than 20 minutes]@@ -114,13 +125,28 @@ Cloudflare scheduler fires cron triggerthen wait for and publish the container-> posts.updateById(id, { status: 'published' })or back to 'pending' for a temporary failure (up to 3 attempts), or 'failed'- -> if cron === '0 0 * * *':+ -> '0 0 * * *':tokenRefresh.refreshExpiringInstagramTokens()-> accounts.listByPlatform('instagram') [all users, filtered in SQL]-> for each expiring token: refreshLongLivedToken()-> accounts.updateById(id, { accessToken, tokenExpiresAt })+ retention.purge()+ -> delete automation comments older than 90 days, audit events older than a year```+## Webhook Lifecycle (Instagram Comments)++```+Meta -> POST /api/webhooks/instagram+ -> CORS, request id, security headers, clients, per-IP rate limit (no requireAuth)+ -> verifyMetaWebhook: 1 MB limit, X-Hub-Signature-256 over the raw body [401 when wrong]+ -> automationWebhook.ingest(): rules for the Instagram account, match, store every comment once+ -> 200 { success: true } [5xx when storing fails; Meta retries]+ -> ctx.waitUntil(automationProcessor.run({ ids })) the new matched comments, after the response+```++The full flow, limits and failure handling are in `docs/architecture/data-flows/AUTOMATION.md`.+## Data Storage Strategy| Data type | Where stored | Why |@@ -129,6 +155,8 @@ Cloudflare scheduler fires cron trigger| YouTube/Instagram accounts | `accounts` table, `data` jsonb | Flexible schema across platforms || User settings (GitHub repository) | `settings` table, `value` jsonb | Generic key-value per user || Scheduled posts | `scheduled_posts` table | Queryable by status + scheduled_at |+| Comment automation rules, received comments, reply attempts, account controls | `automation_rules`, `automation_comments`, `automation_attempts`, `automation_accounts` tables | The comment rows are also the reply queue, so dedupe, claims and limits are enforced in one database |+| Audit events | `audit_events` table | Who connected, removed or changed what; kept a year || Video/media analytics | Upstash Redis (`videos:` / `ig:` keys) | Avoids repeated heavy API calls || Auth email counts | Upstash Redis (`email:day:` / `email:to:` keys, addresses hashed) | Caps verification emails at the provider's free daily quota || Media files (for publishing) | Cloudinary CDN | Instagram requires public URL |diff --git a/docs/architecture/backend/CRON.md b/docs/architecture/backend/CRON.mdindex e3eb558..011fe77 100644--- a/docs/architecture/backend/CRON.md+++ b/docs/architecture/backend/CRON.md@@ -4,27 +4,35 @@```toml[triggers]-crons = ["*/15 * * * *", "0 0 * * *"]+crons = ["*/5 * * * *", "0 0 * * *"]```-Both cron triggers invoke the `scheduled` export from `backend/server.ts`, which hands the cron expression to `runScheduledJob(cron, env)` in `backend/jobs/scheduled.ts`. The expressions are constants there (`PUBLISH_DUE_POSTS_CRON`, `REFRESH_TOKENS_CRON`) and must match `wrangler.toml` character for character.+Both cron triggers invoke the `scheduled` export from `backend/server.ts`, which hands the cron expression and the run's scheduled time to `runScheduledJob(cron, env, scheduledTime)` in `backend/jobs/scheduled.ts`. The expressions are constants there (`EVERY_FIVE_MINUTES_CRON`, `DAILY_CRON`) and must match `wrangler.toml` character for character; `backend/tests/jobs/scheduled.test.ts` checks both.++The Cloudflare account has used all five cron triggers the Workers Free plan allows (two here, three on other Workers), so the Worker cannot add a trigger. One five minute trigger carries two jobs instead: `cronPlan(cron, scheduledTime)` sends the runs at minutes 0, 15, 30 and 45 to scheduled publishing, as before, and every other run to the comment reply queue. Each run is its own invocation with its own 50 subrequests, so the jobs never share a budget except on the quarter-hour runs (see ADR-040).## The Cron Entry Point (`backend/jobs/scheduled.ts`)A cron run uses the same services as the API, built from the Worker env instead of a request:```ts-export async function runScheduledJob(cron: string, env: Env): Promise<void> {- const context = cronContext(cron);- const services = createServices({ supabase: getSupabase(env), redis: getRedis(env) }, readConfig(env), context);+export function cronPlan(cron: string, scheduledTime: number): CronPlan {+ if (cron === DAILY_CRON) return 'daily';+ if (cron !== EVERY_FIVE_MINUTES_CRON) return 'none';+ return new Date(scheduledTime).getUTCMinutes() % PUBLISH_EVERY_MINUTES === 0 ? 'publish_then_sweep' : 'sweep';+}- if (cron === PUBLISH_DUE_POSTS_CRON) {+export async function runScheduledJob(cron: string, env: Env, scheduledTime = Date.now()): Promise<void> {+ // ...+ const plan = cronPlan(cron, scheduledTime);+ if (plan === 'sweep') {+ await sweepReplies(services, context);+ } else if (plan === 'publish_then_sweep') {const run = await services.scheduledPublisher.publishDue();- context.log.info('scheduled publish run', { processed: run.processed, failed: run.errors.length });- } else if (cron === REFRESH_TOKENS_CRON) {+ if (run.processed === 0) await sweepReplies(services, context, SWEEP_AFTER_QUIET_PUBLISH);+ } else if (plan === 'daily') {await services.tokenRefresh.refreshExpiringInstagramTokens();- } else {- context.log.warn('no job for this cron', { cron });+ await services.retention.purge();}}```@@ -33,7 +41,7 @@ export async function runScheduledJob(cron: string, env: Env): Promise<void> {## Cron Handlers-### `*/15 * * * *` - Instagram Scheduled Post Publisher+### `*/5 * * * *` on the quarter hour - Instagram Scheduled Post Publisher**Function:** `scheduledPublisher.publishDue()` in `backend/services/scheduledPublisher.ts`@@ -57,7 +65,15 @@ The lease, attempt limit and failure rules live in `backend/lib/scheduledPublish**Concurrency safety:** The claim is one conditional UPDATE, so when the Worker cron and GitHub Actions overlap, the second run to claim a post gets no row back and skips it. The 20 minute lease is longer than the 14 minute deadline of both schedulers, so a run that is still working is never taken over.-### `0 0 * * *` - Instagram Token Auto-Refresh+### `*/5 * * * *` - Comment Reply Sweep++**Function:** `automationProcessor.run()` in `backend/services/automationProcessor.ts`++Most private replies go out within seconds, from the webhook request itself (`docs/architecture/data-flows/AUTOMATION.md`). The sweep sends the rest: replies waiting for a retry, a cooldown or an hourly limit, replies a webhook could not finish, and jobs whose run stopped. It claims up to `AUTOMATION_BATCH_SIZE` due comments (10 by default), at most half of them from one account, and settles each one before the next. On the quarter-hour runs it sweeps only when publishing had nothing to do, and then only 3, because publishing spends part of the run's 50 subrequests. With nothing due, a sweep is one database call.++A run that stops is recovered by the next one: a comment left `processing` for more than 20 minutes is claimed again, and one left `sending` becomes `needs_review`, because its reply may have reached Instagram. `AUTOMATION_PAUSED=true` makes every sweep return without claiming anything.++### `0 0 * * *` - Instagram Token Auto-Refresh and Retention**Function:** `tokenRefresh.refreshExpiringInstagramTokens()` in `backend/services/tokenRefreshService.ts`@@ -69,6 +85,8 @@ The lease, attempt limit and failure rules live in `backend/lib/scheduledPublishOne failed account is logged and skipped; it never stops the others. `backend/tests/services/tokenRefreshService.test.ts` covers the selection and the updates.+After the refresh, `retention.purge()` in `backend/services/retentionService.ts` deletes received comments older than 90 days (their reply attempts go with them) and audit events older than a year, across all users.+**Token lifecycle:**- Instagram issues long-lived tokens valid for 60 days- Tokens must be refreshed before they expire@@ -83,7 +101,7 @@ The `scheduled` handler passes the job to `ctx.waitUntil()`:```tsasync scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {- ctx.waitUntil(runScheduledJob(event.cron, env));+ ctx.waitUntil(runScheduledJob(event.cron, env, event.scheduledTime));},```@@ -93,22 +111,17 @@ async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) {The same publishing logic also runs via `scripts/publish-scheduled.ts` in GitHub Actions, at minutes 7, 22, 37 and 52 when GitHub starts the runs, which is often hours late. See `docs/architecture/data-flows/SCHEDULING.md` for details on how both systems coexist safely.-## Adding a New Cron Trigger+## Adding a New Cron Job-1. Add the cron expression to `wrangler.toml`:- ```toml- crons = ["*/15 * * * *", "0 0 * * *", "0 12 * * 1"]- ```+The account has no cron trigger to spare on the Workers Free plan, so a new job is a new plan in `cronPlan()` on one of the existing triggers, chosen by the scheduled time, rather than a new trigger. Check the account's count first (Workers and Pages, each Worker's Triggers) if you run your own instance on a paid plan or an account with free slots.-2. Add a constant and a branch in `backend/jobs/scheduled.ts`:+1. Add a plan and its time rule to `cronPlan()` in `backend/jobs/scheduled.ts`, for example a weekly report on the daily trigger:```ts- export const WEEKLY_REPORT_CRON = '0 12 * * 1';- // ...- } else if (cron === WEEKLY_REPORT_CRON) {- await services.weeklyReport.run();- }+ if (cron === DAILY_CRON) return new Date(scheduledTime).getUTCDay() === 1 ? 'daily_and_weekly' : 'daily';```+2. Run the job in that branch of `runScheduledJob()`, and add the case to `backend/tests/jobs/scheduled.test.ts`. A new trigger, when there is a slot, also needs its expression in `wrangler.toml` and a constant in `scheduled.ts`.+3. Implement the job as a service method (a new service is wired in `backend/container.ts`). It receives repositories and the cron's `RequestContext`, logs through `context.log`, and catches per-item failures so one bad record does not stop the run. Add a test in `backend/tests/services/` and run `npm run typecheck`4. Update `docs/architecture/backend/CRON.md` (this file)diff --git a/docs/architecture/backend/HONO.md b/docs/architecture/backend/HONO.mdindex 13a71f7..7a0ccd4 100644--- a/docs/architecture/backend/HONO.md+++ b/docs/architecture/backend/HONO.md@@ -25,7 +25,7 @@ The backend is split into layers, each with one job. `REQUEST_PIPELINE.md` is th| `app.ts` | `createApp()`: the ordered middleware pipeline and the two route groups || `server.ts` | The Worker export: `fetch` and `scheduled` || `container.ts` | The composition root: `createServices(clients, config, context)` wires repositories into services |-| `middleware/` | `cors.ts`, `requestContext.ts`, `securityHeaders.ts`, `clients.ts`, `rateLimit.ts`, `auth.ts`, `authHook.ts`, `validate.ts`, `errorHandler.ts` (see `MIDDLEWARE.md`) |+| `middleware/` | `cors.ts`, `requestContext.ts`, `securityHeaders.ts`, `clients.ts`, `rateLimit.ts`, `auth.ts`, `authHook.ts`, `metaWebhook.ts`, `validate.ts`, `errorHandler.ts` (see `MIDDLEWARE.md`) || `routes/` | One route table per feature (`<feature>Routes.ts`) and `index.ts`, which groups them into `publicRoutes` and `protectedRoutes` || `controllers/` | One controller file per feature (`<feature>Controller.ts`) and `http.ts` with `controller`, `servicesFor(c)` and `pathParam(c, name)` || `validators/` | Request body and query parsers (`<feature>Validators.ts`) and the field helpers in `fields.ts` |@@ -66,7 +66,7 @@ export function createApp(): Hono<AppEnv> {}```-`routes/index.ts` registers the public routes on `publicRoutes` (`GET /health`, `GET /auth/instagram/callback` with the `oauth` rate limit, and the `routes/authHookRoutes.ts` table with `POST /auth/email-hook` behind `verifyAuthHook`) and mounts every feature route table on `protectedRoutes`. The public group is registered before the protected one, so those paths answer without a token.+`routes/index.ts` registers the public routes on `publicRoutes` (`GET /health`, `GET /auth/instagram/callback` with the `oauth` rate limit, the `routes/authHookRoutes.ts` table with `POST /auth/email-hook` behind `verifyAuthHook`, and the `routes/instagramWebhookRoutes.ts` table with `GET /webhooks/instagram` and `POST /webhooks/instagram` behind `verifyMetaWebhook`) and mounts every feature route table on `protectedRoutes`. The public group is registered before the protected one, so those paths answer without a token.See `REQUEST_PIPELINE.md` for what each step does and `RATE_LIMITING.md` for the rate limit rules.diff --git a/docs/architecture/backend/MIDDLEWARE.md b/docs/architecture/backend/MIDDLEWARE.mdindex be090d3..adbaeaa 100644--- a/docs/architecture/backend/MIDDLEWARE.md+++ b/docs/architecture/backend/MIDDLEWARE.md@@ -14,6 +14,7 @@ Request arrives5. rateLimit(ip) app.use('/api/*', rateLimit(RATE_LIMIT_RULES.ip, clientIp)) middleware/rateLimit.tspublic routes app.route('/api', publicRoutes) health check, OAuth callback (+ rateLimit(oauth)),email hook (+ verifyAuthHook) middleware/authHook.ts+ Instagram webhook POST (+ verifyMetaWebhook) middleware/metaWebhook.ts6. requireAuth api.use('*', requireAuth) middleware/auth.ts <- protected routes only7. rateLimit(user, quota, publish) middleware/rateLimit.ts <- protected routes only8. route table api.route('/', protectedRoutes)@@ -177,6 +178,20 @@ The hook route is public, so the signature is the only proof that a request cameA failure throws `UnauthorizedError` (401).+## Meta Webhook Signature++**Source:** `backend/middleware/metaWebhook.ts` (`verifyMetaWebhook`), with `lib/metaWebhookSignature.ts`+**Applied to:** `POST /api/webhooks/instagram` only, before its validator++The webhook route is public, so the signature is the only proof that a notification came from Meta. `verifyMetaWebhook`:++1. Throws `NotConfiguredError` (503) when neither `INSTAGRAM_APP_SECRET` nor `META_APP_SECRET` is set.+2. Refuses a body over 1 MB with `ValidationError` (400), by its `Content-Length` header and again by its size once read.+3. Reads the raw body with `c.req.arrayBuffer()`. Hono caches it, so the JSON validator after it parses the same bytes.+4. Checks `X-Hub-Signature-256` (`sha256=<hex>`): HMAC-SHA256 over the raw body with each configured secret, compared with `crypto.subtle.verify` (constant time).++A failure throws `UnauthorizedError` (401). Meta's notifications carry no timestamp to check; a replayed notification is harmless, because each comment is stored once.+---## Adding New Middlewarediff --git a/docs/architecture/backend/RATE_LIMITING.md b/docs/architecture/backend/RATE_LIMITING.mdindex aa27507..e7e7100 100644--- a/docs/architecture/backend/RATE_LIMITING.md+++ b/docs/architecture/backend/RATE_LIMITING.md@@ -33,10 +33,12 @@ Defined in `backend/lib/rateLimit/rules.ts`.|---|---|---|---|---|| `ip` | Every `/api` request | Client IP; IPv6 by /64 | Sliding window counter | 300 per minute || `user` | Every protected request | User id from the verified JWT | Token bucket | Bursts of 120, refills 2 per second |-| `quota` | `POST /accounts`, `/accounts/reddit`, `/accounts/instagram`, `/accounts/refresh-all`, `/accounts/:id/refresh`, `/accounts/:id/refresh-ig-token`, `/resolve-channel`, `/tracked-content`, `/tracked-content/:id/refresh`, `GET` or `POST /process-scheduled` | User id | Sliding window log | 30 per 10 minutes |+| `quota` | `POST /accounts`, `/accounts/reddit`, `/accounts/instagram`, `/accounts/refresh-all`, `/accounts/:id/refresh`, `/accounts/:id/refresh-ig-token`, `/resolve-channel`, `/tracked-content`, `/tracked-content/:id/refresh`, `GET` or `POST /process-scheduled`, `POST /automations/accounts/:accountId/subscribe` | User id | Sliding window log | 30 per 10 minutes || `publish` | `POST /accounts/:id/ig-media-publish`, `/accounts/:id/ig-publish` | User id | Leaking bucket | 50 deep, drains 1 every 15 seconds || `oauth` | `GET /auth/instagram/callback` | Client IP | Fixed window counter | 10 per 10 minutes |+The Instagram webhook (`POST /api/webhooks/instagram`) has only the `ip` rule. Meta sends from its own servers, so a burst past 300 a minute from one of them gets 429, and Meta delivers those notifications again later; nothing is lost. Private replies have their own limits, which are not rate limit rules: hourly counts per instance, user, account and rule and a daily count per person, kept in the database by `reserve_automation_send` so every Worker sees them (`docs/architecture/data-flows/AUTOMATION.md`).+Auth emails have their own daily caps, which are not rate limit rules: the Send Email hook allows `EMAIL_DAILY_LIMIT` emails a day in total (100 by default) and 5 a day to one address, counted per UTC day by `repositories/emailQuotaRepository.ts`. See `docs/architecture/backend/CACHING.md` for the counters and `SERVICES.md` for the rules. Supabase calls the hook from its own servers, so the `ip` rule above counts Supabase, not the person signing up; the per-address cap and Supabase's own email rate limit are what slow down one person.The limits are sized for the dashboard: an Overview load sends about 20 requests, Instagram container polling sends one every 3 seconds, and bulk publishing sends two Instagram calls per file. Lowering them can block normal use; test the Overview, bulk publishing and tracked content refresh after any change.diff --git a/docs/architecture/backend/REQUEST_PIPELINE.md b/docs/architecture/backend/REQUEST_PIPELINE.mdindex 573fd1b..3a67557 100644--- a/docs/architecture/backend/REQUEST_PIPELINE.md+++ b/docs/architecture/backend/REQUEST_PIPELINE.md@@ -26,7 +26,8 @@ Request4. Clients middleware/clients.ts per-request Supabase and Redis clients5. Rate limit by IP middleware/rateLimit.ts before authentication, so bad tokens never reach Supabase AuthPublic routes routes/index.ts /api/health, /api/auth/instagram/callback (with its own oauth limit),- /api/auth/email-hook (middleware/authHook.ts checks Supabase's signature)+ /api/auth/email-hook (middleware/authHook.ts checks Supabase's signature),+ /api/webhooks/instagram (middleware/metaWebhook.ts checks Meta's signature)6. Authentication middleware/auth.ts verifies the JWT and sets userId; 401 otherwise7. Per-user limits middleware/rateLimit.ts user, quota and publish rules8. Route table routes/<feature>Routes.ts@@ -37,7 +38,7 @@ RequestResponse, or a thrown error -> middleware/errorHandler.ts```-Authorization is ownership: every user-scoped repository method filters by the verified user id, so another user's row is simply not found (404). There are no roles. The Send Email hook has no user: Supabase Auth calls it, and the webhook signature takes the place of the JWT.+Authorization is ownership: every user-scoped repository method filters by the verified user id, so another user's row is simply not found (404). There are no roles. The Send Email hook and the Instagram webhook have no user: Supabase Auth and Meta call them, and their signatures take the place of the JWT. The Instagram webhook attaches each comment to the account its signed payload names.## Request context@@ -53,7 +54,7 @@ Services never see the Hono context. A controller hands them a `RequestContext`The user id is passed to service methods explicitly (`accounts.refresh(userId, accountId)`), never read from the request body.-Cron jobs build the same context in `jobs/scheduled.ts`, with a `cron-` request id and a 14 minute deadline. The Overview's background warming outlives the response, so it uses its own 25 second deadline instead of the request signal.+Cron jobs build the same context in `jobs/scheduled.ts`, with a `cron-` request id and a 14 minute deadline. The Overview's background warming outlives the response, so it uses its own 25 second deadline instead of the request signal. `inBackground(c, label, work)` in `controllers/http.ts` does the same for any work after a response: it builds services with a fresh context (the request id, a 25 second deadline, a logger tagged with the label) and runs the work under `ctx.waitUntil()`, logging a failure because nobody is waiting for it. The Instagram webhook and the automation retry route use it to send replies.## Compositiondiff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.mdindex 069e638..be79f4a 100644--- a/docs/architecture/backend/ROUTES.md+++ b/docs/architecture/backend/ROUTES.md@@ -21,11 +21,11 @@ These statuses apply to every route below and are not repeated in the tables:| 400 | `VALIDATION_ERROR` | The body or query fails its validator, or a stored field the request needs (such as a token or uploads playlist) is missing || 401 | `UNAUTHORIZED` | Protected route without a valid token || 404 | `NOT_FOUND` | The account, post or item does not exist for this user, is on the wrong platform, or the route does not exist |-| 409 | `CONFLICT` | The account is already added |+| 409 | `CONFLICT` | The account is already added, or an automation item cannot be retried in its state || 429 | `RATE_LIMITED` | A rate limit rule is exceeded; the body adds `retryAfter` (seconds). The email hook also answers 429 when the day's emails are used up || 500 | `DATABASE_ERROR`, `INTERNAL_ERROR` | A Supabase query failed, or a bug || 502 | `UPSTREAM_ERROR` | YouTube, Instagram or Reddit answered with an error; the platform's message is kept with URLs removed |-| 503 | `NOT_CONFIGURED` | A Worker secret the route needs (YouTube key, Instagram app, Cloudinary, the email hook secrets) is not set |+| 503 | `NOT_CONFIGURED` | A Worker secret the route needs (YouTube key, Instagram app, Cloudinary, the email hook secrets, the Instagram webhook secrets) is not set || 504 | `UPSTREAM_TIMEOUT` | A platform call was cancelled or timed out |## Public Routes@@ -35,8 +35,20 @@ Registered on `publicRoutes` in `routes/index.ts`.| Method | Path | Controller | Purpose ||---|---|---|---|| GET | `/api/health` | `healthController.getHealth` | Returns `{ status: 'ok', timestamp }` |-| GET | `/api/auth/instagram/callback` | `instagramAuthController.handleInstagramCallback` | OAuth code exchange; always redirects the browser back to the accounts page with `ig_connected=true` or `ig_error=<reason>`, never a JSON error |+| GET | `/api/auth/instagram/callback` | `instagramAuthController.handleInstagramCallback` | OAuth code exchange; always redirects the browser back to the accounts page with `ig_connected=true`, `ig_connected=reconnected` (the account was already connected and its token was renewed) or `ig_error=<reason>`, never a JSON error || POST | `/api/auth/email-hook` | `authHookController.sendAuthEmail` (`routes/authHookRoutes.ts`) | Supabase Auth's Send Email hook: sends sign-up, password reset and other auth emails through Resend. Answers `{}` |+| GET | `/api/webhooks/instagram` | `instagramWebhookController.verifyInstagramWebhook` (`routes/instagramWebhookRoutes.ts`) | Meta's webhook check: answers the bare `hub.challenge` as text when `hub.mode=subscribe` and `hub.verify_token` matches `INSTAGRAM_WEBHOOK_VERIFY_TOKEN`; 403 otherwise, 503 when the token is not set |+| POST | `/api/webhooks/instagram` | `instagramWebhookController.receiveInstagramWebhook` | Instagram comment notifications, signed by Meta. Stores them, answers `{ success: true }`, then sends the matched replies |++### Instagram webhook++Meta calls this route, not a browser:++- **Authentication.** `middleware/metaWebhook.ts` (`verifyMetaWebhook`) checks `X-Hub-Signature-256` (HMAC-SHA256 of the raw body) against `INSTAGRAM_APP_SECRET`, or `META_APP_SECRET` when set. No JWT.+- **Statuses.** `200` once every comment is stored (duplicates included). `400` for a body over 1 MB, malformed JSON, or an `object` other than `instagram`. `401` for a missing or wrong signature. `503` when no app secret is set. `500` when storing fails; Meta delivers the notification again for up to 36 hours.+- **After the response.** The new matched comments are sent with `ctx.waitUntil()` and their own 25 second deadline; anything left is sent by the 5 minute cron.++See `docs/architecture/data-flows/AUTOMATION.md`.### Send Email hook@@ -144,6 +156,24 @@ Controllers call `TrackedContentService`; link detection and the manual views an| 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 |+### Automations++Controllers call `AutomationService` (`services/automationService.ts`). Every route works only on the user's own rules, accounts and items; another user's answers 404.++| Method | Path | File | Purpose |+|---|---|---|---|+| GET | `/api/automations` | `automationRoutes.ts`, `automationController.getAutomations` | The user's rules, each Instagram account's automation state (`paused`, `cooldownUntil`, `cooldownReason`, `subscribedAt`) and the server settings (`webhookConfigured`, `paused`, `limits`) |+| POST | `/api/automations/rules` | `automationController.createAutomationRule` | Create a rule (`accountId`, `name`, `keywords`, `replyText`, optional `matchMode`, `caseSensitive`, `mediaIds`, `linkUrl`, `enabled`, `hourlyLimit`). 404 unless the account is one of the user's Instagram accounts; 400 when the reply and link pass 1,000 bytes. An enabled rule also subscribes the account to comment events |+| PUT | `/api/automations/rules/:id` | `automationController.updateAutomationRule` | Change any of the fields sent; the account stays. Turning it on subscribes the account if needed |+| DELETE | `/api/automations/rules/:id` | `automationController.deleteAutomationRule` | Delete a rule; its past comments keep their status |+| POST | `/api/automations/rules/:id/duplicate` | `automationController.duplicateAutomationRule` | Copy a rule, turned off, named "(copy)" |+| POST | `/api/automations/test` | `automationController.testAutomationRule` | Match a sample `comment` against a rule draft and return `{ matched, keyword, message, messageBytes, maxMessageBytes }`. Stores and sends nothing |+| GET | `/api/automations/activity` | `automationController.listAutomationActivity` | Received comments, newest first. Query: `accountId`, `ruleId`, `status` (one or comma-separated), `from`, `to`, `before` (the previous page's `nextBefore`), `limit` (1 to 100, default 50) |+| POST | `/api/automations/activity/:id/retry` | `automationController.retryAutomationActivity` | Put a failed, skipped or review item inside its 7 days back in the queue and start sending it; 409 for any other state |+| GET | `/api/automations/stats` | `automationController.getAutomationStats` | Comment counts by status and request counts by outcome. Query: `accountId`, `ruleId`, `from`, `to` (default the last 7 days) |+| PUT | `/api/automations/accounts/:accountId` | `automationController.updateAutomationAccount` | `{ paused }`: hold or release the account's replies; resuming also clears a hold the Worker set and sends held replies on the next run |+| POST | `/api/automations/accounts/:accountId/subscribe` | `automationController.subscribeAutomationAccount` | Ask Instagram to send the account's comments to the webhook (`POST /<ig-id>/subscribed_apps?subscribed_fields=comments`); 502 when Instagram refuses. Covered by the quota rate limit |+### Settings| Method | Path | File | Purpose ||---|---|---|---|diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.mdindex 211f404..58d22a4 100644--- a/docs/architecture/backend/SERVICES.md+++ b/docs/architecture/backend/SERVICES.md@@ -42,11 +42,29 @@ A service receives only what it uses: repositories, the cleaned `AppConfig` from| `settings` | `settingsService.ts` | settings | `githubSettings`, `saveGithubSettings`, `serverKeyStatus` || `instagramConnect` | `instagramConnectService.ts` | accounts | `authorizationUrl`, `userIdFromState`, `connect`, plus `configured` and `accountsPageUrl` || `authEmail` | `authEmailService.ts` | email quota (Redis, the fail-fast client) | `send(hook, webhookId)` (Supabase Auth's Send Email hook; no user) |+| `automations` | `automationService.ts` | accounts, automation rules, comments, account controls, audit | `overview`, `createRule`, `updateRule`, `duplicateRule`, `deleteRule`, `test`, `activity`, `stats`, `retry`, `setPaused`, `subscribe` |+| `automationWebhook` | `automationWebhookService.ts` | automation rules, comments | `challengeAnswer` (Meta's verification), `ingest` (store a webhook's comments; no user) |+| `automationProcessor` | `automationProcessor.ts` | comments | `run({ ids?, limit? })` (send due private replies; webhook, retry route and 5 minute cron) |+| `retention` | `retentionService.ts` | comments, audit | `purge` (daily cron) |-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`).+Every user-scoped method takes the verified `userId` as its first argument. Methods that need one of the user's records load it with a `...ForUser` repository method and throw `NotFoundError` when it is missing or on the wrong platform, so another user's record is never found. `scheduledPublisher`, `tokenRefresh`, `automationWebhook`, `automationProcessor` and `retention` are the only services that use the cross-user repository methods (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `claim`, and the automation queue, intake and retention methods).++`accounts.remove` and `instagramConnect.connect` also record `account.removed`, `account.connected` and `account.reconnected` in `audit_events`. Connecting an Instagram account that is already connected renews its token in place and answers `reconnected`, so a revoked token is fixed without removing the account and its rules.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`.+### Comment automation (`automationService.ts`, `automationWebhookService.ts`, `automationProcessor.ts`)++The flow is in `docs/architecture/data-flows/AUTOMATION.md`. The rules the services apply are pure helpers in `backend/lib/`:++| Helper | What it decides |+|---|---|+| `automationMatching.ts` | `matchedKeyword` (contains as whole words, or the exact comment; NFKC and case folding), `coversMedia`, `pickRule` (rules for the post first, then oldest) |+| `automationDelivery.ts` | `classifySendError` (Graph codes to rate limited, blocked, transient, already replied, not authorized, not eligible, refused), `finishPlan` (what to record for each answer), `readinessPlan` and `releasePlan` (jobs that cannot send now), `retryDelayMs`, `cooldownFromUsage`, `composeReply`, `messageBytes`, and the constants: 1,000 byte messages, the 7 day window, the 20 minute claim lease, 5 tries |+| `metaWebhookSignature.ts` | `verifyMetaSignature` and the constant-time `verifyTokenMatches` |++`automationService` checks every account and item against the user before acting, refuses a reply and link over 1,000 bytes, records each change in `audit_events`, and subscribes an account to comment events when one of its rules is first turned on (a refusal is logged and the rule is still saved). `automationProcessor` returns at once when `AUTOMATION_PAUSED` is set, settles one job at a time, and logs a job's database failure and moves on, leaving the job to its lease.+### Accounts (`accountService.ts`, `accountFactory.ts`)`accountFactory.ts` holds pure builders: `tokenExpiryIso` (null without a lifetime), `buildYouTubeAccount`, `buildRedditAccount`, `buildInstagramAccount`. Each builder takes its id from `newRowId()`.@@ -127,6 +145,7 @@ There is no barrel: services and tests import each module directly, and each mod| `instagramCaptions.ts` | Hashtag analysis and caption length correlation || `instagramAnalytics.ts` | `computeInstagramAnalytics` orchestrator, the empty state and the engagement, views and ranking helpers || `instagramPublishing.ts` | `buildMediaParams` (one helper per media type) and the Graph publishing calls: `createMediaContainer`, `fetchContainerStatus`, `publishMediaContainer`, `fetchPublishingLimit` |+| `instagramMessaging.ts` | `sendPrivateReply(igUserId, token, commentId, text, signal)`: `POST /<ig-id>/messages` with the token as a Bearer header and a 10 second timeout. It answers a `SendResult` instead of throwing, because each Graph error code leads somewhere different, and never repeats the request; a timeout or lost connection is `ambiguous`, a fetch the runtime refused at the subrequest cap is `not_sent`. `subscribeToComments` calls `POST /<ig-id>/subscribed_apps?subscribed_fields=comments` and throws `UpstreamError` unless Instagram answers `success: true` |A Graph API error becomes an `UpstreamError` (502) with Instagram's message; a cancelled or timed out call becomes an `UpstreamTimeoutError` (504).diff --git a/docs/architecture/cloudflare/CI_CD.md b/docs/architecture/cloudflare/CI_CD.mdindex b0346a6..4a69fc4 100644--- a/docs/architecture/cloudflare/CI_CD.md+++ b/docs/architecture/cloudflare/CI_CD.md@@ -52,7 +52,7 @@ A type error or failing test stops the run before the deploy step.- `CLOUDFLARE_API_TOKEN` - API token with Worker deploy permission- `CLOUDFLARE_ACCOUNT_ID` - your Cloudflare account ID-The workflow does not set the Worker's own secrets (`SUPABASE_*`, `FRONTEND_URL`, the optional `ALLOWED_ORIGINS`, the optional email secrets `SEND_EMAIL_HOOK_SECRET`, `RESEND_API_KEY`, `EMAIL_FROM` and `EMAIL_DAILY_LIMIT`, and the rest). They are set once with `npx wrangler secret put` and kept across deploys; see `WORKERS.md`.+The workflow does not set the Worker's own secrets (`SUPABASE_*`, `FRONTEND_URL`, the optional `ALLOWED_ORIGINS`, the optional email secrets `SEND_EMAIL_HOOK_SECRET`, `RESEND_API_KEY`, `EMAIL_FROM` and `EMAIL_DAILY_LIMIT`, the optional automation settings `INSTAGRAM_WEBHOOK_VERIFY_TOKEN`, `META_APP_SECRET` and `AUTOMATION_*`, and the rest). They are set once with `npx wrangler secret put` and kept across deploys; see `WORKERS.md`.**Does not** redeploy on frontend-only changes, documentation changes, or script changes.@@ -126,7 +126,7 @@ The site needs no other secret: every value it shows is public and lives in the- `SUPABASE_URL` - the Supabase project URL- `SUPABASE_SERVICE_KEY` - service-role key (needed to query all users' posts)-**This is the GitHub Actions fallback for the Worker cron.** Both this workflow and the Worker cron (`*/15`) run the same publishing logic against the same Supabase table. A conditional claim with a 20 minute lease prevents double-publishing and lets a later run take over a post whose run died; see `docs/architecture/data-flows/SCHEDULING.md`.+**This is the GitHub Actions fallback for the Worker cron.** Both this workflow and the Worker cron (`*/5`, publishing on the quarter hour) run the same publishing logic against the same Supabase table. A conditional claim with a 20 minute lease prevents double-publishing and lets a later run take over a post whose run died; see `docs/architecture/data-flows/SCHEDULING.md`.The script imports the shared rules from `backend/lib/scheduledPublishing.ts` by relative path, and the workflow runs whatever is on the default branch, so a change to that file reaches this workflow on its next run without a deploy.diff --git a/docs/architecture/cloudflare/WORKERS.md b/docs/architecture/cloudflare/WORKERS.mdindex 8c3886f..def0e66 100644--- a/docs/architecture/cloudflare/WORKERS.md+++ b/docs/architecture/cloudflare/WORKERS.md@@ -8,13 +8,13 @@ main = "server.ts"compatibility_date = "2025-01-01"[triggers]-crons = ["*/15 * * * *", "0 0 * * *"]+crons = ["*/5 * * * *", "0 0 * * *"]```- `name` - the Worker name as deployed on Cloudflare; also determines the default URL- `main` - entry point file (`backend/server.ts`). Wrangler bundles it with esbuild, which strips the TypeScript types without checking them; `npm run typecheck` is the check- `compatibility_date` - pins the Workers runtime API version-- `crons` - cron trigger schedules (see `docs/architecture/backend/CRON.md`)+- `crons` - cron trigger schedules (see `docs/architecture/backend/CRON.md`). The five minute trigger carries both scheduled publishing (on the quarter hour) and the comment reply sweep, because the account already uses the five cron triggers the Workers Free plan allows## Worker Export Format@@ -24,12 +24,12 @@ The Worker exports two handlers:export default {fetch: app.fetch, // handles HTTP requests (the Hono app from backend/app.ts)async scheduled(event: ScheduledController, env: Env, ctx: ExecutionContext) { // handles cron triggers- ctx.waitUntil(runScheduledJob(event.cron, env));+ ctx.waitUntil(runScheduledJob(event.cron, env, event.scheduledTime));},} satisfies ExportedHandler<Env>;```-`event.cron` is the cron expression that fired, `env` holds the Worker secrets and variables, and `ctx.waitUntil(promise)` keeps the Worker alive for the job. `runScheduledJob()` in `backend/jobs/scheduled.ts` picks the job for the expression; see `docs/architecture/backend/CRON.md`.+`event.cron` is the cron expression that fired, `event.scheduledTime` the minute it was due for, `env` holds the Worker secrets and variables, and `ctx.waitUntil(promise)` keeps the Worker alive for the job. `runScheduledJob()` in `backend/jobs/scheduled.ts` picks the job for the expression; see `docs/architecture/backend/CRON.md`.`ScheduledController`, `ExecutionContext` and `ExportedHandler` come from `@cloudflare/workers-types`, which `backend/tsconfig.json` loads as its only ambient types.@@ -56,6 +56,16 @@ All secrets are set via `npx wrangler secret put <NAME>`, run from `backend/`. T| `RESEND_API_KEY` | Optional | Resend API key with sending access; sends the auth emails (verification codes) || `EMAIL_FROM` | Optional | Sender of the auth emails on a domain verified in Resend, such as `Twiligent <[email protected]>` || `EMAIL_DAILY_LIMIT` | Optional | Auth emails a day across all users (each code sign-in is one) before the sign-in page pauses email codes and points to Google or a password; defaults to `100`, Resend's free daily quota |+| `INSTAGRAM_WEBHOOK_VERIFY_TOKEN` | Optional | The Verify Token typed into the Meta dashboard's Instagram webhook settings; `GET /api/webhooks/instagram` answers Meta's check only with it. Without it, and `INSTAGRAM_APP_SECRET`, no comment reaches the Worker and the Automations page says so |+| `META_APP_SECRET` | Optional | The Meta app's own secret (App settings, Basic). Webhook signatures are checked against `INSTAGRAM_APP_SECRET` and, when this is set, against it too |+| `AUTOMATION_PAUSED` | Optional | `true` holds every comment-to-DM reply on the instance; comments are still stored and matched |+| `AUTOMATION_ACCOUNT_HOURLY_LIMIT` | Optional | Private replies an hour per Instagram account; default `200`, at most `750` (Instagram's limit) |+| `AUTOMATION_USER_HOURLY_LIMIT` | Optional | Private replies an hour across one member's accounts; default `500` |+| `AUTOMATION_GLOBAL_HOURLY_LIMIT` | Optional | Private replies an hour across the instance; default `1000` |+| `AUTOMATION_RECIPIENT_DAILY_LIMIT` | Optional | Private replies a day one person can get from one account; default `3` |+| `AUTOMATION_BATCH_SIZE` | Optional | Replies sent by one webhook request or one sweep; default `10`, at most `15` (each costs three of the free plan's 50 subrequests) |++The automation values are plain settings, not secrets, but setting them with `wrangler secret put` keeps them across deploys like the rest. A missing or invalid value falls back to its default.### Setting secrets@@ -88,6 +98,9 @@ UPSTASH_REDIS_REST_TOKEN=...# SEND_EMAIL_HOOK_SECRET=v1,whsec_...# RESEND_API_KEY=re_...# EMAIL_FROM=Twiligent <[email protected]>+# only to test the Instagram webhook locally; Meta cannot reach localhost, so sign request bodies yourself+# INSTAGRAM_WEBHOOK_VERIFY_TOKEN=a-long-random-string+# AUTOMATION_PAUSED=true```Run locally from the repository root: `npm run dev:backend` (Worker only, port 8787) or `npm run dev` (Worker and Vite together). Both run `wrangler dev` in `backend/`, which reloads on save.@@ -106,11 +119,13 @@ These are hard constraints imposed by the Cloudflare Workers runtime. Violating3. **No persistent state between requests.** The Worker isolate may be a fresh instance on every request. Do not rely on module-level variables to persist state across requests. All state must come from Supabase, Redis, or Worker KV. (The cache cooldown and the rate limiter's memory fallback keep per-isolate state on purpose, as a best-effort optimization that is safe to lose.)-4. **CPU time limit.** Workers have a CPU time limit per request (typically 50ms on free tier, up to 30s on paid). Long-running synchronous operations will be killed. Use async/await for all I/O.+4. **CPU time limit.** On the Workers Free plan each invocation gets 10 ms of CPU time (Workers Paid: 30 seconds by default, up to 5 minutes). Time waiting on `fetch` does not count, so I/O-bound work fits; long synchronous work is killed. Use async/await for all I/O.++5. **Subrequests.** On the Workers Free plan an invocation can make 50 subrequests (each `fetch`, including Supabase and Redis calls); Workers Paid allows 10,000. A webhook request, a sweep and a publishing run each count separately. `AUTOMATION_BATCH_SIZE` is capped at 15 for this reason, and a fetch the runtime refuses at the cap is recorded as not sent rather than as an unknown outcome.-5. **`ctx.waitUntil()` in cron handlers.** Cron handlers must use `ctx.waitUntil(promise)` for async work. Without it, the Worker may terminate before the work completes.+6. **`ctx.waitUntil()` in cron handlers and after responses.** Cron handlers must use `ctx.waitUntil(promise)` for async work. Without it, the Worker may terminate before the work completes. After an HTTP response, `waitUntil` keeps the Worker running for at most 30 seconds; `inBackground()` in `controllers/http.ts` gives such work its own 25 second deadline.-6. **Bundle size.** The Worker bundle must be a single ESM file (Wrangler handles bundling). Avoid large dependencies. Type-only imports, including everything in `shared/types/`, add nothing to the bundle.+7. **Bundle size.** The Worker bundle must be a single ESM file (Wrangler handles bundling). Avoid large dependencies. Type-only imports, including everything in `shared/types/`, add nothing to the bundle.## Adding a New Worker Secretdiff --git a/docs/architecture/data-flows/AUTOMATION.md b/docs/architecture/data-flows/AUTOMATION.mdnew file mode 100644index 0000000..3cda738--- /dev/null+++ b/docs/architecture/data-flows/AUTOMATION.md@@ -0,0 +1,189 @@+# Data Flow - Comment-to-DM Automation++## Overview++An account owner writes a rule: keywords, which posts it covers, and a reply with an optional link. When someone comments one of the keywords on a post or reel of a connected Instagram professional account, Meta sends the comment to the Worker's webhook, and the Worker sends the commenter a private reply through Instagram's messages endpoint.++```+Instagram comment+ -> Meta comments webhook POST /api/webhooks/instagram (signed with X-Hub-Signature-256)+ -> verifyMetaWebhook 1 MB limit, HMAC-SHA256 over the raw body with the app secret+ -> parseInstagramWebhook comments changes only; anything else is counted and dropped+ -> automationWebhook.ingest rules for the Instagram account -> match -> store every comment (dedupe)+ -> 200 {"success":true} only after the comments are stored; a failure answers 5xx and Meta retries for 36 hours+ -> waitUntil: automationProcessor.run({ ids }) the new matched comments, after the response+ claim -> check -> reserve within limits -> POST /<ig-id>/messages -> finish+ -> every 5 minutes: automationProcessor.run() retries, waits, recovery+```++The database is the queue: a matched comment's row in `automation_comments` is the job that sends its reply. There is no Cloudflare Queue (ADR-040).++## What Instagram Allows++Checked against Meta's documentation on 2026-10-16:++| Rule | Value | Source |+|---|---|---|+| API setup | Instagram API with Instagram Login (`graph.instagram.com`), the setup Twiligent already connects with | Instagram Platform overview |+| Permissions | `instagram_business_basic`, `instagram_business_manage_comments` (comments webhook and private replies), `instagram_business_manage_messages`; Twiligent's OAuth already asks for all three | Private replies, webhook fields |+| Access level | Advanced Access for the `comments` webhook field; Business verification for production; the app must be Live | Webhooks setup |+| Accounts | Professional (Business or Creator) accounts only; the account must be public, since private accounts get no comment notifications | Webhooks setup |+| Replies per comment | One private reply; a follow-up only after the person replies, within 24 hours | Private replies |+| Reply window | 7 days after the comment (Live comments: only during the broadcast, not supported here) | Private replies |+| Rate limit | 750 private replies an hour per professional account for posts and reels | Graph API rate limiting, Business Use Case limits |+| Message size | Text up to 1,000 bytes | Messaging API |+| Webhook retries | Retried with decreasing frequency for 36 hours until a 200; duplicates must be handled | Webhooks setup |++The general Instagram Platform call quota is a different limit from the 750 private replies an hour, and neither is a daily DM allowance. Twiligent's own limits stay below them and are configurable.++## Setup: Getting Comments to the Worker++1. **The app-level webhook** (Meta dashboard, Instagram, API setup with Instagram login, Configure webhooks): callback URL `https://<worker>/api/webhooks/instagram`, the Verify Token from `INSTAGRAM_WEBHOOK_VERIFY_TOKEN`, and the `comments` field. Meta checks the URL with `GET ?hub.mode=subscribe&hub.verify_token=...&hub.challenge=...`; `automationWebhook.challengeAnswer()` compares the token in constant time and answers the bare challenge.+2. **The account-level subscription**: Instagram sends an account's comments only after `POST /<ig-id>/subscribed_apps?subscribed_fields=comments` with that account's token. Twiligent calls it when a rule is first turned on for the account, and from the "Turn on comment events" button (`POST /api/automations/accounts/:accountId/subscribe`). The time is kept in `automation_accounts.subscribed_at`. If Instagram refuses, the rule is still saved and the page shows the account as not receiving comments.++Signatures: Instagram Login apps sign with the Instagram app secret (`INSTAGRAM_APP_SECRET`). `META_APP_SECRET`, the Meta app's own secret, is accepted as a second key because the dashboard shows both and developers report each in use.++## Intake: `POST /api/webhooks/instagram`++1. `verifyMetaWebhook` refuses a body over 1 MB, reads the raw bytes, and checks `X-Hub-Signature-256` against each configured secret with `crypto.subtle.verify` (constant time). No secret configured answers 503; a bad signature 401, before any database work.+2. `parseInstagramWebhook` refuses a body whose `object` is not `instagram` (400). Inside it, each `comments` change becomes an event (comment id from `id` or `comment_id`, author, text, media, the entry's account id and `time`); other fields and malformed changes are counted as unsupported and dropped.+3. `automationWebhook.ingest()` groups the events by Instagram account id and calls `automation_rules_for_ig_user` once per account: the enabled rules of every connected Twiligent account with that `igUserId`, oldest account first. An account with no enabled rule stores nothing.+4. Each comment is classified:+ - the account's own comment: `ignored`, reason `own_comment`+ - no text: `ignored`, `no_text`+ - no rule matches: `ignored`, `no_match`, stored without its text or author+ - a match: `queued`, with the rule, the author and the text (at most 2,200 characters)+5. `insertMany()` upserts all of them with `ignoreDuplicates` on the unique `(ig_user_id, comment_id)`, so a notification Meta delivers again inserts nothing; only the new rows come back.+6. The controller answers `200 {"success":true}` and hands the new queued ids to `inBackground()`, which builds services with their own 25 second deadline (the request's signal ends with the response) and runs `automationProcessor.run({ ids })` under `ctx.waitUntil()`.++If storing fails, the request fails with 5xx, and Meta delivers the notification again later. Nothing is acknowledged that is not stored.++`expires_at` is the notification time plus 7 days. Meta's payload has no comment time, and a redelivered notification carries a later time, so the window can be a little generous; a reply sent after Instagram's window is refused there and recorded as failed.++## Matching (`backend/lib/automationMatching.ts`)++- Text is normalised with NFKC (full-width letters fold to plain ones) and runs of spaces collapse; matching ignores case unless the rule says otherwise.+- `contains`: the keyword appears as whole words (a letter or digit on either side breaks the match, so GUIDE never matches GUIDELINES). Phrases work across spaces; regular expression characters are literal.+- `exact`: the whole comment equals the keyword once spaces, punctuation and emoji at its edges are removed.+- A rule covers every post when `media_ids` is empty, or only the listed posts. Rules for the comment's post are tried before rules for every post, then oldest first; the first match wins. A comment never triggers a rule meant for another post.+- `POST /api/automations/test` runs the same matching on a sample comment and returns the composed reply; it stores and sends nothing.++## Delivery (`backend/services/automationProcessor.ts`)++`run({ ids?, limit? })` returns at once when `AUTOMATION_PAUSED` is true. Otherwise it claims up to the batch size and settles each job in turn, so each account's replies keep their order and the run never opens more than one connection to Instagram at a time:++1. **Claim** (`claim_automation_comments`): due jobs (`queued` or `retry_wait` with `next_attempt_at <= now`) and jobs whose run stopped (`processing` for more than 20 minutes), oldest first, at most `perAccount` per account, locked with `FOR UPDATE SKIP LOCKED` so two runs never take the same job. The same call turns any `sending` job older than 20 minutes into `needs_review`. It returns the rule's reply and the account's token with each job.+2. **Check** (`readinessPlan`): an expired comment becomes `expired`, a rule that was turned off or removed `skipped`, an account without a token `failed`. No limit is spent on these.+3. **Reserve** (`reserve_automation_send`): one transaction under an advisory lock, so every Worker sees the same counts and two jobs cannot both take the last free send. In order: a paused account holds the job; an account cooldown waits for it; the commenter already got the daily number of replies from this account (counting other comments, not retries of this one) skips it; then the rule's, account's, user's and instance's hourly limits. When a scope is full, the job waits until the oldest send in that hour is an hour old. On success the job becomes `sending`, its attempts count goes up, and an `automation_attempts` row records the request before it leaves.+4. **Send** (`sendPrivateReply`): `POST https://graph.instagram.com/v25.0/<ig-id>/messages` with `{ recipient: { comment_id }, message: { text } }` and the account's token as a Bearer header, 10 second timeout, never repeated inside the call.+5. **Finish** (`finish_automation_send`): records the outcome on the attempt and the comment in one transaction, and sets a cooldown or a hold on the account when the answer calls for one.++A database error on one job is logged and the run moves on; that job's claim or reservation expires and the recovery above picks it up.++### What each answer does++| Instagram's answer | Comment | Attempt | Account |+|---|---|---|---|+| 200 with `message_id` | `accepted`, `message_id` kept | `accepted` | |+| Codes 4, 17, 32, 613, 80002, 80006 or HTTP 429 | `retry_wait` until the cooldown ends | `rate_limited` | cooldown from `X-Business-Use-Case-Usage` (`estimated_time_to_regain_access`), else 15 minutes |+| Code 368 (temporarily blocked) | `retry_wait` | `rejected` | 24 hour cooldown |+| Codes 1, 2 or HTTP 5xx | `retry_wait` after 1, 2, 4, 8 minutes (at most an hour) plus up to 30 seconds; `failed` after 5 tries | `rejected` | |+| Code 10900 or subcode 2534023 (already replied) | `skipped` | `rejected` | |+| Codes 3, 190, 200, a bare 10, subcode 2534041 (token or permission) | back to `queued`, held | `rejected` | paused with the reason: reconnect, then resume |+| Code 551, 10903; subcodes 2534014, 2534022, 2534025, 2018001 (not allowed for this comment) | `failed` | `rejected` | |+| Any other error | `failed`, with Instagram's message | `rejected` | |+| Timeout, connection lost, unreadable 200 | `needs_review` | `ambiguous` | |+| The Worker refused the request (subrequest limit) | `retry_wait`, 5 minutes | `rejected` | |++A wait that would end after the 7 day window makes the comment `expired` instead.++## Duplicates and Ambiguity++- A notification Meta delivers twice is stored once: `unique (ig_user_id, comment_id)`.+- A comment repeated inside one notification is stored once.+- Two runs never send the same job: the claim locks rows, and the reservation only moves a job this run holds.+- A job whose run stopped before the request left is claimed again after its 20 minute lease.+- A send that may have reached Instagram (timeout, lost connection, a run that stopped while `sending`) is never retried on its own. It shows as Needs review, and the owner decides after checking the conversation on Instagram. If they retry and the first reply did arrive, Instagram refuses a second private reply to the same comment (10900), and the comment is marked skipped.+- Delivery is at least once into the queue and at most once to Instagram without a person's decision. Instagram reports acceptance, not delivery or reading, so the dashboard says "Accepted by Instagram" and never "Delivered".++## Comment Status Lifecycle++```+ignored (no rule matched; final)+queued -> processing -> sending -> accepted+ ^ | |-> retry_wait -> processing ...+ | | |-> failed | skipped | expired+ | | '-> needs_review (no answer, or the run stopped)+ | |-> queued (held: account paused) | retry_wait (limit, cooldown)+ | '-> skipped (rule off, recipient limit) | expired | failed (no token)+ '-- retry by the owner (failed, skipped, needs_review, within 7 days)+```++| Status | Shown as | Meaning |+|---|---|---|+| `ignored` | No match | Received; no rule answers it |+| `queued` | Waiting, or Held | Waiting to send; Held when its account is paused |+| `processing`, `sending` | Sending | A run holds it |+| `retry_wait` | Trying again | Waiting for a retry, a cooldown or an hourly limit |+| `accepted` | Accepted by Instagram | Instagram took the reply |+| `failed` | Failed | Instagram refused it, or it failed 5 times |+| `needs_review` | Needs review | It may have been sent; check before retrying |+| `skipped` | Skipped | Rule off, recipient limit, or already answered |+| `expired` | Expired | The 7 days ran out first |++## Limits and Controls++| Scope | Default | Set with |+|---|---|---|+| Instance, per hour | 1,000 | `AUTOMATION_GLOBAL_HOURLY_LIMIT` |+| User, per hour | 500 | `AUTOMATION_USER_HOURLY_LIMIT` |+| Instagram account, per hour | 200 (Instagram allows 750) | `AUTOMATION_ACCOUNT_HOURLY_LIMIT`, at most 750 |+| Rule, per hour | none | the rule's hourly limit, 1 to 750 |+| Person, per day per account | 3 replies | `AUTOMATION_RECIPIENT_DAILY_LIMIT` |+| Replies per webhook request or sweep | 10 | `AUTOMATION_BATCH_SIZE`, at most 15 |++| Control | Effect |+|---|---|+| `AUTOMATION_PAUSED=true` | Nothing is sent on the instance; comments are still stored and matched |+| Pause an account (Replies switch) | Its replies are held and go out when resumed, within the 7 days |+| Turn a rule off | New comments stop matching it; its waiting replies are skipped |+| Retry an item | Puts a failed, skipped or review item back in the queue and starts it at once |++The batch cap of 15 comes from the Workers Free plan's 50 subrequests per invocation: each reply costs three (reserve, send, finish), plus the claim and the intake queries.++## Response Time++- Normally a few seconds: Meta delivers the webhook, the Worker stores it and sends the reply right after answering.+- Up to 5 minutes for a reply that waits for the sweep (more than the batch in one notification, or a webhook that stopped early), and up to 10 when a quarter-hour run also published posts.+- Longer only while a limit, a cooldown, a pause or Meta's own delivery delay holds it.++## Data Kept and Removed++| Data | Kept | Removed |+|---|---|---|+| Matched comments: text, author, status, reply id | 90 days | Daily retention; also when the account or user is removed |+| Unmatched comments | 90 days, without text or author | Same |+| Reply attempts | With their comment | With their comment |+| Rules, account controls | Until deleted | With the account |+| Audit events | 1 year | Daily retention; with the user |++Logs carry ids, statuses and error codes, never tokens, secrets or comment text.++## Costs++Everything runs on the existing Worker, Supabase project and Workers Free plan; nothing new is billed. Each comment costs one webhook request and, when matched, about four database calls and one Instagram request. The Workers Free plan allows 100,000 requests a day; webhook deliveries count against it, and the 288 five minute cron runs a day are a small share even counted as requests. Past the daily allowance the free plan refuses requests rather than billing them, and Meta retries a refused webhook for 36 hours. Cloudflare Queues, KV and D1 are not used. Recheck Cloudflare's and Supabase's pricing pages before relying on these numbers.++## Files++| Layer | File |+|---|---|+| Routes | `routes/instagramWebhookRoutes.ts` (public), `routes/automationRoutes.ts` |+| Middleware | `middleware/metaWebhook.ts` |+| Controllers | `controllers/instagramWebhookController.ts`, `controllers/automationController.ts`, `inBackground()` in `controllers/http.ts` |+| Validators | `validators/instagramWebhookValidators.ts`, `validators/automationValidators.ts` |+| Services | `services/automationWebhookService.ts`, `services/automationProcessor.ts`, `services/automationService.ts`, `services/retentionService.ts` |+| Platform | `services/instagram/instagramMessaging.ts` |+| Rules | `lib/automationMatching.ts`, `lib/automationDelivery.ts`, `lib/metaWebhookSignature.ts` |+| Repositories | `repositories/automationRuleRepository.ts`, `automationCommentRepository.ts`, `automationAccountRepository.ts`, `auditRepository.ts` |+| Database | `supabase/migrations/20261016100000` to `20261016101000` |+| App | `frontend/src/features/automations/` |diff --git a/docs/architecture/data-flows/SCHEDULING.md b/docs/architecture/data-flows/SCHEDULING.mdindex a1eb6da..586bdd1 100644--- a/docs/architecture/data-flows/SCHEDULING.md+++ b/docs/architecture/data-flows/SCHEDULING.md@@ -8,7 +8,7 @@ Both schedulers follow the same rules from `backend/lib/scheduledPublishing.ts`:## System A: Cloudflare Worker Cron-**Trigger:** `*/15 * * * *` cron in `wrangler.toml`+**Trigger:** the `*/5 * * * *` cron in `wrangler.toml`, on its runs at minutes 0, 15, 30 and 45 (`cronPlan()`; the other runs send comment replies)**Handler:** `backend/jobs/scheduled.ts` -> `runScheduledJob()` -> `scheduledPublisher.publishDue()` in `backend/services/scheduledPublisher.ts`**Deadline:** 14 minutes (the cron context's signal, under the Worker's 15 minute limit for scheduled events)**Supabase client:** service-role (created from Worker env)diff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.mdindex 7a89dac..54a06ae 100644--- a/docs/architecture/database/SCHEMA.md+++ b/docs/architecture/database/SCHEMA.md@@ -2,11 +2,11 @@## Overview-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.+Supabase (PostgreSQL 17) with nine application tables: the four original ones, the four comment automation tables (`automation_accounts`, `automation_rules`, `automation_comments`, `automation_attempts`) and `audit_events`. 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** 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.+The cron jobs (`scheduledPublisher.publishDue()`, `tokenRefresh.refreshExpiringInstagramTokens()`, the automation sweep and the retention purge) and the Instagram webhook intentionally use the repository methods without a `userId` filter to operate across all users.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`.@@ -36,6 +36,9 @@ The first four files are baselines. Each recreates one table as it stood before| 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 |+| 10 | `create_automation_accounts`, `create_automation_rules`, `create_automation_comments`, `create_automation_attempts`, `create_audit_events` | The automation and audit tables, each with its constraints, row level security, trigger and indexes |+| 11 | `index_accounts_instagram_user` | The webhook's lookup of an account by its Instagram id |+| 12 | `create_automation_rules_for_ig_user_function`, `create_claim_automation_comments_function`, `create_reserve_automation_send_function`, `create_finish_automation_send_function`, `create_automation_stats_function` | The automation functions below |To change the schema, follow `docs/features/NEW_DATABASE_TABLE.md` (Write the Migration). The commands are in `docs/workflows/DEPLOYMENT.md`.@@ -286,6 +289,102 @@ Data is fetched on create and on manual refresh only. Not re-fetched on every GE---+## Comment Automation Tables++The data flow is in `docs/architecture/data-flows/AUTOMATION.md`. Every table references its account with the composite `(account_id, user_id)` foreign key to `accounts (id, user_id)` on delete cascade, so removing an Instagram account removes its rules, controls, comments and attempts.++### Table: `automation_accounts`++One row per Instagram account whose automation was paused, subscribed or cooled down; an account without a row has the defaults.++| Column | Type | Constraints | Description |+|---|---|---|---|+| `account_id` | text | primary key, part of the account foreign key | The Twiligent account |+| `user_id` | uuid | not null, references `auth.users` on delete cascade | Owner |+| `paused` | boolean | not null, default false | Replies are held while true |+| `paused_reason` | text | at most 200 characters | Null when the owner paused it; set when the Worker held replies because Instagram refused the token |+| `cooldown_until` | timestamptz | | No reply is sent before this time; set from Instagram rate limits and blocks, and only ever moved later |+| `cooldown_reason` | text | at most 200 characters | Shown on the page |+| `subscribed_at` | timestamptz | | When Instagram confirmed it sends this account's comments to the webhook |+| `created_at`, `updated_at` | timestamptz | not null, default now() | |++### Table: `automation_rules`++| Column | Type | Constraints | Description |+|---|---|---|---|+| `id` | text | primary key | `newRowId()` |+| `user_id`, `account_id` | uuid, text | not null, composite foreign key | Owner and Instagram account |+| `name` | text | 1 to 80 characters | |+| `keywords` | text[] | 1 to 10 items | Matched as whole words or as the whole comment |+| `match_mode` | text | `contains` or `exact`, default `contains` | |+| `case_sensitive` | boolean | not null, default false | |+| `media_ids` | text[] | not null, default `{}`, at most 50 | Empty means every post and reel |+| `reply_text` | text | 1 to 1,000 characters | The service also checks text plus link against Instagram's 1,000 bytes |+| `link_url` | text | null or `^https://` | Added on its own line after the text |+| `enabled` | boolean | not null, default false | |+| `hourly_limit` | integer | null or 1 to 750 | Replies an hour for this rule |+| `created_at`, `updated_at` | timestamptz | not null, default now() | |++### Table: `automation_comments`++Every comment the webhook delivered for an account with an enabled rule. A matched comment is also the job that sends its reply.++| Column | Type | Constraints | Description |+|---|---|---|---|+| `id` | text | primary key | `newRowId()` |+| `user_id`, `account_id` | uuid, text | not null, composite foreign key | The member whose rule (or oldest account) owns it |+| `rule_id` | text | references `automation_rules` on delete set null | The matched rule; null when none matched |+| `ig_user_id` | text | not null | The professional account the webhook named |+| `comment_id` | text | not null; `unique (ig_user_id, comment_id)` | Refuses a notification Meta delivered again |+| `media_id`, `from_id` | text | | The post and the commenter's Instagram-scoped id |+| `from_username`, `text` | text | `text` at most 2,200 characters | Kept only for matched comments |+| `status` | text | not null, one of the values below | |+| `status_reason`, `error_message` | text | `error_message` at most 500 characters | Why it is in its status, for people |+| `attempts` | integer | not null, default 0, at least 0 | Requests sent to Instagram |+| `next_attempt_at` | timestamptz | required while `queued` or `retry_wait` | When it is due |+| `claimed_at` | timestamptz | | When a run took it; the lease is 20 minutes |+| `message_id`, `accepted_at` | text, timestamptz | | Instagram's message id and when it accepted the reply |+| `notified_at`, `expires_at` | timestamptz | not null | When Meta sent it, and 7 days later |+| `created_at`, `updated_at` | timestamptz | not null, default now() | |++`status` is one of `ignored`, `queued`, `processing`, `retry_wait`, `sending`, `accepted`, `failed`, `needs_review`, `skipped`, `expired`. The lifecycle is in `AUTOMATION.md`.++### Table: `automation_attempts`++One row per private reply request sent to Instagram. The hourly and daily limits count these rows.++| Column | Type | Constraints | Description |+|---|---|---|---|+| `id` | text | primary key | `newRowId()`, made before the reservation |+| `user_id`, `account_id` | uuid, text | not null, composite foreign key | |+| `automation_comment_id` | text | not null, references `automation_comments` on delete cascade | |+| `rule_id` | text | references `automation_rules` on delete set null | |+| `recipient_id` | text | | The commenter |+| `outcome` | text | `sending`, `accepted`, `rejected`, `rate_limited`, `ambiguous` | `sending` while the request is out |+| `error_code`, `error_subcode`, `http_status` | integer | | Instagram's answer |+| `started_at`, `finished_at` | timestamptz | `started_at` not null, default now() | |+| `created_at`, `updated_at` | timestamptz | not null, default now() | |++---++## Table: `audit_events`++Who connected, reconnected or removed an account, changed a rule, paused or subscribed an account, or retried a reply. Rows reference only the user, so they outlive the account they describe.++| Column | Type | Constraints | Description |+|---|---|---|---|+| `id` | text | primary key | `newRowId()` |+| `user_id` | uuid | not null, references `auth.users` on delete cascade | |+| `action` | text | `^[a-z_]+\.[a-z_]+$` | `account.connected`, `account.reconnected`, `account.removed`, `automation_rule.created`, `.updated`, `.duplicated`, `.deleted`, `automation_account.paused`, `.resumed`, `.subscribed`, `automation_comment.retried` |+| `subject_type` | text | `account`, `automation_rule`, `automation_account`, `automation_comment` | |+| `subject_id` | text | | |+| `details` | jsonb | not null, default `{}`, an object | Small facts such as the platform or the changed field names; never tokens or comment text |+| `created_at`, `updated_at` | timestamptz | not null, default now() | |++Retention: the daily cron deletes comments (and their attempts) older than 90 days and audit events older than 365 days.++---+## Why CHECK Constraints, Not EnumsAllowed 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.@@ -303,6 +402,17 @@ An index exists because a frequent query filters or orders on its columns. Each| `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` |+| `accounts_instagram_user_idx` | `accounts ((data ->> 'igUserId')) where platform = 'instagram'` | `automation_rules_for_ig_user`: the accounts a webhook names | An expression index, since the id lives in `data` |+| `automation_rules_user_id_created_at_idx` | `automation_rules (user_id, created_at, id)` | `automationRules.listForUser` | |+| `automation_rules_enabled_account_idx` | `automation_rules (account_id) where enabled` | The webhook's rule lookup | Partial: only enabled rules are read |+| `automation_comments_due_idx` | `automation_comments (next_attempt_at) where status in ('queued', 'retry_wait')` | `claim_automation_comments`: due jobs | Partial, so the growing history is left out |+| `automation_comments_claimed_idx` | `automation_comments (claimed_at) where status in ('processing', 'sending')` | The claim's lease recovery | Partial |+| `automation_comments_user_id_created_at_idx` | `automation_comments (user_id, created_at desc)` | `automationComments.listForUser`, `automation_stats` | |+| `automation_comments_rule_id_idx` | `automation_comments (rule_id) where rule_id is not null` | Removing a rule (set null), stats by rule | |+| `automation_comments_created_at_idx` | `automation_comments (created_at)` | The daily retention delete | |+| `automation_attempts_*_started_at_idx` | `(started_at)`, `(user_id, started_at)`, `(account_id, started_at)`, `(rule_id, started_at)`, `(account_id, recipient_id, started_at)` | `reserve_automation_send`: sends in the last hour per scope, and per recipient in the last day | One per limit the reservation counts |+| `automation_attempts_comment_idx` | `automation_attempts (automation_comment_id)` | Finishing and recovering one comment's attempt; the cascade | |+| `audit_events_user_id_created_at_idx`, `audit_events_created_at_idx` | `(user_id, created_at desc)`, `(created_at)` | Listing a user's events; the retention delete | |The primary keys serve every lookup by `id`, and `settings` is read through its `(user_id, key)` primary key.@@ -329,6 +439,12 @@ Every function sets `search_path = ''` and names its tables with the schema. Fun| `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 |+| `automation_rules_for_ig_user(p_ig_user_id)` | sql, stable | The enabled rules of every connected account with that Instagram id, oldest account first |+| `claim_automation_comments(p_limit, p_per_account, p_lease_seconds, p_ids)` | plpgsql | Marks `sending` jobs past the lease `needs_review` (their attempts `ambiguous`), then claims due jobs with `for update skip locked`, at most `p_per_account` per account, rechecking the status on each locked row. Returns each job with its rule's reply and the account's token |+| `reserve_automation_send(p_id, p_attempt_id, p_global_limit, p_user_limit, p_account_limit, p_recipient_limit)` | plpgsql | Under `pg_advisory_xact_lock`, checks pause, cooldown, the recipient's daily replies and the hourly limits per rule, account, user and instance; on success moves the job to `sending` and inserts the attempt. Returns `outcome` and, for a full scope, `retry_at` |+| `finish_automation_send(p_id, p_attempt_id, p_status, p_outcome, ...)` | plpgsql | Settles a `sending` job (or an interrupted one) and its attempt in one transaction, and sets the account's cooldown or hold when asked. Returns `false` and changes nothing when the job was already settled |+| `automation_stats(p_user_id, p_from, p_to, p_account_id, p_rule_id)` | sql, stable | Comment counts by status and attempt counts by outcome for a period, as jsonb |+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.@@ -381,6 +497,28 @@ patchDataForUser(id, patch: Record<string, unknown>, userId): Promise<void> // mdeleteForUser(id, userId): Promise<void>```+```ts+// Automation rules (automationRuleRepository.ts)+listForUser(userId) / findForUser(id, userId) / create(rule, userId) / updateForUser(id, changes, userId) / deleteForUser(id, userId)+listEnabledForInstagramUser(igUserId): Promise<WebhookRule[]> // webhook only - automation_rules_for_ig_user, every user++// Automation comments (automationCommentRepository.ts)+insertMany(comments): Promise<NewAutomationComment[]> // webhook only - upsert, ignoring duplicates; returns the new ones+claim(options) / reserve(id, attemptId, limits) / finish(id, attemptId, plan) / release(id, plan) // processor only, every user+listForUser(userId, filter) / findForUser(id, userId) / requeueForUser(id, userId) / releaseHeldForAccount(accountId, userId)+statsForUser(userId, filter): Promise<AutomationStats> // automation_stats+deleteCreatedBefore(cutoff): Promise<number> // daily retention only++// Automation account controls (automationAccountRepository.ts)+listForUser(userId) / findForUser(accountId, userId) / setPausedForUser(accountId, userId, paused) / markSubscribedForUser(accountId, userId)++// Audit events (auditRepository.ts)+recordForUser(userId, event): Promise<void>+deleteCreatedBefore(cutoff): Promise<number> // daily retention only+```++Rules and controls are plain columns, so their repositories update columns directly; only `data` jsonb needs the merge functions.+The Redis analytics cache has its own repository, `analyticsCacheRepository.ts`; see `docs/architecture/backend/CACHING.md`.## Adding a New Tablediff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.mdindex 84be526..a5e53ee 100644--- a/docs/architecture/database/SECURITY.md+++ b/docs/architecture/database/SECURITY.md@@ -8,7 +8,7 @@ The backend uses the **service-role key** for all database operations. This 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 (`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).+**This means a missing `.eq('user_id', userId)` call is a security bug.** The centralization of all queries in `backend/repositories/` makes this auditable: a method that takes a `userId` ends in `ForUser`, and the few that reach every user (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `claim`, and for comment automation `listEnabledForInstagramUser`, `insertMany`, the queue methods `claim`, `reserve`, `finish` and `release`, and the retention `deleteCreatedBefore`) are used only by the cron services, the Instagram webhook and the reply processor. Because ownership is a query filter, another user's record is simply not found (404).The merge functions follow the same rule: the `...ForUser` repository methods pass the verified `userId` as `p_user_id`, and only `updateById` passes `null`, the cron form that reaches any user's row.@@ -17,7 +17,9 @@ The merge functions follow the same rule: the `...ForUser` repository methods paA 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.+2. **In the database.** `scheduled_posts`, `tracked_posts` and the four automation tables 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.++An automation rule is created only after `accounts.findForUser(accountId, userId)` returns one of the user's Instagram accounts (404 otherwise), and a rule never moves to another account. Pausing, subscribing and retrying load the account or the item with the user's id first.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.@@ -44,14 +46,14 @@ 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 |+| Row level security on, with no policies | `baseline_<table>` (four files) and each `create_<table>` file | The `anon` and `authenticated` roles match no row |+| No grants to the browser roles | `revoke_browser_access_<table>` (four files) and each `create_<table>` file | `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` |+| Functions closed | each `create_*_function` file | `revoke execute ... from public, anon, authenticated`; the merge and automation functions are granted only to `service_role` |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.-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`.+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 nine tables and for `POST /rest/v1/rpc/merge_account_data` and `POST /rest/v1/rpc/claim_automation_comments`. The manual check is in `docs/workflows/TESTING.md`.### What was wrong before@@ -80,11 +82,20 @@ The Instagram `accessToken` stored in `accounts.data.accessToken` is a long-live3. Only used server-side, by these modules:- Graph API calls: `services/instagram/instagramApi.ts`, `instagramMedia.ts` and `instagramPublishing.ts` (the token is passed in as `access_token`)- Obtaining and storing tokens: `services/instagram/instagramTokens.ts` (long-lived exchange and refresh), `services/instagram/instagramOAuth.ts` (OAuth code exchange), `services/instagramConnectService.ts` (OAuth connect), `services/accountService.ts` and `services/accountFactory.ts` (pasted tokens and new account rows)- - Reading the stored token: `services/publishingService.ts` and `services/scheduledPublisher.ts` (publishing), `services/instagramAnalyticsService.ts` (Instagram analytics and media), `services/accountService.ts` (profile and token refresh), `services/tokenRefreshService.ts` (daily refresh) and `services/overviewService.ts` (overview cache warm-up)+ - Reading the stored token: `services/publishingService.ts` and `services/scheduledPublisher.ts` (publishing), `services/instagramAnalyticsService.ts` (Instagram analytics and media), `services/accountService.ts` (profile and token refresh), `services/tokenRefreshService.ts` (daily refresh), `services/overviewService.ts` (overview cache warm-up), `services/automationService.ts` (webhook subscription) and `services/automationProcessor.ts` (private replies, through `services/instagram/instagramMessaging.ts`, which sends it as a Bearer header)+ - `claim_automation_comments` returns the token to the Worker with each claimed job; the function is granted only to the service role4. The `GET /api/accounts` endpoint passes all accounts through `safeAccount()` before returning**If you add a route that returns account data, you must call `safeAccount()`.** Repositories return full accounts and there is no automatic stripping - it is an explicit step in controllers (and in the services that embed an account in a larger result).+## Instagram Webhook++`POST /api/webhooks/instagram` is public: Meta calls it without a user. `middleware/metaWebhook.ts` refuses a body over 1 MB and checks `X-Hub-Signature-256`, an HMAC-SHA256 of the raw body with the Instagram app secret (or `META_APP_SECRET`), in constant time before anything is parsed or stored. The verification `GET` compares the Verify Token in constant time. A comment is attached to an account only through the Instagram account id Meta signed, and only accounts with an enabled rule store anything. Comments that no rule answers keep neither their text nor their author; matched ones are kept 90 days. Logs carry ids and error codes, never tokens or comment text.++## Audit Events++`audit_events` records connecting, reconnecting and removing accounts, rule changes, pausing and subscribing an account, and retries, with the user, the subject and small details (never tokens or comment text). Rows reference the user only, so they stay after the account is removed, and are deleted after a year or with the user.+## GitHub Settings`settings.value.github` holds only the repository owner, name and branch. No GitHub token is stored; saving the repository deletes a token left by older versions (ADR-031). If a future feature needs a token again, it must never be logged or returned, and the settings route should report only whether one is set.@@ -93,8 +104,9 @@ 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` (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/repositories/` - every user-scoped method ends in `ForUser` and filters by `user_id` (or passes it as `p_user_id` to a merge function); the methods without a `userId` are used only by `scheduledPublisher.ts`, `tokenRefreshService.ts`, `automationWebhookService.ts`, `automationProcessor.ts` and `retentionService.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/middleware/metaWebhook.ts` and `backend/lib/metaWebhookSignature.ts` - the only thing that authenticates the public Instagram webhook- `backend/controllers/` and `backend/services/` - the `userId` passed to a repository always comes from `c.get('userId')`, never from the body or query- `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 themdiff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.mdindex 637f9cc..9cbfbdb 100644--- a/docs/architecture/frontend/API_LAYER.md+++ b/docs/architecture/frontend/API_LAYER.md@@ -121,6 +121,24 @@ Returns `OverviewResponse` from `shared/types/domain.ts`: `{ tracked: TrackedPosThe `analyticsCache` is populated from Redis on the backend; no live API calls are made. Data is only present for accounts whose analytics pages have been previously visited (which populates the Redis cache). The Overview dashboard uses this to compute Total Content, Total Comments, and Total Likes across all platforms without expensive per-account API calls on load.+## Automation Methods++```ts+getAutomations: () => request<AutomationOverviewResponse>('/automations'),+createAutomationRule: (data: AutomationRuleRequest) => request<AutomationRuleResponse>('/automations/rules', { method: 'POST', body: JSON.stringify(data) }),+updateAutomationRule: (id: string, data: AutomationRuleUpdateRequest) => request<AutomationRuleResponse>(`/automations/rules/${id}`, { method: 'PUT', body: JSON.stringify(data) }),+duplicateAutomationRule: (id: string) => request<AutomationRuleResponse>(`/automations/rules/${id}/duplicate`, { method: 'POST' }),+deleteAutomationRule: (id: string) => request<SuccessMessageResponse>(`/automations/rules/${id}`, { method: 'DELETE' }),+testAutomationRule: (data: AutomationTestRequest) => request<AutomationTestResponse>('/automations/test', { method: 'POST', body: JSON.stringify(data) }),+getAutomationActivity: (query: URLSearchParams) => request<AutomationActivityResponse>(`/automations/activity?${query}`),+retryAutomationActivity: (id: string) => request<AutomationActivityItemResponse>(`/automations/activity/${id}/retry`, { method: 'POST' }),+getAutomationStats: (query: URLSearchParams) => request<AutomationStatsResponse>(`/automations/stats?${query}`),+setAutomationAccountPaused: (accountId: string, paused: boolean) => request<AutomationAccountResponse>(`/automations/accounts/${accountId}`, { method: 'PUT', body: JSON.stringify({ paused }) }),+subscribeAutomationAccount: (accountId: string) => request<AutomationAccountResponse>(`/automations/accounts/${accountId}/subscribe`, { method: 'POST' }),+```++The types are in `shared/types/automation.ts`. Activity and stats take their filters as `URLSearchParams` (`accountId`, `ruleId`, `status` as a comma-separated list, `from`, `to`, `before`, `limit`), built in `features/automations/useAutomationActivity.ts`. An accepted reply means Instagram took the request; the API reports nothing about delivery or reading.+## Tracked Content MethodsAdded to the `api` object in `api.ts`. Handles both Reddit posts and YouTube videos:diff --git a/docs/architecture/frontend/DESIGN_SYSTEM.md b/docs/architecture/frontend/DESIGN_SYSTEM.mdindex cfb76f3..27f0877 100644--- a/docs/architecture/frontend/DESIGN_SYSTEM.md+++ b/docs/architecture/frontend/DESIGN_SYSTEM.md@@ -35,6 +35,8 @@ Shared components live in `frontend/src/components/`. Reach for these before wri| `MetricBox` | A single metric: icon, label, tabular value, one line of context. `highlight` marks the page's lead metric || `SectionHeader` | A heading between groups of boxes || `ListRow`, `RankNumber` | Dense clickable rows and mono rank numbers |+| `RowAction` | An icon button with a tooltip at the end of a table or list row; `danger` for removal |+| `AccountSelect` | Choosing one Instagram account, with its avatar and handle || `SearchField`, `FilterChips` | Library search and single-select filters || `Pager` | Previous and next with a count || `MediaCard`, `MediaChip` | Thumbnail cards for videos, Shorts and Instagram media |diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.mdindex df39c78..402fa50 100644--- a/docs/architecture/frontend/FEATURES.md+++ b/docs/architecture/frontend/FEATURES.md@@ -9,6 +9,8 @@ frontend/src/│ ├── MetricAreaChart.tsx <- Shared Recharts area chart for single-metric comparisons│ ├── ChartPanel.tsx <- Titled chart container with an empty state│ ├── ImageLightbox.tsx <- Thumbnail that opens the full image in a Dialog+│ ├── AccountSelect.tsx <- Instagram account picker with avatars (Publish, Automations)+│ ├── RowAction.tsx <- Icon button with a tooltip for table and list rows (Tracked content, Automations)│ └── DocsRedirect.tsx <- The /docs/* route: replaces the location with the same page on the public docs├── lib/│ └── docs.ts <- DOCS_URL and docsUrl(path): links from the app to the public docs@@ -47,7 +49,7 @@ frontend/src/│ │ └── tracked/│ │ ├── TrackedContent.tsx <- Page: tracked Reddit posts and YouTube videos│ │ ├── TrackedMetrics.tsx, TrackedFilters.tsx, BulkCategoryBar.tsx, TrackedTable.tsx, TrackedRow.tsx, TrackedThumbnail.tsx-│ │ ├── AddTrackedDialog.tsx, EditTrackedDialog.tsx, TrackedImageField.tsx, CategoryPicker.tsx, RowAction.tsx+│ │ ├── AddTrackedDialog.tsx, EditTrackedDialog.tsx, TrackedImageField.tsx, CategoryPicker.tsx│ │ ├── useTrackedItems.ts, useTrackedFilters.ts, useTrackedSelection.ts, useBulkCategory.ts│ │ ├── useTrackedDelete.ts, useAddTracked.ts, useTrackedEditor.ts <- Delete, add form, edit and image upload│ │ ├── trackedList.ts <- Pure sort, filter, stats and form helpers (trackedList.test.ts)@@ -73,7 +75,7 @@ frontend/src/│ │ ├── BulkFileList.tsx, BulkFileItem.tsx, BulkResults.tsx, BulkSettings.tsx, BulkScheduleFields.tsx│ │ ├── ScheduledPostsSection.tsx <- Scheduled post table with filters and the overdue alert│ │ ├── ScheduledPostRow.tsx, ScheduledPostEditRow.tsx, ScheduledPostDialogs.tsx, OverdueAlert.tsx-│ │ ├── AccountSelect.tsx, TypePicker.tsx, ScheduleToggle.tsx, ScheduleHint.tsx, IconInput.tsx, StatusBadge.tsx, NoInstagramAccount.tsx+│ │ ├── TypePicker.tsx, ScheduleToggle.tsx, ScheduleHint.tsx, IconInput.tsx, StatusBadge.tsx, NoInstagramAccount.tsx│ │ ├── useSinglePostForm.ts, useSinglePostMedia.ts <- Single post fields, file and cover│ │ ├── useSinglePublish.ts, usePublishProgress.ts <- Single post publish or schedule run│ │ ├── useBulkSettings.ts, useBulkQueue.ts, useBulkPublish.ts <- Bulk settings, file queue, upload loop@@ -82,6 +84,15 @@ frontend/src/│ │ ├── singlePostFlow.ts <- Single post Cloudinary upload, then publish or schedule│ │ ├── publishConstants.ts <- Content types, statuses, intervals, caption limit│ │ └── publishHelpers.ts, scheduleHelpers.ts, queueHelpers.ts <- Pure helpers with *.test.ts+│ ├── automations/+│ │ ├── Automations.tsx <- Page: server notices, counts, account controls, rules, activity, the rule dialog+│ │ ├── AutomationNotices.tsx <- Webhook not set up, or replies paused on the server+│ │ ├── AutomationMetrics.tsx, AutomationAccounts.tsx, AutomationRules.tsx, AutomationActivity.tsx+│ │ ├── RuleDialog.tsx, RuleMediaPicker.tsx, RulePreview.tsx <- Rule form, post picker, reply preview and keyword test+│ │ ├── useAutomations.ts <- Overview and every rule and account action, with toasts+│ │ ├── useAutomationActivity.ts <- Filters, counts, activity pages and retry+│ │ ├── useRuleForm.ts <- Rule dialog state, the account's posts, the test call+│ │ └── automationData.ts <- Pure status labels, filters, summary, form conversion and checks (automationData.test.ts)│ ├── settings/│ │ ├── Settings.tsx <- Page: loads server settings, then renders each section; keeps the #hash scroll│ │ ├── SettingsSection.tsx, AppearanceSection.tsx, PasswordSection.tsx, ServerKeysSection.tsx, SchedulingSection.tsx@@ -210,6 +221,7 @@ Each page manages its own loading/data/error state. Pages do not write to `AppCo| Tracked Category | `/tracked-content/category/:name` | Detailed per-category analytics; YouTube section (views, likes, comments, bar chart, table) and Reddit section (score, ratio, comments, bar chart, table) rendered separately || Video Explorer | `/videos/:id` | YouTube video library with search and sort || Publish | `/upload` | Publish or schedule to Instagram, bulk upload, and the scheduled post queue |+| Automations | `/automations` | Keyword rules that answer Instagram comments with a private reply, account pause and comment events, counts and the reply activity with retry (`docs/architecture/data-flows/AUTOMATION.md`) || Settings | `/settings` | Theme, server key status, who sets up scheduling, the optional GitHub backup guide || Documentation | `/docs/*` | Not a page in the app: `DocsRedirect` sends the visitor to the same path on the public docs at `https://twiligent.ujjwal.fyi/docs`. The Documentation item in the sidebar user menu and Open documentation in the command palette open the docs in a new tab |diff --git a/docs/architecture/frontend/ROUTING.md b/docs/architecture/frontend/ROUTING.mdindex ee05fdd..4960227 100644--- a/docs/architecture/frontend/ROUTING.md+++ b/docs/architecture/frontend/ROUTING.md@@ -12,7 +12,7 @@ The app uses React Router v6 in `frontend/src/App.tsx`. The router uses `Browser| `/docs/*` | `components/DocsRedirect.tsx` | Public. The docs live on the public site; this route replaces the location with the same path and hash under `https://twiligent.ujjwal.fyi/docs` (`docsUrl()` in `lib/docs.ts`), so old links keep working || `/` (layout) | `AppLayout` (inline) | Protected - redirects to `/login` if unauthenticated || `/` (index) | `Overview.tsx` | Default page after login |-| `/accounts` | `AccountManager.tsx` | Connect and remove accounts. `?add=1` opens the add flow; `?ig_connected` and `?ig_error` report the Instagram OAuth result |+| `/accounts` | `AccountManager.tsx` | Connect and remove accounts. `?add=1` opens the add flow; `?ig_connected` (`true`, or `reconnected` when the account was already there) and `?ig_error` report the Instagram OAuth result || `/channel/:id` | `ChannelAnalytics.tsx` | `:id` = account.id for YouTube accounts || `/instagram/:id` | `InstagramAnalytics.tsx` | `:id` = account.id for Instagram accounts || `/reddit/:id` | `RedditAnalytics.tsx` | `:id` = account.id for Reddit accounts |@@ -25,6 +25,7 @@ The app uses React Router v6 in `frontend/src/App.tsx`. The router uses `Browser| `/shorts` | `ShortsExplorer.tsx` | Videos of 60 seconds or less || `/reels` | `ReelsExplorer.tsx` | Instagram reels, posts and videos || `/upload` | `UploadContent.tsx` | Publish and schedule to Instagram, plus the scheduled post queue |+| `/automations` | `features/automations/Automations.tsx` | Comment-to-DM rules, account controls and reply activity; in the sidebar under Publishing || `/settings` | `Settings.tsx` | User/platform settings |## Auth Guarddiff --git a/docs/features/NEW_SCHEDULED_TASK.md b/docs/features/NEW_SCHEDULED_TASK.mdindex d22b566..b2fe2b0 100644--- a/docs/features/NEW_SCHEDULED_TASK.md+++ b/docs/features/NEW_SCHEDULED_TASK.md@@ -65,44 +65,31 @@ Add it to `Services` and `createServices()` in `backend/container.ts`:myPlatformTokenRefresh: createMyPlatformTokenRefreshService({ accounts, context }),```-### Step 2: Register the Trigger in `wrangler.toml`+### Step 2: Choose a Run on an Existing Trigger-```toml-[triggers]-crons = [- "*/15 * * * *", # existing: scheduledPublisher.publishDue()- "0 0 * * *", # existing: tokenRefresh.refreshExpiringInstagramTokens()- "30 3 * * *" # new: myPlatformTokenRefresh.refreshTokens() (runs at 3:30 AM UTC daily)-]-```--**Important:** every cron trigger calls the same `scheduled()` handler exported from `backend/server.ts`, which hands the expression to `runScheduledJob()` in `backend/jobs/scheduled.ts`. When you add a new cron string, you must also handle it there.--### Step 3: Dispatch in `jobs/scheduled.ts`+The Workers Free plan allows five cron triggers per Cloudflare account, and the project's account uses all five, so a new job runs on one of the Worker's two triggers (`*/5 * * * *` and `0 0 * * *`) at the times `cronPlan()` gives it, not on a new trigger. A daily job belongs on the daily trigger:```ts// backend/jobs/scheduled.ts-export const PUBLISH_DUE_POSTS_CRON = '*/15 * * * *';-export const REFRESH_TOKENS_CRON = '0 0 * * *';-export const REFRESH_MY_PLATFORM_TOKENS_CRON = '30 3 * * *';--export async function runScheduledJob(cron: string, env: Env): Promise<void> {- const context = cronContext(cron);- const services = createServices({ supabase: getSupabase(env), redis: getRedis(env) }, readConfig(env), context);-- if (cron === PUBLISH_DUE_POSTS_CRON) {- // ...- } else if (cron === REFRESH_TOKENS_CRON) {- await services.tokenRefresh.refreshExpiringInstagramTokens();- } else if (cron === REFRESH_MY_PLATFORM_TOKENS_CRON) {- await services.myPlatformTokenRefresh.refreshTokens();- } else {- context.log.warn('no job for this cron', { cron });- }+} else if (plan === 'daily') {+ await services.tokenRefresh.refreshExpiringInstagramTokens();+ await services.retention.purge();+ await services.myPlatformTokenRefresh.refreshTokens();}```-`event.cron` is the exact cron string from `wrangler.toml`, so the strings must match character for character. `server.ts` already wraps the job in `ctx.waitUntil()`, and the cron context gives it a `cron-` request id and a 14 minute deadline. Add a test in `backend/tests/services/` with fake repositories or the fake Supabase client (see `tokenRefreshService.test.ts`), and run `npm run typecheck` before deploying.+A job that should run less often gets its own plan from the scheduled time, for example weekly on Mondays: `if (cron === DAILY_CRON) return new Date(scheduledTime).getUTCDay() === 1 ? 'daily_and_weekly' : 'daily';`. Keep each run under its 50 subrequests on the free plan; a job that needs many calls should spread them over several runs.++### Step 3: Add a Trigger Only When There Is a Slot++On an account with a free slot, or on Workers Paid (250 triggers), a job may get its own trigger instead:++```toml+[triggers]+crons = ["*/5 * * * *", "0 0 * * *", "30 3 * * *"]+```++Every cron trigger calls the same `scheduled()` handler exported from `backend/server.ts`, which hands the expression to `runScheduledJob()`. Add a constant for the new expression in `backend/jobs/scheduled.ts`, return a new plan for it from `cronPlan()`, and run the job in that branch. `event.cron` is the exact cron string from `wrangler.toml`, so the strings must match character for character; `backend/tests/jobs/scheduled.test.ts` checks the list. `server.ts` already wraps the job in `ctx.waitUntil()`, and the cron context gives it a `cron-` request id and a 14 minute deadline. Add a test in `backend/tests/services/` with fake repositories or the fake Supabase client (see `tokenRefreshService.test.ts`), and run `npm run typecheck` before deploying.### Step 4: Test Locallydiff --git a/docs/guidelines/CODE_STYLE.md b/docs/guidelines/CODE_STYLE.mdindex c2b2700..c06f39a 100644--- a/docs/guidelines/CODE_STYLE.md+++ b/docs/guidelines/CODE_STYLE.md@@ -79,7 +79,9 @@ 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.+- Redis code catches every failure and falls back; nothing else swallows errors, with two exceptions that log instead: a job that works through many items (the scheduled publisher, the reply processor, the token refresh) catches one item's failure and moves on, and a secondary step after the main write (subscribing an account when a rule is turned on) is logged with `context.log.warn` so the main result still stands.+- A platform call whose every failure leads somewhere different may answer a result union instead of throwing (`sendPrivateReply` returns `{ kind: 'accepted' | 'error' | 'ambiguous' | 'not_sent' }`); the decision table lives in a pure `lib/` helper (`finishPlan` in `lib/automationDelivery.ts`) with its tests.+- Work after a response goes through `inBackground(c, label, work)` in `controllers/http.ts`, which gives it its own deadline, never `c.executionCtx.waitUntil()` with the request's services.- 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).diff --git a/docs/philosophy/SECURITY.md b/docs/philosophy/SECURITY.mdindex 2f11367..03f2613 100644--- a/docs/philosophy/SECURITY.md+++ b/docs/philosophy/SECURITY.md@@ -7,7 +7,9 @@| 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** |+| Instagram App Secret | Worker secret | Worker only (OAuth, state signing, and verifying Instagram webhooks) | **Never** |+| Instagram webhook verify token (`INSTAGRAM_WEBHOOK_VERIFY_TOKEN`) | Worker secret, and the Meta dashboard's webhook settings | Worker (compares) and Meta (sends once) | **Never** |+| Meta app secret (`META_APP_SECRET`, optional) | Worker secret | Worker (a second key for webhook signatures) | **Never** || YouTube API key | Worker secret | Worker only | **Never** || Cloudinary credentials | Worker secrets | Worker only | **Never** || Send Email hook secret (`SEND_EMAIL_HOOK_SECRET`) | Worker secret, and Supabase's hook settings | Worker (verifies) and Supabase Auth (signs) | **Never** |@@ -94,6 +96,18 @@ Without a valid signature nobody can make the Worker send email or read the codeThe caps also protect the free email quota. There are 100 emails a day by default and 5 a day to one address, and a refused send counts nothing, so repeated requests for one address cannot use up the day. Supabase's own email rate limit and CAPTCHA add protection against many addresses at once (see the self-hosting page `self-host/email-codes`).+## Instagram Webhook++`POST /api/webhooks/instagram` is public because Meta, not a browser, calls it. Its only proof of origin is `X-Hub-Signature-256`, HMAC-SHA256 over the raw body with the Instagram app secret (or `META_APP_SECRET`):++1. A body over 1 MB is refused before the signature is computed.+2. The Worker recomputes the signature over the exact bytes it received and compares it in constant time (`crypto.subtle.verify`); without a secret the route answers 503.+3. A comment is attached only to the accounts whose Instagram id the signed payload names, and only when such an account has an enabled rule; nothing in the payload can point a reply at another member's account.++Meta's notifications carry no timestamp, so a captured notification could be sent again; that is harmless, because each comment is stored once and Instagram allows one private reply per comment. The verification `GET` compares the Verify Token in constant time. Comment text is kept only for comments a rule answers, for 90 days, and never logged.++The replies themselves are limited in the database per instance, member, account, rule and recipient, so a flood of comments, a bug or a misconfigured rule cannot turn into a stream of messages (`docs/architecture/data-flows/AUTOMATION.md`). A reply whose outcome is unknown is never sent again without a person's decision.+## Rate LimitingEvery `/api` request is rate limited per client IP before authentication, so a flood of invalid tokens never reaches Supabase Auth. Protected requests are also limited per user, and routes that spend the shared YouTube quota or the Instagram and Reddit limits have a tighter per-user rule. Limits are counted atomically in Redis (one Lua script per check) and fall back to per-isolate memory when Redis is absent or failing, so they never fail open entirely and never fail a request. See `docs/architecture/backend/RATE_LIMITING.md`.@@ -130,6 +144,7 @@ If a credential is compromised:3. Instagram App Secret: rotate in Meta Developer dashboard, then update Worker secret4. Supabase service role key: rotate in Supabase project Settings -> API5. Send Email hook secret: generate a new one in Supabase Authentication -> Auth Hooks, then `wrangler secret put SEND_EMAIL_HOOK_SECRET`; Resend API key: create a new key in Resend, update the Worker secret, then delete the old key-6. User Instagram tokens: user must reconnect their account via the OAuth flow+6. User Instagram tokens: the user connects the account again through the OAuth flow, which renews the stored token in place+7. Instagram webhook verify token: `wrangler secret put INSTAGRAM_WEBHOOK_VERIFY_TOKEN` with a new value, then enter the same value in the Meta dashboard's webhook settings and verify againThere is no automated secrets rotation. This is a known gap.diff --git a/docs/workflows/DEPLOYMENT.md b/docs/workflows/DEPLOYMENT.mdindex 1c3451c..039ec16 100644--- a/docs/workflows/DEPLOYMENT.md+++ b/docs/workflows/DEPLOYMENT.md@@ -135,14 +135,21 @@ npx wrangler secret put SEND_EMAIL_HOOK_SECRET # optional; email verificatinpx wrangler secret put RESEND_API_KEY # optionalnpx wrangler secret put EMAIL_FROM # optionalnpx wrangler secret put EMAIL_DAILY_LIMIT # optional; defaults to 100+npx wrangler secret put INSTAGRAM_WEBHOOK_VERIFY_TOKEN # optional; comment-to-DM automation (with INSTAGRAM_APP_SECRET)+npx wrangler secret put META_APP_SECRET # optional; a second key for webhook signatures+npx wrangler secret put AUTOMATION_PAUSED # optional; "true" holds every automated reply```+The `AUTOMATION_*` limits (`ACCOUNT_HOURLY_LIMIT`, `USER_HOURLY_LIMIT`, `GLOBAL_HOURLY_LIMIT`, `RECIPIENT_DAILY_LIMIT`, `BATCH_SIZE`) are optional too; `WORKERS.md` lists their defaults.+Each command prompts for the value (no echo - the value is not shown).`FRONTEND_URL` is also the browser origin the API accepts: CORS answers only `FRONTEND_URL` and the origins listed in `ALLOWED_ORIGINS`. Set `ALLOWED_ORIGINS` when the app is served from more than one address (for example a custom domain and the `pages.dev` address), and update `FRONTEND_URL` when the domain changes, or the browser blocks every API call. Both name the app's address (`https://app.twiligent.ujjwal.fyi` for the project's own instance), not the public site, which makes no API calls.The email secrets only matter once Supabase's Send Email hook points at `https://<worker>/api/auth/email-hook`. Set them before turning the hook on: while the hook is on and the secrets are missing, every sign-up and password reset fails with a 503. The full setup (Resend domain, hook, **Confirm email**, rate limit) is in the public docs at `https://twiligent.ujjwal.fyi/docs/self-host/email-codes` (source: `site/content/docs/self-host/email-codes.mdx`). To check the hook after a deploy, sign up with an address you own and watch `npx wrangler tail` for the `auth email sent` line. Keep Resend's click and open tracking off: its tracking record once took the name `twiligent` and replaced the Pages record for `twiligent.ujjwal.fyi`, which took the site offline until the record was pointed back at `twiligent.pages.dev` (proxied) and the Pages custom domain was reactivated (#37). That name now belongs to the public site; the same care applies to the `app.twiligent` record.+Comment-to-DM automation needs its migrations applied (`npm run db:push`), `INSTAGRAM_WEBHOOK_VERIFY_TOKEN` set, and the webhook added in the Meta dashboard with the callback `https://<worker>/api/webhooks/instagram` and the `comments` field. The app must be Live with Advanced Access for `comments` before comments from accounts without a role on the app arrive. The full setup is in the public docs at `https://twiligent.ujjwal.fyi/docs/self-host/comment-automation` (source: `site/content/docs/self-host/comment-automation.mdx`). To check it after a deploy, comment a keyword on a post of a connected account from another Instagram account and watch `npx wrangler tail` for `instagram webhook stored` and `automation reply settled`. To stop every reply at once, set `AUTOMATION_PAUSED` to `true`.+## Setting GitHub Actions SecretsRequired for `deploy-frontend.yml`, `deploy-backend.yml`, `deploy-site.yml` and `publish-scheduled.yml`:diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.mdindex 757a855..d2d0ae8 100644--- a/docs/workflows/TESTING.md+++ b/docs/workflows/TESTING.md@@ -37,6 +37,17 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that| `frontend/src/lib/accounts.ts` | `frontend/tests/lib/accounts.test.ts` || `frontend/src/lib/apiErrors.ts` | `frontend/tests/lib/apiErrors.test.ts` || `backend/routes/authHookRoutes.ts` | `backend/tests/routes/authHookRoutes.test.ts` |+| `backend/routes/instagramWebhookRoutes.ts` | `backend/tests/routes/instagramWebhookRoutes.test.ts` |+| `backend/routes/automationRoutes.ts` | `backend/tests/routes/automationRoutes.test.ts` |+| `backend/services/automationProcessor.ts` | `backend/tests/services/automationProcessor.test.ts` |+| `backend/services/automationWebhookService.ts` | `backend/tests/services/automationWebhookService.test.ts` |+| `backend/services/retentionService.ts` | `backend/tests/services/retentionService.test.ts` |+| `backend/lib/automationMatching.ts`, `automationDelivery.ts`, `metaWebhookSignature.ts` | `backend/tests/lib/` with the same names |+| `backend/repositories/automationCommentRepository.ts` | `backend/tests/repositories/automationCommentRepository.test.ts` |+| `backend/repositories/automationRuleRepository.ts`, `automationAccountRepository.ts`, `auditRepository.ts` | `backend/tests/repositories/automationRuleRepository.test.ts` |+| `backend/validators/automationValidators.ts`, `instagramWebhookValidators.ts` | `backend/tests/validators/` with the same names |+| `backend/jobs/scheduled.ts` | `backend/tests/jobs/scheduled.test.ts` |+| `frontend/src/features/automations/automationData.ts` | `frontend/tests/features/automations/automationData.test.ts` || `backend/services/authEmailService.ts` | `backend/tests/services/authEmailService.test.ts` || `frontend/src/lib/authErrors.ts` | `frontend/tests/lib/authErrors.test.ts` || `frontend/src/lib/passwords.ts` | `frontend/tests/lib/passwords.test.ts` |@@ -49,7 +60,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/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.+Backend tests are in `backend/tests/database`, `backend/tests/jobs`, `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. The fake also answers `in`, `gte`, `gt` and `limit` (rows come back in stored order, so a test seeds them in the order it expects), inserts and upserts of several rows, and `ignoreDuplicates` upserts that return only the new rows; `fakeSupabase(rows, rpcHandlers)` runs any other database function the test supplies. `fakeFetch.ts` replies can carry headers. `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.@@ -67,6 +78,8 @@ Scheduled publishing recovery has its own tests. `tests/lib/scheduledPublishing.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).+Comment automation has its own tests. `tests/lib/automationMatching.test.ts` covers whole-word and exact matching, case, look-alike characters, literal punctuation in keywords, and that a comment on one reel never triggers a rule for another. `tests/lib/automationDelivery.test.ts` covers the Graph error classes, backoff with jitter, the cooldown from Meta's usage header, and what is recorded for each answer: accepted, rate limited, blocked, temporary errors up to the fifth try, already replied, a refused token (held), not allowed, no answer (needs review), and a request the runtime refused (not sent). `tests/lib/metaWebhookSignature.test.ts` checks signatures with either secret, changed bodies and malformed headers. `tests/fixtures/fakeAutomationQueue.ts` is an in-memory twin of the claim, reserve and finish functions, following the SQL's rules, and `tests/services/automationProcessor.test.ts` runs the processor against it: two comments at once, three reels with their own rules, two runs competing for the same jobs (each reply sent once), a burst over the batch and per-account fairness, a timeout that is never resent, a run that stopped before and during a send, a rate limit cooling one account while another keeps sending, the hourly and per-person limits, five temporary failures, a rule turned off, a deleted reel, an expired comment, a refused token holding the account, the instance pause, a database failure on one job and on the claim, and a run past its deadline. `tests/services/automationWebhookService.test.ts` covers intake: per-reel matching, unmatched comments kept without words, own comments, duplicates within and across notifications, accounts without rules, a failed insert, and the verify token. `tests/routes/instagramWebhookRoutes.test.ts` runs the public route end to end (challenge, signed comment stored then answered, duplicates, either secret, bad signatures, bad bodies, the 1 MB limit, a missing secret, a database failure), and `tests/routes/automationRoutes.test.ts` the user routes, including every route answering 404 for another user's rule, account or item. `tests/fixtures/metaWebhook.ts` signs notifications the way Meta does. The SQL functions cannot run in Node; they were checked on a local Postgres (PGlite) before the first push: deduplication, fair claims and lease recovery, each limit, pause and cooldown, a late answer for an interrupted send, stats, cascades, browser access and every rollback.+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.@@ -199,9 +212,20 @@ Open the app in a browser. For each changed area, test:**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 anon key gets 401 permission denied on every table (including the automation tables and `audit_events`) and on the merge and automation 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+**Comment automation (if the webhook, rules, the processor or the Automations page changed):**+- [ ] `curl -i "<worker>/api/webhooks/instagram?hub.mode=subscribe&hub.verify_token=<token>&hub.challenge=123"` answers `123`; a wrong token answers 403+- [ ] `curl -i -X POST -H "Content-Type: application/json" -d '{"object":"instagram","entry":[]}' <worker>/api/webhooks/instagram` without a signature answers 401 and stores nothing+- [ ] Create a rule on the Automations page, turn it on, and the account shows Receiving comments (or Turn on comment events succeeds)+- [ ] Test a comment in the rule dialog: a matching sample says it matches, a non-matching one says no reply, and nothing is sent+- [ ] From another Instagram account, comment the keyword on a covered post: the private reply arrives within seconds, Activity shows Accepted by Instagram, and `npx wrangler tail` shows `instagram webhook stored` and `automation reply settled` with no token or comment text in any line+- [ ] Comment the same keyword again on a post the rule does not cover: Activity shows No match without the words+- [ ] Turn off Replies for the account, comment again: Activity shows Held; turn it back on and the reply goes out on the next run+- [ ] Set `AUTOMATION_PAUSED=true`: comments are recorded and nothing is sent; remove it and they go out+- [ ] At 375 px and 1280 px in both themes, the page, the rule dialog and the activity table fit, and the table scrolls inside its box+**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`diff --git a/site/content/docs/self-host/comment-automation.mdx b/site/content/docs/self-host/comment-automation.mdxnew file mode 100644index 0000000..fd801da--- /dev/null+++ b/site/content/docs/self-host/comment-automation.mdx@@ -0,0 +1,88 @@+export const meta = { title: 'Comment automation (optional)', description: 'Let Instagram send comments to your backend so automation rules can answer them with a private reply.' }++<Callout type="note" title="How it works">++When someone comments on a post or reel of a connected Instagram account, Meta sends the comment to your backend's webhook. The backend checks Meta's signature, stores the comment, and if a rule's keyword matches, sends the commenter one private reply through Instagram's official messaging API. Instagram allows one private reply per comment, within 7 days of it, and up to 750 an hour per account. Nothing else is needed on Cloudflare: the webhook and the reply queue run on the Worker and the Supabase database you already have.++</Callout>++<Callout type="warning" title="Meta approval comes first">++Comments reach your backend only while the Meta app is **Live** and has **Advanced Access** for the comments webhook field. Advanced Access needs App Review and business verification. Until then, only Instagram accounts with a role on the app (Settings, Roles) get comment events, which is enough to test with your own account.++</Callout>++<Steps>+<Step title="Finish the Instagram app">++Follow [Instagram app](/docs/self-host/instagram) first. Twiligent's sign-in already asks for the permissions comment automation needs: `instagram_business_basic`, `instagram_business_manage_comments` and `instagram_business_manage_messages`. Accounts connected before you set this up do not need to connect again.++</Step>+<Step title="Apply the database migrations">++From the repository root, run `npm run db:check` and then `npm run db:push`. They add the automation tables and functions. See [Supabase](/docs/self-host/supabase) if your CLI is not linked yet.++</Step>+<Step title="Choose a verify token">++The verify token is any long random string you make up; Meta sends it back once to prove it reached your backend. In `backend/`, run:++```bash+npx wrangler secret put INSTAGRAM_WEBHOOK_VERIFY_TOKEN+```++Webhooks are signed with your Instagram app secret, which is already set as `INSTAGRAM_APP_SECRET`. If signatures fail in the logs, also set the Meta app's own secret (Settings, Basic) with `npx wrangler secret put META_APP_SECRET`; the backend accepts either.++</Step>+<Step title="Add the webhook in the Meta dashboard">++Open the app, **Instagram**, **API setup with Instagram business login**, **Configure webhooks**. Set:++| Field | Value |+| --- | --- |+| Callback URL | Your backend address followed by `/api/webhooks/instagram`, for example `https://twiligent-api.example.workers.dev/api/webhooks/instagram` |+| Verify token | The token from the step before |++Choose **Verify and save**. Meta calls the URL once; if it fails, check that the backend is deployed and the secret is set. Then subscribe to the **comments** field.++</Step>+<Step title="Turn on comment events for each account">++In Twiligent, open **Automations**, create a rule and turn it on. The first rule turned on for an account asks Instagram to send that account's comments to your backend. If the account shows **Not receiving comments**, choose **Turn on comment events**. The account must be public: Instagram sends no comment events for private accounts.++</Step>+<Step title="Test it">++From another Instagram account, comment a rule's keyword on one of the account's posts. The private reply should arrive within a few seconds. To follow it, run `npx wrangler tail` in `backend/` and look for `instagram webhook stored` and `automation reply settled`. The comment and its status also appear under **Activity** on the Automations page.++</Step>+</Steps>++## Limits and controls++These Worker settings are optional; each falls back to its default when unset or invalid. Set them with `npx wrangler secret put` so deploys keep them.++| Setting | Default | What it limits |+| --- | --- | --- |+| `AUTOMATION_ACCOUNT_HOURLY_LIMIT` | 200 | Replies an hour from one Instagram account; at most 750, Instagram's limit |+| `AUTOMATION_USER_HOURLY_LIMIT` | 500 | Replies an hour across one member's accounts |+| `AUTOMATION_GLOBAL_HOURLY_LIMIT` | 1000 | Replies an hour across your whole instance |+| `AUTOMATION_RECIPIENT_DAILY_LIMIT` | 3 | Replies a day one person can get from one account |+| `AUTOMATION_BATCH_SIZE` | 10 | Replies sent by one webhook request or one sweep; at most 15 on the Workers Free plan |+| `AUTOMATION_PAUSED` | not set | `true` holds every reply; comments are still recorded and go out when you remove it, within the 7 days |++A reply that misses its first chance waits for the backend's 5 minute schedule, which also retries temporary Instagram errors and waits out Instagram's rate limits. A reply whose outcome is unknown, for example after a timeout, is never sent again on its own; it shows as **Needs review** so you can check Instagram first.++## Costs++Everything runs on the services you already use, and nothing new is billed on Cloudflare's or Supabase's free plans. Each comment is one Worker request, and a matched one adds a few database calls and one Instagram call. Comments and reply history are deleted after 90 days.++## Troubleshooting++| What you see | What to do |+| --- | --- |+| Meta says the callback could not be verified | Check the URL ends in `/api/webhooks/instagram` and that `INSTAGRAM_WEBHOOK_VERIFY_TOKEN` matches exactly |+| `wrangler tail` shows 401 for webhook calls | The signature does not match: set `META_APP_SECRET` as well, then check that `INSTAGRAM_APP_SECRET` is the Instagram app secret |+| No webhook calls at all | The app is not Live, the account has no role on the app during testing, the account is private, or comment events are not turned on for it |+| A reply failed with "does not allow a private reply" | The comment was deleted, is older than 7 days, or its author does not accept messages |+| An account shows **Held** | Instagram refused its token. Connect the account again on the Accounts page, check that the account allows access to messages in the Instagram app, then turn its replies back on |diff --git a/site/content/docs/self-host/deploy-backend.mdx b/site/content/docs/self-host/deploy-backend.mdxindex 074802d..fa0066f 100644--- a/site/content/docs/self-host/deploy-backend.mdx+++ b/site/content/docs/self-host/deploy-backend.mdx@@ -58,8 +58,8 @@ Deploying also registers two cron triggers from `wrangler.toml`. You do not need| Schedule | What it does || --- | --- |-| `*/15 * * * *` | Publishes scheduled Instagram posts that are due. |-| `0 0 * * *` | Renews Instagram access tokens before they expire. |+| `*/5 * * * *` | At minutes 0, 15, 30 and 45, publishes scheduled Instagram posts that are due. On every run, sends comment replies that are waiting. |+| `0 0 * * *` | Renews Instagram access tokens before they expire, and deletes comment automation records older than 90 days. |## Run it locallydiff --git a/site/content/docs/self-host/index.mdx b/site/content/docs/self-host/index.mdxindex f80dacb..221432d 100644--- a/site/content/docs/self-host/index.mdx+++ b/site/content/docs/self-host/index.mdx@@ -19,7 +19,7 @@ The repository has a third folder, `site`, which is the project's own public web| Supabase | Sign-in and the database | <Badge tone="required">Required</Badge> | Free plan is enough || Cloudflare | Hosting the backend and frontend | <Badge tone="required">Required</Badge> | Free plan is enough || Google Cloud | YouTube analytics | <Badge tone="optional">For YouTube</Badge> | Free, 10,000 quota units a day |-| Meta for Developers | Connecting Instagram and publishing | <Badge tone="optional">For Instagram</Badge> | Free |+| Meta for Developers | Connecting Instagram, publishing, and replying to comments | <Badge tone="optional">For Instagram</Badge> | Free; comment replies need App Review || Cloudinary | Hosting media before Instagram fetches it | <Badge tone="optional">For publishing</Badge> | Free plan is enough || Upstash | Caching to save API quota and speed pages up | <Badge tone="optional">Optional</Badge> | Free plan is enough || Resend | Emailing sign-in and verification codes to members | <Badge tone="optional">Optional</Badge> | Free, 100 emails a day |@@ -30,7 +30,7 @@ Reddit needs no key. Each member pastes their own Reddit session cookie when the## Order of setup1. [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.+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. [Comment automation](/docs/self-host/comment-automation) comes after the Instagram app and the backend are deployed.3. [Deploy the backend](/docs/self-host/deploy-backend) and give it every secret.4. [Deploy the frontend](/docs/self-host/deploy-frontend).5. Optionally connect [GitHub](/docs/self-host/github), then run through the [launch checklist](/docs/self-host/checklist).diff --git a/site/content/docs/use/automations.mdx b/site/content/docs/use/automations.mdxnew file mode 100644index 0000000..d77579e--- /dev/null+++ b/site/content/docs/use/automations.mdx@@ -0,0 +1,48 @@+export const meta = { title: 'Reply to comments automatically', description: 'Send a private message to anyone who comments a keyword on your Instagram posts and reels.' }++Automations send a private reply on Instagram when someone comments a keyword, such as GUIDE, on one of your posts or reels. A typical rule sends a link: "Here is your guide" and the address of the guide.++<Callout type="note" title="Before you start">++You need an Instagram Business or Creator account connected with Instagram sign-in, and the account must be public. Your administrator also turns on comment events for the server; until they do, the Automations page says comment events are not set up.++</Callout>++## Create a rule++1. Open **Automations** in the sidebar and choose **New rule**.+2. Choose the Instagram account, give the rule a name, and type its keywords, separated by commas.+3. Choose how keywords match. **Anywhere in the comment, as a whole word** answers "send me the guide please" for GUIDE but not "guidelines". **The whole comment, nothing else** answers only a comment that is the keyword.+4. Choose **Every post and reel**, or **Only the posts I choose** and pick them.+5. Write the reply and, if you like, a link. The preview shows the message as it will arrive, and how much of Instagram's 1,000 byte limit it uses.+6. Type a sample comment under **Test a comment** and choose **Test** to see whether it would match. Nothing is sent.+7. Leave **Turn the rule on when saved** on, and choose **Create rule**.++A comment gets one reply, from the first rule that matches it. Rules for chosen posts are checked before rules for every post. You can copy a rule (the copy starts off), change it, turn it off, or delete it.++## What Instagram allows++- One private reply per comment, sent within 7 days of the comment.+- The person can only get more messages from you after they reply.+- Up to 750 private replies an hour per account. Your administrator sets lower limits, and each rule can have its own.+- A person gets at most a few replies a day from one account, however many keywords they comment.++## Follow what happened++The counts at the top cover the chosen period. **Activity** lists every comment received on an account with an active rule, newest first, with its status:++| Status | Meaning |+| --- | --- |+| Accepted by Instagram | Instagram took the reply. Instagram does not report whether the person read it |+| Waiting, Sending, Trying again | The reply is queued, going out, or waiting for a retry or a limit |+| Held | Replies for that account are paused |+| Needs review | The reply may or may not have gone out. Check the conversation on Instagram before you retry |+| Failed | Instagram refused it; the details say why |+| Skipped, Expired | The rule was turned off, the person reached the daily number of replies, or the 7 days ran out |+| No match | No rule answers this comment; its words are not kept |++Choose the retry button on a failed, skipped or review item to send it again. Instagram refuses a second private reply to the same comment, so a retry never messages someone twice.++## Pause an account++Turn off **Replies** next to an account to hold its replies, for example during a live event. Comments keep arriving and their replies go out when you turn it back on, if they are still within 7 days. If an account shows **Held**, Instagram refused its permission to send messages: connect it again on the **Accounts** page, then turn its replies back on.diff --git a/site/src/docs/nav.ts b/site/src/docs/nav.tsindex eaffd13..bd279fa 100644--- a/site/src/docs/nav.ts+++ b/site/src/docs/nav.ts@@ -73,6 +73,7 @@ export const DOC_TABS: DocTab[] = [pages: [{ slug: 'use/analytics', title: 'Read your analytics', icon: Chart },{ slug: 'use/publishing', title: 'Publish and schedule', icon: Plane },+ { slug: 'use/automations', title: 'Reply to comments automatically', icon: ChatDots },{ slug: 'use/tracked-content', title: 'Track content', icon: Bookmark },],},@@ -100,6 +101,7 @@ export const DOC_TABS: DocTab[] = [{ slug: 'self-host/instagram', title: 'Instagram app', icon: InstagramIcon },{ slug: 'self-host/cloudinary', title: 'Cloudinary', icon: Gallery },{ slug: 'self-host/redis', title: 'Upstash Redis (optional)', icon: ServerSquare },+ { slug: 'self-host/comment-automation', title: 'Comment automation (optional)', icon: Plug },],},{