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(accounts): route table, controller, service and repository

spacesdrive6fe1de40a17e
diff --git a/backend/container.ts b/backend/container.ts
new file mode 100644
index 0000000..32b4024
--- /dev/null
+++ b/backend/container.ts
@@ -0,0 +1,25 @@
+import { createAccountRepository } from './repositories/accountRepository.ts';
+import { createAnalyticsCacheRepository } from './repositories/analyticsCacheRepository.ts';
+import { createAccountService } from './services/accountService.ts';
+import type { AccountService } from './services/accountService.ts';
+import type { AppConfig } from './lib/config.ts';
+import type { RequestContext } from './types/context.ts';
+import type { Redis, SupabaseClient } from './types/app.ts';
+
+export interface Clients {
+ supabase: SupabaseClient;
+ redis: Redis | null;
+}
+
+export interface Services {
+ accounts: AccountService;
+}
+
+// the composition root: wires repositories into services for one request or one cron run; building them is cheap
+export function createServices(clients: Clients, config: AppConfig, context: RequestContext): Services {
+ const accounts = createAccountRepository(clients.supabase);
+ const cache = createAnalyticsCacheRepository(clients.redis);
+ return {
+ accounts: createAccountService({ accounts, cache, config, context }),
+ };
+}
diff --git a/backend/controllers/accountController.ts b/backend/controllers/accountController.ts
new file mode 100644
index 0000000..01b03d9
--- /dev/null
+++ b/backend/controllers/accountController.ts
@@ -0,0 +1,61 @@
+import { controller, pathParam, servicesFor } from './http.ts';
+import { jsonBody } from '../middleware/validate.ts';
+import { parseChannelInput, parseInstagramToken, parseRedditAccount } from '../validators/accountValidators.ts';
+import { safeAccount } from '../lib/safeAccount.ts';
+import type {
+ AccountListResponse, AccountRefreshAllResponse, AccountResponse, SuccessResponse, YouTubeAccountAddResponse,
+} from '../../shared/types/domain.ts';
+import type { ResolveChannelResponse } from '../../shared/types/youtube.ts';
+import type { InstagramTokenRefreshResponse } from '../../shared/types/instagram.ts';
+
+// stored credentials never leave the Worker: every account in a response goes through safeAccount()
+
+export const listAccounts = controller.createHandlers(async c => {
+ const accounts = await servicesFor(c).accounts.list(c.get('userId'));
+ return c.json(accounts.map(safeAccount) satisfies AccountListResponse);
+});
+
+export const resolveChannel = controller.createHandlers(jsonBody(parseChannelInput), async c => {
+ const data = await servicesFor(c).accounts.resolveChannel(c.req.valid('json').input);
+ return c.json({ success: true, data } satisfies ResolveChannelResponse);
+});
+
+export const addYouTubeAccount = controller.createHandlers(jsonBody(parseChannelInput), async c => {
+ const account = await servicesFor(c).accounts.addYouTube(c.get('userId'), c.req.valid('json').input);
+ return c.json({ success: true, account } satisfies YouTubeAccountAddResponse);
+});
+
+export const addRedditAccount = controller.createHandlers(jsonBody(parseRedditAccount), async c => {
+ const account = await servicesFor(c).accounts.addReddit(c.get('userId'), c.req.valid('json'));
+ return c.json({ success: true, account: safeAccount(account) } satisfies AccountResponse);
+});
+
+export const addInstagramAccount = controller.createHandlers(jsonBody(parseInstagramToken), async c => {
+ const account = await servicesFor(c).accounts.addInstagram(c.get('userId'), c.req.valid('json').accessToken);
+ return c.json({ success: true, account: safeAccount(account) } satisfies AccountResponse);
+});
+
+export const refreshAllAccounts = controller.createHandlers(async c => {
+ const { accounts, results } = await servicesFor(c).accounts.refreshAll(c.get('userId'));
+ return c.json({
+ success: true,
+ accounts: accounts.map(safeAccount),
+ results,
+ updatedAt: new Date().toISOString(),
+ } satisfies AccountRefreshAllResponse);
+});
+
+export const refreshAccount = controller.createHandlers(async c => {
+ const account = await servicesFor(c).accounts.refresh(c.get('userId'), pathParam(c, 'id'));
+ return c.json({ success: true, account: safeAccount(account) } satisfies AccountResponse);
+});
+
+export const refreshInstagramToken = controller.createHandlers(async c => {
+ const expiresAt = await servicesFor(c).accounts.refreshInstagramToken(c.get('userId'), pathParam(c, 'id'));
+ return c.json({ success: true, message: 'Token refreshed for another 60 days', expiresAt } satisfies InstagramTokenRefreshResponse);
+});
+
+export const deleteAccount = controller.createHandlers(async c => {
+ await servicesFor(c).accounts.remove(c.get('userId'), pathParam(c, 'id'));
+ return c.json({ success: true } satisfies SuccessResponse);
+});
diff --git a/backend/controllers/http.ts b/backend/controllers/http.ts
new file mode 100644
index 0000000..8cf635f
--- /dev/null
+++ b/backend/controllers/http.ts
@@ -0,0 +1,22 @@
+import { createFactory } from 'hono/factory';
+import { createServices } from '../container.ts';
+import { readConfig } from '../lib/config.ts';
+import { ValidationError } from '../lib/errors.ts';
+import { requestContextOf } from '../middleware/requestContext.ts';
+import type { Services } from '../container.ts';
+import type { AppContext, AppEnv } from '../types/app.ts';
+
+// createHandlers keeps the validator's types, so c.req.valid() is typed inside each controller
+export const controller = createFactory<AppEnv>();
+
+// controllers are declared apart from their routes, so Hono cannot type the path parameters
+export function pathParam(c: AppContext, name: string): string {
+ const value = c.req.param(name);
+ if (!value) throw new ValidationError(`Missing path parameter: ${name}`);
+ return value;
+}
+
+// the request's services, built from the clients the middleware created and the request context
+export function servicesFor(c: AppContext): Services {
+ return createServices({ supabase: c.get('supabase'), redis: c.get('redis') }, readConfig(c.env), requestContextOf(c));
+}
diff --git a/backend/routes/accountRoutes.ts b/backend/routes/accountRoutes.ts
new file mode 100644
index 0000000..e7b0532
--- /dev/null
+++ b/backend/routes/accountRoutes.ts
@@ -0,0 +1,20 @@
+import { Hono } from 'hono';
+import {
+ listAccounts, resolveChannel, addYouTubeAccount, addRedditAccount, addInstagramAccount,
+ refreshAllAccounts, refreshAccount, refreshInstagramToken, deleteAccount,
+} from '../controllers/accountController.ts';
+import type { AppEnv } from '../types/app.ts';
+
+const router = new Hono<AppEnv>();
+
+router.get('/accounts', ...listAccounts);
+router.post('/resolve-channel', ...resolveChannel);
+router.post('/accounts', ...addYouTubeAccount);
+router.post('/accounts/reddit', ...addRedditAccount);
+router.post('/accounts/instagram', ...addInstagramAccount);
+router.post('/accounts/refresh-all', ...refreshAllAccounts);
+router.post('/accounts/:id/refresh-ig-token', ...refreshInstagramToken);
+router.post('/accounts/:id/refresh', ...refreshAccount);
+router.delete('/accounts/:id', ...deleteAccount);
+
+export default router;
diff --git a/backend/routes/accounts.ts b/backend/routes/accounts.ts
deleted file mode 100644
index dc8ec24..0000000
--- a/backend/routes/accounts.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-import { Hono } from 'hono';
-import { getAccounts, getAccountById, deleteAccount } from '../lib/db.ts';
-import { deleteVideosCache, deleteIGCache, deleteRedditCache } from '../lib/cache.ts';
-import { resolveChannelId, fetchChannelData } from '../services/youtube/youtubeChannels.ts';
-import {
- addYouTubeAccount, addRedditAccount, addInstagramAccount, refreshInstagramToken,
-} from '../services/accountConnect.ts';
-import { refreshAccount, refreshAllAccounts } from '../services/accountRefresh.ts';
-import { safeAccount } from '../lib/safeAccount.ts';
-import type { AppContext, AppEnv } from '../types/app.ts';
-import type { ServiceFailure } from '../services/accountConnect.ts';
-import type {
- AccountListResponse, AccountRefreshAllResponse, AccountResponse, SuccessResponse, YouTubeAccountAddResponse,
-} from '../../shared/types/domain.ts';
-import type { ResolveChannelResponse } from '../../shared/types/youtube.ts';
-import type { InstagramTokenRefreshResponse } from '../../shared/types/instagram.ts';
-
-interface ChannelInputBody {
- input: string;
-}
-
-interface AddRedditAccountBody {
- username?: string;
- cookie?: string;
-}
-
-interface AddInstagramAccountBody {
- accessToken?: string;
-}
-
-const app = new Hono<AppEnv>();
-
-function failureResponse(c: AppContext, failure: ServiceFailure) {
- return c.json({ success: false, message: failure.message }, failure.status);
-}
-
-app.get('/accounts', async (c) => {
- try {
- const accounts = await getAccounts(c.get('supabase'), c.get('userId'));
- return c.json(accounts.map(safeAccount) satisfies AccountListResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 500);
- }
-});
-
-app.post('/resolve-channel', async (c) => {
- try {
- const { input } = await c.req.json() as ChannelInputBody;
- const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^\uFEFF/, '').trim();
- if (!apiKey) return c.json({ success: false, message: 'YouTube API key not configured on server' }, 400);
- const channelId = await resolveChannelId(input, apiKey);
- const channelData = await fetchChannelData(channelId, apiKey);
- return c.json({ success: true, data: channelData } satisfies ResolveChannelResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 400);
- }
-});
-
-app.post('/accounts', async (c) => {
- try {
- const { input } = await c.req.json() as ChannelInputBody;
- const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^\uFEFF/, '').trim();
- if (!apiKey) return c.json({ success: false, message: 'YouTube API key not configured on server' }, 400);
- const account = await addYouTubeAccount(c.get('supabase'), c.get('userId'), input, apiKey);
- return c.json({ success: true, account } satisfies YouTubeAccountAddResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 400);
- }
-});
-
-app.post('/accounts/reddit', async (c) => {
- try {
- const { username, cookie } = await c.req.json() as AddRedditAccountBody;
- if (!username) return c.json({ success: false, message: 'Username is required' }, 400);
- if (!cookie) return c.json({ success: false, message: 'Session cookie is required - open reddit.com in your browser, copy the reddit_session value from DevTools (Application > Cookies > reddit.com), and paste it here' }, 400);
- const account = await addRedditAccount(c.get('supabase'), c.get('userId'), username, cookie);
- return c.json({ success: true, account: safeAccount(account) } satisfies AccountResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 400);
- }
-});
-
-app.post('/accounts/instagram', async (c) => {
- try {
- const { accessToken } = await c.req.json() as AddInstagramAccountBody;
- if (!accessToken) return c.json({ success: false, message: 'Access token is required' }, 400);
- const account = await addInstagramAccount(c.get('supabase'), c.get('userId'), accessToken, c.env.INSTAGRAM_APP_SECRET);
- return c.json({ success: true, account: safeAccount(account) } satisfies AccountResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 400);
- }
-});
-
-app.post('/accounts/refresh-all', async (c) => {
- try {
- const { accounts, results } = await refreshAllAccounts(c.get('supabase'), c.get('userId'), c.env.YOUTUBE_API_KEY);
- return c.json({
- success: true,
- accounts: accounts.map(safeAccount),
- results,
- updatedAt: new Date().toISOString(),
- } satisfies AccountRefreshAllResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 500);
- }
-});
-
-app.post('/accounts/:id/refresh-ig-token', async (c) => {
- try {
- const outcome = await refreshInstagramToken(c.get('supabase'), c.get('userId'), c.req.param('id'));
- if (outcome.failure) return failureResponse(c, outcome.failure);
- return c.json({ success: true, message: 'Token refreshed for another 60 days', expiresAt: outcome.expiresAt } satisfies InstagramTokenRefreshResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 400);
- }
-});
-
-app.post('/accounts/:id/refresh', async (c) => {
- try {
- const outcome = await refreshAccount(c.get('supabase'), c.get('userId'), c.req.param('id'), c.env.YOUTUBE_API_KEY);
- if (outcome.failure) return failureResponse(c, outcome.failure);
- return c.json({ success: true, account: safeAccount(outcome.account) } satisfies AccountResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 400);
- }
-});
-
-app.delete('/accounts/:id', async (c) => {
- try {
- const supabase = c.get('supabase');
- const redis = c.get('redis');
- const userId = c.get('userId');
- const id = c.req.param('id');
- const account = await getAccountById(supabase, id, userId);
- if (!account) return c.json({ success: false, message: 'Not found' }, 404);
- await Promise.all([
- deleteAccount(supabase, id, userId),
- deleteVideosCache(redis, userId, id),
- deleteIGCache(redis, userId, id),
- deleteRedditCache(redis, userId, id),
- ]);
- return c.json({ success: true } satisfies SuccessResponse);
- } catch (err) {
- return c.json({ success: false, message: (err as Error).message }, 500);
- }
-});
-
-export default app;
diff --git a/backend/server.ts b/backend/server.ts
index 7347208..2880d44 100644
--- a/backend/server.ts
+++ b/backend/server.ts
@@ -1,12 +1,15 @@
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 accountsRouter from './routes/accounts.ts';
+import accountRoutes from './routes/accountRoutes.ts';
import analyticsRouter from './routes/analytics.ts';
import publishingRouter from './routes/publishing.ts';
import scheduledPostsRouter from './routes/scheduledPosts.ts';
@@ -22,13 +25,13 @@ import type { Env } from './types/env.ts';
const app = new Hono<AppEnv>();
-app.onError((err, c) => {
- console.error('Worker error:', err.message);
- return c.json({ error: 'Internal server error' }, 500);
-});
+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) => {
@@ -53,7 +56,7 @@ api.use('*', rateLimit(RATE_LIMIT_RULES.quota, userKey, c => matchesRoute(QUOTA_
api.use('*', rateLimit(RATE_LIMIT_RULES.publish, userKey, c => matchesRoute(PUBLISH_ROUTES, c.req.method, c.req.path)));
api.route('/', keysRouter);
-api.route('/', accountsRouter);
+api.route('/', accountRoutes);
api.route('/', analyticsRouter);
api.route('/', publishingRouter);
api.route('/', scheduledPostsRouter);
diff --git a/backend/services/accountService.ts b/backend/services/accountService.ts
new file mode 100644
index 0000000..4d05a93
--- /dev/null
+++ b/backend/services/accountService.ts
@@ -0,0 +1,227 @@
+import { resolveChannelId, fetchChannelData } from './youtube/youtubeChannels.ts';
+import { fetchRedditProfile } from './reddit/redditApi.ts';
+import { fetchInstagramProfile } from './instagram/instagramApi.ts';
+import { exchangeForLongLivedToken, refreshLongLivedToken } from './instagram/instagramTokens.ts';
+import { buildYouTubeAccount, buildRedditAccount, buildInstagramAccount } from './accountFactory.ts';
+import { ConflictError, NotConfiguredError, NotFoundError, ValidationError } from '../lib/errors.ts';
+import type { AccountRepository } from '../repositories/accountRepository.ts';
+import type { AnalyticsCacheRepository } from '../repositories/analyticsCacheRepository.ts';
+import type { AppConfig } from '../lib/config.ts';
+import type { RequestContext } from '../types/context.ts';
+import type { Account, AccountRefreshResult, NewAccount } from '../../shared/types/domain.ts';
+import type { YouTubeChannelData } from '../../shared/types/youtube.ts';
+import type { RedditProfile } from '../../shared/types/reddit.ts';
+import type { InstagramProfile } from '../../shared/types/instagram.ts';
+
+export interface AccountServiceDeps {
+ accounts: AccountRepository;
+ cache: AnalyticsCacheRepository;
+ config: AppConfig;
+ context: RequestContext;
+}
+
+export interface RedditAccountInput {
+ username: string;
+ cookie: string;
+}
+
+export interface RefreshAllOutcome {
+ accounts: Account[];
+ results: AccountRefreshResult[];
+}
+
+export interface AccountService {
+ list(userId: string): Promise<Account[]>;
+ resolveChannel(input: string): Promise<YouTubeChannelData>;
+ addYouTube(userId: string, input: string): Promise<NewAccount>;
+ addReddit(userId: string, input: RedditAccountInput): Promise<Account>;
+ addInstagram(userId: string, accessToken: string): Promise<Account>;
+ refresh(userId: string, accountId: string): Promise<Account>;
+ refreshAll(userId: string): Promise<RefreshAllOutcome>;
+ refreshInstagramToken(userId: string, accountId: string): Promise<string>;
+ remove(userId: string, accountId: string): Promise<void>;
+}
+
+interface PastedToken {
+ token: string;
+ expiresIn: number;
+}
+
+const DEFAULT_TOKEN_LIFETIME_S = 5184000;
+export const NO_YOUTUBE_KEY_MESSAGE = 'YouTube API key not configured on server';
+export const NO_COOKIE_MESSAGE = 'No session cookie stored - re-add this account with a session cookie from reddit.com DevTools';
+const NO_TOKEN_MESSAGE = 'No access token stored - reconnect this Instagram account';
+const NO_USERNAME_MESSAGE = 'No Reddit username stored - delete this account and add it again';
+const NO_CHANNEL_MESSAGE = 'No YouTube channel ID stored - delete this channel and add it again';
+
+// full adds the fields only a single account refresh updates
+function instagramUpdates(profile: InstagramProfile, full: boolean): Partial<Account> {
+ const updates = {
+ followersCount: profile.followersCount,
+ followsCount: profile.followsCount,
+ mediaCount: profile.mediaCount,
+ title: profile.name || profile.username,
+ username: profile.username,
+ profilePictureUrl: profile.profilePictureUrl,
+ };
+ if (!full) return updates;
+ return { ...updates, biography: profile.biography, website: profile.website };
+}
+
+function redditUpdates(profile: RedditProfile): Partial<Account> {
+ return {
+ totalKarma: profile.totalKarma,
+ postKarma: profile.postKarma,
+ commentKarma: profile.commentKarma,
+ iconUrl: profile.iconUrl,
+ };
+}
+
+function youtubeUpdates(channelData: YouTubeChannelData, full: boolean): Partial<Account> {
+ const { subscriberCount, viewCount, videoCount, title, thumbnails } = channelData;
+ if (!full) return { subscriberCount, viewCount, videoCount, title, thumbnails };
+ return {
+ subscriberCount, viewCount, videoCount, title,
+ description: channelData.description,
+ thumbnails,
+ customUrl: channelData.customUrl,
+ country: channelData.country,
+ keywords: channelData.keywords,
+ topicCategories: channelData.topicCategories,
+ };
+}
+
+export function createAccountService({ accounts, cache, config, context }: AccountServiceDeps): AccountService {
+ const { signal, log } = context;
+
+ function youtubeKey(): string {
+ if (!config.youtubeApiKey) throw new NotConfiguredError(NO_YOUTUBE_KEY_MESSAGE);
+ return config.youtubeApiKey;
+ }
+
+ async function findOwned(userId: string, accountId: string): Promise<Account> {
+ const account = await accounts.findForUser(accountId, userId);
+ if (!account) throw new NotFoundError('Account not found');
+ return account;
+ }
+
+ // a pasted token may already be long-lived, so a failed exchange keeps it as is
+ async function exchangePastedToken(accessToken: string): Promise<PastedToken> {
+ const appSecret = config.instagram.appSecret;
+ if (!appSecret) return { token: accessToken, expiresIn: 0 };
+ try {
+ const longToken = await exchangeForLongLivedToken(accessToken, appSecret, signal);
+ return { token: longToken.accessToken, expiresIn: longToken.expiresIn };
+ } catch (err) {
+ log.info('token exchange skipped; the token may already be long-lived', { reason: (err as Error).message });
+ return { token: accessToken, expiresIn: 0 };
+ }
+ }
+
+ // the platform call needs these fields; a missing one is reported before any request goes out
+ async function fetchProfileUpdates(account: Account, full: boolean): Promise<Partial<Account>> {
+ if (account.platform === 'instagram') {
+ if (!account.accessToken) throw new ValidationError(NO_TOKEN_MESSAGE);
+ return instagramUpdates(await fetchInstagramProfile(account.igUserId, account.accessToken, signal), full);
+ }
+ if (account.platform === 'reddit') {
+ if (!account.username) throw new ValidationError(NO_USERNAME_MESSAGE);
+ if (!account.cookie) throw new ValidationError(NO_COOKIE_MESSAGE);
+ return redditUpdates(await fetchRedditProfile(account.username, account.cookie, signal));
+ }
+ if (!account.channelId) throw new ValidationError(NO_CHANNEL_MESSAGE);
+ return youtubeUpdates(await fetchChannelData(account.channelId, youtubeKey(), signal), full);
+ }
+
+ async function refreshListed(userId: string, account: Account): Promise<void> {
+ const updates = { lastUpdated: new Date().toISOString(), ...await fetchProfileUpdates(account, false) };
+ await accounts.updateForUser(account.id, updates, userId);
+ }
+
+ return {
+ list: userId => accounts.listForUser(userId),
+
+ async resolveChannel(input) {
+ const apiKey = youtubeKey();
+ return fetchChannelData(await resolveChannelId(input, apiKey, signal), apiKey, signal);
+ },
+
+ async addYouTube(userId, input) {
+ const apiKey = youtubeKey();
+ const channelId = await resolveChannelId(input, apiKey, signal);
+ const [channelData, existing] = await Promise.all([
+ fetchChannelData(channelId, apiKey, signal),
+ accounts.listForUser(userId),
+ ]);
+ if (existing.find(account => account.channelId === channelId)) throw new ConflictError('This channel is already added');
+
+ const account = buildYouTubeAccount(channelData);
+ await accounts.create(account, userId);
+ return account;
+ },
+
+ async addReddit(userId, { username, cookie }) {
+ const profile = await fetchRedditProfile(username.replace(/^u\//i, '').trim(), cookie, signal);
+ const existing = await accounts.listForUser(userId);
+ if (existing.find(account => account.platform === 'reddit' && account.username === profile.username)) {
+ throw new ConflictError('This Reddit account is already added');
+ }
+
+ const account = buildRedditAccount(profile, cookie);
+ await accounts.create(account, userId);
+ return account;
+ },
+
+ async addInstagram(userId, accessToken) {
+ const { token, expiresIn } = await exchangePastedToken(accessToken);
+ const profile = await fetchInstagramProfile(null, token, signal);
+ if (!profile.igUserId) {
+ throw new ValidationError('Could not get Instagram User ID. Make sure the token has instagram_business_basic permission and is from a Business/Creator account.');
+ }
+ const existing = await accounts.listForUser(userId);
+ if (existing.find(account => account.platform === 'instagram' && account.igUserId === profile.igUserId)) {
+ throw new ConflictError('This Instagram account is already added');
+ }
+
+ const account = buildInstagramAccount(profile, token, expiresIn);
+ await accounts.create(account, userId);
+ return account;
+ },
+
+ async refresh(userId, accountId) {
+ const account = await findOwned(userId, accountId);
+ const updates = { lastUpdated: new Date().toISOString(), ...await fetchProfileUpdates(account, true) };
+ await accounts.updateForUser(account.id, updates, userId);
+ return { ...account, ...updates };
+ },
+
+ // one failure must not stop the rest; results line up with the accounts by index
+ async refreshAll(userId) {
+ const listed = await accounts.listForUser(userId);
+ const settled = await Promise.allSettled(listed.map(account => refreshListed(userId, account)));
+ const results: AccountRefreshResult[] = settled.map((outcome, i) => (outcome.status === 'fulfilled'
+ ? { id: listed[i].id, success: true }
+ : { id: listed[i].id, success: false, error: (outcome.reason as Error)?.message }));
+ return { accounts: await accounts.listForUser(userId), results };
+ },
+
+ async refreshInstagramToken(userId, accountId) {
+ const account = await accounts.findForUser(accountId, userId);
+ if (!account || account.platform !== 'instagram') throw new NotFoundError('Instagram account not found');
+ if (!account.accessToken) throw new ValidationError(NO_TOKEN_MESSAGE);
+
+ const refreshed = await refreshLongLivedToken(account.accessToken, signal);
+ const tokenExpiresAt = new Date(Date.now() + (refreshed.expiresIn || DEFAULT_TOKEN_LIFETIME_S) * 1000).toISOString();
+ await accounts.updateForUser(account.id, { accessToken: refreshed.accessToken, tokenExpiresAt }, userId);
+ return tokenExpiresAt;
+ },
+
+ async remove(userId, accountId) {
+ await findOwned(userId, accountId);
+ await Promise.all([
+ accounts.deleteForUser(accountId, userId),
+ cache.deleteAllForAccount(userId, accountId),
+ ]);
+ },
+ };
+}
diff --git a/backend/tests/fixtures/accountsRoutes.addInstagram.golden.json b/backend/tests/fixtures/accountsRoutes.addInstagram.golden.json
index 10a9340..dac6cee 100644
--- a/backend/tests/fixtures/accountsRoutes.addInstagram.golden.json
+++ b/backend/tests/fixtures/accountsRoutes.addInstagram.golden.json
@@ -2,7 +2,7 @@
"responses": [
{
"status": 400,
- "body": "{\"success\":false,\"message\":\"Access token is required\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"Access token is required\",\"requestId\":\"req-test\"}"
},
{
"status": 200,
@@ -13,20 +13,20 @@
"body": "{\"success\":true,\"account\":{\"id\":\"17882640000004fzz\",\"platform\":\"instagram\",\"igUserId\":\"3001\",\"username\":\"shorty\",\"title\":\"Shorty\",\"biography\":\"\",\"website\":\"\",\"profilePictureUrl\":\"\",\"followersCount\":0,\"followsCount\":0,\"mediaCount\":0,\"tokenExpiresAt\":null,\"addedAt\":\"2026-09-01T12:00:00.000Z\",\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"hasCookie\":false}}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"This Instagram account is already added\"}"
+ "status": 409,
+ "body": "{\"success\":false,\"code\":\"CONFLICT\",\"message\":\"This Instagram account is already added\",\"requestId\":\"req-test\"}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"This Instagram account is already added\"}"
+ "status": 409,
+ "body": "{\"success\":false,\"code\":\"CONFLICT\",\"message\":\"This Instagram account is already added\",\"requestId\":\"req-test\"}"
},
{
"status": 400,
- "body": "{\"success\":false,\"message\":\"Could not get Instagram User ID. Make sure the token has instagram_business_basic permission and is from a Business/Creator account.\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"Could not get Instagram User ID. Make sure the token has instagram_business_basic permission and is from a Business/Creator account.\",\"requestId\":\"req-test\"}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"Invalid OAuth access token\"}"
+ "status": 502,
+ "body": "{\"success\":false,\"code\":\"UPSTREAM_ERROR\",\"message\":\"Invalid OAuth access token\",\"requestId\":\"req-test\"}"
}
],
"requests": [
@@ -163,8 +163,11 @@
"logs": [
[
"log",
- "Token exchange skipped (token may already be long-lived):",
- "Invalid platform app"
+ "{\"level\":\"info\",\"message\":\"token exchange skipped; the token may already be long-lived\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"reason\":\"Invalid platform app\"}"
+ ],
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"UPSTREAM_ERROR\",\"status\":502,\"error\":\"Invalid OAuth access token\",\"errorName\":\"UpstreamError\"}"
]
]
}
diff --git a/backend/tests/fixtures/accountsRoutes.addReddit.golden.json b/backend/tests/fixtures/accountsRoutes.addReddit.golden.json
index 49a5c6d..af6a548 100644
--- a/backend/tests/fixtures/accountsRoutes.addReddit.golden.json
+++ b/backend/tests/fixtures/accountsRoutes.addReddit.golden.json
@@ -2,23 +2,23 @@
"responses": [
{
"status": 400,
- "body": "{\"success\":false,\"message\":\"Username is required\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"Username is required\",\"requestId\":\"req-test\"}"
},
{
"status": 400,
- "body": "{\"success\":false,\"message\":\"Session cookie is required - open reddit.com in your browser, copy the reddit_session value from DevTools (Application > Cookies > reddit.com), and paste it here\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"Session cookie is required - open reddit.com in your browser, copy the reddit_session value from DevTools (Application > Cookies > reddit.com), and paste it here\",\"requestId\":\"req-test\"}"
},
{
"status": 200,
"body": "{\"success\":true,\"account\":{\"id\":\"17882640000004fzz\",\"platform\":\"reddit\",\"username\":\"NewUser\",\"title\":\"u/NewUser\",\"totalKarma\":70,\"postKarma\":50,\"commentKarma\":20,\"iconUrl\":\"https://i?a=1&b=2\",\"createdAt\":\"2020-09-13T12:26:40.000Z\",\"addedAt\":\"2026-09-01T12:00:00.000Z\",\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"hasCookie\":true}}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"This Reddit account is already added\"}"
+ "status": 409,
+ "body": "{\"success\":false,\"code\":\"CONFLICT\",\"message\":\"This Reddit account is already added\",\"requestId\":\"req-test\"}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"Reddit user not found - check the username\"}"
+ "status": 404,
+ "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Reddit user not found - check the username\",\"requestId\":\"req-test\"}"
}
],
"requests": [
diff --git a/backend/tests/fixtures/accountsRoutes.addYouTube.golden.json b/backend/tests/fixtures/accountsRoutes.addYouTube.golden.json
index 2263293..9550eab 100644
--- a/backend/tests/fixtures/accountsRoutes.addYouTube.golden.json
+++ b/backend/tests/fixtures/accountsRoutes.addYouTube.golden.json
@@ -5,20 +5,20 @@
"body": "{\"success\":true,\"account\":{\"id\":\"17882640000004fzz\",\"channelId\":\"UCnnnnnnnnnnnnnnnnnnnnnn\",\"title\":\"Channel UCnn\",\"description\":\"Desc\",\"customUrl\":\"@chan\",\"publishedAt\":\"2020-01-01T00:00:00Z\",\"country\":\"GB\",\"thumbnails\":{\"default\":\"d\",\"medium\":\"m\",\"high\":\"h\"},\"subscriberCount\":500,\"viewCount\":9000,\"videoCount\":12,\"hiddenSubscriberCount\":false,\"uploadsPlaylistId\":\"UUnnnnnnnnnnnnnnnnnnnnnn\",\"keywords\":\"k\",\"topicCategories\":[\"t\"],\"madeForKids\":false,\"addedAt\":\"2026-09-01T12:00:00.000Z\",\"lastUpdated\":\"2026-09-01T12:00:00.000Z\"}}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"This channel is already added\"}"
+ "status": 409,
+ "body": "{\"success\":false,\"code\":\"CONFLICT\",\"message\":\"This channel is already added\",\"requestId\":\"req-test\"}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"This channel is already added\"}"
+ "status": 409,
+ "body": "{\"success\":false,\"code\":\"CONFLICT\",\"message\":\"This channel is already added\",\"requestId\":\"req-test\"}"
},
{
"status": 400,
- "body": "{\"success\":false,\"message\":\"Invalid input\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"Enter a channel URL, @handle or channel ID\",\"requestId\":\"req-test\"}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"YouTube API key not configured on server\"}"
+ "status": 503,
+ "body": "{\"success\":false,\"code\":\"NOT_CONFIGURED\",\"message\":\"YouTube API key not configured on server\",\"requestId\":\"req-test\"}"
}
],
"requests": [
@@ -118,5 +118,10 @@
}
],
"redis": [],
- "logs": []
+ "logs": [
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"NOT_CONFIGURED\",\"status\":503,\"error\":\"YouTube API key not configured on server\",\"errorName\":\"NotConfiguredError\"}"
+ ]
+ ]
}
diff --git a/backend/tests/fixtures/accountsRoutes.dbFailure.golden.json b/backend/tests/fixtures/accountsRoutes.dbFailure.golden.json
index c165b30..659602c 100644
--- a/backend/tests/fixtures/accountsRoutes.dbFailure.golden.json
+++ b/backend/tests/fixtures/accountsRoutes.dbFailure.golden.json
@@ -2,35 +2,35 @@
"responses": [
{
"status": 500,
- "body": "{\"success\":false,\"message\":\"database unavailable\"}"
+ "body": "{\"success\":false,\"code\":\"DATABASE_ERROR\",\"message\":\"The database request failed. Try again in a moment.\",\"requestId\":\"req-test\"}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"database unavailable\"}"
+ "status": 500,
+ "body": "{\"success\":false,\"code\":\"DATABASE_ERROR\",\"message\":\"The database request failed. Try again in a moment.\",\"requestId\":\"req-test\"}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"database unavailable\"}"
+ "status": 500,
+ "body": "{\"success\":false,\"code\":\"DATABASE_ERROR\",\"message\":\"The database request failed. Try again in a moment.\",\"requestId\":\"req-test\"}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"database unavailable\"}"
+ "status": 500,
+ "body": "{\"success\":false,\"code\":\"DATABASE_ERROR\",\"message\":\"The database request failed. Try again in a moment.\",\"requestId\":\"req-test\"}"
},
{
"status": 500,
- "body": "{\"success\":false,\"message\":\"database unavailable\"}"
+ "body": "{\"success\":false,\"code\":\"DATABASE_ERROR\",\"message\":\"The database request failed. Try again in a moment.\",\"requestId\":\"req-test\"}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"database unavailable\"}"
+ "status": 500,
+ "body": "{\"success\":false,\"code\":\"DATABASE_ERROR\",\"message\":\"The database request failed. Try again in a moment.\",\"requestId\":\"req-test\"}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"database unavailable\"}"
+ "status": 500,
+ "body": "{\"success\":false,\"code\":\"DATABASE_ERROR\",\"message\":\"The database request failed. Try again in a moment.\",\"requestId\":\"req-test\"}"
},
{
"status": 500,
- "body": "{\"success\":false,\"message\":\"database unavailable\"}"
+ "body": "{\"success\":false,\"code\":\"DATABASE_ERROR\",\"message\":\"The database request failed. Try again in a moment.\",\"requestId\":\"req-test\"}"
}
],
"requests": [
@@ -58,5 +58,38 @@
],
"calls": [],
"redis": [],
- "logs": []
+ "logs": [
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"DATABASE_ERROR\",\"status\":500,\"error\":\"The database request failed. Try again in a moment.\",\"errorName\":\"DatabaseError\",\"cause\":\"database unavailable\"}"
+ ],
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"DATABASE_ERROR\",\"status\":500,\"error\":\"The database request failed. Try again in a moment.\",\"errorName\":\"DatabaseError\",\"cause\":\"database unavailable\"}"
+ ],
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"DATABASE_ERROR\",\"status\":500,\"error\":\"The database request failed. Try again in a moment.\",\"errorName\":\"DatabaseError\",\"cause\":\"database unavailable\"}"
+ ],
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"DATABASE_ERROR\",\"status\":500,\"error\":\"The database request failed. Try again in a moment.\",\"errorName\":\"DatabaseError\",\"cause\":\"database unavailable\"}"
+ ],
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"DATABASE_ERROR\",\"status\":500,\"error\":\"The database request failed. Try again in a moment.\",\"errorName\":\"DatabaseError\",\"cause\":\"database unavailable\"}"
+ ],
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"DATABASE_ERROR\",\"status\":500,\"error\":\"The database request failed. Try again in a moment.\",\"errorName\":\"DatabaseError\",\"cause\":\"database unavailable\"}"
+ ],
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"DATABASE_ERROR\",\"status\":500,\"error\":\"The database request failed. Try again in a moment.\",\"errorName\":\"DatabaseError\",\"cause\":\"database unavailable\"}"
+ ],
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"DATABASE_ERROR\",\"status\":500,\"error\":\"The database request failed. Try again in a moment.\",\"errorName\":\"DatabaseError\",\"cause\":\"database unavailable\"}"
+ ]
+ ]
}
diff --git a/backend/tests/fixtures/accountsRoutes.delete.golden.json b/backend/tests/fixtures/accountsRoutes.delete.golden.json
index a61045e..50b92ae 100644
--- a/backend/tests/fixtures/accountsRoutes.delete.golden.json
+++ b/backend/tests/fixtures/accountsRoutes.delete.golden.json
@@ -2,11 +2,11 @@
"responses": [
{
"status": 404,
- "body": "{\"success\":false,\"message\":\"Not found\"}"
+ "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Account not found\",\"requestId\":\"req-test\"}"
},
{
"status": 404,
- "body": "{\"success\":false,\"message\":\"Not found\"}"
+ "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Account not found\",\"requestId\":\"req-test\"}"
},
{
"status": 200,
diff --git a/backend/tests/fixtures/accountsRoutes.listResolve.golden.json b/backend/tests/fixtures/accountsRoutes.listResolve.golden.json
index 8842de7..1981451 100644
--- a/backend/tests/fixtures/accountsRoutes.listResolve.golden.json
+++ b/backend/tests/fixtures/accountsRoutes.listResolve.golden.json
@@ -9,16 +9,16 @@
"body": "{\"success\":true,\"data\":{\"channelId\":\"UCnnnnnnnnnnnnnnnnnnnnnn\",\"title\":\"Channel UCnn\",\"description\":\"Desc\",\"customUrl\":\"@chan\",\"publishedAt\":\"2020-01-01T00:00:00Z\",\"country\":\"GB\",\"thumbnails\":{\"default\":\"d\",\"medium\":\"m\",\"high\":\"h\"},\"subscriberCount\":500,\"viewCount\":9000,\"videoCount\":12,\"hiddenSubscriberCount\":false,\"uploadsPlaylistId\":\"UUnnnnnnnnnnnnnnnnnnnnnn\",\"keywords\":\"k\",\"bannerUrl\":\"\",\"madeForKids\":false,\"topicCategories\":[\"t\"],\"isLinked\":false}}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"Channel not found\"}"
+ "status": 404,
+ "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Channel not found\",\"requestId\":\"req-test\"}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"YouTube API key not configured on server\"}"
+ "status": 503,
+ "body": "{\"success\":false,\"code\":\"NOT_CONFIGURED\",\"message\":\"YouTube API key not configured on server\",\"requestId\":\"req-test\"}"
},
{
"status": 400,
- "body": "{\"success\":false,\"message\":\"Expected property name or '}' in JSON at position 1 (line 1 column 2)\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"Malformed JSON in request body\",\"requestId\":\"req-test\"}"
}
],
"requests": [
@@ -49,5 +49,10 @@
}
],
"redis": [],
- "logs": []
+ "logs": [
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"NOT_CONFIGURED\",\"status\":503,\"error\":\"YouTube API key not configured on server\",\"errorName\":\"NotConfiguredError\"}"
+ ]
+ ]
}
diff --git a/backend/tests/fixtures/accountsRoutes.refreshAll.golden.json b/backend/tests/fixtures/accountsRoutes.refreshAll.golden.json
index bcb0d31..d0900a4 100644
--- a/backend/tests/fixtures/accountsRoutes.refreshAll.golden.json
+++ b/backend/tests/fixtures/accountsRoutes.refreshAll.golden.json
@@ -2,20 +2,20 @@
"responses": [
{
"status": 200,
- "body": "{\"success\":true,\"accounts\":[{\"id\":\"yt1\",\"platform\":\"youtube\",\"channelId\":\"UCaaaaaaaaaaaaaaaaaaaaaa\",\"title\":\"Channel UCaa\",\"subscriberCount\":500,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"viewCount\":9000,\"videoCount\":12,\"thumbnails\":{\"default\":\"d\",\"medium\":\"m\",\"high\":\"h\"},\"hasCookie\":false},{\"id\":\"ig1\",\"platform\":\"instagram\",\"igUserId\":\"1789\",\"username\":\"ribbon\",\"tokenExpiresAt\":\"2026-09-05T00:00:00.000Z\",\"followersCount\":2500,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"followsCount\":10,\"mediaCount\":140,\"title\":\"Ribbon\",\"profilePictureUrl\":\"https://p\",\"hasCookie\":false},{\"id\":\"ig2\",\"platform\":\"instagram\",\"igUserId\":\"2000\",\"username\":\"notoken\",\"hasCookie\":false},{\"id\":\"rd1\",\"platform\":\"reddit\",\"username\":\"ribbon_r\",\"totalKarma\":70,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"postKarma\":50,\"commentKarma\":20,\"iconUrl\":\"https://i?a=1&b=2\",\"hasCookie\":true},{\"id\":\"rd2\",\"platform\":\"reddit\",\"username\":\"nocookie\",\"hasCookie\":false},{\"id\":\"yt2\",\"platform\":\"youtube\",\"channelId\":\"UCmissingmissingmissing0\",\"hasCookie\":false}],\"results\":[{\"id\":\"yt1\",\"success\":true},{\"id\":\"ig1\",\"success\":true},{\"id\":\"ig2\",\"success\":false,\"error\":\"No access token\"},{\"id\":\"rd1\",\"success\":true},{\"id\":\"rd2\",\"success\":false,\"error\":\"No session cookie stored - re-add this account with a session cookie from reddit.com DevTools\"},{\"id\":\"yt2\",\"success\":false,\"error\":\"Channel not found\"}],\"updatedAt\":\"2026-09-01T12:00:00.000Z\"}"
+ "body": "{\"success\":true,\"accounts\":[{\"id\":\"yt1\",\"platform\":\"youtube\",\"channelId\":\"UCaaaaaaaaaaaaaaaaaaaaaa\",\"title\":\"Channel UCaa\",\"subscriberCount\":500,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"viewCount\":9000,\"videoCount\":12,\"thumbnails\":{\"default\":\"d\",\"medium\":\"m\",\"high\":\"h\"},\"hasCookie\":false},{\"id\":\"ig1\",\"platform\":\"instagram\",\"igUserId\":\"1789\",\"username\":\"ribbon\",\"tokenExpiresAt\":\"2026-09-05T00:00:00.000Z\",\"followersCount\":2500,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"followsCount\":10,\"mediaCount\":140,\"title\":\"Ribbon\",\"profilePictureUrl\":\"https://p\",\"hasCookie\":false},{\"id\":\"ig2\",\"platform\":\"instagram\",\"igUserId\":\"2000\",\"username\":\"notoken\",\"hasCookie\":false},{\"id\":\"rd1\",\"platform\":\"reddit\",\"username\":\"ribbon_r\",\"totalKarma\":70,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"postKarma\":50,\"commentKarma\":20,\"iconUrl\":\"https://i?a=1&b=2\",\"hasCookie\":true},{\"id\":\"rd2\",\"platform\":\"reddit\",\"username\":\"nocookie\",\"hasCookie\":false},{\"id\":\"yt2\",\"platform\":\"youtube\",\"channelId\":\"UCmissingmissingmissing0\",\"hasCookie\":false}],\"results\":[{\"id\":\"yt1\",\"success\":true},{\"id\":\"ig1\",\"success\":true},{\"id\":\"ig2\",\"success\":false,\"error\":\"No access token stored - reconnect this Instagram account\"},{\"id\":\"rd1\",\"success\":true},{\"id\":\"rd2\",\"success\":false,\"error\":\"No session cookie stored - re-add this account with a session cookie from reddit.com DevTools\"},{\"id\":\"yt2\",\"success\":false,\"error\":\"Channel not found\"}],\"updatedAt\":\"2026-09-01T12:00:00.000Z\"}"
},
{
"status": 200,
- "body": "{\"success\":true,\"accounts\":[{\"id\":\"yt1\",\"platform\":\"youtube\",\"channelId\":\"UCaaaaaaaaaaaaaaaaaaaaaa\",\"title\":\"Channel UCaa\",\"subscriberCount\":500,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"viewCount\":9000,\"videoCount\":12,\"thumbnails\":{\"default\":\"d\",\"medium\":\"m\",\"high\":\"h\"},\"hasCookie\":false},{\"id\":\"ig1\",\"platform\":\"instagram\",\"igUserId\":\"1789\",\"username\":\"ribbon\",\"tokenExpiresAt\":\"2026-09-05T00:00:00.000Z\",\"followersCount\":2500,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"followsCount\":10,\"mediaCount\":140,\"title\":\"Ribbon\",\"profilePictureUrl\":\"https://p\",\"hasCookie\":false},{\"id\":\"ig2\",\"platform\":\"instagram\",\"igUserId\":\"2000\",\"username\":\"notoken\",\"hasCookie\":false},{\"id\":\"rd1\",\"platform\":\"reddit\",\"username\":\"ribbon_r\",\"totalKarma\":70,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"postKarma\":50,\"commentKarma\":20,\"iconUrl\":\"https://i?a=1&b=2\",\"hasCookie\":true},{\"id\":\"rd2\",\"platform\":\"reddit\",\"username\":\"nocookie\",\"hasCookie\":false},{\"id\":\"yt2\",\"platform\":\"youtube\",\"channelId\":\"UCmissingmissingmissing0\",\"hasCookie\":false}],\"results\":[{\"id\":\"yt1\",\"success\":false,\"error\":\"No YouTube API key\"},{\"id\":\"ig1\",\"success\":true},{\"id\":\"ig2\",\"success\":false,\"error\":\"No access token\"},{\"id\":\"rd1\",\"success\":true},{\"id\":\"rd2\",\"success\":false,\"error\":\"No session cookie stored - re-add this account with a session cookie from reddit.com DevTools\"},{\"id\":\"yt2\",\"success\":false,\"error\":\"No YouTube API key\"}],\"updatedAt\":\"2026-09-01T12:00:00.000Z\"}"
+ "body": "{\"success\":true,\"accounts\":[{\"id\":\"yt1\",\"platform\":\"youtube\",\"channelId\":\"UCaaaaaaaaaaaaaaaaaaaaaa\",\"title\":\"Channel UCaa\",\"subscriberCount\":500,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"viewCount\":9000,\"videoCount\":12,\"thumbnails\":{\"default\":\"d\",\"medium\":\"m\",\"high\":\"h\"},\"hasCookie\":false},{\"id\":\"ig1\",\"platform\":\"instagram\",\"igUserId\":\"1789\",\"username\":\"ribbon\",\"tokenExpiresAt\":\"2026-09-05T00:00:00.000Z\",\"followersCount\":2500,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"followsCount\":10,\"mediaCount\":140,\"title\":\"Ribbon\",\"profilePictureUrl\":\"https://p\",\"hasCookie\":false},{\"id\":\"ig2\",\"platform\":\"instagram\",\"igUserId\":\"2000\",\"username\":\"notoken\",\"hasCookie\":false},{\"id\":\"rd1\",\"platform\":\"reddit\",\"username\":\"ribbon_r\",\"totalKarma\":70,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"postKarma\":50,\"commentKarma\":20,\"iconUrl\":\"https://i?a=1&b=2\",\"hasCookie\":true},{\"id\":\"rd2\",\"platform\":\"reddit\",\"username\":\"nocookie\",\"hasCookie\":false},{\"id\":\"yt2\",\"platform\":\"youtube\",\"channelId\":\"UCmissingmissingmissing0\",\"hasCookie\":false}],\"results\":[{\"id\":\"yt1\",\"success\":false,\"error\":\"YouTube API key not configured on server\"},{\"id\":\"ig1\",\"success\":true},{\"id\":\"ig2\",\"success\":false,\"error\":\"No access token stored - reconnect this Instagram account\"},{\"id\":\"rd1\",\"success\":true},{\"id\":\"rd2\",\"success\":false,\"error\":\"No session cookie stored - re-add this account with a session cookie from reddit.com DevTools\"},{\"id\":\"yt2\",\"success\":false,\"error\":\"YouTube API key not configured on server\"}],\"updatedAt\":\"2026-09-01T12:00:00.000Z\"}"
},
{
"status": 200,
- "body": "{\"success\":true,\"accounts\":[{\"id\":\"yt1\",\"platform\":\"youtube\",\"channelId\":\"UCaaaaaaaaaaaaaaaaaaaaaa\",\"title\":\"Channel UCaa\",\"subscriberCount\":500,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"viewCount\":9000,\"videoCount\":12,\"thumbnails\":{\"default\":\"d\",\"medium\":\"m\",\"high\":\"h\"},\"hasCookie\":false},{\"id\":\"ig1\",\"platform\":\"instagram\",\"igUserId\":\"1789\",\"username\":\"ribbon\",\"tokenExpiresAt\":\"2026-09-05T00:00:00.000Z\",\"followersCount\":2500,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"followsCount\":10,\"mediaCount\":140,\"title\":\"Ribbon\",\"profilePictureUrl\":\"https://p\",\"hasCookie\":false},{\"id\":\"ig2\",\"platform\":\"instagram\",\"igUserId\":\"2000\",\"username\":\"notoken\",\"hasCookie\":false},{\"id\":\"rd1\",\"platform\":\"reddit\",\"username\":\"ribbon_r\",\"totalKarma\":70,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"postKarma\":50,\"commentKarma\":20,\"iconUrl\":\"https://i?a=1&b=2\",\"hasCookie\":true},{\"id\":\"rd2\",\"platform\":\"reddit\",\"username\":\"nocookie\",\"hasCookie\":false},{\"id\":\"yt2\",\"platform\":\"youtube\",\"channelId\":\"UCmissingmissingmissing0\",\"hasCookie\":false}],\"results\":[{\"id\":\"yt1\",\"success\":true},{\"id\":\"ig1\",\"success\":true},{\"id\":\"ig2\",\"success\":false,\"error\":\"No access token\"},{\"id\":\"rd1\",\"success\":true},{\"id\":\"rd2\",\"success\":false,\"error\":\"No session cookie stored - re-add this account with a session cookie from reddit.com DevTools\"},{\"id\":\"yt2\",\"success\":false,\"error\":\"Channel not found\"}],\"updatedAt\":\"2026-09-01T12:00:00.000Z\"}"
+ "body": "{\"success\":true,\"accounts\":[{\"id\":\"yt1\",\"platform\":\"youtube\",\"channelId\":\"UCaaaaaaaaaaaaaaaaaaaaaa\",\"title\":\"Channel UCaa\",\"subscriberCount\":500,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"viewCount\":9000,\"videoCount\":12,\"thumbnails\":{\"default\":\"d\",\"medium\":\"m\",\"high\":\"h\"},\"hasCookie\":false},{\"id\":\"ig1\",\"platform\":\"instagram\",\"igUserId\":\"1789\",\"username\":\"ribbon\",\"tokenExpiresAt\":\"2026-09-05T00:00:00.000Z\",\"followersCount\":2500,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"followsCount\":10,\"mediaCount\":140,\"title\":\"Ribbon\",\"profilePictureUrl\":\"https://p\",\"hasCookie\":false},{\"id\":\"ig2\",\"platform\":\"instagram\",\"igUserId\":\"2000\",\"username\":\"notoken\",\"hasCookie\":false},{\"id\":\"rd1\",\"platform\":\"reddit\",\"username\":\"ribbon_r\",\"totalKarma\":70,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"postKarma\":50,\"commentKarma\":20,\"iconUrl\":\"https://i?a=1&b=2\",\"hasCookie\":true},{\"id\":\"rd2\",\"platform\":\"reddit\",\"username\":\"nocookie\",\"hasCookie\":false},{\"id\":\"yt2\",\"platform\":\"youtube\",\"channelId\":\"UCmissingmissingmissing0\",\"hasCookie\":false}],\"results\":[{\"id\":\"yt1\",\"success\":true},{\"id\":\"ig1\",\"success\":true},{\"id\":\"ig2\",\"success\":false,\"error\":\"No access token stored - reconnect this Instagram account\"},{\"id\":\"rd1\",\"success\":true},{\"id\":\"rd2\",\"success\":false,\"error\":\"No session cookie stored - re-add this account with a session cookie from reddit.com DevTools\"},{\"id\":\"yt2\",\"success\":false,\"error\":\"Channel not found\"}],\"updatedAt\":\"2026-09-01T12:00:00.000Z\"}"
}
],
"requests": [
{
- "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCaaaaaaaaaaaaaaaaaaaaaa&key=%EF%BB%BF+YTKEY+%0A",
+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCaaaaaaaaaaaaaaaaaaaaaa&key=YTKEY",
"method": "GET"
},
{
@@ -32,7 +32,7 @@
}
},
{
- "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCmissingmissingmissing0&key=%EF%BB%BF+YTKEY+%0A",
+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCmissingmissingmissing0&key=YTKEY",
"method": "GET"
},
{
diff --git a/backend/tests/fixtures/accountsRoutes.refreshOne.golden.json b/backend/tests/fixtures/accountsRoutes.refreshOne.golden.json
index baa8350..8f582f5 100644
--- a/backend/tests/fixtures/accountsRoutes.refreshOne.golden.json
+++ b/backend/tests/fixtures/accountsRoutes.refreshOne.golden.json
@@ -2,7 +2,7 @@
"responses": [
{
"status": 404,
- "body": "{\"success\":false,\"message\":\"Not found\"}"
+ "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Account not found\",\"requestId\":\"req-test\"}"
},
{
"status": 200,
@@ -10,7 +10,7 @@
},
{
"status": 400,
- "body": "{\"success\":false,\"message\":\"No access token\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"No access token stored - reconnect this Instagram account\",\"requestId\":\"req-test\"}"
},
{
"status": 200,
@@ -18,43 +18,43 @@
},
{
"status": 400,
- "body": "{\"success\":false,\"message\":\"No session cookie stored - re-add this account with a session cookie from reddit.com DevTools\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"No session cookie stored - re-add this account with a session cookie from reddit.com DevTools\",\"requestId\":\"req-test\"}"
},
{
"status": 200,
"body": "{\"success\":true,\"account\":{\"id\":\"yt1\",\"platform\":\"youtube\",\"channelId\":\"UCaaaaaaaaaaaaaaaaaaaaaa\",\"title\":\"Channel UCaa\",\"subscriberCount\":500,\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"viewCount\":9000,\"videoCount\":12,\"description\":\"Desc\",\"thumbnails\":{\"default\":\"d\",\"medium\":\"m\",\"high\":\"h\"},\"customUrl\":\"@chan\",\"country\":\"GB\",\"keywords\":\"k\",\"topicCategories\":[\"t\"],\"hasCookie\":false}}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"No API key\"}"
+ "status": 503,
+ "body": "{\"success\":false,\"code\":\"NOT_CONFIGURED\",\"message\":\"YouTube API key not configured on server\",\"requestId\":\"req-test\"}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"Channel not found\"}"
+ "status": 404,
+ "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Channel not found\",\"requestId\":\"req-test\"}"
},
{
"status": 404,
- "body": "{\"success\":false,\"message\":\"Not found\"}"
+ "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Account not found\",\"requestId\":\"req-test\"}"
},
{
"status": 404,
- "body": "{\"success\":false,\"message\":\"Instagram account not found\"}"
+ "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Instagram account not found\",\"requestId\":\"req-test\"}"
},
{
"status": 404,
- "body": "{\"success\":false,\"message\":\"Instagram account not found\"}"
+ "body": "{\"success\":false,\"code\":\"NOT_FOUND\",\"message\":\"Instagram account not found\",\"requestId\":\"req-test\"}"
},
{
"status": 400,
- "body": "{\"success\":false,\"message\":\"No access token stored\"}"
+ "body": "{\"success\":false,\"code\":\"VALIDATION_ERROR\",\"message\":\"No access token stored - reconnect this Instagram account\",\"requestId\":\"req-test\"}"
},
{
"status": 200,
"body": "{\"success\":true,\"message\":\"Token refreshed for another 60 days\",\"expiresAt\":\"2026-09-02T12:00:00.000Z\"}"
},
{
- "status": 400,
- "body": "{\"success\":false,\"message\":\"Token cannot be refreshed\"}"
+ "status": 502,
+ "body": "{\"success\":false,\"code\":\"UPSTREAM_ERROR\",\"message\":\"Token cannot be refreshed\",\"requestId\":\"req-test\"}"
}
],
"requests": [
@@ -72,11 +72,11 @@
}
},
{
- "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCaaaaaaaaaaaaaaaaaaaaaa&key=%EF%BB%BF+YTKEY+%0A",
+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCaaaaaaaaaaaaaaaaaaaaaa&key=YTKEY",
"method": "GET"
},
{
- "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCmissingmissingmissing0&key=%EF%BB%BF+YTKEY+%0A",
+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCmissingmissingmissing0&key=YTKEY",
"method": "GET"
},
{
@@ -486,5 +486,14 @@
}
],
"redis": [],
- "logs": []
+ "logs": [
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"NOT_CONFIGURED\",\"status\":503,\"error\":\"YouTube API key not configured on server\",\"errorName\":\"NotConfiguredError\"}"
+ ],
+ [
+ "error",
+ "{\"level\":\"error\",\"message\":\"request failed\",\"requestId\":\"req-test\",\"userId\":\"user-1\",\"code\":\"UPSTREAM_ERROR\",\"status\":502,\"error\":\"Token cannot be refreshed\",\"errorName\":\"UpstreamError\"}"
+ ]
+ ]
}
diff --git a/backend/tests/fixtures/routeHarness.ts b/backend/tests/fixtures/routeHarness.ts
index a774d7c..ef037c0 100644
--- a/backend/tests/fixtures/routeHarness.ts
+++ b/backend/tests/fixtures/routeHarness.ts
@@ -1,4 +1,5 @@
import { Hono } from 'hono';
+import { errorHandler, notFoundHandler } from '../../middleware/errorHandler.ts';
import type { AppEnv, AppVariables, Redis } from '../../types/app.ts';
import type { Env } from '../../types/env.ts';
@@ -17,10 +18,16 @@ export interface RouteResult {
export type FakeRedis = Redis & { deleted: string[] };
-// mounts a router behind a middleware that fills the context the way server.js does
+export const TEST_REQUEST_ID = 'req-test';
+
+// mounts a router behind a middleware that fills the context the way the app pipeline does, with its error handler
export function mountWithContext(register: (app: Hono<AppEnv>) => unknown, context: Record<string, unknown>): Hono<AppEnv> {
const app = new Hono<AppEnv>();
+ app.onError(errorHandler);
+ app.notFound(notFoundHandler);
app.use('*', async (c, next) => {
+ c.set('requestId', TEST_REQUEST_ID);
+ c.set('signal', new AbortController().signal);
Object.entries(context).forEach(([key, value]) => c.set(key as keyof AppVariables, value as never));
await next();
});
diff --git a/backend/tests/routes/accounts.test.ts b/backend/tests/routes/accountRoutes.test.ts
similarity index 96%
rename from backend/tests/routes/accounts.test.ts
rename to backend/tests/routes/accountRoutes.test.ts
index d99b7f9..38c0a87 100644
--- a/backend/tests/routes/accounts.test.ts
+++ b/backend/tests/routes/accountRoutes.test.ts
@@ -3,7 +3,7 @@ process.removeAllListeners('warning');
import { test, describe, before, after, beforeEach, afterEach, mock } from 'node:test';
import assert from 'node:assert/strict';
-import accountsRouter from '../../routes/accounts.ts';
+import accountsRouter from '../../routes/accountRoutes.ts';
import { assertGolden } from '../fixtures/golden.ts';
import { installFetch, reply } from '../fixtures/fakeFetch.ts';
import type { FetchMock, RecordedRequest } from '../fixtures/fakeFetch.ts';
@@ -209,8 +209,9 @@ describe('accounts routes golden output', () => {
]);
const app = mountWithContext(app => app.route('/', accountsRouter), { supabase, redis: fakeRedis(), userId: 'user-1' });
const single = async (id: string) => JSON.parse((await callRoute(app, 'POST', `/accounts/${id}/refresh`, { env: ENV })).body) as unknown;
- assert.deepEqual(await single('ytOld'), { success: false, message: 'No YouTube channel ID stored - delete this channel and add it again' });
- assert.deepEqual(await single('rdOld'), { success: false, message: 'No Reddit username stored - delete this account and add it again' });
+ const failure = (message: string) => ({ success: false, code: 'VALIDATION_ERROR', message, requestId: 'req-test' });
+ assert.deepEqual(await single('ytOld'), failure('No YouTube channel ID stored - delete this channel and add it again'));
+ assert.deepEqual(await single('rdOld'), failure('No Reddit username stored - delete this account and add it again'));
const all = JSON.parse((await callRoute(app, 'POST', '/accounts/refresh-all', { env: ENV })).body) as { results: unknown[] };
assert.deepEqual(all.results, [
diff --git a/backend/validators/accountValidators.ts b/backend/validators/accountValidators.ts
new file mode 100644
index 0000000..1b7650c
--- /dev/null
+++ b/backend/validators/accountValidators.ts
@@ -0,0 +1,26 @@
+import { requiredString } from './fields.ts';
+import type { Fields } from './fields.ts';
+import type { RedditAccountInput } from '../services/accountService.ts';
+
+export interface ChannelInput {
+ input: string;
+}
+
+export interface InstagramTokenInput {
+ accessToken: string;
+}
+
+export function parseChannelInput(body: Fields): ChannelInput {
+ return { input: requiredString(body, 'input', 'Enter a channel URL, @handle or channel ID') };
+}
+
+export function parseRedditAccount(body: Fields): RedditAccountInput {
+ return {
+ username: requiredString(body, 'username', 'Username is required'),
+ cookie: requiredString(body, 'cookie', 'Session cookie is required - open reddit.com in your browser, copy the reddit_session value from DevTools (Application > Cookies > reddit.com), and paste it here'),
+ };
+}
+
+export function parseInstagramToken(body: Fields): InstagramTokenInput {
+ return { accessToken: requiredString(body, 'accessToken', 'Access token is required') };
+}