Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

fix(publishing): check Instagram credentials and accounts before publishing

spacesdrive51ac1c0398c2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 12f38bc..bf0afb8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -62,6 +62,8 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Fixed
+- Publishing and scheduling checked too little before calling Instagram: a missing Instagram app secret made the OAuth callback fail with a server error, posts for an account without a token or on another platform called `/undefined/media`, and a Reel still processing after the last status check was published anyway. Each case now fails with a message that says what to fix, and `GET /api/cloudinary-config` answers 503 instead of 200 when Cloudinary is not configured
+- The Instagram sign-in state is now checked in constant time
- When Redis was unreachable, every cached request waited about 4 seconds for the cache client's retries; the cache now gives up after one quick retry and skips Redis for 30 seconds after a failure
- `GET /api/comparison` returned stored account secrets (Instagram tokens, Reddit cookies) and ranked Instagram and Reddit accounts with YouTube channels; it now ranks YouTube channels only, passed through `safeAccount()`
diff --git a/backend/lib/oauthState.ts b/backend/lib/oauthState.ts
index adc9405..c9a0e7a 100644
--- a/backend/lib/oauthState.ts
+++ b/backend/lib/oauthState.ts
@@ -5,21 +5,29 @@ function toBase64Url(text: string): string {
return btoa(text).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
+function hmacKey(secret: string, usage: 'sign' | 'verify'): Promise<CryptoKey> {
+ return crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, [usage]);
+}
+
async function hmacSign(secret: string, message: string): Promise<string> {
- const key = await crypto.subtle.importKey(
- 'raw',
- new TextEncoder().encode(secret),
- { name: 'HMAC', hash: 'SHA-256' },
- false,
- ['sign'],
- );
- const signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(message));
+ const signature = await crypto.subtle.sign('HMAC', await hmacKey(secret, 'sign'), new TextEncoder().encode(message));
return toBase64Url(String.fromCharCode(...new Uint8Array(signature)));
}
+function fromBase64Url(text: string): Uint8Array<ArrayBuffer> | null {
+ try {
+ return Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/')), char => char.charCodeAt(0));
+ } catch {
+ // a tampered state is not valid base64
+ return null;
+ }
+}
+
+// subtle.verify compares in constant time, unlike comparing the two signatures as strings
async function hmacVerify(secret: string, message: string, signature: string): Promise<boolean> {
- const expected = await hmacSign(secret, message);
- return expected === signature;
+ const signatureBytes = fromBase64Url(signature);
+ if (!signatureBytes) return false;
+ return crypto.subtle.verify('HMAC', await hmacKey(secret, 'verify'), signatureBytes, new TextEncoder().encode(message));
}
export async function createOAuthState(userId: string, secret: string): Promise<string> {
@@ -37,8 +45,9 @@ export async function verifyOAuthState(state: string, secret: string): Promise<s
const isValid = await hmacVerify(secret, payload, signature);
if (!isValid) return null;
- const decoded = atob(payload.replace(/-/g, '+').replace(/_/g, '/'));
- const [userId, createdAt] = decoded.split(':');
+ const decoded = fromBase64Url(payload);
+ if (!decoded) return null;
+ const [userId, createdAt] = new TextDecoder().decode(decoded).split(':');
if (Date.now() - Number(createdAt) > STATE_TTL_MS) return null;
return userId;
diff --git a/backend/routes/instagramAuth.ts b/backend/routes/instagramAuth.ts
index 4848c6b..64ef619 100644
--- a/backend/routes/instagramAuth.ts
+++ b/backend/routes/instagramAuth.ts
@@ -1,6 +1,6 @@
import { verifyOAuthState } from '../lib/oauthState.ts';
import {
- readInstagramOAuthConfig, buildAuthorizationUrl, connectInstagramFromOAuth,
+ readInstagramOAuthConfig, buildAuthorizationUrl, connectInstagramFromOAuth, isOAuthConfigured,
} from '../services/instagramOAuth.ts';
import type { AppContext } from '../types/app.ts';
import type { InstagramAuthUrlResponse } from '../../shared/types/instagram.ts';
@@ -9,7 +9,7 @@ import type { InstagramAuthUrlResponse } from '../../shared/types/instagram.ts';
export async function urlHandler(c: AppContext) {
try {
const config = readInstagramOAuthConfig(c.env);
- if (!config.appId || !config.appSecret) {
+ if (!isOAuthConfigured(config)) {
return c.json({ success: false, message: 'Instagram App credentials not configured on server' }, 500);
}
return c.json({ url: await buildAuthorizationUrl(config, c.get('userId')) } satisfies InstagramAuthUrlResponse);
@@ -30,12 +30,14 @@ export async function callbackHandler(c: AppContext) {
return c.redirect(`${accountsUrl}?ig_error=${encodeURIComponent(reason)}`);
}
- const userId = await verifyOAuthState(state, config.appSecret as string);
- if (!userId) {
- return c.redirect(`${accountsUrl}?ig_error=invalid_state`);
+ if (!isOAuthConfigured(config)) {
+ return c.redirect(`${accountsUrl}?ig_error=not_configured`);
}
try {
+ const userId = await verifyOAuthState(state, config.appSecret);
+ if (!userId) return c.redirect(`${accountsUrl}?ig_error=invalid_state`);
+
const outcome = await connectInstagramFromOAuth(c.get('supabase'), userId, config, code);
if (outcome === 'already_added') return c.redirect(`${accountsUrl}?ig_error=already_added`);
return c.redirect(`${accountsUrl}?ig_connected=true`);
diff --git a/backend/routes/publishing.ts b/backend/routes/publishing.ts
index 6a2ac49..efcd415 100644
--- a/backend/routes/publishing.ts
+++ b/backend/routes/publishing.ts
@@ -14,13 +14,15 @@ interface InstagramApiPublishingLimitBody extends InstagramApiErrorBody {
data: InstagramPublishingLimit[];
}
+const NO_TOKEN_MESSAGE = 'No Instagram access token stored - reconnect this account';
+
const app = new Hono<AppEnv>();
app.get('/cloudinary-config', (c) => {
const cloudName = c.env.CLOUDINARY_CLOUD_NAME;
const uploadPreset = c.env.CLOUDINARY_UPLOAD_PRESET;
if (!cloudName || !uploadPreset) {
- return c.json({ success: false, message: 'Cloudinary not configured on server' });
+ return c.json({ success: false, message: 'Cloudinary not configured on server' }, 503);
}
return c.json({ success: true, cloudName, uploadPreset } satisfies CloudinaryConfigResponse);
});
@@ -31,6 +33,7 @@ app.get('/accounts/:id/ig-publishing-limit', async (c) => {
if (!acct || acct.platform !== 'instagram') {
return c.json({ success: false, message: 'Instagram account not found' }, 404);
}
+ if (!acct.accessToken || !acct.igUserId) return c.json({ success: false, message: NO_TOKEN_MESSAGE }, 400);
const response = await fetch(
`https://graph.instagram.com/v25.0/${acct.igUserId}/content_publishing_limit?fields=quota_usage,config&access_token=${acct.accessToken}`
);
@@ -48,9 +51,10 @@ app.post('/accounts/:id/ig-publish', async (c) => {
if (!acct || acct.platform !== 'instagram') {
return c.json({ success: false, message: 'Instagram account not found' }, 404);
}
+ if (!acct.accessToken || !acct.igUserId) return c.json({ success: false, message: NO_TOKEN_MESSAGE }, 400);
const igId = acct.igUserId;
- const params = buildMediaParams(await c.req.json() as InstagramPublishRequest, acct.accessToken!);
+ const params = buildMediaParams(await c.req.json() as InstagramPublishRequest, acct.accessToken);
// URLSearchParams stringifies the boolean and number values
const query = new URLSearchParams(params as unknown as Record<string, string>).toString();
@@ -68,8 +72,12 @@ app.get('/ig-container/:containerId/status', async (c) => {
try {
const containerId = c.req.param('containerId');
const accountId = c.req.query('accountId');
- const acct = await getAccountById(c.get('supabase'), accountId!, c.get('userId'));
- if (!acct) return c.json({ success: false, message: 'Account not found' }, 404);
+ if (!accountId) return c.json({ success: false, message: 'accountId is required' }, 400);
+ const acct = await getAccountById(c.get('supabase'), accountId, c.get('userId'));
+ if (!acct || acct.platform !== 'instagram') {
+ return c.json({ success: false, message: 'Instagram account not found' }, 404);
+ }
+ if (!acct.accessToken) return c.json({ success: false, message: NO_TOKEN_MESSAGE }, 400);
const response = await fetch(
`https://graph.instagram.com/v25.0/${containerId}?fields=status_code,status&access_token=${acct.accessToken}`
@@ -77,7 +85,7 @@ app.get('/ig-container/:containerId/status', async (c) => {
const data = await response.json() as InstagramApiContainerStatus;
if (data.error) throw new Error(data.error.message);
- return c.json({ success: true, statusCode: data.status_code!, status: data.status! } satisfies InstagramContainerStatusResponse);
+ return c.json({ success: true, statusCode: data.status_code ?? 'IN_PROGRESS', status: data.status ?? '' } satisfies InstagramContainerStatusResponse);
} catch (err) {
return c.json({ success: false, message: (err as Error).message }, 500);
}
@@ -89,6 +97,7 @@ app.post('/accounts/:id/ig-media-publish', async (c) => {
if (!acct || acct.platform !== 'instagram') {
return c.json({ success: false, message: 'Instagram account not found' }, 404);
}
+ if (!acct.accessToken || !acct.igUserId) return c.json({ success: false, message: NO_TOKEN_MESSAGE }, 400);
const { containerId } = await c.req.json() as InstagramMediaPublishRequest;
const response = await fetch(
diff --git a/backend/services/instagramOAuth.ts b/backend/services/instagramOAuth.ts
index 0f94c3b..fe899b8 100644
--- a/backend/services/instagramOAuth.ts
+++ b/backend/services/instagramOAuth.ts
@@ -24,6 +24,12 @@ export interface InstagramOAuthConfig {
appSecret: string | undefined;
}
+// what the token exchange needs; urlHandler and callbackHandler check for it first
+export interface ConfiguredInstagramOAuth extends InstagramOAuthConfig {
+ appId: string;
+ appSecret: string;
+}
+
export type InstagramOAuthOutcome = 'already_added' | 'connected';
// answer of the short-lived code exchange at api.instagram.com
@@ -56,12 +62,16 @@ export function readInstagramOAuthConfig(env: InstagramOAuthEnv): InstagramOAuth
};
}
+export function isOAuthConfigured(config: InstagramOAuthConfig): config is ConfiguredInstagramOAuth {
+ return !!config.appId && !!config.appSecret;
+}
+
// the hmac-signed state carries the userId and a timestamp, so no redis is needed
-export async function buildAuthorizationUrl(config: InstagramOAuthConfig, userId: string): Promise<string> {
- const state = await createOAuthState(userId, config.appSecret as string);
+export async function buildAuthorizationUrl(config: ConfiguredInstagramOAuth, userId: string): Promise<string> {
+ const state = await createOAuthState(userId, config.appSecret);
const params = new URLSearchParams({
force_reauth: 'true',
- client_id: config.appId as string,
+ client_id: config.appId,
redirect_uri: config.redirectUri,
response_type: 'code',
scope: OAUTH_SCOPES,
@@ -70,13 +80,13 @@ export async function buildAuthorizationUrl(config: InstagramOAuthConfig, userId
return `${AUTHORIZE_URL}?${params}`;
}
-async function exchangeCodeForToken(config: InstagramOAuthConfig, code: string): Promise<string> {
+async function exchangeCodeForToken(config: ConfiguredInstagramOAuth, code: string): Promise<string> {
const tokenRes = await fetch(TOKEN_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
- client_id: config.appId as string,
- client_secret: config.appSecret as string,
+ client_id: config.appId,
+ client_secret: config.appSecret,
grant_type: 'authorization_code',
redirect_uri: config.redirectUri,
// instagram sometimes appends #_ to the code
@@ -91,11 +101,11 @@ async function exchangeCodeForToken(config: InstagramOAuthConfig, code: string):
}
// keeps the short-lived token (no expiry) when instagram declines the upgrade
-async function upgradeToLongLivedToken(config: InstagramOAuthConfig, shortToken: string): Promise<{ token: string; expiresIn: number }> {
+async function upgradeToLongLivedToken(config: ConfiguredInstagramOAuth, shortToken: string): Promise<{ token: string; expiresIn: number }> {
const longParams = new URLSearchParams({
grant_type: 'ig_exchange_token',
- client_id: config.appId as string,
- client_secret: config.appSecret as string,
+ client_id: config.appId,
+ client_secret: config.appSecret,
access_token: shortToken,
});
const longRes = await fetch(`${LONG_LIVED_TOKEN_URL}?${longParams}`);
@@ -104,7 +114,7 @@ async function upgradeToLongLivedToken(config: InstagramOAuthConfig, shortToken:
}
export async function connectInstagramFromOAuth(
- supabase: SupabaseClient, userId: string, config: InstagramOAuthConfig, code: string,
+ supabase: SupabaseClient, userId: string, config: ConfiguredInstagramOAuth, code: string,
): Promise<InstagramOAuthOutcome> {
const shortToken = await exchangeCodeForToken(config, code);
const { token, expiresIn } = await upgradeToLongLivedToken(config, shortToken);
diff --git a/backend/tests/fixtures/instagramAuth.callback.golden.json b/backend/tests/fixtures/instagramAuth.callback.golden.json
index 0124612..ee9ce5d 100644
--- a/backend/tests/fixtures/instagramAuth.callback.golden.json
+++ b/backend/tests/fixtures/instagramAuth.callback.golden.json
@@ -66,8 +66,9 @@
"location": "https://app.example.com//accounts?ig_error=getaddrinfo%20ENOTFOUND%20api.instagram.com"
},
{
- "status": 500,
- "body": "Internal Server Error"
+ "status": 302,
+ "body": "",
+ "location": "http://localhost:5173/accounts?ig_error=not_configured"
}
],
"requests": [
@@ -265,10 +266,6 @@
"error",
"Instagram OAuth callback error:",
"getaddrinfo ENOTFOUND api.instagram.com"
- ],
- [
- "error",
- {}
]
]
}
diff --git a/backend/tests/fixtures/scheduler.process.golden.json b/backend/tests/fixtures/scheduler.process.golden.json
index c2bdc8f..a4f98ff 100644
--- a/backend/tests/fixtures/scheduler.process.golden.json
+++ b/backend/tests/fixtures/scheduler.process.golden.json
@@ -1,6 +1,6 @@
{
"result": {
- "processed": 4,
+ "processed": 3,
"errors": [
{
"id": "p-story",
@@ -21,6 +21,10 @@
{
"id": "p-publish",
"error": "Publish refused"
+ },
+ {
+ "id": "p-slow",
+ "error": "Instagram did not finish processing the media within 3 minutes"
}
]
},
@@ -124,8 +128,8 @@
"Failed to publish scheduled post p-publish: Publish refused"
],
[
- "log",
- "Published scheduled post p-slow → media m-c-SLOW"
+ "error",
+ "Failed to publish scheduled post p-slow: Instagram did not finish processing the media within 3 minutes"
],
[
"log",
@@ -433,10 +437,6 @@
"url": "https://graph.instagram.com/v25.0/c-SLOW?fields=status_code,status&access_token=T6",
"method": "GET"
},
- {
- "url": "https://graph.instagram.com/v25.0/SLOW/media_publish?creation_id=c-SLOW&access_token=T6",
- "method": "POST"
- },
{
"url": "https://graph.instagram.com/v25.0/IG1/media?access_token=T1&image_url=https%3A%2F%2Fcdn%2Fd.jpg",
"method": "POST"
@@ -909,12 +909,11 @@
"type": "update",
"table": "scheduled_posts",
"values": {
- "status": "published",
+ "status": "failed",
"data": {
"mediaType": "REELS",
"mediaUrl": "https://cdn/slow.mp4",
- "publishedMediaId": "m-c-SLOW",
- "publishedAt": "2026-09-01T12:00:00.000Z"
+ "error": "Instagram did not finish processing the media within 3 minutes"
}
},
"filters": [
@@ -1161,13 +1160,12 @@
"id": "p-slow",
"user_id": "user-1",
"account_id": "igSlow",
- "status": "published",
+ "status": "failed",
"scheduled_at": "2026-09-01T11:00:00.000Z",
"data": {
"mediaType": "REELS",
"mediaUrl": "https://cdn/slow.mp4",
- "publishedMediaId": "m-c-SLOW",
- "publishedAt": "2026-09-01T12:00:00.000Z"
+ "error": "Instagram did not finish processing the media within 3 minutes"
}
},
{
diff --git a/backend/tests/routes/publishing.test.ts b/backend/tests/routes/publishing.test.ts
new file mode 100644
index 0000000..7f110f8
--- /dev/null
+++ b/backend/tests/routes/publishing.test.ts
@@ -0,0 +1,59 @@
+import { test, describe, beforeEach, afterEach } from 'node:test';
+import assert from 'node:assert/strict';
+import publishingRouter from '../../routes/publishing.ts';
+import { installFetch, reply } from '../fixtures/fakeFetch.ts';
+import type { FetchMock } from '../fixtures/fakeFetch.ts';
+import { fakeSupabase, accountRow } from '../fixtures/fakeSupabase.ts';
+import { mountWithContext, callRoute } from '../fixtures/routeHarness.ts';
+
+const ACCOUNTS = [
+ accountRow({ id: 'ig1', platform: 'instagram', igUserId: 'IG1', accessToken: 'T1' }),
+ accountRow({ id: 'igNoToken', platform: 'instagram', igUserId: 'IG2' }),
+ accountRow({ id: 'yt1', platform: 'youtube', channelId: 'UC1' }),
+];
+
+let fetchMock: FetchMock | null = null;
+
+beforeEach(() => {
+ fetchMock = installFetch(() => reply({ id: 'c-1', status_code: 'FINISHED', status: 'Finished' }));
+});
+afterEach(() => fetchMock!.restore());
+
+function buildApp() {
+ return mountWithContext(app => app.route('/', publishingRouter), { supabase: fakeSupabase(ACCOUNTS), userId: 'user-1' });
+}
+
+async function call(method: string, path: string, json?: unknown, env = {}) {
+ const result = await callRoute(buildApp(), method, path, { json, env });
+ return { status: result.status, body: JSON.parse(result.body) as Record<string, unknown> };
+}
+
+describe('publishing routes check the account before calling Instagram', () => {
+ test('an Instagram account without a token is refused with 400 on every publishing route', async () => {
+ const expected = { status: 400, body: { success: false, message: 'No Instagram access token stored - reconnect this account' } };
+ assert.deepEqual(await call('GET', '/accounts/igNoToken/ig-publishing-limit'), expected);
+ assert.deepEqual(await call('POST', '/accounts/igNoToken/ig-publish', { mediaType: 'IMAGE', imageUrl: 'https://cdn/a.jpg' }), expected);
+ assert.deepEqual(await call('POST', '/accounts/igNoToken/ig-media-publish', { containerId: 'c-1' }), expected);
+ assert.deepEqual(await call('GET', '/ig-container/c-1/status?accountId=igNoToken'), expected);
+ assert.deepEqual(fetchMock!.requests, []);
+ });
+
+ test('the container status route needs an Instagram account id', async () => {
+ assert.deepEqual(await call('GET', '/ig-container/c-1/status'), { status: 400, body: { success: false, message: 'accountId is required' } });
+ assert.deepEqual(await call('GET', '/ig-container/c-1/status?accountId=yt1'), { status: 404, body: { success: false, message: 'Instagram account not found' } });
+ assert.deepEqual(fetchMock!.requests, []);
+ });
+
+ test('the container status route reports the status for a valid account', async () => {
+ assert.deepEqual(await call('GET', '/ig-container/c-1/status?accountId=ig1'), {
+ status: 200, body: { success: true, statusCode: 'FINISHED', status: 'Finished' },
+ });
+ });
+
+ test('a missing Cloudinary configuration is an error status, not a 200', async () => {
+ assert.deepEqual(await call('GET', '/cloudinary-config'), { status: 503, body: { success: false, message: 'Cloudinary not configured on server' } });
+ assert.deepEqual(await call('GET', '/cloudinary-config', undefined, { CLOUDINARY_CLOUD_NAME: 'cloud', CLOUDINARY_UPLOAD_PRESET: 'preset' }), {
+ status: 200, body: { success: true, cloudName: 'cloud', uploadPreset: 'preset' },
+ });
+ });
+});
diff --git a/backend/tests/utils/scheduler.test.ts b/backend/tests/utils/scheduler.test.ts
index 6116138..4fe9cfe 100644
--- a/backend/tests/utils/scheduler.test.ts
+++ b/backend/tests/utils/scheduler.test.ts
@@ -1,4 +1,5 @@
import { test, describe, before, after, afterEach, mock } from 'node:test';
+import assert from 'node:assert/strict';
import { processScheduledPosts } from '../../utils/scheduler.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
@@ -96,3 +97,28 @@ describe('processScheduledPosts golden output', () => {
assertGolden({ result, logLines }, 'scheduler.dbFailure');
});
});
+
+describe('processScheduledPosts account checks', () => {
+ test('fails posts whose account is not an Instagram account or has no token, without calling Instagram', async () => {
+ const supabase = fakeSupabase([
+ tableRow('accounts', accountRow({ id: 'yt1', platform: 'youtube', channelId: 'UC1' })),
+ tableRow('accounts', accountRow({ id: 'igNoToken', platform: 'instagram', igUserId: 'IG9' })),
+ postRow('p-youtube', 'yt1', { mediaType: 'IMAGE', mediaUrl: 'https://cdn/y.jpg' }),
+ postRow('p-notoken', 'igNoToken', { mediaType: 'IMAGE', mediaUrl: 'https://cdn/n.jpg' }),
+ ]);
+ fetchMock = installFetch(graphReply);
+ mock.method(console, 'error', () => undefined);
+
+ const result = await processScheduledPosts(supabase);
+ mock.restoreAll();
+
+ assert.deepEqual(result, {
+ processed: 0,
+ errors: [
+ { id: 'p-youtube', error: 'Scheduled posts can only publish to Instagram accounts' },
+ { id: 'p-notoken', error: 'No Instagram access token stored - reconnect this account' },
+ ],
+ });
+ assert.deepEqual(fetchMock.requests, []);
+ });
+});
diff --git a/backend/utils/scheduler.ts b/backend/utils/scheduler.ts
index 6467f97..3f615b4 100644
--- a/backend/utils/scheduler.ts
+++ b/backend/utils/scheduler.ts
@@ -40,6 +40,7 @@ async function waitForContainer(mediaType: InstagramPublishMediaType | undefined
if (statusData.status_code === 'ERROR') throw new Error('Processing failed: ' + (statusData.status || ''));
if (statusData.status_code === 'EXPIRED') throw new Error('Container expired');
}
+ throw new Error('Instagram did not finish processing the media within 3 minutes');
}
async function publishContainer(igId: string, containerId: string, token: string): Promise<string> {
@@ -55,9 +56,11 @@ async function publishContainer(igId: string, containerId: string, token: string
async function publishPost(supabase: SupabaseClient, post: ScheduledPost): Promise<string> {
const acct = await getAccountById(supabase, post.accountId);
if (!acct) throw new Error('Account not found: ' + post.accountId);
+ if (acct.platform !== 'instagram' || !acct.igUserId) throw new Error('Scheduled posts can only publish to Instagram accounts');
+ if (!acct.accessToken) throw new Error('No Instagram access token stored - reconnect this account');
- const igId = acct.igUserId!;
- const token = acct.accessToken!;
+ const igId = acct.igUserId;
+ const token = acct.accessToken;
const params = buildMediaParams(post, token);
const containerId = await createContainer(igId, params);
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index 4be5f1e..2f46acd 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -52,10 +52,10 @@ Channel metrics, the comparison and the all videos filter live in `services/yout
### Publishing
| Method | Path | File | Purpose |
|---|---|---|---|
-| GET | `/api/cloudinary-config` | `routes/publishing.ts` | Returns `{ cloudName, uploadPreset }` for frontend Cloudinary upload |
+| GET | `/api/cloudinary-config` | `routes/publishing.ts` | Returns `{ cloudName, uploadPreset }` for frontend Cloudinary upload; 503 when the Worker has no Cloudinary settings |
| GET | `/api/accounts/:id/ig-publishing-limit` | `routes/publishing.ts` | Checks daily Instagram publishing quota remaining |
| POST | `/api/accounts/:id/ig-publish` | `routes/publishing.ts` | Creates Instagram media container via Graph API; returns `{ containerId }` |
-| GET | `/api/ig-container/:id/status` | `routes/publishing.ts` | Polls container status (`FINISHED`, `IN_PROGRESS`, `ERROR`, `EXPIRED`) |
+| GET | `/api/ig-container/:id/status` | `routes/publishing.ts` | Polls container status (`FINISHED`, `IN_PROGRESS`, `ERROR`, `EXPIRED`); needs `?accountId=` of an Instagram account with a token (400 or 404 otherwise) |
| POST | `/api/accounts/:id/ig-media-publish` | `routes/publishing.ts` | Publishes the container to Instagram; returns `{ mediaId }` |
### Scheduled Posts
diff --git a/docs/architecture/data-flows/PUBLISHING.md b/docs/architecture/data-flows/PUBLISHING.md
index 077cffa..fa7dcd2 100644
--- a/docs/architecture/data-flows/PUBLISHING.md
+++ b/docs/architecture/data-flows/PUBLISHING.md
@@ -8,7 +8,7 @@ User selects account + uploads media + fills caption
▼
1. Frontend: Upload media to Cloudinary
api.getCloudinaryConfig() -> GET /api/cloudinary-config
- -> returns { cloudName, uploadPreset }
+ -> returns { cloudName, uploadPreset }, or 503 when the Worker has no Cloudinary settings
Browser uploads directly to Cloudinary using unsigned preset (api.uploadToCloudinary)
-> Cloudinary returns public URL (e.g., https://res.cloudinary.com/cloud/image/upload/...)
@@ -20,6 +20,7 @@ User selects account + uploads media + fills caption
-> Backend: calls Instagram Graph API
POST https://graph.instagram.com/v25.0/{igUserId}/media
params: { image_url|video_url, caption, media_type, access_token }
+ -> 404 when the account is not an Instagram account of this user, 400 when it has no stored token
-> Returns { containerId }
│
▼
@@ -27,8 +28,10 @@ User selects account + uploads media + fills caption
api.getIGContainerStatus(containerId, accountId)
-> GET /api/ig-container/:containerId/status?accountId=:id
-> Backend: GET https://graph.instagram.com/v25.0/{containerId}?fields=status_code,status
- -> Poll every 3 seconds, up to 30 times (about 90 seconds); a single post then fails,
- the bulk upload goes on to publish
+ -> accountId is required (400 without it); the account must be an Instagram account with a token
+ -> Poll every 3 seconds, up to 30 times (about 90 seconds); after that the post fails
+ with a "took too long" message, in single and bulk publishing alike, because
+ publishing an unfinished container fails anyway
-> Wait for status_code = 'FINISHED'
-> ERROR -> throw error, mark as failed
-> EXPIRED -> throw error
@@ -71,9 +74,12 @@ User creates a scheduled post
(This is the mutex - prevents double-publish if both schedulers fire simultaneously)
b. SELECT account WHERE id=:accountId
- (Gets the accessToken from accounts.data)
+ (Gets the accessToken from accounts.data; a missing account, an account on another
+ platform or a missing token fails the post with a message that says which)
- c. Execute the publish pipeline (same as immediate publishing, steps 2-4 above)
+ c. Execute the publish pipeline (same as immediate publishing, steps 2-4 above); the
+ schedulers poll a Reel or Story up to 60 times (3 minutes) and fail the post if it
+ is still processing
d. On success: UPDATE SET status='published', data.publishedMediaId=:id, data.publishedAt=:ts
@@ -95,4 +101,5 @@ User creates a scheduled post
| Container `ERROR` | Instagram processing failed (bad codec, too long, etc.) | User must re-upload |
| Container `EXPIRED` | >24 hours since container was created | User must re-create container |
| `media_publish` 400 | Usually quota exceeded or invalid containerId | Check publishing limit |
+| Processing timeout | The container was still processing after the last poll | Try again later, or use a shorter or smaller video |
| `status=failed` in scheduled post | Any of the above, plus `accessToken` expired | Re-connect the account |
diff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.md
index eab1b5b..681c29a 100644
--- a/docs/architecture/frontend/API_LAYER.md
+++ b/docs/architecture/frontend/API_LAYER.md
@@ -41,7 +41,7 @@ async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
### `ApiResult<T>`
-A few routes answer `{ success: false, message }` (the `ApiFailure` type in `shared/types/domain.ts`) with a 2xx status, which `request()` returns instead of throwing. Their methods return `request<ApiResult<T>>()`: `getCloudinaryConfig`, `createIGContainer`, `publishIGContainer`, `getScheduledPosts`, `createScheduledPost` and `updateScheduledPost`. The caller narrows on `success` before reading the data:
+A few routes answer `{ success: false, message }` (the `ApiFailure` type in `shared/types/domain.ts`) with a 2xx status, which `request()` returns instead of throwing. Their methods return `request<ApiResult<T>>()`: `createIGContainer`, `publishIGContainer`, `getScheduledPosts`, `createScheduledPost` and `updateScheduledPost`. The caller narrows on `success` before reading the data:
```ts
const res = await api.createScheduledPost(post);
diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.md
index c4d3b70..96f0e72 100644
--- a/docs/workflows/TESTING.md
+++ b/docs/workflows/TESTING.md
@@ -23,6 +23,7 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that
|---|---|
| `backend/services/youtube.ts` | `backend/tests/services/youtube.test.ts` |
| `backend/routes/accounts.ts` | `backend/tests/routes/accounts.test.ts` |
+| `backend/routes/publishing.ts` | `backend/tests/routes/publishing.test.ts` |
| `backend/utils/scheduler.ts` | `backend/tests/utils/scheduler.test.ts` |
| `frontend/src/lib/accounts.ts` | `frontend/tests/lib/accounts.test.ts` |
| `frontend/src/features/analytics/overview/overviewStats.ts` | `frontend/tests/features/analytics/overview/overviewStats.test.ts` |
diff --git a/frontend/src/features/accounts/accountManagerData.ts b/frontend/src/features/accounts/accountManagerData.ts
index ba1e4bc..bf7a0f8 100644
--- a/frontend/src/features/accounts/accountManagerData.ts
+++ b/frontend/src/features/accounts/accountManagerData.ts
@@ -36,6 +36,7 @@ const IG_ERRORS: Record<string, string> = {
cancelled: 'Instagram sign-in was cancelled. Try again when you are ready.',
access_denied: `Instagram did not grant access. Approve every requested permission and try again. ${TESTER_HINT}`,
invalid_state: 'The Instagram sign-in link expired. Start the connection again.',
+ not_configured: 'Instagram connections are not set up on this server. Ask your administrator to add the Instagram app ID and secret.',
};
const METRICS: Record<Platform, (acct: AccountMetricFields) => AccountMetric[]> = {
diff --git a/frontend/src/features/publishing/containerPolling.ts b/frontend/src/features/publishing/containerPolling.ts
index 7b83850..b7656ba 100644
--- a/frontend/src/features/publishing/containerPolling.ts
+++ b/frontend/src/features/publishing/containerPolling.ts
@@ -2,14 +2,12 @@ import { api } from '../../services/api';
import type { InstagramContainerStatusResponse } from '../../../../shared/types/instagram.ts';
import type { MediaType } from '../../../../shared/types/domain.ts';
-export interface ContainerWaitOptions {
- tolerant?: boolean;
- onStatus?: (message: string) => void;
-}
+// tolerant polling survives failed status checks, so it must report each status it sees
+export type ContainerWaitOptions =
+ | { tolerant: true; onStatus: (message: string) => void }
+ | { tolerant?: false; onStatus?: undefined };
-export interface ReadyOptions extends ContainerWaitOptions {
- onProcessing: () => void;
-}
+export type ReadyOptions = ContainerWaitOptions & { onProcessing: () => void };
const POLL_ATTEMPTS = 30;
const POLL_INTERVAL_MS = 3000;
@@ -42,19 +40,18 @@ async function pollStrict(containerId: string, accountId: string): Promise<boole
return containerFinished(status, 'Processing failed');
}
-// single posts survive failed checks and throw on timeout; bulk stops quietly
+// publishing an unfinished container fails, so running out of attempts is an error in both modes
export async function waitForContainer(
- containerId: string, accountId: string, { tolerant = false, onStatus }: ContainerWaitOptions = {},
-): Promise<boolean> {
+ containerId: string, accountId: string, options: ContainerWaitOptions = {},
+): Promise<void> {
for (let i = 0; i < POLL_ATTEMPTS; i++) {
await wait(POLL_INTERVAL_MS);
- const finished = tolerant
- ? await pollTolerant(containerId, accountId, onStatus!)
+ const finished = options.tolerant
+ ? await pollTolerant(containerId, accountId, options.onStatus)
: await pollStrict(containerId, accountId);
- if (finished) return true;
+ if (finished) return;
}
- if (tolerant) throw new Error('Instagram took too long to process the media. Try again in a few minutes.');
- return false;
+ throw new Error('Instagram took too long to process the media. Try again in a few minutes.');
}
// photos need no processing, only a moment before Instagram can publish them
diff --git a/frontend/src/hooks/use-cloudinary-config.ts b/frontend/src/hooks/use-cloudinary-config.ts
index c0a7780..bea3295 100644
--- a/frontend/src/hooks/use-cloudinary-config.ts
+++ b/frontend/src/hooks/use-cloudinary-config.ts
@@ -4,8 +4,7 @@ import type { CloudinaryConfigResponse } from '@shared/types/instagram.ts';
async function fetchCloudinaryConfig(): Promise<CloudinaryConfigResponse | null> {
try {
- const res = await api.getCloudinaryConfig();
- return res?.success ? res : null;
+ return await api.getCloudinaryConfig();
} catch {
// pages already show a missing config as an alert or a disabled upload field
return null;
diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts
index 71b291c..d60619f 100644
--- a/frontend/src/services/api.ts
+++ b/frontend/src/services/api.ts
@@ -155,7 +155,7 @@ export const api = {
getComparison: () => request<YouTubeComparisonResponse>('/comparison'),
- getCloudinaryConfig: () => request<ApiResult<CloudinaryConfigResponse>>('/cloudinary-config'),
+ getCloudinaryConfig: () => request<CloudinaryConfigResponse>('/cloudinary-config'),
uploadToCloudinary,
uploadImage,
diff --git a/scripts/publish-scheduled.ts b/scripts/publish-scheduled.ts
index a2b1f76..d8f04e2 100644
--- a/scripts/publish-scheduled.ts
+++ b/scripts/publish-scheduled.ts
@@ -114,6 +114,8 @@ async function claimPost(id: string): Promise<boolean> {
function sleep(ms: number): Promise<void> { return new Promise(r => setTimeout(r, ms)); }
async function publishToInstagram(post: ScheduledPost, account: Account): Promise<string | undefined> {
+ if (account.platform !== 'instagram' || !account.igUserId) throw new Error('Scheduled posts can only publish to Instagram accounts');
+ if (!account.accessToken) throw new Error('No Instagram access token stored - reconnect this account');
const igId = account.igUserId;
const token = account.accessToken;
// URLSearchParams stringifies the boolean and number values
@@ -154,16 +156,18 @@ async function publishToInstagram(post: ScheduledPost, account: Account): Promis
const containerId = createData.id;
if (post.mediaType === 'REELS' || post.mediaType === 'STORIES') {
- for (let i = 0; i < 60; i++) {
+ let finished = false;
+ for (let i = 0; i < 60 && !finished; i++) {
await sleep(3000);
const statusRes = await fetch(
`https://graph.instagram.com/v25.0/${containerId}?fields=status_code,status&access_token=${token}`
);
const statusData = await statusRes.json() as GraphResponse;
- if (statusData.status_code === 'FINISHED' || statusData.status_code === 'PUBLISHED') break;
+ finished = statusData.status_code === 'FINISHED' || statusData.status_code === 'PUBLISHED';
if (statusData.status_code === 'ERROR') throw new Error('Processing failed: ' + (statusData.status || ''));
if (statusData.status_code === 'EXPIRED') throw new Error('Container expired');
}
+ if (!finished) throw new Error('Instagram did not finish processing the media within 3 minutes');
} else {
await sleep(2000);
}