Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.
refactor(api): remove the manual publish trigger
spacesdrivea0adb98c544b
diff --git a/backend/container.ts b/backend/container.tsindex dfa83e1..b3f4e84 100644--- a/backend/container.ts+++ b/backend/container.ts@@ -118,7 +118,7 @@ export function createServices(clients: Clients, config: AppConfig, context: ReqyoutubeAnalytics: createYouTubeAnalyticsService({ accounts, cache, config, context }),instagramAnalytics: createInstagramAnalyticsService({ accounts, cache, context }),publishing: createPublishingService({ accounts, config, context }),- scheduledPosts: createScheduledPostService({ accounts, posts, publisher: scheduledPublisher }),+ scheduledPosts: createScheduledPostService({ accounts, posts }),scheduledPublisher,tokenRefresh: createTokenRefreshService({ accounts, context }),trackedContent: createTrackedContentService({ tracked, config, context }),diff --git a/backend/controllers/scheduledPostController.ts b/backend/controllers/scheduledPostController.tsindex 1f3960d..d29f06d 100644--- a/backend/controllers/scheduledPostController.ts+++ b/backend/controllers/scheduledPostController.ts@@ -3,7 +3,7 @@ import { jsonBody } from '../middleware/validate.ts';import { parseScheduledPost, parseScheduledPostUpdate } from '../validators/scheduledPostValidators.ts';import type {ScheduledPostDeleteAllResponse, ScheduledPostListResponse, ScheduledPostResponse, ScheduledPostUpdateResponse,- ScheduledPublishRunResponse, SuccessMessageResponse,+ SuccessMessageResponse,} from '../../shared/types/domain.ts';export const listScheduledPosts = controller.createHandlers(async c => {@@ -30,8 +30,3 @@ export const deleteScheduledPost = controller.createHandlers(async c => {await servicesFor(c).scheduledPosts.remove(c.get('userId'), pathParam(c, 'id'));return c.json({ success: true, message: 'Scheduled post deleted' } satisfies SuccessMessageResponse);});--export const publishDuePosts = controller.createHandlers(async c => {- const result = await servicesFor(c).scheduledPosts.publishDueNow(c.get('userId'));- return c.json({ success: true, ...result, timestamp: new Date().toISOString() } satisfies ScheduledPublishRunResponse);-});diff --git a/backend/lib/rateLimit/rules.ts b/backend/lib/rateLimit/rules.tsindex 296816d..3cce33d 100644--- a/backend/lib/rateLimit/rules.ts+++ b/backend/lib/rateLimit/rules.ts@@ -57,7 +57,6 @@ export const QUOTA_ROUTES: readonly RouteMatcher[] = [{ methods: ['POST'], path: /^\/api\/auth\/instagram\/complete$/ },{ methods: ['POST'], path: /^\/api\/tracked-content$/ },{ methods: ['POST'], path: /^\/api\/tracked-content\/[^/]+\/refresh$/ },- { methods: ['GET', 'POST'], path: /^\/api\/process-scheduled$/ },{ methods: ['POST'], path: /^\/api\/automations\/accounts\/[^/]+\/subscribe$/ },];diff --git a/backend/repositories/scheduledPostRepository.ts b/backend/repositories/scheduledPostRepository.tsindex 895ef57..e128069 100644--- a/backend/repositories/scheduledPostRepository.ts+++ b/backend/repositories/scheduledPostRepository.ts@@ -31,15 +31,12 @@ function toPost(row: ScheduledPostRow): ScheduledPost {};}-// methods named ...ForUser filter by the verified user id; listDue, listStale, claim and updateById serve the schedulers across all users,-// and the manual trigger lists only its caller's posts through listDueForUser and listStaleForUser+// methods named ...ForUser filter by the verified user id; listDue, listStale, claim and updateById serve the schedulers across all usersexport interface ScheduledPostRepository {listForUser(userId: string): Promise<ScheduledPost[]>;findForUser(id: string, userId: string): Promise<ScheduledPost | null>;listDue(): Promise<ScheduledPost[]>;listStale(claimedBefore: string): Promise<ScheduledPost[]>;- listDueForUser(userId: string): Promise<ScheduledPost[]>;- listStaleForUser(claimedBefore: string, userId: string): Promise<ScheduledPost[]>;claim(post: ScheduledPost): Promise<ScheduledPost | null>;create(post: ScheduledPost, userId: string): Promise<void>;updatePendingForUser(id: string, updates: Partial<ScheduledPost>, userId: string): Promise<boolean>;@@ -101,26 +98,6 @@ export function createScheduledPostRepository(db: SupabaseClient): ScheduledPostreturn found.map(toPost);},- async listDueForUser(userId) {- const found = await rows<ScheduledPostRow>('scheduledPosts.listDueForUser', () => db- .from('scheduled_posts')- .select(COLUMNS)- .eq('status', 'pending')- .lte('scheduled_at', new Date().toISOString())- .eq('user_id', userId));- return found.map(toPost);- },-- async listStaleForUser(claimedBefore, userId) {- const found = await rows<ScheduledPostRow>('scheduledPosts.listStaleForUser', () => db- .from('scheduled_posts')- .select(COLUMNS)- .eq('status', 'publishing')- .lt('claimed_at', claimedBefore)- .eq('user_id', userId));- return found.map(toPost);- },-// matches only the post as it was listed (pending, or the same expired claim) with the same attempts; null means another run wonasync claim(post) {const claimed = await rows<ScheduledPostRow>('scheduledPosts.claim', () => {diff --git a/backend/routes/scheduledPostRoutes.ts b/backend/routes/scheduledPostRoutes.tsindex 4ebfc95..547f26f 100644--- a/backend/routes/scheduledPostRoutes.ts+++ b/backend/routes/scheduledPostRoutes.ts@@ -1,6 +1,6 @@import { Hono } from 'hono';import {- listScheduledPosts, createScheduledPost, updateScheduledPost, deleteAllScheduledPosts, deleteScheduledPost, publishDuePosts,+ listScheduledPosts, createScheduledPost, updateScheduledPost, deleteAllScheduledPosts, deleteScheduledPost,} from '../controllers/scheduledPostController.ts';import type { AppEnv } from '../types/app.ts';@@ -11,8 +11,5 @@ router.post('/scheduled-posts', ...createScheduledPost);router.put('/scheduled-posts/:id', ...updateScheduledPost);router.delete('/scheduled-posts', ...deleteAllScheduledPosts);router.delete('/scheduled-posts/:id', ...deleteScheduledPost);-// the manual trigger for the scheduler; api.processScheduled() calls the GET form-router.get('/process-scheduled', ...publishDuePosts);-router.post('/process-scheduled', ...publishDuePosts);export default router;diff --git a/backend/services/scheduledPostService.ts b/backend/services/scheduledPostService.tsindex 2f7d668..c5fb736 100644--- a/backend/services/scheduledPostService.ts+++ b/backend/services/scheduledPostService.ts@@ -3,15 +3,11 @@ import { newRowId } from '../lib/ids.ts';import { publishableAccount } from './publishingService.ts';import type { AccountRepository } from '../repositories/accountRepository.ts';import type { ScheduledPostRepository, DeleteAllResult } from '../repositories/scheduledPostRepository.ts';-import type { ScheduledPublisher } from './scheduledPublisher.ts';-import type {- ScheduledPost, ScheduledPostRequest, ScheduledPostUpdateRequest, ScheduledPublishRun,-} from '../../shared/types/domain.ts';+import type { ScheduledPost, ScheduledPostRequest, ScheduledPostUpdateRequest } from '../../shared/types/domain.ts';export interface ScheduledPostDeps {accounts: AccountRepository;posts: ScheduledPostRepository;- publisher: ScheduledPublisher;}export interface ScheduledPostService {@@ -20,7 +16,6 @@ export interface ScheduledPostService {update(userId: string, postId: string, changes: ScheduledPostUpdateRequest): Promise<ScheduledPost | null>;remove(userId: string, postId: string): Promise<void>;removeAll(userId: string): Promise<DeleteAllResult>;- publishDueNow(userId: string): Promise<ScheduledPublishRun>;}function futureDate(value: string): string {@@ -31,7 +26,7 @@ function futureDate(value: string): string {return date.toISOString();}-export function createScheduledPostService({ accounts, posts, publisher }: ScheduledPostDeps): ScheduledPostService {+export function createScheduledPostService({ accounts, posts }: ScheduledPostDeps): ScheduledPostService {async function findOwned(userId: string, postId: string): Promise<ScheduledPost> {const post = await posts.findForUser(postId, userId);if (!post) throw new NotFoundError('Scheduled post not found');@@ -89,8 +84,5 @@ export function createScheduledPostService({ accounts, posts, publisher }: Sched},removeAll: userId => posts.deleteAllForUser(userId),-- // the manual trigger runs the same publisher the cron uses, for every user's due posts- publishDueNow: userId => publisher.publishDueForUser(userId),};}diff --git a/backend/services/scheduledPublisher.ts b/backend/services/scheduledPublisher.tsindex 6196e37..bb145c4 100644--- a/backend/services/scheduledPublisher.ts+++ b/backend/services/scheduledPublisher.ts@@ -20,8 +20,6 @@ export interface ScheduledPublisherDeps {export interface ScheduledPublisher {publishDue(): Promise<ScheduledPublishRun>;- // the manual trigger: only the caller's own due posts, so one person never runs, settles or reads another's- publishDueForUser(userId: string): Promise<ScheduledPublishRun>;}// what one claimed post ended as; 'left' means the outcome on Instagram is unknown and the lease decides later@@ -48,7 +46,7 @@ function isTransientFailure(err: unknown): boolean {return isAbortError(err);}-// publishes every user's due posts, so it runs from the cron job or the manual trigger, never per user+// publishes every user's due posts, so it runs from the cron job, never per requestexport function createScheduledPublisher({ accounts, posts, context }: ScheduledPublisherDeps): ScheduledPublisher {const { signal, log } = context;@@ -155,7 +153,7 @@ export function createScheduledPublisher({ accounts, posts, context }: Scheduled}}- // claims and publishes the listed posts one at a time; the cron run lists everyone's, the manual trigger only its caller's+ // claims and publishes the listed posts one at a timeasync function publishCandidates(load: () => Promise<[ScheduledPost[], ScheduledPost[]]>): Promise<ScheduledPublishRun> {let processed = 0;const errors: ScheduledPublishFailure[] = [];@@ -188,8 +186,5 @@ export function createScheduledPublisher({ accounts, posts, context }: Scheduledreturn {publishDue: () => publishCandidates(() => Promise.all([posts.listDue(), posts.listStale(staleClaimCutoff(Date.now()))])),- publishDueForUser: userId => publishCandidates(() => Promise.all([- posts.listDueForUser(userId), posts.listStaleForUser(staleClaimCutoff(Date.now()), userId),- ])),};}diff --git a/backend/tests/middleware/rateLimit.test.ts b/backend/tests/middleware/rateLimit.test.tsindex fae8756..5ea416e 100644--- a/backend/tests/middleware/rateLimit.test.ts+++ b/backend/tests/middleware/rateLimit.test.ts@@ -129,9 +129,6 @@ test('quota and publish routes match the endpoints that spend platform API callsassert.equal(quota('POST', '/api/tracked-content'), true);assert.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);- // Hono answers HEAD with the GET handler, so HEAD cannot slip past the rule- assert.equal(quota('HEAD', '/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);@@ -140,6 +137,11 @@ test('quota and publish routes match the endpoints that spend platform API callsassert.equal(publish('POST', '/api/accounts/abc/ig-publish'), true);assert.equal(publish('POST', '/api/accounts/abc/ig-media-publish'), true);assert.equal(publish('GET', '/api/accounts/abc/ig-media'), false);++ // Hono answers HEAD with the GET handler, so HEAD cannot slip past a rule written for GET+ const getOnly = [{ methods: ['GET'], path: /^\/api\/report$/ }];+ assert.equal(matchesRoute(getOnly, 'HEAD', '/api/report'), true);+ assert.equal(matchesRoute(getOnly, 'POST', '/api/report'), false);});test('every rule uses a different algorithm and a positive limit', () => {diff --git a/backend/tests/routes/scheduledPostRoutes.test.ts b/backend/tests/routes/scheduledPostRoutes.test.tsindex 88099aa..a3c53cf 100644--- a/backend/tests/routes/scheduledPostRoutes.test.ts+++ b/backend/tests/routes/scheduledPostRoutes.test.ts@@ -100,20 +100,3 @@ describe('scheduled post routes', () => {assert.deepEqual(supabase.table.filter(row => row._table === 'scheduled_posts').map(row => row.id).sort(), ['busy', 'theirs']);});});--describe('the manual publishing trigger', () => {- test('runs only the caller\'s own due posts, so another person\'s posts are never claimed or reported', async () => {- const due = (id: string, userId: string, accountId: string) => tableRow('scheduled_posts', {- id, user_id: userId, account_id: accountId, status: 'pending', scheduled_at: '2026-09-01T11:00:00.000Z', attempts: 0, claimed_at: null, data: { mediaUrl: 'https://cdn/a.jpg' },- });- mock.method(console, 'error', () => undefined);- const { supabase, call } = setup([due('mine', 'user-1', 'missing-1'), due('theirs', 'user-2', 'missing-2')]);- const { status, body } = await call('POST', '/process-scheduled');- assert.equal(status, 200);- assert.deepEqual((body.errors as { id: string }[]).map(failure => failure.id), ['mine']);- const theirs = supabase.table.find(row => row.id === 'theirs');- assert.equal(theirs?.status, 'pending');- assert.equal(theirs?.attempts, 0);- assert.ok(supabase.calls.filter(call => call.table === 'scheduled_posts' && call.type === 'select').every(call => call.filters.some(([column, value]) => column === 'user_id' && value === 'user-1') || call.filters.some(([column]) => column === 'id')));- });-});diff --git a/docs/architecture/backend/CRON.md b/docs/architecture/backend/CRON.mdindex d1da441..009a11c 100644--- a/docs/architecture/backend/CRON.md+++ b/docs/architecture/backend/CRON.md@@ -72,7 +72,7 @@ The lease, attempt limit and failure rules live in `backend/lib/scheduledPublish`backend/tests/services/scheduledPublisher.test.ts` pins this sequence, the log lines and the stored results against a fake Supabase client and Graph API (fixtures and golden snapshots in `backend/tests/fixtures/`), and its recovery tests cover lost replies, takeovers and retries.-**No userId filter** - the publisher operates across all users through the cron-only repository methods (`listDue`, `listStale`, `claim`, `findById`, `updateById`). It uses the service-role Supabase client. The manual trigger (`GET` or `POST /api/process-scheduled`) runs the same `publishDue()`.+**No userId filter** - the publisher operates across all users through the cron-only repository methods (`listDue`, `listStale`, `claim`, `findById`, `updateById`). It uses the service-role Supabase client.**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.diff --git a/docs/architecture/backend/RATE_LIMITING.md b/docs/architecture/backend/RATE_LIMITING.mdindex 8d8e300..adc620f 100644--- a/docs/architecture/backend/RATE_LIMITING.md+++ b/docs/architecture/backend/RATE_LIMITING.md@@ -33,7 +33,7 @@ Defined in `backend/lib/rateLimit/rules.ts`.|---|---|---|---|---|| `ip` | Every `/api` request and `/mcp` | 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/refresh-all`, `/accounts/:id/refresh`, `/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 |+| `quota` | `POST /accounts`, `/accounts/refresh-all`, `/accounts/:id/refresh`, `/resolve-channel`, `/tracked-content`, `/tracked-content/:id/refresh`, `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 || `mcp` | `POST /mcp`, after `requireMcpAuth` | User id from the access token or OAuth token | Token bucket | Bursts of 60, refills 1 per second || `oauth` | `GET /auth/instagram/callback` | Client IP | Fixed window counter | 10 per 10 minutes |diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.mdindex 07a60c5..cef6599 100644--- a/docs/architecture/backend/ROUTES.md+++ b/docs/architecture/backend/ROUTES.md@@ -138,8 +138,6 @@ Controllers call `ScheduledPostService` (`services/scheduledPostService.ts`).| PUT | `/api/scheduled-posts/:id` | `scheduledPostRoutes.ts`, `scheduledPostController.updateScheduledPost` | Edit a pending post (caption, scheduled time, media, etc.); 400 for a post that is not pending || DELETE | `/api/scheduled-posts/:id` | `scheduledPostRoutes.ts`, `scheduledPostController.deleteScheduledPost` | Delete a single post; 400 while it is publishing || DELETE | `/api/scheduled-posts` | `scheduledPostRoutes.ts`, `scheduledPostController.deleteAllScheduledPosts` | Delete all posts except those with `status: 'publishing'`; returns `{ deleted, kept }` |-| GET | `/api/process-scheduled` | `scheduledPostRoutes.ts`, `scheduledPostController.publishDuePosts` | Manual trigger - runs `scheduledPublisher.publishDueForUser()` immediately for the caller's own due and stale posts only; the cron and the GitHub Actions publisher serve everyone |-| POST | `/api/process-scheduled` | `scheduledPostRoutes.ts`, `scheduledPostController.publishDuePosts` | Same as above |### Overview| Method | Path | File | Purpose |diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.mdindex 5049715..b8ac824 100644--- a/docs/architecture/backend/SERVICES.md+++ b/docs/architecture/backend/SERVICES.md@@ -33,8 +33,8 @@ A service receives only what it uses: repositories, the cleaned `AppConfig` from| `youtubeAnalytics` | `youtubeAnalyticsService.ts` | accounts, cache | `channelAnalytics`, `channelVideos`, `comparison` (used by the MCP `compare_youtube_channels` tool) || `instagramAnalytics` | `instagramAnalyticsService.ts` | accounts, cache | `analytics`, `media` || `publishing` | `publishingService.ts` | accounts | `cloudinaryConfig`, `publishingLimit` (used by the MCP `get_instagram_publishing_limit` tool), `createContainer`, `containerStatus`, `publishContainer` |-| `scheduledPosts` | `scheduledPostService.ts` | accounts, scheduled posts (and the publisher) | `list`, `create`, `update`, `remove`, `removeAll`, `publishDueNow` |-| `scheduledPublisher` | `scheduledPublisher.ts` | accounts, scheduled posts | `publishDue` (every user's due posts; cron and manual trigger) |+| `scheduledPosts` | `scheduledPostService.ts` | accounts, scheduled posts | `list`, `create`, `update`, `remove`, `removeAll` |+| `scheduledPublisher` | `scheduledPublisher.ts` | accounts, scheduled posts | `publishDue` (every user's due posts; the cron) || `tokenRefresh` | `tokenRefreshService.ts` | accounts | `refreshExpiringInstagramTokens` (daily cron) || `trackedContent` | `trackedContentService.ts` | tracked posts | `list`, `add`, `update`, `remove`, `refresh` || `overview` | `overviewService.ts` | accounts, tracked posts, cache | `summary` |@@ -258,7 +258,7 @@ Account responses for every platform pass through `safeAccount()` in `backend/li## Shared Instagram publishing parameters-`buildMediaParams(post, accessToken)` in `services/instagram/instagramPublishing.ts` builds the Graph API container parameters for photos, Reels, Stories and carousel items. The same file holds the Graph calls both publishers make: `createMediaContainer`, `fetchContainerStatus`, `publishMediaContainer` and `fetchPublishingLimit`. `PublishingService` (publish now) and `scheduledPublisher` (the cron and the manual trigger) both call them. `scripts/publish-scheduled.ts` keeps its own copy on purpose: it runs in GitHub Actions with zero npm dependencies and cannot import Worker code.+`buildMediaParams(post, accessToken)` in `services/instagram/instagramPublishing.ts` builds the Graph API container parameters for photos, Reels, Stories and carousel items. The same file holds the Graph calls both publishers make: `createMediaContainer`, `fetchContainerStatus`, `publishMediaContainer` and `fetchPublishingLimit`. `PublishingService` (publish now) and `scheduledPublisher` (the cron) both call them. `scripts/publish-scheduled.ts` keeps its own copy on purpose: it runs in GitHub Actions with zero npm dependencies and cannot import Worker code.---diff --git a/docs/architecture/data-flows/SCHEDULING.md b/docs/architecture/data-flows/SCHEDULING.mdindex b4891be..380710f 100644--- a/docs/architecture/data-flows/SCHEDULING.md+++ b/docs/architecture/data-flows/SCHEDULING.md@@ -11,8 +11,7 @@ Both schedulers follow the same rules from `backend/lib/scheduledPublishing.ts`:**Trigger:** the `*/5 * * * *` cron in `wrangler.toml`, on its runs at minutes 0, 15, 30 and 45 (`cronPlan()`; the other five minute runs reconcile the comment reply queue)**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)-**Manual trigger:** `GET` or `POST /api/process-scheduled` runs the same `publishDue()`+**Supabase client:** service-role (created from Worker env)## System B: GitHub Actionsdiff --git a/docs/guidelines/API_CONVENTIONS.md b/docs/guidelines/API_CONVENTIONS.mdindex fbd1619..16c549c 100644--- a/docs/guidelines/API_CONVENTIONS.md+++ b/docs/guidelines/API_CONVENTIONS.md@@ -108,7 +108,7 @@ The backend extracts and verifies it in `requireAuth`. Controllers read the veri- Single resources: `/:id` suffix - `/accounts/:id`- Sub-resources: nested - `/accounts/:id/analytics`, `/accounts/:id/ig-media`- Actions on resources: verb-noun - `/accounts/refresh-all`, `/accounts/:id/refresh`-- Non-resource actions: verb noun - `/resolve-channel`, `/process-scheduled`+- Non-resource actions: verb noun - `/resolve-channel`, `/refresh-all`## Frontend `api.ts` Conventionsdiff --git a/docs/guidelines/NAMING.md b/docs/guidelines/NAMING.mdindex 03ac55d..3a5b137 100644--- a/docs/guidelines/NAMING.md+++ b/docs/guidelines/NAMING.md@@ -89,7 +89,7 @@ Use `.tsx` only for files that contain JSX; everything else is `.ts`.- REST convention: noun-first, plural - `/accounts`, `/scheduled-posts`- Resource nesting: `/accounts/:id/ig-analytics` (not `/ig-analytics/:accountId`)-- Kebab-case multi-word paths - `/refresh-all`, `/ig-publish`, `/process-scheduled`+- Kebab-case multi-word paths - `/refresh-all`, `/ig-publish`, `/scheduled-posts`## Redis Cache Keysdiff --git a/docs/platform-v2/SECURITY_AUDIT.md b/docs/platform-v2/SECURITY_AUDIT.mdindex 2bcd168..2165d77 100644--- a/docs/platform-v2/SECURITY_AUDIT.md+++ b/docs/platform-v2/SECURITY_AUDIT.md@@ -25,7 +25,7 @@ Deviations from the skill, recorded by the run: reconnaissance used 2 agents ins| Id | Severity | Finding | Status ||---|---|---|---|| F1 | Medium (likelihood low, impact high) | **Instagram sign-in was not bound to the person who started it.** The public callback connected the account named by the signed state alone, so a consent link made by one Twiligent user and completed by another person connected that person's Instagram account, with publishing, messaging and insights access, to the first user's account. | Fixed: commit "finish Instagram sign-in only for the person who started it". The callback only checks the state and hands the code to the app in the URL fragment; the signed-in app posts it to `POST /api/auth/instagram/complete`, which refuses a state started by anyone else (403) before any call to Instagram. Regression tests: `backend/tests/routes/instagramAuthRoutes.test.ts` ("a consent link made by one person and completed by another connects nothing") |-| F2 | Low (likelihood medium, impact low) | **The manual publish trigger ran every user's due posts.** `GET` and `POST /api/process-scheduled` started the all-user publisher, so any signed-in user could settle other users' posts, spend their attempts, and read their failed post ids and error reasons. | Fixed: commit "limit the manual publish trigger to the caller's posts". The trigger now lists only the caller's due and stale posts; the cron and the GitHub Actions publisher still serve everyone. Regression test: `backend/tests/routes/scheduledPostRoutes.test.ts` ("runs only the caller's own due posts") |+| F2 | Low (likelihood medium, impact low) | **The manual publish trigger ran every user's due posts.** `GET` and `POST /api/process-scheduled` started the all-user publisher, so any signed-in user could settle other users' posts, spend their attempts, and read their failed post ids and error reasons. | Fixed: commit "limit the manual publish trigger to the caller's posts". The trigger now lists only the caller's due and stale posts; the cron and the GitHub Actions publisher still serve everyone. Regression test: `backend/tests/routes/scheduledPostRoutes.test.ts` ("runs only the caller's own due posts"). Later the trigger itself was removed, since nothing called it (#159), so the exposure is gone entirely |Rejected by the verifiers: "deploy secrets are reachable from any branch". Running a deploy already needs write access to the repository, so no lower-trust person gains anything.diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.mdindex f47134c..c84354b 100644--- a/docs/workflows/TESTING.md+++ b/docs/workflows/TESTING.md@@ -270,7 +270,7 @@ Open the app in a browser. For each changed area, test:**Scheduling (if changed):**- [ ] Create a scheduled post -> appears in queue- [ ] Create a scheduled post with another user's account id (`curl` with your token) -> 404 `Instagram account not found`-- [ ] Manual trigger processes due posts correctly+- [ ] A due post is published by the next quarter-hour cron run (`npx wrangler tail` shows the run)- [ ] Failed posts show error in UI- [ ] A post interrupted mid-publish (status `publishing`, `claimed_at` set more than 20 minutes ago in the SQL editor) is taken over by the next run: it ends `published` if its saved container already went out, without a second post on Instagram- [ ] A lost reply cannot leave a published post marked `failed`: when the run cannot confirm the outcome, the post stays `publishing` until a run after the lease checks the container@@ -352,7 +352,7 @@ After any change to `scripts/publish-scheduled.ts`, `backend/lib/scheduledPublis2. Watch the run output3. Verify: "No posts due for publishing" (if no scheduled posts) or successful publish-If you have a test post scheduled in the near future, use `GET /api/process-scheduled` to run the Worker's publisher for your own due posts (`scheduledPublisher.publishDueForUser()`) manually.+To test the Worker's own publisher, schedule a post a few minutes ahead and watch `npx wrangler tail` at the next quarter-hour run.## Future Test Infrastructurediff --git a/frontend/src/services/api.ts b/frontend/src/services/api.tsindex 08bf73e..6fc271b 100644--- a/frontend/src/services/api.ts+++ b/frontend/src/services/api.ts@@ -4,7 +4,7 @@ import type {AccountListResponse, AccountRefreshAllResponse, AccountResponse, ApiFailure, GitHubSettingsRequest,GitHubSettingsResponse, HealthResponse, KeysStatusResponse, OverviewResponse, ScheduledPostDeleteAllResponse,ScheduledPostListResponse, ScheduledPostRequest, ScheduledPostResponse, ScheduledPostUpdateRequest,- ScheduledPostUpdateResponse, ScheduledPublishRunResponse, SuccessMessageResponse, SuccessResponse,+ ScheduledPostUpdateResponse, SuccessMessageResponse, SuccessResponse,TrackedContentAddRequest, TrackedContentItem, TrackedContentUpdateRequest, YouTubeAccountAddResponse,} from '@shared/types/domain.ts';import type {@@ -168,7 +168,6 @@ export const api = {updateScheduledPost: (id: string, data: ScheduledPostUpdateRequest) => request<ScheduledPostUpdateResponse>(`/scheduled-posts/${id}`, { method: 'PUT', body: JSON.stringify(data) }),deleteScheduledPost: (id: string) => request<SuccessMessageResponse>(`/scheduled-posts/${id}`, { method: 'DELETE' }),deleteAllScheduledPosts: () => request<ScheduledPostDeleteAllResponse>('/scheduled-posts', { method: 'DELETE' }),- processScheduled: () => request<ScheduledPublishRunResponse>('/process-scheduled'),// Comment-to-DM automation; activity and stats take filters as query parametersgetAutomations: () => request<AutomationOverviewResponse>('/automations'),diff --git a/shared/types/domain.ts b/shared/types/domain.tsindex c9851fc..d425c06 100644--- a/shared/types/domain.ts+++ b/shared/types/domain.ts@@ -111,7 +111,7 @@ export interface ScheduledPublishFailure {error: string;}-// processScheduledPosts() output; the process-scheduled routes add success and timestamp+// what one run of the scheduled publisher did, for the cron logexport interface ScheduledPublishRun {processed: number;errors: ScheduledPublishFailure[];@@ -215,12 +215,6 @@ export interface ScheduledPostDeleteAllResponse {kept: number;}-// GET and POST /api/process-scheduled-export interface ScheduledPublishRunResponse extends ScheduledPublishRun {- success: true;- timestamp: string;-}-// GET /api/tracked-contentexport type TrackedContentListResponse = TrackedPost[];