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.

refactor(api): order the middleware pipeline and finish the layers

spacesdrived5d9fb0afe00
diff --git a/backend/app.ts b/backend/app.ts
new file mode 100644
index 0000000..1235762
--- /dev/null
+++ b/backend/app.ts
@@ -0,0 +1,49 @@
+import { Hono } from 'hono';
+import { requestId } from 'hono/request-id';
+import { apiCors } from './middleware/cors.ts';
+import { requestContext } from './middleware/requestContext.ts';
+import { securityHeaders } from './middleware/securityHeaders.ts';
+import { injectClients } from './middleware/clients.ts';
+import { rateLimit, clientIp, userKey } from './middleware/rateLimit.ts';
+import { requireAuth } from './middleware/auth.ts';
+import { errorHandler, notFoundHandler } from './middleware/errorHandler.ts';
+import { RATE_LIMIT_RULES, QUOTA_ROUTES, PUBLISH_ROUTES, matchesRoute } from './lib/rateLimit/rules.ts';
+import { publicRoutes, protectedRoutes } from './routes/index.ts';
+import type { AppEnv } from './types/app.ts';
+
+// the request pipeline, in order; each step can answer early, and the error handler formats anything thrown
+export function createApp(): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+ app.onError(errorHandler);
+ app.notFound(notFoundHandler);
+
+ // 1. CORS first, so a preflight is answered before any other work
+ app.use('*', apiCors);
+ // 2. request id, cancellation signal and the access log line
+ app.use('*', requestId());
+ app.use('*', requestContext);
+ // 3. security headers on every response, errors included
+ app.use('*', securityHeaders);
+ // 4. the per-request database and cache clients
+ app.use('*', injectClients);
+ // 5. limit per network before authentication, so a flood of bad tokens never reaches Supabase Auth
+ app.use('/api/*', rateLimit(RATE_LIMIT_RULES.ip, clientIp));
+
+ // registered before the protected group, so these answer without authentication
+ app.route('/api', publicRoutes);
+
+ const api = new Hono<AppEnv>();
+ // 6. authentication: sets the user id the rest of the pipeline trusts
+ api.use('*', requireAuth);
+ // 7. per-user limits, and tighter ones on routes that spend platform quota or publish
+ api.use('*', rateLimit(RATE_LIMIT_RULES.user, userKey));
+ api.use('*', rateLimit(RATE_LIMIT_RULES.quota, userKey, c => matchesRoute(QUOTA_ROUTES, c.req.method, c.req.path)));
+ api.use('*', rateLimit(RATE_LIMIT_RULES.publish, userKey, c => matchesRoute(PUBLISH_ROUTES, c.req.method, c.req.path)));
+ // 8. route tables, then controllers, services and repositories
+ api.route('/', protectedRoutes);
+ app.route('/api', api);
+
+ return app;
+}
+
+export const app = createApp();
diff --git a/backend/container.ts b/backend/container.ts
index cfd388e..4f2560d 100644
--- a/backend/container.ts
+++ b/backend/container.ts
@@ -1,6 +1,8 @@
import { createAccountRepository } from './repositories/accountRepository.ts';
import { createAnalyticsCacheRepository } from './repositories/analyticsCacheRepository.ts';
import { createScheduledPostRepository } from './repositories/scheduledPostRepository.ts';
+import { createTrackedPostRepository } from './repositories/trackedPostRepository.ts';
+import { createSettingsRepository } from './repositories/settingsRepository.ts';
import { createAccountService } from './services/accountService.ts';
import { createYouTubeAnalyticsService } from './services/youtubeAnalyticsService.ts';
import { createInstagramAnalyticsService } from './services/instagramAnalyticsService.ts';
@@ -9,6 +11,10 @@ import { createPublishingService } from './services/publishingService.ts';
import { createScheduledPublisher } from './services/scheduledPublisher.ts';
import { createScheduledPostService } from './services/scheduledPostService.ts';
import { createTokenRefreshService } from './services/tokenRefreshService.ts';
+import { createTrackedContentService } from './services/trackedContentService.ts';
+import { createOverviewService } from './services/overviewService.ts';
+import { createSettingsService } from './services/settingsService.ts';
+import { createInstagramConnectService } from './services/instagramConnectService.ts';
import type { AccountService } from './services/accountService.ts';
import type { YouTubeAnalyticsService } from './services/youtubeAnalyticsService.ts';
import type { InstagramAnalyticsService } from './services/instagramAnalyticsService.ts';
@@ -17,6 +23,10 @@ import type { PublishingService } from './services/publishingService.ts';
import type { ScheduledPublisher } from './services/scheduledPublisher.ts';
import type { ScheduledPostService } from './services/scheduledPostService.ts';
import type { TokenRefreshService } from './services/tokenRefreshService.ts';
+import type { TrackedContentService } from './services/trackedContentService.ts';
+import type { OverviewService } from './services/overviewService.ts';
+import type { SettingsService } from './services/settingsService.ts';
+import type { InstagramConnectService } from './services/instagramConnectService.ts';
import type { AppConfig } from './lib/config.ts';
import type { RequestContext } from './types/context.ts';
import type { Redis, SupabaseClient } from './types/app.ts';
@@ -35,6 +45,10 @@ export interface Services {
scheduledPosts: ScheduledPostService;
scheduledPublisher: ScheduledPublisher;
tokenRefresh: TokenRefreshService;
+ trackedContent: TrackedContentService;
+ overview: OverviewService;
+ settings: SettingsService;
+ instagramConnect: InstagramConnectService;
}
// the composition root: wires repositories into services for one request or one cron run; building them is cheap
@@ -42,6 +56,8 @@ export function createServices(clients: Clients, config: AppConfig, context: Req
const accounts = createAccountRepository(clients.supabase);
const cache = createAnalyticsCacheRepository(clients.redis);
const posts = createScheduledPostRepository(clients.supabase);
+ const tracked = createTrackedPostRepository(clients.supabase);
+ const settings = createSettingsRepository(clients.supabase);
const scheduledPublisher = createScheduledPublisher({ accounts, posts, context });
return {
accounts: createAccountService({ accounts, cache, config, context }),
@@ -52,5 +68,9 @@ export function createServices(clients: Clients, config: AppConfig, context: Req
scheduledPosts: createScheduledPostService({ posts, publisher: scheduledPublisher }),
scheduledPublisher,
tokenRefresh: createTokenRefreshService({ accounts, context }),
+ trackedContent: createTrackedContentService({ accounts, tracked, config, context }),
+ overview: createOverviewService({ accounts, tracked, cache, config }),
+ settings: createSettingsService({ settings, config }),
+ instagramConnect: createInstagramConnectService({ accounts, config, context }),
};
}
diff --git a/backend/controllers/healthController.ts b/backend/controllers/healthController.ts
new file mode 100644
index 0000000..45b5471
--- /dev/null
+++ b/backend/controllers/healthController.ts
@@ -0,0 +1,6 @@
+import { controller } from './http.ts';
+import type { HealthResponse } from '../../shared/types/domain.ts';
+
+export const getHealth = controller.createHandlers(c => {
+ return c.json({ status: 'ok', timestamp: new Date().toISOString() } satisfies HealthResponse);
+});
diff --git a/backend/controllers/instagramAuthController.ts b/backend/controllers/instagramAuthController.ts
new file mode 100644
index 0000000..fce02f2
--- /dev/null
+++ b/backend/controllers/instagramAuthController.ts
@@ -0,0 +1,32 @@
+import { controller, servicesFor } from './http.ts';
+import { queryParams } from '../middleware/validate.ts';
+import { requestLogger } from '../middleware/requestContext.ts';
+import { parseInstagramCallback } from '../validators/instagramAuthValidators.ts';
+import { errorFields } from '../lib/logger.ts';
+import type { InstagramAuthUrlResponse } from '../../shared/types/instagram.ts';
+
+// protected: the signed state carries the user id to the public callback
+export const getInstagramAuthUrl = controller.createHandlers(async c => {
+ const url = await servicesFor(c).instagramConnect.authorizationUrl(c.get('userId'));
+ return c.json({ url } satisfies InstagramAuthUrlResponse);
+});
+
+// public: Instagram sends the browser here, so every outcome is a redirect back to the accounts page
+export const handleInstagramCallback = controller.createHandlers(queryParams(parseInstagramCallback), async c => {
+ const { code, state, error, errorReason } = c.req.valid('query');
+ const connect = servicesFor(c).instagramConnect;
+ const backToAccounts = (query: string) => c.redirect(`${connect.accountsPageUrl}?${query}`);
+
+ if (error || !code || !state) return backToAccounts(`ig_error=${encodeURIComponent(errorReason || error || 'cancelled')}`);
+ if (!connect.configured) return backToAccounts('ig_error=not_configured');
+
+ try {
+ const userId = await connect.userIdFromState(state);
+ if (!userId) return backToAccounts('ig_error=invalid_state');
+ const outcome = await connect.connect(userId, code);
+ return backToAccounts(outcome === 'already_added' ? 'ig_error=already_added' : 'ig_connected=true');
+ } catch (err) {
+ requestLogger(c).error('instagram connection failed', errorFields(err));
+ return backToAccounts(`ig_error=${encodeURIComponent((err as Error).message.substring(0, 100))}`);
+ }
+});
diff --git a/backend/controllers/overviewController.ts b/backend/controllers/overviewController.ts
new file mode 100644
index 0000000..cadbdc8
--- /dev/null
+++ b/backend/controllers/overviewController.ts
@@ -0,0 +1,9 @@
+import { controller, servicesFor } from './http.ts';
+import type { OverviewResponse } from '../../shared/types/domain.ts';
+
+// the client polls again while accounts are syncing, so warming never holds up the response
+export const getOverview = controller.createHandlers(async c => {
+ const { tracked, analyticsCache, warmTasks } = await servicesFor(c).overview.summary(c.get('userId'));
+ if (warmTasks.length > 0) c.executionCtx.waitUntil(Promise.allSettled(warmTasks));
+ return c.json({ tracked, analyticsCache } satisfies OverviewResponse);
+});
diff --git a/backend/controllers/settingsController.ts b/backend/controllers/settingsController.ts
new file mode 100644
index 0000000..3e16f94
--- /dev/null
+++ b/backend/controllers/settingsController.ts
@@ -0,0 +1,18 @@
+import { controller, servicesFor } from './http.ts';
+import { jsonBody } from '../middleware/validate.ts';
+import { parseGithubSettings } from '../validators/settingsValidators.ts';
+import type { GitHubSettingsResponse, KeysStatusResponse, SuccessResponse } from '../../shared/types/domain.ts';
+
+export const getGithubSettings = controller.createHandlers(async c => {
+ const settings = await servicesFor(c).settings.githubSettings(c.get('userId'));
+ return c.json(settings satisfies GitHubSettingsResponse);
+});
+
+export const saveGithubSettings = controller.createHandlers(jsonBody(parseGithubSettings), async c => {
+ await servicesFor(c).settings.saveGithubSettings(c.get('userId'), c.req.valid('json'));
+ return c.json({ success: true } satisfies SuccessResponse);
+});
+
+export const getKeyStatus = controller.createHandlers(c => {
+ return c.json(servicesFor(c).settings.serverKeyStatus() satisfies KeysStatusResponse);
+});
diff --git a/backend/controllers/trackedContentController.ts b/backend/controllers/trackedContentController.ts
new file mode 100644
index 0000000..9202d62
--- /dev/null
+++ b/backend/controllers/trackedContentController.ts
@@ -0,0 +1,29 @@
+import { controller, pathParam, servicesFor } from './http.ts';
+import { jsonBody } from '../middleware/validate.ts';
+import { parseNewTrackedContent, parseTrackedContentChanges } from '../validators/trackedContentValidators.ts';
+import type { SuccessResponse, TrackedContentListResponse } from '../../shared/types/domain.ts';
+
+export const listTrackedContent = controller.createHandlers(async c => {
+ const items = await servicesFor(c).trackedContent.list(c.get('userId'));
+ return c.json(items satisfies TrackedContentListResponse);
+});
+
+export const addTrackedContent = controller.createHandlers(jsonBody(parseNewTrackedContent), async c => {
+ const item = await servicesFor(c).trackedContent.add(c.get('userId'), c.req.valid('json'));
+ return c.json(item, 201);
+});
+
+export const updateTrackedContent = controller.createHandlers(jsonBody(parseTrackedContentChanges), async c => {
+ const item = await servicesFor(c).trackedContent.update(c.get('userId'), pathParam(c, 'id'), c.req.valid('json'));
+ return c.json(item);
+});
+
+export const deleteTrackedContent = controller.createHandlers(async c => {
+ await servicesFor(c).trackedContent.remove(c.get('userId'), pathParam(c, 'id'));
+ return c.json({ success: true } satisfies SuccessResponse);
+});
+
+export const refreshTrackedContent = controller.createHandlers(async c => {
+ const item = await servicesFor(c).trackedContent.refresh(c.get('userId'), pathParam(c, 'id'));
+ return c.json(item);
+});
diff --git a/backend/lib/cache.ts b/backend/lib/cache.ts
deleted file mode 100644
index ff777e9..0000000
--- a/backend/lib/cache.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-import type { Redis } from '@upstash/redis';
-import type { VideosCacheData } from '../../shared/types/youtube.ts';
-import type { IGCacheData } from '../../shared/types/instagram.ts';
-import type { RedditCacheData } from '../../shared/types/reddit.ts';
-
-// every helper is a no-op without redis: the cache is optional
-export { createOAuthState, verifyOAuthState } from './oauthState.ts';
-
-// stats change constantly, so cached analytics expire instead of going stale
-const ANALYTICS_TTL_SECONDS = 6 * 60 * 60;
-
-// bump on cache shape changes so old entries miss (v2: hidden counts are null)
-const VIDEOS_CACHE_VERSION = 2;
-const IG_CACHE_VERSION = 2;
-
-// after a failure this isolate skips redis for a while, so an outage costs one timeout, not one per call
-const CACHE_COOLDOWN_MS = 30_000;
-
-type Versioned<T> = T & { version: number };
-
-let cacheDownUntil = 0;
-
-export function resetCacheState(): void {
- cacheDownUntil = 0;
-}
-
-function cacheAvailable(redis: Redis | null): redis is Redis {
- return redis !== null && Date.now() >= cacheDownUntil;
-}
-
-function markCacheDown(): void {
- cacheDownUntil = Date.now() + CACHE_COOLDOWN_MS;
-}
-
-async function readKey<T>(redis: Redis | null, key: string): Promise<T | null> {
- if (!cacheAvailable(redis)) return null;
- try {
- return await redis.get<T>(key);
- } catch {
- // a cache miss falls back to the live api
- markCacheDown();
- return null;
- }
-}
-
-async function writeKey(redis: Redis | null, key: string, value: unknown): Promise<undefined> {
- if (!cacheAvailable(redis)) return undefined;
- try {
- await redis.set(key, value, { ex: ANALYTICS_TTL_SECONDS });
- } catch {
- // a failed write only costs a refetch next time
- markCacheDown();
- }
- return undefined;
-}
-
-async function deleteKey(redis: Redis | null, key: string): Promise<undefined> {
- if (!cacheAvailable(redis)) return undefined;
- try {
- await redis.del(key);
- } catch {
- // the entry still expires on its own ttl
- markCacheDown();
- }
- return undefined;
-}
-
-export async function getVideosCache(redis: Redis | null, userId: string, accountId: string): Promise<Versioned<VideosCacheData> | null> {
- const cached = await readKey<Versioned<VideosCacheData>>(redis, `videos:${userId}:${accountId}`);
- return cached?.version === VIDEOS_CACHE_VERSION ? cached : null;
-}
-
-export async function setVideosCache(redis: Redis | null, userId: string, accountId: string, data: VideosCacheData): Promise<void> {
- await writeKey(redis, `videos:${userId}:${accountId}`, { ...data, version: VIDEOS_CACHE_VERSION });
-}
-
-export async function deleteVideosCache(redis: Redis | null, userId: string, accountId: string): Promise<void> {
- await deleteKey(redis, `videos:${userId}:${accountId}`);
-}
-
-export async function getIGCache(redis: Redis | null, userId: string, accountId: string): Promise<Versioned<IGCacheData> | null> {
- const cached = await readKey<Versioned<IGCacheData>>(redis, `ig:${userId}:${accountId}`);
- return cached?.version === IG_CACHE_VERSION ? cached : null;
-}
-
-export async function setIGCache(redis: Redis | null, userId: string, accountId: string, data: IGCacheData): Promise<void> {
- await writeKey(redis, `ig:${userId}:${accountId}`, { ...data, version: IG_CACHE_VERSION });
-}
-
-export async function deleteIGCache(redis: Redis | null, userId: string, accountId: string): Promise<void> {
- await deleteKey(redis, `ig:${userId}:${accountId}`);
-}
-
-export async function getRedditCache(redis: Redis | null, userId: string, accountId: string): Promise<RedditCacheData | null> {
- return (await readKey<RedditCacheData>(redis, `reddit:${userId}:${accountId}`)) || null;
-}
-
-export async function setRedditCache(redis: Redis | null, userId: string, accountId: string, data: RedditCacheData): Promise<void> {
- await writeKey(redis, `reddit:${userId}:${accountId}`, data);
-}
-
-export async function deleteRedditCache(redis: Redis | null, userId: string, accountId: string): Promise<void> {
- await deleteKey(redis, `reddit:${userId}:${accountId}`);
-}
diff --git a/backend/lib/db.ts b/backend/lib/db.ts
deleted file mode 100644
index daea35d..0000000
--- a/backend/lib/db.ts
+++ /dev/null
@@ -1,323 +0,0 @@
-import type { SupabaseClient } from '@supabase/supabase-js';
-import type { Account, NewAccount, Platform, PostStatus, ScheduledPost, TrackedPost } from '../../shared/types/domain.ts';
-
-interface AccountRow {
- id: string;
- platform: Platform;
- data: Omit<Account, 'id' | 'platform'>;
-}
-
-interface ScheduledPostRow {
- id: string;
- account_id: string;
- status: PostStatus;
- scheduled_at: string;
- data: Partial<ScheduledPost> | null;
-}
-
-interface TrackedPostRow {
- id: string;
- account_id: string | null;
- url: string;
- label: string | null;
- category: string | null;
- content_type: string | null;
- created_at: string;
- updated_at: string;
- data: Record<string, unknown> | null;
-}
-
-export type Settings = Record<string, unknown>;
-
-export interface NewTrackedPost {
- id: string;
- accountId?: string | null;
- url: string;
- label?: string;
- category?: string;
- contentType?: string;
-}
-
-export interface TrackedPostUpdates {
- label?: string;
- category?: string;
- accountId?: string | null;
- data?: Record<string, unknown>;
-}
-
-// crons share these, so supabase is an argument; a null userId skips the filter
-export async function getAccounts(supabase: SupabaseClient, userId: string | null = null): Promise<Account[]> {
- let query = supabase.from('accounts').select('id, platform, data');
- if (userId) query = query.eq('user_id', userId);
- const { data, error } = await query;
- if (error) throw error;
- return ((data || []) as AccountRow[]).map(row => ({ id: row.id, platform: row.platform, ...row.data }));
-}
-
-export async function getAccountById(supabase: SupabaseClient, id: string, userId: string | null = null): Promise<Account | null> {
- let query = supabase.from('accounts').select('id, platform, data').eq('id', id);
- if (userId) query = query.eq('user_id', userId);
- const { data, error } = await query.single();
- if (error || !data) return null;
- return { id: data.id, platform: data.platform, ...(data as AccountRow).data };
-}
-
-export async function createAccount(supabase: SupabaseClient, account: NewAccount, userId: string): Promise<void> {
- const { id, platform, ...rest } = account;
- const { error } = await supabase
- .from('accounts')
- .insert({ id, user_id: userId, platform: platform || 'youtube', data: rest });
- if (error) throw error;
-}
-
-export async function updateAccount(supabase: SupabaseClient, id: string, updates: Partial<Account>, userId: string | null = null): Promise<void> {
- const current = await getAccountById(supabase, id, userId);
- if (!current) throw new Error('Account not found: ' + id);
- const { id: _, platform: currentPlatform, ...currentData } = current;
- const { platform: newPlatform, ...dataUpdates } = updates;
- let query = supabase.from('accounts').update({
- platform: newPlatform || currentPlatform,
- data: { ...currentData, ...dataUpdates },
- }).eq('id', id);
- if (userId) query = query.eq('user_id', userId);
- const { error } = await query;
- if (error) throw error;
-}
-
-export async function deleteAccount(supabase: SupabaseClient, id: string, userId: string | null = null): Promise<void> {
- let query = supabase.from('accounts').delete().eq('id', id);
- if (userId) query = query.eq('user_id', userId);
- const { error } = await query;
- if (error) throw error;
-}
-
-// rows are keyed by (user_id, key); every saved value lives under 'api_keys'
-const DEFAULT_KEYS: Settings = {};
-
-export async function getSettings(supabase: SupabaseClient, userId: string): Promise<Settings> {
- const { data, error } = await supabase
- .from('settings')
- .select('value')
- .eq('key', 'api_keys')
- .eq('user_id', userId)
- .single();
- if (error || !data) return { ...DEFAULT_KEYS };
- return { ...DEFAULT_KEYS, ...data.value };
-}
-
-export async function saveSettings(supabase: SupabaseClient, keys: Settings, userId: string): Promise<void> {
- const { error } = await supabase
- .from('settings')
- .upsert({ user_id: userId, key: 'api_keys', value: keys }, { onConflict: 'user_id,key' });
- if (error) throw error;
-}
-
-function rowToPost(row: ScheduledPostRow): ScheduledPost {
- return {
- id: row.id,
- accountId: row.account_id,
- status: row.status,
- scheduledAt: row.scheduled_at,
- ...(row.data || {}),
- };
-}
-
-export async function getPosts(supabase: SupabaseClient, userId: string | null): Promise<ScheduledPost[]> {
- let query = supabase
- .from('scheduled_posts')
- .select('id, account_id, status, scheduled_at, data')
- .order('scheduled_at', { ascending: true });
- if (userId) query = query.eq('user_id', userId);
- const { data, error } = await query;
- if (error) throw error;
- return (data || []).map(rowToPost);
-}
-
-export async function getPostById(supabase: SupabaseClient, id: string, userId: string | null = null): Promise<ScheduledPost | null> {
- let query = supabase
- .from('scheduled_posts')
- .select('id, account_id, status, scheduled_at, data')
- .eq('id', id);
- if (userId) query = query.eq('user_id', userId);
- const { data, error } = await query.single();
- if (error || !data) return null;
- return rowToPost(data);
-}
-
-export async function getDuePosts(supabase: SupabaseClient): Promise<ScheduledPost[]> {
- const { data, error } = await supabase
- .from('scheduled_posts')
- .select('id, account_id, status, scheduled_at, data')
- .eq('status', 'pending')
- .lte('scheduled_at', new Date().toISOString());
- if (error) throw error;
- return (data || []).map(rowToPost);
-}
-
-// atomic pending to publishing; false means the cron or github workflow won
-export async function claimPost(supabase: SupabaseClient, id: string): Promise<boolean> {
- const { data, error } = await supabase
- .from('scheduled_posts')
- .update({ status: 'publishing' })
- .eq('id', id)
- .eq('status', 'pending')
- .select('id');
- if (error) throw error;
- return (data || []).length > 0;
-}
-
-export async function createPost(supabase: SupabaseClient, post: ScheduledPost, userId: string): Promise<void> {
- const { id, accountId, status, scheduledAt, ...rest } = post;
- const { error } = await supabase.from('scheduled_posts').insert({
- id,
- user_id: userId,
- account_id: accountId,
- status: status || 'pending',
- scheduled_at: scheduledAt,
- data: rest,
- });
- if (error) throw error;
-}
-
-export async function updatePost(supabase: SupabaseClient, id: string, updates: Partial<ScheduledPost>, userId: string | null = null): Promise<void> {
- const { status, scheduledAt, accountId: _, ...dataUpdates } = updates;
- const colUpdates: { status?: PostStatus; scheduled_at?: string; data?: Partial<ScheduledPost> } = {};
-
- if (status !== undefined) colUpdates.status = status;
- if (scheduledAt !== undefined) colUpdates.scheduled_at = scheduledAt;
-
- if (Object.keys(dataUpdates).length > 0) {
- let readQuery = supabase.from('scheduled_posts').select('data').eq('id', id);
- if (userId) readQuery = readQuery.eq('user_id', userId);
- const { data: rows } = await readQuery;
- const currentData = rows?.[0]?.data || {};
- colUpdates.data = { ...currentData, ...dataUpdates };
- }
-
- let query = supabase.from('scheduled_posts').update(colUpdates).eq('id', id);
- if (userId) query = query.eq('user_id', userId);
- const { error } = await query;
- if (error) throw error;
-}
-
-export async function deletePost(supabase: SupabaseClient, id: string, userId: string | null = null): Promise<void> {
- let query = supabase.from('scheduled_posts').delete().eq('id', id);
- if (userId) query = query.eq('user_id', userId);
- const { error } = await query;
- if (error) throw error;
-}
-
-export async function deleteAllPosts(supabase: SupabaseClient, userId: string | null): Promise<{ deleted: number; kept: number }> {
- let countQ = supabase.from('scheduled_posts').select('*', { count: 'exact', head: true });
- let keepQ = supabase.from('scheduled_posts').select('*', { count: 'exact', head: true }).eq('status', 'publishing');
- let delQ = supabase.from('scheduled_posts').delete().neq('status', 'publishing');
-
- if (userId) {
- countQ = countQ.eq('user_id', userId);
- keepQ = keepQ.eq('user_id', userId);
- delQ = delQ.eq('user_id', userId);
- }
-
- const { count: total } = await countQ;
- const { count: keeping } = await keepQ;
- const { error } = await delQ;
- if (error) throw error;
- return { deleted: (total || 0) - (keeping || 0), kept: keeping || 0 };
-}
-
-function rowToTrackedPost(row: TrackedPostRow): TrackedPost {
- return {
- id: row.id,
- accountId: row.account_id,
- url: row.url,
- label: row.label || '',
- category: row.category || '',
- contentType: row.content_type || 'reddit',
- createdAt: row.created_at,
- updatedAt: row.updated_at,
- ...(row.data || {}),
- };
-}
-
-export async function getTrackedPosts(supabase: SupabaseClient, userId: string): Promise<TrackedPost[]> {
- const { data, error } = await supabase
- .from('tracked_posts')
- .select('id, account_id, url, label, category, content_type, created_at, updated_at, data')
- .eq('user_id', userId)
- .order('created_at', { ascending: false });
- if (error) throw error;
- return (data || []).map(rowToTrackedPost);
-}
-
-export async function getTrackedPostById(supabase: SupabaseClient, id: string, userId: string): Promise<TrackedPost | null> {
- const { data, error } = await supabase
- .from('tracked_posts')
- .select('id, account_id, url, label, category, content_type, created_at, updated_at, data')
- .eq('id', id)
- .eq('user_id', userId)
- .single();
- if (error || !data) return null;
- return rowToTrackedPost(data);
-}
-
-export async function createTrackedPost(supabase: SupabaseClient, post: NewTrackedPost, userId: string): Promise<void> {
- const { id, accountId, url, label, category, contentType } = post;
- const { error } = await supabase.from('tracked_posts').insert({
- id,
- user_id: userId,
- account_id: accountId || null,
- url,
- label: label || '',
- category: category || '',
- content_type: contentType || 'reddit',
- });
- if (error) throw error;
-}
-
-export async function updateTrackedPost(supabase: SupabaseClient, id: string, updates: TrackedPostUpdates, userId: string): Promise<void> {
- const colUpdates: {
- updated_at: string;
- label?: string;
- category?: string;
- account_id?: string | null;
- data?: Record<string, unknown>;
- } = { updated_at: new Date().toISOString() };
- if (updates.label !== undefined) colUpdates.label = updates.label;
- if (updates.category !== undefined) colUpdates.category = updates.category;
- if (updates.accountId !== undefined) colUpdates.account_id = updates.accountId || null;
- if (updates.data !== undefined) colUpdates.data = updates.data;
- const { error } = await supabase
- .from('tracked_posts')
- .update(colUpdates)
- .eq('id', id)
- .eq('user_id', userId);
- if (error) throw error;
-}
-
-// merges into data so manual fields and live refresh fields survive each other
-export async function patchTrackedPostData(supabase: SupabaseClient, id: string, patch: Record<string, unknown>, userId: string): Promise<void> {
- const { data: row, error: readError } = await supabase
- .from('tracked_posts')
- .select('data')
- .eq('id', id)
- .eq('user_id', userId)
- .single();
- if (readError || !row) throw readError || new Error('Tracked content not found');
-
- const merged = { ...(row.data || {}), ...patch };
- const { error } = await supabase
- .from('tracked_posts')
- .update({ data: merged, updated_at: new Date().toISOString() })
- .eq('id', id)
- .eq('user_id', userId);
- if (error) throw error;
-}
-
-export async function deleteTrackedPost(supabase: SupabaseClient, id: string, userId: string): Promise<void> {
- const { error } = await supabase
- .from('tracked_posts')
- .delete()
- .eq('id', id)
- .eq('user_id', userId);
- if (error) throw error;
-}
diff --git a/backend/middleware/auth.ts b/backend/middleware/auth.ts
index 792dc91..feea763 100644
--- a/backend/middleware/auth.ts
+++ b/backend/middleware/auth.ts
@@ -1,13 +1,16 @@
import type { Next } from 'hono';
import { getSupabaseAuth } from '../database/supabase.ts';
+import { UnauthorizedError } from '../lib/errors.ts';
import type { AppContext } from '../types/app.ts';
-export async function requireAuth(c: AppContext, next: Next) {
- const token = c.req.header('Authorization')?.replace('Bearer ', '');
- if (!token) return c.json({ error: 'Unauthorized' }, 401);
- const supabaseAuth = getSupabaseAuth(c.env);
- const { data: { user }, error } = await supabaseAuth.auth.getUser(token);
- if (error || !user) return c.json({ error: 'Invalid or expired token' }, 401);
+const BEARER = /^Bearer\s+(\S+)$/i;
+
+// the only source of identity: the user id comes from the verified JWT, never from the request body or query
+export async function requireAuth(c: AppContext, next: Next): Promise<void> {
+ const token = c.req.header('Authorization')?.match(BEARER)?.[1];
+ if (!token) throw new UnauthorizedError('Sign in to use the API');
+ const { data: { user }, error } = await getSupabaseAuth(c.env).auth.getUser(token);
+ if (error || !user) throw new UnauthorizedError('Your session has expired - sign in again');
c.set('userId', user.id);
c.set('userEmail', user.email);
await next();
diff --git a/backend/middleware/clients.ts b/backend/middleware/clients.ts
new file mode 100644
index 0000000..d062fb7
--- /dev/null
+++ b/backend/middleware/clients.ts
@@ -0,0 +1,12 @@
+import type { Next } from 'hono';
+import { getSupabase } from '../database/supabase.ts';
+import { getRedis, getRateLimitRedis } from '../database/redis.ts';
+import type { AppContext } from '../types/app.ts';
+
+// the clients are stateless HTTP clients, so creating them per request is cheap and safe
+export async function injectClients(c: AppContext, next: Next): Promise<void> {
+ c.set('supabase', getSupabase(c.env));
+ c.set('redis', getRedis(c.env));
+ c.set('rateLimitRedis', getRateLimitRedis(c.env));
+ await next();
+}
diff --git a/backend/middleware/cors.ts b/backend/middleware/cors.ts
new file mode 100644
index 0000000..d704f2c
--- /dev/null
+++ b/backend/middleware/cors.ts
@@ -0,0 +1,11 @@
+import { cors } from 'hono/cors';
+import { readConfig } from '../lib/config.ts';
+import { RATE_LIMIT_HEADERS } from './rateLimit.ts';
+
+// only the app's own origins may call the API from a browser; a stolen token is useless from another site
+export const apiCors = cors({
+ origin: (origin, c) => (readConfig(c.env).allowedOrigins.includes(origin) ? origin : null),
+ // the browser may only read these when CORS exposes them
+ exposeHeaders: [...RATE_LIMIT_HEADERS, 'X-Request-Id'],
+ maxAge: 600,
+});
diff --git a/backend/middleware/rateLimit.ts b/backend/middleware/rateLimit.ts
index 5e9f948..bc587fe 100644
--- a/backend/middleware/rateLimit.ts
+++ b/backend/middleware/rateLimit.ts
@@ -2,6 +2,7 @@ import type { MiddlewareHandler } from 'hono';
import { checkRateLimit } from '../lib/rateLimit/limiter.ts';
import type { RateLimitRule } from '../lib/rateLimit/limiter.ts';
import type { Decision } from '../lib/rateLimit/algorithms.ts';
+import { errorBody } from './errorHandler.ts';
import type { AppContext, AppEnv } from '../types/app.ts';
export const RATE_LIMIT_HEADERS = ['RateLimit-Limit', 'RateLimit-Remaining', 'RateLimit-Reset', 'Retry-After'];
@@ -62,11 +63,8 @@ export function rateLimit(rule: RateLimitRule, identify: Identify, applies?: (c:
const decision = await checkRateLimit(c.get('rateLimitRedis'), rule, identifier);
if (!decision.allowed) {
- const response = c.json({
- success: false,
- error: `${rule.label} - try again in ${retryWording(decision.retryAfterMs)}.`,
- retryAfter: seconds(decision.retryAfterMs),
- }, 429);
+ const message = `${rule.label} - try again in ${retryWording(decision.retryAfterMs)}.`;
+ const response = c.json({ ...errorBody(c, 'RATE_LIMITED', message), retryAfter: seconds(decision.retryAfterMs) }, 429);
setHeaders(response.headers, decision);
response.headers.set('Retry-After', String(seconds(decision.retryAfterMs)));
return response;
diff --git a/backend/middleware/securityHeaders.ts b/backend/middleware/securityHeaders.ts
new file mode 100644
index 0000000..0c9bb6b
--- /dev/null
+++ b/backend/middleware/securityHeaders.ts
@@ -0,0 +1,8 @@
+import { secureHeaders } from 'hono/secure-headers';
+
+// the API only answers JSON and redirects, so nothing it returns may be framed, sniffed or run as a page
+export const securityHeaders = secureHeaders({
+ contentSecurityPolicy: { defaultSrc: ["'none'"], frameAncestors: ["'none'"] },
+ xFrameOptions: 'DENY',
+ referrerPolicy: 'no-referrer',
+});
diff --git a/backend/routes/index.ts b/backend/routes/index.ts
new file mode 100644
index 0000000..755369c
--- /dev/null
+++ b/backend/routes/index.ts
@@ -0,0 +1,29 @@
+import { Hono } from 'hono';
+import accountRoutes from './accountRoutes.ts';
+import analyticsRoutes from './analyticsRoutes.ts';
+import instagramAuthRoutes from './instagramAuthRoutes.ts';
+import overviewRoutes from './overviewRoutes.ts';
+import publishingRoutes from './publishingRoutes.ts';
+import redditRoutes from './redditRoutes.ts';
+import scheduledPostRoutes from './scheduledPostRoutes.ts';
+import settingsRoutes from './settingsRoutes.ts';
+import trackedContentRoutes from './trackedContentRoutes.ts';
+import { getHealth } from '../controllers/healthController.ts';
+import { handleInstagramCallback } from '../controllers/instagramAuthController.ts';
+import { rateLimit, clientIp } from '../middleware/rateLimit.ts';
+import { RATE_LIMIT_RULES } from '../lib/rateLimit/rules.ts';
+import type { AppEnv } from '../types/app.ts';
+
+// reachable without a token: the health check, and the OAuth redirect, whose signed state names the user
+export const publicRoutes = new Hono<AppEnv>();
+publicRoutes.get('/health', ...getHealth);
+publicRoutes.get('/auth/instagram/callback', rateLimit(RATE_LIMIT_RULES.oauth, clientIp), ...handleInstagramCallback);
+
+// mounted behind requireAuth and the per-user rate limits in app.ts
+export const protectedRoutes = new Hono<AppEnv>();
+for (const routes of [
+ accountRoutes, analyticsRoutes, redditRoutes, publishingRoutes, scheduledPostRoutes, trackedContentRoutes,
+ overviewRoutes, settingsRoutes, instagramAuthRoutes,
+]) {
+ protectedRoutes.route('/', routes);
+}
diff --git a/backend/routes/instagramAuth.ts b/backend/routes/instagramAuth.ts
deleted file mode 100644
index 1c5257a..0000000
--- a/backend/routes/instagramAuth.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { verifyOAuthState } from '../lib/oauthState.ts';
-import {
- readInstagramOAuthConfig, buildAuthorizationUrl, connectInstagramFromOAuth, isOAuthConfigured,
-} from '../services/instagram/instagramOAuth.ts';
-import type { AppContext } from '../types/app.ts';
-import type { InstagramAuthUrlResponse } from '../../shared/types/instagram.ts';
-
-// GET /api/auth/instagram/url - protected; returns the frontend redirect url
-export async function urlHandler(c: AppContext) {
- try {
- const config = readInstagramOAuthConfig(c.env);
- 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);
- } catch (err) {
- console.error('Instagram URL handler error:', (err as Error).message);
- return c.json({ success: false, message: 'Failed to generate auth URL: ' + (err as Error).message }, 500);
- }
-}
-
-// GET /api/auth/instagram/callback - public; the signed state gives the userId
-export async function callbackHandler(c: AppContext) {
- const { code, state, error, error_reason: errorReason } = c.req.query();
- const config = readInstagramOAuthConfig(c.env);
- const accountsUrl = `${config.frontendUrl}/accounts`;
-
- if (error || !code || !state) {
- const reason = errorReason || error || 'cancelled';
- return c.redirect(`${accountsUrl}?ig_error=${encodeURIComponent(reason)}`);
- }
-
- 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`);
- } catch (err) {
- console.error('Instagram OAuth callback error:', (err as Error).message);
- return c.redirect(`${accountsUrl}?ig_error=${encodeURIComponent((err as Error).message.substring(0, 100))}`);
- }
-}
diff --git a/backend/routes/instagramAuthRoutes.ts b/backend/routes/instagramAuthRoutes.ts
new file mode 100644
index 0000000..bc5f14e
--- /dev/null
+++ b/backend/routes/instagramAuthRoutes.ts
@@ -0,0 +1,9 @@
+import { Hono } from 'hono';
+import { getInstagramAuthUrl } from '../controllers/instagramAuthController.ts';
+import type { AppEnv } from '../types/app.ts';
+
+const router = new Hono<AppEnv>();
+
+router.get('/auth/instagram/url', ...getInstagramAuthUrl);
+
+export default router;
diff --git a/backend/routes/keys.ts b/backend/routes/keys.ts
deleted file mode 100644
index b8b9702..0000000
--- a/backend/routes/keys.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { Hono } from 'hono';
-import type { AppEnv } from '../types/app.ts';
-import type { KeysStatusResponse } from '../../shared/types/domain.ts';
-
-const app = new Hono<AppEnv>();
-
-// keys are server env vars; this only reports which are set, for the status ui
-app.get('/keys', (c) => {
- return c.json({
- youtube: { configured: !!c.env.YOUTUBE_API_KEY },
- instagram: { configured: !!(c.env.INSTAGRAM_APP_ID && c.env.INSTAGRAM_APP_SECRET) },
- cloudinary: { configured: !!(c.env.CLOUDINARY_CLOUD_NAME && c.env.CLOUDINARY_UPLOAD_PRESET) },
- } satisfies KeysStatusResponse);
-});
-
-export default app;
diff --git a/backend/routes/overview.ts b/backend/routes/overview.ts
deleted file mode 100644
index c2749fe..0000000
--- a/backend/routes/overview.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { Hono } from 'hono';
-import { getAccounts, getTrackedPosts } from '../lib/db.ts';
-import { summarizeAccountCaches } from '../services/overviewSummary.ts';
-import type { AppContext, AppEnv } from '../types/app.ts';
-import type { OverviewResponse } from '../../shared/types/domain.ts';
-
-const router = new Hono<AppEnv>();
-
-// the client re-polls while syncing, so warming never blocks the response
-function runInBackground(c: AppContext, tasks: Promise<void>[]): void {
- if (tasks.length === 0) return;
- c.executionCtx.waitUntil(Promise.allSettled(tasks));
-}
-
-router.get('/overview', async (c) => {
- const userId = c.get('userId');
- const supabase = c.get('supabase');
- const redis = c.get('redis');
- const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^\uFEFF/, '').trim();
-
- try {
- const [accounts, tracked] = await Promise.all([
- getAccounts(supabase, userId),
- getTrackedPosts(supabase, userId),
- ]);
- const { analyticsCache, warmTasks } = await summarizeAccountCaches(accounts, { redis, userId, apiKey });
- runInBackground(c, warmTasks);
- return c.json({ tracked, analyticsCache } satisfies OverviewResponse);
- } catch (err) {
- console.error('GET /overview:', (err as Error).message);
- return c.json({ error: (err as Error).message }, 500);
- }
-});
-
-export default router;
diff --git a/backend/routes/overviewRoutes.ts b/backend/routes/overviewRoutes.ts
new file mode 100644
index 0000000..7edefeb
--- /dev/null
+++ b/backend/routes/overviewRoutes.ts
@@ -0,0 +1,9 @@
+import { Hono } from 'hono';
+import { getOverview } from '../controllers/overviewController.ts';
+import type { AppEnv } from '../types/app.ts';
+
+const router = new Hono<AppEnv>();
+
+router.get('/overview', ...getOverview);
+
+export default router;
diff --git a/backend/routes/settings.ts b/backend/routes/settings.ts
deleted file mode 100644
index 0e0c2d0..0000000
--- a/backend/routes/settings.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { Hono } from 'hono';
-import { getSettings, saveSettings } from '../lib/db.ts';
-import type { AppEnv } from '../types/app.ts';
-import type { GitHubSettingsRequest, GitHubSettingsResponse, SuccessResponse } from '../../shared/types/domain.ts';
-
-const app = new Hono<AppEnv>();
-
-app.get('/settings/github', async (c) => {
- const settings = await getSettings(c.get('supabase'), c.get('userId'));
- const github = (settings.github || {}) as GitHubSettingsRequest;
- return c.json({
- repoOwner: github.repoOwner || '',
- repoName: github.repoName || '',
- branch: github.branch || 'main',
- } satisfies GitHubSettingsResponse);
-});
-
-// rewrites settings.github whole, so a token saved by older versions is dropped
-app.put('/settings/github', async (c) => {
- const supabase = c.get('supabase');
- const userId = c.get('userId');
- const { repoOwner, repoName, branch } = await c.req.json() as GitHubSettingsRequest;
-
- const current = await getSettings(supabase, userId);
- const github: GitHubSettingsResponse = { repoOwner: repoOwner || '', repoName: repoName || '', branch: branch || 'main' };
- await saveSettings(supabase, { ...current, github }, userId);
- return c.json({ success: true } satisfies SuccessResponse);
-});
-
-export default app;
diff --git a/backend/routes/settingsRoutes.ts b/backend/routes/settingsRoutes.ts
new file mode 100644
index 0000000..45f2fcd
--- /dev/null
+++ b/backend/routes/settingsRoutes.ts
@@ -0,0 +1,11 @@
+import { Hono } from 'hono';
+import { getGithubSettings, saveGithubSettings, getKeyStatus } from '../controllers/settingsController.ts';
+import type { AppEnv } from '../types/app.ts';
+
+const router = new Hono<AppEnv>();
+
+router.get('/settings/github', ...getGithubSettings);
+router.put('/settings/github', ...saveGithubSettings);
+router.get('/keys', ...getKeyStatus);
+
+export default router;
diff --git a/backend/routes/trackedContent.ts b/backend/routes/trackedContent.ts
deleted file mode 100644
index 3c15eea..0000000
--- a/backend/routes/trackedContent.ts
+++ /dev/null
@@ -1,190 +0,0 @@
-import { Hono } from 'hono';
-import {
- getTrackedPosts,
- getTrackedPostById,
- createTrackedPost,
- updateTrackedPost,
- patchTrackedPostData,
- deleteTrackedPost,
- getAccountById,
-} from '../lib/db.ts';
-import { fetchTrackedPostData } from '../services/reddit/redditApi.ts';
-import { fetchTrackedYouTubeData } from '../services/youtube/youtubeTracked.ts';
-import { detectContentType, manualViewsPatch, imageUrlPatch } from '../services/trackedContent.ts';
-import type { AppContext, AppEnv, SupabaseClient } from '../types/app.ts';
-import type { TrackedPostUpdates } from '../lib/db.ts';
-import type { TrackedContentType } from '../services/trackedContent.ts';
-import type {
- SuccessResponse, TrackedContentAddRequest, TrackedContentListResponse, TrackedContentUpdateRequest,
-} from '../../shared/types/domain.ts';
-import type { RedditTrackedPostData } from '../../shared/types/reddit.ts';
-import type { YouTubeTrackedVideoData } from '../../shared/types/youtube.ts';
-
-type TrackedData = YouTubeTrackedVideoData | RedditTrackedPostData;
-
-type RedditCookieLookup = { cookie: string | null; isNotFound?: undefined } | { isNotFound: true; cookie?: undefined };
-
-type TrackedDataFetch = { response: Response; data?: undefined } | { data: TrackedData; response?: undefined };
-
-const router = new Hono<AppEnv>();
-
-// no account means no cookie; a missing or non-reddit account is not found
-async function redditCookieFor(supabase: SupabaseClient, accountId: string | null | undefined, userId: string): Promise<RedditCookieLookup> {
- if (!accountId) return { cookie: null };
- const account = await getAccountById(supabase, accountId, userId);
- if (!account || account.platform !== 'reddit') return { isNotFound: true };
- return { cookie: account.cookie || null };
-}
-
-// returns the fetched data, or an error response the handler sends unchanged
-async function fetchNewTrackedData(
- c: AppContext, contentType: TrackedContentType, url: string, accountId: string | null | undefined,
-): Promise<TrackedDataFetch> {
- if (contentType === 'youtube') {
- const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^\uFEFF/, '').trim();
- if (!apiKey) return { response: c.json({ error: 'YouTube API key not configured on this server' }, 400) };
- return { data: await fetchTrackedYouTubeData(url, apiKey) };
- }
- const reddit = await redditCookieFor(c.get('supabase'), accountId, c.get('userId'));
- if (reddit.isNotFound) return { response: c.json({ error: 'Reddit account not found' }, 404) };
- return { data: await fetchTrackedPostData(url, reddit.cookie) };
-}
-
-router.get('/tracked-content', async (c) => {
- const userId = c.get('userId');
- const supabase = c.get('supabase');
- try {
- const items = await getTrackedPosts(supabase, userId);
- return c.json(items satisfies TrackedContentListResponse);
- } catch (err) {
- console.error('GET /tracked-content:', (err as Error).message);
- return c.json({ error: (err as Error).message }, 500);
- }
-});
-
-router.post('/tracked-content', async (c) => {
- const userId = c.get('userId');
- const supabase = c.get('supabase');
- const body = await c.req.json() as TrackedContentAddRequest;
- const { url, accountId, label, category } = body;
-
- if (!url) return c.json({ error: 'url is required' }, 400);
-
- const contentType = detectContentType(url.trim());
- if (!contentType) return c.json({ error: 'Only Reddit and YouTube URLs are supported' }, 400);
-
- try {
- const fetched = await fetchNewTrackedData(c, contentType, url.trim(), accountId);
- if (fetched.response) return fetched.response;
-
- const id = Date.now().toString(36) + Math.random().toString(36).slice(2);
- await createTrackedPost(supabase, {
- id,
- accountId: contentType === 'youtube' ? null : (accountId || null),
- url: url.trim(),
- label,
- category,
- contentType,
- }, userId);
- await updateTrackedPost(supabase, id, { data: fetched.data as unknown as Record<string, unknown> }, userId);
-
- const created = await getTrackedPostById(supabase, id, userId);
- return c.json(created, 201);
- } catch (err) {
- console.error('POST /tracked-content:', (err as Error).message);
- return c.json({ error: (err as Error).message }, 500);
- }
-});
-
-// Update label, category, account, manually entered view count, or attached image
-router.put('/tracked-content/:id', async (c) => {
- const id = c.req.param('id');
- const userId = c.get('userId');
- const supabase = c.get('supabase');
- const body = await c.req.json() as TrackedContentUpdateRequest;
- const { label, category, accountId, manualViews, imageUrl } = body;
-
- try {
- const existing = await getTrackedPostById(supabase, id, userId);
- if (!existing) return c.json({ error: 'Tracked content not found' }, 404);
-
- const isYouTube = (existing.contentType || 'reddit') === 'youtube';
-
- if (manualViews !== undefined) {
- const viewsResult = manualViewsPatch(manualViews, isYouTube);
- if (viewsResult.error) return c.json({ error: viewsResult.error }, 400);
- await patchTrackedPostData(supabase, id, viewsResult.patch!, userId);
- }
-
- if (imageUrl !== undefined) {
- const imageResult = imageUrlPatch(imageUrl, isYouTube);
- if (imageResult.error) return c.json({ error: imageResult.error }, 400);
- await patchTrackedPostData(supabase, id, imageResult.patch!, userId);
- }
-
- const updates: TrackedPostUpdates = {};
- if (label !== undefined) updates.label = label;
- if (category !== undefined) updates.category = category;
- if (accountId !== undefined) updates.accountId = accountId;
- if (Object.keys(updates).length > 0) {
- await updateTrackedPost(supabase, id, updates, userId);
- }
-
- const updated = await getTrackedPostById(supabase, id, userId);
- return c.json(updated);
- } catch (err) {
- console.error(`PUT /tracked-content/${id}:`, (err as Error).message);
- return c.json({ error: (err as Error).message }, 500);
- }
-});
-
-router.delete('/tracked-content/:id', async (c) => {
- const id = c.req.param('id');
- const userId = c.get('userId');
- const supabase = c.get('supabase');
- try {
- const existing = await getTrackedPostById(supabase, id, userId);
- if (!existing) return c.json({ error: 'Tracked content not found' }, 404);
- await deleteTrackedPost(supabase, id, userId);
- return c.json({ success: true } satisfies SuccessResponse);
- } catch (err) {
- console.error(`DELETE /tracked-content/${id}:`, (err as Error).message);
- return c.json({ error: (err as Error).message }, 500);
- }
-});
-
-router.post('/tracked-content/:id/refresh', async (c) => {
- const id = c.req.param('id');
- const userId = c.get('userId');
- const supabase = c.get('supabase');
- try {
- const existing = await getTrackedPostById(supabase, id, userId);
- if (!existing) return c.json({ error: 'Tracked content not found' }, 404);
-
- const contentType = existing.contentType || 'reddit';
- let fetchedData: TrackedData;
-
- if (contentType === 'youtube') {
- const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^\uFEFF/, '').trim();
- if (!apiKey) return c.json({ error: 'YouTube API key not configured on this server' }, 400);
- fetchedData = await fetchTrackedYouTubeData(existing.url, apiKey);
- } else {
- let cookie: string | null = null;
- if (existing.accountId) {
- const account = await getAccountById(supabase, existing.accountId, userId);
- cookie = account?.cookie || null;
- }
- fetchedData = await fetchTrackedPostData(existing.url, cookie);
- }
-
- // Patch rather than replace so a manually entered view count survives the refresh
- await patchTrackedPostData(supabase, id, fetchedData as unknown as Record<string, unknown>, userId);
- const updated = await getTrackedPostById(supabase, id, userId);
- return c.json(updated);
- } catch (err) {
- console.error(`POST /tracked-content/${id}/refresh:`, (err as Error).message);
- return c.json({ error: (err as Error).message }, 500);
- }
-});
-
-export default router;
diff --git a/backend/routes/trackedContentRoutes.ts b/backend/routes/trackedContentRoutes.ts
new file mode 100644
index 0000000..a3ee072
--- /dev/null
+++ b/backend/routes/trackedContentRoutes.ts
@@ -0,0 +1,15 @@
+import { Hono } from 'hono';
+import {
+ listTrackedContent, addTrackedContent, updateTrackedContent, deleteTrackedContent, refreshTrackedContent,
+} from '../controllers/trackedContentController.ts';
+import type { AppEnv } from '../types/app.ts';
+
+const router = new Hono<AppEnv>();
+
+router.get('/tracked-content', ...listTrackedContent);
+router.post('/tracked-content', ...addTrackedContent);
+router.put('/tracked-content/:id', ...updateTrackedContent);
+router.delete('/tracked-content/:id', ...deleteTrackedContent);
+router.post('/tracked-content/:id/refresh', ...refreshTrackedContent);
+
+export default router;
diff --git a/backend/server.ts b/backend/server.ts
index 59faeaf..a4d10f1 100644
--- a/backend/server.ts
+++ b/backend/server.ts
@@ -1,74 +1,8 @@
-import { Hono } from 'hono';
-import { cors } from 'hono/cors';
-import { requestId } from 'hono/request-id';
-import { getSupabase } from './database/supabase.ts';
-import { getRedis, getRateLimitRedis } from './database/redis.ts';
-import { requireAuth } from './middleware/auth.ts';
-import { requestContext } from './middleware/requestContext.ts';
-import { errorHandler, notFoundHandler } from './middleware/errorHandler.ts';
-import { rateLimit, clientIp, userKey, RATE_LIMIT_HEADERS } from './middleware/rateLimit.ts';
-import { RATE_LIMIT_RULES, QUOTA_ROUTES, PUBLISH_ROUTES, matchesRoute } from './lib/rateLimit/rules.ts';
-import keysRouter from './routes/keys.ts';
-import accountRoutes from './routes/accountRoutes.ts';
-import analyticsRoutes from './routes/analyticsRoutes.ts';
-import publishingRoutes from './routes/publishingRoutes.ts';
-import scheduledPostRoutes from './routes/scheduledPostRoutes.ts';
-import settingsRouter from './routes/settings.ts';
-import redditRoutes from './routes/redditRoutes.ts';
-import trackedContentRouter from './routes/trackedContent.ts';
-import overviewRouter from './routes/overview.ts';
-import { urlHandler, callbackHandler } from './routes/instagramAuth.ts';
+import { app } from './app.ts';
import { runScheduledJob } from './jobs/scheduled.ts';
-import type { AppEnv } from './types/app.ts';
import type { Env } from './types/env.ts';
-const app = new Hono<AppEnv>();
-
-app.onError(errorHandler);
-app.notFound(notFoundHandler);
-
-// the browser may only read the rate limit headers when CORS exposes them
-app.use('*', cors({ exposeHeaders: RATE_LIMIT_HEADERS }));
-app.use('*', requestId());
-app.use('*', requestContext);
-
-// both clients are stateless http clients, so creating them per request is safe
-app.use('*', async (c, next) => {
- c.set('supabase', getSupabase(c.env));
- c.set('redis', getRedis(c.env));
- c.set('rateLimitRedis', getRateLimitRedis(c.env));
- await next();
-});
-
-// before authentication, so a flood of bad tokens never reaches Supabase auth
-app.use('/api/*', rateLimit(RATE_LIMIT_RULES.ip, clientIp));
-
-app.get('/api/health', (c) => c.json({ status: 'ok', timestamp: new Date().toISOString() }));
-
-// public: the oauth redirect has no jwt; the signed hmac state names the user
-app.get('/api/auth/instagram/callback', rateLimit(RATE_LIMIT_RULES.oauth, clientIp), callbackHandler);
-
-const api = new Hono<AppEnv>();
-api.use('*', requireAuth);
-api.use('*', rateLimit(RATE_LIMIT_RULES.user, userKey));
-api.use('*', rateLimit(RATE_LIMIT_RULES.quota, userKey, c => matchesRoute(QUOTA_ROUTES, c.req.method, c.req.path)));
-api.use('*', rateLimit(RATE_LIMIT_RULES.publish, userKey, c => matchesRoute(PUBLISH_ROUTES, c.req.method, c.req.path)));
-
-api.route('/', keysRouter);
-api.route('/', accountRoutes);
-api.route('/', analyticsRoutes);
-api.route('/', publishingRoutes);
-api.route('/', scheduledPostRoutes);
-api.route('/', settingsRouter);
-api.route('/', redditRoutes);
-api.route('/', trackedContentRouter);
-api.route('/', overviewRouter);
-
-// protected: the state token needs the user id
-api.get('/auth/instagram/url', urlHandler);
-
-app.route('/api', api);
-
+// the Worker's two entry points: HTTP requests go through the pipeline in app.ts, cron triggers to jobs/
export default {
fetch: app.fetch,
diff --git a/backend/services/instagram/instagramOAuth.ts b/backend/services/instagram/instagramOAuth.ts
index 75fc6a6..94f6a93 100644
--- a/backend/services/instagram/instagramOAuth.ts
+++ b/backend/services/instagram/instagramOAuth.ts
@@ -1,37 +1,19 @@
import { createOAuthState } from '../../lib/oauthState.ts';
-import { createAccount, getAccounts } from '../../lib/db.ts';
-import { fetchInstagramProfile } from './instagramApi.ts';
-import { buildInstagramAccount } from '../accountFactory.ts';
+import { UpstreamError, UpstreamTimeoutError, isAbortError } from '../../lib/errors.ts';
import type { InstagramApiToken } from './instagramTokens.ts';
-import type { Env } from '../../types/env.ts';
-import type { SupabaseClient } from '../../types/app.ts';
+import type { InstagramOAuthConfig } from '../../lib/config.ts';
-const DEFAULT_BACKEND_URL = 'http://localhost:8787';
-const DEFAULT_FRONTEND_URL = 'http://localhost:5173';
-const CALLBACK_PATH = '/api/auth/instagram/callback';
const AUTHORIZE_URL = 'https://www.instagram.com/oauth/authorize';
const TOKEN_URL = 'https://api.instagram.com/oauth/access_token';
const LONG_LIVED_TOKEN_URL = 'https://graph.instagram.com/access_token';
const OAUTH_SCOPES = 'instagram_business_basic,instagram_business_manage_messages,instagram_business_manage_comments,instagram_business_content_publish,instagram_business_manage_insights';
-export type InstagramOAuthEnv = Pick<Env, 'FRONTEND_URL' | 'BACKEND_URL' | 'INSTAGRAM_APP_ID' | 'INSTAGRAM_APP_SECRET'>;
-
-// appId and appSecret are undefined when the Worker secrets are not set
-export interface InstagramOAuthConfig {
- frontendUrl: string;
- redirectUri: string;
- appId: string | undefined;
- appSecret: string | undefined;
-}
-
-// what the token exchange needs; urlHandler and callbackHandler check for it first
+// what the token exchange needs; callers check isOAuthConfigured() 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
interface InstagramApiCodeToken {
access_token?: string;
@@ -42,30 +24,24 @@ interface InstagramApiCodeToken {
code?: number;
}
-// pasted secrets can carry a byte order mark or stray whitespace
-function cleanSecret(value: string | undefined): string | undefined {
- return value?.replace(/^\uFEFF/, '').trim();
-}
-
-function cleanUrl(value: string | undefined, fallback: string): string {
- return (value || fallback).replace(/^\uFEFF/, '').trim();
-}
-
-export function readInstagramOAuthConfig(env: InstagramOAuthEnv): InstagramOAuthConfig {
- const frontendUrl = cleanUrl(env.FRONTEND_URL, DEFAULT_FRONTEND_URL);
- const backendUrl = cleanUrl(env.BACKEND_URL, DEFAULT_BACKEND_URL).replace(/\/$/, '');
- return {
- frontendUrl,
- redirectUri: `${backendUrl}${CALLBACK_PATH}`,
- appId: cleanSecret(env.INSTAGRAM_APP_ID),
- appSecret: cleanSecret(env.INSTAGRAM_APP_SECRET),
- };
+export interface IssuedInstagramToken {
+ token: string;
+ expiresIn: number;
}
export function isOAuthConfigured(config: InstagramOAuthConfig): config is ConfiguredInstagramOAuth {
return !!config.appId && !!config.appSecret;
}
+async function instagramRequest(url: string, init: RequestInit, signal?: AbortSignal): Promise<Response> {
+ try {
+ return await fetch(url, { ...init, signal });
+ } catch (err) {
+ if (isAbortError(err)) throw new UpstreamTimeoutError('Instagram', err);
+ throw new UpstreamError(`Instagram API unreachable (${(err as Error).message})`, { cause: err });
+ }
+}
+
// the hmac-signed state carries the userId and a timestamp, so no redis is needed
export async function buildAuthorizationUrl(config: ConfiguredInstagramOAuth, userId: string): Promise<string> {
const state = await createOAuthState(userId, config.appSecret);
@@ -80,8 +56,8 @@ export async function buildAuthorizationUrl(config: ConfiguredInstagramOAuth, us
return `${AUTHORIZE_URL}?${params}`;
}
-async function exchangeCodeForToken(config: ConfiguredInstagramOAuth, code: string): Promise<string> {
- const tokenRes = await fetch(TOKEN_URL, {
+export async function exchangeCodeForToken(config: ConfiguredInstagramOAuth, code: string, signal?: AbortSignal): Promise<string> {
+ const tokenRes = await instagramRequest(TOKEN_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
@@ -92,43 +68,23 @@ async function exchangeCodeForToken(config: ConfiguredInstagramOAuth, code: stri
// instagram sometimes appends #_ to the code
code: code.replace(/#.*$/, ''),
}),
- });
+ }, signal);
const tokenData = await tokenRes.json() as InstagramApiCodeToken;
if (!tokenData.access_token) {
- throw new Error(tokenData.error_message || JSON.stringify(tokenData));
+ throw new UpstreamError(tokenData.error_message || JSON.stringify(tokenData));
}
return tokenData.access_token;
}
// keeps the short-lived token (no expiry) when instagram declines the upgrade
-async function upgradeToLongLivedToken(config: ConfiguredInstagramOAuth, shortToken: string): Promise<{ token: string; expiresIn: number }> {
+export async function upgradeToLongLivedToken(config: ConfiguredInstagramOAuth, shortToken: string, signal?: AbortSignal): Promise<IssuedInstagramToken> {
const longParams = new URLSearchParams({
grant_type: 'ig_exchange_token',
client_id: config.appId,
client_secret: config.appSecret,
access_token: shortToken,
});
- const longRes = await fetch(`${LONG_LIVED_TOKEN_URL}?${longParams}`);
+ const longRes = await instagramRequest(`${LONG_LIVED_TOKEN_URL}?${longParams}`, {}, signal);
const longData = await longRes.json() as InstagramApiToken;
return { token: longData.access_token || shortToken, expiresIn: longData.expires_in || 0 };
}
-
-export async function connectInstagramFromOAuth(
- supabase: SupabaseClient, userId: string, config: ConfiguredInstagramOAuth, code: string,
-): Promise<InstagramOAuthOutcome> {
- const shortToken = await exchangeCodeForToken(config, code);
- const { token, expiresIn } = await upgradeToLongLivedToken(config, shortToken);
-
- const profile = await fetchInstagramProfile(null, token);
- if (!profile.igUserId) {
- throw new Error('Could not get Instagram User ID. Account must be a Business or Creator account.');
- }
-
- const existing = await getAccounts(supabase, userId);
- if (existing.find(account => account.platform === 'instagram' && account.igUserId === profile.igUserId)) {
- return 'already_added';
- }
-
- await createAccount(supabase, buildInstagramAccount(profile, token, expiresIn), userId);
- return 'connected';
-}
diff --git a/backend/services/instagramConnectService.ts b/backend/services/instagramConnectService.ts
new file mode 100644
index 0000000..491ac97
--- /dev/null
+++ b/backend/services/instagramConnectService.ts
@@ -0,0 +1,60 @@
+import { buildAuthorizationUrl, exchangeCodeForToken, isOAuthConfigured, upgradeToLongLivedToken } from './instagram/instagramOAuth.ts';
+import { fetchInstagramProfile } from './instagram/instagramApi.ts';
+import { buildInstagramAccount } from './accountFactory.ts';
+import { verifyOAuthState } from '../lib/oauthState.ts';
+import { NotConfiguredError, ValidationError } from '../lib/errors.ts';
+import type { ConfiguredInstagramOAuth } from './instagram/instagramOAuth.ts';
+import type { AccountRepository } from '../repositories/accountRepository.ts';
+import type { AppConfig } from '../lib/config.ts';
+import type { RequestContext } from '../types/context.ts';
+
+export interface InstagramConnectDeps {
+ accounts: AccountRepository;
+ config: AppConfig;
+ context: RequestContext;
+}
+
+export type InstagramConnectOutcome = 'already_added' | 'connected';
+
+export interface InstagramConnectService {
+ readonly configured: boolean;
+ readonly accountsPageUrl: string;
+ authorizationUrl(userId: string): Promise<string>;
+ userIdFromState(state: string): Promise<string | null>;
+ connect(userId: string, code: string): Promise<InstagramConnectOutcome>;
+}
+
+// connects an account through Instagram's OAuth: the user id travels in the signed state, not in a session
+export function createInstagramConnectService({ accounts, config, context }: InstagramConnectDeps): InstagramConnectService {
+ const { signal } = context;
+ const oauth = config.instagram;
+
+ function configured(): ConfiguredInstagramOAuth {
+ if (!isOAuthConfigured(oauth)) throw new NotConfiguredError('Instagram App credentials not configured on server');
+ return oauth;
+ }
+
+ return {
+ configured: isOAuthConfigured(oauth),
+ accountsPageUrl: `${oauth.frontendUrl}/accounts`,
+
+ authorizationUrl: async userId => buildAuthorizationUrl(configured(), userId),
+
+ userIdFromState: async state => verifyOAuthState(state, configured().appSecret),
+
+ async connect(userId, code) {
+ const settings = configured();
+ const shortToken = await exchangeCodeForToken(settings, code, signal);
+ const { token, expiresIn } = await upgradeToLongLivedToken(settings, shortToken, signal);
+
+ const profile = await fetchInstagramProfile(null, token, signal);
+ if (!profile.igUserId) throw new ValidationError('Could not get Instagram User ID. Account must be a Business or Creator account.');
+
+ const existing = await accounts.listForUser(userId);
+ if (existing.some(account => account.platform === 'instagram' && account.igUserId === profile.igUserId)) return 'already_added';
+
+ await accounts.create(buildInstagramAccount(profile, token, expiresIn), userId);
+ return 'connected';
+ },
+ };
+}
diff --git a/backend/services/overviewService.ts b/backend/services/overviewService.ts
new file mode 100644
index 0000000..3410b61
--- /dev/null
+++ b/backend/services/overviewService.ts
@@ -0,0 +1,141 @@
+import { fetchAllVideos } from './youtube/youtubeVideos.ts';
+import { fetchInstagramMedia } from './instagram/instagramMedia.ts';
+import { summarizeContentTypes } from './instagram/instagramContentTypes.ts';
+import { fetchRedditProfile, fetchRedditPosts } from './reddit/redditApi.ts';
+import { computeRedditAnalytics } from './reddit/redditAnalytics.ts';
+import type { AccountRepository } from '../repositories/accountRepository.ts';
+import type { AnalyticsCacheRepository } from '../repositories/analyticsCacheRepository.ts';
+import type { TrackedPostRepository } from '../repositories/trackedPostRepository.ts';
+import type { AppConfig } from '../lib/config.ts';
+import type {
+ Account, AccountSummary, InstagramAccountSummary, OverviewAnalyticsCache, PendingAccountSummary, RedditAccountSummary,
+ TrackedPost, YouTubeAccountSummary,
+} from '../../shared/types/domain.ts';
+
+export interface OverviewDeps {
+ accounts: AccountRepository;
+ tracked: TrackedPostRepository;
+ cache: AnalyticsCacheRepository;
+ config: AppConfig;
+}
+
+export interface OverviewSummary {
+ tracked: TrackedPost[];
+ analyticsCache: OverviewAnalyticsCache;
+ // already running; the controller keeps them alive after the response with waitUntil
+ warmTasks: Promise<void>[];
+}
+
+export interface OverviewService {
+ summary(userId: string): Promise<OverviewSummary>;
+}
+
+type WarmTask = (signal: AbortSignal) => Promise<void>;
+
+// warming outlives the response, so it gets its own deadline instead of the request's signal
+const WARM_DEADLINE_MS = 25_000;
+
+function sumBy<T>(items: T[], pick: (item: T) => number): number {
+ return items.reduce((total, item) => total + pick(item), 0);
+}
+
+export function createOverviewService({ accounts, tracked, cache, config }: OverviewDeps): OverviewService {
+ function redditWarmTask(userId: string, account: Account): WarmTask | null {
+ const { username, cookie } = account;
+ if (!username || !cookie) return null;
+ return async signal => {
+ const [profile, posts] = await Promise.all([
+ fetchRedditProfile(username, cookie, signal),
+ fetchRedditPosts(username, cookie, 100, signal),
+ ]);
+ await cache.setReddit(userId, account.id, { profile, analytics: computeRedditAnalytics(profile, posts), posts });
+ };
+ }
+
+ function instagramWarmTask(userId: string, account: Account): WarmTask | null {
+ const { igUserId, accessToken } = account;
+ if (!igUserId || !accessToken) return null;
+ return async signal => {
+ const media = await fetchInstagramMedia(igUserId, accessToken, 500, signal);
+ await cache.setInstagramMedia(userId, account.id, { media, fetchedAt: new Date().toISOString() });
+ };
+ }
+
+ function youtubeWarmTask(userId: string, account: Account): WarmTask | null {
+ const apiKey = config.youtubeApiKey;
+ const { uploadsPlaylistId } = account;
+ if (!apiKey || !uploadsPlaylistId) return null;
+ return async signal => {
+ const videos = await fetchAllVideos(uploadsPlaylistId, apiKey, 10, signal);
+ await cache.setVideos(userId, account.id, { videos, fetchedAt: new Date().toISOString() });
+ };
+ }
+
+ return {
+ async summary(userId) {
+ const warmTasks: Promise<void>[] = [];
+
+ // syncing only when a fetch started, so the client never waits for nothing
+ const startWarm = (accountId: string, task: WarmTask | null): PendingAccountSummary => {
+ if (!cache.enabled || !task) return { id: accountId, cacheWarmed: false, syncing: false };
+ // a failed warm leaves the cache empty, so the next load starts it again
+ warmTasks.push(task(AbortSignal.timeout(WARM_DEADLINE_MS)).catch(() => undefined));
+ return { id: accountId, cacheWarmed: false, syncing: true };
+ };
+
+ const summarizeReddit = async (account: Account): Promise<RedditAccountSummary | PendingAccountSummary> => {
+ const cached = await cache.getReddit(userId, account.id);
+ if (!cached?.analytics) return startWarm(account.id, redditWarmTask(userId, account));
+ return {
+ id: account.id,
+ cacheWarmed: true,
+ fetchedPosts: cached.analytics.fetchedPosts ?? 0,
+ totalScore: cached.analytics.totalScore ?? 0,
+ totalComments: cached.analytics.totalComments ?? 0,
+ };
+ };
+
+ const summarizeInstagram = async (account: Account): Promise<InstagramAccountSummary | PendingAccountSummary> => {
+ const cached = await cache.getInstagramMedia(userId, account.id);
+ if (!cached?.media) return startWarm(account.id, instagramWarmTask(userId, account));
+ const contentTypes = summarizeContentTypes(cached.media);
+ const types = Object.values(contentTypes);
+ return {
+ id: account.id,
+ cacheWarmed: true,
+ totalLikes: sumBy(types, type => type.likes),
+ totalComments: sumBy(types, type => type.comments),
+ totalViews: sumBy(types, type => type.views),
+ contentTypes,
+ };
+ };
+
+ const summarizeYouTube = async (account: Account): Promise<YouTubeAccountSummary | PendingAccountSummary> => {
+ const cached = await cache.getVideos(userId, account.id);
+ if (!cached?.videos) return startWarm(account.id, youtubeWarmTask(userId, account));
+ return {
+ id: account.id,
+ cacheWarmed: true,
+ totalLikes: sumBy(cached.videos, video => video.likeCount ?? 0),
+ totalComments: sumBy(cached.videos, video => video.commentCount ?? 0),
+ };
+ };
+
+ const summarize = (account: Account): Promise<AccountSummary> => {
+ if (account.platform === 'reddit') return summarizeReddit(account);
+ if (account.platform === 'instagram') return summarizeInstagram(account);
+ return summarizeYouTube(account);
+ };
+
+ const [listed, trackedItems] = await Promise.all([accounts.listForUser(userId), tracked.listForUser(userId)]);
+ const results = await Promise.allSettled(listed.map(summarize));
+
+ // a failed cache read leaves the account out instead of failing the overview
+ const analyticsCache: OverviewAnalyticsCache = {};
+ results.forEach(result => {
+ if (result.status === 'fulfilled' && result.value?.id) analyticsCache[result.value.id] = result.value;
+ });
+ return { tracked: trackedItems, analyticsCache, warmTasks };
+ },
+ };
+}
diff --git a/backend/services/overviewSummary.ts b/backend/services/overviewSummary.ts
deleted file mode 100644
index 46adab2..0000000
--- a/backend/services/overviewSummary.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-import { getVideosCache, setVideosCache, getIGCache, setIGCache, getRedditCache, setRedditCache } from '../lib/cache.ts';
-import { fetchAllVideos } from './youtube/youtubeVideos.ts';
-import { fetchInstagramMedia } from './instagram/instagramMedia.ts';
-import { summarizeContentTypes } from './instagram/instagramContentTypes.ts';
-import { fetchRedditProfile, fetchRedditPosts, computeRedditAnalytics } from './reddit/redditApi.ts';
-import type { Redis } from '../types/app.ts';
-import type {
- Account, AccountSummary, PendingAccountSummary, RedditAccountSummary, InstagramAccountSummary,
- YouTubeAccountSummary, OverviewAnalyticsCache,
-} from '../../shared/types/domain.ts';
-
-type WarmTask = () => Promise<void>;
-
-export interface OverviewSummaryOptions {
- redis: Redis | null;
- userId: string;
- apiKey: string | undefined;
-}
-
-interface SummaryContext extends OverviewSummaryOptions {
- warmTasks: Promise<void>[];
-}
-
-export interface OverviewSummaries {
- analyticsCache: OverviewAnalyticsCache;
- warmTasks: Promise<void>[];
-}
-
-function sumBy<T>(items: T[], pick: (item: T) => number): number {
- return items.reduce((total, item) => total + pick(item), 0);
-}
-
-// syncing only when a fetch started, so the client never waits for nothing
-function startWarm(context: SummaryContext, accountId: string, task: WarmTask | null): PendingAccountSummary {
- if (!context.redis || !task) return { id: accountId, cacheWarmed: false, syncing: false };
- // a failed warm leaves the cache empty, so the next load starts it again
- context.warmTasks.push(task().catch(() => undefined));
- return { id: accountId, cacheWarmed: false, syncing: true };
-}
-
-function redditWarmTask(context: SummaryContext, account: Account): WarmTask | null {
- const { username, cookie } = account;
- if (!username || !cookie) return null;
- return async () => {
- const [profile, posts] = await Promise.all([
- fetchRedditProfile(username, cookie),
- fetchRedditPosts(username, cookie, 100),
- ]);
- await setRedditCache(context.redis, context.userId, account.id, { profile, analytics: computeRedditAnalytics(profile, posts), posts });
- };
-}
-
-function instagramWarmTask(context: SummaryContext, account: Account): WarmTask | null {
- const { igUserId, accessToken } = account;
- if (!igUserId || !accessToken) return null;
- return async () => {
- const media = await fetchInstagramMedia(igUserId, accessToken, 500);
- await setIGCache(context.redis, context.userId, account.id, { media, fetchedAt: new Date().toISOString() });
- };
-}
-
-function youtubeWarmTask(context: SummaryContext, account: Account): WarmTask | null {
- const { apiKey } = context;
- const { uploadsPlaylistId } = account;
- if (!apiKey || !uploadsPlaylistId) return null;
- return async () => {
- const videos = await fetchAllVideos(uploadsPlaylistId, apiKey, 10);
- await setVideosCache(context.redis, context.userId, account.id, { videos, fetchedAt: new Date().toISOString() });
- };
-}
-
-async function summarizeReddit(context: SummaryContext, account: Account): Promise<RedditAccountSummary | PendingAccountSummary> {
- const cached = await getRedditCache(context.redis, context.userId, account.id);
- if (!cached?.analytics) return startWarm(context, account.id, redditWarmTask(context, account));
- return {
- id: account.id,
- cacheWarmed: true,
- fetchedPosts: cached.analytics.fetchedPosts ?? 0,
- totalScore: cached.analytics.totalScore ?? 0,
- totalComments: cached.analytics.totalComments ?? 0,
- };
-}
-
-async function summarizeInstagram(context: SummaryContext, account: Account): Promise<InstagramAccountSummary | PendingAccountSummary> {
- const cached = await getIGCache(context.redis, context.userId, account.id);
- if (!cached?.media) return startWarm(context, account.id, instagramWarmTask(context, account));
- const contentTypes = summarizeContentTypes(cached.media);
- const types = Object.values(contentTypes);
- return {
- id: account.id,
- cacheWarmed: true,
- totalLikes: sumBy(types, type => type.likes),
- totalComments: sumBy(types, type => type.comments),
- totalViews: sumBy(types, type => type.views),
- contentTypes,
- };
-}
-
-async function summarizeYouTube(context: SummaryContext, account: Account): Promise<YouTubeAccountSummary | PendingAccountSummary> {
- const cached = await getVideosCache(context.redis, context.userId, account.id);
- if (!cached?.videos) return startWarm(context, account.id, youtubeWarmTask(context, account));
- return {
- id: account.id,
- cacheWarmed: true,
- totalLikes: sumBy(cached.videos, video => video.likeCount ?? 0),
- totalComments: sumBy(cached.videos, video => video.commentCount ?? 0),
- };
-}
-
-async function summarizeAccount(context: SummaryContext, account: Account): Promise<AccountSummary> {
- if (account.platform === 'reddit') return summarizeReddit(context, account);
- if (account.platform === 'instagram') return summarizeInstagram(context, account);
- return summarizeYouTube(context, account);
-}
-
-// a failed cache read leaves the account out instead of failing the overview
-function collectSummaries(results: PromiseSettledResult<AccountSummary>[]): OverviewAnalyticsCache {
- const analyticsCache: OverviewAnalyticsCache = {};
- results.forEach(result => {
- if (result.status === 'fulfilled' && result.value?.id) {
- analyticsCache[result.value.id] = result.value;
- }
- });
- return analyticsCache;
-}
-
-// the warm tasks already run; the caller decides how long they are kept alive
-export async function summarizeAccountCaches(accounts: Account[], { redis, userId, apiKey }: OverviewSummaryOptions): Promise<OverviewSummaries> {
- const context: SummaryContext = { redis, userId, apiKey, warmTasks: [] };
- const results = await Promise.allSettled(accounts.map(account => summarizeAccount(context, account)));
- return { analyticsCache: collectSummaries(results), warmTasks: context.warmTasks };
-}
diff --git a/backend/services/settingsService.ts b/backend/services/settingsService.ts
new file mode 100644
index 0000000..abec92d
--- /dev/null
+++ b/backend/services/settingsService.ts
@@ -0,0 +1,39 @@
+import type { SettingsRepository } from '../repositories/settingsRepository.ts';
+import type { AppConfig } from '../lib/config.ts';
+import type { GitHubSettingsRequest, GitHubSettingsResponse, KeysStatusResponse } from '../../shared/types/domain.ts';
+
+export interface SettingsDeps {
+ settings: SettingsRepository;
+ config: AppConfig;
+}
+
+export interface SettingsService {
+ githubSettings(userId: string): Promise<GitHubSettingsResponse>;
+ saveGithubSettings(userId: string, input: GitHubSettingsRequest): Promise<void>;
+ serverKeyStatus(): KeysStatusResponse;
+}
+
+export function createSettingsService({ settings, config }: SettingsDeps): SettingsService {
+ return {
+ async githubSettings(userId) {
+ const github = ((await settings.getForUser(userId)).github || {}) as GitHubSettingsRequest;
+ return { repoOwner: github.repoOwner || '', repoName: github.repoName || '', branch: github.branch || 'main' };
+ },
+
+ // rewrites settings.github whole, so a token saved by older versions is dropped
+ async saveGithubSettings(userId, { repoOwner, repoName, branch }) {
+ const current = await settings.getForUser(userId);
+ const github: GitHubSettingsResponse = { repoOwner: repoOwner || '', repoName: repoName || '', branch: branch || 'main' };
+ await settings.saveForUser({ ...current, github }, userId);
+ },
+
+ // the keys are Worker secrets; this only reports which are set, for the Settings page
+ serverKeyStatus() {
+ return {
+ youtube: { configured: !!config.youtubeApiKey },
+ instagram: { configured: !!(config.instagram.appId && config.instagram.appSecret) },
+ cloudinary: { configured: config.cloudinary !== null },
+ };
+ },
+ };
+}
diff --git a/backend/services/trackedContent.ts b/backend/services/trackedContentRules.ts
similarity index 100%
rename from backend/services/trackedContent.ts
rename to backend/services/trackedContentRules.ts
diff --git a/backend/services/trackedContentService.ts b/backend/services/trackedContentService.ts
new file mode 100644
index 0000000..f23f023
--- /dev/null
+++ b/backend/services/trackedContentService.ts
@@ -0,0 +1,126 @@
+import { fetchTrackedPostData } from './reddit/redditApi.ts';
+import { fetchTrackedYouTubeData } from './youtube/youtubeTracked.ts';
+import { detectContentType, manualViewsPatch, imageUrlPatch } from './trackedContentRules.ts';
+import { NotConfiguredError, NotFoundError, ValidationError } from '../lib/errors.ts';
+import type { PatchResult, TrackedContentType } from './trackedContentRules.ts';
+import type { AccountRepository } from '../repositories/accountRepository.ts';
+import type { TrackedPostRepository, TrackedPostUpdates } from '../repositories/trackedPostRepository.ts';
+import type { AppConfig } from '../lib/config.ts';
+import type { RequestContext } from '../types/context.ts';
+import type { TrackedPost } from '../../shared/types/domain.ts';
+import type { RedditTrackedPostData } from '../../shared/types/reddit.ts';
+import type { YouTubeTrackedVideoData } from '../../shared/types/youtube.ts';
+
+export interface TrackedContentDeps {
+ accounts: AccountRepository;
+ tracked: TrackedPostRepository;
+ config: AppConfig;
+ context: RequestContext;
+}
+
+export interface NewTrackedContent {
+ url: string;
+ accountId?: string | null;
+ label?: string;
+ category?: string;
+}
+
+// manualViews and imageUrl arrive as the client sent them; the rules decide what is valid
+export interface TrackedContentChanges {
+ label?: string;
+ category?: string;
+ accountId?: string | null;
+ manualViews?: unknown;
+ imageUrl?: unknown;
+}
+
+export interface TrackedContentService {
+ list(userId: string): Promise<TrackedPost[]>;
+ add(userId: string, input: NewTrackedContent): Promise<TrackedPost | null>;
+ update(userId: string, id: string, changes: TrackedContentChanges): Promise<TrackedPost | null>;
+ remove(userId: string, id: string): Promise<void>;
+ refresh(userId: string, id: string): Promise<TrackedPost | null>;
+}
+
+type TrackedData = YouTubeTrackedVideoData | RedditTrackedPostData;
+
+function newTrackedId(): string {
+ return Date.now().toString(36) + Math.random().toString(36).slice(2);
+}
+
+function patchOrThrow<P>(result: PatchResult<P>): P {
+ if (result.error !== undefined) throw new ValidationError(result.error);
+ return result.patch;
+}
+
+export function createTrackedContentService({ accounts, tracked, config, context }: TrackedContentDeps): TrackedContentService {
+ const { signal } = context;
+
+ function youtubeKey(): string {
+ if (!config.youtubeApiKey) throw new NotConfiguredError('YouTube API key not configured on this server');
+ return config.youtubeApiKey;
+ }
+
+ async function findOwned(userId: string, id: string): Promise<TrackedPost> {
+ const item = await tracked.findForUser(id, userId);
+ if (!item) throw new NotFoundError('Tracked content not found');
+ return item;
+ }
+
+ // a named account must be one of the user's Reddit accounts; no account means no cookie
+ async function redditCookie(userId: string, accountId: string | null | undefined, strict: boolean): Promise<string | null> {
+ if (!accountId) return null;
+ const account = await accounts.findForUser(accountId, userId);
+ if (strict && (!account || account.platform !== 'reddit')) throw new NotFoundError('Reddit account not found');
+ return account?.cookie || null;
+ }
+
+ async function fetchData(userId: string, contentType: TrackedContentType, url: string, accountId: string | null | undefined, strict: boolean): Promise<TrackedData> {
+ if (contentType === 'youtube') return fetchTrackedYouTubeData(url, youtubeKey(), signal);
+ return fetchTrackedPostData(url, await redditCookie(userId, accountId, strict), signal);
+ }
+
+ return {
+ list: userId => tracked.listForUser(userId),
+
+ async add(userId, { url, accountId, label, category }) {
+ const contentType = detectContentType(url);
+ if (!contentType) throw new ValidationError('Only Reddit and YouTube URLs are supported');
+ const data = await fetchData(userId, contentType, url, accountId, true);
+
+ const id = newTrackedId();
+ await tracked.create({ id, accountId: contentType === 'youtube' ? null : (accountId || null), url, label, category, contentType }, userId);
+ await tracked.updateForUser(id, { data: data as unknown as Record<string, unknown> }, userId);
+ return tracked.findForUser(id, userId);
+ },
+
+ async update(userId, id, { label, category, accountId, manualViews, imageUrl }) {
+ const existing = await findOwned(userId, id);
+ const isYouTube = (existing.contentType || 'reddit') === 'youtube';
+
+ if (manualViews !== undefined) await tracked.patchDataForUser(id, patchOrThrow(manualViewsPatch(manualViews, isYouTube)), userId);
+ if (imageUrl !== undefined) await tracked.patchDataForUser(id, patchOrThrow(imageUrlPatch(imageUrl, isYouTube)), userId);
+
+ const updates: TrackedPostUpdates = {};
+ if (label !== undefined) updates.label = label;
+ if (category !== undefined) updates.category = category;
+ if (accountId !== undefined) updates.accountId = accountId;
+ if (Object.keys(updates).length > 0) await tracked.updateForUser(id, updates, userId);
+
+ return tracked.findForUser(id, userId);
+ },
+
+ async remove(userId, id) {
+ await findOwned(userId, id);
+ await tracked.deleteForUser(id, userId);
+ },
+
+ // patched rather than replaced, so a manually entered view count survives the refresh
+ async refresh(userId, id) {
+ const existing = await findOwned(userId, id);
+ const data = await fetchData(userId, existing.contentType === 'youtube' ? 'youtube' : 'reddit', existing.url, existing.accountId, false);
+ await tracked.patchDataForUser(id, data as unknown as Record<string, unknown>, userId);
+ return tracked.findForUser(id, userId);
+ },
+ };
+}
diff --git a/backend/tests/fixtures/instagramAuth.callback.golden.json b/backend/tests/fixtures/instagramAuth.callback.golden.json
index ee9ce5d..6118131 100644
--- a/backend/tests/fixtures/instagramAuth.callback.golden.json
+++ b/backend/tests/fixtures/instagramAuth.callback.golden.json
@@ -3,67 +3,67 @@
{
"status": 302,
"body": "",
- "location": "https://app.example.com//accounts?ig_error=user_denied"
+ "location": "https://app.example.com/accounts?ig_error=user_denied"
},
{
"status": 302,
"body": "",
- "location": "https://app.example.com//accounts?ig_error=access_denied"
+ "location": "https://app.example.com/accounts?ig_error=access_denied"
},
{
"status": 302,
"body": "",
- "location": "https://app.example.com//accounts?ig_error=cancelled"
+ "location": "https://app.example.com/accounts?ig_error=cancelled"
},
{
"status": 302,
"body": "",
- "location": "https://app.example.com//accounts?ig_error=invalid_state"
+ "location": "https://app.example.com/accounts?ig_error=invalid_state"
},
{
"status": 302,
"body": "",
- "location": "https://app.example.com//accounts?ig_error=invalid_state"
+ "location": "https://app.example.com/accounts?ig_error=invalid_state"
},
{
"status": 302,
"body": "",
- "location": "https://app.example.com//accounts?ig_error=invalid_state"
+ "location": "https://app.example.com/accounts?ig_error=invalid_state"
},
{
"status": 302,
"body": "",
- "location": "https://app.example.com//accounts?ig_connected=true"
+ "location": "https://app.example.com/accounts?ig_connected=true"
},
{
"status": 302,
"body": "",
- "location": "https://app.example.com//accounts?ig_connected=true"
+ "location": "https://app.example.com/accounts?ig_connected=true"
},
{
"status": 302,
"body": "",
- "location": "https://app.example.com//accounts?ig_error=already_added"
+ "location": "https://app.example.com/accounts?ig_error=already_added"
},
{
"status": 302,
"body": "",
- "location": "https://app.example.com//accounts?ig_error=Could%20not%20get%20Instagram%20User%20ID.%20Account%20must%20be%20a%20Business%20or%20Creator%20account."
+ "location": "https://app.example.com/accounts?ig_error=Could%20not%20get%20Instagram%20User%20ID.%20Account%20must%20be%20a%20Business%20or%20Creator%20account."
},
{
"status": 302,
"body": "",
- "location": "https://app.example.com//accounts?ig_error=Invalid%20authorization%20code"
+ "location": "https://app.example.com/accounts?ig_error=Invalid%20authorization%20code"
},
{
"status": 302,
"body": "",
- "location": "https://app.example.com//accounts?ig_error=%7B%22unexpected%22%3A%22xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+ "location": "https://app.example.com/accounts?ig_error=%7B%22unexpected%22%3A%22xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
{
"status": 302,
"body": "",
- "location": "https://app.example.com//accounts?ig_error=getaddrinfo%20ENOTFOUND%20api.instagram.com"
+ "location": "https://app.example.com/accounts?ig_error=Instagram%20API%20unreachable%20(getaddrinfo%20ENOTFOUND%20api.instagram.com)"
},
{
"status": 302,
@@ -249,23 +249,19 @@
"logs": [
[
"error",
- "Instagram OAuth callback error:",
- "Could not get Instagram User ID. Account must be a Business or Creator account."
+ "{\"level\":\"error\",\"message\":\"instagram connection failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"error\":\"Could not get Instagram User ID. Account must be a Business or Creator account.\",\"errorName\":\"ValidationError\"}"
],
[
"error",
- "Instagram OAuth callback error:",
- "Invalid authorization code"
+ "{\"level\":\"error\",\"message\":\"instagram connection failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"error\":\"Invalid authorization code\",\"errorName\":\"UpstreamError\"}"
],
[
"error",
- "Instagram OAuth callback error:",
- "{\"unexpected\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"}"
+ "{\"level\":\"error\",\"message\":\"instagram connection failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"error\":\"{\\\"unexpected\\\":\\\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\\\"}\",\"errorName\":\"UpstreamError\"}"
],
[
"error",
- "Instagram OAuth callback error:",
- "getaddrinfo ENOTFOUND api.instagram.com"
+ "{\"level\":\"error\",\"message\":\"instagram connection failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"error\":\"Instagram API unreachable (getaddrinfo ENOTFOUND api.instagram.com)\",\"errorName\":\"UpstreamError\",\"cause\":\"getaddrinfo ENOTFOUND api.instagram.com\"}"
]
]
}
diff --git a/backend/tests/fixtures/instagramAuth.url.golden.json b/backend/tests/fixtures/instagramAuth.url.golden.json
index 43af1ad..3cfcd67 100644
--- a/backend/tests/fixtures/instagramAuth.url.golden.json
+++ b/backend/tests/fixtures/instagramAuth.url.golden.json
@@ -9,13 +9,22 @@
"body": "{\"url\":\"https://www.instagram.com/oauth/authorize?force_reauth=true&client_id=ID&redirect_uri=http%3A%2F%2Flocalhost%3A8787%2Fapi%2Fauth%2Finstagram%2Fcallback&response_type=code&scope=instagram_business_basic%2Cinstagram_business_manage_messages%2Cinstagram_business_manage_comments%2Cinstagram_business_content_publish%2Cinstagram_business_manage_insights&state=dXNlci0xOjE3ODgyNjQwMDAwMDA.Audk7vbgWLAn3iSlHGANEpEKv4wAZr18Cedcn7-ZXmQ\"}"
},
{
- "status": 500,
- "body": "{\"success\":false,\"message\":\"Instagram App credentials not configured on server\"}"
+ "status": 503,
+ "body": "{\"success\":false,\"code\":\"NOT_CONFIGURED\",\"message\":\"Instagram App credentials not configured on server\",\"requestId\":\"req-test\"}"
},
{
- "status": 500,
- "body": "{\"success\":false,\"message\":\"Instagram App credentials not configured on server\"}"
+ "status": 503,
+ "body": "{\"success\":false,\"code\":\"NOT_CONFIGURED\",\"message\":\"Instagram App credentials not configured on server\",\"requestId\":\"req-test\"}"
}
],
- "logs": []
+ "logs": [
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"NOT_CONFIGURED\",\"status\":503,\"error\":\"Instagram App credentials not configured on server\",\"errorName\":\"NotConfiguredError\"}"
+ ],
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"NOT_CONFIGURED\",\"status\":503,\"error\":\"Instagram App credentials not configured on server\",\"errorName\":\"NotConfiguredError\"}"
+ ]
+ ]
}
diff --git a/backend/tests/fixtures/trackedContentRoutes.create.golden.json b/backend/tests/fixtures/trackedContentRoutes.create.golden.json
index e766b57..1ea9499 100644
--- a/backend/tests/fixtures/trackedContentRoutes.create.golden.json
+++ b/backend/tests/fixtures/trackedContentRoutes.create.golden.json
@@ -4,12 +4,12 @@
{
"call": "POST /tracked-content",
"status": 400,
- "body": "{\"error\":\"url is required\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"url is required\",\"requestId\":\"req-test\"}"
},
{
"call": "POST /tracked-content",
"status": 400,
- "body": "{\"error\":\"Only Reddit and YouTube URLs are supported\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"Only Reddit and YouTube URLs are supported\",\"requestId\":\"req-test\"}"
},
{
"call": "POST /tracked-content",
@@ -19,12 +19,12 @@
{
"call": "POST /tracked-content",
"status": 404,
- "body": "{\"error\":\"Reddit account not found\"}"
+ "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Reddit account not found\",\"requestId\":\"req-test\"}"
},
{
"call": "POST /tracked-content",
"status": 404,
- "body": "{\"error\":\"Reddit account not found\"}"
+ "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Reddit account not found\",\"requestId\":\"req-test\"}"
},
{
"call": "POST /tracked-content",
@@ -293,12 +293,17 @@
"responses": [
{
"call": "POST /tracked-content",
- "status": 400,
- "body": "{\"error\":\"YouTube API key not configured on this server\"}"
+ "status": 503,
+ "body": "{\"success\":false,\"code\":\"NOT_CONFIGURED\",\"message\":\"YouTube API key not configured on this server\",\"requestId\":\"req-test\"}"
}
],
"queries": [],
"requests": [],
- "logLines": []
+ "logLines": [
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"NOT_CONFIGURED\",\"status\":503,\"error\":\"YouTube API key not configured on this server\",\"errorName\":\"NotConfiguredError\"}"
+ ]
+ ]
}
}
diff --git a/backend/tests/fixtures/trackedContentRoutes.refresh.golden.json b/backend/tests/fixtures/trackedContentRoutes.refresh.golden.json
index 6f8a4ab..7c757d6 100644
--- a/backend/tests/fixtures/trackedContentRoutes.refresh.golden.json
+++ b/backend/tests/fixtures/trackedContentRoutes.refresh.golden.json
@@ -24,7 +24,7 @@
{
"call": "POST /tracked-content/nope/refresh",
"status": 404,
- "body": "{\"error\":\"Tracked content not found\"}"
+ "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Tracked content not found\",\"requestId\":\"req-test\"}"
},
{
"call": "DELETE /tracked-content/t-youtube",
@@ -34,7 +34,7 @@
{
"call": "DELETE /tracked-content/t-youtube",
"status": 404,
- "body": "{\"error\":\"Tracked content not found\"}"
+ "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Tracked content not found\",\"requestId\":\"req-test\"}"
}
],
"queries": [
@@ -397,8 +397,8 @@
"responses": [
{
"call": "POST /tracked-content/t-youtube/refresh",
- "status": 400,
- "body": "{\"error\":\"YouTube API key not configured on this server\"}"
+ "status": 503,
+ "body": "{\"success\":false,\"code\":\"NOT_CONFIGURED\",\"message\":\"YouTube API key not configured on this server\",\"requestId\":\"req-test\"}"
}
],
"queries": [
@@ -419,6 +419,11 @@
}
],
"requests": [],
- "logLines": []
+ "logLines": [
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"NOT_CONFIGURED\",\"status\":503,\"error\":\"YouTube API key not configured on this server\",\"errorName\":\"NotConfiguredError\"}"
+ ]
+ ]
}
}
diff --git a/backend/tests/fixtures/trackedContentRoutes.update.golden.json b/backend/tests/fixtures/trackedContentRoutes.update.golden.json
index f65ed4f..6270797 100644
--- a/backend/tests/fixtures/trackedContentRoutes.update.golden.json
+++ b/backend/tests/fixtures/trackedContentRoutes.update.golden.json
@@ -3,17 +3,17 @@
{
"call": "PUT /tracked-content/nope",
"status": 404,
- "body": "{\"error\":\"Tracked content not found\"}"
+ "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Tracked content not found\",\"requestId\":\"req-test\"}"
},
{
"call": "PUT /tracked-content/t-youtube",
"status": 400,
- "body": "{\"error\":\"YouTube view counts are fetched automatically and cannot be set by hand\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"YouTube view counts are fetched automatically and cannot be set by hand\",\"requestId\":\"req-test\"}"
},
{
"call": "PUT /tracked-content/t-youtube",
"status": 400,
- "body": "{\"error\":\"Images can only be attached to Reddit posts\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"Images can only be attached to Reddit posts\",\"requestId\":\"req-test\"}"
},
{
"call": "PUT /tracked-content/t-reddit",
@@ -28,12 +28,12 @@
{
"call": "PUT /tracked-content/t-reddit",
"status": 400,
- "body": "{\"error\":\"Views must be a whole number of 0 or more\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"Views must be a whole number of 0 or more\",\"requestId\":\"req-test\"}"
},
{
"call": "PUT /tracked-content/t-reddit",
"status": 400,
- "body": "{\"error\":\"Views must be a whole number of 0 or more\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"Views must be a whole number of 0 or more\",\"requestId\":\"req-test\"}"
},
{
"call": "PUT /tracked-content/t-reddit",
@@ -48,12 +48,12 @@
{
"call": "PUT /tracked-content/t-reddit",
"status": 400,
- "body": "{\"error\":\"Image must be an https URL returned by the uploader\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"Image must be an https URL returned by the uploader\",\"requestId\":\"req-test\"}"
},
{
"call": "PUT /tracked-content/t-reddit",
"status": 400,
- "body": "{\"error\":\"Image must be an https URL returned by the uploader\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"Image must be an https URL returned by the uploader\",\"requestId\":\"req-test\"}"
},
{
"call": "PUT /tracked-content/t-reddit",
diff --git a/backend/tests/lib/cache.test.ts b/backend/tests/lib/cache.test.ts
deleted file mode 100644
index 3509de1..0000000
--- a/backend/tests/lib/cache.test.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { test, beforeEach, mock } from 'node:test';
-import assert from 'node:assert/strict';
-import {
- getVideosCache, setVideosCache, deleteVideosCache,
- getIGCache, setIGCache, getRedditCache, setRedditCache, resetCacheState,
-} from '../../lib/cache.ts';
-import type { Redis } from '../../types/app.ts';
-import type { VideosCacheData, YouTubeVideo } from '../../../shared/types/youtube.ts';
-import type { IGCacheData } from '../../../shared/types/instagram.ts';
-import type { RedditCacheData } from '../../../shared/types/reddit.ts';
-
-type MemoryRedis = Redis & { store: Map<string, unknown> };
-
-function memoryRedis(): MemoryRedis {
- const store = new Map<string, unknown>();
- return {
- store,
- get: async (key: string) => store.get(key) ?? null,
- set: async (key: string, value: unknown, options: unknown) => { store.set(key, value); store.set(`${key}:options`, options); },
- del: async (key: string) => { store.delete(key); },
- } as unknown as MemoryRedis;
-}
-
-const failingRedis = {
- get: async () => { throw new Error('down'); },
- set: async () => { throw new Error('down'); },
- del: async () => { throw new Error('down'); },
-} as unknown as Redis;
-
-beforeEach(() => resetCacheState());
-
-test('every helper is a no-op without redis', async () => {
- assert.equal(await getVideosCache(null, 'u', 'a'), null);
- assert.equal(await getIGCache(null, 'u', 'a'), null);
- assert.equal(await getRedditCache(null, 'u', 'a'), null);
- assert.equal(await setVideosCache(null, 'u', 'a', {} as VideosCacheData), undefined);
- assert.equal(await deleteVideosCache(null, 'u', 'a'), undefined);
-});
-
-test('redis failures fall back silently', async () => {
- assert.equal(await getVideosCache(failingRedis, 'u', 'a'), null);
- assert.equal(await getRedditCache(failingRedis, 'u', 'a'), null);
- assert.equal(await setVideosCache(failingRedis, 'u', 'a', { videos: [] } as unknown as VideosCacheData), undefined);
- assert.equal(await setRedditCache(failingRedis, 'u', 'a', {} as RedditCacheData), undefined);
- assert.equal(await deleteVideosCache(failingRedis, 'u', 'a'), undefined);
-});
-
-test('video entries round-trip with a version and a 6 hour expiry', async () => {
- const redis = memoryRedis();
- await setVideosCache(redis, 'u', 'a', { videos: [1] as unknown as YouTubeVideo[] } as VideosCacheData);
-
- assert.deepEqual(await getVideosCache(redis, 'u', 'a'), { videos: [1], version: 2 });
- assert.deepEqual(redis.store.get('videos:u:a:options'), { ex: 21600 });
-});
-
-test('entries written by older code read as a miss', async () => {
- const redis = memoryRedis();
- redis.store.set('videos:u:a', { videos: [1] });
- redis.store.set('ig:u:a', { media: [], version: 1 });
-
- assert.equal(await getVideosCache(redis, 'u', 'a'), null);
- assert.equal(await getIGCache(redis, 'u', 'a'), null);
-});
-
-test('delete removes the entry', async () => {
- const redis = memoryRedis();
- await setIGCache(redis, 'u', 'a', { media: [] } as unknown as IGCacheData);
- await setVideosCache(redis, 'u', 'a', { videos: [] } as unknown as VideosCacheData);
- await deleteVideosCache(redis, 'u', 'a');
-
- assert.equal(await getVideosCache(redis, 'u', 'a'), null);
- assert.deepEqual(await getIGCache(redis, 'u', 'a'), { media: [], version: 2 });
-});
-
-test('after a failure redis is skipped for 30 seconds, then tried again', async () => {
- mock.timers.enable({ apis: ['Date'], now: 1_000_000 });
- try {
- let calls = 0;
- const flaky = {
- get: async () => { calls++; throw new Error('down'); },
- } as unknown as Redis;
- const healthy = memoryRedis();
- await setVideosCache(healthy, 'u', 'a', { videos: [] } as unknown as VideosCacheData);
-
- assert.equal(await getVideosCache(flaky, 'u', 'a'), null);
- assert.equal(await getVideosCache(healthy, 'u', 'a'), null);
- assert.equal(calls, 1);
-
- mock.timers.tick(30_000);
- assert.deepEqual(await getVideosCache(healthy, 'u', 'a'), { videos: [], version: 2 });
- } finally {
- mock.timers.reset();
- }
-});
diff --git a/backend/tests/middleware/rateLimit.test.ts b/backend/tests/middleware/rateLimit.test.ts
index 8c7e154..f63388a 100644
--- a/backend/tests/middleware/rateLimit.test.ts
+++ b/backend/tests/middleware/rateLimit.test.ts
@@ -6,6 +6,7 @@ import { resetRateLimitState } from '../../lib/rateLimit/limiter.ts';
import type { RateLimitRule } from '../../lib/rateLimit/limiter.ts';
import { RATE_LIMIT_RULES, QUOTA_ROUTES, PUBLISH_ROUTES, matchesRoute } from '../../lib/rateLimit/rules.ts';
import type { AppContext, AppEnv } from '../../types/app.ts';
+import type { ApiFailure } from '../../../shared/types/domain.ts';
const tightRule: RateLimitRule = {
name: 'tight',
@@ -22,6 +23,7 @@ const looseRule: RateLimitRule = {
function appWith(register: (app: Hono<AppEnv>) => void, userId?: string): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.use('*', async (c, next) => {
+ c.set('requestId', 'req-test');
c.set('redis', null);
c.set('rateLimitRedis', null);
if (userId) c.set('userId', userId);
@@ -56,10 +58,12 @@ test('a request over the limit gets 429, Retry-After and a message that says whe
const retryAfter = Number(response.headers.get('Retry-After'));
assert.ok(retryAfter >= 1 && retryAfter <= 60);
assert.equal(response.headers.get('RateLimit-Remaining'), '0');
- const body = await response.json() as { success: boolean; error: string; retryAfter: number };
+ const body = await response.json() as ApiFailure;
assert.equal(body.success, false);
+ assert.equal(body.code, 'RATE_LIMITED');
+ assert.equal(body.requestId, 'req-test');
assert.equal(body.retryAfter, retryAfter);
- assert.match(body.error, /^Too many requests - try again in \d+ seconds?\.$/);
+ assert.match(body.message, /^Too many requests - try again in \d+ seconds?\.$/);
});
test('different clients have separate limits', async () => {
diff --git a/backend/tests/routes/analytics.test.ts b/backend/tests/routes/analyticsRoutes.test.ts
similarity index 99%
rename from backend/tests/routes/analytics.test.ts
rename to backend/tests/routes/analyticsRoutes.test.ts
index 7f9e32b..351e8d2 100644
--- a/backend/tests/routes/analytics.test.ts
+++ b/backend/tests/routes/analyticsRoutes.test.ts
@@ -5,7 +5,7 @@ import { test, describe, before, after, afterEach, mock } from 'node:test';
import type { Mock } from 'node:test';
import type { Hono } from 'hono';
import analyticsRouter from '../../routes/analyticsRoutes.ts';
-import overviewRouter from '../../routes/overview.ts';
+import overviewRouter from '../../routes/overviewRoutes.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
import type { FetchMock, RecordedRequest } from '../fixtures/fakeFetch.ts';
diff --git a/backend/tests/routes/instagramAuth.test.ts b/backend/tests/routes/instagramAuthRoutes.test.ts
similarity index 95%
rename from backend/tests/routes/instagramAuth.test.ts
rename to backend/tests/routes/instagramAuthRoutes.test.ts
index 28d449e..2bdee3f 100644
--- a/backend/tests/routes/instagramAuth.test.ts
+++ b/backend/tests/routes/instagramAuthRoutes.test.ts
@@ -2,8 +2,8 @@
process.removeAllListeners('warning');
import { test, describe, before, after, beforeEach, afterEach, mock } from 'node:test';
-import { urlHandler, callbackHandler } from '../../routes/instagramAuth.ts';
-import { createOAuthState } from '../../lib/cache.ts';
+import { getInstagramAuthUrl, handleInstagramCallback } from '../../controllers/instagramAuthController.ts';
+import { createOAuthState } from '../../lib/oauthState.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
import type { FetchMock, RecordedRequest } from '../fixtures/fakeFetch.ts';
@@ -66,8 +66,8 @@ afterEach(() => {
function buildApp(supabase: FakeSupabase) {
return mountWithContext(app => {
- app.get('/url', urlHandler);
- app.get('/callback', callbackHandler);
+ app.get('/url', ...getInstagramAuthUrl);
+ app.get('/callback', ...handleInstagramCallback);
}, { supabase, userId: 'user-1' });
}
diff --git a/backend/tests/routes/settings.test.ts b/backend/tests/routes/settingsRoutes.test.ts
similarity index 97%
rename from backend/tests/routes/settings.test.ts
rename to backend/tests/routes/settingsRoutes.test.ts
index f0280b1..1e9fb9d 100644
--- a/backend/tests/routes/settings.test.ts
+++ b/backend/tests/routes/settingsRoutes.test.ts
@@ -1,6 +1,6 @@
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
-import settingsRouter from '../../routes/settings.ts';
+import settingsRouter from '../../routes/settingsRoutes.ts';
import { fakeSupabase, tableRow } from '../fixtures/fakeSupabase.ts';
import { mountWithContext, callRoute } from '../fixtures/routeHarness.ts';
diff --git a/backend/tests/routes/trackedContent.test.ts b/backend/tests/routes/trackedContentRoutes.test.ts
similarity index 98%
rename from backend/tests/routes/trackedContent.test.ts
rename to backend/tests/routes/trackedContentRoutes.test.ts
index 13166da..83c4df7 100644
--- a/backend/tests/routes/trackedContent.test.ts
+++ b/backend/tests/routes/trackedContentRoutes.test.ts
@@ -1,6 +1,6 @@
import { test, describe, before, after, afterEach, mock } from 'node:test';
import type { Mock } from 'node:test';
-import trackedContentRouter from '../../routes/trackedContent.ts';
+import trackedContentRouter from '../../routes/trackedContentRoutes.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
import type { FetchMock } from '../fixtures/fakeFetch.ts';
diff --git a/backend/tests/services/trackedContent.test.ts b/backend/tests/services/trackedContentRules.test.ts
similarity index 98%
rename from backend/tests/services/trackedContent.test.ts
rename to backend/tests/services/trackedContentRules.test.ts
index c393535..b2d3d9f 100644
--- a/backend/tests/services/trackedContent.test.ts
+++ b/backend/tests/services/trackedContentRules.test.ts
@@ -1,6 +1,6 @@
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
-import { detectContentType, manualViewsPatch, imageUrlPatch } from '../../services/trackedContent.ts';
+import { detectContentType, manualViewsPatch, imageUrlPatch } from '../../services/trackedContentRules.ts';
describe('detectContentType', () => {
test('recognises reddit and youtube links in any case', () => {
diff --git a/backend/validators/instagramAuthValidators.ts b/backend/validators/instagramAuthValidators.ts
new file mode 100644
index 0000000..af84da7
--- /dev/null
+++ b/backend/validators/instagramAuthValidators.ts
@@ -0,0 +1,19 @@
+import { optionalString } from './fields.ts';
+import type { Fields } from './fields.ts';
+
+export interface InstagramCallbackQuery {
+ code?: string;
+ state?: string;
+ error?: string;
+ errorReason?: string;
+}
+
+// every field is optional: a cancelled sign-in comes back with error and error_reason instead of a code
+export function parseInstagramCallback(query: Fields): InstagramCallbackQuery {
+ return {
+ code: optionalString(query, 'code') || undefined,
+ state: optionalString(query, 'state') || undefined,
+ error: optionalString(query, 'error') || undefined,
+ errorReason: optionalString(query, 'error_reason') || undefined,
+ };
+}
diff --git a/backend/validators/settingsValidators.ts b/backend/validators/settingsValidators.ts
new file mode 100644
index 0000000..6b955dc
--- /dev/null
+++ b/backend/validators/settingsValidators.ts
@@ -0,0 +1,11 @@
+import { optionalString } from './fields.ts';
+import type { Fields } from './fields.ts';
+import type { GitHubSettingsRequest } from '../../shared/types/domain.ts';
+
+export function parseGithubSettings(body: Fields): GitHubSettingsRequest {
+ return {
+ repoOwner: optionalString(body, 'repoOwner'),
+ repoName: optionalString(body, 'repoName'),
+ branch: optionalString(body, 'branch'),
+ };
+}
diff --git a/backend/validators/trackedContentValidators.ts b/backend/validators/trackedContentValidators.ts
new file mode 100644
index 0000000..45d8f7e
--- /dev/null
+++ b/backend/validators/trackedContentValidators.ts
@@ -0,0 +1,36 @@
+import { ValidationError } from '../lib/errors.ts';
+import { optionalString, presentField, requiredString } from './fields.ts';
+import type { Fields } from './fields.ts';
+import type { NewTrackedContent, TrackedContentChanges } from '../services/trackedContentService.ts';
+
+// an account id may be sent as null to unlink the account
+function optionalAccountId(body: Fields): string | null | undefined {
+ if (body.accountId === null) return null;
+ return optionalString(body, 'accountId');
+}
+
+export function parseNewTrackedContent(body: Fields): NewTrackedContent {
+ return {
+ url: requiredString(body, 'url', 'url is required'),
+ accountId: optionalAccountId(body),
+ label: optionalString(body, 'label'),
+ category: optionalString(body, 'category'),
+ };
+}
+
+// manualViews and imageUrl keep their raw value: the tracked content rules explain what is wrong with it
+export function parseTrackedContentChanges(body: Fields): TrackedContentChanges {
+ for (const field of ['manualViews', 'imageUrl']) {
+ const value = body[field];
+ if (value !== undefined && value !== null && typeof value !== 'string' && typeof value !== 'number') {
+ throw new ValidationError(`${field} must be text or a number`);
+ }
+ }
+ const changes: TrackedContentChanges = {};
+ if (presentField(body, 'label')) changes.label = optionalString(body, 'label') ?? '';
+ if (presentField(body, 'category')) changes.category = optionalString(body, 'category') ?? '';
+ if (presentField(body, 'accountId')) changes.accountId = optionalAccountId(body) ?? null;
+ if (presentField(body, 'manualViews')) changes.manualViews = body.manualViews;
+ if (presentField(body, 'imageUrl')) changes.imageUrl = body.imageUrl;
+ return changes;
+}
diff --git a/frontend/src/features/publishing/singlePostFlow.ts b/frontend/src/features/publishing/singlePostFlow.ts
index 73583ec..dcc9657 100644
--- a/frontend/src/features/publishing/singlePostFlow.ts
+++ b/frontend/src/features/publishing/singlePostFlow.ts
@@ -56,8 +56,7 @@ export async function scheduleSinglePost(
const uploaded = await uploadPostMedia(form, cloudConfig, progress);
progress.setPublishStatus('scheduling');
progress.setStatusMessage('Saving the scheduled post');
- const res = await api.createScheduledPost(buildScheduledPostPayload({ ...postDetails(form, uploaded), scheduledAt }));
- if (!res.success) throw new Error(res.message || 'Failed to schedule');
+ await api.createScheduledPost(buildScheduledPostPayload({ ...postDetails(form, uploaded), scheduledAt }));
}
export async function publishSinglePost(
@@ -66,9 +65,8 @@ export async function publishSinglePost(
const uploaded = await uploadPostMedia(form, cloudConfig, progress);
progress.setPublishStatus('creating-container');
progress.setStatusMessage('Creating the Instagram media container');
- const containerRes = await api.createIGContainer(form.selectedAccount, buildContainerPayload(postDetails(form, uploaded)));
- if (!containerRes.success || !containerRes.containerId) throw new Error(containerRes.message || 'Failed to create container');
- await waitUntilReady(form.contentType, containerRes.containerId, form.selectedAccount, {
+ const { containerId } = await api.createIGContainer(form.selectedAccount, buildContainerPayload(postDetails(form, uploaded)));
+ await waitUntilReady(form.contentType, containerId, form.selectedAccount, {
tolerant: true,
onStatus: progress.setStatusMessage,
onProcessing: () => {
@@ -78,7 +76,6 @@ export async function publishSinglePost(
});
progress.setPublishStatus('publishing');
progress.setStatusMessage('Publishing to Instagram');
- const publishRes = await api.publishIGContainer(form.selectedAccount, containerRes.containerId);
- if (!publishRes.success || !publishRes.mediaId) throw new Error(publishRes.message || 'Publish failed');
- return publishRes.mediaId;
+ const { mediaId } = await api.publishIGContainer(form.selectedAccount, containerId);
+ return mediaId;
}
diff --git a/frontend/src/features/publishing/useBulkPublish.ts b/frontend/src/features/publishing/useBulkPublish.ts
index f573811..69fdfde 100644
--- a/frontend/src/features/publishing/useBulkPublish.ts
+++ b/frontend/src/features/publishing/useBulkPublish.ts
@@ -42,25 +42,22 @@ async function scheduleItem(run: BulkRun, item: QueueItem, mediaUrl: string, off
const { settings } = run;
run.patchFile(item.id, { status: 'scheduling', progress: 100 });
const scheduledAt = bulkScheduledTime(run.baseTime as Date, offset, settings.interval);
- const res = await api.createScheduledPost(buildScheduledPostPayload({ ...bulkPostDetails(settings, item, mediaUrl), scheduledAt }));
- if (!res.success) throw new Error(res.message || 'Failed to schedule');
+ await api.createScheduledPost(buildScheduledPostPayload({ ...bulkPostDetails(settings, item, mediaUrl), scheduledAt }));
run.patchFile(item.id, { status: 'scheduled', progress: 100 });
}
async function publishItem(run: BulkRun, item: QueueItem, mediaUrl: string): Promise<ItemOutcome> {
const { settings } = run;
run.patchFile(item.id, { status: 'creating', progress: 100 });
- const containerRes = await api.createIGContainer(settings.account, buildContainerPayload(bulkPostDetails(settings, item, mediaUrl)));
- if (!containerRes.success || !containerRes.containerId) throw new Error(containerRes.message || 'Container creation failed');
+ const { containerId } = await api.createIGContainer(settings.account, buildContainerPayload(bulkPostDetails(settings, item, mediaUrl)));
if (run.isCancelled()) return CANCELLED;
- await waitUntilReady(settings.contentType, containerRes.containerId, settings.account, {
+ await waitUntilReady(settings.contentType, containerId, settings.account, {
onProcessing: () => run.patchFile(item.id, { status: 'processing' }),
});
if (run.isCancelled()) return CANCELLED;
run.patchFile(item.id, { status: 'publishing' });
- const publishRes = await api.publishIGContainer(settings.account, containerRes.containerId);
- if (!publishRes.success || !publishRes.mediaId) throw new Error(publishRes.message || 'Publish failed');
- run.patchFile(item.id, { status: 'done', mediaId: publishRes.mediaId });
+ const { mediaId } = await api.publishIGContainer(settings.account, containerId);
+ run.patchFile(item.id, { status: 'done', mediaId });
return DONE;
}
diff --git a/frontend/src/features/publishing/useScheduledPostEdit.ts b/frontend/src/features/publishing/useScheduledPostEdit.ts
index 936d84b..5609dfd 100644
--- a/frontend/src/features/publishing/useScheduledPostEdit.ts
+++ b/frontend/src/features/publishing/useScheduledPostEdit.ts
@@ -37,8 +37,7 @@ export function useScheduledPostEdit({ showToast, loadScheduledPosts }: Schedule
const scheduledAt = new Date(`${draft.date}T${draft.time}`);
setSavingEdit(true);
try {
- const res = await api.updateScheduledPost(draft.postId as string, { caption: draft.caption, scheduledAt: scheduledAt.toISOString() });
- if (!res.success) throw new Error(res.message || 'Update failed');
+ await api.updateScheduledPost(draft.postId as string, { caption: draft.caption, scheduledAt: scheduledAt.toISOString() });
showToast('Scheduled post updated');
cancelEdit();
loadScheduledPosts();
diff --git a/frontend/src/features/publishing/useScheduledPosts.ts b/frontend/src/features/publishing/useScheduledPosts.ts
index 20a8baf..cece8d5 100644
--- a/frontend/src/features/publishing/useScheduledPosts.ts
+++ b/frontend/src/features/publishing/useScheduledPosts.ts
@@ -10,7 +10,7 @@ export function useScheduledPosts() {
const loadScheduledPosts = useCallback(async () => {
try {
const res = await api.getScheduledPosts();
- if (res.success) setScheduledPosts(res.posts || []);
+ setScheduledPosts(res.posts);
} catch {
// the schedule list is optional, publishing still works
return;
diff --git a/frontend/src/lib/apiErrors.ts b/frontend/src/lib/apiErrors.ts
new file mode 100644
index 0000000..a5aa233
--- /dev/null
+++ b/frontend/src/lib/apiErrors.ts
@@ -0,0 +1,7 @@
+import type { ApiFailure } from '../../../shared/types/domain.ts';
+
+// a server-side failure is logged under its request id, so the message carries the id for the user to quote
+export function failureMessage(status: number, body: Partial<ApiFailure> | null): string {
+ const message = body?.message || `The server answered with status ${status}. Try again in a moment.`;
+ return status >= 500 && body?.requestId ? `${message} (request ${body.requestId})` : message;
+}
diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts
index d60619f..103e042 100644
--- a/frontend/src/services/api.ts
+++ b/frontend/src/services/api.ts
@@ -1,4 +1,5 @@
import { supabase } from '../lib/supabase';
+import { failureMessage } from '../lib/apiErrors.ts';
import type {
AccountListResponse, AccountRefreshAllResponse, AccountResponse, ApiFailure, GitHubSettingsRequest,
GitHubSettingsResponse, HealthResponse, KeysStatusResponse, OverviewResponse, ScheduledPostDeleteAllResponse,
@@ -18,16 +19,7 @@ import type {
const API = import.meta.env.VITE_API_URL || 'http://localhost:8787/api';
-// the fields request() reads from any body to decide whether it failed
-interface ResponseStatusFields {
- success?: boolean;
- message?: string;
- error?: string;
-}
-
-// callers that check success also handle a failure body the server sent with a 2xx status; success bodies carry no message
-export type ApiResult<T> = (T & { message?: undefined }) | ApiFailure;
-
+// every failure arrives with a 4xx or 5xx status and the ApiFailure body, so a 2xx is always a success
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const { data: { session } } = await supabase.auth.getSession();
const token = session?.access_token;
@@ -39,9 +31,10 @@ async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
},
...options,
});
- const data = await res.json() as T & ResponseStatusFields;
- if (!res.ok && !data.success) throw new Error(data.message || data.error || 'Request failed');
- return data;
+ // a proxy error page is not JSON; the status still explains the failure
+ const data = await res.json().catch(() => null) as unknown;
+ if (!res.ok) throw new Error(failureMessage(res.status, data as Partial<ApiFailure> | null));
+ return data as T;
}
const CLOUDINARY_API = 'https://api.cloudinary.com/v1_1';
@@ -161,9 +154,9 @@ export const api = {
// Instagram Publishing
getIGPublishingLimit: (id: string) => request<InstagramPublishingLimitResponse>(`/accounts/${id}/ig-publishing-limit`),
- createIGContainer: (id: string, data: InstagramPublishRequest) => request<ApiResult<InstagramPublishResponse>>(`/accounts/${id}/ig-publish`, { method: 'POST', body: JSON.stringify(data) }),
+ createIGContainer: (id: string, data: InstagramPublishRequest) => request<InstagramPublishResponse>(`/accounts/${id}/ig-publish`, { method: 'POST', body: JSON.stringify(data) }),
getIGContainerStatus: (containerId: string, accountId: string) => request<InstagramContainerStatusResponse>(`/ig-container/${containerId}/status?accountId=${accountId}`),
- publishIGContainer: (id: string, containerId: string) => request<ApiResult<InstagramMediaPublishResponse>>(`/accounts/${id}/ig-media-publish`, { method: 'POST', body: JSON.stringify({ containerId }) }),
+ publishIGContainer: (id: string, containerId: string) => request<InstagramMediaPublishResponse>(`/accounts/${id}/ig-media-publish`, { method: 'POST', body: JSON.stringify({ containerId }) }),
addRedditAccount: (username: string, cookie: string) => request<AccountResponse>('/accounts/reddit', { method: 'POST', body: JSON.stringify({ username, cookie }) }),
getRedditAnalytics: (id: string) => request<RedditCacheData>(`/accounts/${id}/reddit-analytics`),
@@ -183,9 +176,9 @@ export const api = {
getGithubSettings: () => request<GitHubSettingsResponse>('/settings/github'),
saveGithubSettings: (data: GitHubSettingsRequest) => request<SuccessResponse>('/settings/github', { method: 'PUT', body: JSON.stringify(data) }),
- getScheduledPosts: () => request<ApiResult<ScheduledPostListResponse>>('/scheduled-posts'),
- createScheduledPost: (data: ScheduledPostRequest) => request<ApiResult<ScheduledPostResponse>>('/scheduled-posts', { method: 'POST', body: JSON.stringify(data) }),
- updateScheduledPost: (id: string, data: ScheduledPostUpdateRequest) => request<ApiResult<ScheduledPostUpdateResponse>>(`/scheduled-posts/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
+ getScheduledPosts: () => request<ScheduledPostListResponse>('/scheduled-posts'),
+ createScheduledPost: (data: ScheduledPostRequest) => request<ScheduledPostResponse>('/scheduled-posts', { method: 'POST', body: JSON.stringify(data) }),
+ 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'),
diff --git a/frontend/tests/lib/apiErrors.test.ts b/frontend/tests/lib/apiErrors.test.ts
new file mode 100644
index 0000000..840df46
--- /dev/null
+++ b/frontend/tests/lib/apiErrors.test.ts
@@ -0,0 +1,18 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { failureMessage } from '../../src/lib/apiErrors.ts';
+
+test('a client error shows the server message as it is', () => {
+ assert.equal(failureMessage(404, { success: false, code: 'NOT_FOUND', message: 'Account not found', requestId: 'r1' }), 'Account not found');
+});
+
+test('a server error adds the request id the user can quote', () => {
+ assert.equal(
+ failureMessage(500, { success: false, code: 'DATABASE_ERROR', message: 'The database request failed. Try again in a moment.', requestId: 'r2' }),
+ 'The database request failed. Try again in a moment. (request r2)',
+ );
+});
+
+test('a body that is not the error contract still explains the status', () => {
+ assert.equal(failureMessage(502, null), 'The server answered with status 502. Try again in a moment.');
+});