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): move account and OAuth logic into services
spacesdrive92b1f3ac9e64
diff --git a/backend/routes/accounts.js b/backend/routes/accounts.jsindex a9978f8..bfd4153 100644--- a/backend/routes/accounts.js+++ b/backend/routes/accounts.js@@ -1,15 +1,19 @@import { Hono } from 'hono';-import {- getAccounts, getAccountById, createAccount, updateAccount, deleteAccount,-} from '../lib/db.js';+import { getAccounts, getAccountById, deleteAccount } from '../lib/db.js';import { deleteVideosCache, deleteIGCache, deleteRedditCache } from '../lib/cache.js';-import { fetchInstagramProfile, exchangeForLongLivedToken, refreshLongLivedToken } from '../services/instagram.js';import { resolveChannelId, fetchChannelData } from '../services/youtube.js';-import { fetchRedditProfile } from '../services/reddit.js';+import {+ addYouTubeAccount, addRedditAccount, addInstagramAccount, refreshInstagramToken,+} from '../services/accountConnect.js';+import { refreshAccount, refreshAllAccounts } from '../services/accountRefresh.js';import { safeAccount } from '../lib/safeAccount.js';const app = new Hono();+function failureResponse(c, failure) {+ 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'));@@ -35,44 +39,10 @@ app.post('/resolve-channel', async (c) => {app.post('/accounts', async (c) => {try {const { input } = await c.req.json();- const supabase = c.get('supabase');- const userId = c.get('userId');const apiKey = c.env.YOUTUBE_API_KEY?.replace(/^/, '').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, accounts] = await Promise.all([- fetchChannelData(channelId, apiKey),- getAccounts(supabase, userId),- ]);-- if (accounts.find(a => a.channelId === channelId)) {- return c.json({ success: false, message: 'This channel is already added' }, 400);- }-- const newAccount = {- id: Date.now().toString() + Math.random().toString(36).substring(2, 6),- channelId: channelData.channelId,- title: channelData.title,- description: channelData.description,- customUrl: channelData.customUrl,- publishedAt: channelData.publishedAt,- country: channelData.country,- thumbnails: channelData.thumbnails,- subscriberCount: channelData.subscriberCount,- viewCount: channelData.viewCount,- videoCount: channelData.videoCount,- hiddenSubscriberCount: channelData.hiddenSubscriberCount,- uploadsPlaylistId: channelData.uploadsPlaylistId,- keywords: channelData.keywords,- topicCategories: channelData.topicCategories,- madeForKids: channelData.madeForKids,- addedAt: new Date().toISOString(),- lastUpdated: new Date().toISOString(),- };-- await createAccount(supabase, newAccount, userId);- return c.json({ success: true, account: newAccount });+ const account = await addYouTubeAccount(c.get('supabase'), c.get('userId'), input, apiKey);+ return c.json({ success: true, account });} catch (err) {return c.json({ success: false, message: err.message }, 400);}@@ -83,35 +53,8 @@ app.post('/accounts/reddit', async (c) => {const { username, cookie } = await c.req.json();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 supabase = c.get('supabase');- const userId = c.get('userId');- const cleanUsername = username.replace(/^u\//i, '').trim();-- const profile = await fetchRedditProfile(cleanUsername, cookie);-- const accounts = await getAccounts(supabase, userId);- if (accounts.find(a => a.platform === 'reddit' && a.username === profile.username)) {- return c.json({ success: false, message: 'This Reddit account is already added' }, 400);- }-- const newAccount = {- id: Date.now().toString() + Math.random().toString(36).substring(2, 6),- platform: 'reddit',- username: profile.username,- title: `u/${profile.username}`,- totalKarma: profile.totalKarma,- postKarma: profile.postKarma,- commentKarma: profile.commentKarma,- iconUrl: profile.iconUrl,- createdAt: profile.createdAt,- cookie,- addedAt: new Date().toISOString(),- lastUpdated: new Date().toISOString(),- };-- await createAccount(supabase, newAccount, userId);- return c.json({ success: true, account: safeAccount(newAccount) });+ const account = await addRedditAccount(c.get('supabase'), c.get('userId'), username, cookie);+ return c.json({ success: true, account: safeAccount(account) });} catch (err) {return c.json({ success: false, message: err.message }, 400);}@@ -121,55 +64,8 @@ app.post('/accounts/instagram', async (c) => {try {const { accessToken } = await c.req.json();if (!accessToken) return c.json({ success: false, message: 'Access token is required' }, 400);-- const supabase = c.get('supabase');- const userId = c.get('userId');- const appSecret = c.env.INSTAGRAM_APP_SECRET;-- let finalToken = accessToken;- let expiresIn = 0;- if (appSecret) {- try {- const longToken = await exchangeForLongLivedToken(accessToken, appSecret);- finalToken = longToken.accessToken;- expiresIn = longToken.expiresIn;- } catch (err) {- console.log('Token exchange skipped (token may already be long-lived):', err.message);- }- }-- const profile = await fetchInstagramProfile(null, finalToken);- if (!profile.igUserId) {- throw new Error('Could not get Instagram User ID. Make sure the token has instagram_business_basic permission and is from a Business/Creator account.');- }-- const accounts = await getAccounts(supabase, userId);- if (accounts.find(a => a.platform === 'instagram' && a.igUserId === profile.igUserId)) {- return c.json({ success: false, message: 'This Instagram account is already added' }, 400);- }-- const newAccount = {- id: Date.now().toString() + Math.random().toString(36).substring(2, 6),- platform: 'instagram',- igUserId: profile.igUserId,- username: profile.username,- title: profile.name || profile.username,- biography: profile.biography,- website: profile.website,- profilePictureUrl: profile.profilePictureUrl,- followersCount: profile.followersCount,- followsCount: profile.followsCount,- mediaCount: profile.mediaCount,- accessToken: finalToken,- tokenExpiresAt: expiresIn > 0- ? new Date(Date.now() + expiresIn * 1000).toISOString()- : null,- addedAt: new Date().toISOString(),- lastUpdated: new Date().toISOString(),- };-- await createAccount(supabase, newAccount, userId);- return c.json({ success: true, account: safeAccount(newAccount) });+ const account = await addInstagramAccount(c.get('supabase'), c.get('userId'), accessToken, c.env.INSTAGRAM_APP_SECRET);+ return c.json({ success: true, account: safeAccount(account) });} catch (err) {return c.json({ success: false, message: err.message }, 400);}@@ -177,60 +73,10 @@ app.post('/accounts/instagram', async (c) => {app.post('/accounts/refresh-all', async (c) => {try {- const supabase = c.get('supabase');- const userId = c.get('userId');- const apiKey = c.env.YOUTUBE_API_KEY;- const accounts = await getAccounts(supabase, userId);- const settled = await Promise.allSettled(accounts.map(async (account) => {- let updates = { lastUpdated: new Date().toISOString() };- if (account.platform === 'instagram') {- if (!account.accessToken) throw new Error('No access token');- const profile = await fetchInstagramProfile(account.igUserId, account.accessToken);- updates = {- ...updates,- followersCount: profile.followersCount,- followsCount: profile.followsCount,- mediaCount: profile.mediaCount,- title: profile.name || profile.username,- username: profile.username,- profilePictureUrl: profile.profilePictureUrl,- };- } else if (account.platform === 'reddit') {- if (!account.cookie) throw new Error('No session cookie stored - re-add this account with a session cookie from reddit.com DevTools');- const profile = await fetchRedditProfile(account.username, account.cookie);- updates = {- ...updates,- totalKarma: profile.totalKarma,- postKarma: profile.postKarma,- commentKarma: profile.commentKarma,- iconUrl: profile.iconUrl,- };- } else {- if (!apiKey) throw new Error('No YouTube API key');- const channelData = await fetchChannelData(account.channelId, apiKey);- updates = {- ...updates,- subscriberCount: channelData.subscriberCount,- viewCount: channelData.viewCount,- videoCount: channelData.videoCount,- title: channelData.title,- thumbnails: channelData.thumbnails,- };- }- await updateAccount(supabase, account.id, updates, userId);- return account.id;- }));-- const results = settled.map((r, i) =>- r.status === 'fulfilled'- ? { id: accounts[i].id, success: true }- : { id: accounts[i].id, success: false, error: r.reason?.message }- );-- const updatedAccounts = await getAccounts(supabase, userId);+ const { accounts, results } = await refreshAllAccounts(c.get('supabase'), c.get('userId'), c.env.YOUTUBE_API_KEY);return c.json({success: true,- accounts: updatedAccounts.map(safeAccount),+ accounts: accounts.map(safeAccount),results,updatedAt: new Date().toISOString(),});@@ -241,19 +87,9 @@ app.post('/accounts/refresh-all', async (c) => {app.post('/accounts/:id/refresh-ig-token', async (c) => {try {- const supabase = c.get('supabase');- const userId = c.get('userId');- const account = await getAccountById(supabase, c.req.param('id'), userId);- if (!account || account.platform !== 'instagram') {- return c.json({ success: false, message: 'Instagram account not found' }, 404);- }- if (!account.accessToken) {- return c.json({ success: false, message: 'No access token stored' }, 400);- }- const refreshed = await refreshLongLivedToken(account.accessToken);- const tokenExpiresAt = new Date(Date.now() + (refreshed.expiresIn || 5184000) * 1000).toISOString();- await updateAccount(supabase, account.id, { accessToken: refreshed.accessToken, tokenExpiresAt }, userId);- return c.json({ success: true, message: 'Token refreshed for another 60 days', expiresAt: tokenExpiresAt });+ 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 });} catch (err) {return c.json({ success: false, message: err.message }, 400);}@@ -261,58 +97,9 @@ app.post('/accounts/:id/refresh-ig-token', async (c) => {app.post('/accounts/:id/refresh', async (c) => {try {- const supabase = c.get('supabase');- const userId = c.get('userId');- const account = await getAccountById(supabase, c.req.param('id'), userId);- if (!account) return c.json({ success: false, message: 'Not found' }, 404);-- let updates = { lastUpdated: new Date().toISOString() };-- if (account.platform === 'instagram') {- if (!account.accessToken) return c.json({ success: false, message: 'No access token' }, 400);- const profile = await fetchInstagramProfile(account.igUserId, account.accessToken);- updates = {- ...updates,- followersCount: profile.followersCount,- followsCount: profile.followsCount,- mediaCount: profile.mediaCount,- title: profile.name || profile.username,- username: profile.username,- profilePictureUrl: profile.profilePictureUrl,- biography: profile.biography,- website: profile.website,- };- } else if (account.platform === 'reddit') {- if (!account.cookie) return c.json({ success: false, message: 'No session cookie stored - re-add this account with a session cookie from reddit.com DevTools' }, 400);- const profile = await fetchRedditProfile(account.username, account.cookie);- updates = {- ...updates,- totalKarma: profile.totalKarma,- postKarma: profile.postKarma,- commentKarma: profile.commentKarma,- iconUrl: profile.iconUrl,- };- } else {- const apiKey = c.env.YOUTUBE_API_KEY;- if (!apiKey) return c.json({ success: false, message: 'No API key' }, 400);- const channelData = await fetchChannelData(account.channelId, apiKey);- updates = {- ...updates,- subscriberCount: channelData.subscriberCount,- viewCount: channelData.viewCount,- videoCount: channelData.videoCount,- title: channelData.title,- description: channelData.description,- thumbnails: channelData.thumbnails,- customUrl: channelData.customUrl,- country: channelData.country,- keywords: channelData.keywords,- topicCategories: channelData.topicCategories,- };- }-- await updateAccount(supabase, account.id, updates, userId);- return c.json({ success: true, account: safeAccount({ ...account, ...updates }) });+ 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) });} catch (err) {return c.json({ success: false, message: err.message }, 400);}diff --git a/backend/routes/accounts.test.js b/backend/routes/accounts.test.jsnew file mode 100644index 0000000..8601cad--- /dev/null+++ b/backend/routes/accounts.test.js@@ -0,0 +1,200 @@+// keeps node's experimental mock timer warning out of the captured console output+process.removeAllListeners('warning');++import { test, describe, before, after, beforeEach, afterEach, mock } from 'node:test';+import accountsRouter from './accounts.js';+import { assertGolden } from '../services/fixtures/golden.js';+import { installFetch, reply } from '../services/fixtures/fakeFetch.js';+import { fakeSupabase, accountRow } from '../services/fixtures/fakeSupabase.js';+import { mountWithContext, callRoute, fakeRedis } from '../services/fixtures/routeHarness.js';++// a byte order mark that pasted secrets sometimes start with+const BOM = String.fromCharCode(0xfeff);+const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');+const CHANNEL_A = 'UCaaaaaaaaaaaaaaaaaaaaaa';+const CHANNEL_NEW = 'UCnnnnnnnnnnnnnnnnnnnnnn';+const ENV = { YOUTUBE_API_KEY: `${BOM} YTKEY \n`, INSTAGRAM_APP_SECRET: 'IGSECRET' };++const storedAccounts = [+ accountRow({ id: 'yt1', platform: 'youtube', channelId: CHANNEL_A, title: 'Old title', subscriberCount: 1 }),+ accountRow({ id: 'ig1', platform: 'instagram', igUserId: '1789', username: 'ribbon', accessToken: 'IGTOKEN', tokenExpiresAt: '2026-09-05T00:00:00.000Z', followersCount: 1 }),+ accountRow({ id: 'ig2', platform: 'instagram', igUserId: '2000', username: 'notoken' }),+ accountRow({ id: 'rd1', platform: 'reddit', username: 'ribbon_r', cookie: 'COOKIE', totalKarma: 1 }),+ accountRow({ id: 'rd2', platform: 'reddit', username: 'nocookie' }),+ accountRow({ id: 'yt2', platform: 'youtube', channelId: 'UCmissingmissingmissing0' }),+ accountRow({ id: 'other', platform: 'youtube', channelId: CHANNEL_NEW }, 'user-2'),+];++function channelBody(channelId) {+ if (channelId.startsWith('UCmissing')) return { items: [] };+ return {+ items: [{+ id: channelId,+ snippet: { title: `Channel ${channelId.slice(0, 4)}`, description: 'Desc', customUrl: '@chan', publishedAt: '2020-01-01T00:00:00Z', country: 'GB', thumbnails: { default: { url: 'd' }, medium: { url: 'm' }, high: { url: 'h' } } },+ statistics: { subscriberCount: '500', viewCount: '9000', videoCount: '12' },+ contentDetails: { relatedPlaylists: { uploads: `UU${channelId.slice(2)}` } },+ brandingSettings: { channel: { keywords: 'k' } },+ status: { madeForKids: false },+ topicDetails: { topicCategories: ['t'] },+ }],+ };+}++const instagramProfiles = {+ IGTOKEN: { user_id: '1789', username: 'ribbon', name: 'Ribbon', followers_count: 2500, follows_count: 10, media_count: 140, biography: 'Bio', website: 'https://r.example', profile_picture_url: 'https://p' },+ LONGTOKEN: { user_id: '3000', username: 'fresh', name: '', followers_count: 5, media_count: 1 },+ SHORTONLY: { user_id: '3001', username: 'shorty', name: 'Shorty' },+ NOID: { username: 'ghost' },+};++function instagramReply(url) {+ const params = url.searchParams;+ const token = params.get('access_token');+ if (url.pathname === '/access_token') {+ if (token === 'SHORT') return reply({ access_token: 'LONGTOKEN', expires_in: 5000 });+ return reply({ error: { message: 'Invalid platform app' } });+ }+ if (url.pathname === '/refresh_access_token') {+ if (token === 'IGTOKEN') return reply({ access_token: 'IGTOKEN2', expires_in: 86400 });+ return reply({ error: { message: 'Token cannot be refreshed' } });+ }+ const profile = instagramProfiles[token];+ return profile ? reply(profile) : reply({ error: { message: 'Invalid OAuth access token' } });+}++function platformServer(request) {+ const url = new URL(request.url);+ if (url.hostname === 'graph.instagram.com') return instagramReply(url);+ if (url.hostname === 'www.reddit.com') {+ const username = url.pathname.split('/')[2];+ if (username === 'missing') return reply({}, 404, 'Not Found');+ return reply({ data: { name: username === 'ribbon_r' ? 'ribbon_r' : 'NewUser', total_karma: 70, link_karma: 50, comment_karma: 20, icon_img: 'https://i?a=1&b=2', created_utc: 1600000000 } });+ }+ const params = url.searchParams;+ if (params.get('forHandle')) return reply({ items: [{ id: params.get('forHandle') === 'existing' ? CHANNEL_A : CHANNEL_NEW }] });+ if (params.get('forUsername') || params.get('q')) return reply({ items: [] });+ return reply(channelBody(params.get('id')));+}++let fetchMock = null;+let logLines = [];++before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));+after(() => mock.timers.reset());+beforeEach(() => {+ mock.method(Math, 'random', () => 0.123456789);+ logLines = [];+ mock.method(console, 'log', (...args) => logLines.push(['log', ...args]));+ mock.method(console, 'error', (...args) => logLines.push(['error', ...args]));+ fetchMock = installFetch(platformServer);+});+afterEach(() => {+ fetchMock.restore();+ mock.restoreAll();+});++async function runScenario(steps, options = {}) {+ const supabase = options.supabase ?? fakeSupabase(storedAccounts);+ const redis = fakeRedis();+ const app = mountWithContext(app => app.route('/', accountsRouter), { supabase, redis, userId: 'user-1' });+ const responses = [];+ for (const [method, path, json, env] of steps) {+ responses.push(await callRoute(app, method, path, { json, env: env ?? ENV }));+ }+ return { responses, requests: fetchMock.requests, calls: supabase.calls, redis: redis.deleted, logs: logLines };+}++const brokenSupabase = { calls: [], from() { throw new Error('database unavailable'); } };++describe('accounts routes golden output', () => {+ test('lists accounts and resolves channels', async () => {+ assertGolden(await runScenario([+ ['GET', '/accounts'],+ ['POST', '/resolve-channel', { input: 'https://youtube.com/@creator' }],+ ['POST', '/resolve-channel', { input: 'UCmissingmissingmissing0' }],+ ['POST', '/resolve-channel', { input: 'x' }, {}],+ ['POST', '/resolve-channel', '{not json'],+ ]), 'accountsRoutes.listResolve');+ });++ test('adds YouTube channels and rejects duplicates', async () => {+ assertGolden(await runScenario([+ ['POST', '/accounts', { input: 'https://youtube.com/@creator' }],+ ['POST', '/accounts', { input: '@existing' }],+ ['POST', '/accounts', { input: 'https://youtube.com/@existing' }],+ ['POST', '/accounts', { input: '' }],+ ['POST', '/accounts', { input: 'x' }, { YOUTUBE_API_KEY: `${BOM} ` }],+ ]), 'accountsRoutes.addYouTube');+ });++ test('adds Reddit accounts and rejects missing fields and duplicates', async () => {+ assertGolden(await runScenario([+ ['POST', '/accounts/reddit', { cookie: 'C' }],+ ['POST', '/accounts/reddit', { username: 'someone' }],+ ['POST', '/accounts/reddit', { username: 'U/NewUser ', cookie: 'NEWCOOKIE' }],+ ['POST', '/accounts/reddit', { username: 'ribbon_r', cookie: 'C2' }],+ ['POST', '/accounts/reddit', { username: 'missing', cookie: 'C3' }],+ ]), 'accountsRoutes.addReddit');+ });++ test('adds Instagram accounts with and without a long-lived exchange', async () => {+ assertGolden(await runScenario([+ ['POST', '/accounts/instagram', {}],+ ['POST', '/accounts/instagram', { accessToken: 'SHORT' }],+ ['POST', '/accounts/instagram', { accessToken: 'SHORTONLY' }],+ ['POST', '/accounts/instagram', { accessToken: 'SHORTONLY' }, {}],+ ['POST', '/accounts/instagram', { accessToken: 'IGTOKEN' }, {}],+ ['POST', '/accounts/instagram', { accessToken: 'NOID' }, {}],+ ['POST', '/accounts/instagram', { accessToken: 'BROKEN' }, {}],+ ]), 'accountsRoutes.addInstagram');+ });++ test('refreshes every account and reports each result', async () => {+ assertGolden(await runScenario([+ ['POST', '/accounts/refresh-all'],+ ['POST', '/accounts/refresh-all', undefined, {}],+ ['POST', '/accounts/refresh-all', undefined, { YOUTUBE_API_KEY: 'PLAINKEY' }],+ ]), 'accountsRoutes.refreshAll');+ });++ test('refreshes one account or one Instagram token', async () => {+ assertGolden(await runScenario([+ ['POST', '/accounts/nope/refresh'],+ ['POST', '/accounts/ig1/refresh'],+ ['POST', '/accounts/ig2/refresh'],+ ['POST', '/accounts/rd1/refresh'],+ ['POST', '/accounts/rd2/refresh'],+ ['POST', '/accounts/yt1/refresh'],+ ['POST', '/accounts/yt1/refresh', undefined, {}],+ ['POST', '/accounts/yt2/refresh'],+ ['POST', '/accounts/other/refresh'],+ ['POST', '/accounts/nope/refresh-ig-token'],+ ['POST', '/accounts/rd1/refresh-ig-token'],+ ['POST', '/accounts/ig2/refresh-ig-token'],+ ['POST', '/accounts/ig1/refresh-ig-token'],+ ['POST', '/accounts/ig1/refresh-ig-token'],+ ]), 'accountsRoutes.refreshOne');+ });++ test('deletes accounts and clears their caches', async () => {+ assertGolden(await runScenario([+ ['DELETE', '/accounts/nope'],+ ['DELETE', '/accounts/other'],+ ['DELETE', '/accounts/rd2'],+ ['GET', '/accounts'],+ ]), 'accountsRoutes.delete');+ });++ test('database failures surface as errors', async () => {+ assertGolden(await runScenario([+ ['GET', '/accounts'],+ ['POST', '/accounts', { input: '@creator' }],+ ['POST', '/accounts/reddit', { username: 'NewUser', cookie: 'C' }],+ ['POST', '/accounts/instagram', { accessToken: 'IGTOKEN' }, {}],+ ['POST', '/accounts/refresh-all'],+ ['POST', '/accounts/ig1/refresh'],+ ['POST', '/accounts/ig1/refresh-ig-token'],+ ['DELETE', '/accounts/ig1'],+ ], { supabase: brokenSupabase }), 'accountsRoutes.dbFailure');+ });+});diff --git a/backend/routes/instagramAuth.js b/backend/routes/instagramAuth.jsindex a61e3bc..3281d01 100644--- a/backend/routes/instagramAuth.js+++ b/backend/routes/instagramAuth.js@@ -1,125 +1,44 @@-import { createOAuthState, verifyOAuthState } from '../lib/cache.js';-import { createAccount, getAccounts } from '../lib/db.js';-import { fetchInstagramProfile } from '../services/instagram.js';+import { verifyOAuthState } from '../lib/cache.js';+import {+ readInstagramOAuthConfig, buildAuthorizationUrl, connectInstagramFromOAuth,+} from '../services/instagramOAuth.js';-// GET /api/auth/instagram/url - protected (requireAuth applied by the sub-app in server.js)-// Returns the Instagram OAuth authorization URL for the frontend to redirect to.+// GET /api/auth/instagram/url - protected; returns the url the frontend redirects toexport async function urlHandler(c) {try {- const APP_ID = c.env.INSTAGRAM_APP_ID?.replace(/^/, '').trim();- const APP_SECRET = c.env.INSTAGRAM_APP_SECRET?.replace(/^/, '').trim();- if (!APP_ID || !APP_SECRET) {+ const config = readInstagramOAuthConfig(c.env);+ if (!config.appId || !config.appSecret) {return c.json({ success: false, message: 'Instagram App credentials not configured on server' }, 500);}-- const REDIRECT_URI = `${(c.env.BACKEND_URL || 'http://localhost:8787').replace(/^/, '').trim().replace(/\/$/, '')}/api/auth/instagram/callback`;-- // HMAC-signed state - no Redis needed, userId + timestamp embedded- const state = await createOAuthState(c.get('userId'), APP_SECRET);-- const params = new URLSearchParams({- force_reauth: 'true',- client_id: APP_ID,- redirect_uri: REDIRECT_URI,- response_type: 'code',- scope: 'instagram_business_basic,instagram_business_manage_messages,instagram_business_manage_comments,instagram_business_content_publish,instagram_business_manage_insights',- state,- });-- return c.json({ url: `https://www.instagram.com/oauth/authorize?${params}` });+ return c.json({ url: await buildAuthorizationUrl(config, c.get('userId')) });} catch (err) {console.error('Instagram URL handler error:', err.message);return c.json({ success: false, message: 'Failed to generate auth URL: ' + err.message }, 500);}}-// GET /api/auth/instagram/callback - public (browser redirect from Instagram)-// No auth header here - userId is recovered from the HMAC state token.+// GET /api/auth/instagram/callback - public browser redirect; the signed state supplies the userIdexport async function callbackHandler(c) {- const { code, state, error, error_reason } = c.req.query();- const FRONTEND_URL = (c.env.FRONTEND_URL || 'http://localhost:5173').replace(/^/, '').trim();- const BACKEND_URL = (c.env.BACKEND_URL || 'http://localhost:8787').replace(/^/, '').trim().replace(/\/$/, '');- const REDIRECT_URI = `${BACKEND_URL}/api/auth/instagram/callback`;- const APP_ID = c.env.INSTAGRAM_APP_ID?.replace(/^/, '').trim();- const APP_SECRET = c.env.INSTAGRAM_APP_SECRET?.replace(/^/, '').trim();+ 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 = error_reason || error || 'cancelled';- return c.redirect(`${FRONTEND_URL}/accounts?ig_error=${encodeURIComponent(reason)}`);+ const reason = errorReason || error || 'cancelled';+ return c.redirect(`${accountsUrl}?ig_error=${encodeURIComponent(reason)}`);}- // Verify HMAC state - recovers userId without Redis- const userId = await verifyOAuthState(state, APP_SECRET);+ const userId = await verifyOAuthState(state, config.appSecret);if (!userId) {- return c.redirect(`${FRONTEND_URL}/accounts?ig_error=invalid_state`);+ return c.redirect(`${accountsUrl}?ig_error=invalid_state`);}try {- // Exchange code for short-lived access token- const tokenRes = await fetch('https://api.instagram.com/oauth/access_token', {- method: 'POST',- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },- body: new URLSearchParams({- client_id: APP_ID,- client_secret: APP_SECRET,- grant_type: 'authorization_code',- redirect_uri: REDIRECT_URI,- code: code.replace(/#.*$/, ''), // strip trailing #_ Instagram sometimes appends- }),- });- const tokenData = await tokenRes.json();- if (!tokenData.access_token) {- throw new Error(tokenData.error_message || JSON.stringify(tokenData));- }-- // Exchange short-lived for long-lived token (60 days)- const longParams = new URLSearchParams({- grant_type: 'ig_exchange_token',- client_id: APP_ID,- client_secret: APP_SECRET,- access_token: tokenData.access_token,- });- const longRes = await fetch(`https://graph.instagram.com/access_token?${longParams}`);- const longData = await longRes.json();- const finalToken = longData.access_token || tokenData.access_token;- const expiresIn = longData.expires_in || 0;-- const supabase = c.get('supabase');-- const profile = await fetchInstagramProfile(null, finalToken);- 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(a => a.platform === 'instagram' && a.igUserId === profile.igUserId)) {- return c.redirect(`${FRONTEND_URL}/accounts?ig_error=already_added`);- }-- const newAccount = {- id: Date.now().toString() + Math.random().toString(36).substring(2, 6),- platform: 'instagram',- igUserId: profile.igUserId,- username: profile.username,- title: profile.name || profile.username,- biography: profile.biography,- website: profile.website,- profilePictureUrl: profile.profilePictureUrl,- followersCount: profile.followersCount,- followsCount: profile.followsCount,- mediaCount: profile.mediaCount,- accessToken: finalToken,- tokenExpiresAt: expiresIn > 0- ? new Date(Date.now() + expiresIn * 1000).toISOString()- : null,- addedAt: new Date().toISOString(),- lastUpdated: new Date().toISOString(),- };-- await createAccount(supabase, newAccount, userId);- return c.redirect(`${FRONTEND_URL}/accounts?ig_connected=true`);+ 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.message);- return c.redirect(`${FRONTEND_URL}/accounts?ig_error=${encodeURIComponent(err.message.substring(0, 100))}`);+ return c.redirect(`${accountsUrl}?ig_error=${encodeURIComponent(err.message.substring(0, 100))}`);}}diff --git a/backend/routes/instagramAuth.test.js b/backend/routes/instagramAuth.test.jsnew file mode 100644index 0000000..d9527bd--- /dev/null+++ b/backend/routes/instagramAuth.test.js@@ -0,0 +1,114 @@+// keeps node's experimental mock timer warning out of the captured console output+process.removeAllListeners('warning');++import { test, describe, before, after, beforeEach, afterEach, mock } from 'node:test';+import { urlHandler, callbackHandler } from './instagramAuth.js';+import { createOAuthState } from '../lib/cache.js';+import { assertGolden } from '../services/fixtures/golden.js';+import { installFetch, reply } from '../services/fixtures/fakeFetch.js';+import { fakeSupabase, accountRow } from '../services/fixtures/fakeSupabase.js';+import { mountWithContext, callRoute } from '../services/fixtures/routeHarness.js';++// a byte order mark that pasted secrets sometimes start with+const BOM = String.fromCharCode(0xfeff);+const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');+const ENV = {+ INSTAGRAM_APP_ID: `${BOM} APPID \n`,+ INSTAGRAM_APP_SECRET: `${BOM}APPSECRET `,+ BACKEND_URL: `${BOM} https://api.example.com/ `,+ FRONTEND_URL: ' https://app.example.com/ ',+};++const profiles = {+ LONG: { user_id: '5000', username: 'longlived', name: 'Long Lived', followers_count: 10, follows_count: 2, media_count: 3, biography: 'B', website: 'W', profile_picture_url: 'P' },+ SHORT_FALLBACK: { user_id: '5001', username: 'fallback' },+ SHORT_NOID: { username: 'ghost' },+ SHORT_DUP: { user_id: '1789', username: 'ribbon' },+};++// the short token returned for each authorization code decides the rest of the flow+const shortTokens = { good: 'SHORT_GOOD', fallback: 'SHORT_FALLBACK', noid: 'SHORT_NOID', dup: 'SHORT_DUP' };++function instagramServer(request) {+ const url = new URL(request.url);+ if (url.hostname === 'api.instagram.com') {+ const code = new URLSearchParams(request.body).get('code');+ if (code === 'bad') return reply({ error_type: 'OAuthException', code: 400, error_message: 'Invalid authorization code' });+ if (code === 'weird') return reply({ unexpected: 'x'.repeat(200) });+ if (code === 'offline') return new Error('getaddrinfo ENOTFOUND api.instagram.com');+ return reply({ access_token: shortTokens[code], user_id: 1 });+ }+ const token = url.searchParams.get('access_token');+ if (url.pathname === '/access_token') {+ if (token === 'SHORT_GOOD') return reply({ access_token: 'LONG', token_type: 'bearer', expires_in: 5183944 });+ return reply({ error: { message: 'Unsupported request' } });+ }+ return reply(profiles[token] ?? { error: { message: 'Invalid OAuth access token' } });+}++let fetchMock = null;+let logLines = [];++before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));+after(() => mock.timers.reset());+beforeEach(() => {+ mock.method(Math, 'random', () => 0.987654321);+ logLines = [];+ mock.method(console, 'error', (...args) => logLines.push(['error', ...args]));+ fetchMock = installFetch(instagramServer);+});+afterEach(() => {+ fetchMock.restore();+ mock.restoreAll();+});++function buildApp(supabase) {+ return mountWithContext(app => {+ app.get('/url', urlHandler);+ app.get('/callback', callbackHandler);+ }, { supabase, userId: 'user-1' });+}++describe('instagram oauth golden output', () => {+ test('builds the authorization url from trimmed config', async () => {+ const app = buildApp(fakeSupabase());+ const responses = [+ await callRoute(app, 'GET', '/url', { env: ENV }),+ await callRoute(app, 'GET', '/url', { env: { INSTAGRAM_APP_ID: 'ID', INSTAGRAM_APP_SECRET: 'SECRET' } }),+ await callRoute(app, 'GET', '/url', { env: { INSTAGRAM_APP_ID: 'ID' } }),+ await callRoute(app, 'GET', '/url', { env: { INSTAGRAM_APP_ID: 'ID', INSTAGRAM_APP_SECRET: `${BOM} ` } }),+ ];+ assertGolden({ responses, logs: logLines }, 'instagramAuth.url');+ });++ test('handles every callback outcome', async () => {+ const supabase = fakeSupabase([accountRow({ id: 'ig1', platform: 'instagram', igUserId: '1789', username: 'ribbon' })]);+ const app = buildApp(supabase);+ const validState = encodeURIComponent(await createOAuthState('user-1', 'APPSECRET'));+ const staleState = await (async () => {+ mock.timers.setTime(FIXED_NOW - 11 * 60 * 1000);+ const state = await createOAuthState('user-1', 'APPSECRET');+ mock.timers.setTime(FIXED_NOW);+ return encodeURIComponent(state);+ })();+ const paths = [+ '/callback?error=access_denied&error_reason=user_denied&code=x&state=y',+ '/callback?error=access_denied',+ '/callback?state=abc',+ `/callback?code=good&state=${staleState}`,+ '/callback?code=good&state=no-separator',+ `/callback?code=good&state=${validState}x`,+ `/callback?code=good%23_&state=${validState}`,+ `/callback?code=fallback&state=${validState}`,+ `/callback?code=dup&state=${validState}`,+ `/callback?code=noid&state=${validState}`,+ `/callback?code=bad&state=${validState}`,+ `/callback?code=weird&state=${validState}`,+ `/callback?code=offline&state=${validState}`,+ ];+ const responses = [];+ for (const path of paths) responses.push(await callRoute(app, 'GET', path, { env: ENV }));+ responses.push(await callRoute(app, 'GET', `/callback?code=good&state=${validState}`, { env: {} }));+ assertGolden({ responses, requests: fetchMock.requests, calls: supabase.calls, logs: logLines }, 'instagramAuth.callback');+ });+});diff --git a/backend/services/accountConnect.js b/backend/services/accountConnect.jsnew file mode 100644index 0000000..88a883d--- /dev/null+++ b/backend/services/accountConnect.js@@ -0,0 +1,84 @@+import { getAccounts, getAccountById, createAccount, updateAccount } from '../lib/db.js';+import { resolveChannelId, fetchChannelData } from './youtubeChannels.js';+import { fetchRedditProfile } from './reddit.js';+import { fetchInstagramProfile } from './instagramApi.js';+import { exchangeForLongLivedToken, refreshLongLivedToken } from './instagramTokens.js';+import { buildYouTubeAccount, buildRedditAccount, buildInstagramAccount } from './accountFactory.js';++const DEFAULT_TOKEN_LIFETIME_S = 5184000;++// duplicates throw like any other failure because the route answers both with the same 400+export async function addYouTubeAccount(supabase, userId, input, apiKey) {+ const channelId = await resolveChannelId(input, apiKey);+ const [channelData, accounts] = await Promise.all([+ fetchChannelData(channelId, apiKey),+ getAccounts(supabase, userId),+ ]);++ if (accounts.find(account => account.channelId === channelId)) {+ throw new Error('This channel is already added');+ }++ const newAccount = buildYouTubeAccount(channelData);+ await createAccount(supabase, newAccount, userId);+ return newAccount;+}++export async function addRedditAccount(supabase, userId, username, cookie) {+ const cleanUsername = username.replace(/^u\//i, '').trim();+ const profile = await fetchRedditProfile(cleanUsername, cookie);++ const accounts = await getAccounts(supabase, userId);+ if (accounts.find(account => account.platform === 'reddit' && account.username === profile.username)) {+ throw new Error('This Reddit account is already added');+ }++ const newAccount = buildRedditAccount(profile, cookie);+ await createAccount(supabase, newAccount, userId);+ return newAccount;+}++// a pasted token may already be long-lived, so a failed exchange keeps it as is+async function exchangePastedToken(accessToken, appSecret) {+ if (!appSecret) return { token: accessToken, expiresIn: 0 };+ try {+ const longToken = await exchangeForLongLivedToken(accessToken, appSecret);+ return { token: longToken.accessToken, expiresIn: longToken.expiresIn };+ } catch (err) {+ console.log('Token exchange skipped (token may already be long-lived):', err.message);+ return { token: accessToken, expiresIn: 0 };+ }+}++export async function addInstagramAccount(supabase, userId, accessToken, appSecret) {+ const { token, expiresIn } = await exchangePastedToken(accessToken, appSecret);++ const profile = await fetchInstagramProfile(null, token);+ if (!profile.igUserId) {+ throw new Error('Could not get Instagram User ID. Make sure the token has instagram_business_basic permission and is from a Business/Creator account.');+ }++ const accounts = await getAccounts(supabase, userId);+ if (accounts.find(account => account.platform === 'instagram' && account.igUserId === profile.igUserId)) {+ throw new Error('This Instagram account is already added');+ }++ const newAccount = buildInstagramAccount(profile, token, expiresIn);+ await createAccount(supabase, newAccount, userId);+ return newAccount;+}++export async function refreshInstagramToken(supabase, userId, accountId) {+ const account = await getAccountById(supabase, accountId, userId);+ if (!account || account.platform !== 'instagram') {+ return { failure: { status: 404, message: 'Instagram account not found' } };+ }+ if (!account.accessToken) {+ return { failure: { status: 400, message: 'No access token stored' } };+ }++ const refreshed = await refreshLongLivedToken(account.accessToken);+ const tokenExpiresAt = new Date(Date.now() + (refreshed.expiresIn || DEFAULT_TOKEN_LIFETIME_S) * 1000).toISOString();+ await updateAccount(supabase, account.id, { accessToken: refreshed.accessToken, tokenExpiresAt }, userId);+ return { expiresAt: tokenExpiresAt };+}diff --git a/backend/services/accountFactory.js b/backend/services/accountFactory.jsnew file mode 100644index 0000000..bdc4cc6--- /dev/null+++ b/backend/services/accountFactory.js@@ -0,0 +1,70 @@+export function newAccountId() {+ return Date.now().toString() + Math.random().toString(36).substring(2, 6);+}++// a token without a known lifetime is stored with no expiry+export function tokenExpiryIso(expiresIn) {+ return expiresIn > 0+ ? new Date(Date.now() + expiresIn * 1000).toISOString()+ : null;+}++export function buildYouTubeAccount(channelData) {+ return {+ id: newAccountId(),+ channelId: channelData.channelId,+ title: channelData.title,+ description: channelData.description,+ customUrl: channelData.customUrl,+ publishedAt: channelData.publishedAt,+ country: channelData.country,+ thumbnails: channelData.thumbnails,+ subscriberCount: channelData.subscriberCount,+ viewCount: channelData.viewCount,+ videoCount: channelData.videoCount,+ hiddenSubscriberCount: channelData.hiddenSubscriberCount,+ uploadsPlaylistId: channelData.uploadsPlaylistId,+ keywords: channelData.keywords,+ topicCategories: channelData.topicCategories,+ madeForKids: channelData.madeForKids,+ addedAt: new Date().toISOString(),+ lastUpdated: new Date().toISOString(),+ };+}++export function buildRedditAccount(profile, cookie) {+ return {+ id: newAccountId(),+ platform: 'reddit',+ username: profile.username,+ title: `u/${profile.username}`,+ totalKarma: profile.totalKarma,+ postKarma: profile.postKarma,+ commentKarma: profile.commentKarma,+ iconUrl: profile.iconUrl,+ createdAt: profile.createdAt,+ cookie,+ addedAt: new Date().toISOString(),+ lastUpdated: new Date().toISOString(),+ };+}++export function buildInstagramAccount(profile, accessToken, expiresIn) {+ return {+ id: newAccountId(),+ platform: 'instagram',+ igUserId: profile.igUserId,+ username: profile.username,+ title: profile.name || profile.username,+ biography: profile.biography,+ website: profile.website,+ profilePictureUrl: profile.profilePictureUrl,+ followersCount: profile.followersCount,+ followsCount: profile.followsCount,+ mediaCount: profile.mediaCount,+ accessToken,+ tokenExpiresAt: tokenExpiryIso(expiresIn),+ addedAt: new Date().toISOString(),+ lastUpdated: new Date().toISOString(),+ };+}diff --git a/backend/services/accountFactory.test.js b/backend/services/accountFactory.test.jsnew file mode 100644index 0000000..acffe79--- /dev/null+++ b/backend/services/accountFactory.test.js@@ -0,0 +1,67 @@+import { test, describe, before, after, beforeEach, afterEach, mock } from 'node:test';+import assert from 'node:assert/strict';+import {+ newAccountId, tokenExpiryIso, buildYouTubeAccount, buildRedditAccount, buildInstagramAccount,+} from './accountFactory.js';++const FIXED_NOW = Date.parse('2026-09-01T12:00:00Z');+const NOW_ISO = '2026-09-01T12:00:00.000Z';+const ACCOUNT_ID = '17882640000004fzz';++describe('accountFactory', () => {+ before(() => mock.timers.enable({ apis: ['Date'], now: FIXED_NOW }));+ after(() => mock.timers.reset());+ beforeEach(() => mock.method(Math, 'random', () => 0.123456789));+ afterEach(() => mock.restoreAll());++ test('newAccountId joins the time and four random base 36 characters', () => {+ assert.equal(newAccountId(), ACCOUNT_ID);+ });++ test('tokenExpiryIso adds seconds to now, or returns null without a lifetime', () => {+ assert.equal(tokenExpiryIso(3600), '2026-09-01T13:00:00.000Z');+ assert.equal(tokenExpiryIso(0), null);+ assert.equal(tokenExpiryIso(undefined), null);+ });++ test('buildYouTubeAccount copies the channel fields in a fixed order', () => {+ const channelData = {+ channelId: 'UC1', title: 'T', description: 'D', customUrl: '@c', publishedAt: 'P', country: 'GB',+ thumbnails: { default: 'd' }, subscriberCount: 1, viewCount: 2, videoCount: 3, hiddenSubscriberCount: false,+ uploadsPlaylistId: 'UU1', keywords: 'k', topicCategories: ['t'], madeForKids: false, bannerUrl: 'ignored',+ };+ const account = buildYouTubeAccount(channelData);+ assert.deepStrictEqual(Object.keys(account), [+ 'id', 'channelId', 'title', 'description', 'customUrl', 'publishedAt', 'country', 'thumbnails',+ 'subscriberCount', 'viewCount', 'videoCount', 'hiddenSubscriberCount', 'uploadsPlaylistId', 'keywords',+ 'topicCategories', 'madeForKids', 'addedAt', 'lastUpdated',+ ]);+ assert.equal(account.id, ACCOUNT_ID);+ assert.equal(account.addedAt, NOW_ISO);+ assert.equal(account.lastUpdated, NOW_ISO);+ });++ test('buildRedditAccount keeps the cookie and prefixes the title', () => {+ const profile = { username: 'ribbon', totalKarma: 3, postKarma: 2, commentKarma: 1, iconUrl: 'i', createdAt: 'c', isGold: true };+ assert.deepStrictEqual(buildRedditAccount(profile, 'COOKIE'), {+ id: ACCOUNT_ID, platform: 'reddit', username: 'ribbon', title: 'u/ribbon',+ totalKarma: 3, postKarma: 2, commentKarma: 1, iconUrl: 'i', createdAt: 'c', cookie: 'COOKIE',+ addedAt: NOW_ISO, lastUpdated: NOW_ISO,+ });+ });++ test('buildInstagramAccount falls back to the username as title and sets the expiry', () => {+ const profile = {+ igUserId: '9', username: 'ribbon', name: '', biography: 'b', website: 'w', profilePictureUrl: 'p',+ followersCount: 5, followsCount: 6, mediaCount: 7,+ };+ const account = buildInstagramAccount(profile, 'TOKEN', 60);+ assert.deepStrictEqual(account, {+ id: ACCOUNT_ID, platform: 'instagram', igUserId: '9', username: 'ribbon', title: 'ribbon',+ biography: 'b', website: 'w', profilePictureUrl: 'p', followersCount: 5, followsCount: 6, mediaCount: 7,+ accessToken: 'TOKEN', tokenExpiresAt: '2026-09-01T12:01:00.000Z', addedAt: NOW_ISO, lastUpdated: NOW_ISO,+ });+ assert.deepStrictEqual(Object.keys(account), Object.keys(buildInstagramAccount(profile, 'TOKEN', 0)));+ assert.equal(buildInstagramAccount({ ...profile, name: 'Ribbon' }, 'TOKEN', 0).tokenExpiresAt, null);+ });+});diff --git a/backend/services/accountRefresh.js b/backend/services/accountRefresh.jsnew file mode 100644index 0000000..10fafa8--- /dev/null+++ b/backend/services/accountRefresh.js@@ -0,0 +1,102 @@+import { getAccounts, getAccountById, updateAccount } from '../lib/db.js';+import { fetchChannelData } from './youtubeChannels.js';+import { fetchRedditProfile } from './reddit.js';+import { fetchInstagramProfile } from './instagramApi.js';++const NO_COOKIE_MESSAGE = 'No session cookie stored - re-add this account with a session cookie from reddit.com DevTools';++// the single refresh and refresh-all have always worded a missing YouTube key differently+const SINGLE_REFRESH_MESSAGES = { accessToken: 'No access token', cookie: NO_COOKIE_MESSAGE, apiKey: 'No API key' };+const REFRESH_ALL_MESSAGES = { accessToken: 'No access token', cookie: NO_COOKIE_MESSAGE, apiKey: 'No YouTube API key' };++function findMissingCredential(account, apiKey) {+ if (account.platform === 'instagram') return account.accessToken ? null : 'accessToken';+ if (account.platform === 'reddit') return account.cookie ? null : 'cookie';+ return apiKey ? null : 'apiKey';+}++// full adds the fields only a single account refresh updates+function instagramUpdates(profile, full) {+ 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) {+ return {+ totalKarma: profile.totalKarma,+ postKarma: profile.postKarma,+ commentKarma: profile.commentKarma,+ iconUrl: profile.iconUrl,+ };+}++function youtubeUpdates(channelData, full) {+ 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 async function fetchAccountUpdates(account, apiKey, full) {+ if (account.platform === 'instagram') {+ const profile = await fetchInstagramProfile(account.igUserId, account.accessToken);+ return instagramUpdates(profile, full);+ }+ if (account.platform === 'reddit') {+ const profile = await fetchRedditProfile(account.username, account.cookie);+ return redditUpdates(profile);+ }+ const channelData = await fetchChannelData(account.channelId, apiKey);+ return youtubeUpdates(channelData, full);+}++export async function refreshAccount(supabase, userId, accountId, apiKey) {+ const account = await getAccountById(supabase, accountId, userId);+ if (!account) return { failure: { status: 404, message: 'Not found' } };++ const lastUpdated = new Date().toISOString();+ const missing = findMissingCredential(account, apiKey);+ if (missing) return { failure: { status: 400, message: SINGLE_REFRESH_MESSAGES[missing] } };++ const updates = { lastUpdated, ...await fetchAccountUpdates(account, apiKey, true) };+ await updateAccount(supabase, account.id, updates, userId);+ return { account: { ...account, ...updates } };+}++async function refreshListedAccount(supabase, userId, account, apiKey) {+ const lastUpdated = new Date().toISOString();+ const missing = findMissingCredential(account, apiKey);+ if (missing) throw new Error(REFRESH_ALL_MESSAGES[missing]);++ const updates = { lastUpdated, ...await fetchAccountUpdates(account, apiKey, false) };+ await updateAccount(supabase, account.id, updates, userId);+ return account.id;+}++// one failing account must not stop the others, so results line up with the accounts by index+export async function refreshAllAccounts(supabase, userId, apiKey) {+ const accounts = await getAccounts(supabase, userId);+ const settled = await Promise.allSettled(accounts.map(account => refreshListedAccount(supabase, userId, account, apiKey)));++ const results = settled.map((outcome, i) => (outcome.status === 'fulfilled'+ ? { id: accounts[i].id, success: true }+ : { id: accounts[i].id, success: false, error: outcome.reason?.message }));++ const updatedAccounts = await getAccounts(supabase, userId);+ return { accounts: updatedAccounts, results };+}diff --git a/backend/services/fixtures/accountsRoutes.addInstagram.golden.json b/backend/services/fixtures/accountsRoutes.addInstagram.golden.jsonnew file mode 100644index 0000000..10a9340--- /dev/null+++ b/backend/services/fixtures/accountsRoutes.addInstagram.golden.json@@ -0,0 +1,170 @@+{+ "responses": [+ {+ "status": 400,+ "body": "{\"success\":false,\"message\":\"Access token is required\"}"+ },+ {+ "status": 200,+ "body": "{\"success\":true,\"account\":{\"id\":\"17882640000004fzz\",\"platform\":\"instagram\",\"igUserId\":\"3000\",\"username\":\"fresh\",\"title\":\"fresh\",\"biography\":\"\",\"website\":\"\",\"profilePictureUrl\":\"\",\"followersCount\":5,\"followsCount\":0,\"mediaCount\":1,\"tokenExpiresAt\":\"2026-09-01T13:23:20.000Z\",\"addedAt\":\"2026-09-01T12:00:00.000Z\",\"lastUpdated\":\"2026-09-01T12:00:00.000Z\",\"hasCookie\":false}}"+ },+ {+ "status": 200,+ "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": 400,+ "body": "{\"success\":false,\"message\":\"This Instagram account is already added\"}"+ },+ {+ "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.\"}"+ },+ {+ "status": 400,+ "body": "{\"success\":false,\"message\":\"Invalid OAuth access token\"}"+ }+ ],+ "requests": [+ {+ "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret=IGSECRET&access_token=SHORT",+ "method": "GET"+ },+ {+ "url": "https://graph.instagram.com/v25.0/me?access_token=LONGTOKEN&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",+ "method": "GET"+ },+ {+ "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret=IGSECRET&access_token=SHORTONLY",+ "method": "GET"+ },+ {+ "url": "https://graph.instagram.com/v25.0/me?access_token=SHORTONLY&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",+ "method": "GET"+ },+ {+ "url": "https://graph.instagram.com/v25.0/me?access_token=SHORTONLY&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",+ "method": "GET"+ },+ {+ "url": "https://graph.instagram.com/v25.0/me?access_token=IGTOKEN&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",+ "method": "GET"+ },+ {+ "url": "https://graph.instagram.com/v25.0/me?access_token=NOID&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",+ "method": "GET"+ },+ {+ "url": "https://graph.instagram.com/v25.0/me?access_token=BROKEN&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",+ "method": "GET"+ }+ ],+ "calls": [+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "insert",+ "table": "accounts",+ "values": {+ "id": "17882640000004fzz",+ "user_id": "user-1",+ "platform": "instagram",+ "data": {+ "igUserId": "3000",+ "username": "fresh",+ "title": "fresh",+ "biography": "",+ "website": "",+ "profilePictureUrl": "",+ "followersCount": 5,+ "followsCount": 0,+ "mediaCount": 1,+ "accessToken": "LONGTOKEN",+ "tokenExpiresAt": "2026-09-01T13:23:20.000Z",+ "addedAt": "2026-09-01T12:00:00.000Z",+ "lastUpdated": "2026-09-01T12:00:00.000Z"+ }+ },+ "filters": []+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "insert",+ "table": "accounts",+ "values": {+ "id": "17882640000004fzz",+ "user_id": "user-1",+ "platform": "instagram",+ "data": {+ "igUserId": "3001",+ "username": "shorty",+ "title": "Shorty",+ "biography": "",+ "website": "",+ "profilePictureUrl": "",+ "followersCount": 0,+ "followsCount": 0,+ "mediaCount": 0,+ "accessToken": "SHORTONLY",+ "tokenExpiresAt": null,+ "addedAt": "2026-09-01T12:00:00.000Z",+ "lastUpdated": "2026-09-01T12:00:00.000Z"+ }+ },+ "filters": []+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ }+ ],+ "redis": [],+ "logs": [+ [+ "log",+ "Token exchange skipped (token may already be long-lived):",+ "Invalid platform app"+ ]+ ]+}diff --git a/backend/services/fixtures/accountsRoutes.addReddit.golden.json b/backend/services/fixtures/accountsRoutes.addReddit.golden.jsonnew file mode 100644index 0000000..49a5c6d--- /dev/null+++ b/backend/services/fixtures/accountsRoutes.addReddit.golden.json@@ -0,0 +1,101 @@+{+ "responses": [+ {+ "status": 400,+ "body": "{\"success\":false,\"message\":\"Username is required\"}"+ },+ {+ "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\"}"+ },+ {+ "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": 400,+ "body": "{\"success\":false,\"message\":\"Reddit user not found - check the username\"}"+ }+ ],+ "requests": [+ {+ "url": "https://www.reddit.com/user/NewUser/about.json",+ "method": "GET",+ "headers": {+ "User-Agent": "script:twiligent:v1.0 (by /u/spacesdrive)",+ "Accept": "application/json",+ "Cookie": "reddit_session=NEWCOOKIE"+ }+ },+ {+ "url": "https://www.reddit.com/user/ribbon_r/about.json",+ "method": "GET",+ "headers": {+ "User-Agent": "script:twiligent:v1.0 (by /u/spacesdrive)",+ "Accept": "application/json",+ "Cookie": "reddit_session=C2"+ }+ },+ {+ "url": "https://www.reddit.com/user/missing/about.json",+ "method": "GET",+ "headers": {+ "User-Agent": "script:twiligent:v1.0 (by /u/spacesdrive)",+ "Accept": "application/json",+ "Cookie": "reddit_session=C3"+ }+ }+ ],+ "calls": [+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "insert",+ "table": "accounts",+ "values": {+ "id": "17882640000004fzz",+ "user_id": "user-1",+ "platform": "reddit",+ "data": {+ "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",+ "cookie": "NEWCOOKIE",+ "addedAt": "2026-09-01T12:00:00.000Z",+ "lastUpdated": "2026-09-01T12:00:00.000Z"+ }+ },+ "filters": []+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ }+ ],+ "redis": [],+ "logs": []+}diff --git a/backend/services/fixtures/accountsRoutes.addYouTube.golden.json b/backend/services/fixtures/accountsRoutes.addYouTube.golden.jsonnew file mode 100644index 0000000..2263293--- /dev/null+++ b/backend/services/fixtures/accountsRoutes.addYouTube.golden.json@@ -0,0 +1,122 @@+{+ "responses": [+ {+ "status": 200,+ "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": 400,+ "body": "{\"success\":false,\"message\":\"This channel is already added\"}"+ },+ {+ "status": 400,+ "body": "{\"success\":false,\"message\":\"Invalid input\"}"+ },+ {+ "status": 400,+ "body": "{\"success\":false,\"message\":\"YouTube API key not configured on server\"}"+ }+ ],+ "requests": [+ {+ "url": "https://www.googleapis.com/youtube/v3/channels?part=id&forHandle=creator&key=YTKEY",+ "method": "GET"+ },+ {+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCnnnnnnnnnnnnnnnnnnnnnn&key=YTKEY",+ "method": "GET"+ },+ {+ "url": "https://www.googleapis.com/youtube/v3/channels?part=id&forHandle=%40existing&key=YTKEY",+ "method": "GET"+ },+ {+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCnnnnnnnnnnnnnnnnnnnnnn&key=YTKEY",+ "method": "GET"+ },+ {+ "url": "https://www.googleapis.com/youtube/v3/channels?part=id&forHandle=existing&key=YTKEY",+ "method": "GET"+ },+ {+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCaaaaaaaaaaaaaaaaaaaaaa&key=YTKEY",+ "method": "GET"+ }+ ],+ "calls": [+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "insert",+ "table": "accounts",+ "values": {+ "id": "17882640000004fzz",+ "user_id": "user-1",+ "platform": "youtube",+ "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",+ "topicCategories": [+ "t"+ ],+ "madeForKids": false,+ "addedAt": "2026-09-01T12:00:00.000Z",+ "lastUpdated": "2026-09-01T12:00:00.000Z"+ }+ },+ "filters": []+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ }+ ],+ "redis": [],+ "logs": []+}diff --git a/backend/services/fixtures/accountsRoutes.dbFailure.golden.json b/backend/services/fixtures/accountsRoutes.dbFailure.golden.jsonnew file mode 100644index 0000000..c165b30--- /dev/null+++ b/backend/services/fixtures/accountsRoutes.dbFailure.golden.json@@ -0,0 +1,62 @@+{+ "responses": [+ {+ "status": 500,+ "body": "{\"success\":false,\"message\":\"database unavailable\"}"+ },+ {+ "status": 400,+ "body": "{\"success\":false,\"message\":\"database unavailable\"}"+ },+ {+ "status": 400,+ "body": "{\"success\":false,\"message\":\"database unavailable\"}"+ },+ {+ "status": 400,+ "body": "{\"success\":false,\"message\":\"database unavailable\"}"+ },+ {+ "status": 500,+ "body": "{\"success\":false,\"message\":\"database unavailable\"}"+ },+ {+ "status": 400,+ "body": "{\"success\":false,\"message\":\"database unavailable\"}"+ },+ {+ "status": 400,+ "body": "{\"success\":false,\"message\":\"database unavailable\"}"+ },+ {+ "status": 500,+ "body": "{\"success\":false,\"message\":\"database unavailable\"}"+ }+ ],+ "requests": [+ {+ "url": "https://www.googleapis.com/youtube/v3/channels?part=id&forHandle=%40creator&key=YTKEY",+ "method": "GET"+ },+ {+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCnnnnnnnnnnnnnnnnnnnnnn&key=YTKEY",+ "method": "GET"+ },+ {+ "url": "https://www.reddit.com/user/NewUser/about.json",+ "method": "GET",+ "headers": {+ "User-Agent": "script:twiligent:v1.0 (by /u/spacesdrive)",+ "Accept": "application/json",+ "Cookie": "reddit_session=C"+ }+ },+ {+ "url": "https://graph.instagram.com/v25.0/me?access_token=IGTOKEN&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",+ "method": "GET"+ }+ ],+ "calls": [],+ "redis": [],+ "logs": []+}diff --git a/backend/services/fixtures/accountsRoutes.delete.golden.json b/backend/services/fixtures/accountsRoutes.delete.golden.jsonnew file mode 100644index 0000000..a61045e--- /dev/null+++ b/backend/services/fixtures/accountsRoutes.delete.golden.json@@ -0,0 +1,99 @@+{+ "responses": [+ {+ "status": 404,+ "body": "{\"success\":false,\"message\":\"Not found\"}"+ },+ {+ "status": 404,+ "body": "{\"success\":false,\"message\":\"Not found\"}"+ },+ {+ "status": 200,+ "body": "{\"success\":true}"+ },+ {+ "status": 200,+ "body": "[{\"id\":\"yt1\",\"platform\":\"youtube\",\"channelId\":\"UCaaaaaaaaaaaaaaaaaaaaaa\",\"title\":\"Old title\",\"subscriberCount\":1,\"hasCookie\":false},{\"id\":\"ig1\",\"platform\":\"instagram\",\"igUserId\":\"1789\",\"username\":\"ribbon\",\"tokenExpiresAt\":\"2026-09-05T00:00:00.000Z\",\"followersCount\":1,\"hasCookie\":false},{\"id\":\"ig2\",\"platform\":\"instagram\",\"igUserId\":\"2000\",\"username\":\"notoken\",\"hasCookie\":false},{\"id\":\"rd1\",\"platform\":\"reddit\",\"username\":\"ribbon_r\",\"totalKarma\":1,\"hasCookie\":true},{\"id\":\"yt2\",\"platform\":\"youtube\",\"channelId\":\"UCmissingmissingmissing0\",\"hasCookie\":false}]"+ }+ ],+ "requests": [],+ "calls": [+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "nope"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "other"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "rd2"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "delete",+ "table": "accounts",+ "filters": [+ [+ "id",+ "rd2"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ }+ ],+ "redis": [+ "videos:user-1:rd2",+ "ig:user-1:rd2",+ "reddit:user-1:rd2"+ ],+ "logs": []+}diff --git a/backend/services/fixtures/accountsRoutes.listResolve.golden.json b/backend/services/fixtures/accountsRoutes.listResolve.golden.jsonnew file mode 100644index 0000000..8842de7--- /dev/null+++ b/backend/services/fixtures/accountsRoutes.listResolve.golden.json@@ -0,0 +1,53 @@+{+ "responses": [+ {+ "status": 200,+ "body": "[{\"id\":\"yt1\",\"platform\":\"youtube\",\"channelId\":\"UCaaaaaaaaaaaaaaaaaaaaaa\",\"title\":\"Old title\",\"subscriberCount\":1,\"hasCookie\":false},{\"id\":\"ig1\",\"platform\":\"instagram\",\"igUserId\":\"1789\",\"username\":\"ribbon\",\"tokenExpiresAt\":\"2026-09-05T00:00:00.000Z\",\"followersCount\":1,\"hasCookie\":false},{\"id\":\"ig2\",\"platform\":\"instagram\",\"igUserId\":\"2000\",\"username\":\"notoken\",\"hasCookie\":false},{\"id\":\"rd1\",\"platform\":\"reddit\",\"username\":\"ribbon_r\",\"totalKarma\":1,\"hasCookie\":true},{\"id\":\"rd2\",\"platform\":\"reddit\",\"username\":\"nocookie\",\"hasCookie\":false},{\"id\":\"yt2\",\"platform\":\"youtube\",\"channelId\":\"UCmissingmissingmissing0\",\"hasCookie\":false}]"+ },+ {+ "status": 200,+ "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": 400,+ "body": "{\"success\":false,\"message\":\"YouTube API key not configured on server\"}"+ },+ {+ "status": 400,+ "body": "{\"success\":false,\"message\":\"Expected property name or '}' in JSON at position 1 (line 1 column 2)\"}"+ }+ ],+ "requests": [+ {+ "url": "https://www.googleapis.com/youtube/v3/channels?part=id&forHandle=creator&key=YTKEY",+ "method": "GET"+ },+ {+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCnnnnnnnnnnnnnnnnnnnnnn&key=YTKEY",+ "method": "GET"+ },+ {+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCmissingmissingmissing0&key=YTKEY",+ "method": "GET"+ }+ ],+ "calls": [+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ }+ ],+ "redis": [],+ "logs": []+}diff --git a/backend/services/fixtures/accountsRoutes.refreshAll.golden.json b/backend/services/fixtures/accountsRoutes.refreshAll.golden.jsonnew file mode 100644index 0000000..bcb0d31--- /dev/null+++ b/backend/services/fixtures/accountsRoutes.refreshAll.golden.json@@ -0,0 +1,488 @@+{+ "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\"}"+ },+ {+ "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\"}"+ },+ {+ "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\"}"+ }+ ],+ "requests": [+ {+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCaaaaaaaaaaaaaaaaaaaaaa&key=%EF%BB%BF+YTKEY+%0A",+ "method": "GET"+ },+ {+ "url": "https://graph.instagram.com/v25.0/1789?access_token=IGTOKEN&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",+ "method": "GET"+ },+ {+ "url": "https://www.reddit.com/user/ribbon_r/about.json",+ "method": "GET",+ "headers": {+ "User-Agent": "script:twiligent:v1.0 (by /u/spacesdrive)",+ "Accept": "application/json",+ "Cookie": "reddit_session=COOKIE"+ }+ },+ {+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCmissingmissingmissing0&key=%EF%BB%BF+YTKEY+%0A",+ "method": "GET"+ },+ {+ "url": "https://graph.instagram.com/v25.0/1789?access_token=IGTOKEN&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",+ "method": "GET"+ },+ {+ "url": "https://www.reddit.com/user/ribbon_r/about.json",+ "method": "GET",+ "headers": {+ "User-Agent": "script:twiligent:v1.0 (by /u/spacesdrive)",+ "Accept": "application/json",+ "Cookie": "reddit_session=COOKIE"+ }+ },+ {+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCaaaaaaaaaaaaaaaaaaaaaa&key=PLAINKEY",+ "method": "GET"+ },+ {+ "url": "https://graph.instagram.com/v25.0/1789?access_token=IGTOKEN&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",+ "method": "GET"+ },+ {+ "url": "https://www.reddit.com/user/ribbon_r/about.json",+ "method": "GET",+ "headers": {+ "User-Agent": "script:twiligent:v1.0 (by /u/spacesdrive)",+ "Accept": "application/json",+ "Cookie": "reddit_session=COOKIE"+ }+ },+ {+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCmissingmissingmissing0&key=PLAINKEY",+ "method": "GET"+ }+ ],+ "calls": [+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "yt1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "ig1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "rd1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "update",+ "table": "accounts",+ "values": {+ "platform": "youtube",+ "data": {+ "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"+ }+ }+ },+ "filters": [+ [+ "id",+ "yt1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "update",+ "table": "accounts",+ "values": {+ "platform": "instagram",+ "data": {+ "igUserId": "1789",+ "username": "ribbon",+ "accessToken": "IGTOKEN",+ "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"+ }+ },+ "filters": [+ [+ "id",+ "ig1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "update",+ "table": "accounts",+ "values": {+ "platform": "reddit",+ "data": {+ "username": "ribbon_r",+ "cookie": "COOKIE",+ "totalKarma": 70,+ "lastUpdated": "2026-09-01T12:00:00.000Z",+ "postKarma": 50,+ "commentKarma": 20,+ "iconUrl": "https://i?a=1&b=2"+ }+ },+ "filters": [+ [+ "id",+ "rd1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "ig1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "rd1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "update",+ "table": "accounts",+ "values": {+ "platform": "instagram",+ "data": {+ "igUserId": "1789",+ "username": "ribbon",+ "accessToken": "IGTOKEN",+ "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"+ }+ },+ "filters": [+ [+ "id",+ "ig1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "update",+ "table": "accounts",+ "values": {+ "platform": "reddit",+ "data": {+ "username": "ribbon_r",+ "cookie": "COOKIE",+ "totalKarma": 70,+ "lastUpdated": "2026-09-01T12:00:00.000Z",+ "postKarma": 50,+ "commentKarma": 20,+ "iconUrl": "https://i?a=1&b=2"+ }+ },+ "filters": [+ [+ "id",+ "rd1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "yt1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "ig1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "rd1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "update",+ "table": "accounts",+ "values": {+ "platform": "youtube",+ "data": {+ "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"+ }+ }+ },+ "filters": [+ [+ "id",+ "yt1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "update",+ "table": "accounts",+ "values": {+ "platform": "instagram",+ "data": {+ "igUserId": "1789",+ "username": "ribbon",+ "accessToken": "IGTOKEN",+ "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"+ }+ },+ "filters": [+ [+ "id",+ "ig1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "update",+ "table": "accounts",+ "values": {+ "platform": "reddit",+ "data": {+ "username": "ribbon_r",+ "cookie": "COOKIE",+ "totalKarma": 70,+ "lastUpdated": "2026-09-01T12:00:00.000Z",+ "postKarma": 50,+ "commentKarma": 20,+ "iconUrl": "https://i?a=1&b=2"+ }+ },+ "filters": [+ [+ "id",+ "rd1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ }+ ],+ "redis": [],+ "logs": []+}diff --git a/backend/services/fixtures/accountsRoutes.refreshOne.golden.json b/backend/services/fixtures/accountsRoutes.refreshOne.golden.jsonnew file mode 100644index 0000000..baa8350--- /dev/null+++ b/backend/services/fixtures/accountsRoutes.refreshOne.golden.json@@ -0,0 +1,490 @@+{+ "responses": [+ {+ "status": 404,+ "body": "{\"success\":false,\"message\":\"Not found\"}"+ },+ {+ "status": 200,+ "body": "{\"success\":true,\"account\":{\"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\",\"biography\":\"Bio\",\"website\":\"https://r.example\",\"hasCookie\":false}}"+ },+ {+ "status": 400,+ "body": "{\"success\":false,\"message\":\"No access token\"}"+ },+ {+ "status": 200,+ "body": "{\"success\":true,\"account\":{\"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}}"+ },+ {+ "status": 400,+ "body": "{\"success\":false,\"message\":\"No session cookie stored - re-add this account with a session cookie from reddit.com DevTools\"}"+ },+ {+ "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": 400,+ "body": "{\"success\":false,\"message\":\"Channel not found\"}"+ },+ {+ "status": 404,+ "body": "{\"success\":false,\"message\":\"Not found\"}"+ },+ {+ "status": 404,+ "body": "{\"success\":false,\"message\":\"Instagram account not found\"}"+ },+ {+ "status": 404,+ "body": "{\"success\":false,\"message\":\"Instagram account not found\"}"+ },+ {+ "status": 400,+ "body": "{\"success\":false,\"message\":\"No access token stored\"}"+ },+ {+ "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\"}"+ }+ ],+ "requests": [+ {+ "url": "https://graph.instagram.com/v25.0/1789?access_token=IGTOKEN&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",+ "method": "GET"+ },+ {+ "url": "https://www.reddit.com/user/ribbon_r/about.json",+ "method": "GET",+ "headers": {+ "User-Agent": "script:twiligent:v1.0 (by /u/spacesdrive)",+ "Accept": "application/json",+ "Cookie": "reddit_session=COOKIE"+ }+ },+ {+ "url": "https://www.googleapis.com/youtube/v3/channels?part=snippet%2Cstatistics%2CcontentDetails%2CbrandingSettings%2Cstatus%2CtopicDetails&id=UCaaaaaaaaaaaaaaaaaaaaaa&key=%EF%BB%BF+YTKEY+%0A",+ "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",+ "method": "GET"+ },+ {+ "url": "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=IGTOKEN",+ "method": "GET"+ },+ {+ "url": "https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=IGTOKEN2",+ "method": "GET"+ }+ ],+ "calls": [+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "nope"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "ig1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "ig1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "update",+ "table": "accounts",+ "values": {+ "platform": "instagram",+ "data": {+ "igUserId": "1789",+ "username": "ribbon",+ "accessToken": "IGTOKEN",+ "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",+ "biography": "Bio",+ "website": "https://r.example"+ }+ },+ "filters": [+ [+ "id",+ "ig1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "ig2"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "rd1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "rd1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "update",+ "table": "accounts",+ "values": {+ "platform": "reddit",+ "data": {+ "username": "ribbon_r",+ "cookie": "COOKIE",+ "totalKarma": 70,+ "lastUpdated": "2026-09-01T12:00:00.000Z",+ "postKarma": 50,+ "commentKarma": 20,+ "iconUrl": "https://i?a=1&b=2"+ }+ },+ "filters": [+ [+ "id",+ "rd1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "rd2"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "yt1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "yt1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "update",+ "table": "accounts",+ "values": {+ "platform": "youtube",+ "data": {+ "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"+ ]+ }+ },+ "filters": [+ [+ "id",+ "yt1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "yt1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "yt2"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "other"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "nope"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "rd1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "ig2"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "ig1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "ig1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "update",+ "table": "accounts",+ "values": {+ "platform": "instagram",+ "data": {+ "igUserId": "1789",+ "username": "ribbon",+ "accessToken": "IGTOKEN2",+ "tokenExpiresAt": "2026-09-02T12:00:00.000Z",+ "followersCount": 2500,+ "lastUpdated": "2026-09-01T12:00:00.000Z",+ "followsCount": 10,+ "mediaCount": 140,+ "title": "Ribbon",+ "profilePictureUrl": "https://p",+ "biography": "Bio",+ "website": "https://r.example"+ }+ },+ "filters": [+ [+ "id",+ "ig1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "id",+ "ig1"+ ],+ [+ "user_id",+ "user-1"+ ]+ ]+ }+ ],+ "redis": [],+ "logs": []+}diff --git a/backend/services/fixtures/instagramAuth.callback.golden.json b/backend/services/fixtures/instagramAuth.callback.golden.jsonnew file mode 100644index 0000000..0124612--- /dev/null+++ b/backend/services/fixtures/instagramAuth.callback.golden.json@@ -0,0 +1,274 @@+{+ "responses": [+ {+ "status": 302,+ "body": "",+ "location": "https://app.example.com//accounts?ig_error=user_denied"+ },+ {+ "status": 302,+ "body": "",+ "location": "https://app.example.com//accounts?ig_error=access_denied"+ },+ {+ "status": 302,+ "body": "",+ "location": "https://app.example.com//accounts?ig_error=cancelled"+ },+ {+ "status": 302,+ "body": "",+ "location": "https://app.example.com//accounts?ig_error=invalid_state"+ },+ {+ "status": 302,+ "body": "",+ "location": "https://app.example.com//accounts?ig_error=invalid_state"+ },+ {+ "status": 302,+ "body": "",+ "location": "https://app.example.com//accounts?ig_error=invalid_state"+ },+ {+ "status": 302,+ "body": "",+ "location": "https://app.example.com//accounts?ig_connected=true"+ },+ {+ "status": 302,+ "body": "",+ "location": "https://app.example.com//accounts?ig_connected=true"+ },+ {+ "status": 302,+ "body": "",+ "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."+ },+ {+ "status": 302,+ "body": "",+ "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"+ },+ {+ "status": 302,+ "body": "",+ "location": "https://app.example.com//accounts?ig_error=getaddrinfo%20ENOTFOUND%20api.instagram.com"+ },+ {+ "status": 500,+ "body": "Internal Server Error"+ }+ ],+ "requests": [+ {+ "url": "https://api.instagram.com/oauth/access_token",+ "method": "POST",+ "headers": {+ "Content-Type": "application/x-www-form-urlencoded"+ },+ "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=good"+ },+ {+ "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_id=APPID&client_secret=APPSECRET&access_token=SHORT_GOOD",+ "method": "GET"+ },+ {+ "url": "https://graph.instagram.com/v25.0/me?access_token=LONG&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",+ "method": "GET"+ },+ {+ "url": "https://api.instagram.com/oauth/access_token",+ "method": "POST",+ "headers": {+ "Content-Type": "application/x-www-form-urlencoded"+ },+ "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=fallback"+ },+ {+ "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_id=APPID&client_secret=APPSECRET&access_token=SHORT_FALLBACK",+ "method": "GET"+ },+ {+ "url": "https://graph.instagram.com/v25.0/me?access_token=SHORT_FALLBACK&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",+ "method": "GET"+ },+ {+ "url": "https://api.instagram.com/oauth/access_token",+ "method": "POST",+ "headers": {+ "Content-Type": "application/x-www-form-urlencoded"+ },+ "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=dup"+ },+ {+ "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_id=APPID&client_secret=APPSECRET&access_token=SHORT_DUP",+ "method": "GET"+ },+ {+ "url": "https://graph.instagram.com/v25.0/me?access_token=SHORT_DUP&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",+ "method": "GET"+ },+ {+ "url": "https://api.instagram.com/oauth/access_token",+ "method": "POST",+ "headers": {+ "Content-Type": "application/x-www-form-urlencoded"+ },+ "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=noid"+ },+ {+ "url": "https://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_id=APPID&client_secret=APPSECRET&access_token=SHORT_NOID",+ "method": "GET"+ },+ {+ "url": "https://graph.instagram.com/v25.0/me?access_token=SHORT_NOID&fields=user_id%2Cusername%2Cname%2Cprofile_picture_url%2Cfollowers_count%2Cfollows_count%2Cmedia_count%2Cbiography%2Cwebsite",+ "method": "GET"+ },+ {+ "url": "https://api.instagram.com/oauth/access_token",+ "method": "POST",+ "headers": {+ "Content-Type": "application/x-www-form-urlencoded"+ },+ "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=bad"+ },+ {+ "url": "https://api.instagram.com/oauth/access_token",+ "method": "POST",+ "headers": {+ "Content-Type": "application/x-www-form-urlencoded"+ },+ "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=weird"+ },+ {+ "url": "https://api.instagram.com/oauth/access_token",+ "method": "POST",+ "headers": {+ "Content-Type": "application/x-www-form-urlencoded"+ },+ "body": "client_id=APPID&client_secret=APPSECRET&grant_type=authorization_code&redirect_uri=https%3A%2F%2Fapi.example.com%2Fapi%2Fauth%2Finstagram%2Fcallback&code=offline"+ }+ ],+ "calls": [+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "insert",+ "table": "accounts",+ "values": {+ "id": "1788264000000zk00",+ "user_id": "user-1",+ "platform": "instagram",+ "data": {+ "igUserId": "5000",+ "username": "longlived",+ "title": "Long Lived",+ "biography": "B",+ "website": "W",+ "profilePictureUrl": "P",+ "followersCount": 10,+ "followsCount": 2,+ "mediaCount": 3,+ "accessToken": "LONG",+ "tokenExpiresAt": "2026-10-31T11:59:04.000Z",+ "addedAt": "2026-09-01T12:00:00.000Z",+ "lastUpdated": "2026-09-01T12:00:00.000Z"+ }+ },+ "filters": []+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ },+ {+ "type": "insert",+ "table": "accounts",+ "values": {+ "id": "1788264000000zk00",+ "user_id": "user-1",+ "platform": "instagram",+ "data": {+ "igUserId": "5001",+ "username": "fallback",+ "title": "fallback",+ "biography": "",+ "website": "",+ "profilePictureUrl": "",+ "followersCount": 0,+ "followsCount": 0,+ "mediaCount": 0,+ "accessToken": "SHORT_FALLBACK",+ "tokenExpiresAt": null,+ "addedAt": "2026-09-01T12:00:00.000Z",+ "lastUpdated": "2026-09-01T12:00:00.000Z"+ }+ },+ "filters": []+ },+ {+ "type": "select",+ "table": "accounts",+ "columns": "id, platform, data",+ "filters": [+ [+ "user_id",+ "user-1"+ ]+ ]+ }+ ],+ "logs": [+ [+ "error",+ "Instagram OAuth callback error:",+ "Could not get Instagram User ID. Account must be a Business or Creator account."+ ],+ [+ "error",+ "Instagram OAuth callback error:",+ "Invalid authorization code"+ ],+ [+ "error",+ "Instagram OAuth callback error:",+ "{\"unexpected\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"}"+ ],+ [+ "error",+ "Instagram OAuth callback error:",+ "getaddrinfo ENOTFOUND api.instagram.com"+ ],+ [+ "error",+ {}+ ]+ ]+}diff --git a/backend/services/fixtures/instagramAuth.url.golden.json b/backend/services/fixtures/instagramAuth.url.golden.jsonnew file mode 100644index 0000000..43af1ad--- /dev/null+++ b/backend/services/fixtures/instagramAuth.url.golden.json@@ -0,0 +1,21 @@+{+ "responses": [+ {+ "status": 200,+ "body": "{\"url\":\"https://www.instagram.com/oauth/authorize?force_reauth=true&client_id=APPID&redirect_uri=https%3A%2F%2Fapi.example.com%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.kPwa14uVn6c44E1UPm5jQWV7kLuUxf75IOfMu8CrWTo\"}"+ },+ {+ "status": 200,+ "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": 500,+ "body": "{\"success\":false,\"message\":\"Instagram App credentials not configured on server\"}"+ }+ ],+ "logs": []+}diff --git a/backend/services/fixtures/routeHarness.js b/backend/services/fixtures/routeHarness.jsnew file mode 100644index 0000000..d80aec6--- /dev/null+++ b/backend/services/fixtures/routeHarness.js@@ -0,0 +1,33 @@+import { Hono } from 'hono';++// mounts a router behind a middleware that fills the context the way server.js does+export function mountWithContext(register, context) {+ const app = new Hono();+ app.use('*', async (c, next) => {+ Object.entries(context).forEach(([key, value]) => c.set(key, value));+ await next();+ });+ register(app);+ return app;+}++export async function callRoute(app, method, path, options = {}) {+ const init = { method };+ if (options.json !== undefined) {+ init.body = typeof options.json === 'string' ? options.json : JSON.stringify(options.json);+ init.headers = { 'Content-Type': 'application/json' };+ }+ const response = await app.request(path, init, options.env ?? {});+ const result = { status: response.status, body: await response.text() };+ const location = response.headers.get('location');+ if (location !== null) result.location = location;+ return result;+}++export function fakeRedis() {+ const deleted = [];+ return {+ deleted,+ async del(key) { deleted.push(key); },+ };+}diff --git a/backend/services/instagramOAuth.js b/backend/services/instagramOAuth.jsnew file mode 100644index 0000000..1bed7f0--- /dev/null+++ b/backend/services/instagramOAuth.js@@ -0,0 +1,97 @@+import { createOAuthState } from '../lib/cache.js';+import { createAccount, getAccounts } from '../lib/db.js';+import { fetchInstagramProfile } from './instagramApi.js';+import { buildInstagramAccount } from './accountFactory.js';++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';++// secrets pasted into the dashboard can carry a byte order mark or stray whitespace+function cleanSecret(value) {+ return value?.replace(/^/, '').trim();+}++function cleanUrl(value, fallback) {+ return (value || fallback).replace(/^/, '').trim();+}++export function readInstagramOAuthConfig(env) {+ 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),+ };+}++// the hmac-signed state carries the userId and a timestamp, so no redis is needed+export async function buildAuthorizationUrl(config, userId) {+ const state = await createOAuthState(userId, config.appSecret);+ const params = new URLSearchParams({+ force_reauth: 'true',+ client_id: config.appId,+ redirect_uri: config.redirectUri,+ response_type: 'code',+ scope: OAUTH_SCOPES,+ state,+ });+ return `${AUTHORIZE_URL}?${params}`;+}++async function exchangeCodeForToken(config, code) {+ const tokenRes = await fetch(TOKEN_URL, {+ method: 'POST',+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },+ body: new URLSearchParams({+ client_id: config.appId,+ client_secret: config.appSecret,+ grant_type: 'authorization_code',+ redirect_uri: config.redirectUri,+ // instagram sometimes appends #_ to the code+ code: code.replace(/#.*$/, ''),+ }),+ });+ const tokenData = await tokenRes.json();+ if (!tokenData.access_token) {+ throw new Error(tokenData.error_message || JSON.stringify(tokenData));+ }+ return tokenData.access_token;+}++// keeps the short-lived token, with no expiry, when instagram declines the 60 day upgrade+async function upgradeToLongLivedToken(config, shortToken) {+ 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 longData = await longRes.json();+ return { token: longData.access_token || shortToken, expiresIn: longData.expires_in || 0 };+}++export async function connectInstagramFromOAuth(supabase, userId, config, code) {+ 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/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.mdindex c5463d0..16ad241 100644--- a/docs/architecture/backend/ROUTES.md+++ b/docs/architecture/backend/ROUTES.md@@ -17,6 +17,9 @@ All routes live under `/api`. Routes under the `api` sub-app require a valid Sup| GET | `/api/keys` | `routes/keys.js` | Returns `{ youtube: bool, instagram: bool, cloudinary: bool }` - whether each API key is configured |### Accounts++Handlers delegate to `services/accountConnect.js` and `services/accountRefresh.js`; the Instagram OAuth handlers delegate to `services/instagramOAuth.js`. See `SERVICES.md`.+| Method | Path | File | Purpose ||---|---|---|---|| GET | `/api/accounts` | `routes/accounts.js` | List all user accounts (tokens stripped via `safeAccount()`) |diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.mdindex 8099ae5..a11c768 100644--- a/docs/architecture/backend/SERVICES.md+++ b/docs/architecture/backend/SERVICES.md@@ -142,6 +142,26 @@ Reddit integration requires no Worker secrets. The session cookie is a per-user---+## Accounts (`accountFactory.js`, `accountConnect.js`, `accountRefresh.js`)++The account routes in `routes/accounts.js` only parse the request, check required fields and shape the response; the work lives here.++| Module | Contents |+|---|---|+| `accountFactory.js` | Pure builders: `newAccountId`, `tokenExpiryIso` (null without a lifetime), `buildYouTubeAccount`, `buildRedditAccount`, `buildInstagramAccount` |+| `accountConnect.js` | `addYouTubeAccount`, `addRedditAccount`, `addInstagramAccount` (tries the long-lived exchange when `INSTAGRAM_APP_SECRET` is set and keeps the pasted token if it fails), `refreshInstagramToken` |+| `accountRefresh.js` | `fetchAccountUpdates` (profile fields per platform; a single refresh updates more fields than refresh-all), `refreshAccount`, `refreshAllAccounts` (`Promise.allSettled`, results aligned with the account list by index) |++Duplicate accounts throw an `Error` whose message the route returns with status 400, the same shape as any other failure. Failures that need another status (404 for a missing account, 400 for a missing credential) come back as `{ failure: { status, message } }`.++---++## Instagram OAuth (`instagramOAuth.js`)++Used by `routes/instagramAuth.js`. `readInstagramOAuthConfig(env)` strips a leading byte order mark and whitespace from the app id, secret and URLs, drops a trailing slash from `BACKEND_URL`, and falls back to `http://localhost:8787` and `http://localhost:5173`. `buildAuthorizationUrl` signs the state with the app secret. `connectInstagramFromOAuth` exchanges the code (stripping a trailing `#_`), upgrades to a long-lived token when Instagram allows it (otherwise keeps the short-lived token with no expiry), fetches the profile and returns `'already_added'` or `'connected'`. The route turns those into the `ig_error` and `ig_connected` redirects.++---+## Shared Instagram publishing parameters`buildMediaParams(post, accessToken)` in `services/instagramPublishing.js` (re-exported by `services/instagram.js`) builds the Graph API container parameters for photos, Reels, Stories and carousel items. The publish route (`routes/publishing.js`) and the cron scheduler (`utils/scheduler.js`) both call it. `scripts/publish-scheduled.js` keeps its own copy on purpose: it runs in GitHub Actions with zero npm dependencies and cannot import Worker code.